_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q26800
|
Sonos.Discovery.discover
|
test
|
def discover
result = SSDP::Consumer.new.search(service: 'urn:schemas-upnp-org:device:ZonePlayer:1', first_only: true, timeout: @timeout, filter: lambda {|r| r[:params]["ST"].match(/ZonePlayer/) })
@first_device_ip = result[:address]
end
|
ruby
|
{
"resource": ""
}
|
q26801
|
Sonos.Discovery.topology
|
test
|
def topology
self.discover unless @first_device_ip
return [] unless @first_device_ip
doc = Nokogiri::XML(open("http://#{@first_device_ip}:#{Sonos::PORT}/status/topology"))
doc.xpath('//ZonePlayers/ZonePlayer').map do |node|
TopologyNode.new(node)
end
end
|
ruby
|
{
"resource": ""
}
|
q26802
|
MTG.QueryBuilder.find
|
test
|
def find(id)
response = RestClient.get("#{@type.Resource}/#{id}")
singular_resource = @type.Resource[0...-1]
if response.body[singular_resource].nil?
raise ArgumentError, 'Resource not found'
end
type.new.from_json(response.body[singular_resource].to_json)
end
|
ruby
|
{
"resource": ""
}
|
q26803
|
MTG.QueryBuilder.all
|
test
|
def all
list = []
page = 1
fetch_all = true
if @query.has_key?(:page)
page = @query[:page]
fetch_all = false
end
while true
response = RestClient.get(@type.Resource, @query)
data = response.body[@type.Resource]
if !data.empty?
data.each {|item| list << @type.new.from_json(item.to_json)}
if !fetch_all
break
else
where(page: page += 1)
end
else
break
end
end
return list
end
|
ruby
|
{
"resource": ""
}
|
q26804
|
Reform::Form::ORM.UniquenessValidator.validate
|
test
|
def validate(form)
property = attributes.first
# here is the thing: why does AM::UniquenessValidator require a filled-out record to work properly? also, why do we need to set
# the class? it would be way easier to pass #validate a hash of attributes and get back an errors hash.
# the class for the finder could either be infered from the record or set in the validator instance itself in the call to ::validates.
record = form.model_for_property(property)
record.send("#{property}=", form.send(property))
@klass = record.class # this is usually done in the super-sucky #setup method.
super(record).tap do |res|
form.errors.add(property, record.errors.first.last) if record.errors.present?
end
end
|
ruby
|
{
"resource": ""
}
|
q26805
|
Reform::Form::ActiveModel.ClassMethods.validates
|
test
|
def validates(*args, &block)
validation(name: :default, inherit: true) { validates *args, &block }
end
|
ruby
|
{
"resource": ""
}
|
q26806
|
ROXML.XMLTextRef.update_xml
|
test
|
def update_xml(xml, value)
wrap(xml).tap do |xml|
if content?
add(xml, value)
elsif name?
xml.name = value
elsif array?
value.each do |v|
add(XML.add_node(xml, name), v)
end
else
add(XML.add_node(xml, name), value)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26807
|
Exonio.Financial.ipmt
|
test
|
def ipmt(rate, per, nper, pv, fv = 0, end_or_beginning = 0)
pmt = self.pmt(rate, nper, pv, fv, end_or_beginning)
fv = self.fv(rate, (per - 1), pmt, pv, end_or_beginning) * rate
temp = end_or_beginning == 1 ? fv / (1 + rate) : fv
(per == 1 && end_or_beginning == 1) ? 0.0 : temp
end
|
ruby
|
{
"resource": ""
}
|
q26808
|
Exonio.Financial.nper
|
test
|
def nper(rate, pmt, pv, fv = 0, end_or_beginning = 0)
z = pmt * (1 + rate * end_or_beginning) / rate
temp = Math.log((-fv + z) / (pv + z))
temp / Math.log(1 + rate)
end
|
ruby
|
{
"resource": ""
}
|
q26809
|
Exonio.Financial.pmt
|
test
|
def pmt(rate, nper, pv, fv = 0, end_or_beginning = 0)
temp = (1 + rate) ** nper
fact = (1 + rate * end_or_beginning) * (temp - 1) / rate
-(fv + pv * temp) / fact
end
|
ruby
|
{
"resource": ""
}
|
q26810
|
Exonio.Financial.rate
|
test
|
def rate(nper, pmt, pv, fv = 0, end_or_beginning = 0, rate_guess = 0.10)
guess = rate_guess
tolerancy = 1e-6
close = false
begin
temp = newton_iter(guess, nper, pmt, pv, fv, end_or_beginning)
next_guess = (guess - temp).round(20)
diff = (next_guess - guess).abs
close = diff < tolerancy
guess = next_guess
end while !close
next_guess
end
|
ruby
|
{
"resource": ""
}
|
q26811
|
Exonio.Financial.npv
|
test
|
def npv(discount, cashflows)
total = 0
cashflows.each_with_index do |cashflow, index|
total += (cashflow.to_f / (1 + discount.to_f) ** (index + 1))
end
total
end
|
ruby
|
{
"resource": ""
}
|
q26812
|
Exonio.Financial.irr
|
test
|
def irr(values)
func = Helpers::IrrHelper.new(values)
guess = [ func.eps ]
nlsolve( func, guess)
guess[0]
end
|
ruby
|
{
"resource": ""
}
|
q26813
|
Exonio.Financial.newton_iter
|
test
|
def newton_iter(r, n, p, x, y, w)
t1 = (r+1)**n
t2 = (r+1)**(n-1)
((y + t1*x + p*(t1 - 1)*(r*w + 1)/r) / (n*t2*x - p*(t1 - 1)*(r*w + 1)/(r**2) + n*p*t2*(r*w + 1)/r + p*(t1 - 1)*w/r))
end
|
ruby
|
{
"resource": ""
}
|
q26814
|
Sensu.Handler.event_summary
|
test
|
def event_summary(trim_at = 100)
summary = @event['check']['notification'] || @event['check']['description']
if summary.nil?
source = @event['check']['source'] || @event['client']['name']
event_context = [source, @event['check']['name']].join('/')
output = @event['check']['output'].chomp
output = output.length > trim_at ? output[0..trim_at] + '...' : output
summary = [event_context, output].join(' : ')
end
summary
end
|
ruby
|
{
"resource": ""
}
|
q26815
|
Ole.Storage.load
|
test
|
def load
# we always read 512 for the header block. if the block size ends up being different,
# what happens to the 109 fat entries. are there more/less entries?
@io.rewind
header_block = @io.read 512
@header = Header.new header_block
# create an empty bbat.
@bbat = AllocationTable::Big.new self
bbat_chain = header_block[Header::SIZE..-1].unpack 'V*'
mbat_block = @header.mbat_start
@header.num_mbat.times do
blocks = @bbat.read([mbat_block]).unpack 'V*'
mbat_block = blocks.pop
bbat_chain += blocks
end
# am i using num_bat in the right way?
@bbat.load @bbat.read(bbat_chain[0, @header.num_bat])
# get block chain for directories, read it, then split it into chunks and load the
# directory entries. semantics changed - used to cut at first dir where dir.type == 0
@dirents = @bbat.read(@header.dirent_start).to_enum(:each_chunk, Dirent::SIZE).
map { |str| Dirent.new self, str }
# now reorder from flat into a tree
# links are stored in some kind of balanced binary tree
# check that everything is visited at least, and at most once
# similarly with the blocks of the file.
# was thinking of moving this to Dirent.to_tree instead.
class << @dirents
def to_tree idx=0
return [] if idx == Dirent::EOT
d = self[idx]
to_tree(d.child).each { |child| d << child }
raise FormatError, "directory #{d.inspect} used twice" if d.idx
d.idx = idx
to_tree(d.prev) + [d] + to_tree(d.next)
end
end
@root = @dirents.to_tree.first
@dirents.reject! { |d| d.type_id == 0 }
# silence this warning by default, its not really important (issue #5).
# fairly common one appears to be "R" (from office OS X?) which smells
# like some kind of UTF16 snafu, but scottwillson also has had some kanji...
#Log.warn "root name was #{@root.name.inspect}" unless @root.name == 'Root Entry'
unused = @dirents.reject(&:idx).length
Log.warn "#{unused} unused directories" if unused > 0
# FIXME i don't currently use @header.num_sbat which i should
# hmm. nor do i write it. it means what exactly again?
# which mode to use here?
@sb_file = RangesIOResizeable.new @bbat, :first_block => @root.first_block, :size => @root.size
@sbat = AllocationTable::Small.new self
@sbat.load @bbat.read(@header.sbat_start)
end
|
ruby
|
{
"resource": ""
}
|
q26816
|
Ole.Storage.repack
|
test
|
def repack temp=:file
case temp
when :file
Tempfile.open 'ole-repack' do |io|
io.binmode
repack_using_io io
end
when :mem; StringIO.open(''.dup, &method(:repack_using_io))
else raise ArgumentError, "unknown temp backing #{temp.inspect}"
end
end
|
ruby
|
{
"resource": ""
}
|
q26817
|
WpApiClient.Relationship.load_relation
|
test
|
def load_relation(relationship, position = nil)
if objects = @resource.dig("_embedded", relationship)
location = position ? objects[position] : objects
begin
WpApiClient::Collection.new(location)
rescue WpApiClient::ErrorResponse
load_from_links(relationship, position)
end
else
load_from_links(relationship, position)
end
end
|
ruby
|
{
"resource": ""
}
|
q26818
|
WpApiClient.Client.native_representation_of
|
test
|
def native_representation_of(response_body)
# Do we have a collection of objects?
if response_body.is_a? Array
WpApiClient::Collection.new(response_body, @headers)
else
WpApiClient::Entities::Base.build(response_body)
end
end
|
ruby
|
{
"resource": ""
}
|
q26819
|
CITA.Contract.call_func
|
test
|
def call_func(method:, params: [], tx: {}) # rubocop:disable Naming/UncommunicativeMethodParamName
data, output_types = function_data_with_ot(method, *params)
resp = @rpc.call_rpc(:call, params: [tx.merge(data: data, to: address), "latest"])
result = resp["result"]
data = [Utils.remove_hex_prefix(result)].pack("H*")
return if data.nil?
re = decode_abi output_types, data
re.length == 1 ? re.first : re
end
|
ruby
|
{
"resource": ""
}
|
q26820
|
CITA.Contract.send_func
|
test
|
def send_func(tx:, private_key:, method:, params: []) # rubocop:disable Naming/UncommunicativeMethodParamName
data, _output_types = function_data_with_ot(method, *params)
transaction = if tx.is_a?(Hash)
Transaction.from_hash(tx)
else
tx
end
transaction.data = data
resp = @rpc.send_transaction(transaction, private_key)
resp&.dig("result")
end
|
ruby
|
{
"resource": ""
}
|
q26821
|
CITA.Contract.parse_url
|
test
|
def parse_url
uri = URI.parse(@url)
@host = uri.host
@port = uri.port
@scheme = uri.scheme
end
|
ruby
|
{
"resource": ""
}
|
q26822
|
CITA.Http.call_rpc
|
test
|
def call_rpc(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)
conn.post("/", rpc_params(method, jsonrpc: jsonrpc, params: params, id: id))
end
|
ruby
|
{
"resource": ""
}
|
q26823
|
CITA.Http.rpc_params
|
test
|
def rpc_params(method, jsonrpc: DEFAULT_JSONRPC, params: DEFAULT_PARAMS, id: DEFAULT_ID)
{
jsonrpc: jsonrpc,
id: id,
method: method,
params: params
}.to_json
end
|
ruby
|
{
"resource": ""
}
|
q26824
|
CITA.Http.conn
|
test
|
def conn
Faraday.new(url: url) do |faraday|
faraday.headers["Content-Type"] = "application/json"
faraday.request :url_encoded # form-encode POST params
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end
|
ruby
|
{
"resource": ""
}
|
q26825
|
CITA.RPC.transfer
|
test
|
def transfer(to:, private_key:, value:, quota: 30_000)
valid_until_block = block_number["result"].hex + 88
meta_data = get_meta_data("latest")["result"]
version = meta_data["version"]
chain_id = if version.zero?
meta_data["chainId"]
elsif version == 1
meta_data["chainIdV1"]
end
transaction = Transaction.new(nonce: Utils.nonce, valid_until_block: valid_until_block, chain_id: chain_id, to: to, value: value, quota: quota, version: version)
send_transaction(transaction, private_key)
end
|
ruby
|
{
"resource": ""
}
|
q26826
|
Browser.Storage.replace
|
test
|
def replace(new)
if String === new
@data.replace(JSON.parse(new))
else
@data.replace(new)
end
end
|
ruby
|
{
"resource": ""
}
|
q26827
|
Browser.Storage.to_json
|
test
|
def to_json
io = StringIO.new("{")
io << JSON.create_id.to_json << ":" << self.class.name.to_json << ","
@data.each {|key, value|
io << key.to_json.to_s << ":" << value.to_json << ","
}
io.seek(-1, IO::SEEK_CUR)
io << "}"
io.string
end
|
ruby
|
{
"resource": ""
}
|
q26828
|
Browser.Console.time
|
test
|
def time(label, &block)
raise ArgumentError, "no block given" unless block
`#@native.time(label)`
begin
if block.arity == 0
instance_exec(&block)
else
block.call(self)
end
ensure
`#@native.timeEnd()`
end
end
|
ruby
|
{
"resource": ""
}
|
q26829
|
Browser.Console.group
|
test
|
def group(*args, &block)
raise ArgumentError, "no block given" unless block
`#@native.group.apply(#@native, args)`
begin
if block.arity == 0
instance_exec(&block)
else
block.call(self)
end
ensure
`#@native.groupEnd()`
end
end
|
ruby
|
{
"resource": ""
}
|
q26830
|
Browser.Console.group!
|
test
|
def group!(*args, &block)
return unless block_given?
`#@native.groupCollapsed.apply(#@native, args)`
begin
if block.arity == 0
instance_exec(&block)
else
block.call(self)
end
ensure
`#@native.groupEnd()`
end
end
|
ruby
|
{
"resource": ""
}
|
q26831
|
Metaforce.AbstractClient.authenticate!
|
test
|
def authenticate!
options = authentication_handler.call(self, @options)
@options.merge!(options)
client.config.soap_header = soap_headers
end
|
ruby
|
{
"resource": ""
}
|
q26832
|
Xcodeproj.Project.new_with_uuid
|
test
|
def new_with_uuid(klass, uuid)
if klass.is_a?(String)
klass = Object.const_get(klass)
end
object = klass.new(self, uuid)
object.initialize_defaults
object
end
|
ruby
|
{
"resource": ""
}
|
q26833
|
Xcodeproj::Project::Object.PBXGroup.new_reference_with_uuid
|
test
|
def new_reference_with_uuid(path, uuid, source_tree = :group)
# customize `FileReferencesFactory.new_file_reference`
path = Pathname.new(path)
ref = self.project.new_with_uuid(PBXFileReference, uuid)
self.children << ref
GroupableHelper.set_path_with_source_tree(ref, path, source_tree)
ref.set_last_known_file_type
# customize `FileReferencesFactory.configure_defaults_for_file_reference`
if ref.path.include?('/')
ref.name = ref.path.split('/').last
end
if File.extname(ref.path).downcase == '.framework'
ref.include_in_index = nil
end
ref
end
|
ruby
|
{
"resource": ""
}
|
q26834
|
Xcodeproj::Project::Object.AbstractBuildPhase.add_file_reference_with_uuid
|
test
|
def add_file_reference_with_uuid(file_ref, uuid, avoid_duplicates = false)
if avoid_duplicates && existing = build_file(file_ref)
existing
else
build_file = project.new_with_uuid(PBXBuildFile, uuid)
build_file.file_ref = file_ref
files.insert(0, build_file)
build_file
end
end
|
ruby
|
{
"resource": ""
}
|
q26835
|
Seeds.Core.remove_seeds
|
test
|
def remove_seeds
removings = self.locks.keys - self.seeds.keys
removings.each do |name|
say "Removing #{name} (#{self.locks[name].version})".red
dirname = File.join(self.root_path, "Seeds", name)
FileUtils.rm_rf(dirname)
end
end
|
ruby
|
{
"resource": ""
}
|
q26836
|
Seeds.Core.configure_phase
|
test
|
def configure_phase
self.project.targets.each do |target|
begin
phase = target.sources_build_phase
# support resources phase
resource_phase = target.resources_build_phase
next unless phase
rescue NoMethodError
next
end
# remove zombie build files
phase.files_references.each do |file|
begin
file.real_path
rescue
phase.files.each do |build_file|
phase.files.delete(build_file) if build_file.file_ref == file
end
end
end
resource_phase.files_references.each do |file|
begin
file.real_path
rescue
resource_phase.files.each do |build_file|
resource_phase.files.delete(build_file) if build_file.file_ref == file
end
end
end
removings = [] # name of seeds going to be removed from the target
addings = [] # name of seeds going to be added to the target
self.targets.keys.sort.each do |seed_name|
target_names = self.targets[seed_name]
if not target_names.include?(target.name)
removings << seed_name if not removings.include?(seed_name)
else
addings << seed_name if not addings.include?(seed_name)
end
end
self.file_references.each do |file|
removings.each do |seed_names|
next if not seed_names.include?(file.parent.name)
phase.files.each do |build_file|
phase.files.delete(build_file) if build_file.file_ref == file
end
resource_phase.files.each do |build_file|
resource_phase.files.delete(build_file) if build_file.file_ref == file
end
end
addings.each do |seed_names|
next if file.name.end_with? ".h"
next if not seed_names.include?(file.parent.name)
uuid = Xcodeproj::uuid_with_name "#{target.name}:#{file.name}"
# Treat a file as resource file unless confirm it can be compiled.
if self.valid_source_file?(file)
phase.add_file_reference_with_uuid(file, uuid, true)
else
resource_phase.add_file_reference_with_uuid(file, uuid, true)
end
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26837
|
Seeds.Core.valid_source_file?
|
test
|
def valid_source_file? filename
suffixs = [".h", ".c", ".m", ".mm", ".swift", ".cpp"]
suffixs.each do |suffix|
return true if filename.name.end_with? suffix
end
return false
end
|
ruby
|
{
"resource": ""
}
|
q26838
|
Yast.SpellcheckTask.speller
|
test
|
def speller
return @speller if @speller
# raspell is an optional dependency, handle the missing case nicely
begin
require "raspell"
rescue LoadError
$stderr.puts "ERROR: Ruby gem \"raspell\" is not installed."
exit 1
end
# initialize aspell
@speller = Aspell.new("en_US")
@speller.suggestion_mode = Aspell::NORMAL
# ignore the HTML tags in the text
@speller.set_option("mode", "html")
@speller
end
|
ruby
|
{
"resource": ""
}
|
q26839
|
Yast.SpellcheckTask.files_to_check
|
test
|
def files_to_check
files = config["check"].reduce([]) { |a, e| a + Dir[e] }
config["ignore"].reduce(files) { |a, e| a - Dir[e] }
end
|
ruby
|
{
"resource": ""
}
|
q26840
|
Yast.SpellcheckTask.read_spell_config
|
test
|
def read_spell_config(file)
return {} unless File.exist?(file)
puts "Loading config file (#{file})..." if verbose == true
require "yaml"
YAML.load_file(file)
end
|
ruby
|
{
"resource": ""
}
|
q26841
|
Yast.SpellcheckTask.report_duplicates
|
test
|
def report_duplicates(dict1, dict2)
duplicates = dict1 & dict2
return if duplicates.empty?
$stderr.puts "Warning: Found dictionary duplicates in the local dictionary " \
"(#{CUSTOM_SPELL_CONFIG_FILE}):\n"
duplicates.each { |duplicate| $stderr.puts " #{duplicate}" }
$stderr.puts
end
|
ruby
|
{
"resource": ""
}
|
q26842
|
Yast.SpellcheckTask.config
|
test
|
def config
return @config if @config
@config = read_spell_config(GLOBAL_SPELL_CONFIG_FILE)
custom_config = read_spell_config(CUSTOM_SPELL_CONFIG_FILE)
report_duplicates(config["dictionary"], custom_config["dictionary"].to_a)
custom_config["dictionary"] = @config["dictionary"] + custom_config["dictionary"].to_a
custom_config["dictionary"].uniq!
# override the global values by the local if present
@config.merge!(custom_config)
@config
end
|
ruby
|
{
"resource": ""
}
|
q26843
|
Yast.SpellcheckTask.check_file
|
test
|
def check_file(file)
puts "Checking #{file}..." if verbose == true
# spell check each line separately so we can report error locations properly
lines = File.read(file).split("\n")
success = true
lines.each_with_index do |text, index|
misspelled = misspelled_on_line(text)
next if misspelled.empty?
success = false
print_misspelled(misspelled, index, text)
end
success
end
|
ruby
|
{
"resource": ""
}
|
q26844
|
OptParseValidator.OptPath.check_writable
|
test
|
def check_writable(path)
raise Error, "'#{path}' is not writable" if path.exist? && !path.writable? || !path.parent.writable?
end
|
ruby
|
{
"resource": ""
}
|
q26845
|
OptParseValidator.OptParser.check_option
|
test
|
def check_option(opt)
raise Error, "The option is not an OptBase, #{opt.class} supplied" unless opt.is_a?(OptBase)
raise Error, "The option #{opt.to_sym} is already used !" if @symbols_used.include?(opt.to_sym)
end
|
ruby
|
{
"resource": ""
}
|
q26846
|
OptParseValidator.OptParser.post_processing
|
test
|
def post_processing
@opts.each do |opt|
raise NoRequiredOption, "The option #{opt} is required" if opt.required? && [email protected]?(opt.to_sym)
next if opt.required_unless.empty? || @results.key?(opt.to_sym)
fail_msg = "One of the following options is required: #{opt}, #{opt.required_unless.join(', ')}"
raise NoRequiredOption, fail_msg unless opt.required_unless.any? do |sym|
@results.key?(sym)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26847
|
Zipping.ZipBuilder.subdir_entities
|
test
|
def subdir_entities(dir = @current_dir)
Dir.glob(dir[:path].gsub(/[*?\\\[\]{}]/, '\\\\\0') + '/*').map!{|path| {path: path, time: File.mtime(path), name: File.basename(path)}}
end
|
ruby
|
{
"resource": ""
}
|
q26848
|
Zipping.ZipBuilder.string_to_bytes
|
test
|
def string_to_bytes(str)
unless @e.nil? || @e == :utf8
if @e == :shift_jis
begin
str = str.gsub /[\\:*?"<>|\uff5e]/, '?'
str.encode! 'Shift_JIS', :invalid => :replace, :undef => :replace, :replace => '?'
rescue => e
end
end
end
[str].pack('a*')
end
|
ruby
|
{
"resource": ""
}
|
q26849
|
Zipping.ZipBuilder.pack
|
test
|
def pack(files)
entities = Entity.entities_from files
return if entities.empty?
reset_state
pack_entities entities
while has_dir?
cd next_dir
pack_current_dir
end
end
|
ruby
|
{
"resource": ""
}
|
q26850
|
Zipping.ZipBuilder.pack_symlinks
|
test
|
def pack_symlinks
reset_state
@l.each do |link|
if @w.path_exists? Entity.linked_path(link[:abs_path], File.readlink(link[:path]))
link[:name] = link[:abs_path]
pack_symbolic_link_entity link
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26851
|
Zipping.ZipBuilder.pack_entities
|
test
|
def pack_entities(entities)
entities.each do |entity|
# ignore bad entities
next unless entity.is_a?(Hash) && entity[:path]
path = entity[:path]
if File.symlink? path
postpone_symlink entity
elsif File.directory? path
postpone_dir entity
elsif File.file? path
pack_file_entity entity
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26852
|
UiBibz::Ui::Core::Lists::Components.List.header
|
test
|
def header content = nil, options = nil, html_options = nil, &block
@header = UiBibz::Ui::Core::Lists::Components::ListHeader.new content, options, html_options, &block
end
|
ruby
|
{
"resource": ""
}
|
q26853
|
UiBibz::Ui::Core::Lists::Components.List.body
|
test
|
def body content = nil, options = nil, html_options = nil, &block
@body = UiBibz::Ui::Core::Lists::Components::ListBody.new content, options, html_options, &block
end
|
ruby
|
{
"resource": ""
}
|
q26854
|
UiBibz::Ui::Ux::Tables.Table.td_content
|
test
|
def td_content record, col
content = col.count ? record.send(col.data_index).count : record.send(col.data_index)
unless content.nil?
content = content.strftime(col.date_format) unless col.date_format.nil?
content = link_to content, action.inject_url(col.link, record) unless col.link.nil?
content = col.format.call(@store.records, record) unless col.format.nil?
end
content = As.new(col, record, content, @options).render unless col.as.nil?
content
end
|
ruby
|
{
"resource": ""
}
|
q26855
|
UiBibz::Ui::Core::Boxes.Card.body
|
test
|
def body content = nil, options = nil, html_options = nil, &block
options, content = inherit_options(content, options, block)
if is_tap(content, options)
content = (content || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )
@items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options).tap(&block).render
else
options = (options || {}).merge(collapse: options.try(:[], :collapse), parent_collapse: @options[:parent_collapse] )
@items << UiBibz::Ui::Core::Boxes::Components::CardBody.new(content, options, html_options, &block).render
end
end
|
ruby
|
{
"resource": ""
}
|
q26856
|
UiBibz::Ui::Core::Boxes.Card.footer
|
test
|
def footer content = nil, options = nil, html_options = nil, &block
options, content = inherit_options(content, options, block)
@footer = UiBibz::Ui::Core::Boxes::Components::CardFooter.new(content, options, html_options, &block).render
end
|
ruby
|
{
"resource": ""
}
|
q26857
|
UiBibz::Ui::Core::Boxes.Card.list_group
|
test
|
def list_group content = nil, options = nil, html_options = nil, &block
@items << UiBibz::Ui::Core::Boxes::Components::CardListGroup.new(content, options, html_options).tap(&block).render
end
|
ruby
|
{
"resource": ""
}
|
q26858
|
UiBibz::Ui::Core::Boxes.Card.image
|
test
|
def image content = nil, options = nil, html_options = nil, &block
@items << UiBibz::Ui::Core::Boxes::Components::CardImage.new(content, options, html_options, &block).render
end
|
ruby
|
{
"resource": ""
}
|
q26859
|
UiBibz::Ui::Core::Forms::Dropdowns.Dropdown.html
|
test
|
def html content = nil, &block
if !block.nil?
context = eval("self", block.binding)
@items << context.capture(&block)
else
@items << content
end
end
|
ruby
|
{
"resource": ""
}
|
q26860
|
UiBibz::Ui::Core::Forms::Selects.AbstractSelect.component_html_options
|
test
|
def component_html_options
super.merge({
multiple: options[:multiple],
disabled: options[:state] == :disabled,
include_blank: options[:include_blank],
prompt: options[:prompt]
})
end
|
ruby
|
{
"resource": ""
}
|
q26861
|
UiBibz::Ui::Core::Navigations.Nav.nav
|
test
|
def nav content = nil, options = {}, html_options = nil, &block
@items << UiBibz::Ui::Core::Component.new(Nav.new(content, options).tap(&block).render, {}, html_options)
end
|
ruby
|
{
"resource": ""
}
|
q26862
|
UiBibz::Ui::Core::Notifications.Alert.body
|
test
|
def body content = nil, options = nil, html_options = nil, &block
@body = UiBibz::Ui::Core::Notifications::Components::AlertBody.new(content, options, html_options, &block).render
end
|
ruby
|
{
"resource": ""
}
|
q26863
|
UiBibz::Ui::Core.Component.is_tap
|
test
|
def is_tap content, options
(content[:tap] if content.kind_of?(Hash)) || (options[:tap] unless options.nil?)
end
|
ruby
|
{
"resource": ""
}
|
q26864
|
UiBibz::Ui::Core.Component.component_html_data
|
test
|
def component_html_data
# To stimulusjs
data_target = html_options.try(:[], :data).try(:[], :target) || options.try(:delete, :target)
add_html_data(:target, data_target) unless data_target.nil?
data_controller = html_options.try(:[], :data).try(:[], :controller) || options.try(:delete, :controller)
add_html_data(:controller, data_controller) unless data_controller.nil?
data_action = html_options.try(:[], :data).try(:[], :action) || options.try(:delete, :action)
add_html_data(:action, data_action) unless data_action.nil?
# To turbolinks
data_turbolinks = html_options.try(:[], :data).try(:[], :turbolinks) || options.try(:delete, :turbolinks)
add_html_data(:turbolinks, data_turbolinks) unless data_turbolinks.nil?
end
|
ruby
|
{
"resource": ""
}
|
q26865
|
UiBibz::Ui::Core.Component.add_html_data
|
test
|
def add_html_data name, value = true
html_options[:data] = {} if html_options[:data].nil?
value = value.kind_of?(String) ? value.strip : value
html_options[:data].update(Hash[name, value])
end
|
ruby
|
{
"resource": ""
}
|
q26866
|
UiBibz::Ui::Ux::Tables.Sortable.header
|
test
|
def header column, name = nil
@column = column
defaults = [translate_headers_by_defaults, translate_headers_by_defaults_active_record, translate_headers_by_active_record, header_name(name)]
@name = UiBibz::Utils::Internationalization.new(translate_headers_by_model, default: defaults).translate
sortable? ? sortable_link : title
end
|
ruby
|
{
"resource": ""
}
|
q26867
|
UiBibz::Ui::Ux::Tables.Columns.column
|
test
|
def column data_index = nil, options = nil, html_options = nil, &block
@columns << Column.new(data_index, options, html_options, &block)
end
|
ruby
|
{
"resource": ""
}
|
q26868
|
UiBibz::Ui::Ux::Tables.Actions.link
|
test
|
def link content = nil, options = nil, html_options = nil, &block
@actions << UiBibz::Ui::Core::Forms::Dropdowns::Components::DropdownLink.new(content, options, html_options, &block).render
end
|
ruby
|
{
"resource": ""
}
|
q26869
|
SparkEngine.Scaffold.engine_scaffold
|
test
|
def engine_scaffold
FileUtils.mkdir_p(@gem_temp)
Dir.chdir(@gem_temp) do
response = Open3.capture3("rails plugin new #{gem} --mountable --dummy-path=site --skip-test-unit")
if !response[1].empty?
puts response[1]
abort "FAILED: Please be sure you have the rails gem installed with `gem install rails`"
end
# Remove files and directories that are unnecessary for the
# light-weight Rails documentation site
remove = %w(mailers models assets channels jobs views).map{ |f| File.join('app', f) }
remove.concat %w(cable.yml storage.yml database.yml).map{ |f| File.join('config', f) }
remove.each { |f| FileUtils.rm_rf File.join(@gem, 'site', f), secure: true }
end
engine_copy
end
|
ruby
|
{
"resource": ""
}
|
q26870
|
SparkEngine.Scaffold.engine_copy
|
test
|
def engine_copy
site_path = File.join path, 'site'
FileUtils.mkdir_p site_path
## Copy Rails plugin files
Dir.chdir "#{@gem_temp}/#{gem}/site" do
%w(app config bin config.ru Rakefile public log).each do |item|
target = File.join site_path, item
FileUtils.cp_r item, target
action_log "create", target.sub(@cwd+'/','')
end
end
# Remove temp dir
FileUtils.rm_rf @gem_temp
end
|
ruby
|
{
"resource": ""
}
|
q26871
|
SassC.SassYaml.make_map
|
test
|
def make_map(item)
'(' + item.map {|key, value| key.to_s + ':' + convert_to_sass_value(value) }.join(',') + ')'
end
|
ruby
|
{
"resource": ""
}
|
q26872
|
SparkEngine.Plugin.add_files
|
test
|
def add_files(klass)
ext = asset_ext klass
find_files(ext).map do |path|
klass.new(self, path)
end
end
|
ruby
|
{
"resource": ""
}
|
q26873
|
SparkEngine.Plugin.find_files
|
test
|
def find_files(ext)
files = Dir[File.join(paths[ext.to_sym], asset_glob(ext))]
# Filter out partials
files.reject { |f| File.basename(f).start_with?('_') }
end
|
ruby
|
{
"resource": ""
}
|
q26874
|
SparkEngine.Command.dispatch
|
test
|
def dispatch(command, *args)
@threads = []
send command, *args
@threads.each { |thr| thr.join }
end
|
ruby
|
{
"resource": ""
}
|
q26875
|
SparkEngine.Command.watch
|
test
|
def watch(options={})
build(options)
require 'listen'
trap("SIGINT") {
puts "\nspark_engine watcher stopped. Have a nice day!"
exit!
}
@threads.concat SparkEngine.load_plugin.watch(options)
end
|
ruby
|
{
"resource": ""
}
|
q26876
|
SportDb.ReaderBase.load_setup
|
test
|
def load_setup( name )
reader = create_fixture_reader( name )
reader.each do |fixture_name|
load( fixture_name )
end
end
|
ruby
|
{
"resource": ""
}
|
q26877
|
ODFReport.Images.avoid_duplicate_image_names
|
test
|
def avoid_duplicate_image_names(content)
nodes = content.xpath("//draw:frame[@draw:name]")
nodes.each_with_index do |node, i|
node.attribute('name').value = "pic_#{i}"
end
end
|
ruby
|
{
"resource": ""
}
|
q26878
|
DynamicScaffold.ControllerUtilities.scope_params
|
test
|
def scope_params
return {} if dynamic_scaffold.scope.nil?
case dynamic_scaffold.scope
when Array then
dynamic_scaffold.scope.each_with_object({}) do |val, res|
if val.is_a? Hash
val.each {|k, v| res[k] = v }
else
res[val] = params[val]
end
end
when Hash then
dynamic_scaffold.scope
end
end
|
ruby
|
{
"resource": ""
}
|
q26879
|
DynamicScaffold.ControllerUtilities.pkey_string_to_hash
|
test
|
def pkey_string_to_hash(pkey)
# https://github.com/gomo/dynamic_scaffold/pull/9/commits/ff5de0e38b3544347e82539c45ffd2efaf3410da
# Stop support multiple pkey, on this commit.
# Convert "key:1,code:foo" to {key: "1", code: "foo"}
pkey.split(',').map {|v| v.split(':') }.each_with_object({}) {|v, res| res[v.first] = v.last }
end
|
ruby
|
{
"resource": ""
}
|
q26880
|
DynamicScaffold.ControllerUtilities.update_values
|
test
|
def update_values # rubocop:disable Metrics/AbcSize
# set the parameters of carrierwave_image at the end for validates.
permitting = []
dynamic_scaffold.form.items.reject {|i| i.type?(:carrierwave_image) }.each do |item|
item.extract_parameters(permitting)
end
permitting.concat(dynamic_scaffold.form.permit_params)
dynamic_scaffold.form.items.select {|i| i.type?(:carrierwave_image) }.each do |item|
item.extract_parameters(permitting)
end
values = params
.require(dynamic_scaffold.model.name.underscore)
.permit(*permitting)
if dynamic_scaffold.scope && !valid_for_scope?(values)
raise DynamicScaffold::Error::InvalidOperation, "You can update only to #{scope_params} on this scope"
end
values
end
|
ruby
|
{
"resource": ""
}
|
q26881
|
DynamicScaffold.ControllerUtilities.valid_for_scope?
|
test
|
def valid_for_scope?(update_params)
return true if dynamic_scaffold.scope_options[:changeable]
result = true
scope_params.each do |key, value|
if update_params.key?(key) && update_params[key] != value
result = false
break
end
end
result
end
|
ruby
|
{
"resource": ""
}
|
q26882
|
RedisLocks.Semaphore.lock
|
test
|
def lock(timeout: nil, &block)
ensure_exists_and_release_stale_locks!
success = @redis.with do |conn|
if timeout
!conn.blpop(available_key, timeout.to_i).nil?
else
!conn.lpop(available_key).nil?
end
end
return false unless success
token = SecureRandom.hex(16)
@tokens.push(token)
@redis.with do |conn|
conn.zadd(grabbed_key, epoch_f(conn), token)
end
return_or_yield(token, &block)
end
|
ruby
|
{
"resource": ""
}
|
q26883
|
RedisLocks.Semaphore.unlock
|
test
|
def unlock(token = @tokens.pop)
return unless token
removed = false
@redis.with do |conn|
removed = conn.zrem grabbed_key, token
if removed
conn.lpush available_key, 1
end
end
removed
end
|
ruby
|
{
"resource": ""
}
|
q26884
|
Libnotify.API.apply_options
|
test
|
def apply_options(options={})
options.each { |key, value| send("#{key}=", value) if respond_to?(key) }
yield(self) if block_given?
end
|
ruby
|
{
"resource": ""
}
|
q26885
|
Libnotify.API.show!
|
test
|
def show!
notify_init(app_name) or raise "notify_init failed"
raw_ptr = notify_notification_new(summary, body, icon_path, nil)
@notification = ::FFI::AutoPointer.new(raw_ptr, method(:g_object_unref))
show
end
|
ruby
|
{
"resource": ""
}
|
q26886
|
Libnotify.API.update
|
test
|
def update(options={}, &block)
apply_options(options, &block)
if @notification
notify_notification_update(@notification, summary, body, icon_path, nil)
show
else
show!
end
end
|
ruby
|
{
"resource": ""
}
|
q26887
|
YoutubeDL.Video.download
|
test
|
def download
raise ArgumentError.new('url cannot be nil') if @url.nil?
raise ArgumentError.new('url cannot be empty') if @url.empty?
set_information_from_json(YoutubeDL::Runner.new(url, runner_options).run)
end
|
ruby
|
{
"resource": ""
}
|
q26888
|
YoutubeDL.Video.method_missing
|
test
|
def method_missing(method, *args, &block)
value = information[method]
if value.nil?
super
else
value
end
end
|
ruby
|
{
"resource": ""
}
|
q26889
|
YoutubeDL.Runner.options_to_commands
|
test
|
def options_to_commands
commands = []
@options.sanitize_keys.each_paramized_key do |key, paramized_key|
if @options[key].to_s == 'true'
commands.push "--#{paramized_key}"
elsif @options[key].to_s == 'false'
commands.push "--no-#{paramized_key}"
else
commands.push "--#{paramized_key} :#{key}"
end
end
commands.push quoted(url)
commands.join(' ')
end
|
ruby
|
{
"resource": ""
}
|
q26890
|
YoutubeDL.Options.with
|
test
|
def with(hash)
merged = Options.new(@store.merge(hash.to_h))
merged.banned_keys = @banned_keys
merged.send(:remove_banned)
merged
end
|
ruby
|
{
"resource": ""
}
|
q26891
|
YoutubeDL.Options.method_missing
|
test
|
def method_missing(method, *args, &_block)
remove_banned
if method.to_s.include? '='
method = method.to_s.tr('=', '').to_sym
return nil if banned? method
@store[method] = args.first
else
return nil if banned? method
@store[method]
end
end
|
ruby
|
{
"resource": ""
}
|
q26892
|
YoutubeDL.Options.manipulate_keys!
|
test
|
def manipulate_keys!(&block)
@store.keys.each do |old_name|
new_name = block.call(old_name)
unless new_name == old_name
@store[new_name] = @store[old_name]
@store.delete(old_name)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q26893
|
YoutubeDL.Options.sanitize_keys!
|
test
|
def sanitize_keys!
# Symbolize
manipulate_keys! { |key_name| key_name.is_a?(Symbol) ? key_name : key_name.to_sym }
# Underscoreize (because Cocaine doesn't like hyphens)
manipulate_keys! { |key_name| key_name.to_s.tr('-', '_').to_sym }
end
|
ruby
|
{
"resource": ""
}
|
q26894
|
Roar::Rails.ControllerAdditions.representer_for
|
test
|
def representer_for(format, model, options={})
options.delete(:represent_with) || self.class.represents_options.for(format, model, controller_path)
end
|
ruby
|
{
"resource": ""
}
|
q26895
|
Easyzpl.LabelTemplate.variable_text_field
|
test
|
def variable_text_field(x, y, params = {})
x = 0 unless numeric?(x)
y = 0 unless numeric?(y)
options = { height: 0.1, width: 0.1 }.merge!(params)
# update the variable field count
self.variable_fields_count += 1
label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +
Integer(y * printer_dpi).to_s)
if params[:orientation] == :landscape
label_data.push('^A0N,')
else
label_data.push('^A0B,')
end
label_data.push(Integer(options[:height] * printer_dpi).to_s + ',' +
Integer(options[:width] * printer_dpi).to_s +
'^FN' + variable_fields_count.to_s + '^FS')
# return unless label_height > 0 && label_width > 0
# pdf.text_box '{Variable Field ' + variable_fields_count.to_s + '}',
# at: [Integer(x * pdf_dpi), Integer(label_width * pdf_dpi) -
# Integer(y * pdf_dpi) -
# Integer(options[:height] / 10) * pdf_dpi],
# size: Integer(options[:height] * pdf_dpi) if label_height &&
# label_width
end
|
ruby
|
{
"resource": ""
}
|
q26896
|
Easyzpl.Label.home_position
|
test
|
def home_position(x, y)
x = 0 unless numeric?(x)
y = 0 unless numeric?(y)
label_data.push('^LH' + x.to_s + ',' + y.to_s)
end
|
ruby
|
{
"resource": ""
}
|
q26897
|
Easyzpl.Label.draw_border
|
test
|
def draw_border(x, y, height, width)
return unless numeric?(height) && numeric?(width)
x = 0 unless numeric?(x)
y = 0 unless numeric?(y)
label_data.push('^FO' + Integer(x * printer_dpi).to_s + ',' +
Integer(y * printer_dpi).to_s + '^GB' +
Integer(height * printer_dpi).to_s +
',' + Integer(width * printer_dpi).to_s + ',1^FS')
# draw_rectangle(x * pdf_dpi, y * pdf_dpi, height * pdf_dpi, width * pdf_dpi)
end
|
ruby
|
{
"resource": ""
}
|
q26898
|
Easyzpl.Label.reset_barcode_fields_to_default
|
test
|
def reset_barcode_fields_to_default
label_data.push('^BY' + Integer(self.barcode_default_module_width).to_s + ',' +
Float(self.barcode_default_width_ratio).to_s + ',' +
Integer(self.barcode_default_height).to_s)
end
|
ruby
|
{
"resource": ""
}
|
q26899
|
Easyzpl.Label.draw_bar_code_39
|
test
|
def draw_bar_code_39(bar_code_string, x, y, height)
return unless label_height > 0 && label_width > 0
pdf.bounding_box [x, Integer(label_width) - y - (height * pdf_dpi)],
width: (height * pdf_dpi) do
barcode = Barby::Code39.new(bar_code_string)
barcode.annotate_pdf(pdf, height: (height * pdf_dpi))
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.