_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q26700
|
Aerospike.Command.write_header
|
test
|
def write_header(policy, read_attr, write_attr, field_count, operation_count)
read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL
# Write all header data except total size which must be written last.
@data_buffer.write_byte(MSG_REMAINING_HEADER_SIZE, 8) # Message heade.length.
@data_buffer.write_byte(read_attr, 9)
@data_buffer.write_byte(write_attr, 10)
i = 11
|
ruby
|
{
"resource": ""
}
|
q26701
|
Aerospike.Command.write_header_with_policy
|
test
|
def write_header_with_policy(policy, read_attr, write_attr, field_count, operation_count)
# Set flags.
generation = Integer(0)
info_attr = Integer(0)
case policy.record_exists_action
when Aerospike::RecordExistsAction::UPDATE
when Aerospike::RecordExistsAction::UPDATE_ONLY
info_attr |= INFO3_UPDATE_ONLY
when Aerospike::RecordExistsAction::REPLACE
info_attr |= INFO3_CREATE_OR_REPLACE
when Aerospike::RecordExistsAction::REPLACE_ONLY
info_attr |= INFO3_REPLACE_ONLY
when Aerospike::RecordExistsAction::CREATE_ONLY
write_attr |= INFO2_CREATE_ONLY
end
case policy.generation_policy
when Aerospike::GenerationPolicy::NONE
when Aerospike::GenerationPolicy::EXPECT_GEN_EQUAL
generation = policy.generation
write_attr |= INFO2_GENERATION
when Aerospike::GenerationPolicy::EXPECT_GEN_GT
generation = policy.generation
write_attr |= INFO2_GENERATION_GT
end
info_attr |= INFO3_COMMIT_MASTER if policy.commit_level == Aerospike::CommitLevel::COMMIT_MASTER
read_attr |= INFO1_CONSISTENCY_ALL if policy.consistency_level == Aerospike::ConsistencyLevel::CONSISTENCY_ALL
write_attr |= INFO2_DURABLE_DELETE
|
ruby
|
{
"resource": ""
}
|
q26702
|
Aerospike.ExecuteTask.all_nodes_done?
|
test
|
def all_nodes_done?
if @scan
command = 'scan-list'
else
command = 'query-list'
end
nodes = @cluster.nodes
done = false
nodes.each do |node|
conn = node.get_connection(0)
responseMap, _ = Info.request(conn, command)
node.put_connection(conn)
response = responseMap[command]
find = "job_id=#{@task_id}:"
index = response.index(find)
unless index
|
ruby
|
{
"resource": ""
}
|
q26703
|
Aerospike.Node.get_connection
|
test
|
def get_connection(timeout)
loop do
conn = @connections.poll
if conn.connected?
|
ruby
|
{
"resource": ""
}
|
q26704
|
Aerospike.MultiCommand.parse_record
|
test
|
def parse_record(key, op_count, generation, expiration)
bins = op_count > 0 ? {} : nil
i = 0
while i < op_count
raise Aerospike::Exceptions::QueryTerminated.new unless valid?
read_bytes(8)
op_size = @data_buffer.read_int32(0).ord
particle_type = @data_buffer.read(5).ord
name_size = @data_buffer.read(7).ord
read_bytes(name_size)
name = @data_buffer.read(0, name_size).force_encoding('utf-8')
|
ruby
|
{
"resource": ""
}
|
q26705
|
Aerospike.Cluster.random_node
|
test
|
def random_node
# Must copy array reference for copy on write semantics to work.
node_array = nodes
length = node_array.length
i = 0
while i < length
# Must handle concurrency with other non-tending threads, so node_index is consistent.
index
|
ruby
|
{
"resource": ""
}
|
q26706
|
Aerospike.Cluster.get_node_by_name
|
test
|
def get_node_by_name(node_name)
node = find_node_by_name(node_name)
|
ruby
|
{
"resource": ""
}
|
q26707
|
Aerospike.Client.prepend
|
test
|
def prepend(key, bins, options = nil)
policy = create_policy(options, WritePolicy, default_write_policy)
command = WriteCommand.new(@cluster,
|
ruby
|
{
"resource": ""
}
|
q26708
|
Aerospike.Client.get_header
|
test
|
def get_header(key, options = nil)
policy = create_policy(options, Policy, default_read_policy)
command = ReadHeaderCommand.new(@cluster,
|
ruby
|
{
"resource": ""
}
|
q26709
|
Aerospike.Client.batch_exists
|
test
|
def batch_exists(keys, options = nil)
policy = create_policy(options, BatchPolicy, default_batch_policy)
results = Array.new(keys.length)
if policy.use_batch_direct
key_map = BatchItem.generate_map(keys)
execute_batch_direct_commands(keys) do |node, batch|
BatchDirectExistsCommand.new(node, batch, policy, key_map, results)
end
|
ruby
|
{
"resource": ""
}
|
q26710
|
Aerospike.Client.register_udf
|
test
|
def register_udf(udf_body, server_path, language, options = nil)
policy = create_policy(options, Policy, default_info_policy)
content = Base64.strict_encode64(udf_body).force_encoding('binary')
str_cmd = "udf-put:filename=#{server_path};content=#{content};"
str_cmd << "content-len=#{content.length};udf-type=#{language};"
# Send UDF to one node. That node will distribute the UDF to other nodes.
response_map = @cluster.request_info(policy, str_cmd)
res = {}
response_map.each do |k, response|
vals = response.to_s.split(';')
vals.each do |pair|
k, v =
|
ruby
|
{
"resource": ""
}
|
q26711
|
Aerospike.Client.remove_udf
|
test
|
def remove_udf(udf_name, options = nil)
policy = create_policy(options, Policy, default_info_policy)
str_cmd = "udf-remove:filename=#{udf_name};"
# Send command to one node. That node will distribute it to other nodes.
# Send UDF to one node. That node will distribute the UDF to other nodes.
response_map = @cluster.request_info(policy, str_cmd)
_, response = response_map.first
|
ruby
|
{
"resource": ""
}
|
q26712
|
Aerospike.Client.list_udf
|
test
|
def list_udf(options = nil)
policy = create_policy(options, Policy, default_info_policy)
str_cmd = 'udf-list'
# Send command to one node. That node will distribute it to other nodes.
response_map = @cluster.request_info(policy, str_cmd)
_, response = response_map.first
vals = response.split(';')
vals.map do |udf_info|
next if udf_info.strip! == ''
udf_parts = udf_info.split(',')
udf = UDF.new
udf_parts.each do |values|
k,
|
ruby
|
{
"resource": ""
}
|
q26713
|
Aerospike.Client.execute_udf_on_query
|
test
|
def execute_udf_on_query(statement, package_name, function_name, function_args=[], options = nil)
policy = create_policy(options, QueryPolicy, default_query_policy)
nodes = @cluster.nodes
if nodes.empty?
raise Aerospike::Exceptions::Aerospike.new(Aerospike::ResultCode::SERVER_NOT_AVAILABLE, "Executing UDF failed because cluster is empty.")
end
# TODO: wait until all migrations are finished
statement.set_aggregate_function(package_name, function_name, function_args, false)
# Use a thread per node
nodes.each do |node|
Thread.new do
Thread.current.abort_on_exception = true
|
ruby
|
{
"resource": ""
}
|
q26714
|
Aerospike.Client.create_index
|
test
|
def create_index(namespace, set_name, index_name, bin_name, index_type, collection_type = nil, options = nil)
if options.nil? && collection_type.is_a?(Hash)
options, collection_type = collection_type, nil
end
policy = create_policy(options, Policy, default_info_policy)
str_cmd = "sindex-create:ns=#{namespace}"
str_cmd << ";set=#{set_name}" unless set_name.to_s.strip.empty?
str_cmd << ";indexname=#{index_name};numbins=1"
str_cmd << ";indextype=#{collection_type.to_s.upcase}" if collection_type
str_cmd << ";indexdata=#{bin_name},#{index_type.to_s.upcase}"
str_cmd << ";priority=normal"
# Send index command to one node. That node will distribute the command to other nodes.
response = send_info_command(policy, str_cmd).upcase
if response == 'OK'
# Return
|
ruby
|
{
"resource": ""
}
|
q26715
|
Aerospike.Client.drop_index
|
test
|
def drop_index(namespace, set_name, index_name, options = nil)
policy = create_policy(options, Policy, default_info_policy)
str_cmd = "sindex-delete:ns=#{namespace}"
str_cmd << ";set=#{set_name}" unless set_name.to_s.strip.empty?
str_cmd << ";indexname=#{index_name}"
# Send index command to one node. That node will distribute the command to other nodes.
response = send_info_command(policy, str_cmd).upcase
|
ruby
|
{
"resource": ""
}
|
q26716
|
Aerospike.Client.scan_node
|
test
|
def scan_node(node, namespace, set_name, bin_names = nil, options = nil)
policy = create_policy(options, ScanPolicy, default_scan_policy)
# wait until all migrations are finished
# TODO: implement
# @cluster.WaitUntillMigrationIsFinished(policy.timeout)
# Retry policy must be one-shot for scans.
# copy on write for policy
new_policy = policy.clone
new_policy.max_retries = 0
node = @cluster.get_node_by_name(node) unless node.is_a?(Aerospike::Node)
recordset = Recordset.new(policy.record_queue_size, 1, :scan)
Thread.new do
|
ruby
|
{
"resource": ""
}
|
q26717
|
Aerospike.Client.drop_user
|
test
|
def drop_user(user, options = nil)
policy = create_policy(options, AdminPolicy, default_admin_policy)
command =
|
ruby
|
{
"resource": ""
}
|
q26718
|
Aerospike.Client.change_password
|
test
|
def change_password(user, password, options = nil)
raise Aerospike::Exceptions::Aerospike.new(INVALID_USER) unless @cluster.user && @cluster.user != ""
policy = create_policy(options, AdminPolicy, default_admin_policy)
hash = AdminCommand.hash_password(password)
command = AdminCommand.new
if user == @cluster.user
# Change own password.
|
ruby
|
{
"resource": ""
}
|
q26719
|
Aerospike.Client.grant_roles
|
test
|
def grant_roles(user, roles, options = nil)
policy = create_policy(options, AdminPolicy, default_admin_policy)
command =
|
ruby
|
{
"resource": ""
}
|
q26720
|
Aerospike.Client.query_users
|
test
|
def query_users(options = nil)
policy = create_policy(options, AdminPolicy, default_admin_policy)
command =
|
ruby
|
{
"resource": ""
}
|
q26721
|
Aerospike.Recordset.next_record
|
test
|
def next_record
raise @thread_exception.get unless @thread_exception.get.nil?
r =
|
ruby
|
{
"resource": ""
}
|
q26722
|
Aerospike.Recordset.each
|
test
|
def each(&block)
r = true
while r
r = next_record
# nil means EOF
unless r.nil?
block.call(r)
else
|
ruby
|
{
"resource": ""
}
|
q26723
|
IntercomRails.ScriptTagHelper.intercom_script_tag
|
test
|
def intercom_script_tag(user_details = nil, options={})
controller.instance_variable_set(IntercomRails::SCRIPT_TAG_HELPER_CALLED_INSTANCE_VARIABLE, true) if defined?(controller)
options[:user_details] = user_details if user_details.present?
options[:find_current_user_details] = !options[:user_details]
|
ruby
|
{
"resource": ""
}
|
q26724
|
MiniGL.Movement.move_free
|
test
|
def move_free(aim, speed)
if aim.is_a? Vector
x_d = aim.x - @x; y_d = aim.y - @y
distance = Math.sqrt(x_d**2 + y_d**2)
if distance == 0
@speed.x = @speed.y = 0
return
end
@speed.x = 1.0 * x_d * speed / distance
@speed.y = 1.0 * y_d * speed / distance
if (@speed.x < 0 and @x + @speed.x <= aim.x) or (@speed.x >= 0 and @x + @speed.x >= aim.x)
@x = aim.x
@speed.x = 0
else
@x += @speed.x
end
|
ruby
|
{
"resource": ""
}
|
q26725
|
MiniGL.Map.get_absolute_size
|
test
|
def get_absolute_size
return Vector.new(@tile_size.x * @size.x, @tile_size.y * @size.y) unless @isometric
avg = (@size.x + @size.y) * 0.5
|
ruby
|
{
"resource": ""
}
|
q26726
|
MiniGL.Map.get_screen_pos
|
test
|
def get_screen_pos(map_x, map_y)
return Vector.new(map_x * @tile_size.x - @cam.x, map_y * @tile_size.y - @cam.y) unless @isometric
Vector.new ((map_x - map_y - 1) * @tile_size.x * 0.5)
|
ruby
|
{
"resource": ""
}
|
q26727
|
MiniGL.Map.get_map_pos
|
test
|
def get_map_pos(scr_x, scr_y)
return Vector.new((scr_x + @cam.x) / @tile_size.x, (scr_y + @cam.y) / @tile_size.y) unless @isometric
# Gets the position transformed to isometric coordinates
v = get_isometric_position scr_x, scr_y
|
ruby
|
{
"resource": ""
}
|
q26728
|
MiniGL.Map.is_in_map
|
test
|
def is_in_map(v)
v.x >= 0 && v.y >= 0 &&
|
ruby
|
{
"resource": ""
}
|
q26729
|
MiniGL.Sprite.animate_once
|
test
|
def animate_once(indices, interval)
if @animate_once_control == 2
return if indices == @animate_once_indices && interval == @animate_once_interval
@animate_once_control = 0
end
unless @animate_once_control == 1
@anim_counter = 0
@img_index = indices[0]
@index_index = 0
@animate_once_indices = indices
@animate_once_interval = interval
@animate_once_control = 1
return
end
@anim_counter += 1
|
ruby
|
{
"resource": ""
}
|
q26730
|
MiniGL.Sprite.draw
|
test
|
def draw(map = nil, scale_x = 1, scale_y = 1, alpha = 0xff, color = 0xffffff, angle = nil, flip = nil, z_index = 0, round = false)
if map.is_a? Hash
scale_x = map.fetch(:scale_x, 1)
scale_y = map.fetch(:scale_y, 1)
alpha = map.fetch(:alpha, 0xff)
color = map.fetch(:color, 0xffffff)
angle = map.fetch(:angle, nil)
flip = map.fetch(:flip, nil)
z_index = map.fetch(:z_index, 0)
round = map.fetch(:round, false)
map = map.fetch(:map, nil)
end
color = (alpha << 24) | color
if angle
@img[@img_index].draw_rot @x - (map ? map.cam.x : 0) + @img[0].width * scale_x * 0.5,
@y - (map ? map.cam.y : 0) + @img[0].height * scale_y * 0.5,
z_index, angle, 0.5, 0.5, (flip == :horiz ? -scale_x : scale_x),
|
ruby
|
{
"resource": ""
}
|
q26731
|
MiniGL.Button.update
|
test
|
def update
return unless @enabled and @visible
mouse_over = Mouse.over? @x, @y, @w, @h
mouse_press = Mouse.button_pressed? :left
mouse_rel = Mouse.button_released? :left
if @state == :up
if mouse_over
@img_index = 1
@state = :over
else
@img_index = 0
end
elsif @state == :over
if not mouse_over
@img_index = 0
@state = :up
elsif mouse_press
@img_index = 2
@state = :down
else
@img_index = 1
end
elsif @state == :down
if not mouse_over
@img_index = 0
@state = :down_out
elsif mouse_rel
|
ruby
|
{
"resource": ""
}
|
q26732
|
MiniGL.Button.draw
|
test
|
def draw(alpha = 0xff, z_index = 0, color = 0xffffff)
return unless @visible
color = (alpha << 24) | color
text_color =
if @enabled
if @state == :down
@down_text_color
else
@state == :over ? @over_text_color : @text_color
end
else
@disabled_text_color
end
text_color = (alpha << 24) | text_color
@img[@img_index].draw @x, @y, z_index, @scale_x, @scale_y, color if @img
if @text
if @center_x or @center_y
rel_x = @center_x ? 0.5 :
|
ruby
|
{
"resource": ""
}
|
q26733
|
MiniGL.TextField.text=
|
test
|
def text=(value, trigger_changed = true)
@text = value[0...@max_length]
@nodes.clear; @nodes << @text_x
x = @nodes[0]
@text.chars.each { |char|
x += @font.text_width(char) * @scale_x
@nodes << x
}
@cur_node = @nodes.size - 1
|
ruby
|
{
"resource": ""
}
|
q26734
|
MiniGL.TextField.set_position
|
test
|
def set_position(x, y)
d_x = x - @x
d_y = y - @y
@x = x; @y = y
@text_x += d_x
|
ruby
|
{
"resource": ""
}
|
q26735
|
MiniGL.TextField.draw
|
test
|
def draw(alpha = 0xff, z_index = 0, color = 0xffffff, disabled_color = 0x808080)
return unless @visible
color = (alpha << 24) | ((@enabled or @disabled_img) ? color : disabled_color)
text_color = (alpha << 24) | (@enabled ? @text_color : @disabled_text_color)
img = ((@enabled or @disabled_img.nil?) ? @img : @disabled_img)
img.draw @x, @y, z_index, @scale_x, @scale_y, color
@font.draw_text @text, @text_x, @text_y, z_index, @scale_x, @scale_y, text_color
if @anchor1 and @anchor2
selection_color = ((alpha / 2) << 24) | @selection_color
G.window.draw_quad @nodes[@anchor1], @text_y, selection_color,
@nodes[@anchor2] + 1, @text_y, selection_color,
@nodes[@anchor2] + 1, @text_y + @font.height * @scale_y, selection_color,
@nodes[@anchor1], @text_y + @font.height * @scale_y, selection_color, z_index
end
if @cursor_visible
if @cursor_img
@cursor_img.draw @nodes[@cur_node] - (@cursor_img.width *
|
ruby
|
{
"resource": ""
}
|
q26736
|
MiniGL.ProgressBar.draw
|
test
|
def draw(alpha = 0xff, z_index = 0, color = 0xffffff)
return unless @visible
if @bg
c = (alpha << 24) | color
@bg.draw @x, @y, z_index, @scale_x, @scale_y, c
else
c = (alpha << 24) | @bg_color
G.window.draw_quad @x, @y, c,
@x + @w, @y, c,
@x + @w, @y + @h, c,
@x, @y + @h, c, z_index
end
if @fg
c = (alpha << 24) | color
w1 = @fg.width * @scale_x
w2 = (@value.to_f / @max_value * @w).round
x0 = @x + @fg_margin_x
x = 0
while x <= w2 - w1
@fg.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c
x += w1
end
if w2 - x > 0
img = Gosu::Image.new(@fg_path, tileable: true, retro: @retro, rect: [0, 0, ((w2 - x) / @scale_x).round, @fg.height])
img.draw x0 + x, @y + @fg_margin_y, z_index, @scale_x, @scale_y, c
end
else
c = (alpha << 24) | @fg_color
|
ruby
|
{
"resource": ""
}
|
q26737
|
MiniGL.DropDownList.update
|
test
|
def update
return unless @enabled and @visible
if @open and Mouse.button_pressed? :left and not Mouse.over?(@x, @y, @w, @max_h)
toggle
|
ruby
|
{
"resource": ""
}
|
q26738
|
MiniGL.DropDownList.value=
|
test
|
def value=(val)
if @options.include? val
old = @value
@value = @buttons[0].text = val
|
ruby
|
{
"resource": ""
}
|
q26739
|
MiniGL.DropDownList.draw
|
test
|
def draw(alpha = 0xff, z_index = 0, color = 0xffffff, over_color = 0xcccccc)
return unless @visible
unless @img
bottom = @y + (@open ? @max_h : @h) + @scale_y
b_color = (alpha << 24)
G.window.draw_quad @x - @scale_x, @y - @scale_y, b_color,
@x + @w + @scale_x, @y - @scale_y, b_color,
@x + @w + @scale_x, bottom, b_color,
@x - @scale_x, bottom, b_color, z_index
@buttons.each do |b|
c = (alpha << 24) | (b.state == :over ? over_color : color)
|
ruby
|
{
"resource": ""
}
|
q26740
|
MiniGL.Label.draw
|
test
|
def draw(alpha = 255, z_index = 0, color = 0xffffff)
c = @enabled ? @text_color : @disabled_text_color
r1 = c >> 16
g1 = (c & 0xff00) >> 8
b1 = (c & 0xff)
r2 = color >> 16
g2 = (color & 0xff00) >> 8
b2 = (color & 0xff)
r1 *= r2; r1
|
ruby
|
{
"resource": ""
}
|
q26741
|
MiniGL.TextHelper.write_line
|
test
|
def write_line(text, x = nil, y = nil, mode = :left, color = 0, alpha = 0xff,
effect = nil, effect_color = 0, effect_size = 1, effect_alpha = 0xff,
z_index = 0)
if text.is_a? Hash
x = text[:x]
y = text[:y]
mode = text.fetch(:mode, :left)
color = text.fetch(:color, 0)
alpha = text.fetch(:alpha, 0xff)
effect = text.fetch(:effect, nil)
effect_color = text.fetch(:effect_color, 0)
effect_size = text.fetch(:effect_size, 1)
effect_alpha = text.fetch(:effect_alpha, 0xff)
z_index = text.fetch(:z_index, 0)
text = text[:text]
end
color = (alpha << 24) | color
rel =
case mode
when :left then 0
when :center then 0.5
when :right then 1
else 0
end
if effect
effect_color = (effect_alpha << 24) | effect_color
if effect == :border
@font.draw_markup_rel text, x - effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color
@font.draw_markup_rel text, x, y - effect_size, z_index, rel, 0, 1, 1, effect_color
@font.draw_markup_rel text, x + effect_size, y - effect_size, z_index, rel, 0, 1, 1, effect_color
@font.draw_markup_rel text, x + effect_size, y, z_index, rel, 0,
|
ruby
|
{
"resource": ""
}
|
q26742
|
MiniGL.TextHelper.write_breaking
|
test
|
def write_breaking(text, x, y, width, mode = :left, color = 0, alpha = 0xff, z_index = 0)
color = (alpha << 24) | color
text.split("\n").each do |p|
if mode == :justified
y = write_paragraph_justified p, x, y, width, color, z_index
else
rel =
case mode
when :left then 0
when :center then 0.5
|
ruby
|
{
"resource": ""
}
|
q26743
|
Fit4Ruby.FitMessageIdMapper.add_global
|
test
|
def add_global(message)
unless (slot = @entries.index { |e| e.nil? })
# No more free slots. We have to find the least recently used one.
slot = 0
0.upto(15) do |i|
if i != slot && @entries[slot].last_use > @entries[i].last_use
|
ruby
|
{
"resource": ""
}
|
q26744
|
Fit4Ruby.FitMessageIdMapper.get_local
|
test
|
def get_local(message)
0.upto(15) do |i|
if (entry = @entries[i]) && entry.global_message == message
|
ruby
|
{
"resource": ""
}
|
q26745
|
Fit4Ruby.Monitoring_B.check
|
test
|
def check
last_timestamp = ts_16_offset = nil
last_ts_16 = nil
# The timestamp_16 is a 2 byte time stamp value that is used instead of
# the 4 byte timestamp field for monitoring records that have
# current_activity_type_intensity values with an activity type of 6. The
# value seems to be in seconds, but the 0 value reference does not seem
# to be included in the file. However, it can be approximated using the
# surrounding timestamp values.
@monitorings.each do |record|
if last_ts_16 && ts_16_offset && record.timestamp_16 &&
record.timestamp_16 < last_ts_16
# Detect timestamp_16 wrap-arounds. timestamp_16 is a 16 bit value.
# In case of a wrap-around we adjust the ts_16_offset accordingly.
ts_16_offset += 2 ** 16
end
if ts_16_offset
# We have already found the offset. Adjust all timestamps according
# to 'offset + timestamp_16'
if record.timestamp_16
record.timestamp = ts_16_offset + record.timestamp_16
last_ts_16 = record.timestamp_16
end
else
#
|
ruby
|
{
"resource": ""
}
|
q26746
|
Fit4Ruby.FieldDescription.create_global_definition
|
test
|
def create_global_definition(fit_entity)
messages = fit_entity.developer_fit_messages
unless (gfm = GlobalFitMessages[@native_mesg_num])
Log.error "Developer field description references unknown global " +
"message number #{@native_mesg_num}"
return
end
if @developer_data_index >=
fit_entity.top_level_record.developer_data_ids.size
Log.error "Developer data index #{@developer_data_index} is too large"
return
end
msg = messages[@native_mesg_num] ||
messages.message(@native_mesg_num, gfm.name)
unless (@fit_base_type_id & 0x7F) < FIT_TYPE_DEFS.size
Log.error "fit_base_type_id #{@fit_base_type_id} is too large"
|
ruby
|
{
"resource": ""
}
|
q26747
|
Fit4Ruby.DeviceInfo.check
|
test
|
def check(index)
unless @device_index
Log.fatal 'device info record must have a device_index'
end
if @device_index == 0
unless @manufacturer
Log.fatal 'device info record 0 must have a manufacturer field set'
end
if @manufacturer == 'garmin'
unless @garmin_product
Log.fatal 'device info record 0 must have a garman_product ' +
'field set'
end
|
ruby
|
{
"resource": ""
}
|
q26748
|
Fit4Ruby.ILogger.open
|
test
|
def open(io)
begin
@@logger = Logger.new(io)
rescue => e
@@logger = Logger.new($stderr)
|
ruby
|
{
"resource": ""
}
|
q26749
|
Fit4Ruby.FitFileEntity.set_type
|
test
|
def set_type(type)
if @top_level_record
Log.fatal "FIT file type has already been set to " +
"#{@top_level_record.class}"
end
case type
when 4, 'activity'
@top_level_record = Activity.new
@type = 'activity'
when 32, 'monitoring_b'
@top_level_record = Monitoring_B.new
|
ruby
|
{
"resource": ""
}
|
q26750
|
Fit4Ruby.Activity.check
|
test
|
def check
unless @timestamp && @timestamp >= Time.parse('1990-01-01T00:00:00+00:00')
Log.fatal "Activity has no valid timestamp"
end
unless @total_timer_time
Log.fatal "Activity has no valid total_timer_time"
end
unless @device_infos.length > 0
Log.fatal "Activity must have at least one device_info section"
end
@device_infos.each.with_index { |d, index| d.check(index) }
@sensor_settings.each.with_index { |s, index| s.check(index) }
unless @num_sessions == @sessions.count
Log.fatal "Activity record requires #{@num_sessions}, but "
"#{@sessions.length} session records were found in the "
"FIT file."
end
# Records must have consecutively growing timestamps and distances.
ts = Time.parse('1989-12-31')
distance = nil
invalid_records = []
@records.each_with_index do |r, idx|
Log.fatal "Record has no timestamp" unless r.timestamp
if r.timestamp < ts
Log.fatal "Record has earlier timestamp than previous record"
end
if r.distance
if distance && r.distance < distance
# Normally this should be a fatal error as the FIT file is clearly
# broken. Unfortunately, the Skiing/Boarding app in the Fenix3
# produces such broken FIT files. So we just warn about this
# problem and discard the earlier records.
Log.error "Record #{r.timestamp} has smaller distance " +
"(#{r.distance}) than an earlier record (#{distance})."
# Index of the list record to be discarded.
(idx - 1).downto(0) do |i|
if (ri = @records[i]).distance > r.distance
# This is just an approximation. It looks like the app adds
# records to the FIT file for runs that it meant to discard.
# Maybe the two successive time start events are a better
|
ruby
|
{
"resource": ""
}
|
q26751
|
Fit4Ruby.Activity.total_gps_distance
|
test
|
def total_gps_distance
timer_stops = []
# Generate a list of all timestamps where the timer was stopped.
@events.each do |e|
if e.event == 'timer' && e.event_type == 'stop_all'
timer_stops << e.timestamp
end
end
# The first record of a FIT file can already have a distance associated
# with it. The GPS location of the first record is not where the start
# button was pressed. This introduces a slight inaccurcy when computing
# the total distance purely on the GPS coordinates found in the records.
d = 0.0
last_lat = last_long = nil
last_timestamp = nil
# Iterate over all the records and accumlate the distances between the
# neiboring coordinates.
@records.each do |r|
if (lat = r.position_lat) && (long = r.position_long)
if last_lat && last_long
distance = Fit4Ruby::GeoMath.distance(last_lat, last_long,
lat, long)
d += distance
|
ruby
|
{
"resource": ""
}
|
q26752
|
Fit4Ruby.Activity.vo2max
|
test
|
def vo2max
# First check the event log for a vo2max reporting event.
@events.each do |e|
return e.vo2max if e.event == 'vo2max'
end
# Then check the user_data entries for a metmax entry. METmax * 3.5
# is same value
|
ruby
|
{
"resource": ""
}
|
q26753
|
Fit4Ruby.Activity.write
|
test
|
def write(io, id_mapper)
@file_id.write(io, id_mapper)
@file_creator.write(io, id_mapper)
(@field_descriptions + @developer_data_ids +
@device_infos + @sensor_settings +
|
ruby
|
{
"resource": ""
}
|
q26754
|
Fit4Ruby.Activity.new_fit_data_record
|
test
|
def new_fit_data_record(record_type, field_values = {})
case record_type
when 'file_id'
@file_id = (record = FileId.new(field_values))
when 'field_description'
@field_descriptions << (record = FieldDescription.new(field_values))
when 'developer_data_id'
@developer_data_ids << (record = DeveloperDataId.new(field_values))
when 'epo_data'
@epo_data = (record = EPO_Data.new(field_values))
when 'file_creator'
@file_creator = (record = FileCreator.new(field_values))
when 'device_info'
@device_infos << (record = DeviceInfo.new(field_values))
when 'sensor_settings'
@sensor_settings << (record = SensorSettings.new(field_values))
when 'data_sources'
@data_sources << (record = DataSources.new(field_values))
when 'user_data'
@user_data << (record = UserData.new(field_values))
when 'user_profile'
@user_profiles << (record = UserProfile.new(field_values))
when 'physiological_metrics'
@physiological_metrics <<
(record = PhysiologicalMetrics.new(field_values))
when 'event'
@events << (record = Event.new(field_values))
when 'session'
unless @cur_lap_records.empty?
# Copy selected fields from section to lap.
lap_field_values = {}
[ :timestamp, :sport ].each do |f|
lap_field_values[f] = field_values[f] if
|
ruby
|
{
"resource": ""
}
|
q26755
|
Fit4Ruby.Session.check
|
test
|
def check(activity)
unless @first_lap_index
Log.fatal 'first_lap_index is not set'
end
unless @num_laps
Log.fatal 'num_laps is not set'
end
@first_lap_index.upto(@first_lap_index - @num_laps) do |i|
if (lap = activity.lap[i])
@laps << lap
|
ruby
|
{
"resource": ""
}
|
q26756
|
Fit4Ruby.GlobalFitMessage.field
|
test
|
def field(number, type, name, opts = {})
field = Field.new(type, name, opts)
register_field_by_name(field, name)
|
ruby
|
{
"resource": ""
}
|
q26757
|
Fit4Ruby.GlobalFitMessage.alt_field
|
test
|
def alt_field(number, ref_field, &block)
unless @fields_by_name.include?(ref_field)
raise "Unknown ref_field: #{ref_field}"
end
field
|
ruby
|
{
"resource": ""
}
|
q26758
|
MailForm.Delivery.spam?
|
test
|
def spam?
self.class.mail_captcha.each do |field|
next if send(field).blank?
if defined?(Rails) && Rails.env.development?
|
ruby
|
{
"resource": ""
}
|
q26759
|
MailForm.Delivery.deliver!
|
test
|
def deliver!
mailer = MailForm::Notifier.contact(self)
if mailer.respond_to?(:deliver_now)
|
ruby
|
{
"resource": ""
}
|
q26760
|
MailForm.Delivery.mail_form_attributes
|
test
|
def mail_form_attributes
self.class.mail_attributes.each_with_object({}) do |attr, hash|
|
ruby
|
{
"resource": ""
}
|
q26761
|
SolrWrapper.Instance.start
|
test
|
def start
extract_and_configure
if config.managed?
exec('start', p: port, c: config.cloud)
|
ruby
|
{
"resource": ""
}
|
q26762
|
SolrWrapper.Instance.restart
|
test
|
def restart
if config.managed? && started?
exec('restart',
|
ruby
|
{
"resource": ""
}
|
q26763
|
SolrWrapper.Instance.create
|
test
|
def create(options = {})
options[:name] ||= SecureRandom.hex
create_options = { p: port }
create_options[:c] = options[:name] if options[:name]
create_options[:n] = options[:config_name] if options[:config_name]
create_options[:d] = options[:dir] if options[:dir]
Retriable.retriable do
raise "Not started yet" unless started?
end
|
ruby
|
{
"resource": ""
}
|
q26764
|
SolrWrapper.Instance.upconfig
|
test
|
def upconfig(options = {})
options[:name] ||= SecureRandom.hex
options[:zkhost] ||= zkhost
upconfig_options = { upconfig: true, n: options[:name] }
upconfig_options[:d] = options[:dir] if options[:dir]
|
ruby
|
{
"resource": ""
}
|
q26765
|
SolrWrapper.Instance.downconfig
|
test
|
def downconfig(options = {})
options[:name] ||= SecureRandom.hex
options[:zkhost] ||= zkhost
downconfig_options = { downconfig: true, n: options[:name] }
downconfig_options[:d] = options[:dir] if options[:dir]
|
ruby
|
{
"resource": ""
}
|
q26766
|
SolrWrapper.Instance.with_collection
|
test
|
def with_collection(options = {})
options = config.collection_options.merge(options)
return yield if options.empty?
name = create(options)
|
ruby
|
{
"resource": ""
}
|
q26767
|
SolrWrapper.Instance.clean!
|
test
|
def clean!
stop
remove_instance_dir!
FileUtils.remove_entry(config.download_dir, true) if File.exist?(config.download_dir)
|
ruby
|
{
"resource": ""
}
|
q26768
|
Qt.MetaInfo.get_signals
|
test
|
def get_signals
all_signals = []
current = @klass
while current != Qt::Base
meta = Meta[current.name]
if !meta.nil?
|
ruby
|
{
"resource": ""
}
|
q26769
|
MotionSupport.Duration.+
|
test
|
def +(other)
if Duration === other
Duration.new(value + other.value, @parts + other.parts)
else
|
ruby
|
{
"resource": ""
}
|
q26770
|
DateAndTime.Calculations.days_to_week_start
|
test
|
def days_to_week_start(start_day = Date.beginning_of_week)
start_day_number = DAYS_INTO_WEEK[start_day]
current_day_number = wday
|
ruby
|
{
"resource": ""
}
|
q26771
|
TTY.ProgressBar.reset
|
test
|
def reset
@width = 0 if no_width
@render_period = frequency == 0 ? 0 : 1.0 / frequency
@current = 0
@last_render_time = Time.now
@last_render_width = 0
@done = false
|
ruby
|
{
"resource": ""
}
|
q26772
|
TTY.ProgressBar.advance
|
test
|
def advance(progress = 1, tokens = {})
return if done?
synchronize do
emit(:progress, progress)
if progress.respond_to?(:to_hash)
tokens, progress = progress, 1
end
@start_at = Time.now if @current.zero? && !@started
@current += progress
@tokens = tokens
|
ruby
|
{
"resource": ""
}
|
q26773
|
TTY.ProgressBar.iterate
|
test
|
def iterate(collection, progress = 1, &block)
update(total: collection.count * progress) unless total
progress_enum = Enumerator.new do |iter|
|
ruby
|
{
"resource": ""
}
|
q26774
|
TTY.ProgressBar.update
|
test
|
def update(options = {})
synchronize do
options.each do |name, val|
if @configuration.respond_to?("#{name}=")
|
ruby
|
{
"resource": ""
}
|
q26775
|
TTY.ProgressBar.render
|
test
|
def render
return if done?
if hide_cursor && @last_render_width == 0 && !(@current >= total)
write(TTY::Cursor.hide)
end
if @multibar
characters_in = @multibar.line_inset(self)
update(inset: self.class.display_columns(characters_in))
end
formatted = @formatter.decorate(self, @format)
@tokens.each do |token, val|
|
ruby
|
{
"resource": ""
}
|
q26776
|
TTY.ProgressBar.move_to_row
|
test
|
def move_to_row
if @multibar
CURSOR_LOCK.synchronize do
if @first_render
@row = @multibar.next_row
yield if block_given?
output.print "\n"
@first_render = false
else
lines_up = (@multibar.rows + 1) - @row
|
ruby
|
{
"resource": ""
}
|
q26777
|
TTY.ProgressBar.write
|
test
|
def write(data, clear_first = false)
return unless tty? # write only to terminal
move_to_row do
output.print(TTY::Cursor.column(1)) if clear_first
|
ruby
|
{
"resource": ""
}
|
q26778
|
TTY.ProgressBar.finish
|
test
|
def finish
return if done?
@current = total unless no_width
render
clear ? clear_line : write("\n", false)
ensure
@meter.clear
@done = true
# reenable cursor if it is turned off
|
ruby
|
{
"resource": ""
}
|
q26779
|
TTY.ProgressBar.stop
|
test
|
def stop
# reenable cursor if it is turned off
if hide_cursor && @last_render_width != 0
write(TTY::Cursor.show, false)
|
ruby
|
{
"resource": ""
}
|
q26780
|
TTY.ProgressBar.log
|
test
|
def log(message)
sanitized_message = message.gsub(/\r|\n/, ' ')
if done?
write(sanitized_message + "\n", false)
return
|
ruby
|
{
"resource": ""
}
|
q26781
|
TTY.ProgressBar.padout
|
test
|
def padout(message)
message_length = self.class.display_columns(message)
if @last_render_width > message_length
|
ruby
|
{
"resource": ""
}
|
q26782
|
Delayed.Job.lock_exclusively!
|
test
|
def lock_exclusively!(max_run_time, worker = worker_name)
now = self.class.db_time_now
affected_rows = if locked_by != worker
# We don't own this job so we will update the locked_by name and the locked_at
self.class.update_all(["locked_at = ?, locked_by = ?", now, worker], ["id = ? and (locked_at is null or locked_at < ?)", id, (now - max_run_time.to_i)])
else
# We already own this job, this may happen if the
|
ruby
|
{
"resource": ""
}
|
q26783
|
Elephrame.Trace.setup_tracery
|
test
|
def setup_tracery dir_path
raise "Provided path not a directory" unless Dir.exist?(dir_path)
@grammar = {}
Dir.open(dir_path) do |dir|
dir.each do |file|
# skip our current and parent dir
next if file =~ /^\.\.?$/
# read the rule file into the files hash
@grammar[file.split('.').first] =
createGrammar(JSON.parse(File.read("#{dir_path}/#{file}")))
|
ruby
|
{
"resource": ""
}
|
q26784
|
Elephrame.Trace.expand_and_post
|
test
|
def expand_and_post(text, *options)
opts = Hash[*options]
rules = opts.fetch(:rules, 'default')
actually_post(@grammar[rules].flatten(text),
|
ruby
|
{
"resource": ""
}
|
q26785
|
Elephrame.AllInteractions.run_interact
|
test
|
def run_interact
@streamer.user do |update|
if update.kind_of? Mastodon::Notification
case update.type
when 'mention'
# this makes it so .content calls strip instead
update.status.class.module_eval { alias_method :content, :strip } if @strip_html
store_mention_data update.status
@on_reply.call(self, update.status) unless @on_reply.nil?
when 'reblog'
@on_boost.call(self, update) unless @on_boost.nil?
|
ruby
|
{
"resource": ""
}
|
q26786
|
Elephrame.Reply.reply
|
test
|
def reply(text, *options)
options = Hash[*options]
post("@#{@mention_data[:account].acct} #{text}",
|
ruby
|
{
"resource": ""
}
|
q26787
|
Elephrame.Reply.run_reply
|
test
|
def run_reply
@streamer.user do |update|
next unless update.kind_of? Mastodon::Notification and update.type == 'mention'
# this makes it so .content calls strip instead
update.status.class.module_eval { alias_method :content, :strip } if @strip_html
store_mention_data update.status
|
ruby
|
{
"resource": ""
}
|
q26788
|
Elephrame.Reply.store_mention_data
|
test
|
def store_mention_data(mention)
@mention_data = {
reply_id: mention.id,
visibility: mention.visibility,
spoiler: mention.spoiler_text,
|
ruby
|
{
"resource": ""
}
|
q26789
|
Elephrame.Streaming.setup_streaming
|
test
|
def setup_streaming
stream_uri = @client.instance()
.attributes['urls']['streaming_api'].gsub(/^wss?/, 'https')
@streamer =
|
ruby
|
{
"resource": ""
}
|
q26790
|
PoiseService.Utils.parse_service_name
|
test
|
def parse_service_name(path)
parts = Pathname.new(path).each_filename.to_a.reverse!
# Find the last segment not in common segments, fall back
|
ruby
|
{
"resource": ""
}
|
q26791
|
Net.TCPClient.connect
|
test
|
def connect
start_time = Time.now
retries = 0
close
# Number of times to try
begin
connect_to_server(servers, policy)
logger.info(message: "Connected to #{address}", duration: (Time.now - start_time) * 1000) if respond_to?(:logger)
rescue ConnectionFailure, ConnectionTimeout => exception
cause = exception.is_a?(ConnectionTimeout) ? exception : exception.cause
# Retry-able?
if self.class.reconnect_on_errors.include?(cause.class) && (retries < connect_retry_count.to_i)
retries += 1
logger.warn "#connect Failed to connect to any of #{servers.join(',')}. Sleeping:#{connect_retry_interval}s. Retry: #{retries}" if respond_to?(:logger)
sleep(connect_retry_interval)
retry
else
|
ruby
|
{
"resource": ""
}
|
q26792
|
Net.TCPClient.write
|
test
|
def write(data, timeout = write_timeout)
data = data.to_s
if respond_to?(:logger)
payload = {timeout: timeout}
# With trace level also log the sent data
payload[:data] = data if logger.trace?
logger.benchmark_debug('#write', payload: payload) do
|
ruby
|
{
"resource": ""
}
|
q26793
|
Net.TCPClient.read
|
test
|
def read(length, buffer = nil, timeout = read_timeout)
if respond_to?(:logger)
payload = {bytes: length, timeout: timeout}
logger.benchmark_debug('#read', payload: payload) do
data = socket_read(length, buffer, timeout)
# With trace level also log the received data
|
ruby
|
{
"resource": ""
}
|
q26794
|
Net.TCPClient.close
|
test
|
def close
socket.close if socket && !socket.closed?
@socket = nil
@address = nil
true
rescue IOError
|
ruby
|
{
"resource": ""
}
|
q26795
|
Net.TCPClient.alive?
|
test
|
def alive?
return false if socket.nil? || closed?
if IO.select([socket], nil, nil, 0)
!socket.eof? rescue false
|
ruby
|
{
"resource": ""
}
|
q26796
|
Net.TCPClient.socket_connect
|
test
|
def socket_connect(socket, address, timeout)
socket_address = Socket.pack_sockaddr_in(address.port, address.ip_address)
# Timeout of -1 means wait forever for a connection
return socket.connect(socket_address) if timeout == -1
deadline = Time.now.utc + timeout
begin
non_blocking(socket, deadline) { socket.connect_nonblock(socket_address) }
rescue Errno::EISCONN
# Connection was successful.
rescue NonBlockingTimeout
|
ruby
|
{
"resource": ""
}
|
q26797
|
Net.TCPClient.socket_write
|
test
|
def socket_write(data, timeout)
if timeout < 0
socket.write(data)
else
deadline = Time.now.utc + timeout
length = data.bytesize
total_count = 0
non_blocking(socket, deadline) do
loop do
begin
count = socket.write_nonblock(data)
rescue Errno::EWOULDBLOCK
retry
end
total_count += count
return total_count if total_count >= length
data = data.byteslice(count..-1)
end
end
end
rescue NonBlockingTimeout
logger.warn "#write Timeout after #{timeout}
|
ruby
|
{
"resource": ""
}
|
q26798
|
Net.TCPClient.ssl_connect
|
test
|
def ssl_connect(socket, address, timeout)
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.set_params(ssl.is_a?(Hash) ? ssl : {})
ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ssl_context)
ssl_socket.hostname = address.host_name
ssl_socket.sync_close = true
begin
if timeout == -1
# Timeout of -1 means wait forever for a connection
ssl_socket.connect
else
deadline = Time.now.utc + timeout
begin
non_blocking(socket, deadline) { ssl_socket.connect_nonblock }
rescue Errno::EISCONN
# Connection was successful.
rescue NonBlockingTimeout
raise ConnectionTimeout.new("SSL handshake Timed out after #{timeout} seconds trying to connect to #{address.to_s}")
|
ruby
|
{
"resource": ""
}
|
q26799
|
Sonos.System.party_mode
|
test
|
def party_mode new_master = nil
return nil unless speakers.length > 1
new_master = find_party_master if new_master.nil?
party_over
speakers.each do |slave|
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.