_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q23700
RightScraper::Retrievers.CheckoutBase.retrieve
train
def retrieve raise RetrieverError.new("retriever is unavailable") unless available? updated = false explanation = '' if exists? @logger.operation(:updating) do # a retriever may be able to determine that the repo directory is # already pointing to the same commit as the revision. in that case # we can return quickly. if remote_differs? # there is no point in updating and failing the size check when the # directory on disk already exceeds size limit; fall back to a clean # checkout in hopes that the latest revision corrects the issue. if size_limit_exceeded? explanation = 'switching to checkout due to existing directory exceeding size limimt' else # attempt update. begin do_update updated = true rescue ::RightScraper::Processes::Shell::LimitError # update exceeded a limitation; requires user intervention raise rescue Exception => e # retry with clean checkout after discarding repo dir. explanation = 'switching to checkout after unsuccessful update' end end else # no retrieval needed but warn exactly why we didn't do full # checkout to avoid being challenged about it. repo_ref = @repository.tag do_update_tag full_head_ref = @repository.tag abbreviated_head_ref = full_head_ref[0..6] if repo_ref == full_head_ref || repo_ref == abbreviated_head_ref detail = abbreviated_head_ref else detail = "#{repo_ref} = #{abbreviated_head_ref}" end message = "Skipped updating local directory due to the HEAD commit SHA " + "on local matching the remote repository reference (#{detail})." @logger.note_warning(message) return false end end end # Clean checkout only if not updated. unless updated @logger.operation(:checkout, explanation) do # remove any full or partial directory before attempting a clean # checkout in case repo_dir is in a bad state. if exists? ::FileUtils.remove_entry_secure(@repo_dir) end ::FileUtils.mkdir_p(@repo_dir) begin do_checkout rescue Exception # clean checkout failed; repo directory is in an undetermined # state and must be deleted to prevent a future update attempt. if exists? ::FileUtils.remove_entry_secure(@repo_dir) rescue nil end raise end end end true end
ruby
{ "resource": "" }
q23701
RightScraper::Retrievers.CheckoutBase.size_limit_exceeded?
train
def size_limit_exceeded? if @max_bytes # note that Dir.glob ignores hidden directories (e.g. ".git") so the # size total correctly excludes those hidden contents that are not to # be uploaded after scrape. this may cause the on-disk directory size # to far exceed the upload size. globbie = ::File.join(@repo_dir, '**/*') size = 0 ::Dir.glob(globbie) do |f| size += ::File.stat(f).size rescue 0 if ::File.file?(f) break if size > @max_bytes end size > @max_bytes else false end end
ruby
{ "resource": "" }
q23702
RightScraper::Resources.Cookbook.to_hash
train
def to_hash { repository: repository, resource_hash: resource_hash, # location of cookbook manifest in S3 metadata: ::JSON.dump(metadata), # pass as opaque JSON blob pos: pos } end
ruby
{ "resource": "" }
q23703
RightGit::Git.BranchCollection.current
train
def current lines = @repo.git_output(['symbolic-ref', 'HEAD'], :raise_on_failure => false).lines if lines.size == 1 line = lines.first.strip if (match = HEAD_REF.match(line)) @branches.detect { |b| b.fullname == match[1] } elsif line == NO_HEAD_REF nil end else raise GitError, "Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}" end end
ruby
{ "resource": "" }
q23704
RightGit::Git.BranchCollection.merged
train
def merged(revision) # By hand, build a list of all branches known to be merged into master git_args = ['branch', '-a', '--merged', revision] all_merged = [] @repo.git_output(git_args).lines.each do |line| line.strip! all_merged << Branch.new(@repo, line) end # Filter the contents of this collection according to the big list merged = [] @branches.each do |candidate| # For some reason Set#include? does not play nice with our overridden comparison operators # for branches, so we need to do this the hard way :( merged << candidate if all_merged.detect { |b| candidate == b } end BranchCollection.new(@repo, merged) end
ruby
{ "resource": "" }
q23705
RightGit::Git.BranchCollection.[]
train
def [](argument) case argument when String target = Branch.new(@repo, argument) @branches.detect { |b| b == target } else @branches.__send__(:[], argument) end end
ruby
{ "resource": "" }
q23706
RightGit::Git.BranchCollection.method_missing
train
def method_missing(meth, *args, &block) result = @branches.__send__(meth, *args, &block) if result.is_a?(::Array) BranchCollection.new(@repo, result) else result end end
ruby
{ "resource": "" }
q23707
RightScraper::Scanners.CookbookS3Upload.notice
train
def notice(relative_position) contents = yield name = Digest::MD5.hexdigest(contents) path = File.join('Files', name) unless @bucket.key(path).exists? @bucket.put(path, contents) end end
ruby
{ "resource": "" }
q23708
Vic.Color.to_gui
train
def to_gui return to_standard_hex if hexadecimal? return Convert.xterm_to_hex(@value) if cterm? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to gui" end
ruby
{ "resource": "" }
q23709
Vic.Color.to_cterm
train
def to_cterm return @value if cterm? return Convert.hex_to_xterm(to_standard_hex) if hexadecimal? return :NONE if none? raise ColorError.new "can't convert \"#{ @value }\" to cterm" end
ruby
{ "resource": "" }
q23710
Vic.Color.to_standard_hex
train
def to_standard_hex color = @value.dup color.insert(0, '#') unless color.start_with? '#' # Convert shorthand hex to standard hex. if color.size == 4 color.slice!(1, 3).chars { |char| color << char * 2 } end color end
ruby
{ "resource": "" }
q23711
RightScraper::Retrievers.Svn.resolve_revision
train
def resolve_revision revision = @repository.tag.to_s.strip if revision.empty? revision = nil elsif (revision =~ SVN_REVISION_REGEX).nil? raise RetrieverError, "Revision reference contained illegal characters: #{revision.inspect}" end # timestamps can contain spaces; surround them with double quotes. revision = revision.inspect if revision.index(' ') revision end
ruby
{ "resource": "" }
q23712
BioTCM.Table.row_keys=
train
def row_keys=(val) raise ArgumentError, 'Illegal agrument type' unless val.is_a?(Array) raise ArgumentError, 'Unmatched size' if val.size < @row_keys.size @row_keys = val.map.with_index { |v, i| [v, i] }.to_h end
ruby
{ "resource": "" }
q23713
BioTCM.Table.ele
train
def ele(row, col, val = nil) if val.nil? get_ele(row, col) else set_ele(row, col, val) end end
ruby
{ "resource": "" }
q23714
BioTCM.Table.get_ele
train
def get_ele(row, col) row = @row_keys[row] col = @col_keys[col] row && col ? @content[row][col] : nil end
ruby
{ "resource": "" }
q23715
BioTCM.Table.set_ele
train
def set_ele(row, col, val) unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s) raise ArgumentError, 'Illegal argument type' end set_row(row, [''] * @col_keys.size) unless @row_keys[row] set_col(col, [''] * @row_keys.size) unless @col_keys[col] row = @row_keys[row] col = @col_keys[col] @content[row][col] = val.to_s self end
ruby
{ "resource": "" }
q23716
BioTCM.Table.row
train
def row(row, val = nil) if val.nil? get_row(row) else set_row(row, val) end end
ruby
{ "resource": "" }
q23717
BioTCM.Table.get_row
train
def get_row(row) row = @row_keys[row] row.nil? ? nil : @col_keys.map { |c, ci| [c, @content[row][ci]] }.to_h end
ruby
{ "resource": "" }
q23718
BioTCM.Table.set_row
train
def set_row(row, val) # Setter if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != col_keys.size raise ArgumentError, 'Column size not match' end case val when Array if @row_keys[row] row = @row_keys[row] @content[row] = val else @row_keys[row] = @row_keys.size @content << val end when Hash unless @row_keys[row] @row_keys[row] = @row_keys.size @content << ([''] * @col_keys.size) end row = @row_keys[row] val.each do |k, v| col = @col_keys[k] @content[row][col] = v if col end end self end
ruby
{ "resource": "" }
q23719
BioTCM.Table.col
train
def col(col, val = nil) if val.nil? get_col(col) else set_col(col, val) end end
ruby
{ "resource": "" }
q23720
BioTCM.Table.get_col
train
def get_col(col) col = @col_keys[col] col.nil? ? nil : @row_keys.map { |r, ri| [r, @content[ri][col]] }.to_h end
ruby
{ "resource": "" }
q23721
BioTCM.Table.set_col
train
def set_col(col, val) if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array)) raise ArgumentError, 'Illegal argument type' elsif val.is_a?(Array) && val.size != row_keys.size raise ArgumentError, 'Row size not match' end case val when Array if @col_keys[col] col = @col_keys[col] val.each_with_index { |v, row| @content[row][col] = v } else col = @col_keys[col] = @col_keys.size val.each_with_index { |v, row| @content[row] << v } end when Hash unless @col_keys[col] @col_keys[col] = @col_keys.size @content.each { |arr| arr << '' } end col = @col_keys[col] val.each do |k, v| row = @row_keys[k] @content[row][col] = v if row end end self end
ruby
{ "resource": "" }
q23722
BioTCM.Table.each_row
train
def each_row if block_given? @row_keys.each_key { |r| yield(r, row(r)) } self else Enumerator.new do |y| @row_keys.each_key { |r| y << [r, row(r)] } end end end
ruby
{ "resource": "" }
q23723
BioTCM.Table.each_col
train
def each_col if block_given? @col_keys.each_key { |c| yield(c, col(c)) } self else Enumerator.new do |y| @col_keys.each_key { |c| y << [c, col(c)] } end end end
ruby
{ "resource": "" }
q23724
BioTCM::Databases::HGNC.Rescuer.rescue_symbol
train
def rescue_symbol(symbol, method = @rescue_method, rehearsal = false) return @rescue_history[symbol] if @rescue_history[symbol] case method when :auto auto_rescue = '' if @symbol2hgncid[symbol.upcase] auto_rescue = symbol.upcase elsif @symbol2hgncid[symbol.downcase] auto_rescue = symbol.downcase elsif @symbol2hgncid[symbol.delete('-')] auto_rescue = symbol.delete('-') elsif @symbol2hgncid[symbol.upcase.delete('-')] auto_rescue = symbol.upcase.delete('-') elsif @symbol2hgncid[symbol.downcase.delete('-')] auto_rescue = symbol.downcase.delete('-') # Add more rules here end # Record unless rehearsal BioTCM.logger.warn('HGNC') { "Unrecognized symbol \"#{symbol}\", \"#{auto_rescue}\" used instead" } @rescue_history[symbol] = auto_rescue end return auto_rescue when :manual # Try automatic rescue first if (auto_rescue = rescue_symbol(symbol, :auto, true)) != '' print "\"#{symbol}\" unrecognized. Use \"#{auto_rescue}\" instead? [Yn] " unless gets.chomp == 'n' @rescue_history[symbol] = auto_rescue unless rehearsal # rubocop:disable Metrics/BlockNesting return auto_rescue end end # Manually rescue loop do print "Please correct \"#{symbol}\" or press enter directly to return empty String instead:\n" unless (manual_rescue = gets.chomp) == '' || @symbol2hgncid[manual_rescue] puts "Failed to recognize \"#{manual_rescue}\"" next end unless rehearsal @rescue_history[symbol] = manual_rescue File.open(@rescue_history_filepath, 'a').print(symbol, "\t", manual_rescue, "\n") end return manual_rescue end end end
ruby
{ "resource": "" }
q23725
SeedFu.Seeder.seed_with_undo
train
def seed_with_undo if r = SeedFuNdo.recorder r.record self # return existing records in case they are processed by the caller @data.map { |record_data| find_record(record_data) } else seed_without_undo end end
ruby
{ "resource": "" }
q23726
Quantify.Dimensions.units
train
def units(by=nil) Unit.units.values.select { |unit| unit.dimensions == self }.map(&by).to_a end
ruby
{ "resource": "" }
q23727
Quantify.Dimensions.si_unit
train
def si_unit return Unit.steridian if describe == 'solid angle' return Unit.radian if describe == 'plane angle' val = si_base_units return nil unless val return val[0] if val.length == 1 val = val.inject(Unit.unity) do |compound,unit| compound * unit end val = val.or_equivalent unless val.acts_as_equivalent_unit end
ruby
{ "resource": "" }
q23728
Quantify.Dimensions.si_base_units
train
def si_base_units(by=nil) val = self.to_hash.map do |dimension, index| dimension_name = dimension.remove_underscores Unit.base_quantity_si_units.select do |unit| unit.measures == dimension_name end.first.clone ** index end val = val.map(&by) if by val.to_a end
ruby
{ "resource": "" }
q23729
Quantify.Dimensions.init_base_quantities
train
def init_base_quantities(options = { }) if options.has_key?(:physical_quantity) pq = options.delete(:physical_quantity) self.physical_quantity = pq.remove_underscores.downcase if pq end options.each_pair do |base_quantity, index| base_quantity = base_quantity.to_s.downcase.to_sym unless index.is_a?(Integer) && BASE_QUANTITIES.include?(base_quantity) raise Exceptions::InvalidDimensionError, "An invalid base quantity was specified (#{base_quantity})" end if @base_quantity_hash.has_key?(base_quantity) new_index = @base_quantity_hash[base_quantity] + index if new_index == 0 @base_quantity_hash.delete(base_quantity) else @base_quantity_hash[base_quantity] = new_index end else @base_quantity_hash[base_quantity] = index end end end
ruby
{ "resource": "" }
q23730
Quantify.Quantity.to_s
train
def to_s format=:symbol if format == :name unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name else unit_string = @unit.send format end string = "#{@value}" string += " #{unit_string}" unless unit_string.empty? string end
ruby
{ "resource": "" }
q23731
Quantify.Quantity.to_si
train
def to_si if @unit.is_compound_unit? Quantity.new(@value,@unit).convert_compound_unit_to_si! elsif @unit.is_dimensionless? return self.clone elsif @value.nil? return Quantity.new(nil, @unit.si_unit) else self.to(@unit.si_unit) end end
ruby
{ "resource": "" }
q23732
Vic.ColorScheme.highlight!
train
def highlight!(group, attributes={}) highlight(group, attributes.dup.tap { |hash| hash[:force] = true }) end
ruby
{ "resource": "" }
q23733
Vic.ColorScheme.link
train
def link(*from_groups, to_group) from_groups.flatten.map do |from_group| # Don't add anything we don't already have. next if find_link(from_group, to_group) link = Link.new(from_group, to_group) link.tap { |l| @links << l } end.compact end
ruby
{ "resource": "" }
q23734
Vic.ColorScheme.link!
train
def link!(*from_groups, to_group) # Use the default method first. self.link(from_groups, to_group) # Then update the links. from_groups.flatten.map do |from_group| link = find_link(from_group, to_group) link.tap(&:force!) end end
ruby
{ "resource": "" }
q23735
Vic.ColorScheme.language
train
def language(name = nil, &block) return @language unless name and block_given? previous_language = self.language @language = name block.arity == 0 ? instance_eval(&block) : yield(self) @language = previous_language end
ruby
{ "resource": "" }
q23736
RightScraper::Scanners.CookbookMetadataReadOnly.generated_metadata_json_readonly
train
def generated_metadata_json_readonly @logger.operation(:metadata_readonly) do # path constants freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos) freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA) # in the multi-pass case we will run this scanner only on the second # and any subsequent passed, which are outside of containment. the # metadata must have already been generated at this point or else it # should be considered an internal error. return ::File.read(freed_metadata_json_path) end end
ruby
{ "resource": "" }
q23737
BioTCM.Layer.save
train
def save(path, prefix = '') FileUtils.mkdir_p(path) @edge_tab.save(File.expand_path(prefix + 'edges.tab', path)) @node_tab.save(File.expand_path(prefix + 'nodes.tab', path)) end
ruby
{ "resource": "" }
q23738
RightScraper.Main.scrape
train
def scrape(repo, incremental=true, &callback) old_logger_callback = @logger.callback @logger.callback = callback errorlen = errors.size begin if retrieved = retrieve(repo) scan(retrieved) end rescue Exception # legacy logger handles communication with the end user and appending # to our error list; we just need to keep going. the new methodology # has no such guaranteed communication so the caller will decide how to # handle errors, etc. ensure @logger.callback = old_logger_callback cleanup end errors.size == errorlen end
ruby
{ "resource": "" }
q23739
RightScraper::Retrievers.Download.retrieve
train
def retrieve raise RetrieverError.new("download retriever is unavailable") unless available? ::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir) ::FileUtils.remove_entry_secure workdir if File.exists?(workdir) ::FileUtils.mkdir_p @repo_dir ::FileUtils.mkdir_p workdir file = ::File.join(workdir, "package") # TEAL FIX: we have to always-download the tarball before we can # determine if contents have changed, but afterward we can compare the # previous download against the latest downloaded and short-circuit the # remaining flow for the no-difference case. @logger.operation(:downloading) do credential_command = if @repository.first_credential && @repository.second_credential ['-u', "#{@repository.first_credential}:#{@repository.second_credential}"] else [] end @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = [ 'curl', '--silent', '--show-error', '--location', '--fail', '--location-trusted', '-o', file, credential_command, @repository.url ].flatten begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => workdir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, 'curl', e) raise end end note_tag(file) @logger.operation(:unpacking) do path = @repository.to_url.path if path =~ /\.gz$/ extraction = "xzf" elsif path =~ /\.bz2$/ extraction = "xjf" else extraction = "xf" end Dir.chdir(@repo_dir) do @output = ::RightScale::RightPopen::SafeOutputBuffer.new @cmd = ['tar', extraction, file] begin ::RightScale::RightPopen.popen3_sync( @cmd, :target => self, :pid_handler => :pid_download, :timeout_handler => :timeout_download, :size_limit_handler => :size_limit_download, :exit_handler => :exit_download, :stderr_handler => :output_download, :stdout_handler => :output_download, :inherit_io => true, # avoid killing any rails connection :watch_directory => @repo_dir, :size_limit_bytes => @max_bytes, :timeout_seconds => @max_seconds) rescue Exception => e @logger.note_phase(:abort, :running_command, @cmd.first, e) raise end end end true end
ruby
{ "resource": "" }
q23740
Cadmus.Renderable.setup_renderer
train
def setup_renderer(renderer) renderer.default_assigns = liquid_assigns if respond_to?(:liquid_assigns, true) renderer.default_registers = liquid_registers if respond_to?(:liquid_registers, true) renderer.default_filters = liquid_filters if respond_to?(:liquid_filters, true) end
ruby
{ "resource": "" }
q23741
Spectus.ExpectationTarget.MUST
train
def MUST(m) RequirementLevel::High.new(m, false, subject, *challenges).result end
ruby
{ "resource": "" }
q23742
Spectus.ExpectationTarget.MUST_NOT
train
def MUST_NOT(m) RequirementLevel::High.new(m, true, subject, *challenges).result end
ruby
{ "resource": "" }
q23743
Spectus.ExpectationTarget.SHOULD
train
def SHOULD(m) RequirementLevel::Medium.new(m, false, subject, *challenges).result end
ruby
{ "resource": "" }
q23744
Spectus.ExpectationTarget.SHOULD_NOT
train
def SHOULD_NOT(m) RequirementLevel::Medium.new(m, true, subject, *challenges).result end
ruby
{ "resource": "" }
q23745
RightScraper::Scrapers.Cookbook.find_next
train
def find_next(dir) @logger.operation(:finding_next_cookbook, "in #{dir.path}") do if COOKBOOK_SENTINELS.any? { |f| File.exists?(File.join(dir.path, f)) } @logger.operation(:reading_cookbook, "from #{dir.path}") do cookbook = RightScraper::Resources::Cookbook.new( @repository, strip_repo_dir(dir.path), repo_dir) @builder.go(dir.path, cookbook) cookbook end else @stack << dir search_dirs end end end
ruby
{ "resource": "" }
q23746
RightScraper::Scrapers.Base.search_dirs
train
def search_dirs @logger.operation(:searching) do until @stack.empty? dir = @stack.last entry = dir.read if entry == nil dir.close @stack.pop next end next if entry == '.' || entry == '..' next if ignorable?(entry) fullpath = File.join(dir.path, entry) if File.directory?(fullpath) result = find_next(Dir.new(fullpath)) break end end result end end
ruby
{ "resource": "" }
q23747
RightScraper::Scanners.Union.notice
train
def notice(relative_position) data = nil @subscanners.each {|scanner| scanner.notice(relative_position) { data = yield if data.nil? data } } end
ruby
{ "resource": "" }
q23748
RightScraper.SpecHelpers.create_file_layout
train
def create_file_layout(path, layout) FileUtils.mkdir_p(path) result = [] layout.each do |elem| if elem.is_a?(Hash) elem.each do |k, v| full_path = File.join(path, k) FileUtils.mkdir_p(full_path) result += create_file_layout(full_path, v) end elsif elem.is_a?(FileContent) fullpath = ::File.join(path, elem.name) File.open(fullpath, 'w') { |f| f.write elem.content } result << fullpath else fullpath = ::File.join(path, elem.to_s) File.open(fullpath, 'w') { |f| f.puts elem.to_s } result << fullpath end end result end
ruby
{ "resource": "" }
q23749
RightScraper.SpecHelpers.extract_file_layout
train
def extract_file_layout(path, ignore=[]) return [] unless File.directory?(path) dirs = [] files = [] ignore += [ '.', '..' ] Dir.foreach(path) do |f| next if ignore.include?(f) full_path = File.join(path, f) if File.directory?(full_path) dirs << { f => extract_file_layout(full_path, ignore) } else files << f end end dirs + files.sort end
ruby
{ "resource": "" }
q23750
RightScraper::Repositories.Base.equal_repo?
train
def equal_repo?(other) if other.is_a?(RightScraper::Repositories::Base) repository_hash == other.repository_hash else false end end
ruby
{ "resource": "" }
q23751
RightScraper::Repositories.Base.add_users_to
train
def add_users_to(uri, username=nil, password=nil) begin uri = URI.parse(uri) if uri.instance_of?(String) if username userinfo = URI.escape(username, USERPW) userinfo += ":" + URI.escape(password, USERPW) unless password.nil? uri.userinfo = userinfo end uri rescue URI::InvalidURIError if uri =~ PATTERN::GIT_URI user, host, path = $1, $2, $3 userinfo = URI.escape(user, USERPW) userinfo += ":" + URI.escape(username, USERPW) unless username.nil? path = "/" + path unless path.start_with?('/') URI::Generic::build({:scheme => "ssh", :userinfo => userinfo, :host => host, :path => path }) else raise end end end
ruby
{ "resource": "" }
q23752
Canis.KeyDispatcher.process_key
train
def process_key ch chr = nil if ch > 0 and ch < 256 chr = ch.chr end return :UNHANDLED unless @key_map @key_map.each_pair do |k,p| #$log.debug "KKK: processing key #{ch} #{chr} " if (k == ch || k == chr) #$log.debug "KKK: checking match == #{k}: #{ch} #{chr} " # compare both int key and chr #$log.debug "KKK: found match 1 #{ch} #{chr} " p.call(self, ch) return 0 elsif k.respond_to? :include? #$log.debug "KKK: checking match include #{k}: #{ch} #{chr} " # this bombs if its a String and we check for include of a ch. if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr)) #$log.debug "KKK: found match include #{ch} #{chr} " p.call(self, ch) return 0 end elsif k.is_a? Regexp if k.match(chr) #$log.debug "KKK: found match regex #{ch} #{chr} " p.call(self, ch) return 0 end end end return :UNHANDLED end
ruby
{ "resource": "" }
q23753
Canis.KeyDispatcher.default_string_key_map
train
def default_string_key_map require 'canis/core/include/action' @key_map ||= {} @key_map[ Regexp.new('[a-zA-Z0-9_\.\/]') ] = Action.new("Append to pattern") { |obj, ch| obj.buffer << ch.chr obj.buffer_changed } @key_map[ [127, ?\C-h.getbyte(0)] ] = Action.new("Delete Prev Char") { |obj, ch| # backspace buff = obj.buffer buff = buff[0..-2] unless buff == "" obj.set_buffer buff } end
ruby
{ "resource": "" }
q23754
Canis.CommandWindow.press
train
def press ch ch = ch.getbyte(0) if ch.class==String ## 1.9 $log.debug " XXX press #{ch} " if $log.debug? case ch when -1 return when KEY_F1, 27, ?\C-q.getbyte(0) @stop = true return when KEY_ENTER, 10, 13 #$log.debug "popup ENTER : #{@selected_index} " #$log.debug "popup ENTER : #{field.name}" if !field.nil? @stop = true return when ?\C-d.getbyte(0) @start += @height-1 bounds_check when KEY_UP @start -= 1 @start = 0 if @start < 0 when KEY_DOWN @start += 1 bounds_check when ?\C-b.getbyte(0) @start -= @height-1 @start = 0 if @start < 0 when 0 @start = 0 end Ncurses::Panel.update_panels(); Ncurses.doupdate(); @window.wrefresh end
ruby
{ "resource": "" }
q23755
Canis.CommandWindow.configure
train
def configure(*val , &block) case val.size when 1 return @config[val[0]] when 2 @config[val[0]] = val[1] instance_variable_set("@#{val[0]}", val[1]) end instance_eval &block if block_given? end
ruby
{ "resource": "" }
q23756
Canis.ControlPHandler.recursive_search
train
def recursive_search glob="**/*" @command = Proc.new {|str| Dir.glob(glob).select do |p| p.index str; end } end
ruby
{ "resource": "" }
q23757
Canis.ControlPHandler.data_changed
train
def data_changed list sz = list.size @source.text(list) wh = @source.form.window.height @source.form.window.hide th = @source.height sh = Ncurses.LINES-1 if sz < @maxht # rows is less than tp size so reduce tp and window @source.height = sz nl = _new_layout sz+1 $log.debug "XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) #Window.refresh_all else # expand the window ht to maxht tt = @maxht-1 @source.height = tt nl = _new_layout tt+1 $log.debug "XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}" @source.form.window.resize_with(nl) end @source.fire_dimension_changed @source.init_vars # do if rows is less than current_index. @source.set_form_row @source.form.window.show #Window.refresh_all @source.form.window.wrefresh Ncurses::Panel.update_panels(); Ncurses.doupdate(); end
ruby
{ "resource": "" }
q23758
Canis.ControlPHandler.buffer_changed
train
def buffer_changed # display the pattern on the header @header.text1(">>>#{@buffer}_") if @header @header.text_right(Dir.pwd) if @header @no_match = false if @command @list = @command.call(@buffer) else @list = @__list.select do |line| line.index @buffer end end sz = @list.size if sz == 0 Ncurses.beep #return 1 #this should make ENTER and arrow keys unusable except for BS or Esc, @list = ["No entries"] @no_match = true end data_changed @list 0 end
ruby
{ "resource": "" }
q23759
Canis.ControlPHandler.handle_key
train
def handle_key ch $log.debug " HANDLER GOT KEY #{ch} " @keyint = ch @keychr = nil # accumulate keys in a string # need to track insertion point if user uses left and right arrow @buffer ||= "" chr = nil chr = ch.chr if ch > 47 and ch < 127 @keychr = chr # Don't let user hit enter or keys if no match if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch if @no_match $log.warn "XXX: KEY GOT WAS #{ch}, #{chr} " # viewer has already blocked KEY_ENTER ! return 0 if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch else if [13,10, KEY_ENTER].include? ch @source.form.window.ungetch(1001) return 0 end end end ret = process_key ch # revert to the basic handling of key_map and refreshing pad. # but this will rerun the keys and may once again run a mapping. @source._handle_key(ch) if ret == :UNHANDLED end
ruby
{ "resource": "" }
q23760
Canis.ControlPHandler.default_key_map
train
def default_key_map tp = source source.bind_key(?\M-n.getbyte(0), 'goto_end'){ tp.goto_end } source.bind_key(?\M-p.getbyte(0), 'goto_start'){ tp.goto_start } end
ruby
{ "resource": "" }
q23761
Canis.ControlPHandler.directory_key_map
train
def directory_key_map @key_map["<"] = Action.new("Goto Parent Dir") { |obj| # go to parent dir $log.debug "KKK: called proc for <" Dir.chdir("..") obj.buffer_changed } @key_map[">"] = Action.new("Change Dir"){ |obj| $log.debug "KKK: called proc for > : #{obj.current_value} " # step into directory dir = obj.current_value if File.directory? dir Dir.chdir dir obj.buffer_changed end } end
ruby
{ "resource": "" }
q23762
Canis.BorderTitle.print_borders
train
def print_borders bordertitle_init unless @_bordertitle_init_called raise ArgumentError, "Graphic not set" unless @graphic raise "#{self} needs width" unless @width raise "#{self} needs height" unless @height width = @width height = @height-1 window = @graphic startcol = @col startrow = @row @color_pair = get_color($datacolor) bordercolor = @border_color || @color_pair borderatt = @border_attrib || Ncurses::A_NORMAL window.print_border startrow, startcol, height, width, bordercolor, borderatt print_title end
ruby
{ "resource": "" }
q23763
Canis.List.list
train
def list *val return @list if val.empty? alist = val[0] case alist when Array @list = alist # I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27 # Based no issue: https://github.com/mare-imbrium/canis/issues/15 @current_index = @toprow = @pcol = 0 when NilClass @list = [] # or nil ? @current_index = @toprow = @pcol = 0 when Variable @list = alist.value @current_index = @toprow = @pcol = 0 else raise ArgumentError, "Listbox list(): do not know how to handle #{alist.class} " end clear_selection @repaint_required = true @widget_scrolled = true # 2011-10-15 @list end
ruby
{ "resource": "" }
q23764
Canis.List.ask_search_backward
train
def ask_search_backward regex = get_string("Enter regex to search (backward)") @last_regex = regex ix = @list.find_prev regex, @current_index if ix.nil? alert("No matching data for: #{regex}") else set_focus_on(ix) end end
ruby
{ "resource": "" }
q23765
Canis.List.repaint
train
def repaint #:nodoc: return unless @repaint_required # # TRYING OUT dangerous 2011-10-15 @repaint_required = false @repaint_required = true if @widget_scrolled || @pcol != @old_pcol || @record_changed || @property_changed unless @repaint_required unhighlight_row @old_selected_index highlight_selected_row end return unless @repaint_required $log.debug "BASICLIST REPAINT WILL HAPPEN #{current_index} " # not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16 my_win = @form ? @form.window : @target_window @graphic = my_win unless @graphic raise " #{@name} neither form, nor target window given LB paint " unless my_win raise " #{@name} NO GRAPHIC set as yet LB paint " unless @graphic raise "width or height not given w:#{@width} , h:#{@height} " if @width.nil? || @height.nil? @win_left = my_win.left @win_top = my_win.top @left_margin ||= @row_selected_symbol.length # we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere _dl = [@display_length || 100, @width-@internal_width-@left_margin].min # 2011-09-17 RK overwriting when we move grabbar in vimsplit $log.debug "basiclistbox repaint #{@name} graphic #{@graphic}" #$log.debug "XXX repaint to_print #{@to_print_borders} " print_borders unless @suppress_borders # do this once only, unless everything changes #maxlen = @maxlen || @width-2 tm = list() rc = row_count @longest_line = @width $log.debug " rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} " if rc > 0 # just added in case no data passed tr = @toprow acolor = get_color $datacolor h = scrollatrow() r,c = rowcol 0.upto(h) do |hh| crow = tr+hh if crow < rc _focussed = @current_index == crow ? true : false # row focussed ? focus_type = _focussed focus_type = :SOFT_FOCUS if _focussed && !@focussed selected = is_row_selected crow content = tm[crow] # 2009-01-17 18:37 chomp giving error in some cases says frozen content = convert_value_to_text content, crow # 2010-09-23 20:12 # by now it has to be a String if content.is_a? String content = content.dup sanitize content if @sanitization_required truncate content if @truncation_required end ## set the selector symbol if requested selection_symbol = '' if @show_selector if selected selection_symbol = @row_selected_symbol else selection_symbol = @row_unselected_symbol end @graphic.printstring r+hh, c, selection_symbol, acolor,@attr end #renderer = get_default_cell_renderer_for_class content.class.to_s renderer = cell_renderer() renderer.display_length = _dl # 2011-09-17 RK overwriting when we move grabbar in vimsplit renderer.repaint @graphic, r+hh, c+@left_margin, crow, content, focus_type, selected else # clear rows @graphic.printstring r+hh, c, " " * (@width-@internal_width), acolor,@attr end end end # rc == 0 @repaint_required = false # 2011-10-13 @widget_scrolled = false @record_changed = false @property_changed = false @old_pcol = @pcol end
ruby
{ "resource": "" }
q23766
Canis.List.sanitize
train
def sanitize content #:nodoc: if content.is_a? String content.chomp! content.gsub!(/\t/, ' ') # don't display tab content.gsub!(/[^[:print:]]/, '') # don't display non print characters else content end end
ruby
{ "resource": "" }
q23767
Canis.List.init_actions
train
def init_actions am = action_manager() am.add_action(Action.new("&Disable selection") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } ) am.add_action(Action.new("&Edit Toggle") { @edit_toggle = !@edit_toggle; $status_message.value = "Edit toggle is #{@edit_toggle}" }) end
ruby
{ "resource": "" }
q23768
Canis.Box.repaint
train
def repaint return unless @repaint_required bc = $datacolor bordercolor = @border_color || bc borderatt = @border_attrib || Ncurses::A_NORMAL @window.print_border row, col, height, width, bordercolor, borderatt #print_borders print_title @repaint_required = false end
ruby
{ "resource": "" }
q23769
Canis.WidgetShortcuts.dock
train
def dock labels, config={}, &block require 'canis/core/widgets/keylabelprinter' klp = Canis::KeyLabelPrinter.new @form, labels, config, &block end
ruby
{ "resource": "" }
q23770
Canis.WidgetShortcuts.status_line
train
def status_line config={}, &block require 'canis/core/widgets/statusline' sl = Canis::StatusLine.new @form, config, &block end
ruby
{ "resource": "" }
q23771
Canis.WidgetShortcuts.table
train
def table config={}, &block #def tabular_widget config={}, &block require 'canis/core/widgets/table' events = [:PROPERTY_CHANGE, :LEAVE, :ENTER, :CHANGE, :ENTER_ROW, :PRESS ] block_event = nil # if no width given, expand to stack width #config.delete :title useform = nil w = Table.new useform, config # NO BLOCK GIVEN w.width ||= :expand w.height ||= :expand # TODO This has to come before other in stack next one will overwrite. _position(w) if block_given? #@current_object << w yield_or_eval &block #@current_object.pop end return w end
ruby
{ "resource": "" }
q23772
Canis.WidgetShortcuts._configure
train
def _configure s s[:row] ||= 0 s[:col] ||= 0 s[:row] += (s[:margin_top] || 0) s[:col] += (s[:margin_left] || 0) s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 last = @_ws_active.last if last if s[:width_pc] if last.is_a? WsStack s[:width] = (last[:width] * (s[:width_pc].to_i * 0.01)).floor else # i think this width is picked up by next stack in this flow last[:item_width] = (last[:width] * (s[:width_pc].to_i* 0.01)).floor end end if s[:height_pc] if last.is_a? WsFlow s[:height] = ( (last[:height] * s[:height_pc].to_i)/100).floor else # this works only for flows within stacks not for an object unless # you put a single object in a flow s[:item_height] = ( (last[:height] * s[:height_pc].to_i)/100).floor end #alert "item height set as #{s[:height]} for #{s} " end if last.is_a? WsStack s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) else s[:row] += (last[:row] || 0) s[:col] += (last[:col] || 0) # we are updating with item_width as each st finishes s[:width] ||= last[:item_width] # end else # this should be outer most flow or stack, if nothing mentioned # trying this out s[:width] ||= :expand s[:height] ||= :expand s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30 end s[:components] = [] end
ruby
{ "resource": "" }
q23773
KnifeCloudstack.CsServerCreate.is_ssh_open?
train
def is_ssh_open?(ip) s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) sa = Socket.sockaddr_in(locate_config_value(:ssh_port), ip) begin s.connect_nonblock(sa) rescue Errno::EINPROGRESS resp = IO.select(nil, [s], nil, 1) if resp.nil? sleep SSH_POLL_INTERVAL return false end begin s.connect_nonblock(sa) rescue Errno::EISCONN Chef::Log.debug("sshd accepting connections on #{ip}") yield return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH sleep SSH_POLL_INTERVAL return false end ensure s && s.close end end
ruby
{ "resource": "" }
q23774
Cream.UserControl.sign_in
train
def sign_in(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope expire_session_data_after_sign_in! warden.set_user(resource, options.merge!(:scope => scope)) # set user id post_signin resource, options end
ruby
{ "resource": "" }
q23775
Cream.UserControl.sign_out
train
def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) warden.user(scope) # Without loading user here, before_logout hook is not called warden.raw_session.inspect # Without this inspect here. The session does not clear. warden.logout(scope) # user id post_signout scope end
ruby
{ "resource": "" }
q23776
Canis.TextArea.insert
train
def insert off0, data _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen data = wrap_text data # $log.debug "after wrap text done :#{data}" data = data.split("\n") data[-1] << "\r" #XXXX data.each do |row| @list.insert off0, row off0 += 1 end else data << "\r" if data[-1,1] != "\r" #XXXX @list.insert off0, data end # expecting array !! #data.each do |row| #@list.insert off0, row #off0 += 1 #end #$log.debug " AFTER INSERT: #{@list}" end
ruby
{ "resource": "" }
q23777
Canis.TextArea.<<
train
def << data # if width if nil, either set it, or add this to a container that sets it before calling this method _maxlen = @maxlen || @width - @internal_width if data.length > _maxlen #$log.debug "wrapped append for #{data}" data = wrap_text data #$log.debug "after wrap text for :#{data}" data = data.split("\n") # 2009-01-01 22:24 the \n was needed so we would put a space at time of writing. # we need a soft return so a space can be added when pushing down. # commented off 2008-12-28 21:59 #data.each {|line| @list << line+"\n"} data.each {|line| @list << line} @list[-1] << "\r" #XXXX else #$log.debug "normal append for #{data}" data << "\r" if data[-1,1] != "\r" #XXXX @list << data end set_modified # added 2009-03-07 18:29 goto_end if @auto_scroll self end
ruby
{ "resource": "" }
q23778
Canis.TextArea.undo_delete
train
def undo_delete # added 2008-11-27 12:43 paste delete buffer into insertion point return if @delete_buffer.nil? $log.warn "undo_delete is broken! perhaps cannot be used . textarea 347 " # FIXME - can be an array case @delete_buffer when Array # we need to unroll array, and it could be lines not just a string str = @delete_buffer.first else str = @delete_buffer end @buffer.insert @curpos, str set_modified fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT, @current_index, @delete_buffer) # 2008-12-24 18:34 end
ruby
{ "resource": "" }
q23779
Canis.TextArea.insert_break
train
def insert_break return -1 unless @editable # insert a blank row and append rest of this line to cursor $log.debug "ENTER PRESSED at #{@curpos}, on row #{@current_index}" @delete_buffer = (delete_eol || "") @list[@current_index] << "\r" $log.debug "DELETE BUFFER #{@delete_buffer}" @list.insert @current_index+1, @delete_buffer @curpos = 0 down col = @orig_col + @col_offset setrowcol @row+1, col # FIXME maybe this should be insert line since line inserted, not just data, undo will delete it fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos+@delete_buffer.length, self, :INSERT_LINE, @current_index, @delete_buffer) # 2008-12-24 18:34 end
ruby
{ "resource": "" }
q23780
Canis.TextArea.set_form_col
train
def set_form_col col1=@curpos @curpos = col1 @cols_panned ||= 0 cursor_bounds_check ## added win_col on 2009-12-28 20:21 for embedded forms BUFFERED TRYING OUT win_col = 0 # 2010-02-07 23:19 new cursor stuff #col = win_col + @orig_col + @col_offset + @curpos #col = win_col + @orig_col + @col_offset + @curpos + @cols_panned # 2010-01-14 13:31 changed orig_col to col for embedded forms, splitpanes. col = win_col + @col + @col_offset + @curpos + @cols_panned $log.debug "sfc: wc:#{win_col} col:#{@col}, coff:#{@col_offset}. cp:#{@curpos} colsp:#{@cols_panned} . " #@form.setrowcol @form.row, col # added 2009-12-29 18:50 BUFFERED $log.debug " TA calling setformrow col nil, #{col} " setrowcol nil, col # added 2009-12-29 18:50 BUFFERED @repaint_footer_required = true end
ruby
{ "resource": "" }
q23781
Canis.TextArea.insert_wrap
train
def insert_wrap lineno, pos, lastchars _maxlen = @maxlen || @width - @internal_width @list[lineno].insert pos, lastchars len = @list[lineno].length if len > _maxlen push_last_word lineno #- sometime i may push down 10 chars but the last word is less end end
ruby
{ "resource": "" }
q23782
Canis.TextArea.putch
train
def putch char _maxlen = @maxlen || @width - @internal_width @buffer ||= @list[@current_index] return -1 if !@editable #or @buffer.length >= _maxlen #if @chars_allowed != nil # remove useless functionality #return if char.match(@chars_allowed).nil? #end raise "putch expects only one char" if char.length != 1 oldcurpos = @curpos #$log.debug "putch : pr:#{@current_index}, cp:#{@curpos}, char:#{char}, lc:#{@buffer[-1]}, buf:(#{@buffer})" if @overwrite_mode @buffer[@curpos] = char else @buffer.insert(@curpos, char) end @curpos += 1 #$log.debug "putch INS: cp:#{@curpos}, max:#{_maxlen}, buf:(#{@buffer.length})" if @curpos-1 > _maxlen or @buffer.length()-1 > _maxlen lastchars, lastspace = push_last_word @current_index #$log.debug "last sapce #{lastspace}, lastchars:#{lastchars},lc:#{lastchars[-1]}, #{@list[@current_index]} " ## wrap on word XX If last char is 10 then insert line @buffer = @list[@current_index] if @curpos-1 > _maxlen or @curpos-1 > @buffer.length()-1 ret = down # keep the cursor in the same position in the string that was pushed down. @curpos = oldcurpos - lastspace #lastchars.length # 0 end end set_form_row @buffer = @list[@current_index] set_form_col @modified = true fire_handler :CHANGE, InputDataEvent.new(oldcurpos,@curpos, self, :INSERT, @current_index, char) # 2008-12-24 18:34 @repaint_required = true 0 end
ruby
{ "resource": "" }
q23783
Canis.TextArea.remove_last_word
train
def remove_last_word lineno @list[lineno].chomp! line=@list[lineno] lastspace = line.rindex(" ") if !lastspace.nil? lastchars = line[lastspace+1..-1] @list[lineno].slice!(lastspace..-1) $log.debug " remove_last: lastspace #{lastspace},#{lastchars},#{@list[lineno]}" fire_handler :CHANGE, InputDataEvent.new(lastspace,lastchars.length, self, :DELETE, lineno, lastchars) # 2008-12-26 23:06 return lastchars end return nil end
ruby
{ "resource": "" }
q23784
Canis.TextArea.move_chars_up
train
def move_chars_up oldprow = @current_index oldcurpos = @curpos _maxlen = @maxlen || @width - @internal_width space_left = _maxlen - @buffer.length can_move = [space_left, next_line.length].min carry_up = @list[@current_index+1].slice!(0, can_move) @list[@current_index] << carry_up delete_line(@current_index+1) if next_line().length==0 fire_handler :CHANGE, InputDataEvent.new(oldcurpos,oldcurpos+can_move, self, :INSERT, oldprow, carry_up) # 2008-12-24 18:34 end
ruby
{ "resource": "" }
q23785
Canis.TextArea.get_text
train
def get_text l = getvalue str = "" old = " " l.each_with_index do |line, i| tmp = line.gsub("\n","") tmp.gsub!("\r", "\n") if old[-1,1] !~ /\s/ and tmp[0,1] !~ /\s/ str << " " end str << tmp old = tmp end str end
ruby
{ "resource": "" }
q23786
Canis.Tree.root
train
def root node=nil, asks_allow_children=false, &block if @treemodel return @treemodel.root unless node raise ArgumentError, "Root already set" end raise ArgumentError, "root: node cannot be nil" unless node @treemodel = Canis::DefaultTreeModel.new(node, asks_allow_children, &block) end
ruby
{ "resource": "" }
q23787
Canis.Tree.select_default_values
train
def select_default_values return if @default_value.nil? # NOTE list not yet created raise "list has not yet been created" unless @list index = node_to_row @default_value raise "could not find node #{@default_value}, #{@list} " unless index return unless index @current_index = index toggle_row_selection @default_value = nil end
ruby
{ "resource": "" }
q23788
Canis.Tree.node_to_row
train
def node_to_row node crow = nil @list.each_with_index { |e,i| if e == node crow = i break end } crow end
ruby
{ "resource": "" }
q23789
Canis.Tree.expand_parents
train
def expand_parents node _path = node.tree_path _path.each do |e| # if already expanded parent then break we should break #set_expanded_state(e, true) expand_node(e) end end
ruby
{ "resource": "" }
q23790
Canis.Tree.expand_children
train
def expand_children node=:current_index $multiplier = 999 if !$multiplier || $multiplier == 0 node = row_to_node if node == :current_index return if node.children.empty? # or node.is_leaf? #node.children.each do |e| #expand_node e # this will keep expanding parents #expand_children e #end node.breadth_each($multiplier) do |e| expand_node e end $multiplier = 0 _structure_changed true end
ruby
{ "resource": "" }
q23791
Canis.DefaultTableRowSorter.sort
train
def sort return unless @model return if @sort_keys.empty? $log.debug "TABULAR SORT KEYS #{sort_keys} " # first row is the header which should remain in place # We could have kept column headers separate, but then too much of mucking around # with textpad, this way we avoid touching it header = @model.delete_at 0 begin # next line often can give error "array within array" - i think on date fields that # contain nils @model.sort!{|x,y| res = 0 @sort_keys.each { |ee| e = ee.abs-1 # since we had offsetted by 1 earlier abse = e.abs if ee < 0 xx = x[abse] yy = y[abse] # the following checks are since nil values cause an error to be raised if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = 1 elsif yy.nil? res = -1 else res = y[abse] <=> x[abse] end else xx = x[e] yy = y[e] # the following checks are since nil values cause an error to be raised # whereas we want a nil to be wither treated as a zero or a blank if xx.nil? && yy.nil? res = 0 elsif xx.nil? res = -1 elsif yy.nil? res = 1 else res = x[e] <=> y[e] end end break if res != 0 } res } ensure @model.insert 0, header if header end end
ruby
{ "resource": "" }
q23792
Canis.DefaultTableRowSorter.toggle_sort_order
train
def toggle_sort_order index index += 1 # increase by 1, since 0 won't multiple by -1 # internally, reverse sort is maintained by multiplying number by -1 @sort_keys ||= [] if @sort_keys.first && index == @sort_keys.first.abs @sort_keys[0] *= -1 else @sort_keys.delete index # in case its already there @sort_keys.delete(index*-1) # in case its already there @sort_keys.unshift index # don't let it go on increasing if @sort_keys.size > 3 @sort_keys.pop end end end
ruby
{ "resource": "" }
q23793
Canis.DefaultTableRenderer.convert_value_to_text
train
def convert_value_to_text r str = [] fmt = nil field = nil # we need to loop through chash and get index from it and get that row from r each_column {|c,i| e = r[c.index] w = c.width l = e.to_s.length # if value is longer than width, then truncate it if l > w fmt = "%.#{w}s " else case c.align when :right fmt = "%#{w}s " else fmt = "%-#{w}s " end end field = fmt % e # if we really want to print a single column with color, we need to print here itself # each cell. If we want the user to use tmux formatting in the column itself ... # FIXME - this must not be done for headers. #if c.color #field = "#[fg=#{c.color}]#{field}#[/end]" #end str << field } return str end
ruby
{ "resource": "" }
q23794
Canis.DefaultTableRenderer.render_data
train
def render_data pad, lineno, text text = text.join # FIXME why repeatedly getting this colorpair cp = @color_pair att = @attrib # added for selection, but will crash if selection is not extended !!! XXX if @source.is_row_selected? lineno att = REVERSE # FIXME currentl this overflows into next row end FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att) FFI::NCurses.mvwaddstr(pad, lineno, 0, text) FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att) end
ruby
{ "resource": "" }
q23795
Canis.DefaultTableRenderer.check_colors
train
def check_colors each_column {|c,i| if c.color || c.bgcolor || c.attrib @_check_coloring = true return end @_check_coloring = false } end
ruby
{ "resource": "" }
q23796
Canis.Table.get_column
train
def get_column index return @chash[index] if @chash[index] # create a new entry since none present c = ColumnInfo.new c.index = index @chash[index] = c return c end
ruby
{ "resource": "" }
q23797
Canis.Table.content_cols
train
def content_cols total = 0 #@chash.each_pair { |i, c| #@chash.each_with_index { |c, i| #next if c.hidden each_column {|c,i| w = c.width # if you use prepare_format then use w+2 due to separator symbol total += w + 1 } return total end
ruby
{ "resource": "" }
q23798
Canis.Table.fire_column_event
train
def fire_column_event eve require 'canis/core/include/ractionevent' aev = TextActionEvent.new self, eve, get_column(@column_pointer.current_index), @column_pointer.current_index, @column_pointer.last_index fire_handler eve, aev end
ruby
{ "resource": "" }
q23799
Canis.Table._init_model
train
def _init_model array # clear the column data -- this line should be called otherwise previous tables stuff will remain. @chash.clear array.each_with_index { |e,i| # if columns added later we could be overwriting the width c = get_column(i) c.width ||= 10 } # maintains index in current pointer and gives next or prev @column_pointer = Circular.new array.size()-1 end
ruby
{ "resource": "" }