_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q800
|
JOSE.JWE.key_encrypt
|
train
|
def key_encrypt(key, decrypted_key)
encrypted_key, new_alg = alg.key_encrypt(key, enc, decrypted_key)
new_jwe = JOSE::JWE.from_map(to_map)
new_jwe.alg = new_alg
return encrypted_key, new_jwe
end
|
ruby
|
{
"resource": ""
}
|
q801
|
JOSE.JWE.next_cek
|
train
|
def next_cek(key)
decrypted_key, new_alg = alg.next_cek(key, enc)
new_jwe = JOSE::JWE.from_map(to_map)
new_jwe.alg = new_alg
return decrypted_key, new_jwe
end
|
ruby
|
{
"resource": ""
}
|
q802
|
Stove.Validator.run
|
train
|
def run(cookbook, options = {})
log.info("Running validations for `#{klass.id}.#{id}'")
inside(cookbook) do
instance = klass.new(cookbook, options)
unless result = instance.instance_eval(&block)
log.debug("Validation failed, result: #{result.inspect}")
# Convert the class and id to their magical equivalents
error = Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed")
raise error.new(path: Dir.pwd, result: result)
end
end
log.debug("Validation #{id} passed!")
end
|
ruby
|
{
"resource": ""
}
|
q803
|
Stove.Packager.tar
|
train
|
def tar(root, slip)
io = StringIO.new('', 'r+b')
Gem::Package::TarWriter.new(io) do |tar|
slip.each do |original_file, tarball_file|
mode = File.stat(original_file).mode
if File.directory?(original_file)
tar.mkdir(tarball_file, mode)
else
tar.add_file(tarball_file, mode) do |tf|
File.open(original_file, 'rb') { |f| tf.write(f.read) }
end
end
end
end
io.rewind
io
end
|
ruby
|
{
"resource": ""
}
|
q804
|
Stove.Cli.option_parser
|
train
|
def option_parser
@option_parser ||= OptionParser.new do |opts|
opts.banner = 'Usage: stove [OPTIONS]'
opts.separator ''
opts.separator 'Plugins:'
opts.on('--no-git', 'Do not use the git plugin. Skips tagging if specified.') do
options[:no_git] = true
end
opts.separator ''
opts.separator 'Upload Options:'
opts.on('--endpoint [URL]', 'Supermarket endpoint') do |v|
options[:endpoint] = v
end
opts.on('--username [USERNAME]', 'Username to authenticate with') do |v|
options[:username] = v
end
opts.on('--key [PATH]', 'Path to the private key on disk') do |v|
options[:key] = v
end
opts.on('--[no-]extended-metadata', 'Include non-backwards compatible metadata keys such as `issues_url`') do |v|
options[:extended_metadata] = v
end
opts.on('--no-ssl-verify', 'Turn off ssl verify') do
options[:ssl_verify] = false
end
opts.separator ''
opts.separator 'Git Options:'
opts.on('--remote [REMOTE]', 'Name of the git remote') do |v|
options[:remote] = v
end
opts.on('--branch [BRANCH]', 'Name of the git branch') do |v|
options[:branch] = v
end
opts.on('--sign', 'Sign git tags') do
options[:sign] = true
end
opts.separator ''
opts.separator 'Artifactory Options:'
opts.on('--artifactory [URL]', 'URL for the Artifactory repository') do |v|
options[:artifactory] = v
end
opts.on('--artifactory-key [KEY]', 'Artifactory API key to use') do |v|
options[:artifactory_key] = if v[0] == '@'
# If passed a key looking like @foo, read it as a file. This allows
# passing in the key securely.
IO.read(File.expand_path(v[1..-1]))
else
v
end
end
opts.separator ''
opts.separator 'Global Options:'
opts.on('--log-level [LEVEL]', 'Set the log verbosity') do |v|
options[:log_level] = v
end
opts.on('--path [PATH]', 'Change the path to a cookbook') do |v|
options[:path] = v
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
opts.on_tail('-v', '--version', 'Show version') do
puts Stove::VERSION
exit(0)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q805
|
Stove.Cli.options
|
train
|
def options
@options ||= {
# Upload options
:endpoint => nil,
:username => Config.username,
:key => Config.key,
:extended_metadata => true,
:ssl_verify => true,
# Git options
:remote => 'origin',
:branch => 'master',
:sign => false,
# Artifactory options
:artifactory => false,
:artifactory_key => ENV['ARTIFACTORY_API_KEY'],
# Global options
:log_level => :warn,
:path => Dir.pwd,
}
end
|
ruby
|
{
"resource": ""
}
|
q806
|
Stove.Supermarket.upload
|
train
|
def upload(cookbook, extended_metadata = false)
connection.post('cookbooks', {
'tarball' => cookbook.tarball(extended_metadata),
# This is for legacy, backwards-compatability reasons. The new
# Supermarket site does not require a category, but many of the testing
# tools still assume a cookbook category is present. We just hardcode
# "Other" here.
'cookbook' => JSON.fast_generate(category: 'Other'),
})
end
|
ruby
|
{
"resource": ""
}
|
q807
|
Stove.Supermarket.connection
|
train
|
def connection
@connection ||= ChefAPI::Connection.new do |conn|
conn.endpoint = ENV['STOVE_ENDPOINT'] || Config.endpoint || DEFAULT_ENDPOINT
conn.client = ENV['STOVE_USERNAME'] || Config.username
conn.key = ENV['STOVE_KEY'] || Config.key
conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify
end
end
|
ruby
|
{
"resource": ""
}
|
q808
|
Stove.Artifactory.upload
|
train
|
def upload(cookbook, extended_metadata = false)
# Artifactory doesn't prevent uploading over an existing release in
# some cases so let's check for that. Seriously never do this, go delete
# and then re-upload if you have to.
response = request(:get, "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}")
# Artifactory's version of the cookbook_version endpoint returns an
# empty 200 on an unknown version.
unless response.code == '404' || (response.code == '200' && response.body.to_s == '')
raise Error::CookbookAlreadyExists.new(cookbook: cookbook)
end
# Run the upload.
response = request(:post, "api/v1/cookbooks/#{cookbook.name}.tgz") do |req|
req.body_stream = cookbook.tarball(extended_metadata)
req.content_length = req.body_stream.size
req['Content-Type'] = 'application/x-binary'
end
response.error! unless response.code == '201'
end
|
ruby
|
{
"resource": ""
}
|
q809
|
Stove.Artifactory.connection
|
train
|
def connection
@connection ||= begin
uri = URI(Config.artifactory.strip)
# Open the HTTP connection to artifactory.
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
# Mimic the behavior of the Cookbook uploader for SSL verification.
if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
end
http.start
end
end
|
ruby
|
{
"resource": ""
}
|
q810
|
Stove.Artifactory.request
|
train
|
def request(method, path, &block)
uri_string = Config.artifactory.strip
# Make sure we end up with the right number of separators.
uri_string << '/' unless uri_string.end_with?('/')
uri_string << path
uri = URI(uri_string)
request = Net::HTTP.const_get(method.to_s.capitalize).new(uri)
request['X-Jfrog-Art-Api'] = Config.artifactory_key.strip
block.call(request) if block
connection.request(request)
end
|
ruby
|
{
"resource": ""
}
|
q811
|
Stove.Cookbook.released?
|
train
|
def released?
Supermarket.cookbook(name, version)
true
rescue ChefAPI::Error::HTTPNotFound
false
end
|
ruby
|
{
"resource": ""
}
|
q812
|
Stove.Filter.run
|
train
|
def run(cookbook, options = {})
log.info(message)
instance = klass.new(cookbook, options)
inside(cookbook) do
instance.instance_eval(&block)
end
end
|
ruby
|
{
"resource": ""
}
|
q813
|
Erubis.RubyEvaluator.evaluate
|
train
|
def evaluate(_context=Context.new)
_context = Context.new(_context) if _context.is_a?(Hash)
#return _context.instance_eval(@src, @filename || '(erubis)')
#@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)')
@_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)')
return _context.instance_eval(&@_proc)
end
|
ruby
|
{
"resource": ""
}
|
q814
|
Erubis.RubyEvaluator.def_method
|
train
|
def def_method(object, method_name, filename=nil)
m = object.is_a?(Module) ? :module_eval : :instance_eval
object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)')
end
|
ruby
|
{
"resource": ""
}
|
q815
|
Erubis.Converter.convert
|
train
|
def convert(input)
codebuf = "" # or []
@preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble))
convert_input(codebuf, input)
@postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble))
@_proc = nil # clear cached proc object
return codebuf # or codebuf.join()
end
|
ruby
|
{
"resource": ""
}
|
q816
|
Erubis.Converter.detect_spaces_at_bol
|
train
|
def detect_spaces_at_bol(text, is_bol)
lspace = nil
if text.empty?
lspace = "" if is_bol
elsif text[-1] == ?\n
lspace = ""
else
rindex = text.rindex(?\n)
if rindex
s = text[rindex+1..-1]
if s =~ /\A[ \t]*\z/
lspace = s
#text = text[0..rindex]
text[rindex+1..-1] = ''
end
else
if is_bol && text =~ /\A[ \t]*\z/
#lspace = text
#text = nil
lspace = text.dup
text[0..-1] = ''
end
end
end
return lspace
end
|
ruby
|
{
"resource": ""
}
|
q817
|
Erubis.Engine.process
|
train
|
def process(input, context=nil, filename=nil)
code = convert(input)
filename ||= '(erubis)'
if context.is_a?(Binding)
return eval(code, context, filename)
else
context = Context.new(context) if context.is_a?(Hash)
return context.instance_eval(code, filename)
end
end
|
ruby
|
{
"resource": ""
}
|
q818
|
Erubis.Engine.process_proc
|
train
|
def process_proc(proc_obj, context=nil, filename=nil)
if context.is_a?(Binding)
filename ||= '(erubis)'
return eval(proc_obj, context, filename)
else
context = Context.new(context) if context.is_a?(Hash)
return context.instance_eval(&proc_obj)
end
end
|
ruby
|
{
"resource": ""
}
|
q819
|
LIBUSB.Device.open
|
train
|
def open
ppHandle = FFI::MemoryPointer.new :pointer
res = Call.libusb_open(@pDev, ppHandle)
LIBUSB.raise_error res, "in libusb_open" if res!=0
handle = DevHandle.new self, ppHandle.read_pointer
return handle unless block_given?
begin
yield handle
ensure
handle.close
end
end
|
ruby
|
{
"resource": ""
}
|
q820
|
LIBUSB.Device.max_packet_size
|
train
|
def max_packet_size(endpoint)
endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress
res = Call.libusb_get_max_packet_size(@pDev, endpoint)
LIBUSB.raise_error res, "in libusb_get_max_packet_size" unless res>=0
res
end
|
ruby
|
{
"resource": ""
}
|
q821
|
LIBUSB.Device.max_iso_packet_size
|
train
|
def max_iso_packet_size(endpoint)
endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress
res = Call.libusb_get_max_iso_packet_size(@pDev, endpoint)
LIBUSB.raise_error res, "in libusb_get_max_iso_packet_size" unless res>=0
res
end
|
ruby
|
{
"resource": ""
}
|
q822
|
LIBUSB.Device.config_descriptor
|
train
|
def config_descriptor(index)
ppConfig = FFI::MemoryPointer.new :pointer
res = Call.libusb_get_config_descriptor(@pDev, index, ppConfig)
LIBUSB.raise_error res, "in libusb_get_config_descriptor" if res!=0
pConfig = ppConfig.read_pointer
config = Configuration.new(self, pConfig)
config
end
|
ruby
|
{
"resource": ""
}
|
q823
|
LIBUSB.Device.configurations
|
train
|
def configurations
configs = []
bNumConfigurations.times do |config_index|
begin
configs << config_descriptor(config_index)
rescue RuntimeError
# On Windows some devices don't return it's configuration.
end
end
configs
end
|
ruby
|
{
"resource": ""
}
|
q824
|
LIBUSB.Context.eventmachine_register
|
train
|
def eventmachine_register
@eventmachine_attached_fds = {}
@eventmachine_timer = nil
pollfds = self.pollfds
if pollfds
pollfds.each do |pollfd|
eventmachine_add_pollfd(pollfd)
end
self.on_pollfd_added do |pollfd|
eventmachine_add_pollfd(pollfd)
end
self.on_pollfd_removed do |pollfd|
eventmachine_rm_pollfd(pollfd)
end
else
# Libusb pollfd API is not available on this platform.
# Use simple polling timer, instead:
EventMachine.add_periodic_timer(0.01) do
@eventmachine_timer = self.handle_events 0
end
end
end
|
ruby
|
{
"resource": ""
}
|
q825
|
LIBUSB.DevHandle.claim_interface
|
train
|
def claim_interface(interface)
interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber
res = Call.libusb_claim_interface(@pHandle, interface)
LIBUSB.raise_error res, "in libusb_claim_interface" if res!=0
return self unless block_given?
begin
yield self
ensure
release_interface(interface)
end
end
|
ruby
|
{
"resource": ""
}
|
q826
|
LIBUSB.DevHandle.set_configuration
|
train
|
def set_configuration(configuration)
configuration = configuration.bConfigurationValue if configuration.respond_to? :bConfigurationValue
res = Call.libusb_set_configuration(@pHandle, configuration || -1)
LIBUSB.raise_error res, "in libusb_set_configuration" if res!=0
end
|
ruby
|
{
"resource": ""
}
|
q827
|
LIBUSB.DevHandle.set_interface_alt_setting
|
train
|
def set_interface_alt_setting(setting_or_interface_number, alternate_setting=nil)
alternate_setting ||= setting_or_interface_number.bAlternateSetting if setting_or_interface_number.respond_to? :bAlternateSetting
setting_or_interface_number = setting_or_interface_number.bInterfaceNumber if setting_or_interface_number.respond_to? :bInterfaceNumber
res = Call.libusb_set_interface_alt_setting(@pHandle, setting_or_interface_number, alternate_setting)
LIBUSB.raise_error res, "in libusb_set_interface_alt_setting" if res!=0
end
|
ruby
|
{
"resource": ""
}
|
q828
|
LIBUSB.DevHandle.kernel_driver_active?
|
train
|
def kernel_driver_active?(interface)
interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber
res = Call.libusb_kernel_driver_active(@pHandle, interface)
LIBUSB.raise_error res, "in libusb_kernel_driver_active" unless res>=0
return res==1
end
|
ruby
|
{
"resource": ""
}
|
q829
|
LIBUSB.DevHandle.detach_kernel_driver
|
train
|
def detach_kernel_driver(interface)
interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber
res = Call.libusb_detach_kernel_driver(@pHandle, interface)
LIBUSB.raise_error res, "in libusb_detach_kernel_driver" if res!=0
end
|
ruby
|
{
"resource": ""
}
|
q830
|
LIBUSB.DevHandle.bulk_transfer
|
train
|
def bulk_transfer(args={}, &block)
timeout = args.delete(:timeout) || 1000
endpoint = args.delete(:endpoint) || raise(ArgumentError, "no endpoint given")
endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress
if endpoint&ENDPOINT_IN != 0
dataIn = args.delete(:dataIn) || raise(ArgumentError, "no :dataIn given for bulk read")
else
dataOut = args.delete(:dataOut) || raise(ArgumentError, "no :dataOut given for bulk write")
end
raise ArgumentError, "invalid params #{args.inspect}" unless args.empty?
# reuse transfer struct to speed up transfer
@bulk_transfer ||= BulkTransfer.new dev_handle: self, allow_device_memory: true
tr = @bulk_transfer
tr.endpoint = endpoint
tr.timeout = timeout
if dataOut
tr.buffer = dataOut
else
tr.alloc_buffer(dataIn)
end
submit_transfer(tr, dataIn, 0, &block)
end
|
ruby
|
{
"resource": ""
}
|
q831
|
LIBUSB.DevHandle.control_transfer
|
train
|
def control_transfer(args={}, &block)
bmRequestType = args.delete(:bmRequestType) || raise(ArgumentError, "param :bmRequestType not given")
bRequest = args.delete(:bRequest) || raise(ArgumentError, "param :bRequest not given")
wValue = args.delete(:wValue) || raise(ArgumentError, "param :wValue not given")
wIndex = args.delete(:wIndex) || raise(ArgumentError, "param :wIndex not given")
timeout = args.delete(:timeout) || 1000
if bmRequestType&ENDPOINT_IN != 0
dataIn = args.delete(:dataIn) || 0
dataOut = ''
else
dataOut = args.delete(:dataOut) || ''
end
raise ArgumentError, "invalid params #{args.inspect}" unless args.empty?
# reuse transfer struct to speed up transfer
@control_transfer ||= ControlTransfer.new dev_handle: self, allow_device_memory: true
tr = @control_transfer
tr.timeout = timeout
if dataIn
setup_data = [bmRequestType, bRequest, wValue, wIndex, dataIn].pack('CCvvv')
tr.alloc_buffer( dataIn + CONTROL_SETUP_SIZE, setup_data )
else
tr.buffer = [bmRequestType, bRequest, wValue, wIndex, dataOut.bytesize, dataOut].pack('CCvvva*')
end
submit_transfer(tr, dataIn, CONTROL_SETUP_SIZE, &block)
end
|
ruby
|
{
"resource": ""
}
|
q832
|
LIBUSB.Bos.device_capabilities
|
train
|
def device_capabilities
pp_ext = FFI::MemoryPointer.new :pointer
caps = []
# Capabilities are appended to the bos header
ptr = pointer + offset_of(:dev_capability)
bNumDeviceCaps.times do
cap = DeviceCapability.new self, ptr.read_pointer
case cap.bDevCapabilityType
when LIBUSB::BT_WIRELESS_USB_DEVICE_CAPABILITY
# no struct defined in libusb -> use generic DeviceCapability
when LIBUSB::BT_USB_2_0_EXTENSION
res = Call.libusb_get_usb_2_0_extension_descriptor(@ctx, cap.pointer, pp_ext)
cap = Usb20Extension.new(pp_ext.read_pointer) if res==0
when LIBUSB::BT_SS_USB_DEVICE_CAPABILITY
res = Call.libusb_get_ss_usb_device_capability_descriptor(@ctx, cap.pointer, pp_ext)
cap = SsUsbDeviceCapability.new(pp_ext.read_pointer) if res==0
when LIBUSB::BT_CONTAINER_ID
res = Call.libusb_get_container_id_descriptor(@ctx, cap.pointer, pp_ext)
cap = ContainerId.new(pp_ext.read_pointer) if res==0
else
# unknown capability -> use generic DeviceCapability
end
ptr += FFI.type_size(:pointer)
caps << cap
end
caps
end
|
ruby
|
{
"resource": ""
}
|
q833
|
LIBUSB.Transfer.submit!
|
train
|
def submit!(&block)
self.callback = block if block_given?
# puts "submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}"
res = Call.libusb_submit_transfer( @transfer )
LIBUSB.raise_error res, "in libusb_submit_transfer" if res!=0
end
|
ruby
|
{
"resource": ""
}
|
q834
|
LIBUSB.Transfer.submit_and_wait
|
train
|
def submit_and_wait
raise ArgumentError, "#{self.class}#dev_handle not set" unless @dev_handle
@completion_flag.completed = false
submit! do |tr2|
@completion_flag.completed = true
end
until @completion_flag.completed?
begin
@dev_handle.device.context.handle_events nil, @completion_flag
rescue ERROR_INTERRUPTED
next
rescue LIBUSB::Error
cancel!
until @completion_flag.completed?
@dev_handle.device.context.handle_events nil, @completion_flag
end
raise
end
end
end
|
ruby
|
{
"resource": ""
}
|
q835
|
LIBUSB.Context.handle_events
|
train
|
def handle_events(timeout=nil, completion_flag=nil)
if completion_flag && !completion_flag.is_a?(Context::CompletionFlag)
raise ArgumentError, "completion_flag is not a CompletionFlag"
end
if timeout
timeval = Call::Timeval.new
timeval.in_ms = timeout
res = if Call.respond_to?(:libusb_handle_events_timeout_completed)
Call.libusb_handle_events_timeout_completed(@ctx, timeval, completion_flag)
else
Call.libusb_handle_events_timeout(@ctx, timeval)
end
else
res = if Call.respond_to?(:libusb_handle_events_completed)
Call.libusb_handle_events_completed(@ctx, completion_flag )
else
Call.libusb_handle_events(@ctx)
end
end
LIBUSB.raise_error res, "in libusb_handle_events" if res<0
end
|
ruby
|
{
"resource": ""
}
|
q836
|
LIBUSB.Context.devices
|
train
|
def devices(filter_hash={})
device_list.select do |dev|
( !filter_hash[:bClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ?
dev.settings.map(&:bInterfaceClass).&([filter_hash[:bClass]].flatten).any? :
[filter_hash[:bClass]].flatten.include?(dev.bDeviceClass))) &&
( !filter_hash[:bSubClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ?
dev.settings.map(&:bInterfaceSubClass).&([filter_hash[:bSubClass]].flatten).any? :
[filter_hash[:bSubClass]].flatten.include?(dev.bDeviceSubClass))) &&
( !filter_hash[:bProtocol] || (dev.bDeviceClass==CLASS_PER_INTERFACE ?
dev.settings.map(&:bInterfaceProtocol).&([filter_hash[:bProtocol]].flatten).any? :
[filter_hash[:bProtocol]].flatten.include?(dev.bDeviceProtocol))) &&
( !filter_hash[:bMaxPacketSize0] || [filter_hash[:bMaxPacketSize0]].flatten.include?(dev.bMaxPacketSize0) ) &&
( !filter_hash[:idVendor] || [filter_hash[:idVendor]].flatten.include?(dev.idVendor) ) &&
( !filter_hash[:idProduct] || [filter_hash[:idProduct]].flatten.include?(dev.idProduct) ) &&
( !filter_hash[:bcdUSB] || [filter_hash[:bcdUSB]].flatten.include?(dev.bcdUSB) ) &&
( !filter_hash[:bcdDevice] || [filter_hash[:bcdDevice]].flatten.include?(dev.bcdDevice) )
end
end
|
ruby
|
{
"resource": ""
}
|
q837
|
LIBUSB.Context.pollfds
|
train
|
def pollfds
ppPollfds = Call.libusb_get_pollfds(@ctx)
return nil if ppPollfds.null?
offs = 0
pollfds = []
while !(pPollfd=ppPollfds.get_pointer(offs)).null?
pollfd = Call::Pollfd.new pPollfd
pollfds << Pollfd.new(pollfd[:fd], pollfd[:events])
offs += FFI.type_size :pointer
end
if Call.respond_to?(:libusb_free_pollfds)
Call.libusb_free_pollfds(ppPollfds)
else
Stdio.free(ppPollfds)
end
pollfds
end
|
ruby
|
{
"resource": ""
}
|
q838
|
LIBUSB.Context.next_timeout
|
train
|
def next_timeout
timeval = Call::Timeval.new
res = Call.libusb_get_next_timeout @ctx, timeval
LIBUSB.raise_error res, "in libusb_get_next_timeout" if res<0
res == 1 ? timeval.in_s : nil
end
|
ruby
|
{
"resource": ""
}
|
q839
|
LIBUSB.Context.on_pollfd_added
|
train
|
def on_pollfd_added &block
@on_pollfd_added = proc do |fd, events, _|
pollfd = Pollfd.new fd, events
block.call pollfd
end
Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil
end
|
ruby
|
{
"resource": ""
}
|
q840
|
LIBUSB.Context.on_pollfd_removed
|
train
|
def on_pollfd_removed &block
@on_pollfd_removed = proc do |fd, _|
pollfd = Pollfd.new fd
block.call pollfd
end
Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil
end
|
ruby
|
{
"resource": ""
}
|
q841
|
LIBUSB.Context.on_hotplug_event
|
train
|
def on_hotplug_event(args={}, &block)
events = args.delete(:events) || (HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT)
flags = args.delete(:flags) || 0
vendor_id = args.delete(:vendor_id) || HOTPLUG_MATCH_ANY
product_id = args.delete(:product_id) || HOTPLUG_MATCH_ANY
dev_class = args.delete(:dev_class) || HOTPLUG_MATCH_ANY
raise ArgumentError, "invalid params #{args.inspect}" unless args.empty?
handle = HotplugCallback.new self, @ctx, @hotplug_callbacks
block2 = proc do |ctx, pDevice, event, _user_data|
raise "internal error: unexpected context" unless @ctx==ctx
dev = Device.new @ctx, pDevice
blres = block.call(dev, event)
case blres
when :finish
1
when :repeat
0
else
raise ArgumentError, "hotplug event handler must return :finish or :repeat"
end
end
res = Call.libusb_hotplug_register_callback(@ctx,
events, flags,
vendor_id, product_id, dev_class,
block2, nil, handle)
LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0
# Avoid GC'ing of the block:
@hotplug_callbacks[handle[:handle]] = block2
return handle
end
|
ruby
|
{
"resource": ""
}
|
q842
|
Telegrammer.Bot.send_message
|
train
|
def send_message(params)
extra_params_validation = {
text: { required: true, class: [String] },
parse_mode: { required: false, class: [String] },
disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] }
}
send_something(:message, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q843
|
Telegrammer.Bot.forward_message
|
train
|
def forward_message(params)
params_validation = {
chat_id: { required: true, class: [Fixnum] },
from_chat_id: { required: true, class: [String] },
message_id: { required: true, class: [Fixnum] }
}
response = api_request('forwardMessage', params, params_validation)
Telegrammer::DataTypes::Message.new(response.result)
end
|
ruby
|
{
"resource": ""
}
|
q844
|
Telegrammer.Bot.send_photo
|
train
|
def send_photo(params)
extra_params_validation = {
photo: { required: true, class: [File, String] },
caption: { required: false, class: [String] }
}
send_something(:photo, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q845
|
Telegrammer.Bot.send_audio
|
train
|
def send_audio(params)
extra_params_validation = {
audio: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
performer: { required: false, class: [String] },
title: { required: false, class: [String] }
}
send_something(:audio, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q846
|
Telegrammer.Bot.send_voice
|
train
|
def send_voice(params)
extra_params_validation = {
voice: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] }
}
send_something(:audio, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q847
|
Telegrammer.Bot.send_document
|
train
|
def send_document(params)
extra_params_validation = {
document: { required: true, class: [File, String] }
}
send_something(:document, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q848
|
Telegrammer.Bot.send_sticker
|
train
|
def send_sticker(params)
extra_params_validation = {
sticker: { required: true, class: [File, String] }
}
send_something(:sticker, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q849
|
Telegrammer.Bot.send_video
|
train
|
def send_video(params)
extra_params_validation = {
video: { required: true, class: [File, String] },
duration: { required: false, class: [Integer] },
caption: { required: false, class: [String] }
}
send_something(:video, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q850
|
Telegrammer.Bot.send_location
|
train
|
def send_location(params)
extra_params_validation = {
latitude: { required: true, class: [Float] },
longitude: { required: true, class: [Float] }
}
send_something(:location, params, extra_params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q851
|
Telegrammer.Bot.send_chat_action
|
train
|
def send_chat_action(params)
params_validation = {
chat_id: { required: true, class: [Fixnum, String] },
action: { required: true, class: [String] }
}
api_request('sendChatAction', params, params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q852
|
Telegrammer.Bot.get_user_profile_photos
|
train
|
def get_user_profile_photos(params)
params_validation = {
user_id: { required: true, class: [Fixnum] },
offset: { required: false, class: [Fixnum] },
limit: { required: false, class: [Fixnum] }
}
response = api_request('getUserProfilePhotos', params, params_validation)
Telegrammer::DataTypes::UserProfilePhotos.new(response.result).to_h
end
|
ruby
|
{
"resource": ""
}
|
q853
|
Telegrammer.Bot.get_file
|
train
|
def get_file(params)
params_validation = {
file_id: { required: true, class: [String] }
}
response = api_request("getFile", params, params_validation)
file_object = Telegrammer::DataTypes::File.new(response.result)
"#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}"
end
|
ruby
|
{
"resource": ""
}
|
q854
|
Telegrammer.Bot.answer_inline_query
|
train
|
def answer_inline_query(params)
params_validation = {
inline_query_id: { required: true, class: [String] },
results: { required: true, class: [Array] },
cache_time: { required: false, class: [Fixnum] },
is_personal: { required: false, class: [TrueClass, FalseClass] },
next_offset: { required: false, class: [String] }
}
response = api_request("answerInlineQuery", params, params_validation)
end
|
ruby
|
{
"resource": ""
}
|
q855
|
GoogleMapsService::Apis.DistanceMatrix.distance_matrix
|
train
|
def distance_matrix(origins, destinations,
mode: nil, language: nil, avoid: nil, units: nil,
departure_time: nil, arrival_time: nil, transit_mode: nil,
transit_routing_preference: nil)
params = {
origins: GoogleMapsService::Convert.waypoints(origins),
destinations: GoogleMapsService::Convert.waypoints(destinations)
}
params[:language] = language if language
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
params[:avoid] = GoogleMapsService::Validator.avoid(avoid) if avoid
params[:units] = units if units
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list('|', transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/distancematrix/json', params)
end
|
ruby
|
{
"resource": ""
}
|
q856
|
GoogleMapsService.Convert.components
|
train
|
def components(arg)
if arg.kind_of?(Hash)
arg = arg.sort.map { |k, v| "#{k}:#{v}" }
return arg.join("|")
end
raise ArgumentError, "Expected a Hash for components, but got #{arg.class}"
end
|
ruby
|
{
"resource": ""
}
|
q857
|
GoogleMapsService.Convert.waypoint
|
train
|
def waypoint(waypoint)
if waypoint.kind_of?(String)
return waypoint
end
return GoogleMapsService::Convert.latlng(waypoint)
end
|
ruby
|
{
"resource": ""
}
|
q858
|
GoogleMapsService::Apis.Geocoding.reverse_geocode
|
train
|
def reverse_geocode(latlng, location_type: nil, result_type: nil, language: nil)
params = {
latlng: GoogleMapsService::Convert.latlng(latlng)
}
params[:result_type] = GoogleMapsService::Convert.join_list('|', result_type) if result_type
params[:location_type] = GoogleMapsService::Convert.join_list('|', location_type) if location_type
params[:language] = language if language
return get('/maps/api/geocode/json', params)[:results]
end
|
ruby
|
{
"resource": ""
}
|
q859
|
GoogleMapsService::Apis.TimeZone.timezone
|
train
|
def timezone(location, timestamp: Time.now, language: nil)
location = GoogleMapsService::Convert.latlng(location)
timestamp = GoogleMapsService::Convert.time(timestamp)
params = {
location: location,
timestamp: timestamp
}
params[:language] = language if language
return get('/maps/api/timezone/json', params)
end
|
ruby
|
{
"resource": ""
}
|
q860
|
GoogleMapsService.Url.sign_hmac
|
train
|
def sign_hmac(secret, payload)
secret = secret.encode('ASCII')
payload = payload.encode('ASCII')
# Decode the private key
raw_key = Base64.urlsafe_decode64(secret)
# Create a signature using the private key and the URL
digest = OpenSSL::Digest.new('sha1')
raw_signature = OpenSSL::HMAC.digest(digest, raw_key, payload)
# Encode the signature into base64 for url use form.
signature = Base64.urlsafe_encode64(raw_signature)
return signature
end
|
ruby
|
{
"resource": ""
}
|
q861
|
GoogleMapsService.Url.unquote_unreserved
|
train
|
def unquote_unreserved(uri)
parts = uri.split('%')
(1..parts.length-1).each do |i|
h = parts[i][0..1]
if h =~ /^([\h]{2})(.*)/ and c = $1.to_i(16).chr and UNRESERVED_SET.include?(c)
parts[i] = c + $2
else
parts[i] = '%' + parts[i]
end
end
parts.join
end
|
ruby
|
{
"resource": ""
}
|
q862
|
GoogleMapsService.Client.new_client
|
train
|
def new_client
client = Hurley::Client.new
client.request_options.query_class = Hurley::Query::Flat
client.request_options.redirection_limit = 0
client.header[:user_agent] = user_agent
client.connection = @connection if @connection
@request_options.each_pair {|key, value| client.request_options[key] = value } if @request_options
@ssl_options.each_pair {|key, value| client.ssl_options[key] = value } if @ssl_options
client
end
|
ruby
|
{
"resource": ""
}
|
q863
|
GoogleMapsService.Client.get
|
train
|
def get(path, params, base_url: DEFAULT_BASE_URL, accepts_client_id: true, custom_response_decoder: nil)
url = base_url + generate_auth_url(path, params, accepts_client_id)
Retriable.retriable timeout: @retry_timeout, on: RETRIABLE_ERRORS do |try|
begin
request_query_ticket
response = client.get url
ensure
release_query_ticket
end
return custom_response_decoder.call(response) if custom_response_decoder
decode_response_body(response)
end
end
|
ruby
|
{
"resource": ""
}
|
q864
|
GoogleMapsService.Client.generate_auth_url
|
train
|
def generate_auth_url(path, params, accepts_client_id)
# Deterministic ordering through sorting by key.
# Useful for tests, and in the future, any caching.
if params.kind_of?(Hash)
params = params.sort
else
params = params.dup
end
if accepts_client_id and @client_id and @client_secret
params << ["client", @client_id]
path = [path, GoogleMapsService::Url.urlencode_params(params)].join("?")
sig = GoogleMapsService::Url.sign_hmac(@client_secret, path)
return path + "&signature=" + sig
end
if @key
params << ["key", @key]
return path + "?" + GoogleMapsService::Url.urlencode_params(params)
end
raise ArgumentError, "Must provide API key for this API. It does not accept enterprise credentials."
end
|
ruby
|
{
"resource": ""
}
|
q865
|
GoogleMapsService.Client.decode_response_body
|
train
|
def decode_response_body(response)
check_response_status_code(response)
body = MultiJson.load(response.body, :symbolize_keys => true)
check_body_error(response, body)
body
end
|
ruby
|
{
"resource": ""
}
|
q866
|
GoogleMapsService.Client.check_response_status_code
|
train
|
def check_response_status_code(response)
case response.status_code
when 200..300
# Do-nothing
when 301, 302, 303, 307
raise GoogleMapsService::Error::RedirectError.new(response), sprintf('Redirect to %s', response.header[:location])
when 401
raise GoogleMapsService::Error::ClientError.new(response), 'Unauthorized'
when 304, 400, 402...500
raise GoogleMapsService::Error::ClientError.new(response), 'Invalid request'
when 500..600
raise GoogleMapsService::Error::ServerError.new(response), 'Server error'
end
end
|
ruby
|
{
"resource": ""
}
|
q867
|
GoogleMapsService::Apis.Directions.directions
|
train
|
def directions(origin, destination,
mode: nil, waypoints: nil, alternatives: false, avoid: nil,
language: nil, units: nil, region: nil, departure_time: nil,
arrival_time: nil, optimize_waypoints: false, transit_mode: nil,
transit_routing_preference: nil)
params = {
origin: GoogleMapsService::Convert.waypoint(origin),
destination: GoogleMapsService::Convert.waypoint(destination)
}
params[:mode] = GoogleMapsService::Validator.travel_mode(mode) if mode
if waypoints = waypoints
waypoints = GoogleMapsService::Convert.as_list(waypoints)
waypoints = waypoints.map { |waypoint| GoogleMapsService::Convert.waypoint(waypoint) }
waypoints = ['optimize:true'] + waypoints if optimize_waypoints
params[:waypoints] = GoogleMapsService::Convert.join_list("|", waypoints)
end
params[:alternatives] = 'true' if alternatives
params[:avoid] = GoogleMapsService::Convert.join_list('|', avoid) if avoid
params[:language] = language if language
params[:units] = units if units
params[:region] = region if region
params[:departure_time] = GoogleMapsService::Convert.time(departure_time) if departure_time
params[:arrival_time] = GoogleMapsService::Convert.time(arrival_time) if arrival_time
if departure_time and arrival_time
raise ArgumentError, 'Should not specify both departure_time and arrival_time.'
end
params[:transit_mode] = GoogleMapsService::Convert.join_list("|", transit_mode) if transit_mode
params[:transit_routing_preference] = transit_routing_preference if transit_routing_preference
return get('/maps/api/directions/json', params)[:routes]
end
|
ruby
|
{
"resource": ""
}
|
q868
|
GoogleMapsService::Apis.Elevation.elevation_along_path
|
train
|
def elevation_along_path(path, samples)
if path.kind_of?(String)
path = "enc:%s" % path
else
path = GoogleMapsService::Convert.waypoints(path)
end
params = {
path: path,
samples: samples
}
return get('/maps/api/elevation/json', params)[:results]
end
|
ruby
|
{
"resource": ""
}
|
q869
|
GoogleMapsService::Apis.Roads.snap_to_roads
|
train
|
def snap_to_roads(path, interpolate: false)
path = GoogleMapsService::Convert.waypoints(path)
params = {
path: path
}
params[:interpolate] = 'true' if interpolate
return get('/v1/snapToRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end
|
ruby
|
{
"resource": ""
}
|
q870
|
GoogleMapsService::Apis.Roads.nearest_roads
|
train
|
def nearest_roads(points)
points = GoogleMapsService::Convert.waypoints(points)
params = {
points: points
}
return get('/v1/nearestRoads', params,
base_url: ROADS_BASE_URL,
accepts_client_id: false,
custom_response_decoder: method(:extract_roads_body))[:snappedPoints]
end
|
ruby
|
{
"resource": ""
}
|
q871
|
GoogleMapsService::Apis.Roads.extract_roads_body
|
train
|
def extract_roads_body(response)
begin
body = MultiJson.load(response.body, :symbolize_keys => true)
rescue
unless response.status_code == 200
check_response_status_code(response)
end
raise GoogleMapsService::Error::ApiError.new(response), 'Received a malformed response.'
end
check_roads_body_error(response, body)
unless response.status_code == 200
raise GoogleMapsService::Error::ApiError.new(response)
end
return body
end
|
ruby
|
{
"resource": ""
}
|
q872
|
GoogleMapsService.Polyline.encode
|
train
|
def encode(points)
last_lat = last_lng = 0
result = ""
points.each do |point|
ll = GoogleMapsService::Convert.normalize_latlng(point)
lat = (ll[0] * 1e5).round.to_i
lng = (ll[1] * 1e5).round.to_i
d_lat = lat - last_lat
d_lng = lng - last_lng
[d_lat, d_lng].each do |v|
v = (v < 0) ? ~(v << 1) : (v << 1)
while v >= 0x20
result += ((0x20 | (v & 0x1f)) + 63).chr
v >>= 5
end
result += (v + 63).chr
end
last_lat = lat
last_lng = lng
end
result
end
|
ruby
|
{
"resource": ""
}
|
q873
|
Mongoid::FullTextSearch.ClassMethods.map_query_filters
|
train
|
def map_query_filters(filters)
Hash[filters.map do |key, value|
case value
when Hash then
if value.key? :any then format_query_filter('$in', key, value[:any])
elsif value.key? :all then format_query_filter('$all', key, value[:all])
else raise UnknownFilterQueryOperator, value.keys.join(','), caller end
else format_query_filter('$all', key, value)
end
end]
end
|
ruby
|
{
"resource": ""
}
|
q874
|
Stickler.SpecLite.=~
|
train
|
def =~(other)
other = coerce( other )
return (other and
self.name == other.name and
self.version.to_s == other.version.to_s and
self.platform_string == other.platform_string )
end
|
ruby
|
{
"resource": ""
}
|
q875
|
::Stickler::Repository.RemoteMirror.mirror
|
train
|
def mirror( spec, upstream_host )
raise Stickler::Repository::Error, "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist?( spec )
resource_request( mirror_resource( spec, upstream_host ) )
end
|
ruby
|
{
"resource": ""
}
|
q876
|
Stickler::Middleware.Index.marshalled_specs
|
train
|
def marshalled_specs( spec_a )
a = spec_a.collect { |s| s.to_rubygems_a }
marshal( optimize_specs( a ) )
end
|
ruby
|
{
"resource": ""
}
|
q877
|
Stickler.Client.parser
|
train
|
def parser
me = self # scoping forces this
@parser ||= Trollop::Parser.new do
banner me.class.banner
opt :server, "The gem or stickler server URL", :type => :string, :default => Client.config.server
opt :debug, "Output debug information for the server interaction", :default => false
end
end
|
ruby
|
{
"resource": ""
}
|
q878
|
Flickr.Attribute.find_value
|
train
|
def find_value(context)
locations.each do |location|
begin
value = context.instance_exec(&location)
next if value.nil?
return value
rescue
end
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q879
|
Flickr.AttributeSet.add_locations
|
train
|
def add_locations(hash)
hash.each do |attribute_name, locations|
find(attribute_name).add_locations(locations)
end
end
|
ruby
|
{
"resource": ""
}
|
q880
|
Helpers.ClassMethods.record_api_methods
|
train
|
def record_api_methods
before do
stub_const("Flickr::Client::Data", Class.new(Flickr::Client::Data) do
def do_request(http_method, flickr_method, params = {})
VCR.use_cassette(flickr_method) { super }
end
end)
stub_const("Flickr::Client::Upload", Class.new(Flickr::Client::Upload) do
def do_request(http_method, path, params = {})
if VCR.send(:cassettes).empty?
VCR.use_cassette(path) { super }
else
super
end
end
end)
end
end
|
ruby
|
{
"resource": ""
}
|
q881
|
Flickr.Object.inspect
|
train
|
def inspect
attribute_values = self.class.attributes
.inject({}) { |hash, attribute| hash.update(attribute.name => send(attribute.name)) }
.reject { |name, value| value.nil? or (value.respond_to?(:empty?) and value.empty?) }
attributes = attribute_values
.map { |name, value| "#{name}=#{value.inspect}" }
.join(" ")
class_name = self.class.name
hex_code = "0x#{(object_id >> 1).to_s(16)}"
"#<#{class_name}:#{hex_code} #{attributes}>"
end
|
ruby
|
{
"resource": ""
}
|
q882
|
Flickr.SanitizedFile.sanitize!
|
train
|
def sanitize!
if rails_file?
@file = @original
@content_type = @original.content_type
@path = @original.tempfile
elsif sinatra_file?
@file = @original[:tempfile]
@content_type = @original[:type]
@path = @original[:tempfile].path
elsif io?
@file = @original
@content_type = @original.content_type if @original.respond_to?(:content_type)
@path = @original.path if @original.respond_to?(:path)
elsif string?
@file = File.open(@original)
@content_type = nil
@path = @original
else
raise ArgumentError, "invalid file format"
end
end
|
ruby
|
{
"resource": ""
}
|
q883
|
Jquery.Helpers.link_to_modal
|
train
|
def link_to_modal(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
block_result = capture(&block)
link_to_modal(block_result, options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
# extend the html_options
html_options[:rel] = "modal:open"
if (html_options.has_key?(:remote))
if (html_options[:remote] == true)
html_options[:rel] = "modal:open:ajaxpost"
end
# remove the remote tag
html_options.delete(:remote)
end
# check if we have an id
html_options[:id] = UUIDTools::UUID.random_create().to_s unless html_options.has_key?(:id)
# perform the normal link_to operation
html_link = link_to(name, options, html_options)
# emit both
html_link.html_safe
end
end
|
ruby
|
{
"resource": ""
}
|
q884
|
JekyllData.Reader.read_theme_data
|
train
|
def read_theme_data
if @theme.data_path
#
# show contents of "<theme>/_data/" dir being read while degugging.
inspect_theme_data
theme_data = ThemeDataReader.new(site).read(site.config["data_dir"])
@site.data = Jekyll::Utils.deep_merge_hashes(theme_data, @site.data)
#
# show contents of merged site.data hash while debugging with
# additional --show-data switch.
inspect_merged_hash if site.config["show-data"] && site.config["verbose"]
end
end
|
ruby
|
{
"resource": ""
}
|
q885
|
JekyllData.Reader.inspect_inner_hash
|
train
|
def inspect_inner_hash(hash)
hash.each do |key, value|
if value.is_a? Array
print_label key
extract_hashes_and_print value
elsif value.is_a? Hash
print_subkey_and_value key, value
else
print_hash key, value
end
end
end
|
ruby
|
{
"resource": ""
}
|
q886
|
JekyllData.Reader.print_subkey_and_value
|
train
|
def print_subkey_and_value(key, value)
print_label key
value.each do |subkey, val|
if val.is_a? Hash
print_inner_subkey subkey
inspect_inner_hash val
elsif val.is_a? Array
print_inner_subkey subkey
extract_hashes_and_print val
elsif val.is_a? String
print_hash subkey, val
end
end
end
|
ruby
|
{
"resource": ""
}
|
q887
|
PahoMqtt.ConnectionHelper.should_send_ping?
|
train
|
def should_send_ping?(now, keep_alive, last_packet_received_at)
last_pingreq_sent_at = @sender.last_pingreq_sent_at
last_pingresp_received_at = @handler.last_pingresp_received_at
if !last_pingreq_sent_at || (last_pingresp_received_at && (last_pingreq_sent_at <= last_pingresp_received_at))
next_pingreq_at = [@sender.last_packet_sent_at, last_packet_received_at].min + (keep_alive * 0.7).ceil
return next_pingreq_at <= now
end
end
|
ruby
|
{
"resource": ""
}
|
q888
|
Picasa.Utils.array_wrap
|
train
|
def array_wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end
|
ruby
|
{
"resource": ""
}
|
q889
|
RSpecCommand.MatchFixture.failure_message
|
train
|
def failure_message
matching_files = @fixture.files & @local.files
fixture_only_files = @fixture.files - @local.files
local_only_files = @local.files - @fixture.files
buf = "expected fixture #{@fixture.path} to match files:\n"
(@fixture.files | @local.files).sort.each do |file|
if matching_files.include?(file)
local_file = @local.absolute(file)
fixture_file = @fixture.absolute(file)
if File.directory?(local_file) && File.directory?(fixture_file)
# Do nothing
elsif File.directory?(fixture_file)
buf << " #{file} should be a directory\n"
elsif File.directory?(local_file)
buf << " #{file} should not be a directory"
else
actual = IO.read(local_file)
expected = IO.read(fixture_file)
if actual != expected
# Show a diff
buf << " #{file} does not match fixture:"
buf << differ.diff(actual, expected).split(/\n/).map {|line| ' '+line }.join("\n")
end
end
elsif fixture_only_files.include?(file)
buf << " #{file} is not found\n"
elsif local_only_files.include?(file)
buf << " #{file} should not exist\n"
end
end
buf
end
|
ruby
|
{
"resource": ""
}
|
q890
|
RSpecCommand.MatchFixture.file_content_match?
|
train
|
def file_content_match?
@fixture.full_files.zip(@local.full_files).all? do |fixture_file, local_file|
if File.directory?(fixture_file)
File.directory?(local_file)
else
!File.directory?(local_file) && IO.read(fixture_file) == IO.read(local_file)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q891
|
RSpecCommand.ClassMethods.file
|
train
|
def file(path, content=nil, &block)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do
content = instance_eval(&block) if block
dest_path = File.join(temp_path, path)
FileUtils.mkdir_p(File.dirname(dest_path))
IO.write(dest_path, content)
end
end
|
ruby
|
{
"resource": ""
}
|
q892
|
RSpecCommand.ClassMethods.fixture_file
|
train
|
def fixture_file(path, dest=nil)
raise "file path should be relative the the temporary directory." if path == File.expand_path(path)
before do |example|
fixture_path = find_fixture(example.file_path, path)
dest_path = dest ? File.join(temp_path, dest) : temp_path
FileUtils.mkdir_p(dest_path)
file_list = MatchFixture::FileList.new(fixture_path)
file_list.files.each do |file|
abs = file_list.absolute(file)
if File.directory?(abs)
FileUtils.mkdir_p(File.join(dest_path, file))
else
FileUtils.copy(abs , File.join(dest_path, file), preserve: true)
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q893
|
RSpecCommand.ClassMethods.environment
|
train
|
def environment(variables)
before do
variables.each do |key, value|
if value.nil?
_environment.delete(key.to_s)
else
_environment[key.to_s] = value.to_s
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q894
|
DataMagic.StandardTranslation.randomize
|
train
|
def randomize(value)
case value
when Array then value[rand(value.size)]
when Range then rand((value.last+1) - value.first) + value.first
else value
end
end
|
ruby
|
{
"resource": ""
}
|
q895
|
DataMagic.StandardTranslation.sequential
|
train
|
def sequential(value)
index = index_variable_for(value)
index = (index ? index + 1 : 0)
index = 0 if index == value.length
set_index_variable(value, index)
value[index]
end
|
ruby
|
{
"resource": ""
}
|
q896
|
ActionAccess.Keeper.let
|
train
|
def let(clearance_level, actions, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
actions = Array(actions).map(&:to_sym)
controller = get_controller_name(resource, options)
@rules[controller] ||= {}
@rules[controller][clearance_level] ||= []
@rules[controller][clearance_level] += actions
@rules[controller][clearance_level].uniq!
return nil
end
|
ruby
|
{
"resource": ""
}
|
q897
|
ActionAccess.Keeper.lets?
|
train
|
def lets?(clearance_level, action, resource, options = {})
clearance_level = clearance_level.to_s.singularize.to_sym
action = action.to_sym
controller = get_controller_name(resource, options)
# Load the controller to ensure its rules are loaded (lazy loading rules).
controller.constantize.new
rules = @rules[controller]
return false unless rules
# Check rules
Array(rules[:all]).include?(:all) ||
Array(rules[:all]).include?(action) ||
Array(rules[clearance_level]).include?(:all) ||
Array(rules[clearance_level]).include?(action)
end
|
ruby
|
{
"resource": ""
}
|
q898
|
ActionAccess.ControllerAdditions.validate_access!
|
train
|
def validate_access!
action = self.action_name
clearance_levels = Array(current_clearance_levels)
authorized = clearance_levels.any? { |c| keeper.lets? c, action, self.class }
not_authorized! unless authorized
end
|
ruby
|
{
"resource": ""
}
|
q899
|
ActionAccess.ControllerAdditions.not_authorized!
|
train
|
def not_authorized!(*args)
options = args.extract_options!
message = options[:message] ||
I18n.t('action_access.redirection_message', default: 'Not authorized.')
path = options[:path] || unauthorized_access_redirection_path
redirect_to path, alert: message
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.