_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q20500 | HQMF2CQL.Document.make_positive_entry | train | def make_positive_entry
negated_criteria = []
data_criteria_index_lookup = []
# Find the criteria that are negated
# At the same time build a hash of all criteria and their code_list_id, definition, status, and negation status
@data_criteria.each_with_index do |criterion, source_index|
negated_criteria << criterion if criterion.negation
data_criteria_index_lookup << [criterion.code_list_id, criterion.definition, criterion.status, criterion.negation]
end
negated_criteria.each do |criterion|
# Check if there is a criterion with the same OID, definition and status BUT that isn't negated
unless data_criteria_index_lookup.include?([criterion.code_list_id, criterion.definition, criterion.status, false])
spoofed_positive_instance = criterion.clone
spoofed_positive_instance.make_criterion_positive
@data_criteria << spoofed_positive_instance
sdc = spoofed_positive_instance.clone
sdc.id += '_source'
@source_data_criteria << sdc
end
end
end | ruby | {
"resource": ""
} |
q20501 | Measures.CqlLoader.extract_measures | train | def extract_measures
measure_files = MATMeasureFiles.create_from_zip_file(@measure_zip)
measures = []
if measure_files.components.present?
measure, component_measures = create_measure_and_components(measure_files)
measures.push(*component_measures)
else
measure = create_measure(measure_files)
end
measure.package = CQM::MeasurePackage.new(file: BSON::Binary.new(@measure_zip.read))
measures << measure
measures.each { |m| CqlLoader.update_population_set_and_strat_titles(m, @measure_details[:population_titles]) }
return measures
end | ruby | {
"resource": ""
} |
q20502 | Measures.CqlLoader.create_measure | train | def create_measure(measure_files)
hqmf_xml = measure_files.hqmf_xml
# update the valueset info in each elm (update version and remove urn:oid)
measure_files.cql_libraries.each { |cql_lib_files| modify_elm_valueset_information(cql_lib_files.elm) }
measure = CQM::Measure.new(HQMFMeasureLoader.extract_fields(hqmf_xml))
measure.cql_libraries = create_cql_libraries(measure_files.cql_libraries, measure.main_cql_library)
measure.composite = measure_files.components.present?
measure.calculation_method = @measure_details[:episode_of_care] ? 'EPISODE_OF_CARE' : 'PATIENT'
measure.calculate_sdes = @measure_details[:calculate_sdes]
hqmf_model = HQMF::Parser::V2CQLParser.new.parse(hqmf_xml) # TODO: move away from using V2CQLParser
elms = measure.cql_libraries.map(&:elm)
elm_valuesets = ValueSetHelpers.unique_list_of_valuesets_referenced_by_elms(elms)
verify_hqmf_valuesets_match_elm_valuesets(elm_valuesets, hqmf_model)
value_sets_from_single_code_references = ValueSetHelpers.make_fake_valuesets_from_single_code_references(elms, @vs_model_cache)
measure.source_data_criteria = SourceDataCriteriaLoader.new(hqmf_xml, value_sets_from_single_code_references).extract_data_criteria
measure.value_sets = value_sets_from_single_code_references
measure.value_sets.concat(@value_set_loader.retrieve_and_modelize_value_sets_from_vsac(elm_valuesets)) if @value_set_loader.present?
## this to_json is needed, it doesn't actually produce json, it just makes a hash that is better
## suited for our uses (e.g. source_data_criteria goes from an array to a hash keyed by id)
hqmf_model_hash = hqmf_model.to_json.deep_symbolize_keys!
HQMFMeasureLoader.add_fields_from_hqmf_model_hash(measure, hqmf_model_hash)
return measure
end | ruby | {
"resource": ""
} |
q20503 | HQMF2.DataCriteria.retrieve_code_system_for_model | train | def retrieve_code_system_for_model
code_system = attr_val("#{@code_list_xpath}/@codeSystem")
if code_system
code_system_name = HQMF::Util::CodeSystemHelper.code_system_for(code_system)
else
code_system_name = attr_val("#{@code_list_xpath}/@codeSystemName")
end
code_value = attr_val("#{@code_list_xpath}/@code")
{ code_system_name => [code_value] } if code_system_name && code_value
end | ruby | {
"resource": ""
} |
q20504 | HQMF2.Document.read_attribute | train | def read_attribute(attribute)
id = attribute.at_xpath('./cda:id/@root', NAMESPACES).try(:value)
code = attribute.at_xpath('./cda:code/@code', NAMESPACES).try(:value)
name = attribute.at_xpath('./cda:code/cda:displayName/@value', NAMESPACES).try(:value)
value = attribute.at_xpath('./cda:value/@value', NAMESPACES).try(:value)
id_obj = nil
if attribute.at_xpath('./cda:id', NAMESPACES)
id_obj = HQMF::Identifier.new(attribute.at_xpath('./cda:id/@xsi:type', NAMESPACES).try(:value),
id,
attribute.at_xpath('./cda:id/@extension', NAMESPACES).try(:value))
end
code_obj = nil
if attribute.at_xpath('./cda:code', NAMESPACES)
code_obj, null_flavor, o_text = handle_attribute_code(attribute, code, name)
# Mapping for nil values to align with 1.0 parsing
code = null_flavor if code.nil?
name = o_text if name.nil?
end
value_obj = nil
value_obj = handle_attribute_value(attribute, value) if attribute.at_xpath('./cda:value', NAMESPACES)
# Handle the cms_id - changed to eCQM in MAT 5.4 (QDM 5.3)
@cms_id = "CMS#{value}v#{@hqmf_version_number.to_i}" if name&.start_with?('eMeasure Identifier', 'eCQM Identifier')
HQMF::Attribute.new(id, code, value, nil, name, id_obj, code_obj, value_obj)
end | ruby | {
"resource": ""
} |
q20505 | HQMF2CQL.DocumentPopulationHelper.extract_populations_cql_map | train | def extract_populations_cql_map
populations_cql_map = {}
@doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES).each do |population_def|
{
HQMF::PopulationCriteria::IPP => 'initialPopulationCriteria',
HQMF::PopulationCriteria::DENOM => 'denominatorCriteria',
HQMF::PopulationCriteria::NUMER => 'numeratorCriteria',
HQMF::PopulationCriteria::NUMEX => 'numeratorExclusionCriteria',
HQMF::PopulationCriteria::DENEXCEP => 'denominatorExceptionCriteria',
HQMF::PopulationCriteria::DENEX => 'denominatorExclusionCriteria',
HQMF::PopulationCriteria::MSRPOPL => 'measurePopulationCriteria',
HQMF::PopulationCriteria::MSRPOPLEX => 'measurePopulationExclusionCriteria',
HQMF::PopulationCriteria::STRAT => 'stratifierCriteria'
}.each_pair do |criteria_id, criteria_element_name|
criteria_def = population_def.at_xpath("cda:#{criteria_element_name}", HQMF2::Document::NAMESPACES)
if criteria_def
# Ignore Supplemental Data Elements
next if HQMF::PopulationCriteria::STRAT == criteria_id &&
!criteria_def.xpath("cda:component[@typeCode='COMP']/cda:measureAttribute/cda:code[@code='SDE']").empty?
cql_statement = criteria_def.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/"([^"]*)"/)
if populations_cql_map[criteria_id].nil?
populations_cql_map[criteria_id] = []
end
cql_statement = cql_statement.to_s.delete('\\"')
populations_cql_map[criteria_id].push cql_statement
end
end
end
populations_cql_map
end | ruby | {
"resource": ""
} |
q20506 | HQMF2CQL.DocumentPopulationHelper.extract_main_library | train | def extract_main_library
population_criteria_sections = @doc.xpath("//cda:populationCriteriaSection/cda:component[@typeCode='COMP']", HQMF2::Document::NAMESPACES)
criteria_section = population_criteria_sections.at_xpath("cda:initialPopulationCriteria", HQMF2::Document::NAMESPACES)
if criteria_section
# Example: the full name for the population criteria section is "BonnieNesting01.\"Initial Population\""
# The regex returns everything before the "." (BonnieNesting01), which is the file name of the cql measure
cql_main_library_name = criteria_section.at_xpath("*/*/cda:id", HQMF2::Document::NAMESPACES).attribute('extension').to_s.match(/[^.]*/).to_s
else
nil
end
end | ruby | {
"resource": ""
} |
q20507 | HQMF2CQL.DataCriteria.title | train | def title
disp_value = attr_val("#{@code_list_xpath}/cda:displayName/@value")
# Attempt to pull display value from the localVariableName for
# MAT 5.3+ exports that appear to no longer include displayName for
# code entries.
# NOTE: A long term replacement for this and for other portions of the
# parsing process should involve reaching out to VSAC for oid information
# pulled from the CQL, and then to use that information while parsing.
unless disp_value.present?
# Grab the localVariableName from the XML
disp_value = attr_val('./cda:localVariableName/@value')
# Grab everything before the first underscore
disp_value = disp_value.partition('_').first unless disp_value.nil?
end
@title || disp_value || @description || id # allow defined titles to take precedence
end | ruby | {
"resource": ""
} |
q20508 | WeixinRailsMiddleware.WexinAdapter.render_authorize_result | train | def render_authorize_result(status=401, text=nil, valid=false)
text = text || error_msg
Rails.logger.error(text) if status != 200
{plain: text, status: status, valid: valid}
end | ruby | {
"resource": ""
} |
q20509 | WeixinRailsMiddleware.ReplyWeixinMessageHelper.reply_music_message | train | def reply_music_message(from=nil, to=nil, music)
message = MusicReplyMessage.new
message.FromUserName = from || @weixin_message.ToUserName
message.ToUserName = to || @weixin_message.FromUserName
message.Music = music
encrypt_message message.to_xml
end | ruby | {
"resource": ""
} |
q20510 | SGF.Writer.save | train | def save(root_node, filename)
# TODO: - accept any I/O object?
stringify_tree_from root_node
File.open(filename, 'w') {|f| f << @sgf}
end | ruby | {
"resource": ""
} |
q20511 | SGF.Node.add_children | train | def add_children(*nodes)
new_children = nodes.flatten
new_children.each do |node|
node.set_parent self
node.add_observer(self)
end
changed
notify_observers :new_children, new_children
end | ruby | {
"resource": ""
} |
q20512 | RichTextRenderer.TextRenderer.render | train | def render(node)
node = Marshal.load(Marshal.dump(node)) # Clone the node
node.fetch('marks', []).each do |mark|
renderer = mappings[mark['type']]
return mappings[nil].new(mappings).render(mark) if renderer.nil? && mappings.key?(nil)
node['value'] = renderer.new(mappings).render(node) unless renderer.nil?
end
node['value']
end | ruby | {
"resource": ""
} |
q20513 | RichTextRenderer.Renderer.render | train | def render(document)
renderer = find_renderer(document)
renderer.render(document) unless renderer.nil?
end | ruby | {
"resource": ""
} |
q20514 | RichTextRenderer.AssetHyperlinkRenderer.render | train | def render(node)
asset = nil
begin
asset = node['data']['target']
rescue
fail "Node target is not an asset - Node: #{node}"
end
# Check by class name instead of instance type to
# avoid dependending on the Contentful SDK.
return render_asset(asset, node) if asset.class.ancestors.map(&:to_s).any? { |name| name.include?('Asset') }
if asset.is_a?(::Hash)
unless asset.key?('fields') && asset['fields'].key?('file')
fail "Node target is not an asset - Node: #{node}"
end
return render_hash(asset, node)
end
fail "Node target is not an asset - Node: #{node}"
end | ruby | {
"resource": ""
} |
q20515 | RichTextRenderer.DocumentRenderer.render | train | def render(document)
document['content'].each_with_object([]) do |node, result|
result << find_renderer(node).render(node)
end.join("\n")
end | ruby | {
"resource": ""
} |
q20516 | SBConstants.CLI.parse_xibs | train | def parse_xibs
Dir["#{options.source_dir}/**/*.{storyboard,xib}"].each_with_index do |xib, xib_index|
filename = File.basename(xib, '.*')
next if options.ignored.include? filename
xibs << filename
group_name = "#{xib.split(".").last}Names"
constants[filename] << Location.new(group_name, nil, xib, filename, xib_index + 1)
File.readlines(xib, encoding: 'UTF-8').each_with_index do |line, index|
options.queries.each do |query|
next unless value = line[query.regex, 1]
next if value.strip.empty?
next unless value.start_with?(options.prefix) if options.prefix
constants[value] << Location.new(query.node, query.attribute, line.strip, filename, index + 1)
end
end
end
end | ruby | {
"resource": ""
} |
q20517 | Jekyll.Filters.textilize | train | def textilize(input)
site = @context.registers[:site]
converter = if site.respond_to?(:find_converter_instance)
site.find_converter_instance(Jekyll::Converters::Textile)
else
site.getConverterImpl(Jekyll::Converters::Textile)
end
converter.convert(input)
end | ruby | {
"resource": ""
} |
q20518 | Alma.AvailabilityResponse.parse_bibs_data | train | def parse_bibs_data(bibs)
bibs.reduce(Hash.new) { |acc, bib|
acc.merge({"#{bib.id}" => {holdings: build_holdings_for(bib)}})
}
end | ruby | {
"resource": ""
} |
q20519 | Alma.User.method_missing | train | def method_missing(name)
return response[name.to_s] if has_key?(name.to_s)
super.method_missing name
end | ruby | {
"resource": ""
} |
q20520 | Alma.User.save! | train | def save!
response = HTTParty.put("#{users_base_path}/#{id}", timeout: timeout, headers: headers, body: to_json)
get_body_from(response)
end | ruby | {
"resource": ""
} |
q20521 | Cortex.GraphqlController.ensure_hash | train | def ensure_hash(ambiguous_param)
case ambiguous_param
when String
if ambiguous_param.present?
ensure_hash(JSON.parse(ambiguous_param))
else
{}
end
when Hash, ActionController::Parameters
ambiguous_param
when nil
{}
else
raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
end
end | ruby | {
"resource": ""
} |
q20522 | ApipieBindings.Resource.call | train | def call(action, params={}, headers={}, options={})
@api.call(@name, action, params, headers, options)
end | ruby | {
"resource": ""
} |
q20523 | Nestful.Connection.request | train | def request(method, path, *arguments)
response = http.send(method, path, *arguments)
response.uri = URI.join(endpoint, path)
handle_response(response)
rescue Timeout::Error, Net::OpenTimeout => e
raise TimeoutError.new(@request, e.message)
rescue OpenSSL::SSL::SSLError => e
raise SSLError.new(@request, e.message)
rescue SocketError,
EOFError,
Net::HTTPBadResponse,
Net::HTTPHeaderSyntaxError,
Net::HTTPServerException,
Net::ProtocolError,
Errno::ECONNABORTED,
Errno::ECONNREFUSED,
Errno::ECONNRESET,
Errno::ETIMEDOUT,
Errno::ENETUNREACH,
Errno::EHOSTUNREACH,
Errno::EINVAL,
Errno::ENOPROTOOPT => e
raise ErrnoError.new(@request, e.message)
rescue Zlib::DataError,
Zlib::BufError => e
raise ZlibError.new(@request, e.message)
end | ruby | {
"resource": ""
} |
q20524 | ExceptionHandling.ExceptionInfo.extract_and_merge_controller_data | train | def extract_and_merge_controller_data(data)
if @controller
data[:request] = {
params: @controller.request.parameters.to_hash,
rails_root: defined?(Rails) && defined?(Rails.root) ? Rails.root : "Rails.root not defined. Is this a test environment?",
url: @controller.complete_request_uri
}
data[:environment].merge!(@controller.request.env.to_hash)
@controller.session[:fault_in_session]
data[:session] = {
key: @controller.request.session_options[:id],
data: @controller.session.to_hash
}
end
end | ruby | {
"resource": ""
} |
q20525 | Rsync.Change.summary | train | def summary
if update_type == :message
message
elsif update_type == :recv and @data[2,9] == "+++++++++"
"creating local"
elsif update_type == :recv
"updating local"
elsif update_type == :sent and @data[2,9] == "+++++++++"
"creating remote"
elsif update_type == :sent
"updating remote"
else
changes = []
[:checksum, :size, :timestamp, :permissions, :owner, :group, :acl].each do |prop|
changes << prop if send(prop) == :changed
end
changes.join(", ")
end
end | ruby | {
"resource": ""
} |
q20526 | Fidgit.Element.with | train | def with(&block)
raise ArgumentError.new("Must pass a block") unless block_given?
case block.arity
when 1
yield self
when 0
instance_methods_eval(&block)
else
raise "block arity must be 0 or 1"
end
end | ruby | {
"resource": ""
} |
q20527 | Fidgit.Schema.merge_constants! | train | def merge_constants!(constants_hash)
constants_hash.each_pair do |name, value|
@constants[name] = case value
when Array
case value.size
when 3 then Gosu::Color.rgb(*value)
when 4 then Gosu::Color.rgba(*value)
else
raise "Colors must be in 0..255, RGB or RGBA array format"
end
else
value
end
end
self
end | ruby | {
"resource": ""
} |
q20528 | Fidgit.Schema.merge_elements! | train | def merge_elements!(elements_hash)
elements_hash.each_pair do |klass_names, data|
klass = Fidgit
klass_names.to_s.split('::').each do |klass_name|
klass = klass.const_get klass_name
end
raise "elements must be names of classes derived from #{Element}" unless klass.ancestors.include? Fidgit::Element
@elements[klass] ||= {}
@elements[klass].deep_merge! data
end
self
end | ruby | {
"resource": ""
} |
q20529 | Fidgit.TextArea.selection_range | train | def selection_range
from = [@text_input.selection_start, caret_position].min
to = [@text_input.selection_start, caret_position].max
(from...to)
end | ruby | {
"resource": ""
} |
q20530 | Fidgit.TextArea.selection_text= | train | def selection_text=(str)
from = [@text_input.selection_start, @text_input.caret_pos].min
to = [@text_input.selection_start, @text_input.caret_pos].max
new_length = str.length
full_text = text
tags_length_before = (0...from).inject(0) {|m, i| m + @tags[i].length }
tags_length_inside = (from...to).inject(0) {|m, i| m + @tags[i].length }
range = (selection_range.first + tags_length_before)...(selection_range.last + tags_length_before + tags_length_inside)
full_text[range] = str.encode('UTF-8', undef: :replace)
@text_input.text = full_text
@text_input.selection_start = @text_input.caret_pos = from + new_length
recalc # This may roll back the text if it is too long!
publish :changed, self.text
str
end | ruby | {
"resource": ""
} |
q20531 | Fidgit.TextArea.caret_position= | train | def caret_position=(position)
raise ArgumentError, "Caret position must be in the range 0 to the length of the text (inclusive)" unless position.between?(0, stripped_text.length)
@text_input.caret_pos = position
position
end | ruby | {
"resource": ""
} |
q20532 | Fidgit.TextArea.draw_foreground | train | def draw_foreground
# Always roll back changes made by the user unless the text is editable.
if editable? or text == @old_text
recalc if focused? # Workaround for Windows draw/update bug.
@old_caret_position = caret_position
@old_selection_start = @text_input.selection_start
else
roll_back
end
if caret_position > stripped_text.length
self.caret_position = stripped_text.length
end
if @text_input.selection_start >= stripped_text.length
@text_input.selection_start = stripped_text.length
end
# Draw the selection.
selection_range.each do |pos|
char_x, char_y = @caret_positions[pos]
char_width = @char_widths[pos]
left, top = x + padding_left + char_x, y + padding_top + char_y
draw_rect left, top, char_width, font.height, z, @selection_color
end
# Draw text.
@lines.each_with_index do |line, index|
font.draw(line, x + padding_left, y + padding_top + y_at_line(index), z)
end
# Draw the caret.
if focused? and ((Gosu::milliseconds / @caret_period) % 2 == 0)
caret_x, caret_y = @caret_positions[caret_position]
left, top = x + padding_left + caret_x, y + padding_top + caret_y
draw_rect left, top, 1, font.height, z, @caret_color
end
end | ruby | {
"resource": ""
} |
q20533 | Fidgit.TextArea.text_index_at_position | train | def text_index_at_position(x, y)
# Move caret to position the user clicks on.
mouse_x, mouse_y = x - (self.x + padding_left), y - (self.y + padding_top)
@char_widths.each.with_index do |width, i|
char_x, char_y = @caret_positions[i]
if mouse_x.between?(char_x, char_x + width) and mouse_y.between?(char_y, char_y + font.height)
return i
end
end
nil # Didn't find a character at that position.
end | ruby | {
"resource": ""
} |
q20534 | Fidgit.TextArea.cut | train | def cut
str = selection_text
unless str.empty?
Clipboard.copy str
self.selection_text = '' if editable?
end
end | ruby | {
"resource": ""
} |
q20535 | Fidgit.Container.button | train | def button(text, options = {}, &block)
Button.new(text, {parent: self}.merge!(options), &block)
end | ruby | {
"resource": ""
} |
q20536 | Fidgit.Container.image_frame | train | def image_frame(image, options = {}, &block)
ImageFrame.new(image, {parent: self}.merge!(options), &block)
end | ruby | {
"resource": ""
} |
q20537 | Fidgit.Container.hit_element | train | def hit_element(x, y)
@children.reverse_each do |child|
case child
when Container, Composite
if element = child.hit_element(x, y)
return element
end
else
return child if child.hit?(x, y)
end
end
self if hit?(x, y)
end | ruby | {
"resource": ""
} |
q20538 | Fidgit.Label.icon_position= | train | def icon_position=(position)
raise ArgumentError.new("icon_position must be one of #{ICON_POSITIONS}") unless ICON_POSITIONS.include? position
@icon_position = position
case @icon_position
when :top, :bottom
@contents.instance_variable_set :@type, :fixed_columns
@contents.instance_variable_set :@num_columns, 1
when :left, :right
@contents.instance_variable_set :@type, :fixed_rows
@contents.instance_variable_set :@num_rows, 1
end
self.icon = @icon.image if @icon.image # Force the icon into the correct position.
position
end | ruby | {
"resource": ""
} |
q20539 | Fidgit.Packer.layout | train | def layout
# This assumes that the container overlaps all the children.
# Move all children if we have moved.
@children.each.with_index do |child, index|
child.x = padding_left + x
child.y = padding_top + y
end
# Make us as wrap around the largest child.
rect.width = (@children.map {|c| c.width }.max || 0) + padding_left + padding_right
rect.height = (@children.map {|c| c.height }.max || 0) + padding_top + padding_bottom
super
end | ruby | {
"resource": ""
} |
q20540 | Fidgit.GuiState.draw_rect | train | def draw_rect(x, y, width, height, z, color, mode = :default)
@@draw_pixel.draw x, y, z, width, height, color, mode
nil
end | ruby | {
"resource": ""
} |
q20541 | Fidgit.GuiState.draw_frame | train | def draw_frame(x, y, width, height, thickness, z, color, mode = :default)
draw_rect(x - thickness, y, thickness, height, z, color, mode) # left
draw_rect(x - thickness, y - thickness, width + thickness * 2, thickness, z, color, mode) # top (full)
draw_rect(x + width, y, thickness, height, z, color, mode) # right
draw_rect(x - thickness, y + height, width + thickness * 2, thickness, z, color, mode) # bottom (full)
nil
end | ruby | {
"resource": ""
} |
q20542 | Notiffany.Notifier.turn_on | train | def turn_on(options = {})
_check_server!
return unless enabled?
fail "Already active!" if active?
_turn_on_notifiers(options)
_env.notify_active = true
end | ruby | {
"resource": ""
} |
q20543 | Notiffany.Notifier.turn_off | train | def turn_off
_check_server!
fail "Not active!" unless active?
@detected.available.each do |obj|
obj.turn_off if obj.respond_to?(:turn_off)
end
_env.notify_active = false
end | ruby | {
"resource": ""
} |
q20544 | Notiffany.Notifier.notify | train | def notify(message, message_opts = {})
if _client?
return unless enabled?
else
return unless active?
end
@detected.available.each do |notifier|
notifier.notify(message, message_opts.dup)
end
end | ruby | {
"resource": ""
} |
q20545 | Turn.Controller.runner | train | def runner
@runner ||= (
require 'turn/runners/minirunner'
case config.runmode
when :marshal
Turn::MiniRunner
when :solo
require 'turn/runners/solorunner'
Turn::SoloRunner
when :cross
require 'turn/runners/crossrunner'
Turn::CrossRunner
else
Turn::MiniRunner
end
)
end | ruby | {
"resource": ""
} |
q20546 | Turn.PrettyReporter.pass | train | def pass(message=nil)
banner PASS
if message
message = Colorize.magenta(message)
message = message.to_s.tabto(TAB_SIZE)
io.puts(message)
end
end | ruby | {
"resource": ""
} |
q20547 | Turn.PrettyReporter.finish_suite | train | def finish_suite(suite)
total = colorize_count("%d tests", suite.count_tests, :bold)
passes = colorize_count("%d passed", suite.count_passes, :pass)
assertions = colorize_count("%d assertions", suite.count_assertions, nil)
failures = colorize_count("%d failures", suite.count_failures, :fail)
errors = colorize_count("%d errors", suite.count_errors, :error)
skips = colorize_count("%d skips", suite.count_skips, :skip)
io.puts "Finished in %.6f seconds." % (Time.now - @time)
io.puts
io.puts [ total, passes, failures, errors, skips, assertions ].join(", ")
# Please keep this newline, since it will be useful when after test case
# there will be other lines. For example "rake aborted!" or kind of.
io.puts
end | ruby | {
"resource": ""
} |
q20548 | Turn.PrettyReporter.colorize_count | train | def colorize_count(str, count, colorize_method)
str= str % [count]
str= Colorize.send(colorize_method, str) if colorize_method and count != 0
str
end | ruby | {
"resource": ""
} |
q20549 | Turn.PrettyReporter.prettify | train | def prettify(raised, message=nil)
# Get message from raised, if not given
message ||= raised.message
backtrace = raised.respond_to?(:backtrace) ? raised.backtrace : raised.location
# Filter and clean backtrace
backtrace = clean_backtrace(backtrace)
# Add trace mark to first line.
backtrace.first.insert(0, TRACE_MARK)
io.puts Colorize.bold(message.tabto(TAB_SIZE))
io.puts backtrace.shift.tabto(TAB_SIZE - TRACE_MARK.length)
io.puts backtrace.join("\n").tabto(TAB_SIZE)
io.puts
end | ruby | {
"resource": ""
} |
q20550 | Turn.Command.main | train | def main(*argv)
option_parser.parse!(argv)
@loadpath = ['lib'] if loadpath.empty?
tests = ARGV.empty? ? nil : argv.dup
#config = Turn::Configuration.new do |c|
config = Turn.config do |c|
c.live = live
c.log = log
c.loadpath = loadpath
c.requires = requires
c.tests = tests
c.runmode = runmode
c.format = outmode
c.mode = decmode
c.pattern = pattern
c.matchcase = matchcase
c.trace = trace
c.natural = natural
c.verbose = verbose
c.mark = mark
c.ansi = ansi unless ansi.nil?
end
controller = Turn::Controller.new(config)
#result = controller.start
#if result
# exit(result.passed? ? 0 : -1)
#else # no tests
# exit(-1)
#end
controller.start
#exit(success ? 0 : -1)
end | ruby | {
"resource": ""
} |
q20551 | Turn.Configuration.files | train | def files
@files ||= (
fs = tests.map do |t|
File.directory?(t) ? Dir[File.join(t, '**', '*')] : Dir[t]
end
fs = fs.flatten.reject{ |f| File.directory?(f) }
ex = exclude.map do |x|
File.directory?(x) ? Dir[File.join(x, '**', '*')] : Dir[x]
end
ex = ex.flatten.reject{ |f| File.directory?(f) }
(fs - ex).uniq.map{ |f| File.expand_path(f) }
).flatten
end | ruby | {
"resource": ""
} |
q20552 | Turn.Configuration.reporter_class | train | def reporter_class
rpt_format = format || :pretty
class_name = rpt_format.to_s.capitalize + "Reporter"
path = "turn/reporters/#{rpt_format}_reporter"
[File.expand_path('~'), Dir.pwd].each do |dir|
file = File.join(dir, ".turn", "reporters", "#{rpt_format}_reporter.rb")
path = file if File.exist?(file)
end
require path
Turn.const_get(class_name)
end | ruby | {
"resource": ""
} |
q20553 | Turn.MiniRunner.start | train | def start(args=[])
# minitest changed #run in 6023c879cf3d5169953e on April 6th, 2011
if ::MiniTest::Unit.respond_to?(:runner=)
::MiniTest::Unit.runner = self
end
# FIXME: why isn't @test_count set?
run(args)
return @turn_suite
end | ruby | {
"resource": ""
} |
q20554 | Poncho.Request.action_dispatch_params | train | def action_dispatch_params
action_dispatch_params = env['action_dispatch.request.path_parameters'] || {}
action_dispatch_params.inject({}) {|hash, (key, value)| hash[key.to_s] = value; hash }
end | ruby | {
"resource": ""
} |
q20555 | ForemanChef.ChefServerImporter.changes | train | def changes
changes = {'new' => {}, 'obsolete' => {}, 'updated' => {}}
if @environment.nil?
new_environments.each do |env|
changes['new'][env] = {}
end
old_environments.each do |env|
changes['obsolete'][env] = {}
end
else
env = @environment
changes['new'][env] = {} if new_environments.include?(@environment)
changes['obsolete'][env] = {} if old_environments.include?(@environment)
end
changes
end | ruby | {
"resource": ""
} |
q20556 | Poncho.Errors.as_json | train | def as_json(options=nil)
return {} if messages.empty?
attribute, types = messages.first
type = types.first
{
:error => {
:param => attribute,
:type => type,
:message => nil
}
}
end | ruby | {
"resource": ""
} |
q20557 | ForemanChef.FactParser.set_additional_attributes | train | def set_additional_attributes(attributes, name)
if name =~ VIRTUAL_NAMES
attributes[:virtual] = true
if $1.nil? && name =~ BRIDGES
attributes[:bridge] = true
else
attributes[:attached_to] = $1
end
else
attributes[:virtual] = false
end
attributes
end | ruby | {
"resource": ""
} |
q20558 | Poncho.Resource.param_for_validation? | train | def param_for_validation?(name)
if respond_to?(name)
!send(name).nil?
else
!param_before_type_cast(name).nil?
end
end | ruby | {
"resource": ""
} |
q20559 | Integral.Post.set_tags_context | train | def set_tags_context
return unless tag_list_changed? || status_changed? || !persisted?
# Give all tags current context
set_tag_list_on(tag_context, tag_list)
# Clear previous contexts
self.tag_list = []
inactive_tag_contexts.each do |context|
set_tag_list_on(context, [])
end
end | ruby | {
"resource": ""
} |
q20560 | Integral.User.role? | train | def role?(role_sym)
role_sym = [role_sym] unless role_sym.is_a?(Array)
roles.map { |r| r.name.underscore.to_sym }.any? { |user_role| role_sym.include?(user_role) }
end | ruby | {
"resource": ""
} |
q20561 | Integral.ListRenderer.render | train | def render
rendered_items = ''
list.list_items.each do |list_item|
rendered_items += render_item(list_item)
end
content_tag opts[:wrapper_element], rendered_items, html_options, false
end | ruby | {
"resource": ""
} |
q20562 | Features.Helpers.sign_in | train | def sign_in(user=create(:user))
visit new_user_session_path
within("#new_user") do
fill_in 'user_email', with: user.email
fill_in 'user_password', with: user.password
end
click_button 'Log in'
end | ruby | {
"resource": ""
} |
q20563 | Integral.PostsController.find_related_posts | train | def find_related_posts
@related_posts = @post.find_related_tags.limit(amount_of_related_posts_to_display)
amount_of_related_posts = @related_posts.length
if amount_of_related_posts != amount_of_related_posts_to_display && (amount_of_related_posts + @popular_posts.length) >= amount_of_related_posts_to_display
@related_posts = @related_posts.to_a.concat(@popular_posts[0...amount_of_related_posts_to_display - amount_of_related_posts])
end
end | ruby | {
"resource": ""
} |
q20564 | Integral.ImageUploader.full_filename | train | def full_filename(for_file)
parent_name = super(for_file)
extension = File.extname(parent_name)
base_name = parent_name.chomp(extension)
base_name = base_name[version_name.size.succ..-1] if version_name
[base_name, version_name].compact.join('-') + extension
end | ruby | {
"resource": ""
} |
q20565 | Integral.ImageUploader.full_original_filename | train | def full_original_filename
parent_name = super
extension = File.extname(parent_name)
base_name = parent_name.chomp(extension)
base_name = base_name[version_name.size.succ..-1] if version_name
[base_name, version_name].compact.join('-') + extension
end | ruby | {
"resource": ""
} |
q20566 | Integral.GalleryHelper.render_thumb_gallery | train | def render_thumb_gallery(list, opts = {})
opts.reverse_merge!(
renderer: Integral::SwiperListRenderer,
item_renderer: Integral::PartialListItemRenderer,
item_renderer_opts: {
partial_path: 'integral/shared/gallery/thumb_slide',
wrapper_element: 'div',
image_version: :small,
html_classes: 'swiper-slide'
}
)
opts[:renderer].render(list, opts).html_safe
end | ruby | {
"resource": ""
} |
q20567 | Integral.Enquiry.process | train | def process
ContactMailer.forward_enquiry(self).deliver_later
ContactMailer.auto_reply(self).deliver_later
NewsletterSignup.create(name: name, email: email, context: context) if newsletter_opt_in?
end | ruby | {
"resource": ""
} |
q20568 | Integral.ListItemRenderer.render_children | train | def render_children
children = ''
list_item.children.each do |child|
children += self.class.render(child, opts)
end
children
end | ruby | {
"resource": ""
} |
q20569 | Integral.ListItemRenderer.provide_attr | train | def provide_attr(attr)
list_item_attr_value = list_item.public_send(attr)
# Provide user supplied attr
return list_item_attr_value if list_item_attr_value.present?
# Provide object supplied attr
return object_data[attr] if object_available?
# Provide error - Object is linked but has been deleted
return 'Object Unavailable' if list_item.object? && !object_available?
# Provide empty string - no attr supplied and no object linked
''
end | ruby | {
"resource": ""
} |
q20570 | Integral.PostDecorator.header_tags | train | def header_tags
return I18n.t('integral.posts.show.subtitle') if object.tags_on('published').empty?
header_tags = ''
object.tags_on('published').each_with_index do |tag, i|
header_tags += tag.name
header_tags += ' | ' unless i == object.tags_on('published').size - 1
end
header_tags
end | ruby | {
"resource": ""
} |
q20571 | Integral.PostDecorator.preview_image | train | def preview_image(size = :small)
preview_image = object&.preview_image&.url(size)
return preview_image if preview_image.present?
image(size, false)
end | ruby | {
"resource": ""
} |
q20572 | Integral.PostDecorator.image | train | def image(size = :small, fallback = true)
image = object&.image&.url(size)
return image if image.present?
h.image_url('integral/defaults/no_image_available.jpg') if fallback
end | ruby | {
"resource": ""
} |
q20573 | Integral.SupportHelper.anchor_to | train | def anchor_to(body, location)
current_path = url_for(only_path: false)
path = "#{current_path}##{location}"
link_to body, path
end | ruby | {
"resource": ""
} |
q20574 | Integral.SupportHelper.method_missing | train | def method_missing(method, *args, &block)
if method.to_s.end_with?('_path', '_url')
if main_app.respond_to?(method)
main_app.send(method, *args)
else
super
end
else
super
end
end | ruby | {
"resource": ""
} |
q20575 | Integral.NewsletterSignupJob.perform | train | def perform(signup)
return unless NewsletterSignup.api_available?
gibbon = Gibbon::Request.new(api_key: Settings.newsletter_api_key)
request_body = { email_address: signup.email, status: 'subscribed' }
gibbon.lists(newsletter_list_id(signup)).members.create(body: request_body)
# Update signup when the response is successful (in this case - if no error returned)
signup.update_attribute(:processed, true)
end | ruby | {
"resource": ""
} |
q20576 | Integral.ContactMailer.forward_enquiry | train | def forward_enquiry(enquiry)
@enquiry = enquiry
sender = email_sender(enquiry.name, enquiry.email)
mail subject: forwarding_subject(enquiry), from: sender, to: incoming_email_address, reply_to: sender
end | ruby | {
"resource": ""
} |
q20577 | Integral.ContactMailer.auto_reply | train | def auto_reply(enquiry)
@enquiry = enquiry
sender = email_sender(Integral::Settings.website_title, outgoing_email_address)
mail subject: auto_reply_subject(enquiry), to: enquiry.email, from: sender, reply_to: sender
end | ruby | {
"resource": ""
} |
q20578 | TheComments.Controller.create | train | def create
@comment = @commentable.comments.new comment_params
if @comment.valid?
@comment.save
return render layout: false, partial: comment_partial(:comment), locals: { tree: @comment }
end
render json: { errors: @comment.errors }
end | ruby | {
"resource": ""
} |
q20579 | TheComments.User.recalculate_my_comments_counter! | train | def recalculate_my_comments_counter!
dcount = my_draft_comments.count
pcount = my_published_comments.count
update_attributes!({
my_draft_comments_count: dcount,
my_published_comments_count: pcount,
my_comments_count: dcount + pcount
})
end | ruby | {
"resource": ""
} |
q20580 | AttrDefault.ClassMethods.field_added | train | def field_added(name, type, args, options)
if (default = options[:ruby_default])
attr_default name, default
elsif (default = options[:default]) && default.is_a?(Proc)
ActiveSupport::Deprecation.warn(':default => Proc has been deprecated. Use :ruby_default.', caller)
attr_default name, default
options.delete(:default)
options[:ruby_default] = default
end
end | ruby | {
"resource": ""
} |
q20581 | Zip.InputStream.get_io | train | def get_io(io, offset=0)
io = ::File.open(io, "rb") unless io.is_a?(IO) || io.is_a?(StringIO)
io.seek(offset, ::IO::SEEK_SET)
io
end | ruby | {
"resource": ""
} |
q20582 | Promisepay.DirectDebitAuthorityResource.find_all | train | def find_all(account_id, options = {})
response = JSON.parse(@client.get('direct_debit_authorities', { account_id: account_id }.merge(options)).body)
direct_debit_authorities = response.key?('direct_debit_authorities') ? response['direct_debit_authorities'] : []
direct_debit_authorities.map { |attributes| Promisepay::DirectDebitAuthority.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
q20583 | Promisepay.BankAccountResource.validate | train | def validate(routing_number)
response = @client.get('tools/routing_number', { routing_number: routing_number }, true)
(response.status == 200) ? JSON.parse(response.body)['routing_number'] : {}
end | ruby | {
"resource": ""
} |
q20584 | Promisepay.CompanyResource.find_all | train | def find_all(options = {})
response = JSON.parse(@client.get('companies', options).body)
users = response.key?('companies') ? response['companies'] : []
users.map { |attributes| Promisepay::Company.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
q20585 | Promisepay.CompanyResource.update | train | def update(attributes)
response = JSON.parse(@client.patch("companies/#{attributes[:id]}", attributes).body)
Promisepay::Company.new(@client, response['companies'])
end | ruby | {
"resource": ""
} |
q20586 | Promisepay.Client.method_missing | train | def method_missing(name, *args, &block)
if self.class.resources.keys.include?(name)
resources[name] ||= self.class.resources[name].new(self)
resources[name]
else
super
end
end | ruby | {
"resource": ""
} |
q20587 | Promisepay.Item.buyer | train | def buyer
response = JSON.parse(@client.get("items/#{send(:id)}/buyers").body)
Promisepay::User.new(@client, response['users'])
end | ruby | {
"resource": ""
} |
q20588 | Promisepay.Item.fees | train | def fees(options = {})
response = JSON.parse(@client.get("items/#{send(:id)}/fees", options).body)
fees = response.key?('fees') ? response['fees'] : []
fees.map { |attributes| Promisepay::Fee.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
q20589 | Promisepay.Item.transactions | train | def transactions(options = {})
response = JSON.parse(@client.get("items/#{send(:id)}/transactions", options).body)
transactions = response.key?('transactions') ? response['transactions'] : []
transactions.map { |attributes| Promisepay::Transaction.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
q20590 | Promisepay.Item.batch_transactions | train | def batch_transactions(options = {})
response = JSON.parse(@client.get("items/#{send(:id)}/batch_transactions", options).body)
batch_transactions = response.key?('batch_transactions') ? response['batch_transactions'] : []
batch_transactions.map { |attributes| Promisepay::BatchTransaction.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
q20591 | Promisepay.Item.make_payment | train | def make_payment(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/make_payment", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20592 | Promisepay.Item.request_payment | train | def request_payment(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/request_payment", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20593 | Promisepay.Item.release_payment | train | def release_payment(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/release_payment", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20594 | Promisepay.Item.request_release | train | def request_release(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/request_release", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20595 | Promisepay.Item.acknowledge_wire | train | def acknowledge_wire(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/acknowledge_wire", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20596 | Promisepay.Item.revert_wire | train | def revert_wire(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/revert_wire", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20597 | Promisepay.Item.request_refund | train | def request_refund(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/request_refund", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20598 | Promisepay.Item.raise_dispute | train | def raise_dispute(options = {})
response = JSON.parse(@client.patch("items/#{send(:id)}/raise_dispute", options).body)
@attributes = response['items']
true
end | ruby | {
"resource": ""
} |
q20599 | Promisepay.ItemResource.find_all | train | def find_all(options = {})
response = JSON.parse(@client.get('items', options).body)
items = response.key?('items') ? response['items'] : []
items.map { |attributes| Promisepay::Item.new(@client, attributes) }
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.