_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q24000
Handshake.ClauseMethods.Block
train
def Block(contract_hash) pc = Handshake::ProcContract.new pc.signature = contract_hash pc end
ruby
{ "resource": "" }
q24001
Openapi2ruby.Openapi::Schema.properties
train
def properties return [] if @definition['properties'].nil? @definition['properties'].each_with_object([]) do |(key, value), results| content = { name: key, definition: value } results << Openapi2ruby::Openapi::Schema::Property.new(content) end end
ruby
{ "resource": "" }
q24002
TeslaAPI.Connection.vehicles
train
def vehicles @vehicles ||= begin _, json = get_json("/vehicles") json.map { |data| Vehicle.new(self, data) } end end
ruby
{ "resource": "" }
q24003
Omniship.Carrier.valid_credentials?
train
def valid_credentials? location = self.class.default_location find_rates(location,location,Package.new(100, [5,15,30]), :test => test_mode) rescue Omniship::ResponseError false else true end
ruby
{ "resource": "" }
q24004
RDF.Statement.to_mongo
train
def to_mongo self.to_hash.inject({}) do |hash, (place_in_statement, entity)| hash.merge(RDF::Mongo::Conversion.to_mongo(entity, place_in_statement)) end end
ruby
{ "resource": "" }
q24005
RLP.DecodeLazy.decode_lazy
train
def decode_lazy(rlp, sedes: nil, sedes_options: {}) item, next_start = consume_item_lazy(rlp, 0) raise DecodingError.new("RLP length prefix announced wrong length", rlp) if next_start != rlp.size if item.instance_of?(LazyList) item.sedes = sedes item.sedes_options = sedes_options ...
ruby
{ "resource": "" }
q24006
RLP.DecodeLazy.consume_item_lazy
train
def consume_item_lazy(rlp, start) t, l, s = consume_length_prefix(rlp, start) if t == :str consume_payload(rlp, s, :str, l) elsif t == :list [LazyList.new(rlp, s, s+l), s+l] else raise "Invalid item type: #{t}" end end
ruby
{ "resource": "" }
q24007
RLP.DecodeLazy.peek
train
def peek(rlp, index, sedes: nil) ll = decode_lazy(rlp) index = Array(index) index.each do |i| raise IndexError, "Too many indices given" if primitive?(ll) ll = ll.fetch(i) end sedes ? sedes.deserialize(ll) : ll end
ruby
{ "resource": "" }
q24008
Handshake.ClassMethods.contract_reader
train
def contract_reader(meth_to_clause) attr_reader(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract meth, nil => cls end end
ruby
{ "resource": "" }
q24009
Handshake.ClassMethods.contract_writer
train
def contract_writer(meth_to_clause) attr_writer(*(meth_to_clause.keys)) meth_to_clause.each do |meth, cls| contract "#{meth}=".to_sym, cls => anything end end
ruby
{ "resource": "" }
q24010
Handshake.ClassMethods.method_added
train
def method_added(meth_name) @deferred ||= {} unless @deferred.empty? @deferred.each do |k, v| case k when :before, :after, :around define_condition meth_name, k, v when :contract define_contract meth_name, v end end @def...
ruby
{ "resource": "" }
q24011
Handshake.MethodContract.accepts=
train
def accepts=(args) if args.last == Block # Transform into a ProcContract args.pop @block_contract = ProcContract.new @block_contract.accepts = ClauseMethods::ANYTHING @block_contract.returns = ClauseMethods::ANYTHING elsif args.last.is_a?(ProcContract) @block_...
ruby
{ "resource": "" }
q24012
RackStatsD.RequestStatus.call
train
def call(env) if env[REQUEST_METHOD] == GET if env[PATH_INFO] == @status_path if @callback.respond_to?(:call) return @callback.call else return [200, HEADERS, [@callback.to_s]] end end end @app.call env end
ruby
{ "resource": "" }
q24013
RackStatsD.RequestHostname.call
train
def call(env) status, headers, body = @app.call(env) headers['X-Node'] = @host if @host headers['X-Revision'] = @sha [status, headers, body] end
ruby
{ "resource": "" }
q24014
RackStatsD.ProcessUtilization.procline
train
def procline "unicorn %s[%s] worker[%02d]: %5d reqs, %4.1f req/s, %4dms avg, %5.1f%% util" % [ domain, revision, worker_number.to_i, total_requests.to_i, requests_per_second.to_f, average_response_time.to_i, percentage_active.to_f ] end
ruby
{ "resource": "" }
q24015
RackStatsD.ProcessUtilization.record_request
train
def record_request(status, env) now = Time.now diff = (now - @start) @active_time += diff @requests += 1 $0 = procline if @stats @stats.timing("#{@stats_prefix}.response_time", diff * 1000) if VALID_METHODS.include?(env[REQUEST_METHOD]) stat = "#{@stats_pr...
ruby
{ "resource": "" }
q24016
RackStatsD.ProcessUtilization.call
train
def call(env) @start = Time.now GC.clear_stats if @track_gc @total_requests += 1 first_request if @total_requests == 1 env['process.request_start'] = @start.to_f env['process.total_requests'] = total_requests # newrelic X-Request-Start env.delete('HTTP_X_REQUEST_START'...
ruby
{ "resource": "" }
q24017
HammerCLIForemanTasks.Helper.task_progress
train
def task_progress(task_or_id) task_id = task_or_id.is_a?(Hash) ? task_or_id['id'] : task_or_id if !task_id.empty? options = { verbosity: @context[:verbosity] || HammerCLI::V_VERBOSE } task_progress = TaskProgress.new(task_id, options) { |id| load_task(id) } task_progress.render ...
ruby
{ "resource": "" }
q24018
RLP.Decode.decode
train
def decode(rlp, **options) rlp = str_to_bytes(rlp) sedes = options.delete(:sedes) strict = options.has_key?(:strict) ? options.delete(:strict) : true begin item, next_start = consume_item(rlp, 0) rescue Exception => e raise DecodingError.new("Cannot decode rlp string: #{e}...
ruby
{ "resource": "" }
q24019
RLP.Decode.consume_item
train
def consume_item(rlp, start) t, l, s = consume_length_prefix(rlp, start) consume_payload(rlp, s, t, l) end
ruby
{ "resource": "" }
q24020
RLP.Decode.consume_payload
train
def consume_payload(rlp, start, type, length) case type when :str [rlp[start...(start+length)], start+length] when :list items = [] next_item_start = start payload_end = next_item_start + length while next_item_start < payload_end item, next_item_star...
ruby
{ "resource": "" }
q24021
Pipes.Context.add
train
def add(values) values.each do |key, val| k_sym = key.to_sym fail Override, "Property :#{key} already present" if respond_to?(k_sym) define_singleton_method(k_sym) { val } end end
ruby
{ "resource": "" }
q24022
RubyFS.Stream.run
train
def run logger.debug "Starting up..." @socket = TCPSocket.from_ruby_socket ::TCPSocket.new(@host, @port) post_init loop { receive_data @socket.readpartial(4096) } rescue EOFError, IOError, Errno::ECONNREFUSED => e logger.info "Client socket closed due to (#{e.class}) #{e.message}!" ...
ruby
{ "resource": "" }
q24023
RubyFS.Stream.command
train
def command(command, options = {}, &callback) uuid = SecureRandom.uuid @command_callbacks << (callback || lambda { |reply| signal uuid, reply }) string = "#{command}\n" body_value = options.delete :command_body_value options.each_pair do |key, value| string << "#{key.to_s.gsub '_',...
ruby
{ "resource": "" }
q24024
RubyFS.Stream.application
train
def application(call, appname, options = nil) opts = {call_command: 'execute', execute_app_name: appname} if options opts[:content_type] = 'text/plain' opts[:content_length] = options.bytesize opts[:command_body_value] = options end sendmsg call, opts end
ruby
{ "resource": "" }
q24025
GdprExporter.ClassMethods.gdpr_collect
train
def gdpr_collect(*args) # Params handling if args.class == Hash # when user provides the hash_params only simple_fields, hash_params = [[], args] else simple_fields, hash_params = [args[0..-2], args.last] end unless hash_params.class == Hash raise ArgumentError.new...
ruby
{ "resource": "" }
q24026
SpinningCursor.ConsoleHelpers.reset_line
train
def reset_line(text = "") # Initialise ANSI escape string escape = "" # Get terminal window width cols = console_columns # The number of lines the previous message spanned lines = @@prev / cols # If cols == 80 and @@prev == 80, @@prev / cols == 1 but we don't want to #...
ruby
{ "resource": "" }
q24027
Bump.BumpInfo.valid?
train
def valid? create_update_rules.each do |rule| return false if !rule.file_exists || !rule.pattern_exists end true end
ruby
{ "resource": "" }
q24028
Hermitage.RailsRenderCore.render
train
def render # Initialize the resulting tag tag_parts = [] # Slice objects into separate lists lists = slice_objects # Render each list into `tag` variable lists.each do |list| items = list.collect { |item| render_link_for(item) } tag_parts << render_content_tag_for(i...
ruby
{ "resource": "" }
q24029
Hermitage.RailsRenderCore.value_for
train
def value_for(item, option) attribute = @options[option] if attribute.is_a? Proc attribute.call(item) else eval("item.#{attribute}") end end
ruby
{ "resource": "" }
q24030
Hermitage.RailsRenderCore.render_link_for
train
def render_link_for(item) original_path = value_for(item, :original) thumbnail_path = value_for(item, :thumbnail) title = @options[:title] ? value_for(item, :title) : nil image = @template.image_tag(thumbnail_path, class: @options[:image_class]) @template.link_to(image, original_path, rel:...
ruby
{ "resource": "" }
q24031
RLP.Encode.encode
train
def encode(obj, sedes: nil, infer_serializer: true, cache: false) return obj._cached_rlp if obj.is_a?(Sedes::Serializable) && obj._cached_rlp && sedes.nil? really_cache = obj.is_a?(Sedes::Serializable) && sedes.nil? && cache if sedes item = sedes.serialize(obj) elsif infer_serializer ...
ruby
{ "resource": "" }
q24032
Bump.Application.create_bump_info
train
def create_bump_info repo = BumpInfoRepository.new @file begin bump_info = repo.from_file rescue Errno::ENOENT log_red "Error: the file `#{@file}` not found." return nil end bump_info end
ruby
{ "resource": "" }
q24033
Bump.Application.print_version_patterns
train
def print_version_patterns(bump_info) log 'Current Version:', false log_green " #{bump_info.before_version}" log 'Version patterns:' bump_info.update_rules.each do |rule| print_rule rule end end
ruby
{ "resource": "" }
q24034
Bump.Application.print_rule
train
def print_rule(rule) unless rule.file_exists log_red " #{rule.file}:", false log_red " '#{rule.before_pattern}' (file not found)" return end log " #{rule.file}:", false unless rule.pattern_exists log_red " '#{rule.before_pattern}' (pattern not found)" ...
ruby
{ "resource": "" }
q24035
Bump.Application.report
train
def report(bump_info) bump_info.update_rules.each do |rule| log rule.file.to_s log ' Performed pattern replacement:' log_green " '#{rule.before_pattern}' => '#{rule.after_pattern}'" log end end
ruby
{ "resource": "" }
q24036
Bump.Application.action_bump
train
def action_bump bump_info = create_bump_info return false if bump_info.nil? print_bump_plan bump_info unless bump_info.valid? print_invalid_bump_info bump_info return false end bump_info.perform_update report bump_info save_bump_info bump_info ...
ruby
{ "resource": "" }
q24037
Bump.Application.print_bump_plan
train
def print_bump_plan(bump_info) level = bump_level print_bump_plan_level level, bump_info unless level.nil? preid = @options[:preid] print_bump_plan_preid preid, bump_info unless preid.nil? print_bump_plan_release bump_info if @options[:release] log end
ruby
{ "resource": "" }
q24038
Bump.Application.print_bump_plan_preid
train
def print_bump_plan_preid(preid, bump_info) bump_info.preid = preid log 'Set pre-release version id: ', false log_green preid print_version_transition bump_info end
ruby
{ "resource": "" }
q24039
Omniship.UPS.create_shipment
train
def create_shipment(origin, destination, packages, options={}) @options = @options.merge(options) origin, destination = upsified_location(origin), upsified_location(destination) options = @options.merge(options) options[:test] = options[:test].nil? ? true : option...
ruby
{ "resource": "" }
q24040
Ansible.Vault.write
train
def write file = FileWriter.new(@path) encryptor = Encryptor.new(password: @password, file: file) encryptor.encrypt(@plaintext) file.write end
ruby
{ "resource": "" }
q24041
Ansible.Vault.read
train
def read file = FileReader.new(@path) return File.read(@path) unless file.encrypted? decryptor = Decryptor.new(password: @password, file: file) decryptor.plaintext end
ruby
{ "resource": "" }
q24042
JSchema.ValidationHelpers.non_empty_array?
train
def non_empty_array?(value, uniqueness_check = true) result = value.is_a?(Array) && !value.empty? if uniqueness_check result && value.size == value.uniq.size else result end end
ruby
{ "resource": "" }
q24043
JSchema.ValidationHelpers.schema_array?
train
def schema_array?(value, id, uniqueness_check = true) non_empty_array?(value, uniqueness_check) && value.to_enum.with_index.all? do |schema, index| full_id = [id, index].join('/') valid_schema? schema, full_id end end
ruby
{ "resource": "" }
q24044
JSchema.ValidationHelpers.valid_schema?
train
def valid_schema?(schema, id) schema.is_a?(Hash) && Schema.build(schema, parent, id) rescue InvalidSchema false end
ruby
{ "resource": "" }
q24045
Redmine.AcceptJson.get
train
def get(path, headers = {}) response = super(path, { 'Accept' => ACCEPT }.merge(headers.to_h)) case response.content_type when CONTENT_TYPE then [parse_response(response), response] else raise "Unknown content type #{response.content_type.inspect}" end end
ruby
{ "resource": "" }
q24046
Kondate.HashExt.deep_merge!
train
def deep_merge!(other_hash, &block) other_hash.each_pair do |current_key, other_value| this_value = self[current_key] self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash) _this_value = HashExt.new.replace(this_value) _this_value.deep_merge(other_value, &blo...
ruby
{ "resource": "" }
q24047
RestfulResource.Request.format_headers
train
def format_headers @headers.stringify_keys.each_with_object({}) do |key_with_value, headers| headers[format_key(key_with_value.first)] = key_with_value.last end end
ruby
{ "resource": "" }
q24048
CFoundry.Zip.unpack
train
def unpack(file, dest) ::Zip::ZipFile.foreach(file) do |zentry| epath = "#{dest}/#{zentry}" dirname = File.dirname(epath) FileUtils.mkdir_p(dirname) unless File.exists?(dirname) zentry.extract(epath) unless File.exists?(epath) end end
ruby
{ "resource": "" }
q24049
CFoundry.Zip.files_to_pack
train
def files_to_pack(dir) Dir.glob("#{dir}/**/*", File::FNM_DOTMATCH).select do |f| File.exists?(f) && PACK_EXCLUSION_GLOBS.none? do |e| File.fnmatch(e, File.basename(f)) end end end
ruby
{ "resource": "" }
q24050
CFoundry.Zip.pack
train
def pack(dir, zipfile) files = files_to_pack(dir) return false if files.empty? ::Zip::ZipFile.open(zipfile, true) do |zf| files.each do |f| zf.add(f.sub("#{dir}/",''), f) end end true end
ruby
{ "resource": "" }
q24051
Effective.FormBuilder.remote_link_to
train
def remote_link_to(name, url, options = {}, &block) options[:href] ||= url Effective::FormInputs::RemoteLinkTo.new(name, options, builder: self).to_html(&block) end
ruby
{ "resource": "" }
q24052
Slackbotsy.Api.get_objects
train
def get_objects(method, key) self.class.get("/#{method}", query: { token: @token }).tap do |response| raise "error retrieving #{key} from #{method}: #{response.fetch('error', 'unknown error')}" unless response['ok'] end.fetch(key) end
ruby
{ "resource": "" }
q24053
Slackbotsy.Api.join
train
def join(channel) self.class.post('/channels.join', body: {name: channel, token: @token}).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
{ "resource": "" }
q24054
Slackbotsy.Api.post_message
train
def post_message(params) self.class.post('/chat.postMessage', body: params.merge({token: @token})).tap do |response| raise "error posting message: #{response.fetch('error', 'unknown error')}" unless response['ok'] end end
ruby
{ "resource": "" }
q24055
CFoundry.UploadHelpers.prune_empty_directories
train
def prune_empty_directories(path) all_files = all_files(path) directories = all_files.select { |x| File.directory?(x) } directories.sort! { |a, b| b.size <=> a.size } directories.each do |directory| entries = all_files(directory) FileUtils.rmdir(directory) if entries.empty? ...
ruby
{ "resource": "" }
q24056
Slackbotsy.Bot.setup_incoming_webhook
train
def setup_incoming_webhook ## incoming_webhook will be used if provided, otherwise fallback to old-style url with team and token url = @options.fetch('incoming_webhook', false) || "https://#{@options['team']}.slack.com/services/hooks/incoming-webhook?token=#{@options['incoming_token']}" @uri = URI.pa...
ruby
{ "resource": "" }
q24057
Slackbotsy.Bot.post
train
def post(options) payload = { username: @options['name'], channel: @options['channel'] }.merge(options) payload[:channel] = payload[:channel].gsub(/^#?/, '#') #slack api needs leading # on channel request = Net::HTTP::Post.new(@uri.request_uri) request.set_form_data(payloa...
ruby
{ "resource": "" }
q24058
Slackbotsy.Bot.hear
train
def hear(regex, &block) @listeners << OpenStruct.new(regex: regex, desc: @last_desc, proc: block) @last_desc = nil end
ruby
{ "resource": "" }
q24059
Slackbotsy.Bot.eval_scripts
train
def eval_scripts(*files) files.flatten.each do |file| self.instance_eval(File.open(file).read) end end
ruby
{ "resource": "" }
q24060
Slackbotsy.Bot.handle_outgoing_webhook
train
def handle_outgoing_webhook(msg) return nil unless @options['outgoing_token'].include?(msg[:token]) # ensure messages are for us from slack return nil if msg[:user_name] == 'slackbot' # do not reply to self return nil unless msg[:text].is_a?(String) # skip empty messages responses = get_respon...
ruby
{ "resource": "" }
q24061
Slackbotsy.Bot.get_responses
train
def get_responses(msg, text) message = Slackbotsy::Message.new(self, msg) @listeners.map do |listener| text.match(listener.regex) do |mdata| begin message.instance_exec(mdata, *mdata[1..-1], &listener.proc) rescue => err # keep running even with a broken script, but re...
ruby
{ "resource": "" }
q24062
CFoundry::V2.Client.current_user
train
def current_user return unless token token_data = @base.token.token_data if guid = token_data[:user_id] user = user(guid) user.emails = [{ :value => token_data[:email] }] user end end
ruby
{ "resource": "" }
q24063
Twittbot.Bot.auth
train
def auth require 'oauth' say "This will reset your current access tokens.", :red if already_authed? # get the request token URL callback = OAuth::OUT_OF_BAND consumer = OAuth::Consumer.new $bot[:config][:consumer_key], $bot[:config][:consumer_secret], ...
ruby
{ "resource": "" }
q24064
Twittbot.Bot.start
train
def start check_config init_clients if $bot[:stream] puts "connecting to streaming APIs" @userstream_thread ||= Thread.new do loop do begin puts "connected to user stream" @streamer.user do |obj| handle_stream_object o...
ruby
{ "resource": "" }
q24065
Twittbot.Bot.load_bot_code
train
def load_bot_code load_special_tasks files = Dir["#{File.expand_path('./lib', @options[:current_dir])}/**/*"] files.each do |file| require_relative file.sub(/\.rb$/, '') if file.end_with? '.rb' end end
ruby
{ "resource": "" }
q24066
Twittbot.Bot.do_callbacks
train
def do_callbacks(callback_type, object, options = {}) return if $bot[:callbacks][callback_type].nil? $bot[:callbacks][callback_type].each do |c| c[:block].call object, options end end
ruby
{ "resource": "" }
q24067
Twittbot.Bot.do_direct_message
train
def do_direct_message(dm, opts = {}) return if dm.sender.screen_name == $bot[:config][:screen_name] return do_callbacks(:direct_message, dm, opts) unless dm.text.start_with? $bot[:config][:dm_command_prefix] dm_text = dm.text.sub($bot[:config][:dm_command_prefix], '').strip return if dm_text.emp...
ruby
{ "resource": "" }
q24068
Twittbot.Bot.list_tasks
train
def list_tasks tasks = $bot[:tasks].map do |name, value| [name, value[:desc]] end.to_h longest_name = tasks.keys.map(&:to_s).max { |a, b| a.length <=> b.length }.length tasks = tasks.map do |name, desc| "twittbot cron %-*s # %s" % [longest_name + 2, name, desc] end.sort ...
ruby
{ "resource": "" }
q24069
Phys.Quantity.want
train
def want(unit=nil) case unit when Unit expr = unit.expr when Quantity expr = unit.expr unit = unit.unit when String,Symbol expr = unit unit = Unit.parse(expr) when Numeric unit = Unit.cast(unit) when NilClass unit = Unit.cast(1)...
ruby
{ "resource": "" }
q24070
Phys.Quantity.close_to
train
def close_to(other,epsilon=Float::EPSILON) other_value = @unit.convert(other) abs_sum = @value.abs+other_value.abs (@value-other_value).abs <= abs_sum*epsilon end
ruby
{ "resource": "" }
q24071
Phys.Quantity.to_base_unit
train
def to_base_unit unit = @unit.base_unit val = unit.convert(self) expr = unit.unit_string self.class.new( val, expr, unit ) end
ruby
{ "resource": "" }
q24072
Phys.Quantity.inspect
train
def inspect expr = @expr || @unit.expr expr = (expr) ? ","+expr.inspect : "" sufx = (@@verbose_inspect) ? " "+@unit.inspect : "" self.class.to_s+"["+Unit::Utils.num_inspect(@value)+expr+"]"+sufx end
ruby
{ "resource": "" }
q24073
LIS::Message.Base.to_message
train
def to_message @fields ||= {} arr = Array.new(self.class.default_fields) type_id + @fields.inject(arr) { |a,(k,v)| a[k-1] = v; a }.join("|") end
ruby
{ "resource": "" }
q24074
Slaw.ActGenerator.guess_section_number_after_title
train
def guess_section_number_after_title(text) before = text.scan(/^\w{4,}[^\n]+\n\d+\. /).length after = text.scan(/^\s*\n\d+\. \w{4,}/).length before > after * 1.25 end
ruby
{ "resource": "" }
q24075
Slaw.ActGenerator.text_from_act
train
def text_from_act(doc) # look on the load path for an XSL file for this grammar filename = "/slaw/grammars/#{@grammar}/act_text.xsl" if dir = $LOAD_PATH.find { |p| File.exist?(p + filename) } xslt = Nokogiri::XSLT(File.read(dir + filename)) xslt.transform(doc).child.to_xml else ...
ruby
{ "resource": "" }
q24076
ThreeScale.Client.authorize
train
def authorize(options) extensions = options.delete :extensions creds = creds_params(options) path = "/transactions/authorize.xml" + options_to_params(options, ALL_PARAMS) + '&' + creds headers = extensions_to_header extensions if extensions http_response = @http.get(path, headers: headers...
ruby
{ "resource": "" }
q24077
ThreeScale.Client.usage_report
train
def usage_report(node) period_start = node.at('period_start') period_end = node.at('period_end') { :metric => node['metric'].to_s.strip, :period => node['period'].to_s.strip.to_sym, :period_start => period_start ? period_start.content : '', :period_end => per...
ruby
{ "resource": "" }
q24078
ThreeScale.Client.generate_creds_params
train
def generate_creds_params define_singleton_method :creds_params, if @service_tokens lambda do |options| token = options.delete(:service_token) service_id = options[:service_id] raise ArgumentError, "need to specify a service_token and a service_id" unless toke...
ruby
{ "resource": "" }
q24079
Twitter.Tweet.reply
train
def reply(tweet_text, options = {}) return if $bot.nil? or $bot[:client].nil? opts = { reply_all: false }.merge(options) mentions = self.mentioned_users(opts[:reply_all]) result = "@#{mentions.join(" @")} #{tweet_text}"[(0...140)] $bot[:client].update result, in_reply_to_s...
ruby
{ "resource": "" }
q24080
Twitter.Tweet.mentioned_users
train
def mentioned_users(reply_all = true, screen_name = $bot[:config][:screen_name]) userlist = [ self.user.screen_name ] if reply_all self.text.scan /@([A-Za-z0-9_]{1,16})/ do |user_name| user_name = user_name[0] userlist << user_name unless userlist.include?(user_name) or screen_na...
ruby
{ "resource": "" }
q24081
Twitter.DirectMessage.reply
train
def reply(direct_message_text) return if $bot.nil? or $bot[:client].nil? $bot[:client].create_direct_message self.sender.id, direct_message_text rescue Twitter::Error => e puts "caught Twitter error while replying via DM: #{e.message}" end
ruby
{ "resource": "" }
q24082
Sinew.Request.perform
train
def perform validate! party_options = options.dup # merge proxy if proxy = self.proxy addr, port = proxy.split(':') party_options[:http_proxyaddr] = addr party_options[:http_proxyport] = port || 80 end # now merge runtime_options party_options = party...
ruby
{ "resource": "" }
q24083
Sinew.Request.parse_url
train
def parse_url(url) s = url # remove entities s = HTML_ENTITIES.decode(s) # fix a couple of common encoding bugs s = s.gsub(' ', '%20') s = s.gsub("'", '%27') # append query manually (instead of letting HTTParty handle it) so we can # include it in cache_key query...
ruby
{ "resource": "" }
q24084
Twittbot.BotPart.cmd
train
def cmd(name, options = {}, &block) raise "Command already exists: #{name}" if $bot[:commands].include? name raise "Command name does not contain only alphanumerical characters" unless name.to_s.match /\A[A-Za-z0-9]+\z/ opts = { admin: true }.merge(options) $bot[:commands][name...
ruby
{ "resource": "" }
q24085
Twittbot.BotPart.task
train
def task(name, options = {}, &block) name = name.to_s.downcase.to_sym task_re = /\A[a-z0-9.:-_]+\z/ raise "Task already exists: #{name}" if $bot[:tasks].include?(name) raise "Task name does not match regexp #{task_re.to_s}" unless name.to_s.match(task_re) opts = { desc: '' }...
ruby
{ "resource": "" }
q24086
Twittbot.BotPart.save_config
train
def save_config botpart_config = Hash[@config.to_a - $bot[:config].to_a] unless botpart_config.empty? File.open @botpart_config_path, 'w' do |f| f.write botpart_config.to_yaml end end end
ruby
{ "resource": "" }
q24087
CFoundry::V2.App.health
train
def health if state == "STARTED" healthy_count = running_instances expected = total_instances if expected > 0 ratio = healthy_count / expected.to_f if ratio == 1.0 "RUNNING" else "#{(ratio * 100).to_i}%" end else ...
ruby
{ "resource": "" }
q24088
CFoundry::V2.App.bind
train
def bind(*instances) instances.each do |i| binding = @client.service_binding binding.app = self binding.service_instance = i binding.create! end self end
ruby
{ "resource": "" }
q24089
CFoundry::V2.App.unbind
train
def unbind(*instances) service_bindings.each do |b| if instances.include? b.service_instance b.delete! end end self end
ruby
{ "resource": "" }
q24090
Metar.Station.parser
train
def parser raw = Metar::Raw::Noaa.new(@cccc) Metar::Parser.new(raw) end
ruby
{ "resource": "" }
q24091
Openfoodfacts.Product.weburl
train
def weburl(locale: nil, domain: DEFAULT_DOMAIN) locale ||= self.lc || DEFAULT_LOCALE if self.code && prefix = LOCALE_WEBURL_PREFIXES[locale] path = "#{prefix}/#{self.code}" "https://#{locale}.#{domain}/#{path}" end end
ruby
{ "resource": "" }
q24092
Metar.Parser.seek_visibility
train
def seek_visibility if observer.value == :auto # WMO 15.4 if @chunks[0] == '////' @chunks.shift # Simply dispose of it return end end if @chunks[0] == '1' or @chunks[0] == '2' @visibility = Metar::Data::Visibility.parse(@chunks[0] + ' ' + @chunks[1]) ...
ruby
{ "resource": "" }
q24093
Phys.Unit.inspect
train
def inspect use_dimension a = [Utils.num_inspect(@factor), @dim.inspect] a << "@name="+@name.inspect if @name a << "@expr="+@expr.inspect if @expr a << "@offset="+@offset.inspect if @offset a << "@dimensionless=true" if @dimensionless if @dimension_value && @dimension_value!=1 ...
ruby
{ "resource": "" }
q24094
Phys.Unit.unit_string
train
def unit_string use_dimension a = [] a << Utils.num_inspect(@factor) if @factor!=1 a += @dim.map do |k,d| if d==1 k else "#{k}^#{d}" end end a.join(" ") end
ruby
{ "resource": "" }
q24095
Phys.Unit.conversion_factor
train
def conversion_factor use_dimension f = @factor @dim.each do |k,d| if d != 0 u = LIST[k] if u.dimensionless? f *= u.dimension_value**d end end end f end
ruby
{ "resource": "" }
q24096
Phys.Unit.convert
train
def convert(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.unit.convert_value_to_base_unit(quantity.value) convert_value_from_base_unit(v) else quantity / to_numeric end end
ruby
{ "resource": "" }
q24097
Phys.Unit.convert_scale
train
def convert_scale(quantity) if Quantity===quantity assert_same_dimension(quantity.unit) v = quantity.value * quantity.unit.conversion_factor v = v / self.conversion_factor else quantity / to_numeric end end
ruby
{ "resource": "" }
q24098
Phys.Unit.+
train
def +(x) x = Unit.cast(x) check_operable2(x) assert_same_dimension(x) Unit.new(@factor+x.factor,@dim.dup) end
ruby
{ "resource": "" }
q24099
Phys.Unit.*
train
def *(x) x = Unit.cast(x) if scalar? return x elsif x.scalar? return self.dup end check_operable2(x) dims = dimension_binop(x){|a,b| a+b} factor = self.factor * x.factor Unit.new(factor,dims) end
ruby
{ "resource": "" }