_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6800 | Kalindar.Event.finish_time_f | train | def finish_time_f day
if dtend.class == Date
# whole day
""
elsif finish_time.to_date == day.to_date
finish_time.strftime('%H:%M')
else
return "..."
end
end | ruby | {
"resource": ""
} |
q6801 | Kalindar.Event.time_f | train | def time_f day
start = start_time_f day
finish = finish_time_f day
if start == finish && start == ""
# whole day
""
elsif start == finish && start == "..."
"..."
else
"#{start_time_f day} - #{finish_time_f day}"
end
end | ruby | {
"resource": ""
} |
q6802 | Garcon.ExecutorOptions.get_executor_from | train | def get_executor_from(opts = {})
if (executor = opts[:executor]).is_a? Symbol
case opts[:executor]
when :fast
Garcon.global_fast_executor
when :io
Garcon.global_io_executor
when :immediate
Garcon::ImmediateExecutor.new
else
raise Argu... | ruby | {
"resource": ""
} |
q6803 | Familia.Tools.rename | train | def rename(filter, source_uri, target_uri=nil, &each_key)
target_uri ||= source_uri
move_keys filter, source_uri, target_uri if source_uri != target_uri
source_keys = Familia.redis(source_uri).keys(filter)
puts "Renaming #{source_keys.size} keys from #{source_uri} (filter: #{filter})"
sour... | ruby | {
"resource": ""
} |
q6804 | Roroacms.Comment.deal_with_abnormalaties | train | def deal_with_abnormalaties
self.comment = comment.to_s.gsub(%r{</?[^>]+?>}, '').gsub(/<script.*?>[\s\S]*<\/script>/i, "")
if !self.website.blank?
website = self.website.sub(/^https?\:\/\//, '').sub(/^www./,'')
unless self.website[/\Awww.\/\//] || self.website[/\Awww.\/\//]
websit... | ruby | {
"resource": ""
} |
q6805 | Bullring.ServerRegistry.lease_server! | train | def lease_server!
begin
if num_current_generation_servers < MAX_SERVERS_PER_GENERATION && registry_open?
start_a_server
end
lease_server
rescue ServerOffline => e
Bullring.logger.debug {"Lost connection with a server, retrying..."}
retry
end
end | ruby | {
"resource": ""
} |
q6806 | CurrentCost.Meter.update | train | def update(message)
unless message.nil?
# Parse reading from message
@latest_reading = Reading.from_xml(message)
# Inform observers
changed
notify_observers(@latest_reading)
end
rescue CurrentCost::ParseError
nil
end | ruby | {
"resource": ""
} |
q6807 | OrientdbBinary.Database.open | train | def open
conn = connection.protocol::DbOpen.new(params(name: @name, storage: @storage, user: @user, password: @password)).process(connection)
@session = conn[:session] || OrientdbBinary::OperationTypes::NEW_SESSION
@clusters = conn[:clusters]
self
end | ruby | {
"resource": ""
} |
q6808 | OrientdbBinary.Database.reload | train | def reload
answer = connection.protocol::DbReload.new(params).process(connection)
@clusters = answer[:clusters]
self
end | ruby | {
"resource": ""
} |
q6809 | Sendregning.Client.send_invoice | train | def send_invoice(invoice)
response = post_xml(invoice.to_xml, {:action => 'send', :type => 'invoice'})
InvoiceParser.parse(response, invoice)
end | ruby | {
"resource": ""
} |
q6810 | Sendregning.Client.find_invoice | train | def find_invoice(invoice_id)
builder = Builder::XmlMarkup.new(:indent=>2)
builder.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
request_xml = builder.select do |select|
select.invoiceNumbers do |numbers|
numbers.invoiceNumber invoice_id
end
end
response = po... | ruby | {
"resource": ""
} |
q6811 | LogCabin.DirCollection.find_file | train | def find_file(name)
@load_path.each do |dir|
file_path = File.join(dir, "#{name}.rb")
return file_path if File.exist? file_path
end
raise("Module #{name} not found")
end | ruby | {
"resource": ""
} |
q6812 | Figs.DirectoryFlattener.flattened_filenames | train | def flattened_filenames(filenames)
# Expect an array of filenames return otherwise
return filenames if !filenames.is_a?(Array)
# Iterate through array
filenames.map! do |filename|
# Flatten if its a file, flatten if a dir.
Dir.exist?(filename) ? directory_to_filenames(filename) :... | ruby | {
"resource": ""
} |
q6813 | Figs.DirectoryFlattener.flatten_files | train | def flatten_files(directoryname,filename)
# If the filename turns out to be a directory...
if Dir.exist?("#{directoryname}/#{filename}")
# do a recursive call to the parent method, unless the directory is . or ..
directory_to_filenames("#{directoryname}/#{filename}") unless ['.','..'].includ... | ruby | {
"resource": ""
} |
q6814 | Balancer.Profile.profile_name | train | def profile_name
# allow user to specify the path also
if @options[:profile] && File.exist?(@options[:profile])
filename_profile = File.basename(@options[:profile], '.yml')
end
name = derandomize(@name)
if File.exist?(profile_file(name))
name_profile = name
end
... | ruby | {
"resource": ""
} |
q6815 | BarkestCore.MsSqlDbDefinition.add_source | train | def add_source(sql)
sql_def = BarkestCore::MsSqlDefinition.new(sql, '')
sql_def.instance_variable_set(:@source_location, "::#{sql_def.name}::")
add_sql_def sql_def
nil
end | ruby | {
"resource": ""
} |
q6816 | BarkestCore.MsSqlDbDefinition.add_source_path | train | def add_source_path(path)
raise 'path must be a string' unless path.is_a?(String)
path = File.expand_path(path)
raise 'cannot add root path' if path == '/'
path = path[0...-1] if path[-1] == '/'
unless @source_paths.include?(path)
@source_paths << path
if Dir.e... | ruby | {
"resource": ""
} |
q6817 | Remi.Extractor::SftpFile.extract | train | def extract
begin_connection
entries.map do |entry|
local_file = File.join(@local_path, entry.name)
logger.info "Downloading #{entry.name} to #{local_file}"
sftp_retry { sftp_session.download!(File.join(@remote_path, entry.name), local_file) }
local_file
end
ensure... | ruby | {
"resource": ""
} |
q6818 | Remi.Loader::SftpFile.load | train | def load(data)
begin_connection
logger.info "Uploading #{data} to #{@username}@#{@host}: #{@remote_path}"
sftp_retry { sftp_session.upload! data, @remote_path }
true
ensure
end_connection
end | ruby | {
"resource": ""
} |
q6819 | CssCompare.Comparison.run | train | def run
result = CssCompare::Engine.new(@options)
.parse!
.equal?
write_output(result.to_s + "\n", @options[:output])
end | ruby | {
"resource": ""
} |
q6820 | GhostInThePost.PhantomTransform.html_file | train | def html_file(html)
file = Tempfile.new(['ghost_in_the_post', '.html'], encoding: Encoding::UTF_8)
file.write(html)
file.close #closing the file makes it accessible by phantom
file
end | ruby | {
"resource": ""
} |
q6821 | BibSonomy.CSL.render | train | def render(grouping, name, tags, count)
# get posts from BibSonomy
posts = JSON.parse(@bibsonomy.get_posts(grouping, name, 'publication', tags, 0, count))
# render them with citeproc
cp = CiteProc::Processor.new style: @style, format: 'html'
cp.import posts
# to check for duplicate... | ruby | {
"resource": ""
} |
q6822 | BibSonomy.CSL.get_public_docs | train | def get_public_docs(documents)
result = []
for doc in documents
file_name = doc["fileName"]
if file_name.end_with? ".pdf"
if documents.length < 2 or file_name.end_with? @public_doc_postfix
result << doc
end
end
end
return result
end | ruby | {
"resource": ""
} |
q6823 | Garcon.ChefHelpers.find_by | train | def find_by(type, filter, single = true, &block)
nodes = []
env = node.chef_environment
if node.public_send(Inflections.pluralize(type.to_s)).include? filter
nodes << node
end
if !single || nodes.empty?
search(:node, "#{type}:#{filter} AND chef_environment:#{env}") do |n|... | ruby | {
"resource": ""
} |
q6824 | Garcon.ChefHelpers.cookbook_version | train | def cookbook_version(name = nil)
cookbook = name.nil? ? cookbook_name : name
node.run_context.cookbook_collection[cookbook].metadata.version
end | ruby | {
"resource": ""
} |
q6825 | Garcon.ChefHelpers.file_cache_path | train | def file_cache_path(*args)
if args.nil?
Chef::Config[:file_cache_path]
else
::File.join(Chef::Config[:file_cache_path], args)
end
end | ruby | {
"resource": ""
} |
q6826 | Garcon.ChefHelpers._? | train | def _?(*args, &block)
if args.empty? && block_given?
yield self
else
resp = public_send(*args[0], &block) if respond_to?(args.first)
return nil if resp.nil?
!!resp == resp ? args[1] : [args[1], resp]
end
end | ruby | {
"resource": ""
} |
q6827 | Garcon.ChefHelpers.zip_hash | train | def zip_hash(col1, col2)
col1.zip(col2).inject({}) { |r, i| r[i[0]] = i[1]; r }
end | ruby | {
"resource": ""
} |
q6828 | Garcon.ChefHelpers.with_tmp_dir | train | def with_tmp_dir(&block)
Dir.mktmpdir(SecureRandom.hex(3)) do |tmp_dir|
Dir.chdir(tmp_dir, &block)
end
end | ruby | {
"resource": ""
} |
q6829 | Evvnt.ClassTemplateMethods.create | train | def create(**params)
path = nest_path_within_parent(plural_resource_path, params)
api_request(:post, path, params: params)
end | ruby | {
"resource": ""
} |
q6830 | Evvnt.ClassTemplateMethods.index | train | def index(**params)
params.stringify_keys!
path = nest_path_within_parent(plural_resource_path, params)
api_request(:get, path, params: params)
end | ruby | {
"resource": ""
} |
q6831 | Evvnt.ClassTemplateMethods.show | train | def show(record_id = nil, **params)
if record_id.nil? && !singular_resource?
raise ArgumentError, "record_id cannot be nil"
end
path = nest_path_within_parent(singular_path_for_record(record_id, params), params)
api_request(:get, path, params: params)
end | ruby | {
"resource": ""
} |
q6832 | Fried::Schema::Attribute.DefineWriter.call | train | def call(definition, klass)
is_a = is[definition.type]
define_writer(definition, is_a, klass)
end | ruby | {
"resource": ""
} |
q6833 | RailsExtension::ActionControllerExtension::Routing.ClassMethods.assert_no_route | train | def assert_no_route(verb,action,args={})
test "#{brand}no route to #{verb} #{action} #{args}" do
assert_raise(ActionController::RoutingError){
send(verb,action,args)
}
end
end | ruby | {
"resource": ""
} |
q6834 | Richcss.RichUI.debug | train | def debug(depth = 0)
if debug?
debug_info = yield
debug_info = debug_info.inspect unless debug_info.is_a?(String)
STDERR.puts debug_info.split("\n").map {|s| " " * depth + s }
end
end | ruby | {
"resource": ""
} |
q6835 | Bebox.RoleCommands.role_list_command | train | def role_list_command(role_command)
role_command.desc _('cli.role.list.desc')
role_command.command :list do |role_list_command|
role_list_command.action do |global_options,options,args|
roles = Bebox::Role.list(project_root)
title _('cli.role.list.current_roles')
roles.... | ruby | {
"resource": ""
} |
q6836 | Bebox.RoleCommands.role_new_command | train | def role_new_command(role_command)
role_command.desc _('cli.role.new.desc')
role_command.arg_name "[name]"
role_command.command :new do |role_new_command|
role_new_command.action do |global_options,options,args|
help_now!(error(_('cli.role.new.name_arg_missing'))) if args.count == 0
... | ruby | {
"resource": ""
} |
q6837 | Bebox.RoleCommands.generate_role_command | train | def generate_role_command(role_command, command, send_command, description)
role_command.desc description
role_command.command command do |generated_command|
generated_command.action do |global_options,options,args|
Bebox::RoleWizard.new.send(send_command, project_root)
end
e... | ruby | {
"resource": ""
} |
q6838 | Bebox.RoleCommands.role_list_profiles_command | train | def role_list_profiles_command(role_command)
role_command.desc _('cli.role.list_profiles.desc')
role_command.arg_name "[role_name]"
role_command.command :list_profiles do |list_profiles_command|
list_profiles_command.action do |global_options,options,args|
help_now!(error(_('cli.role... | ruby | {
"resource": ""
} |
q6839 | Pushfile.Util.filename | train | def filename(name)
# Replace space with underscore and downcase extension
pre, dot, ext = name.rpartition('.')
name = "#{pre.gsub(' ', '_')}.#{ext.downcase}"
# Remove illegal characters
# http://stackoverflow.com/questions/13517100/whats-the-difference-between-palpha-i-and-pl-i-in-ruby
... | ruby | {
"resource": ""
} |
q6840 | Garcon.MemStash.load | train | def load(data)
@monitor.synchronize do
data.each do |key, value|
expire!
store(key, val)
end
end
end | ruby | {
"resource": ""
} |
q6841 | Garcon.MemStash.fetch | train | def fetch(key)
@monitor.synchronize do
found, value = get(key)
found ? value : store(key, yield)
end
end | ruby | {
"resource": ""
} |
q6842 | Garcon.MemStash.delete | train | def delete(key)
@monitor.synchronize do
entry = @stash.delete(key)
if entry
@expires_at.delete(entry)
entry.value
else
nil
end
end
end | ruby | {
"resource": ""
} |
q6843 | RichUnits.Duration.reset_segments | train | def reset_segments(segmentA=nil, segmentB=nil)
if !segmentA
@segments = [:days, :hours, :minutes, :seconds]
elsif !segmentB
case segmentA
when Array
@segments = segmentA.map{ |p| (p.to_s.downcase.chomp('s') + 's').to_sym }
raise ArgumentError unless @segments.all?... | ruby | {
"resource": ""
} |
q6844 | RichUnits.Duration.strftime | train | def strftime(fmt)
h = to_h
hx = {
'y' => h[:years] ,
'w' => h[:weeks] ,
'd' => h[:days] ,
'h' => h[:hours] ,
'm' => h[:minutes],
's' => h[:seconds],
't' => total,
'x' => to_s
}
fmt.gsub(/%?%(w|d|h|m|s|t|x)/) do |match|
hx[matc... | ruby | {
"resource": ""
} |
q6845 | BarkestCore.RecaptchaHelper.verify_recaptcha_challenge | train | def verify_recaptcha_challenge(model = nil)
# always true in tests.
return true if recaptcha_disabled?
# model must respond to the 'errors' message and the result of that must respond to 'add'
if !model || !model.respond_to?('errors') || !model.send('errors').respond_to?('add')
model =... | ruby | {
"resource": ""
} |
q6846 | SqsMocks.MockClient.get_queue_attributes | train | def get_queue_attributes(queue_url: nil, attribute_names: nil)
r = MockResponse.new
if attribute_names == "All"
r.attributes = FAUX_ATTRIBUTES
else
attribute_names.each do |attribute_name|
r.attributes[attribute_name] = FAUX_ATTRIBUTES[attribute_name]
end
end
... | ruby | {
"resource": ""
} |
q6847 | MetaEnum.Type.[] | train | def [](key)
case key
when Element, MissingElement
raise ArgumentError, "wrong type" unless key.type == self
key
when Symbol
elements_by_name.fetch(key)
else
key = normalize_value(key)
elements_by_value.fetch(key) { MissingElement.new key, self }
end
... | ruby | {
"resource": ""
} |
q6848 | Hoodie.UrlHelper.unshorten | train | def unshorten(url, opts= {})
options = {
max_level: opts.fetch(:max_level, 10),
timeout: opts.fetch(:timeout, 2),
use_cache: opts.fetch(:use_cache, true)
}
url = (url =~ /^https?:/i) ? url : "http://#{url}"
__unshorten__(url, options)
end | ruby | {
"resource": ""
} |
q6849 | EventHub.Helper.format_string | train | def format_string(message,max_characters=80)
max_characters = 5 if max_characters < 5
m = message.gsub(/\r\n|\n|\r/m,";")
return (m[0..max_characters-4] + "...") if m.size > max_characters
return m
end | ruby | {
"resource": ""
} |
q6850 | WatsonNLPWrapper.WatsonNLPApi.analyze | train | def analyze(text, features = default_features)
if text.nil? || features.nil?
raise ArgumentError.new(NIL_ARGUMENT_ERROR)
end
response = self.class.post(
"#{@url}/analyze?version=#{@version}",
body: {
text: text.to_s,
features: features
}.to_json,
... | ruby | {
"resource": ""
} |
q6851 | WatsonNLPWrapper.WatsonNLPApi.default_features | train | def default_features
{
entities: {
emotion: true,
sentiment: true,
limit: 2
},
keywords: {
emotion: true,
sentiment: true,
limit: 2
}
}
end | ruby | {
"resource": ""
} |
q6852 | CapybaraObjects.PageObject.visit | train | def visit
raise ::CapybaraObjects::Exceptions::MissingUrl unless url.present?
page.visit url
validate!
self
end | ruby | {
"resource": ""
} |
q6853 | Spidercrawl.Request.curl | train | def curl
puts "fetching #{@uri.to_s}".green.on_black
start_time = Time.now
begin
c = @c
c.url = @uri.to_s
c.perform
end_time = Time.now
case c.response_code
when 200 then
page = Page.new(@uri, response_code: c.response_code,
... | ruby | {
"resource": ""
} |
q6854 | Incline.EmailValidator.validate_each | train | def validate_each(record, attribute, value)
unless value.blank?
record.errors[attribute] << (options[:message] || 'is not a valid email address') unless value =~ VALID_EMAIL_REGEX
end
end | ruby | {
"resource": ""
} |
q6855 | Garcon.Interpolation.interpolate | train | def interpolate(item = self, parent = nil)
item = render item, parent
item.is_a?(Hash) ? ::Mash.new(item) : item
end | ruby | {
"resource": ""
} |
q6856 | Garcon.Interpolation.render | train | def render(item, parent = nil)
item = item.to_hash if item.respond_to?(:to_hash)
if item.is_a?(Hash)
item = item.inject({}) { |memo, (k,v)| memo[sym(k)] = v; memo }
item.inject({}) {|memo, (k,v)| memo[sym(k)] = render(v, item); memo}
elsif item.is_a?(Array)
item.map { |i| rende... | ruby | {
"resource": ""
} |
q6857 | ActionCommand.ExecutableTransaction.execute | train | def execute(result)
if ActiveRecord::Base.connection.open_transactions >= 1
super(result)
else
result.info('start_transaction')
ActiveRecord::Base.transaction do
super(result)
if result.ok?
result.info('end_transaction')
else
resu... | ruby | {
"resource": ""
} |
q6858 | UlePage.SitePrismExtender.element_collection | train | def element_collection(collection_name, *find_args)
build collection_name, *find_args do
define_method collection_name.to_s do |*runtime_args, &element_block|
self.class.raise_if_block(self, collection_name.to_s, !element_block.nil?)
page.all(*find_args)
end
end
end | ruby | {
"resource": ""
} |
q6859 | UlePage.SitePrismExtender.define_elements_js | train | def define_elements_js(model_class, excluded_props = [])
attributes = model_class.new.attributes.keys
attributes.each do |attri|
unless excluded_props.include? attri
selector = "#"+attri
# self.class.send "element", attri.to_sym, selector
element attri, selector
... | ruby | {
"resource": ""
} |
q6860 | MultiBitField.ClassMethods.range_for | train | def range_for column_name, field_name
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
return column[field_name] if column[field_name]
raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}"
end | ruby | {
"resource": ""
} |
q6861 | MultiBitField.ClassMethods.reset_mask_for | train | def reset_mask_for column_name, *fields
fields = bitfields if fields.empty?
max = bitfield_max(column_name)
(0..max).sum{|i| 2 ** i} - only_mask_for(column_name, *fields)
end | ruby | {
"resource": ""
} |
q6862 | MultiBitField.ClassMethods.increment_mask_for | train | def increment_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
fields.sum do |field_name|
raise ArugmentError, "Unknown field: #{field_name} for column #{c... | ruby | {
"resource": ""
} |
q6863 | MultiBitField.ClassMethods.only_mask_for | train | def only_mask_for column_name, *fields
fields = bitfields if fields.empty?
column = @@bitfields[column_name]
max = bitfield_max(column_name)
raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
column.sum do |field_name, range|
fields.include?(field_na... | ruby | {
"resource": ""
} |
q6864 | MultiBitField.ClassMethods.count_by | train | def count_by column_name, field
inc = increment_mask_for column_name, field
only = only_mask_for column_name, field
# Create super-special-bitfield-grouping-query w/ AREL
sql = arel_table.
project("count(#{primary_key}) as #{field}_count, (#{column_name} & #{only})/#{inc} as #{field}").
... | ruby | {
"resource": ""
} |
q6865 | MultiBitField.InstanceMethods.reset_bitfields | train | def reset_bitfields column_name, *fields
mask = self.class.reset_mask_for column_name, *fields
self[column_name] = self[column_name] & mask
save
end | ruby | {
"resource": ""
} |
q6866 | MultiBitField.InstanceMethods.increment_bitfields | train | def increment_bitfields column_name, *fields
mask = self.class.increment_mask_for column_name, *fields
self[column_name] = self[column_name] += mask
save
end | ruby | {
"resource": ""
} |
q6867 | OpenStax::Connect.CurrentUserManager.connect_current_user= | train | def connect_current_user=(user)
@connect_current_user = user || User.anonymous
@app_current_user = user_provider.connect_user_to_app_user(@connect_current_user)
if @connect_current_user.is_anonymous?
@session[:user_id] = nil
@cookies.delete(:secure_user_id)
else
@session... | ruby | {
"resource": ""
} |
q6868 | Vidibus.Encoder.register_format | train | def register_format(name, processor)
unless processor.new.is_a?(Vidibus::Encoder::Base)
raise(ArgumentError, 'The processor must inherit Vidibus::Encoder::Base')
end
@formats ||= {}
@formats[name] = processor
end | ruby | {
"resource": ""
} |
q6869 | RComp.Conf.read_conf_file | train | def read_conf_file
conf = {}
if File.exists?(CONF_PATH) && File.size?(CONF_PATH)
# Store valid conf keys
YAML.load_file(CONF_PATH).each do |key, value|
if VALID_KEYS.include? key
conf[key] = value
else
say "Invalid configuration key: #{key}"
... | ruby | {
"resource": ""
} |
q6870 | Monet.BaselineControl.rebase | train | def rebase(image)
new_path = @router.baseline_dir(image.name)
create_path_for_file(new_path)
FileUtils.move(image.path, new_path)
Monet::Image.new(new_path)
end | ruby | {
"resource": ""
} |
q6871 | Associates.Persistence.save | train | def save(*args)
return false unless valid?
ActiveRecord::Base.transaction do
begin
associates.all? do |associate|
send(associate.name).send(:save!, *args)
end
rescue ActiveRecord::RecordInvalid
false
end
end
end | ruby | {
"resource": ""
} |
q6872 | Auger.Project.connections | train | def connections(*roles)
if roles.empty?
@connections
else
@connections.select { |c| c.roles.empty? or !(c.roles & roles).empty? }
end
end | ruby | {
"resource": ""
} |
q6873 | Poster.Rss.extract_data | train | def extract_data item, text_limit: 1200
link = item.link
desc = item.description
title = item.title.force_encoding('UTF-8')
# Extract main image
case
when desc.match(/\|.*\|/m)
img, terms, text = desc.split('|')
when desc.include?('|')
img, text = desc.split('|... | ruby | {
"resource": ""
} |
q6874 | GoogleAnymote.Pair.start_pairing | train | def start_pairing
@gtv = GoogleAnymote::TV.new(@cert, host, 9551 + 1)
# Let the TV know that we want to pair with it
send_message(pair, OuterMessage::MessageType::MESSAGE_TYPE_PAIRING_REQUEST)
# Build the options and send them to the TV
options = Options.new
encoding = O... | ruby | {
"resource": ""
} |
q6875 | GoogleAnymote.Pair.complete_pairing | train | def complete_pairing(code)
# Send secret code to the TV to compete the pairing process
secret = Secret.new
secret.secret = encode_hex_secret(code)
outer = send_message(secret, OuterMessage::MessageType::MESSAGE_TYPE_SECRET)
# Clean up
@gtv.ssl_client.close
raise PairingFailed... | ruby | {
"resource": ""
} |
q6876 | GoogleAnymote.Pair.send_message | train | def send_message(msg, type)
# Build the message and get it's size
message = wrap_message(msg, type).serialize_to_string
message_size = [message.length].pack('N')
# Write the message to the SSL client and get the response
@gtv.ssl_client.write(message_size + message)
data = ""
... | ruby | {
"resource": ""
} |
q6877 | GoogleAnymote.Pair.wrap_message | train | def wrap_message(msg, type)
# Wrap it in an envelope
outer = OuterMessage.new
outer.protocol_version = 1
outer.status = OuterMessage::Status::STATUS_OK
outer.type = type
outer.payload = msg.serialize_to_string
return outer
end | ruby | {
"resource": ""
} |
q6878 | GoogleAnymote.Pair.encode_hex_secret | train | def encode_hex_secret secret
# TODO(stevenle): Something further encodes the secret to a 64-char hex
# string. For now, use adb logcat to figure out what the expected challenge
# is. Eventually, make sure the encoding matches the server reference
# implementation:
# http://code.google.co... | ruby | {
"resource": ""
} |
q6879 | Sumac.IDAllocator.free | train | def free(id)
enclosing_range_index = @allocated_ranges.index { |range| range.last >= id && range.first <= id }
enclosing_range = @allocated_ranges[enclosing_range_index]
if enclosing_range.size == 1
@allocated_ranges.delete(enclosing_range)
elsif enclosing_range.first == id
@allo... | ruby | {
"resource": ""
} |
q6880 | Incline::Extensions.ActionViewBase.full_title | train | def full_title(page_title = '')
aname = Rails.application.app_name.strip
return aname if page_title.blank?
"#{page_title.strip} | #{aname}"
end | ruby | {
"resource": ""
} |
q6881 | Incline::Extensions.ActionViewBase.glyph | train | def glyph(name, size = '')
size =
case size.to_s.downcase
when 'small', 'sm'
'glyphicon-small'
when 'large', 'lg'
'glyphicon-large'
else
nil
end
name = name.to_s.strip
return nil if name.blank?
re... | ruby | {
"resource": ""
} |
q6882 | Incline::Extensions.ActionViewBase.fmt_num | train | def fmt_num(value, places = 2)
return nil if value.blank?
value =
if value.respond_to?(:to_f)
value.to_f
else
nil
end
return nil unless value.is_a?(::Float)
"%0.#{places}f" % value.round(places)
end | ruby | {
"resource": ""
} |
q6883 | Incline::Extensions.ActionViewBase.panel | train | def panel(title, options = { }, &block)
options = {
type: 'primary',
size: 6,
offset: 3,
open_body: true
}.merge(options || {})
options[:type] = options[:type].to_s.downcase
options[:type] = 'primary' unless %w(primary success info warning danger).include... | ruby | {
"resource": ""
} |
q6884 | M4DBI.Model.delete | train | def delete
if self.class.hooks[:active]
self.class.hooks[:before_delete].each do |block|
self.class.hooks[:active] = false
block.yield self
self.class.hooks[:active] = true
end
end
st = prepare("DELETE FROM #{table} WHERE #{pk_clause}")
num_deleted ... | ruby | {
"resource": ""
} |
q6885 | Sock.Server.subscribe | train | def subscribe(subscription)
@logger.info "Subscribing to: #{subscription + '*'}"
pubsub.psubscribe(subscription + '*') do |chan, msg|
@logger.info "pushing c: #{chan} msg: #{msg}"
channel(chan).push(msg)
end
end | ruby | {
"resource": ""
} |
q6886 | LiveFront.TabHelper.nav_link | train | def nav_link(options = {}, &block)
c, a = fetch_controller_and_action(options)
p = options.delete(:params) || {}
klass = page_active?(c, a, p) ? 'active' : ''
# Add our custom class into the html_options, which may or may not exist
# and which may or may not already have a :class key
... | ruby | {
"resource": ""
} |
q6887 | HotTub.Sessions.get_or_set | train | def get_or_set(key, pool_options={}, &client_block)
unless @_staged[key]
@mutex.synchronize do
@_staged[key] ||= [pool_options,client_block]
end
end
get(key)
end | ruby | {
"resource": ""
} |
q6888 | HotTub.Sessions.delete | train | def delete(key)
deleted = false
pool = nil
@mutex.synchronize do
pool = @_sessions.delete(key)
end
if pool
pool.shutdown!
deleted = true
HotTub.logger.info "[HotTub] #{key} was deleted from #{@name}." if HotTub.logger
end
deleted
end | ruby | {
"resource": ""
} |
q6889 | HotTub.Sessions.reap! | train | def reap!
HotTub.logger.info "[HotTub] Reaping #{@name}!" if HotTub.log_trace?
@mutex.synchronize do
@_sessions.each_value do |pool|
break if @shutdown
pool.reap!
end
end
nil
end | ruby | {
"resource": ""
} |
q6890 | BetterRailsDebugger::Parser::Ruby.Processor.emit_signal | train | def emit_signal(signal_name, node)
@subscriptions ||= Hash.new()
@runner ||= BetterRailsDebugger::Parser::Ruby::ContextRunner.new self
(@subscriptions[signal_name] || {}).values.each do |block|
@runner.node = node
@runner.instance_eval &block
# block.call(node)
end
en... | ruby | {
"resource": ""
} |
q6891 | BetterRailsDebugger::Parser::Ruby.Processor.subscribe_signal | train | def subscribe_signal(signal_name, step=:first_pass, &block)
key = SecureRandom.hex(5)
@subscriptions ||= Hash.new()
@subscriptions[signal_name] ||= Hash.new
@subscriptions[signal_name][key] = block
key
end | ruby | {
"resource": ""
} |
q6892 | SublimeSunippetter.Dsl.add | train | def add(method_name, *args)
return if error?(method_name, *args)
has_do_block = args.include?('block@d')
has_brace_block = args.include?('block@b')
args = delete_block_args args
@target_methods << TargetMethod.new do |t|
t.method_name = method_name
t.args = args
t.h... | ruby | {
"resource": ""
} |
q6893 | WhoopsLogger.Sender.send_message | train | def send_message(data)
# TODO: format
# TODO: validation
data = prepare_data(data)
logger.debug { "Sending request to #{url.to_s}:\n#{data}" } if logger
http =
Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass).
new(url.host, url.port)
http.read_timeou... | ruby | {
"resource": ""
} |
q6894 | Shoehorn.DocumentsBase.status | train | def status(inserter_id)
status_hash = Hash.new
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetDocumentStatusCall do |xml|
xml.InserterId(inserter_id)
... | ruby | {
"resource": ""
} |
q6895 | HtmlMockup::Release::Processors.Requirejs.rjs_check | train | def rjs_check(path = @options[:rjs])
rjs_command = rjs_file(path) || rjs_bin(path)
if !(rjs_command)
raise RuntimeError, "Could not find r.js optimizer in #{path.inspect} - try updating this by npm install -g requirejs"
end
rjs_command
end | ruby | {
"resource": ""
} |
q6896 | Types.Type.match_type? | train | def match_type?(object)
result = object.kind_of_any? self.type_classes
if not result
result = object.type_of_any? self.type_types
end
return result
end | ruby | {
"resource": ""
} |
q6897 | Hook.Collection.create | train | def create data
if data.kind_of?(Array)
# TODO: server should accept multiple items to create,
# instead of making multiple requests.
data.map {|item| self.create(item) }
else
@client.post @segments, data
end
end | ruby | {
"resource": ""
} |
q6898 | Hook.Collection.where | train | def where fields = {}, operation = 'and'
fields.each_pair do |k, value|
field = (k.respond_to?(:field) ? k.field : k).to_s
comparation = k.respond_to?(:comparation) ? k.comparation : '='
# Range syntatic sugar
value = [ value.first, value.last ] if value.kind_of?(Range)
@... | ruby | {
"resource": ""
} |
q6899 | Hook.Collection.order | train | def order fields
by_num = { 1 => 'asc', -1 => 'desc' }
ordering = []
fields.each_pair do |key, value|
ordering << [key.to_s, by_num[value] || value]
end
@ordering = ordering
self
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.