_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q22400 | DICOM.DLibrary.as_name | train | def as_name(value)
case true
when value.tag?
element(value).name
when value.dicom_name?
@methods_from_names.has_key?(value) ? value.to_s : nil
when value.dicom_method?
@names_from_methods[value.to_sym]
else
nil
end
end | ruby | {
"resource": ""
} |
q22401 | DICOM.DLibrary.as_tag | train | def as_tag(value)
case true
when value.tag?
element(value) ? value : nil
when value.dicom_name?
get_tag(value)
when value.dicom_method?
get_tag(@names_from_methods[value.to_sym])
else
nil
end
end | ruby | {
"resource": ""
} |
q22402 | DICOM.DLibrary.element | train | def element(tag)
element = @elements[tag]
unless element
if tag.group_length?
element = DictionaryElement.new(tag, 'Group Length', ['UL'], '1', '')
else
if tag.private?
element = DictionaryElement.new(tag, 'Private', ['UN'], '1', '')
else
element = unknown_or_range_element(tag)
end
end
end
element
end | ruby | {
"resource": ""
} |
q22403 | DICOM.DLibrary.extract_transfer_syntaxes_and_sop_classes | train | def extract_transfer_syntaxes_and_sop_classes
transfer_syntaxes = Hash.new
sop_classes = Hash.new
@uids.each_value do |uid|
if uid.transfer_syntax?
transfer_syntaxes[uid.value] = uid.name
elsif uid.sop_class?
sop_classes[uid.value] = uid.name
end
end
return transfer_syntaxes, sop_classes
end | ruby | {
"resource": ""
} |
q22404 | DICOM.DLibrary.get_tag | train | def get_tag(name)
tag = nil
name = name.to_s.downcase
@tag_name_pairs_cache ||= Hash.new
return @tag_name_pairs_cache[name] unless @tag_name_pairs_cache[name].nil?
@elements.each_value do |element|
next unless element.name.downcase == name
tag = element.tag
break
end
@tag_name_pairs_cache[name]=tag
return tag
end | ruby | {
"resource": ""
} |
q22405 | DICOM.DLibrary.unknown_or_range_element | train | def unknown_or_range_element(tag)
element = nil
range_candidates(tag).each do |range_candidate_tag|
if de = @elements[range_candidate_tag]
element = DictionaryElement.new(tag, de.name, de.vrs, de.vm, de.retired)
break
end
end
# If nothing was matched, we are facing an unknown (but not private) tag:
element ||= DictionaryElement.new(tag, 'Unknown', ['UN'], '1', '')
end | ruby | {
"resource": ""
} |
q22406 | AutoNetwork.PoolManager.with_pool_for | train | def with_pool_for(machine, read_only=false)
@pool_storage.transaction(read_only) do
pool = lookup_pool_for(machine)
pool ||= generate_pool_for(machine)
yield pool
end
end | ruby | {
"resource": ""
} |
q22407 | AutoNetwork.Action::Base.machine_auto_networks | train | def machine_auto_networks(machine)
machine.config.vm.networks.select do |(net_type, options)|
net_type == :private_network and options[:auto_network]
end
end | ruby | {
"resource": ""
} |
q22408 | AutoNetwork.Pool.request | train | def request(machine)
if (address = address_for(machine))
return address
elsif (address = next_available_lease)
@pool[address] = id_for(machine)
return address
else
raise PoolExhaustedError,
:name => machine.name,
:network => @network_range
end
end | ruby | {
"resource": ""
} |
q22409 | AutoNetwork.Pool.address_for | train | def address_for(machine)
machine_id = id_for(machine)
addr, _ = @pool.find do |(addr, id)|
if id.is_a?(String)
# Check for old-style UUID values. These should eventually cycle out
# as machines are destroyed.
id == machine.id
else
id == machine_id
end
end
addr
end | ruby | {
"resource": ""
} |
q22410 | AutoNetwork.Settings.default_pool= | train | def default_pool=(pool)
# Ensure the pool is valid.
begin
IPAddr.new pool
rescue ArgumentError
raise InvalidSettingErrror,
:setting_name => 'default_pool',
:value => pool.inspect
end
@default_pool = pool
end | ruby | {
"resource": ""
} |
q22411 | RAutomation.ElementCollections.has_many | train | def has_many(*elements)
elements.each do |element|
class_name_plural = element.to_s.split("_").map {|e| e.capitalize}.join
class_name = class_name_plural.chop
adapter_class = self.to_s.scan(/(.*)::/).flatten.first
clazz = RAutomation.constants.include?(class_name) ? RAutomation : class_eval(adapter_class)
clazz.class_eval %Q{
class #{class_name_plural}
include Enumerable
def initialize(window, locators)
if locators[:hwnd] || locators[:pid]
raise UnsupportedLocatorException,
":hwnd or :pid in " + locators.inspect + " are not supported for #{adapter_class}::#{class_name_plural}"
end
@window = window
@locators = locators
end
def each
i = -1
while true
args = [@window, @locators.merge(:index => i += 1)].compact
object = #{clazz}::#{class_name}.new(*args)
break unless object.exists?
yield object
end
end
def method_missing(name, *args)
ary = self.to_a
ary.respond_to?(name) ? ary.send(name, *args) : super
end
end
}
class_eval %Q{
def #{element}(locators = {})
#{adapter_class}::#{class_name_plural}.new(@window || self, locators)
end
}
end
end | ruby | {
"resource": ""
} |
q22412 | ActiveEvent.EventSourceServer.process_projection | train | def process_projection(data)
mutex.synchronize do
projection_status = status[data[:projection]]
projection_status.set_error data[:error], data[:backtrace]
projection_status.event = data[:event]
end
end | ruby | {
"resource": ""
} |
q22413 | RallyAPI.RallyRestJson.allowed_values | train | def allowed_values(type, field, workspace = nil)
rally_workspace_object(workspace)
type_def = get_typedef_for(type, workspace)
allowed_vals = {}
type_def["Attributes"].each do |attr|
next if attr["ElementName"] != field
attr["AllowedValues"].each do |val_ref|
val = val_ref["StringValue"]
val = "Null" if val.nil? || val.empty?
allowed_vals[val] = true
end
end
allowed_vals
end | ruby | {
"resource": ""
} |
q22414 | RallyAPI.RallyRestJson.check_type | train | def check_type(type_name)
alias_name = @rally_alias_types[type_name.downcase.to_s]
return alias_name unless alias_name.nil?
return type_name
end | ruby | {
"resource": ""
} |
q22415 | RallyAPI.RallyRestJson.check_id | train | def check_id(type, idstring)
if idstring.class == Fixnum
return make_read_url(type, idstring)
end
if (idstring.class == String)
return idstring if idstring.index("http") == 0
return ref_by_formatted_id(type, idstring.split("|")[1]) if idstring.index("FormattedID") == 0
end
make_read_url(type, idstring)
end | ruby | {
"resource": ""
} |
q22416 | RallyAPI.RallyObject.method_missing | train | def method_missing(sym, *args)
ret_val = get_val(sym.to_s)
if ret_val.nil? && @rally_rest.rally_rest_api_compat
ret_val = get_val(camel_case_word(sym))
end
ret_val
end | ruby | {
"resource": ""
} |
q22417 | BunnyMock.Channel.ack | train | def ack(delivery_tag, multiple = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
ack(key, false) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
update_acknowledgement_state(delivery_tag, :acked)
end
nil
end | ruby | {
"resource": ""
} |
q22418 | BunnyMock.Channel.nack | train | def nack(delivery_tag, multiple = false, requeue = false)
if multiple
@acknowledged_state[:pending].keys.each do |key|
nack(key, false, requeue) if key <= delivery_tag
end
elsif @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :nacked)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | ruby | {
"resource": ""
} |
q22419 | BunnyMock.Channel.reject | train | def reject(delivery_tag, requeue = false)
if @acknowledged_state[:pending].key?(delivery_tag)
delivery, header, body = update_acknowledgement_state(delivery_tag, :rejected)
delivery.queue.publish(body, header.to_hash) if requeue
end
nil
end | ruby | {
"resource": ""
} |
q22420 | BunnyMock.Queue.bind | train | def bind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | ruby | {
"resource": ""
} |
q22421 | BunnyMock.Queue.unbind | train | def unbind(exchange, opts = {})
check_queue_deleted!
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to lookup the exchange
@channel.queue_unbind self, opts.fetch(:routing_key, @name), exchange
end
end | ruby | {
"resource": ""
} |
q22422 | BunnyMock.Queue.pop | train | def pop(opts = { manual_ack: false }, &block)
if BunnyMock.use_bunny_queue_pop_api
bunny_pop(opts, &block)
else
warn '[DEPRECATED] This behavior is deprecated - please set `BunnyMock::use_bunny_queue_pop_api` to true to use Bunny Queue#pop behavior'
@messages.shift
end
end | ruby | {
"resource": ""
} |
q22423 | BunnyMock.Exchange.bind | train | def bind(exchange, opts = {})
if exchange.respond_to?(:add_route)
# we can do the binding ourselves
exchange.add_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_bind self, opts.fetch(:routing_key, @name), exchange
end
self
end | ruby | {
"resource": ""
} |
q22424 | BunnyMock.Exchange.unbind | train | def unbind(exchange, opts = {})
if exchange.respond_to?(:remove_route)
# we can do the unbinding ourselves
exchange.remove_route opts.fetch(:routing_key, @name), self
else
# we need the channel to look up the exchange
@channel.xchg_unbind opts.fetch(:routing_key, @name), exchange, self
end
self
end | ruby | {
"resource": ""
} |
q22425 | BunnyMock.Exchange.routes_to? | train | def routes_to?(exchange_or_queue, opts = {})
route = exchange_or_queue.respond_to?(:name) ? exchange_or_queue.name : exchange_or_queue
rk = opts.fetch(:routing_key, route)
@routes.key?(rk) && @routes[rk].any? { |r| r == exchange_or_queue }
end | ruby | {
"resource": ""
} |
q22426 | TTY.Cursor.move | train | def move(x, y)
(x < 0 ? backward(-x) : (x > 0 ? forward(x) : '')) +
(y < 0 ? down(-y) : (y > 0 ? up(y) : ''))
end | ruby | {
"resource": ""
} |
q22427 | TTY.Cursor.clear_lines | train | def clear_lines(n, direction = :up)
n.times.reduce([]) do |acc, i|
dir = direction == :up ? up : down
acc << clear_line + ((i == n - 1) ? '' : dir)
end.join
end | ruby | {
"resource": ""
} |
q22428 | Jkf::Parser.Kif.transform_move | train | def transform_move(line, c)
ret = {}
ret["comments"] = c if !c.empty?
if line["move"].is_a? Hash
ret["move"] = line["move"]
else
ret["special"] = special2csa(line["move"])
end
ret["time"] = line["time"] if line["time"]
ret
end | ruby | {
"resource": ""
} |
q22429 | Jkf::Parser.Kif.transform_teban_fugou_from | train | def transform_teban_fugou_from(teban, fugou, from)
ret = { "color" => teban2color(teban.join), "piece" => fugou["piece"] }
if fugou["to"]
ret["to"] = fugou["to"]
else
ret["same"] = true
end
ret["promote"] = true if fugou["promote"]
ret["from"] = from if from
ret
end | ruby | {
"resource": ""
} |
q22430 | Jkf::Parser.Kif.reverse_color | train | def reverse_color(moves)
moves.each do |move|
if move["move"] && move["move"]["color"]
move["move"]["color"] = (move["move"]["color"] + 1) % 2
end
move["forks"].each { |_fork| reverse_color(_fork) } if move["forks"]
end
end | ruby | {
"resource": ""
} |
q22431 | Jkf::Parser.Ki2.transform_fugou | train | def transform_fugou(pl, pi, sou, dou, pro, da)
ret = { "piece" => pi }
if pl["same"]
ret["same"] = true
else
ret["to"] = pl
end
ret["promote"] = (pro == "成") if pro
if da
ret["relative"] = "H"
else
rel = soutai2relative(sou) + dousa2relative(dou)
ret["relative"] = rel unless rel.empty?
end
ret
end | ruby | {
"resource": ""
} |
q22432 | Jkf::Parser.Base.match_spaces | train | def match_spaces
stack = []
matched = match_space
while matched != :failed
stack << matched
matched = match_space
end
stack
end | ruby | {
"resource": ""
} |
q22433 | Jkf::Parser.Kifuable.transform_root_forks | train | def transform_root_forks(forks, moves)
fork_stack = [{ "te" => 0, "moves" => moves }]
forks.each do |f|
now_fork = f
_fork = fork_stack.pop
_fork = fork_stack.pop while _fork["te"] > now_fork["te"]
move = _fork["moves"][now_fork["te"] - _fork["te"]]
move["forks"] ||= []
move["forks"] << now_fork["moves"]
fork_stack << _fork
fork_stack << now_fork
end
end | ruby | {
"resource": ""
} |
q22434 | Jkf::Parser.Kifuable.transform_initialboard | train | def transform_initialboard(lines)
board = []
9.times do |i|
line = []
9.times do |j|
line << lines[j][8 - i]
end
board << line
end
{ "preset" => "OTHER", "data" => { "board" => board } }
end | ruby | {
"resource": ""
} |
q22435 | Jkf::Parser.Csa.transform_komabetsu_lines | train | def transform_komabetsu_lines(lines)
board = generate_empty_board
hands = [
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 },
{ "FU" => 0, "KY" => 0, "KE" => 0, "GI" => 0, "KI" => 0, "KA" => 0, "HI" => 0 }
]
all = { "FU" => 18, "KY" => 4, "KE" => 4, "GI" => 4, "KI" => 4, "KA" => 2, "HI" => 2 }
lines.each do |line|
line["pieces"].each do |piece|
xy = piece["xy"]
if xy["x"] == 0
if piece["piece"] == "AL"
hands[line["teban"]] = all
return { "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end
obj = hands[line["teban"]]
obj[piece["piece"]] += 1
else
board[xy["x"] - 1][xy["y"] - 1] = { "color" => line["teban"],
"kind" => piece["piece"] }
end
all[piece["piece"]] -= 1 if piece["piece"] != "OU"
end
end
{ "preset" => "OTHER", "data" => { "board" => board, "hands" => hands } }
end | ruby | {
"resource": ""
} |
q22436 | Jkf::Parser.Csa.generate_empty_board | train | def generate_empty_board
board = []
9.times do |_i|
line = []
9.times do |_j|
line << {}
end
board << line
end
board
end | ruby | {
"resource": ""
} |
q22437 | Stellar.Transaction.to_operations | train | def to_operations
cloned = Marshal.load Marshal.dump(operations)
operations.each do |op|
op.source_account ||= self.source_account
end
end | ruby | {
"resource": ""
} |
q22438 | Stellar.PathPaymentResult.send_amount | train | def send_amount
s = success!
return s.last.amount if s.offers.blank?
source_asset = s.offers.first.asset_bought
source_offers = s.offers.take_while{|o| o.asset_bought == source_asset}
source_offers.map(&:amount_bought).sum
end | ruby | {
"resource": ""
} |
q22439 | Stellar.TransactionEnvelope.signed_correctly? | train | def signed_correctly?(*key_pairs)
hash = tx.hash
return false if signatures.empty?
key_index = key_pairs.index_by(&:signature_hint)
signatures.all? do |sig|
key_pair = key_index[sig.hint]
break false if key_pair.nil?
key_pair.verify(sig.signature, hash)
end
end | ruby | {
"resource": ""
} |
q22440 | Beetle.Client.configure | train | def configure(options={}, &block)
configurator = Configurator.new(self, options)
if block.arity == 1
yield configurator
else
configurator.instance_eval(&block)
end
self
end | ruby | {
"resource": ""
} |
q22441 | Beetle.Client.rpc | train | def rpc(message_name, data=nil, opts={})
message_name = validated_message_name(message_name)
publisher.rpc(message_name, data, opts)
end | ruby | {
"resource": ""
} |
q22442 | Beetle.Client.trace | train | def trace(queue_names=self.queues.keys, tracer=nil, &block)
queues_to_trace = self.queues.slice(*queue_names)
queues_to_trace.each do |name, opts|
opts.merge! :durable => false, :auto_delete => true, :amqp_name => queue_name_for_tracing(opts[:amqp_name])
end
tracer ||=
lambda do |msg|
puts "-----===== new message =====-----"
puts "SERVER: #{msg.server}"
puts "HEADER: #{msg.header.attributes[:headers].inspect}"
puts "EXCHANGE: #{msg.header.method.exchange}"
puts "KEY: #{msg.header.method.routing_key}"
puts "MSGID: #{msg.msg_id}"
puts "DATA: #{msg.data}"
end
register_handler(queue_names){|msg| tracer.call msg }
listen_queues(queue_names, &block)
end | ruby | {
"resource": ""
} |
q22443 | Beetle.Client.load | train | def load(glob)
b = binding
Dir[glob].each do |f|
eval(File.read(f), b, f)
end
end | ruby | {
"resource": ""
} |
q22444 | Beetle.Message.decode | train | def decode #:nodoc:
amqp_headers = header.attributes
@uuid = amqp_headers[:message_id]
@timestamp = amqp_headers[:timestamp]
headers = amqp_headers[:headers].symbolize_keys
@format_version = headers[:format_version].to_i
@flags = headers[:flags].to_i
@expires_at = headers[:expires_at].to_i
rescue Exception => @exception
Beetle::reraise_expectation_errors!
logger.error "Could not decode message. #{self.inspect}"
end | ruby | {
"resource": ""
} |
q22445 | Beetle.Message.key_exists? | train | def key_exists?
old_message = !@store.msetnx(msg_id, :status =>"incomplete", :expires => @expires_at, :timeout => now + timeout)
if old_message
logger.debug "Beetle: received duplicate message: #{msg_id} on queue: #{@queue}"
end
old_message
end | ruby | {
"resource": ""
} |
q22446 | Beetle.Message.process | train | def process(handler)
logger.debug "Beetle: processing message #{msg_id}"
result = nil
begin
result = process_internal(handler)
handler.process_exception(@exception) if @exception
handler.process_failure(result) if result.failure?
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.warn "Beetle: exception '#{e}' during processing of message #{msg_id}"
logger.warn "Beetle: backtrace: #{e.backtrace.join("\n")}"
result = RC::InternalError
end
result
end | ruby | {
"resource": ""
} |
q22447 | Beetle.Message.ack! | train | def ack!
#:doc:
logger.debug "Beetle: ack! for message #{msg_id}"
header.ack
return if simple? # simple messages don't use the deduplication store
if !redundant? || @store.incr(msg_id, :ack_count) == 2
@store.del_keys(msg_id)
end
end | ruby | {
"resource": ""
} |
q22448 | Beetle.Publisher.bunny_exceptions | train | def bunny_exceptions
[
Bunny::ConnectionError, Bunny::ForcedChannelCloseError, Bunny::ForcedConnectionCloseError,
Bunny::MessageError, Bunny::ProtocolError, Bunny::ServerDownError, Bunny::UnsubscribeError,
Bunny::AcknowledgementError, Qrack::BufferOverflowError, Qrack::InvalidTypeError,
Errno::EHOSTUNREACH, Errno::ECONNRESET, Timeout::Error
]
end | ruby | {
"resource": ""
} |
q22449 | Beetle.Publisher.recycle_dead_servers | train | def recycle_dead_servers
recycle = []
@dead_servers.each do |s, dead_since|
recycle << s if dead_since < 10.seconds.ago
end
if recycle.empty? && @servers.empty?
recycle << @dead_servers.keys.sort_by{|k| @dead_servers[k]}.first
end
@servers.concat recycle
recycle.each {|s| @dead_servers.delete(s)}
end | ruby | {
"resource": ""
} |
q22450 | Beetle.DeduplicationStore.with_failover | train | def with_failover #:nodoc:
end_time = Time.now.to_i + @config.redis_failover_timeout.to_i
begin
yield
rescue Exception => e
Beetle::reraise_expectation_errors!
logger.error "Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})"
if Time.now.to_i < end_time
sleep 1
logger.info "Beetle: retrying redis operation"
retry
else
raise NoRedisMaster.new(e.to_s)
end
end
end | ruby | {
"resource": ""
} |
q22451 | Beetle.DeduplicationStore.extract_redis_master | train | def extract_redis_master(text)
system_name = @config.system_name
redis_master = ""
text.each_line do |line|
parts = line.split('/', 2)
case parts.size
when 1
redis_master = parts[0]
when 2
name, master = parts
redis_master = master if name == system_name
end
end
redis_master
end | ruby | {
"resource": ""
} |
q22452 | Beetle.Subscriber.close_all_connections | train | def close_all_connections
if @connections.empty?
EM.stop_event_loop
else
server, connection = @connections.shift
logger.debug "Beetle: closing connection to #{server}"
connection.close { close_all_connections }
end
end | ruby | {
"resource": ""
} |
q22453 | ForemanDigitalocean.Digitalocean.setup_key_pair | train | def setup_key_pair
public_key, private_key = generate_key
key_name = "foreman-#{id}#{Foreman.uuid}"
client.create_ssh_key key_name, public_key
KeyPair.create! :name => key_name, :compute_resource_id => id, :secret => private_key
rescue StandardError => e
logger.warn 'failed to generate key pair'
logger.error e.message
logger.error e.backtrace.join("\n")
destroy_key_pair
raise
end | ruby | {
"resource": ""
} |
q22454 | Keen.SavedQueries.clear_nil_attributes | train | def clear_nil_attributes(hash)
hash.reject! do |key, value|
if value.nil?
return true
elsif value.is_a? Hash
value.reject! { |inner_key, inner_value| inner_value.nil? }
end
false
end
hash
end | ruby | {
"resource": ""
} |
q22455 | SugarCRM.ConnectionPool.with_connection | train | def with_connection
connection_id = current_connection_id
fresh_connection = true unless @reserved_connections[connection_id]
yield connection
ensure
release_connection(connection_id) if fresh_connection
end | ruby | {
"resource": ""
} |
q22456 | SugarCRM.ConnectionPool.clear_stale_cached_connections! | train | def clear_stale_cached_connections!
keys = @reserved_connections.keys - Thread.list.find_all { |t|
t.alive?
}.map { |thread| thread.object_id }
keys.each do |key|
checkin @reserved_connections[key]
@reserved_connections.delete(key)
end
end | ruby | {
"resource": ""
} |
q22457 | SugarCRM.AttributeMethods.merge_attributes | train | def merge_attributes(attrs={})
# copy attributes from the parent module fields array
@attributes = self.class.attributes_from_module
# populate the attributes with values from the attrs provided to init.
@attributes.keys.each do |name|
write_attribute name, attrs[name] if attrs[name]
end
# If this is an existing record, blank out the modified_attributes hash
@modified_attributes = {} unless new?
end | ruby | {
"resource": ""
} |
q22458 | SugarCRM.AttributeMethods.save_modified_attributes! | train | def save_modified_attributes!(opts={})
options = { :validate => true }.merge(opts)
if options[:validate]
# Complain if we aren't valid
raise InvalidRecord, @errors.full_messages.join(", ") unless valid?
end
# Send the save request
response = self.class.session.connection.set_entry(self.class._module.name, serialize_modified_attributes)
# Complain if we don't get a parseable response back
raise RecordsaveFailed, "Failed to save record: #{self}. Response was not a Hash" unless response.is_a? Hash
# Complain if we don't get a valid id back
raise RecordSaveFailed, "Failed to save record: #{self}. Response did not contain a valid 'id'." if response["id"].nil?
# Save the id to the record, if it's a new record
@attributes[:id] = response["id"] if new?
raise InvalidRecord, "Failed to update id for: #{self}." if id.nil?
# Clear the modified attributes Hash
@modified_attributes = {}
true
end | ruby | {
"resource": ""
} |
q22459 | SugarCRM.Associations.find! | train | def find!(target)
@associations.each do |a|
return a if a.include? target
end
raise InvalidAssociation, "Could not lookup association for: #{target}"
end | ruby | {
"resource": ""
} |
q22460 | SugarCRM.AssociationMethods.query_association | train | def query_association(assoc, reload=false)
association = assoc.to_sym
return @association_cache[association] if association_cached?(association) && !reload
# TODO: Some relationships aren't fetchable via get_relationship (i.e users.contacts)
# even though get_module_fields lists them on the related_fields array. This is most
# commonly seen with one-to-many relationships without a join table. We need to cook
# up some elegant way to handle this.
collection = AssociationCollection.new(self,association,true)
# add it to the cache
@association_cache[association] = collection
collection
end | ruby | {
"resource": ""
} |
q22461 | SugarCRM.AssociationCache.update_association_cache_for | train | def update_association_cache_for(association, target, action=:add)
return unless association_cached? association
case action
when :add
return if @association_cache[association].collection.include? target
@association_cache[association].push(target) # don't use `<<` because overriden method in AssociationCollection gets called instead
when :delete
@association_cache[association].delete target
end
end | ruby | {
"resource": ""
} |
q22462 | SugarCRM.AssociationCollection.changed? | train | def changed?
return false unless loaded?
return true if added.length > 0
return true if removed.length > 0
false
end | ruby | {
"resource": ""
} |
q22463 | SugarCRM.AssociationCollection.delete | train | def delete(record)
load
raise InvalidRecord, "#{record.class} does not have a valid :id!" if record.id.empty?
@collection.delete record
end | ruby | {
"resource": ""
} |
q22464 | SugarCRM.AssociationCollection.<< | train | def <<(record)
load
record.save! if record.new?
result = true
result = false if include?(record)
@owner.update_association_cache_for(@association, record, :add)
record.update_association_cache_for(record.associations.find!(@owner).link_field, @owner, :add)
result && self
end | ruby | {
"resource": ""
} |
q22465 | SugarCRM.AssociationCollection.method_missing | train | def method_missing(method_name, *args, &block)
load
@collection.send(method_name.to_sym, *args, &block)
end | ruby | {
"resource": ""
} |
q22466 | SugarCRM.AssociationCollection.save! | train | def save!
load
added.each do |record|
associate!(record)
end
removed.each do |record|
disassociate!(record)
end
reload
true
end | ruby | {
"resource": ""
} |
q22467 | SugarCRM.AssociationCollection.load_associated_records | train | def load_associated_records
array = @owner.class.session.connection.get_relationships(@owner.class._module.name, @owner.id, @association.to_s)
@loaded = true
# we use original to track the state of the collection at start
@collection = Array.wrap(array).dup
@original = Array.wrap(array).freeze
end | ruby | {
"resource": ""
} |
q22468 | SugarCRM.Connection.class_for | train | def class_for(module_name)
begin
class_const = @session.namespace_const.const_get(module_name.classify)
klass = class_const.new
rescue NameError
raise InvalidModule, "Module: #{module_name} is not registered"
end
end | ruby | {
"resource": ""
} |
q22469 | SugarCRM.Connection.send! | train | def send!(method, json, max_retry=3)
if max_retry == 0
raise SugarCRM::RetryLimitExceeded, "SugarCRM::Connection Errors: \n#{@errors.reverse.join "\n\s\s"}"
end
@request = SugarCRM::Request.new(@url, method, json, @options[:debug])
# Send Ze Request
begin
if @request.length > 3900
@response = @connection.post(@url.path, @request)
else
@response = @connection.get(@url.path.dup + "?" + @request.to_s)
end
return handle_response
# Timeouts are usually a server side issue
rescue Timeout::Error => error
@errors << error
send!(method, json, max_retry.pred)
# Lower level errors requiring a reconnect
rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPIPE, EOFError => error
@errors << error
reconnect!
send!(method, json, max_retry.pred)
# Handle invalid sessions
rescue SugarCRM::InvalidSession => error
@errors << error
old_session = @sugar_session_id.dup
login!
# Update the session id in the request that we want to retry.
json.gsub!(old_session, @sugar_session_id)
send!(method, json, max_retry.pred)
end
end | ruby | {
"resource": ""
} |
q22470 | SugarCRM.Session.reconnect | train | def reconnect(url=nil, user=nil, pass=nil, opts={})
@connection_pool.disconnect!
connect(url, user, pass, opts)
end | ruby | {
"resource": ""
} |
q22471 | SugarCRM.Session.load_extensions | train | def load_extensions
self.class.validate_path @extensions_path
Dir[File.join(@extensions_path, '**', '*.rb').to_s].each { |f| load(f) }
end | ruby | {
"resource": ""
} |
q22472 | SugarCRM.Association.include? | train | def include?(attribute)
return true if attribute.class == @target
return true if attribute == link_field
return true if methods.include? attribute
false
end | ruby | {
"resource": ""
} |
q22473 | SugarCRM.Association.resolve_target | train | def resolve_target
# Use the link_field name first
klass = @link_field.singularize.camelize
namespace = @owner.class.session.namespace_const
return namespace.const_get(klass) if namespace.const_defined? klass
# Use the link_field attribute "module"
if @attributes["module"].length > 0
module_name = SugarCRM::Module.find(@attributes["module"], @owner.class.session)
return namespace.const_get(module_name.klass) if module_name && namespace.const_defined?(module_name.klass)
end
# Use the "relationship" target
if @attributes["relationship"].length > 0
klass = @relationship[:target][:name].singularize.camelize
return namespace.const_get(klass) if namespace.const_defined? klass
end
false
end | ruby | {
"resource": ""
} |
q22474 | SugarCRM.Association.define_methods | train | def define_methods
methods = []
pretty_name = @relationship[:target][:name]
methods << define_method(@link_field)
methods << define_alias(pretty_name, @link_field) if pretty_name != @link_field
methods
end | ruby | {
"resource": ""
} |
q22475 | SugarCRM.Association.define_method | train | def define_method(link_field)
raise ArgumentError, "argument cannot be nil" if link_field.nil?
if (@owner.respond_to? link_field.to_sym) && @owner.debug
warn "Warning: Overriding method: #{@owner.class}##{link_field}"
end
@owner.class.module_eval %Q?
def #{link_field}
query_association :#{link_field}
end
?
link_field
end | ruby | {
"resource": ""
} |
q22476 | SugarCRM.Association.cardinality_for | train | def cardinality_for(*args)
args.inject([]) {|results,arg|
result = :many
result = :one if arg.singularize == arg
results << result
}
end | ruby | {
"resource": ""
} |
q22477 | SugarCRM.Request.convert_reserved_characters | train | def convert_reserved_characters(string)
string.gsub!(/"/, '\"')
string.gsub!(/'/, '\'')
string.gsub!(/&/, '\&')
string.gsub!(/</, '\<')
string.gsub!(/</, '\>')
string
end | ruby | {
"resource": ""
} |
q22478 | SugarCRM.Module.fields | train | def fields
return @fields if fields_registered?
all_fields = @session.connection.get_fields(@name)
@fields = all_fields["module_fields"].with_indifferent_access
@link_fields= all_fields["link_fields"]
handle_empty_arrays
@fields_registered = true
@fields
end | ruby | {
"resource": ""
} |
q22479 | SugarCRM.Module.required_fields | train | def required_fields
required_fields = []
ignore_fields = [:id, :date_entered, :date_modified]
self.fields.each_value do |field|
next if ignore_fields.include? field["name"].to_sym
required_fields << field["name"].to_sym if field["required"] == 1
end
required_fields
end | ruby | {
"resource": ""
} |
q22480 | SugarCRM.Module.deregister | train | def deregister
return true unless registered?
klass = self.klass
@session.namespace_const.instance_eval{ remove_const klass }
true
end | ruby | {
"resource": ""
} |
q22481 | SugarCRM.AttributeSerializers.serialize_attribute | train | def serialize_attribute(name,value)
attr_value = value
attr_type = attr_type_for(name)
case attr_type
when :bool
attr_value = 0
attr_value = 1 if value
when :datetime, :datetimecombo
begin
attr_value = value.strftime("%Y-%m-%d %H:%M:%S")
rescue
attr_value = value
end
when :int
attr_value = value.to_s
end
{:name => name, :value => attr_value}
end | ruby | {
"resource": ""
} |
q22482 | SugarCRM.Base.save | train | def save(opts={})
options = { :validate => true }.merge(opts)
return false if !(new_record? || changed?)
if options[:validate]
return false if !valid?
end
begin
save!(options)
rescue
return false
end
true
end | ruby | {
"resource": ""
} |
q22483 | SugarCRM.AttributeValidations.valid? | train | def valid?
@errors = (defined?(HashWithIndifferentAccess) ? HashWithIndifferentAccess : ActiveSupport::HashWithIndifferentAccess).new
self.class._module.required_fields.each do |attribute|
valid_attribute?(attribute)
end
# for rails compatibility
def @errors.full_messages
# After removing attributes without errors, flatten the error hash, repeating the name of the attribute before each message:
# e.g. {'name' => ['cannot be blank', 'is too long'], 'website' => ['is not valid']}
# will become 'name cannot be blank, name is too long, website is not valid
self.inject([]){|memo, obj| memo.concat(obj[1].inject([]){|m, o| m << "#{obj[0].to_s.humanize} #{o}" })}
end
# Rails needs each attribute to be present in the error hash (if the attribute has no error, it has [] as a value)
# Redefine the [] method for the errors hash to return [] instead of nil is the hash doesn't contain the key
class << @errors
alias :old_key_lookup :[]
def [](key)
old_key_lookup(key) || Array.new
end
end
@errors.size == 0
end | ruby | {
"resource": ""
} |
q22484 | SugarCRM.AttributeValidations.validate_class_for | train | def validate_class_for(attribute, class_array)
return true if class_array.include? @attributes[attribute].class
add_error(attribute, "must be a #{class_array.join(" or ")} object (not #{@attributes[attribute].class})")
false
end | ruby | {
"resource": ""
} |
q22485 | SugarCRM.AttributeValidations.add_error | train | def add_error(attribute, message)
@errors[attribute] ||= []
@errors[attribute] = @errors[attribute] << message unless @errors[attribute].include? message
@errors
end | ruby | {
"resource": ""
} |
q22486 | SugarCRM.Response.to_obj | train | def to_obj
# If this is not a "entry_list" response, just return
return @response unless @response && @response["entry_list"]
objects = []
@response["entry_list"].each do |object|
attributes = []
_module = resolve_module(object)
attributes = flatten_name_value_list(object)
namespace = @session.namespace_const
if namespace.const_get(_module)
if attributes.length == 0
raise AttributeParsingError, "response contains objects without attributes!"
end
objects << namespace.const_get(_module).new(attributes)
else
raise InvalidModule, "#{_module} does not exist, or is not accessible"
end
end
# If we only have one result, just return the object
if objects.length == 1 && !@options[:always_return_array]
return objects[0]
else
return objects
end
end | ruby | {
"resource": ""
} |
q22487 | SugarCRM.AttributeTypeCast.attr_type_for | train | def attr_type_for(attribute)
fields = self.class._module.fields
field = fields[attribute]
raise UninitializedModule, "#{self.class.session.namespace_const}Module #{self.class._module.name} was not initialized properly (fields.length == 0)" if fields.length == 0
raise InvalidAttribute, "#{self.class}._module.fields does not contain an entry for #{attribute} (of type: #{attribute.class})\nValid fields: #{self.class._module.fields.keys.sort.join(", ")}" if field.nil?
raise InvalidAttributeType, "#{self.class}._module.fields[#{attribute}] does not have a key for \'type\'" if field["type"].nil?
field["type"].to_sym
end | ruby | {
"resource": ""
} |
q22488 | SugarCRM.AttributeTypeCast.typecast_attributes | train | def typecast_attributes
@attributes.each_pair do |name,value|
# skip primary key columns
# ajay Singh --> skip the loop if attribute is null (!name.present?)
next if (name == "id") or (!name.present?)
attr_type = attr_type_for(name)
# empty attributes should stay empty (e.g. an empty int field shouldn't be typecast as 0)
if [:datetime, :datetimecombo, :int].include? attr_type && (value.nil? || value == '')
@attributes[name] = nil
next
end
case attr_type
when :bool
@attributes[name] = (value == "1")
when :datetime, :datetimecombo
begin
@attributes[name] = DateTime.parse(value)
rescue
@attributes[name] = value
end
when :int
@attributes[name] = value.to_i
end
end
@attributes
end | ruby | {
"resource": ""
} |
q22489 | Angular.Setup.make_nodes | train | def make_nodes(ids, opt)
result = []
ids.each do |id|
id = id.tr('"', '')
selector = "//*[@capybara-ng-match='#{id}']"
nodes = page.driver.find_xpath(selector)
raise NotFound.new("Failed to match found id to node") if nodes.empty?
result.concat(nodes)
end
page.evaluate_script("clearCapybaraNgMatches('#{opt[:root_selector]}')");
result
end | ruby | {
"resource": ""
} |
q22490 | Angular.DSL.ng_root_selector | train | def ng_root_selector(root_selector = nil)
opt = ng.page.ng_session_options
if root_selector
opt[:root_selector] = root_selector
end
opt[:root_selector] || ::Angular.root_selector
end | ruby | {
"resource": ""
} |
q22491 | Angular.DSL.ng_binding | train | def ng_binding(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_bindings(binding, opt)[row]
end | ruby | {
"resource": ""
} |
q22492 | Angular.DSL.ng_bindings | train | def ng_bindings(binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findBindingsIds, [binding, opt[:exact] == true], opt
end | ruby | {
"resource": ""
} |
q22493 | Angular.DSL.ng_model | train | def ng_model(model, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_models(model, opt)[row]
end | ruby | {
"resource": ""
} |
q22494 | Angular.DSL.has_ng_options? | train | def has_ng_options?(options, opt = {})
opt[:root_selector] ||= ng_root_selector
ng_options(options, opt)
true
rescue NotFound
false
end | ruby | {
"resource": ""
} |
q22495 | Angular.DSL.ng_option | train | def ng_option(options, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_options(options, opt)[row]
end | ruby | {
"resource": ""
} |
q22496 | Angular.DSL.ng_repeater_row | train | def ng_repeater_row(repeater, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
data = ng.get_nodes_2(:findRepeaterRowsIds, [repeater, row], opt)
data.first
end | ruby | {
"resource": ""
} |
q22497 | Angular.DSL.ng_repeater_column | train | def ng_repeater_column(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
row = ng.row(opt)
ng_repeater_columns(repeater, binding, opt)[row]
end | ruby | {
"resource": ""
} |
q22498 | Angular.DSL.ng_repeater_columns | train | def ng_repeater_columns(repeater, binding, opt = {})
opt[:root_selector] ||= ng_root_selector
ng.get_nodes_2 :findRepeaterColumnIds, [repeater, binding], opt
end | ruby | {
"resource": ""
} |
q22499 | ZBar.Image.set_data | train | def set_data(format, data, width=nil, height=nil)
ZBar.zbar_image_set_format(@img, format)
# Note the @buffer jog: it's to keep Ruby GC from losing the last
# reference to the old @buffer before calling image_set_data.
new_buffer = FFI::MemoryPointer.from_string(data)
ZBar.zbar_image_set_data(@img, new_buffer, data.size, nil)
@buffer = new_buffer
if width && height
ZBar.zbar_image_set_size(@img, width.to_i, height.to_i)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.