_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q23900
|
Canis.MultiBuffers.buffer_prev
|
train
|
def buffer_prev
buffer_update_info
if @_buffer_ctr < 1
buffer_last
return
end
@_buffer_ctr -= 1 if @_buffer_ctr > 0
x = @_buffer_ctr
l = @_buffers[x]
if l
populate_buffer_from_filename x
l = @_buffers[x]
$log.debug "bp calling set_content with #{l.class} "
set_content l, @_buffers_conf[x]
buffer_update_position
end
end
|
ruby
|
{
"resource": ""
}
|
q23901
|
Canis.MultiBuffers.buffer_menu
|
train
|
def buffer_menu
menu = PromptMenu.new self do
item :n, :buffer_next
item :p, :buffer_prev
item :b, :scroll_backward
item :f, :scroll_forward
item :l, :list_buffers
item :q, :close
submenu :m, "submenu..." do
item :p, :goto_last_position
item :r, :scroll_right
item :l, :scroll_left
end
end
menu.display_new :title => "Buffer Menu"
end
|
ruby
|
{
"resource": ""
}
|
q23902
|
Canis.MultiBuffers.list_buffers
|
train
|
def list_buffers
arr = []
@_buffers_conf.each_with_index do |e, i|
t = e[:title] || "no title for #{i}"
#$log.debug " TITLE is #{e.title} , t is #{t} "
arr << t
end
ix = popuplist arr
buffer_at ix
end
|
ruby
|
{
"resource": ""
}
|
q23903
|
Canis.TextView.row_length
|
train
|
def row_length
case @buffer
when String
@buffer.length
when Chunks::ChunkLine
return @buffer.length
when Array
# this is for those old cases like rfe.rb which sent in an array
# (before we moved to chunks)
# line is an array of arrays
if @buffer[0].is_a? Array
result = 0
@buffer.each {|e| result += e[1].length }
return result
end
# line is one single chunk
return @buffer[1].length
end
end
|
ruby
|
{
"resource": ""
}
|
q23904
|
Canis.TextView.getstr
|
train
|
def getstr prompt, maxlen=80 #:nodoc:
tabc = Proc.new {|str| Dir.glob(str +"*") }
config={}; config[:tab_completion] = tabc
config[:default] = "test"
config[:display_length] = 11
$log.debug " inside getstr before call "
ret, str = rbgetstr(@form.window, @row+@height-1, @col+1, prompt, maxlen, config)
$log.debug " rbgetstr returned #{ret} ,#{str}."
return "" if ret != 0
return str
end
|
ruby
|
{
"resource": ""
}
|
q23905
|
Canis.MessageBox.message
|
train
|
def message message # yield label or field being used for display for further customization
@suggested_h = @height || 10
message = message.gsub(/[\n\r\t]/,' ') rescue message
message_col = 5
@suggested_w = @width || [message.size + 8 + message_col , FFI::NCurses.COLS-2].min
r = 3
len = message.length
@suggested_w = len + 8 + message_col if len < @suggested_w - 8 - message_col
display_length = @suggested_w-8
display_length -= message_col
message_height = 2
clr = @color || :white
bgclr = @bgcolor || :black
# trying this out. sometimes very long labels get truncated, so i give a field in wchich user
# can use arrow key or C-a and C-e
if message.size > display_length
message_label = Canis::Field.new @form, {:text => message, :name=>"message_label",
:row => r, :col => message_col, :width => display_length,
:bgcolor => bgclr , :color => clr, :editable => false}
else
message_label = Canis::Label.new @form, {:text => message, :name=>"message_label",
:row => r, :col => message_col, :width => display_length,
:height => message_height, :bgcolor => bgclr , :color => clr}
end
@maxrow = 3
yield message_label if block_given?
end
|
ruby
|
{
"resource": ""
}
|
q23906
|
Canis.MessageBox.text
|
train
|
def text message
@suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
@suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor
message_col = 3
r = 2
display_length = @suggested_w-4
display_length -= message_col
clr = @color || :white
bgclr = @bgcolor || :black
if message.is_a? Array
l = longest_in_list message
if l > @suggested_w
if l < FFI::NCurses.COLS
#@suggested_w = l
@suggested_w = FFI::NCurses.COLS-2
else
@suggested_w = FFI::NCurses.COLS-2
end
display_length = @suggested_w-6
end
# reduce width and height if you can based on array contents
else
message = wrap_text(message, display_length).split("\n")
end
# now that we have moved to textpad that +8 was causing black lines to remain after the text
message_height = message.size #+ 8
# reduce if possible if its not required.
#
r1 = (FFI::NCurses.LINES-@suggested_h)/2
r1 = r1.floor
w = @suggested_w
c1 = (FFI::NCurses.COLS-w)/2
c1 = c1.floor
@suggested_row = r1
@suggested_col = c1
brow = @button_row || @suggested_h-4
available_ht = brow - r + 1
message_height = [message_height, available_ht].min
# replaced 2014-04-14 - 23:51
message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
:row => r, :col => message_col, :width => display_length, :suppress_borders => true,
:height => message_height, :bgcolor => bgclr , :color => clr}
#message_label.set_content message
yield message_label if block_given?
end
|
ruby
|
{
"resource": ""
}
|
q23907
|
Canis.WidgetShortcuts.textarea
|
train
|
def textarea config={}, &block
require 'canis/rtextarea'
# TODO confirm events many more
events = [ :CHANGE, :LEAVE, :ENTER ]
block_event = events[0]
#_process_args args, config, block_event, events
#config[:width] = config[:display_length] unless config.has_key? :width
# if no width given, expand to flows width
#config[:width] ||= @stack.last.width if @stack.last
useform = nil
#useform = @form if @current_object.empty?
w = TextArea.new useform, config
w.width = :expand unless w.width
w.height ||= 8 # TODO
_position(w)
# need to expand to stack's width or flows itemwidth if given
if block
w.bind(block_event, &block)
end
return w
end
|
ruby
|
{
"resource": ""
}
|
q23908
|
Canis.WidgetShortcuts.stack
|
train
|
def stack config={}, &block
s = WsStack.new config
_configure s
@_ws_active << s
yield_or_eval &block if block_given?
@_ws_active.pop
# ---- stack is finished now
last = @_ws_active.last
if last
case last
when WsStack
when WsFlow
last[:col] += last[:item_width] || 0
# this tries to set height of outer flow based on highest row
# printed, however that does not account for height of object,
# so user should give a height to the flow.
last[:height] = s[:row] if s[:row] > (last[:height]||0)
$log.debug "XXX: STACK setting col to #{s[:col]} "
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23909
|
Canis.WidgetShortcuts.flow
|
train
|
def flow config={}, &block
s = WsFlow.new config
_configure s
@_ws_active << s
yield_or_eval &block if block_given?
@_ws_active.pop
last = @_ws_active.last
if last
case last
when WsStack
if s[:height]
last[:row] += s[:height]
else
#last[:row] += last[:highest_row]
last[:row] += 1
end
when WsFlow
last[:col] += last[:item_width] || 0
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23910
|
Canis.WidgetShortcuts.box
|
train
|
def box config={}, &block
require 'canis/core/widgets/box'
# take current stacks row and col
# advance row by one and col by one
# at end note row and advance by one
# draw a box around using these coordinates. width should be
# provided unless we have item width or something.
last = @_ws_active.last
if last
r = last[:row]
c = last[:col]
config[:row] = r
config[:col] = c
last[:row] += config[:margin_top] || 1
last[:col] += config[:margin_left] || 1
_box = Box.new @form, config # needs to be created first or will overwrite area after others painted
yield_or_eval &block if block_given?
h = config[:height] || last[:height] || (last[:row] - r)
h = 2 if h < 2
w = config[:width] || last[:width] || 15 # tmp
case last
when WsFlow
w = last[:col]
when WsStack
#h += 1
end
config[:row] = r
config[:col] = c
config[:height] = h
config[:width] = w
_box.row r
_box.col c
_box.height h
_box.width w
last[:row] += 1
last[:col] += 1 # ??? XXX if flow we need to increment properly or not ?
end
end
|
ruby
|
{
"resource": ""
}
|
q23911
|
Canis.PromptMenu.menu_tree
|
train
|
def menu_tree mt, pm = self
mt.each_pair { |ch, code|
if code.is_a? Canis::MenuTree
item = pm.add(ch, code.value, "")
current = PromptMenu.new @caller, code.value
item.action = current
menu_tree code, current
else
item = pm.add(ch, code.to_s, "", code)
end
}
end
|
ruby
|
{
"resource": ""
}
|
q23912
|
Canis.PromptMenu.submenu
|
train
|
def submenu key, label, &block
item = CMenuItem.new(key, label)
@options << item
item.action = PromptMenu.new @caller, label, &block
end
|
ruby
|
{
"resource": ""
}
|
q23913
|
Canis.PromptMenu.display_columns
|
train
|
def display_columns config={}
prompt = config[:prompt] || "Choose: "
require 'canis/core/util/rcommandwindow'
layout = { :height => 5, :width => Ncurses.COLS-0, :top => Ncurses.LINES-6, :left => 0 }
rc = CommandWindow.new nil, :layout => layout, :box => true, :title => config[:title] || "Menu"
w = rc.window
r = 4
c = 1
color = $datacolor
begin
menu = @options
$log.debug " DISP MENU "
ret = 0
len = 80
while true
h = {}
valid = []
labels = []
menu.each{ |item|
if item.respond_to? :hotkey
hk = item.hotkey.to_s
else
raise ArgumentError, "Promptmenu needs hotkey or mnemonic"
end
# 187compat 2013-03-20 - 19:00 throws up
labels << "%c. %s " % [ hk.getbyte(0), item.label ]
h[hk] = item
valid << hk
}
#$log.debug " valid are #{valid} "
color = $datacolor
#print_this(win, str, color, r, c)
rc.display_menu labels, :indexing => :custom
ch=w.getchar()
rc.clear
#$log.debug " got ch #{ch} "
next if ch < 0 or ch > 255
if ch == 3 || ch == ?\C-g.getbyte(0)
clear_this w, r, c, color, len
print_this(w, "Aborted.", color, r,c)
break
end
ch = ch.chr
index = valid.index ch
if index.nil?
clear_this w, r, c, color, len
print_this(w, "Not valid. Valid are #{valid}. C-c/C-g to abort.", color, r,c)
sleep 1
next
end
#$log.debug " index is #{index} "
item = h[ch]
# I don;t think this even shows now, its useless
if item.respond_to? :desc
desc = item.desc
#desc ||= "Could not find desc for #{ch} "
desc ||= ""
clear_this w, r, c, color, len
print_this(w, desc, color, r,c)
end
action = item.action
case action
#when Array
when PromptMenu
# submenu
menu = action.options
title = rc.title
rc.title title +" => " + action.text # set title of window to submenu
when Proc
#rc.destroy
##bottom needs to be refreshed somehow
#FFI::NCurses.ungetch ?j
rc.hide
ret = action.call
break
when Symbol
if @caller.respond_to?(action, true)
rc.hide
$log.debug "XXX: IO caller responds to action #{action} "
ret = @caller.send(action)
elsif @caller.respond_to?(:execute_this, true)
rc.hide
ret = @caller.send(:execute_this, action)
else
alert "PromptMenu: unidentified action #{action} for #{@caller.class} "
raise "PromptMenu: unidentified action #{action} for #{@caller.class} "
end
break
else
$log.debug " Unidentified flying class #{action.class} "
break
end
end # while
ensure
rc.destroy
rc = nil
end
end
|
ruby
|
{
"resource": ""
}
|
q23914
|
Canis.ListCellRenderer.create_color_pairs
|
train
|
def create_color_pairs
@color_pair = get_color $datacolor
@pairs = Hash.new(@color_pair)
@attrs = Hash.new(Ncurses::A_NORMAL)
color_pair = get_color $selectedcolor, @parent.selected_color, @parent.selected_bgcolor
@pairs[:normal] = @color_pair
@pairs[:selected] = color_pair
@pairs[:focussed] = @pairs[:normal]
@attrs[:selected] = $row_selected_attr
@attrs[:focussed] = $row_focussed_attr
end
|
ruby
|
{
"resource": ""
}
|
q23915
|
Canis.ListCellRenderer.repaint
|
train
|
def repaint graphic, r=@row,c=@col, row_index=-1,value=@text, focussed=false, selected=false
select_colors focussed, selected
# if listboxes width is reduced, display_len remains the same
# XXX FIXME parent may not be the list but a container like rfe !!
# maybe caller should update at start of repain loop.
#@display_length = @parent.width - 2 - @parent.left_margin
value=value.to_s
if !@display_length.nil?
if value.length > @display_length
value = value[0..@display_length-1]
end
# added 2010-09-27 11:05 TO UNCOMMENT AND TEST IT OUT
if @justify == :center
value = value.center(@display_length)
end
end
len = @display_length || value.length
#$log.debug " XXX @display_length: #{@display_length}, #{value.length}, L:#{len}, pw:#{@parent.width} ::attr:: #{@attr} "
graphic.printstring r, c, @format % [len, value], @color_pair, @attr
end
|
ruby
|
{
"resource": ""
}
|
q23916
|
Canis.Io.rb_getchar
|
train
|
def rb_getchar(prompt, config={}) # yield field
begin
win = __create_footer_window
#form = Form.new win
r = 0; c = 1;
default = config[:default]
prompt = "#{prompt} [#{default}] " if default
win.mvprintw(r, c, "%s: " % prompt);
bg = Ncurses.COLORS >= 236 ? 236 : :blue
color_pair = get_color($reversecolor, :white, bg)
win.printstring r, c + prompt.size + 2, " ", color_pair
win.wrefresh
prevchar = 0
entries = nil
while ((ch = win.getchar()) != 999)
return default.ord if default && (ch == 13 || ch == KEY_ENTER)
return nil if ch == ?\C-c.getbyte(0) || ch == ?\C-g.getbyte(0)
if ch == KEY_F1
help_text = config[:help_text] || "No help provided. C-c/C-g aborts."
print_status_message help_text, :wait => 7
win.wrefresh # nevr had to do this with ncurses, but have to with ffi-ncurses ??
next
end
if config[:regexp]
reg = config[:regexp]
if ch > 0 && ch < 256
chs = ch.chr
return ch if chs =~ reg
alert "Wrong character. #{reg} "
else
alert "Wrong character. #{reg} "
end
else
return ch
end
#form.handle_key ch
win.wrefresh
end
rescue => err
Ncurses.beep
$log.error "EXC in rb_getstr #{err} "
$log.error(err.backtrace.join("\n"))
ensure
win.destroy if win
end
return nil
end
|
ruby
|
{
"resource": ""
}
|
q23917
|
Canis.Io.get_file
|
train
|
def get_file prompt, config={} #:nodoc:
maxlen = 70
tabc = Proc.new {|str| Dir.glob(str +"*") }
config[:tab_completion] ||= tabc
config[:maxlen] ||= maxlen
#config[:default] = "test"
#ret, str = rb_getstr(nil,0,0, prompt, maxlen, config)
# 2014-04-25 - 12:42 removed call to deprecated method
str = rb_gets(prompt, config)
#$log.debug " get_file returned #{ret} , #{str} "
str ||= ""
return str
end
|
ruby
|
{
"resource": ""
}
|
q23918
|
Canis.Io.print_this
|
train
|
def print_this(win, text, color, x, y)
raise "win nil in print_this" unless win
color=Ncurses.COLOR_PAIR(color);
win.attron(color);
#win.mvprintw(x, y, "%-40s" % text);
win.mvprintw(x, y, "%s" % text);
win.attroff(color);
win.refresh
end
|
ruby
|
{
"resource": ""
}
|
q23919
|
Canis.Io.rb_getstr
|
train
|
def rb_getstr(nolongerused, r, c, prompt, maxlen, config={})
config[:maxlen] = maxlen
str = rb_gets(prompt, config)
if str
return 0, str
else
return -1, nil
end
end
|
ruby
|
{
"resource": ""
}
|
q23920
|
Canis.TabularWidget.columns=
|
train
|
def columns=(array)
@_header_adjustment = 1
@columns = array
@columns.each_with_index { |c,i|
@cw[i] ||= c.to_s.length
@calign[i] ||= :left
}
# maintains index in current pointer and gives next or prev
@column_pointer = Circular.new @columns.size()-1
end
|
ruby
|
{
"resource": ""
}
|
q23921
|
Canis.TabularWidget.OLDprint_borders
|
train
|
def OLDprint_borders #:nodoc:
raise "#{self.class} needs width" unless @width
raise "#{self.class} needs height" unless @height
$log.debug " #{@name} print_borders, #{@graphic.name} "
bordercolor = @border_color || $datacolor
borderatt = @border_attrib || Ncurses::A_NORMAL
@graphic.print_border @row, @col, @height-1, @width, bordercolor, borderatt
print_title
end
|
ruby
|
{
"resource": ""
}
|
q23922
|
Canis.TabularWidget.set_form_col
|
train
|
def set_form_col col1=@curpos #:nodoc:
@cols_panned ||= 0
@pad_offset ||= 0 # added 2010-02-11 21:54 since padded widgets get an offset.
@curpos = col1
maxlen = @maxlen || @width-@internal_width
#@curpos = maxlen if @curpos > maxlen
if @curpos > maxlen
@pcol = @curpos - maxlen
@curpos = maxlen - 1
@repaint_required = true # this is required so C-e can pan screen
else
@pcol = 0
end
# the rest only determines cursor placement
win_col = 0 # 2010-02-07 23:19 new cursor stuff
col2 = win_col + @col + @col_offset + @curpos + @cols_panned + @pad_offset
#$log.debug "TV SFC #{@name} setting c to #{col2} #{win_col} #{@col} #{@col_offset} #{@curpos} "
#@form.setrowcol @form.row, col
setrowcol nil, col2
@repaint_footer_required = true
end
|
ruby
|
{
"resource": ""
}
|
q23923
|
Canis.TabularWidget.print_data_row
|
train
|
def print_data_row r, c, len, value, color, attr
@graphic.printstring r, c, "%-*s" % [len,value], color, attr
end
|
ruby
|
{
"resource": ""
}
|
q23924
|
Canis.TabularWidget.truncate
|
train
|
def truncate content #:nodoc:
#maxlen = @maxlen || @width-2
_maxlen = @maxlen || @width-@internal_width
_maxlen = @width-@internal_width if _maxlen > @width-@internal_width
_maxlen -= @left_margin
if !content.nil?
cl = content.length
if cl > _maxlen # only show maxlen
@longest_line = cl if cl > @longest_line
## taking care of when scrolling is needed but longest_line is misreported
# So we scroll always and need to check 2013-03-06 - 00:09
#content.replace content[@pcol..@pcol+_maxlen-1]
content.replace(content[@pcol..@pcol+maxlen-1] || " ")
else
#content.replace content[@pcol..-1] if @pcol > 0
content.replace(content[@pcol..-1]||" ") if @pcol > 0
end
end
content
end
|
ruby
|
{
"resource": ""
}
|
q23925
|
Canis.TabularWidget.print_header_row
|
train
|
def print_header_row r, c, len, value, color, attr
#acolor = $promptcolor
@graphic.printstring r, c+@left_margin, "%-*s" % [len-@left_margin ,value], color, attr
end
|
ruby
|
{
"resource": ""
}
|
q23926
|
Canis.TabularWidget.print_header
|
train
|
def print_header
r,c = rowcol
value = convert_value_to_text :columns, 0
len = @width - @internal_width
truncate value # else it can later suddenly exceed line
@header_color_pair ||= get_color $promptcolor, @header_fgcolor, @header_bgcolor
@header_attrib ||= @attr
print_header_row r, c, len, value, @header_color_pair, @header_attrib
end
|
ruby
|
{
"resource": ""
}
|
q23927
|
Canis.TabularWidget._guess_col_widths
|
train
|
def _guess_col_widths #:nodoc:
return if @second_time
@second_time = true if @list.size > 0
@list.each_with_index { |r, i|
break if i > 10
next if r == :separator
r.each_with_index { |c, j|
x = c.to_s.length
if @cw[j].nil?
@cw[j] = x
else
@cw[j] = x if x > @cw[j]
end
}
}
#sum = @cw.values.inject(0) { |mem, var| mem + var }
#$log.debug " SUM is #{sum} "
total = 0
@cw.each_pair { |name, val| total += val }
@preferred_width = total + (@cw.size() *2)
@preferred_width += 4 if @numbering # FIXME this 4 is rough
end
|
ruby
|
{
"resource": ""
}
|
q23928
|
Canis.TabularWidget.next_column
|
train
|
def next_column
c = @column_pointer.next
cp = @coffsets[c]
#$log.debug " next_column #{c} , #{cp} "
@curpos = cp if cp
next_row() if c < @column_pointer.last_index
#addcol cp
set_form_col
end
|
ruby
|
{
"resource": ""
}
|
q23929
|
CloudstackClient.Connection.get_server
|
train
|
def get_server(name)
params = {
'command' => 'listVirtualMachines',
'name' => name
}
json = send_request(params)
machines = json['virtualmachine']
if !machines || machines.empty? then
return nil
end
machine = machines.select { |item| name == item['name'] }
machine.first
end
|
ruby
|
{
"resource": ""
}
|
q23930
|
CloudstackClient.Connection.get_server_public_ip
|
train
|
def get_server_public_ip(server, cached_rules=nil, cached_nat=nil)
return nil unless server
# find the public ip
nic = get_server_default_nic(server)
ssh_rule = get_ssh_port_forwarding_rule(server, cached_rules)
return ssh_rule['ipaddress'] if ssh_rule
winrm_rule = get_winrm_port_forwarding_rule(server, cached_rules)
return winrm_rule['ipaddress'] if winrm_rule
#check for static NAT
if cached_nat
ip_addr = cached_nat.find {|v| v['virtualmachineid'] == server['id']}
else
ip_addr = list_public_ip_addresses.find {|v| v['virtualmachineid'] == server['id']}
end
if ip_addr
return ip_addr['ipaddress']
end
if nic.empty?
return []
end
nic['ipaddress'] || []
end
|
ruby
|
{
"resource": ""
}
|
q23931
|
CloudstackClient.Connection.get_server_fqdn
|
train
|
def get_server_fqdn(server)
return nil unless server
nic = get_server_default_nic(server) || {}
networks = list_networks || {}
id = nic['networkid']
network = networks.select { |net|
net['id'] == id
}.first
return nil unless network
"#{server['name']}.#{network['networkdomain']}"
end
|
ruby
|
{
"resource": ""
}
|
q23932
|
CloudstackClient.Connection.list_object
|
train
|
def list_object(params, json_result)
json = send_request(params)
Chef::Log.debug("JSON (list_object) result: #{json}")
result = json["#{json_result}"] || []
result = data_filter(result, params['filter']) if params['filter']
result
end
|
ruby
|
{
"resource": ""
}
|
q23933
|
CloudstackClient.Connection.create_server
|
train
|
def create_server(host_name, service_name, template_name, disk_name=nil, zone_name=nil, network_names=[], extra_params)
if host_name then
if get_server(host_name) then
puts "\nError: Server '#{host_name}' already exists."
exit 1
end
end
service = get_service_offering(service_name)
if !service then
puts "\nError: Service offering '#{service_name}' is invalid"
exit 1
end
template = get_template(template_name, zone_name)
template = get_iso(template_name, zone_name) unless template
if !template then
puts "\nError: Template / ISO name: '#{template_name}' is invalid"
exit 1
end
if disk_name then
disk = get_disk_offering(disk_name)
if !disk then
puts "\nError: Disk offering '#{disk_name}' is invalid"
exit 1
end
end
zone = zone_name ? get_zone(zone_name) : get_default_zone
if !zone then
msg = zone_name ? "Zone '#{zone_name}' is invalid" : "No default zone found"
puts "\nError: #{msg}"
exit 1
end
if zone['networktype'] != 'Basic' then
# If this is a Basic zone no networkids are needed in the params
networks = []
if network_names.nil? then
networks << get_default_network(zone['id'])
else
network_names.each do |name|
network = get_network(name)
if !network then
puts "\nError: Network '#{name}' not found"
end
networks << get_network(name)
end
end
if networks.empty? then
networks << get_default_network(zone['id'])
end
if networks.empty? then
puts "\nError: No default network found"
exit 1
end
network_ids = networks.map { |network|
network['id']
}
params = {
'command' => 'deployVirtualMachine',
'serviceOfferingId' => service['id'],
'templateId' => template['id'],
'zoneId' => zone['id'],
'networkids' => network_ids.join(',')
}
else
params = {
'command' => 'deployVirtualMachine',
'serviceOfferingId' => service['id'],
'templateId' => template['id'],
'zoneId' => zone['id']
}
end
params.merge!(extra_params) if extra_params
params['name'] = host_name if host_name
params['diskOfferingId'] = disk['id'] if disk
json = send_async_request(params)
json['virtualmachine']
end
|
ruby
|
{
"resource": ""
}
|
q23934
|
CloudstackClient.Connection.delete_server
|
train
|
def delete_server(name, expunge)
server = get_server(name)
if !server || !server['id'] then
puts "\nError: Virtual machine '#{name}' does not exist"
exit 1
end
params = {
'command' => 'destroyVirtualMachine',
'id' => server['id'],
'expunge' => expunge
}
json = send_async_request(params)
json['virtualmachine']
end
|
ruby
|
{
"resource": ""
}
|
q23935
|
CloudstackClient.Connection.stop_server
|
train
|
def stop_server(name, forced=nil)
server = get_server(name)
if !server || !server['id'] then
puts "\nError: Virtual machine '#{name}' does not exist"
exit 1
end
params = {
'command' => 'stopVirtualMachine',
'id' => server['id']
}
params['forced'] = true if forced
json = send_async_request(params)
json['virtualmachine']
end
|
ruby
|
{
"resource": ""
}
|
q23936
|
CloudstackClient.Connection.start_server
|
train
|
def start_server(name)
server = get_server(name)
if !server || !server['id'] then
puts "\nError: Virtual machine '#{name}' does not exist"
exit 1
end
params = {
'command' => 'startVirtualMachine',
'id' => server['id']
}
json = send_async_request(params)
json['virtualmachine']
end
|
ruby
|
{
"resource": ""
}
|
q23937
|
CloudstackClient.Connection.get_service_offering
|
train
|
def get_service_offering(name)
# TODO: use name parameter
# listServiceOfferings in CloudStack 2.2 doesn't seem to work
# when the name parameter is specified. When this is fixed,
# the name parameter should be added to the request.
params = {
'command' => 'listServiceOfferings'
}
json = send_request(params)
services = json['serviceoffering']
return nil unless services
services.each { |s|
if name.is_uuid? then
return s if s['id'] == name
else
return s if s['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23938
|
CloudstackClient.Connection.get_template
|
train
|
def get_template(name, zone_name=nil)
# TODO: use name parameter
# listTemplates in CloudStack 2.2 doesn't seem to work
# when the name parameter is specified. When this is fixed,
# the name parameter should be added to the request.
zone = zone_name ? get_zone(zone_name) : get_default_zone
params = {
'command' => 'listTemplates',
'templateFilter' => 'executable',
}
params['zoneid'] = zone['id'] if zone
json = send_request(params)
templates = json['template']
return nil unless templates
templates.each { |t|
if name.is_uuid? then
return t if t['id'] == name
else
return t if t['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23939
|
CloudstackClient.Connection.get_iso
|
train
|
def get_iso(name, zone_name=nil)
zone = zone_name ? get_zone(zone_name) : get_default_zone
params = {
'command' => 'listIsos',
'isoFilter' => 'executable',
}
params['zoneid'] = zone['id'] if zone
json = send_request(params)
iso = json['iso']
return nil unless iso
iso.each { |i|
if name.is_uuid? then
return i if i['id'] == name
else
return i if i['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23940
|
CloudstackClient.Connection.get_disk_offering
|
train
|
def get_disk_offering(name)
params = {
'command' => 'listDiskOfferings',
}
json = send_request(params)
disks = json['diskoffering']
return nil if !disks
disks.each { |d|
return d if d['name'] == name
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23941
|
CloudstackClient.Connection.get_volume
|
train
|
def get_volume(name)
params = {
'command' => 'listVolumes',
'name' => name
}
json = send_request(params)
volumes = json['volume']
if !volumes || volumes.empty? then
return nil
end
volume = volumes.select { |item| name == item['name'] }
volume.first
end
|
ruby
|
{
"resource": ""
}
|
q23942
|
CloudstackClient.Connection.delete_volume
|
train
|
def delete_volume(name)
volume = get_volume(name)
if !volume || !volume['id'] then
puts "\nError: Volume '#{name}' does not exist"
exit 1
end
params = {
'command' => 'deleteVolume',
'id' => volume['id']
}
json = send_request(params)
json['success']
end
|
ruby
|
{
"resource": ""
}
|
q23943
|
CloudstackClient.Connection.get_project
|
train
|
def get_project(name)
params = {
'command' => 'listProjects',
'listall' => true
}
json = send_request(params)
projects = json['project']
return nil unless projects
projects.each { |n|
if name.is_uuid? then
return n if n['id'] == name
else
return n if n['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23944
|
CloudstackClient.Connection.data_filter
|
train
|
def data_filter(data, filters)
filters.split(',').each do |filter|
field = filter.split(':').first.strip.downcase
search = filter.split(':').last.strip
if search =~ /^\/.*\/?/
data = data.find_all { |k| k["#{field}"].to_s =~ search.to_regexp } if field && search
else
data = data.find_all { |k| k["#{field}"].to_s == "#{search}" } if field && search
end
end
data
end
|
ruby
|
{
"resource": ""
}
|
q23945
|
CloudstackClient.Connection.get_network
|
train
|
def get_network(name)
params = {
'command' => 'listNetworks'
}
json = send_request(params)
networks = json['network']
return nil unless networks
networks.each { |n|
if name.is_uuid? then
return n if n['id'] == name
else
return n if n['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23946
|
CloudstackClient.Connection.get_default_network
|
train
|
def get_default_network(zone)
params = {
'command' => 'listNetworks',
'isDefault' => true,
'zoneid' => zone
}
json = send_request(params)
networks = json['network']
return nil if !networks || networks.empty?
default = networks.first
return default if networks.length == 1
networks.each { |n|
if n['type'] == 'Direct' then
default = n
break
end
}
default
end
|
ruby
|
{
"resource": ""
}
|
q23947
|
CloudstackClient.Connection.get_zone
|
train
|
def get_zone(name)
params = {
'command' => 'listZones',
'available' => 'true'
}
json = send_request(params)
networks = json['zone']
return nil unless networks
networks.each { |z|
if name.is_uuid? then
return z if z['id'] == name
else
return z if z['name'] == name
end
}
nil
end
|
ruby
|
{
"resource": ""
}
|
q23948
|
CloudstackClient.Connection.get_default_zone
|
train
|
def get_default_zone
params = {
'command' => 'listZones',
'available' => 'true'
}
json = send_request(params)
zones = json['zone']
return nil unless zones
# zones.sort! # sort zones so we always return the same zone
# !this gives error in our production environment so need to retest this
zones.first
end
|
ruby
|
{
"resource": ""
}
|
q23949
|
CloudstackClient.Connection.get_public_ip_address
|
train
|
def get_public_ip_address(ip_address)
params = {
'command' => 'listPublicIpAddresses',
'ipaddress' => ip_address
}
json = send_request(params)
return nil unless json['publicipaddress']
json['publicipaddress'].first
end
|
ruby
|
{
"resource": ""
}
|
q23950
|
CloudstackClient.Connection.associate_ip_address
|
train
|
def associate_ip_address(zone_id, networks)
params = {
'command' => 'associateIpAddress',
'zoneId' => zone_id
}
#Choose the first network from the list
if networks.nil? || networks.empty?
default_network = get_default_network(zone_id)
params['networkId'] = default_network['id']
else
params['networkId'] = get_network(networks.first)['id']
end
Chef::Log.debug("associate ip params: #{params}")
json = send_async_request(params)
json['ipaddress']
end
|
ruby
|
{
"resource": ""
}
|
q23951
|
CloudstackClient.Connection.list_port_forwarding_rules
|
train
|
def list_port_forwarding_rules(ip_address_id=nil, listall=false)
params = { 'command' => 'listPortForwardingRules' }
params['ipAddressId'] = ip_address_id if ip_address_id
params['listall'] = listall
json = send_request(params)
json['portforwardingrule']
end
|
ruby
|
{
"resource": ""
}
|
q23952
|
CloudstackClient.Connection.get_ssh_port_forwarding_rule
|
train
|
def get_ssh_port_forwarding_rule(server, cached_rules=nil)
rules = cached_rules || list_port_forwarding_rules || []
rules.find_all { |r|
r['virtualmachineid'] == server['id'] &&
r['privateport'] == '22'&&
r['publicport'] == '22'
}.first
end
|
ruby
|
{
"resource": ""
}
|
q23953
|
CloudstackClient.Connection.get_winrm_port_forwarding_rule
|
train
|
def get_winrm_port_forwarding_rule(server, cached_rules=nil)
rules = cached_rules || list_port_forwarding_rules || []
rules.find_all { |r|
r['virtualmachineid'] == server['id'] &&
(r['privateport'] == '5985' &&
r['publicport'] == '5985') ||
(r['privateport'] == '5986' &&
r['publicport'] == '5986')
}.first
end
|
ruby
|
{
"resource": ""
}
|
q23954
|
CloudstackClient.Connection.create_port_forwarding_rule
|
train
|
def create_port_forwarding_rule(ip_address_id, private_port, protocol, public_port, virtual_machine_id)
params = {
'command' => 'createPortForwardingRule',
'ipAddressId' => ip_address_id,
'privatePort' => private_port,
'protocol' => protocol,
'publicPort' => public_port,
'virtualMachineId' => virtual_machine_id
}
json = send_async_request(params)
json['portforwardingrule']
end
|
ruby
|
{
"resource": ""
}
|
q23955
|
Canis.Utils.key_tos
|
train
|
def key_tos ch # -- {{{
x = $key_cache[ch]
return x if x
chr = case ch
when 10,13 , KEY_ENTER
"<CR>"
when 9
"<TAB>"
when 0
"<C-@>"
when 27
"<ESC>"
when 31
"<C-/>"
when 1..30
x= ch + 96
"<C-#{x.chr}>"
when 32
"<SPACE>"
when 41
"<M-CR>"
when 33..126
ch.chr
when 127,263
"<BACKSPACE>"
when 128..154
x = ch - 128
#"<M-C-#{x.chr}>"
xx = key_tos(x).gsub(/[<>]/,"")
"<M-#{xx}>"
when 160..255
x = ch - 128
xx = key_tos(x).gsub(/[<>]/,"")
"<M-#{xx}>"
when 255
"<M-BACKSPACE>"
when 2727
"<ESC-ESC>"
else
chs = FFI::NCurses::keyname(ch)
# remove those ugly brackets around function keys
if chs && chs[-1]==')'
chs = chs.gsub(/[()]/,'')
end
if chs
chs = chs.gsub("KEY_","")
"<#{chs}>"
else
"UNKNOWN:#{ch}"
end
end
$key_cache[ch] = chr
return chr
end
|
ruby
|
{
"resource": ""
}
|
q23956
|
Canis.Utils.get_color
|
train
|
def get_color default=$datacolor, color=color(), bgcolor=bgcolor()
return default if color.nil? || bgcolor.nil?
#raise ArgumentError, "Color not valid: #{color}: #{ColorMap.colors} " if !ColorMap.is_color? color
#raise ArgumentError, "Bgolor not valid: #{bgcolor} : #{ColorMap.colors} " if !ColorMap.is_color? bgcolor
acolor = ColorMap.get_color(color, bgcolor)
return acolor
end
|
ruby
|
{
"resource": ""
}
|
q23957
|
Canis.Utils.print_key_bindings
|
train
|
def print_key_bindings *args
f = get_current_field
#labels = [@key_label, f.key_label]
#labels = [@key_label]
#labels << f.key_label if f.key_label
labels = []
labels << (f.key_label || {}) #if f.key_label
labels << @key_label
arr = []
if get_current_field.help_text
arr << get_current_field.help_text
end
labels.each_with_index { |h, i|
case i
when 0
arr << " === Current widget bindings ==="
when 1
arr << " === Form bindings ==="
end
h.each_pair { |name, val|
if name.is_a? Integer
name = keycode_tos name
elsif name.is_a? String
name = keycode_tos(name.getbyte(0))
elsif name.is_a? Array
s = []
name.each { |e|
s << keycode_tos(e.getbyte(0))
}
name = s
else
#$log.debug "XXX: KEY #{name} #{name.class} "
end
arr << " %-30s %s" % [name ,val]
$log.debug "KEY: #{name} : #{val} "
}
}
textdialog arr, :title => "Key Bindings"
end
|
ruby
|
{
"resource": ""
}
|
q23958
|
Canis.Utils.view
|
train
|
def view what, config={}, &block # :yields: textview for further configuration
require 'canis/core/util/viewer'
Canis::Viewer.view what, config, &block
end
|
ruby
|
{
"resource": ""
}
|
q23959
|
Canis.Utils.create_logger
|
train
|
def create_logger path
#path = File.join(ENV["LOGDIR"] || "./" ,"canis14.log")
_path = File.open(path, File::WRONLY|File::TRUNC|File::CREAT)
logg = Logger.new(_path)
raise "Could not create logger: #{path}" unless logg
# if not set, will default to 0 which is debug. Other values are 1 - info, 2 - warn
logg.level = ENV["CANIS_LOG_LEVEL"].to_i
colors = Ncurses.COLORS
logg.info "START #{colors} colors -- #{$0} win: #{@window} : log level: #{logg.level}. To change log level, increase CANIS_LOG_LEVEL in your environment to 1 or 2 or 3."
return logg
end
|
ruby
|
{
"resource": ""
}
|
q23960
|
Canis.EventHandler.fire_property_change
|
train
|
def fire_property_change text, oldvalue, newvalue
return if @_object_created.nil? # 2018-05-15 - removed check for nil, as object can be nil on creation
# but set later.
#$log.debug " FPC #{self}: #{text} #{oldvalue}, #{newvalue}"
$log.debug " FPC #{self}: #{text} "
if @pce.nil?
@pce = PropertyChangeEvent.new(self, text, oldvalue, newvalue)
else
@pce.set( self, text, oldvalue, newvalue)
end
fire_handler :PROPERTY_CHANGE, @pce
@repaint_required = true
repaint_all(true) # for repainting borders, headers etc 2011-09-28 V1.3.1
end
|
ruby
|
{
"resource": ""
}
|
q23961
|
Canis.Widget.property_set
|
train
|
def property_set sym, val
oldvalue = instance_variable_get "@#{sym}"
tmp = val.size == 1 ? val[0] : val
newvalue = tmp
if oldvalue.nil? || @_object_created.nil?
#@#{sym} = tmp
instance_variable_set "@#{sym}", tmp
end
return(self) if oldvalue.nil? || @_object_created.nil?
if oldvalue != newvalue
# trying to reduce calls to fire, when object is being created
begin
@property_changed = true
fire_property_change("#{sym}", oldvalue, newvalue) if !oldvalue.nil?
#@#{sym} = tmp
instance_variable_set "@#{sym}", tmp
#@config["#{sym}"]=@#{sym}
rescue PropertyVetoException
$log.warn "PropertyVetoException for #{sym}:" + oldvalue.to_s + "-> "+ newvalue.to_s
end
end # if old
self
end
|
ruby
|
{
"resource": ""
}
|
q23962
|
Canis.Widget.repaint
|
train
|
def repaint
r,c = rowcol
#@bgcolor ||= $def_bg_color # moved down 2011-11-5
#@color ||= $def_fg_color
_bgcolor = bgcolor()
_color = color()
$log.debug("widget repaint : r:#{r} c:#{c} col:#{_color}" )
value = getvalue_for_paint
len = @width || value.length
acolor = @color_pair || get_color($datacolor, _color, _bgcolor)
@graphic.printstring r, c, "%-*s" % [len, value], acolor, attr()
# next line should be in same color but only have @att so we can change att is nec
#@form.window.mvchgat(y=r, x=c, max=len, Ncurses::A_NORMAL, @bgcolor, nil)
end
|
ruby
|
{
"resource": ""
}
|
q23963
|
Canis.Widget.set_form
|
train
|
def set_form form
raise "Form is nil in set_form" if form.nil?
@form = form
@id = form.add_widget(self) if !form.nil? and form.respond_to? :add_widget
# 2009-10-29 15:04 use form.window, unless buffer created
# should not use form.window so explicitly everywhere.
# added 2009-12-27 20:05 BUFFERED in case child object needs a form.
# We don;t wish to overwrite the graphic object
if @graphic.nil?
#$log.debug " setting graphic to form window for #{self.class}, #{form} "
@graphic = form.window unless form.nil? # use screen for writing, not buffer
end
# execute those actions delayed due to absence of form -- used internally
# mostly by buttons and labels to bind hotkey to form
fire_handler(:FORM_ATTACHED, self) if event? :FORM_ATTACHED
end
|
ruby
|
{
"resource": ""
}
|
q23964
|
Canis.Widget.color_pair
|
train
|
def color_pair(*val)
if val.empty?
#return @color_pair
return @color_pair || get_color($datacolor, color(), bgcolor())
end
oldvalue = @color_pair
case val.size
when 1
raise ArgumentError, "Expecting fixnum for color_pair." unless val[0].is_a? Integer
@color_pair = val[0]
@color, @bgcolor = ColorMap.get_colors_for_pair @color_pair
when 2
@color = val.first if val.first
@bgcolor = val.last if val.last
@color_pair = get_color $datacolor, @color, @bgcolor
end
if oldvalue != @color_pair
fire_property_change(:color_pair, oldvalue, @color_pair)
@property_changed = true
repaint_all true
end
self
end
|
ruby
|
{
"resource": ""
}
|
q23965
|
Canis.Widget.command
|
train
|
def command *args, &block
if event? :PRESS
bind :PRESS, *args, &block
else
bind :CHANGED, *args, &block
end
end
|
ruby
|
{
"resource": ""
}
|
q23966
|
Canis.Form.set_menu_bar
|
train
|
def set_menu_bar mb
@menu_bar = mb
add_widget mb
mb.toggle_key ||= Ncurses.KEY_F2
if !mb.toggle_key.nil?
ch = mb.toggle_key
bind_key(ch, 'Menu Bar') do |_form|
if !@menu_bar.nil?
@menu_bar.toggle
@menu_bar.handle_keys
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23967
|
Canis.Form.repaint
|
train
|
def repaint
$log.debug " form repaint:#{self}, #{@name} , r #{@row} c #{@col} " if $log.debug?
if @resize_required && @layout_manager
@layout_manager.form = self unless @layout_manager.form
@layout_manager.do_layout
@resize_required = false
end
@widgets.each do |f|
next if f.visible == false # added 2008-12-09 12:17
#$log.debug "XXX: FORM CALLING REPAINT OF WIDGET #{f} IN LOOP"
#raise "Row or col nil #{f.row} #{f.col} for #{f}, #{f.name} " if f.row.nil? || f.col.nil?
f.repaint
f._object_created = true # added 2010-09-16 13:02 now prop handlers can be fired
end
_update_focusables if @focusable_modified
# this can bomb if someone sets row. We need a better way!
if @row == -1 and @_firsttime == true
select_first_field
@_firsttime = false
end
setpos
# XXX this creates a problem if window is a pad
# although this does show cursor movement etc.
### @window.wrefresh
#if @window.window_type == :WINDOW
#$log.debug " formrepaint #{@name} calling window.wrefresh #{@window} "
@window.wrefresh
Ncurses::Panel.update_panels ## added 2010-11-05 00:30 to see if clears the stdscr problems
#else
#$log.warn " XXX formrepaint #{@name} no refresh called 2011-09-19 #{@window} "
#end
end
|
ruby
|
{
"resource": ""
}
|
q23968
|
Canis.Form.setpos
|
train
|
def setpos r=@row, c=@col
#$log.debug "setpos : (#{self.name}) #{r} #{c} XXX"
## adding just in case things are going out of bounds of a parent and no cursor to be shown
return if r.nil? or c.nil? # added 2009-12-29 23:28 BUFFERED
return if r<0 or c<0 # added 2010-01-02 18:49 stack too deep coming if goes above screen
@window.wmove r,c
end
|
ruby
|
{
"resource": ""
}
|
q23969
|
Canis.Form.on_leave
|
train
|
def on_leave f
return if f.nil? || !f.focusable # added focusable, else label was firing
f.state = :NORMAL
# on leaving update text_variable if defined. Should happen on modified only
# should this not be f.text_var ... f.buffer ? 2008-11-25 18:58
#f.text_variable.value = f.buffer if !f.text_variable.nil? # 2008-12-20 23:36
f.on_leave if f.respond_to? :on_leave
# 2014-04-24 - 17:42 NO MORE ENTER LEAVE at FORM LEVEL
#fire_handler :LEAVE, f
## to test XXX in combo boxes the box may not be editable by be modified by selection.
if f.respond_to? :editable and f.modified?
$log.debug " Form about to fire CHANGED for #{f} "
f.fire_handler(:CHANGED, f)
end
end
|
ruby
|
{
"resource": ""
}
|
q23970
|
Canis.Form.on_enter
|
train
|
def on_enter f
return if f.nil? || !f.focusable # added focusable, else label was firing 2010-09
f.state = :HIGHLIGHTED
# If the widget has a color defined for focussed, set repaint
# otherwise it will not be repainted unless user edits !
if f.highlight_bgcolor || f.highlight_color
f.repaint_required true
end
f.modified false
#f.set_modified false
f.on_enter if f.respond_to? :on_enter
# 2014-04-24 - 17:42 NO MORE ENTER LEAVE at FORM LEVEL
#fire_handler :ENTER, f
end
|
ruby
|
{
"resource": ""
}
|
q23971
|
Canis.Form.map_keys
|
train
|
def map_keys
return if @keys_mapped
bind_key(KEY_F1, 'help') { hm = help_manager(); hm.display_help }
bind_keys([?\M-?,?\?], 'show field help') {
#if get_current_field.help_text
#textdialog(get_current_field.help_text, 'title' => 'Help Text', :bgcolor => 'green', :color => :white)
#else
print_key_bindings
#end
}
bind_key(FFI::NCurses::KEY_F9, "Print keys", :print_key_bindings) # show bindings, tentative on F9
bind_key(?\M-:, 'show menu') {
fld = get_current_field
am = fld.action_manager()
#fld.init_menu
am.show_actions
}
@keys_mapped = true
end
|
ruby
|
{
"resource": ""
}
|
q23972
|
Canis.Field._set_buffer
|
train
|
def _set_buffer value #:nodoc:
@repaint_required = true
@datatype = value.class
@delete_buffer = @buffer.dup
@buffer = value.to_s.dup
# don't allow setting of value greater than maxlen
@buffer = @buffer[0,@maxlen] if @maxlen && @buffer.length > @maxlen
@curpos = 0
# hope @delete_buffer is not overwritten
fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos, self, :DELETE, 0, @delete_buffer) # 2010-09-11 13:01
fire_handler :CHANGE, InputDataEvent.new(@curpos,@curpos, self, :INSERT, 0, @buffer) # 2010-09-11 13:01
self # 2011-10-2
end
|
ruby
|
{
"resource": ""
}
|
q23973
|
Canis.Field.set_label
|
train
|
def set_label label
# added case for user just using a string
case label
when String
# what if no form at this point
@label_unattached = true unless @form
label = Label.new @form, {:text => label}
end
@label = label
# in the case of app it won't be set yet FIXME
# So app sets label to 0 and t his won't trigger
# can this be delayed to when paint happens XXX
if @row
position_label
else
@label_unplaced = true
end
label
end
|
ruby
|
{
"resource": ""
}
|
q23974
|
Canis.Field.position_label
|
train
|
def position_label
$log.debug "XXX: LABEL row #{@label.row}, #{@label.col} "
@label.row @row unless @label.row #if @label.row == -1
@label.col @col-(@label.name.length+1) unless @label.col #if @label.col == -1
@label.label_for(self) # this line got deleted when we redid stuff !
$log.debug " XXX: LABEL row #{@label.row}, #{@label.col} "
end
|
ruby
|
{
"resource": ""
}
|
q23975
|
Canis.Field.cursor_end
|
train
|
def cursor_end
blen = @buffer.rstrip.length
if blen < @width
set_form_col blen
else
# there is a problem here FIXME.
@pcol = blen-@width
#set_form_col @width-1
set_form_col blen
end
@curpos = blen # this is position in array where editing or motion is to happen regardless of what you see
# regardless of pcol (panning)
# $log.debug " crusor END cp:#{@curpos} pcol:#{@pcol} b.l:#{@buffer.length} d_l:#{@width} fc:#{@form.col}"
#set_form_col @buffer.length
end
|
ruby
|
{
"resource": ""
}
|
q23976
|
Canis.Field.set_form_col
|
train
|
def set_form_col col1=@curpos
@curpos = col1 || 0 # NOTE we set the index of cursor here
c = @col + @col_offset + @curpos - @pcol
min = @col + @col_offset
max = min + @width
c = min if c < min
c = max if c > max
#$log.debug " #{@name} FIELD set_form_col #{c}, curpos #{@curpos} , #{@col} + #{@col_offset} pcol:#{@pcol} "
setrowcol nil, c
end
|
ruby
|
{
"resource": ""
}
|
q23977
|
Canis.Field.in_range?
|
train
|
def in_range?( val )
val = val.to_i
(@above.nil? or val > @above) and
(@below.nil? or val < @below) and
(@valid_range.nil? or @valid_range.include?(val))
end
|
ruby
|
{
"resource": ""
}
|
q23978
|
Canis.LabeledField.repaint
|
train
|
def repaint
return unless @repaint_required
_lrow = @lrow || @row
# the next was nice, but in some cases this goes out of screen. and the container
# only sets row and col for whatever is added, it does not know that lcol has to be
# taken into account
#_lcol = @lcol || (@col - @label.length - 2)
unless @lcol
@lcol = @col
@col = @lcol + @label.length + 2
end
_lcol = @lcol
@graphic = @form.window if @graphic.nil?
lcolor = @label_color_pair || $datacolor # this should be the same color as window bg XXX
lattr = @label_attr || NORMAL
@graphic.printstring _lrow, _lcol, @label, lcolor, lattr
##c += @label.length + 2
#@col_offset = c-@col # required so cursor lands in right place
super
end
|
ruby
|
{
"resource": ""
}
|
q23979
|
Canis.Label.bind_hotkey
|
train
|
def bind_hotkey
if @mnemonic
ch = @mnemonic.downcase()[0].ord ## 1.9 DONE
# meta key
mch = ?\M-a.getbyte(0) + (ch - ?a.getbyte(0)) ## 1.9
if (@label_for.is_a? Canis::Button ) && (@label_for.respond_to? :fire)
@form.bind_key(mch, "hotkey for button #{@label_for.text} ") { |_form, _butt| @label_for.fire }
else
$log.debug " bind_hotkey label for: #{@label_for}"
@form.bind_key(mch, "hotkey for label #{text} ") { |_form, _field| @label_for.focus }
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23980
|
Canis.Label.repaint
|
train
|
def repaint
return unless @repaint_required
raise "Label row or col nil #{@row} , #{@col}, #{@text} " if @row.nil? || @col.nil?
r,c = rowcol
#@bgcolor ||= $def_bg_color
#@color ||= $def_fg_color
_bgcolor = bgcolor()
_color = color()
# value often nil so putting blank, but usually some application error
value = getvalue_for_paint || ""
if value.is_a? Array
value = value.join " "
end
# ensure we do not exceed
if @width
if value.length > @width
value = value[0..@width-1]
end
end
len = @width || value.length
#acolor = get_color $datacolor
# the user could have set color_pair, use that, else determine color
# This implies that if he sets cp, then changing col and bg won't have an effect !
# A general routine that only changes color will not work here.
acolor = @color_pair || get_color($datacolor, _color, _bgcolor)
#$log.debug "label :#{@text}, #{value}, r #{r}, c #{c} col= #{@color}, #{@bgcolor} acolor #{acolor} j:#{@justify} dlL: #{@width} "
str = @justify.to_sym == :right ? "%*s" : "%-*s" # added 2008-12-22 19:05
@graphic ||= @form.window
# clear the area
@graphic.printstring r, c, " " * len , acolor, attr()
if @justify.to_sym == :center
padding = (@width - value.length)/2
value = " "*padding + value + " "*padding # so its cleared if we change it midway
end
@graphic.printstring r, c, str % [len, value], acolor, attr()
if @mnemonic
ulindex = value.index(@mnemonic) || value.index(@mnemonic.swapcase)
@graphic.mvchgat(y=r, x=c+ulindex, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, acolor, nil)
end
@repaint_required = false
end
|
ruby
|
{
"resource": ""
}
|
q23981
|
Canis.Button.action
|
train
|
def action a
text a.name
mnemonic a.mnemonic unless a.mnemonic.nil?
command { a.call }
end
|
ruby
|
{
"resource": ""
}
|
q23982
|
Canis.Button.repaint
|
train
|
def repaint # button
#@bgcolor ||= $def_bg_color
#@color ||= $def_fg_color
$log.debug("BUTTON repaint : #{self} r:#{@row} c:#{@col} , #{@color} , #{@bgcolor} , #{getvalue_for_paint}" )
r,c = @row, @col #rowcol include offset for putting cursor
# NOTE: please override both (if using a string), or else it won't work
# These are both colorpairs not colors ??? 2014-05-31 - 11:58
_highlight_color = @highlight_color || $reversecolor
_highlight_bgcolor = @highlight_bgcolor || 0
_bgcolor = bgcolor()
_color = color()
if @state == :HIGHLIGHTED
_bgcolor = @state==:HIGHLIGHTED ? _highlight_bgcolor : _bgcolor
_color = @state==:HIGHLIGHTED ? _highlight_color : _color
elsif selected? # only for certain buttons lie toggle and radio
_bgcolor = @selected_bgcolor || _bgcolor
_color = @selected_color || _color
end
$log.debug "XXX: button #{text} STATE is #{@state} color #{_color} , bg: #{_bgcolor} "
if _bgcolor.is_a?( Integer) && _color.is_a?( Integer)
# i think this means they are colorpairs not colors, but what if we use colors on the 256 scale ?
# i don;t like this at all.
else
_color = get_color($datacolor, _color, _bgcolor)
end
value = getvalue_for_paint
$log.debug("button repaint :#{self} r:#{r} c:#{c} col:#{_color} bg #{_bgcolor} v: #{value} ul #{@underline} mnem #{@mnemonic} datacolor #{$datacolor} ")
len = @width || value.length
@graphic = @form.window if @graphic.nil? ## cell editor listbox hack
@graphic.printstring r, c, "%-*s" % [len, value], _color, attr()
# @form.window.mvchgat(y=r, x=c, max=len, Ncurses::A_NORMAL, bgcolor, nil)
# in toggle buttons the underline can change as the text toggles
if @underline || @mnemonic
uline = @underline && (@underline + @text_offset) || value.index(@mnemonic) ||
value.index(@mnemonic.swapcase)
# if the char is not found don't print it
if uline
y=r #[email protected]
x=c+uline #[email protected]
#
# NOTE: often values go below zero since root windows are defined
# with 0 w and h, and then i might use that value for calcaluting
#
$log.error "XXX button underline location error #{x} , #{y} " if x < 0 or c < 0
raise " #{r} #{c} #{uline} button underline location error x:#{x} , y:#{y}. left #{@graphic.left} top:#{@graphic.top} " if x < 0 or c < 0
@graphic.mvchgat(y, x, max=1, Ncurses::A_BOLD|Ncurses::A_UNDERLINE, _color, nil)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23983
|
Canis.ItemEvent.set
|
train
|
def set state, item_first=-1, item_last=-1, param_string=nil
@state, @item_first, @item_last, @param_string =
state, item_first, item_last, param_string
@param_string = "Item event fired: #{item}, #{state}" if param_string.nil?
end
|
ruby
|
{
"resource": ""
}
|
q23984
|
Canis.ButtonGroup.select
|
train
|
def select button
if button.is_a? String
;
else
button = button.value
end
set_value button
end
|
ruby
|
{
"resource": ""
}
|
q23985
|
Canis.WidgetMenu._show_menu
|
train
|
def _show_menu
return if @_menuitems.nil? || @_menuitems.empty?
list = @_menuitems
menu = PromptMenu.new self do |m|
list.each { |e|
m.add *e
}
end
menu.display_new :title => 'Widget Menu (Press letter)'
end
|
ruby
|
{
"resource": ""
}
|
q23986
|
Canis.ListScrollable.bounds_check
|
train
|
def bounds_check
h = scrollatrow()
rc = row_count
@old_toprow = @toprow
@_header_adjustment ||= 0
@current_index = 0 if @current_index < 0 # not lt 0
@current_index = rc-1 if @current_index >= rc && rc>0 # not gt rowcount
@toprow = rc-h-1 if rc > h && @toprow > rc - h - 1 # toprow shows full page if possible
# curr has gone below table, move toprow forward
if @current_index - @toprow > h
@toprow = @current_index - h
elsif @current_index < @toprow
# curr has gone above table, move toprow up
# sometimes current row gets hidden below header line
@toprow = @current_index - (@_header_adjustment ||0)
# prev line can make top row -1, however, if we are going back, lets
# put it at start of page, so first or second row is not hidden
@toprow = 0 if @toprow < h
end
@row_changed = false
if @oldrow != @current_index
on_leave_row @oldrow if respond_to? :on_leave_row # to be defined by widget that has included this
on_enter_row @current_index if respond_to? :on_enter_row # to be defined by widget that has included this
set_form_row
@row_changed = true
end
#set_form_row # 2011-10-13
if @old_toprow != @toprow # only if scrolling has happened should we repaint
@repaint_required = true #if @old_toprow != @toprow # only if scrolling has happened should we repaint
@widget_scrolled = true
end
end
|
ruby
|
{
"resource": ""
}
|
q23987
|
Canis.ListScrollable.show_caret_func
|
train
|
def show_caret_func
return unless @show_caret
# trying highlighting cursor 2010-01-23 19:07 TABBEDPANE TRYING
# TODO take into account rows_panned etc ? I don't think so.
@rows_panned ||= 0
r,c = rowcol
yy = r + @current_index - @toprow - @win_top
#xx = @form.col # how do we know what value has been set earlier ?
yy = r + @current_index - @toprow #- @win_top
yy = @row_offset + @current_index - @toprow #- @win_top
xx = @col_offset + @curpos || 0
#yy = @row_offset if yy < @row_offset # sometimes r is 0, we are missing something in tabbedpane+scroll
#xx = @col_offset if xx < @col_offset
#xx = 0 if xx < 0
$log.debug " #{@name} printing CARET at #{yy},#{xx}: fwt:- #{@win_top} r:#{@row} tr:-#{@toprow}+ci:#{@current_index},+r #{r} "
if [email protected]?
@graphic.mvchgat(y=@oldcursorrow, x=@oldcursorcol, 1, Ncurses::A_NORMAL, $datacolor, NIL)
end
@oldcursorrow = yy
@oldcursorcol = xx
@graphic.mvchgat(y=yy, x=xx, 1, Ncurses::A_NORMAL, $reversecolor, nil)
@buffer_modified = true
end
|
ruby
|
{
"resource": ""
}
|
q23988
|
Canis.ListScrollable.next_match
|
train
|
def next_match char
data = get_content
row = focussed_index + 1
row.upto(data.length-1) do |ix|
#val = data[ix].chomp rescue return # 2010-01-05 15:28 crashed on trueclass
val = data[ix].to_s rescue return # 2010-01-05 15:28 crashed on trueclass
#if val[0,1] == char #and val != currval
if val[0,1].casecmp(char) == 0 #AND VAL != CURRval
return ix
end
end
row = focussed_index - 1
0.upto(row) do |ix|
#val = data[ix].chomp
val = data[ix].to_s
#if val[0,1] == char #and val != currval
if val[0,1].casecmp(char) == 0 #and val != currval
return ix
end
end
return -1
end
|
ruby
|
{
"resource": ""
}
|
q23989
|
Canis.ListScrollable._find_next
|
train
|
def _find_next regex=@last_regex, start = @search_found_ix, first_time = false
#raise "No previous search" if regex.nil?
warn "No previous search" and return if regex.nil?
#$log.debug " _find_next #{@search_found_ix} : #{@current_index}"
extra = 1 # first time search on current line, next time skip current line or else we get stuck.
extra = 0 if first_time
start ||= 0
fend = @list.size-1
if start != fend
start += extra unless start == fend # used to be +=1 so we don't get stuck in same row
@last_regex = regex
@search_start_ix = start
regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case
start.upto(fend) do |ix|
row1 = @list[ix].to_s
# 2011-09-29 crashing on a character F3 in log file
# 2013-03-20 - 18:25 187compat
if row1.respond_to? :encode
row = row1.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?")
else
row = row1
end
m=row.match(regex)
if !m.nil?
@find_offset = m.offset(0)[0]
@find_offset1 = m.offset(0)[1]
ix += (@_header_adjustment || 0)
@search_found_ix = ix
return ix
end
end
end
fend = start-1
start = 0
if @search_wrap
start.upto(fend) do |ix|
row = @list[ix].to_s
m=row.match(regex)
if !m.nil?
@find_offset = m.offset(0)[0]
@find_offset1 = m.offset(0)[1]
ix += (@_header_adjustment || 0)
@search_found_ix = ix
return ix
end
end
end
return nil
end
|
ruby
|
{
"resource": ""
}
|
q23990
|
Canis.ListScrollable._find_prev
|
train
|
def _find_prev regex=@last_regex, start = @search_found_ix, first_time = false
#TODO the firsttime part, see find_next
#raise "No previous search" if regex.nil?
warn "No previous search" and return if regex.nil?
#$log.debug " _find_prev #{@search_found_ix} : #{@current_index}"
if start != 0
start -= 1 unless start == 0
@last_regex = regex
@search_start_ix = start
regex = Regexp.new(regex, Regexp::IGNORECASE) if @search_case
start.downto(0) do |ix|
row = @list[ix].to_s
m=row.match(regex)
if !m.nil?
@find_offset = m.offset(0)[0]
@find_offset1 = m.offset(0)[1]
ix += (@_header_adjustment || 0)
@search_found_ix = ix
return ix
end
end
end
fend = start-1
start = @list.size-1
if @search_wrap
start.downto(fend) do |ix|
row = @list[ix].to_s
m=row.match(regex)
if !m.nil?
@find_offset = m.offset(0)[0]
@find_offset1 = m.offset(0)[1]
ix += (@_header_adjustment || 0)
@search_found_ix = ix
return ix
end
end
end
return nil
end
|
ruby
|
{
"resource": ""
}
|
q23991
|
Canis.ListScrollable.sanitize
|
train
|
def sanitize content #:nodoc:
if content.is_a? String
content.chomp!
# 2013-03-20 - 18:29 187compat
if content.respond_to? :encode
content.replace(content.encode("ASCII-8BIT", :invalid => :replace, :undef => :replace, :replace => "?"))
end
content.gsub!(/[\t\r\n]/, ' ') # don't display tab, newline
content.gsub!(/\n/, ' ') # don't display tab, newline
content.gsub!(/[^[:print:]]/, '') # don't display non print characters
else
content
end
end
|
ruby
|
{
"resource": ""
}
|
q23992
|
Canis.ListScrollable._convert_index_to_printable_row
|
train
|
def _convert_index_to_printable_row index=@current_index
r,c = rowcol
pos = _convert_index_to_visible_row(index)
return nil unless pos
pos = r + pos
return pos
end
|
ruby
|
{
"resource": ""
}
|
q23993
|
Canis.Tree.data
|
train
|
def data alist=nil
# if nothing passed, print an empty root, rather than crashing
alist = [] if alist.nil?
@data = alist # data given by user
case alist
when Array
@treemodel = Canis::DefaultTreeModel.new("/")
@treemodel.root.add alist
when Hash
@treemodel = Canis::DefaultTreeModel.new("/")
@treemodel.root.add alist
when TreeNode
# this is a root node
@treemodel = Canis::DefaultTreeModel.new(alist)
when DefaultTreeModel
@treemodel = alist
else
if alist.is_a? DefaultTreeModel
@treemodel = alist
else
raise ArgumentError, "Tree does not know how to handle #{alist.class} "
end
end
# we now have a tree
raise "I still don't have a tree" unless @treemodel
set_expanded_state(@treemodel.root, true)
convert_to_list @treemodel
# added on 2009-01-13 23:19 since updates are not automatic now
#@list.bind(:LIST_DATA_EVENT) { |e| list_data_changed() }
#create_default_list_selection_model TODO
fire_dimension_changed
self
end
|
ruby
|
{
"resource": ""
}
|
q23994
|
Canis.Tree.XXXpadrefresh
|
train
|
def XXXpadrefresh
top = @window.top
left = @window.left
sr = @startrow + top
sc = @startcol + left
# first do header always in first row
retval = FFI::NCurses.prefresh(@pad,0,@pcol, sr , sc , 2 , @cols+ sc );
# now print rest of data
# h is header_adjustment
h = 1
retval = FFI::NCurses.prefresh(@pad,@prow + h,@pcol, sr + h , sc , @rows + sr , @cols+ sc );
$log.warn "XXX: PADREFRESH #{retval}, #{@prow}, #{@pcol}, #{sr}, #{sc}, #{@rows+sr}, #{@cols+sc}." if retval == -1
# padrefresh can fail if width is greater than NCurses.COLS
end
|
ruby
|
{
"resource": ""
}
|
q23995
|
Cream::View.Role.area_for_roles
|
train
|
def area_for_roles(*user_roles, &block)
options = last_option(user_roles)
return area(&block) if user_roles.empty?
not_for_roles(user_roles, &block) if user_roles.first == false
for_roles user_roles do
area(options, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q23996
|
Cream::View.Role.area_not_for_roles
|
train
|
def area_not_for_roles(*user_roles, &block)
options = last_option(user_roles)
not_for_roles user_roles do
clazz = options[:class] || 'special'
area(:class => clazz, &block)
end
end
|
ruby
|
{
"resource": ""
}
|
q23997
|
Openapi2ruby.Generator.generate
|
train
|
def generate(output_path, template_path)
template_path = TEMPLATE_PATH if template_path.nil?
template = File.read(template_path)
generated_class = ERB.new(template, nil, '-').result(binding)
output_file = Pathname.new(output_path).join("#{@schema.name.underscore}_serializer.rb")
File.open(output_file.to_s, 'w') { |file| file << generated_class }
output_file.to_s
end
|
ruby
|
{
"resource": ""
}
|
q23998
|
Handshake.ClauseMethods.responds_to?
|
train
|
def responds_to?(*methods)
respond_assertions = methods.map do |m|
clause("responds to #{m}") { |o| o.respond_to? m }
end
all?(*respond_assertions)
end
|
ruby
|
{
"resource": ""
}
|
q23999
|
Openapi2ruby.Openapi.schemas
|
train
|
def schemas
@content['components']['schemas'].each_with_object([]) do |(key, value), results|
schema_content = { name: key, definition: value}
schema = Openapi2ruby::Openapi::Schema.new(schema_content)
results << schema unless schema.properties.empty?
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.