_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q24800
TeaLeaves.MovingAverage.check_weights
train
def check_weights raise ArgumentError.new("Weights should be an odd list") unless @span.odd? sum = weights.inject(&:+) if sum < 0.999999 || sum > 1.000001 raise ArgumentError.new("Weights must sum to 1") end end
ruby
{ "resource": "" }
q24801
MediaWiki.Purge.purge_request
train
def purge_request(params, *titles) params[:action] = 'purge' params[:titles] = titles.join('|') post(params)['purge'].inject({}) do |result, hash| title = hash['title'] result[title] = hash.key?('purged') && !hash.key?('missing') warn "Invalid purge (#{title}) #{hash['invalidreason']}" if hash.key?('invalid') result end end
ruby
{ "resource": "" }
q24802
Spice.Config.reset
train
def reset self.user_agent = DEFAULT_USER_AGENT self.server_url = DEFAULT_SERVER_URL self.chef_version = DEFAULT_CHEF_VERSION self.client_name = DEFAULT_CLIENT_NAME self.client_key = DEFAULT_CLIENT_KEY self.connection_options = DEFAULT_CONNECTION_OPTIONS self.middleware = DEFAULT_MIDDLEWARE self end
ruby
{ "resource": "" }
q24803
DataSift.Client.valid?
train
def valid?(csdl, boolResponse = true) requires({ :csdl => csdl }) res = DataSift.request(:POST, 'validate', @config, :csdl => csdl ) boolResponse ? res[:http][:status] == 200 : res end
ruby
{ "resource": "" }
q24804
DataSift.Client.dpu
train
def dpu(hash = '', historics_id = '') fail ArgumentError, 'Must pass a filter hash or Historics ID' if hash.empty? && historics_id.empty? fail ArgumentError, 'Must only pass hash or Historics ID; not both' unless hash.empty? || historics_id.empty? params = {} params.merge!(hash: hash) unless hash.empty? params.merge!(historics_id: historics_id) unless historics_id.empty? DataSift.request(:POST, 'dpu', @config, params) end
ruby
{ "resource": "" }
q24805
Danger.DangerSynx.synx_issues
train
def synx_issues (git.modified_files + git.added_files) .select { |f| f.include? '.xcodeproj' } .reduce([]) { |i, f| i + synx_project(f) } end
ruby
{ "resource": "" }
q24806
Teambition.API.valid_token?
train
def valid_token? uri = URI.join(Teambition::API_DOMAIN, "/api/applications/#{Teambition.client_key}/tokens/check") req = Net::HTTP::Get.new(uri) req['Authorization'] = "OAuth2 #{token}" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |https| https.request(req) end res.code == '200' end
ruby
{ "resource": "" }
q24807
S3SwfUpload.Signature.core_sha1
train
def core_sha1(x, len) # append padding x[len >> 5] ||= 0 x[len >> 5] |= 0x80 << (24 - len % 32) x[((len + 64 >> 9) << 4) + 15] = len w = Array.new(80, 0) a = 1_732_584_193 b = -271_733_879 c = -1_732_584_194 d = 271_733_878 e = -1_009_589_776 # for(var i = 0; i < x.length; i += 16) i = 0 while i < x.length olda = a oldb = b oldc = c oldd = d olde = e # for(var j = 0; j < 80; j++) j = 0 while j < 80 if j < 16 w[j] = x[i + j] || 0 else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1) end t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))) e = d d = c c = rol(b, 30) b = a a = t j += 1 end a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) e = safe_add(e, olde) i += 16 end [a, b, c, d, e] end
ruby
{ "resource": "" }
q24808
S3SwfUpload.Signature.sha1_ft
train
def sha1_ft(t, b, c, d) return (b & c) | ((~b) & d) if t < 20 return b ^ c ^ d if t < 40 return (b & c) | (b & d) | (c & d) if t < 60 b ^ c ^ d end
ruby
{ "resource": "" }
q24809
S3SwfUpload.Signature.core_hmac_sha1
train
def core_hmac_sha1(key, data) bkey = str2binb(key) bkey = core_sha1(bkey, key.length * $chrsz) if bkey.length > 16 ipad = Array.new(16, 0) opad = Array.new(16, 0) # for(var i = 0; i < 16; i++) i = 0 while i < 16 ipad[i] = (bkey[i] || 0) ^ 0x36363636 opad[i] = (bkey[i] || 0) ^ 0x5C5C5C5C i += 1 end hash = core_sha1((ipad + str2binb(data)), 512 + data.length * $chrsz) core_sha1((opad + hash), 512 + 160) end
ruby
{ "resource": "" }
q24810
S3SwfUpload.Signature.str2binb
train
def str2binb(str) bin = [] mask = (1 << $chrsz) - 1 # for(var i = 0; i < str.length * $chrsz; i += $chrsz) i = 0 while i < str.length * $chrsz bin[i >> 5] ||= 0 bin[i >> 5] |= (str[i / $chrsz] & mask) << (32 - $chrsz - i % 32) i += $chrsz end bin end
ruby
{ "resource": "" }
q24811
S3SwfUpload.Signature.binb2b64
train
def binb2b64(binarray) tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' str = '' # for(var i = 0; i < binarray.length * 4; i += 3) i = 0 while i < binarray.length * 4 triplet = (((binarray[i >> 2].to_i >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2].to_i >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2].to_i >> 8 * (3 - (i + 2) % 4)) & 0xFF) # for(var j = 0; j < 4; j++) j = 0 while j < 4 if i * 8 + j * 6 > binarray.length * 32 str += $b64pad else str += tab[(triplet >> 6 * (3 - j)) & 0x3F].chr end j += 1 end i += 3 end str end
ruby
{ "resource": "" }
q24812
DataSift.AccountIdentity.create
train
def create(label = '', status = 'active', master = '') fail ArgumentError, 'label is missing' if label.empty? params = { label: label } params.merge!(status: status) unless status.empty? params.merge!(master: master) if [TrueClass, FalseClass].include?(master.class) DataSift.request(:POST, 'account/identity', @config, params) end
ruby
{ "resource": "" }
q24813
DataSift.AccountIdentity.list
train
def list(label = '', per_page = '', page = '') params = {} params.merge!(label: label) unless label.empty? params.merge!(per_page: per_page) unless per_page.empty? params.merge!(page: page) unless page.empty? DataSift.request(:GET, 'account/identity', @config, params) end
ruby
{ "resource": "" }
q24814
EmbeddedAssociations.Processor.handle_resource
train
def handle_resource(definition, parent, parent_params) if definition.is_a? Array return definition.each{|d| handle_resource(d, parent, parent_params)} end # normalize to a hash unless definition.is_a? Hash definition = {definition => nil} end definition.each do |name, child_definition| if !parent_params || !parent_params.has_key?(name.to_s) next end reflection = parent.class.reflect_on_association(name) attrs = parent_params.delete(name.to_s) if reflection.collection? attrs ||= [] handle_plural_resource parent, name, attrs, child_definition else handle_singular_resource parent, name, attrs, child_definition end end end
ruby
{ "resource": "" }
q24815
GoogleBook.Book.search
train
def search(query,type = nil) checking_type(type) type = set_type(type) unless type.nil? if query.nil? puts 'Enter the text to search' text = gets end json = JSON.parse(connect_google(@api_key,type,query)) @total_count = json["totalItems"] @items = json["items"] end
ruby
{ "resource": "" }
q24816
GoogleBook.Book.filter
train
def filter(query, type = nil) checking_filter_type(type) filter_type = set_filter_type(type) unless type.nil? json = JSON.parse(connect_google(@api_key,nil,query,filter_type)) @total_count = json["totalItems"] @items = json["items"] end
ruby
{ "resource": "" }
q24817
DataSift.Push.valid?
train
def valid?(params, bool_response = true) requires params res = DataSift.request(:POST, 'push/validate', @config, params) bool_response ? res[:http][:status] == 200 : res end
ruby
{ "resource": "" }
q24818
DataSift.Push.log_for
train
def log_for(id, page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :id => id } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir ) DataSift.request(:GET, 'push/log', @config, params) end
ruby
{ "resource": "" }
q24819
DataSift.Push.log
train
def log(page = 1, per_page = 20, order_by = :request_time, order_dir = :desc) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir } DataSift.request(:GET, 'push/log', @config, params) end
ruby
{ "resource": "" }
q24820
DataSift.Push.get_by_hash
train
def get_by_hash(hash, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :hash => hash } requires params params.merge!( :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all ) DataSift.request(:GET, 'push/get', @config, params) end
ruby
{ "resource": "" }
q24821
DataSift.Push.get_by_historics_id
train
def get_by_historics_id(historics_id, page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :historics_id => historics_id, :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
ruby
{ "resource": "" }
q24822
DataSift.Push.get
train
def get(page = 1, per_page = 20, order_by = :created_at, order_dir = :desc, include_finished = 0, all = false) params = { :page => page, :per_page => per_page, :order_by => order_by, :order_dir => order_dir, :include_finished => include_finished, :all => all } DataSift.request(:GET, 'push/get', @config, params) end
ruby
{ "resource": "" }
q24823
DataSift.Push.pull
train
def pull(id, size = 52_428_800, cursor = '', callback = nil) params = { :id => id } requires params params.merge!( :size => size, :cursor => cursor ) params.merge!({:on_interaction => callback}) unless callback.nil? DataSift.request(:GET, 'pull', @config, params, {}, 30, 30, true) end
ruby
{ "resource": "" }
q24824
MediaWiki.Edit.edit
train
def edit(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true params = { action: 'edit', title: title, text: text, nocreate: 1, format: 'json', token: get_token } params[:summary] ||= opts[:summary] params[:minor] = '1' if opts[:minor] params[:bot] = '1' if opts[:bot] response = post(params) if response.dig('edit', 'result') == 'Success' return false if response.dig('edit', 'nochange') return response.dig('edit', 'newrevid') end raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
{ "resource": "" }
q24825
MediaWiki.Edit.create_page
train
def create_page(title, text, opts = {}) opts[:bot] = opts.key?(:bot) ? opts[:bot] : true opts[:summary] ||= 'New page' params = { action: 'edit', title: title, text: text, summary: opts[:summary], createonly: 1, format: 'json', token: get_token } params[:bot] = '1' if opts[:bot] response = post(params) return response['edit']['pageid'] if response.dig('edit', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
{ "resource": "" }
q24826
MediaWiki.Edit.upload
train
def upload(url, filename = nil) params = { action: 'upload', url: url, token: get_token } filename = filename.nil? ? url.split('/')[-1] : filename.sub(/^File:/, '') ext = filename.split('.')[-1] allowed_extensions = get_allowed_file_extensions raise MediaWiki::Butt::UploadInvalidFileExtError.new unless allowed_extensions.include?(ext) params[:filename] = filename response = post(params) response.dig('upload', 'warnings')&.each do |warning| warn warning end return true if response.dig('upload', 'result') == 'Success' raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
{ "resource": "" }
q24827
MediaWiki.Edit.move
train
def move(from, to, opts = {}) opts[:talk] = opts.key?(:talk) ? opts[:talk] : true params = { action: 'move', from: from, to: to, token: get_token } params[:reason] ||= opts[:reason] params[:movetalk] = '1' if opts[:talk] params[:noredirect] = '1' if opts[:suppress_redirect] response = post(params) return true if response['move'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
{ "resource": "" }
q24828
MediaWiki.Edit.delete
train
def delete(title, reason = nil) params = { action: 'delete', title: title, token: get_token } params[:reason] = reason unless reason.nil? response = post(params) return true if response['delete'] raise MediaWiki::Butt::EditError.new(response.dig('error', 'code') || 'Unknown error code') end
ruby
{ "resource": "" }
q24829
Middleman::Cli.ListAll.list_all
train
def list_all # Determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end app_config = app.config.clone app.shutdown! # Because after_configuration won't run again until we # build, we'll fake the strings with the one given for # the default. So for each target, gsub the target for # the initial target already given in config. app_config[:targets].each do |target| target_org = app_config[:target].to_s target_req = target[0].to_s path_org = app_config[:build_dir] path_req = path_org.reverse.sub(target_org.reverse, target_req.reverse).reverse say "#{target_req}, #{File.expand_path(path_req)}", :cyan end end
ruby
{ "resource": "" }
q24830
ActionMailer.Base.render_with_layout_and_partials
train
def render_with_layout_and_partials(format) # looking for system mail. template = MailEngine::MailTemplate.where(:path => "#{controller_path}/#{action_name}", :format => format, :locale => I18n.locale, :partial => false, :for_marketing => false).first # looking for marketing mail. template = MailEngine::MailTemplate.where(:path => action_name, :format => format, :locale => I18n.locale, :partial => false, :for_marketing => true).first if template.blank? # if found db template set the layout and partial for it. if template related_partial_paths = {} # set @footer or @header template.template_partials.each do |tmp| related_partial_paths["#{tmp.placeholder_name}_path".to_sym] = tmp.partial.path end # set layout render :template => "#{controller_path}/#{action_name}", :layout => "layouts/mail_engine/mail_template_layouts/#{template.layout}", :locals => related_partial_paths else # if not found db template should render file template render(action_name) end end
ruby
{ "resource": "" }
q24831
Diane.Recorder.record
train
def record if File.exist? DIFILE CSV.open(DIFILE, 'a') { |csv| csv << [@user, @message, @time] } else CSV.open(DIFILE, 'a') do |csv| csv << %w[user message time] csv << [@user, @message, @time] end end puts '✓'.green rescue StandardError => e abort 'Broken'.magenta + e end
ruby
{ "resource": "" }
q24832
Diane.Recorder.slug
train
def slug(user) abort 'User is nil. Fuck off.'.magenta if user.nil? user.downcase.strip.tr(' ', '_').gsub(/[^\w-]/, '') end
ruby
{ "resource": "" }
q24833
FREDAPI.Connection.connection
train
def connection opts={} connection = Faraday.new(opts) do |conn| if opts[:force_urlencoded] conn.request :url_encoded else conn.request :json end conn.request :json conn.use FaradayMiddleware::FollowRedirects conn.use FaradayMiddleware::Mashify conn.use FaradayMiddleware::ParseJson, :content_type => /\bjson$/ conn.use FaradayMiddleware::ParseXml, :content_type => /\bxml$/ conn.adapter adapter end connection.headers[:user_agent] = user_agent connection end
ruby
{ "resource": "" }
q24834
Aequitas.Violation.message
train
def message(transformer = Undefined) return @custom_message if @custom_message transformer = self.transformer if Undefined.equal?(transformer) transformer.transform(self) end
ruby
{ "resource": "" }
q24835
Eldritch.DSL.together
train
def together old = Thread.current.eldritch_group group = Group.new Thread.current.eldritch_group = group yield group group.join_all Thread.current.eldritch_group = old end
ruby
{ "resource": "" }
q24836
AlchemyFlux.Service.start
train
def start return if @state != :stopped Service.start(@options[:ampq_uri], @options[:threadpool_size]) EM.run do @channel = AMQP::Channel.new(@@connection) @channel.on_error do |ch, channel_close| message = "Channel exception: [#{channel_close.reply_code}] #{channel_close.reply_text}" puts message raise message end @channel.prefetch(@options[:prefetch]) @channel.auto_recovery = true @service_queue = @channel.queue( @service_queue_name, {:durable => true}) @service_queue.subscribe({:ack => true}) do |metadata, payload| payload = JSON.parse(payload) process_service_queue_message(metadata, payload) end response_queue = @channel.queue(@response_queue_name, {:exclusive => true, :auto_delete => true}) response_queue.subscribe({}) do |metadata, payload| payload = JSON.parse(payload) process_response_queue_message(metadata, payload) end @channel.default_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end # RESOURCES HANDLE @resources_exchange = @channel.topic("resources.exchange", {:durable => true}) @resources_exchange.on_return do |basic_return, frame, payload| payload = JSON.parse(payload) process_returned_message(basic_return, frame.properties, payload) end bound_resources = 0 for resource_path in @options[:resource_paths] binding_key = "#{path_to_routing_key(resource_path)}.#" @service_queue.bind(@resources_exchange, :key => binding_key) { bound_resources += 1 } end begin # simple loop to wait for the resources to be bound sleep(0.01) end until bound_resources == @options[:resource_paths].length @state = :started end end
ruby
{ "resource": "" }
q24837
AlchemyFlux.Service.stop
train
def stop return if @state != :started # stop receiving new incoming messages @service_queue.unsubscribe # only stop the service if all incoming and outgoing messages are complete decisecond_timeout = @options[:timeout]/100 waited_deciseconds = 0 # guarantee that this loop will stop while (@transactions.length > 0 || @processing_messages > 0) && waited_deciseconds < decisecond_timeout sleep(0.1) # wait a decisecond to check the incoming and outgoing messages again waited_deciseconds += 1 end @channel.close @state = :stopped end
ruby
{ "resource": "" }
q24838
AlchemyFlux.Service.process_service_queue_message
train
def process_service_queue_message(metadata, payload) service_to_reply_to = metadata.reply_to message_replying_to = metadata.message_id this_message_id = AlchemyFlux::Service.generateUUID() delivery_tag = metadata.delivery_tag operation = proc { @processing_messages += 1 begin response = @service_fn.call(payload) { 'status_code' => response['status_code'] || 200, 'body' => response['body'] || "", 'headers' => response['headers'] || {} } rescue AlchemyFlux::NAckError => e AlchemyFlux::NAckError rescue Exception => e e end } callback = proc { |result| if result == AlchemyFlux::NAckError @service_queue.reject(delivery_tag) elsif result.is_a?(Exception) # if there is an unhandled exception from the service, # raise it to force exit and container management can spin up a new one raise result else #if there is a service to reply to then reply, else ignore if service_to_reply_to send_message(@channel.default_exchange, service_to_reply_to, result, { :message_id => this_message_id, :correlation_id => message_replying_to, :type => 'http_response' }) end @processing_messages -= 1 @service_queue.acknowledge(delivery_tag) end } EventMachine.defer(operation, callback) end
ruby
{ "resource": "" }
q24839
AlchemyFlux.Service.process_response_queue_message
train
def process_response_queue_message(metadata, payload) response_queue = @transactions.delete metadata.correlation_id response_queue << payload if response_queue end
ruby
{ "resource": "" }
q24840
AlchemyFlux.Service.process_returned_message
train
def process_returned_message(basic_return, metadata, payload) response_queue = @transactions.delete metadata[:message_id] response_queue << MessageNotDeliveredError if response_queue end
ruby
{ "resource": "" }
q24841
AlchemyFlux.Service.send_message
train
def send_message(exchange, routing_key, message, options) message_options = options.merge({:routing_key => routing_key}) message = message.to_json EventMachine.next_tick do exchange.publish message, message_options end end
ruby
{ "resource": "" }
q24842
AlchemyFlux.Service.send_request_to_service
train
def send_request_to_service(service_name, message) if block_given? EventMachine.defer do yield send_request_to_service(service_name, message) end else send_HTTP_request(@channel.default_exchange, service_name, message) end end
ruby
{ "resource": "" }
q24843
AlchemyFlux.Service.send_request_to_resource
train
def send_request_to_resource(message) routing_key = path_to_routing_key(message['path']) if block_given? EventMachine.defer do yield send_request_to_resource(message) end else send_HTTP_request(@resources_exchange, routing_key, message) end end
ruby
{ "resource": "" }
q24844
AlchemyFlux.Service.path_to_routing_key
train
def path_to_routing_key(path) new_path = "" path.split('').each_with_index do |c,i| if c == '/' and i != 0 and i != path.length-1 new_path += '.' elsif c != '/' new_path += c end end new_path end
ruby
{ "resource": "" }
q24845
AlchemyFlux.Service.format_HTTP_message
train
def format_HTTP_message(message) message = { # Request Parameters 'body' => message['body'] || "", 'verb' => message['verb'] || "GET", 'headers' => message['headers'] || {}, 'path' => message['path'] || "/", 'query' => message['query'] || {}, # Location 'scheme' => message['protocol'] || 'http', 'host' => message['hostname'] || '127.0.0.1', 'port' => message['port'] || 8080, # Custom Authentication 'session' => message['session'] } message end
ruby
{ "resource": "" }
q24846
OhEmbedr.OhEmbedr.gets
train
def gets begin data = make_http_request @hash = send(@@formats[@format][:oembed_parser], data) # Call the method specified in default_formats hash above rescue RuntimeError => e if e.message == "401" # Embedding disabled return nil elsif e.message == "501" # Format not supported raise UnsupportedError, "#{@format} not supported by #{@domain}" elsif e.message == "404" # Not found raise Error, "#{@url} not found" else raise e end end end
ruby
{ "resource": "" }
q24847
OhEmbedr.OhEmbedr.load_format
train
def load_format requested_format = nil raise ArgumentError, "Requested format not supported" if !requested_format.nil? && @@formats[requested_format].nil? @format = requested_format || @@default_format attempted_formats = "" begin attempted_formats += @@formats[@format][:require] require @@formats[@format][:require] return true rescue LoadError # If the user requested the format and it failed. Just give up! raise Error("Please install: '#{@@formats[@format][:require]}' to use #{@format} format.") unless requested_format.nil? # Otherwise lets exhaust all our other options first available_formats = @@formats available_formats.delete(@format) available_formats.each_key do |format| begin attempted_formats += ", " require @@formats[format][:require] @format = format return true rescue LoadError attempted_formats += @@formats[format][:require] end end raise Error, "Could not find any suitable library to parse response with, tried: #{attempted_formats}. Please install one of these to use OEmbed." end end
ruby
{ "resource": "" }
q24848
BcmsBlog.BlogObserver.create_post_portlet_page
train
def create_post_portlet_page page = Cms::Page.find_by_name(portlet_name = "#{@blog.name}: Post") || Cms::Page.create!( :name => portlet_name, :path => "/#{@blog.name_for_path}/post", :section => @section, :template_file_name => "default.html.erb", :hidden => true) page.publish create_route(page, portlet_name, "/#{@blog.name_for_path}/:year/:month/:day/:slug") create_portlet(page, portlet_name, BlogPostPortlet) end
ruby
{ "resource": "" }
q24849
Evnt.Command.err
train
def err(message, code: nil) @state[:result] = false @state[:errors].push( message: message, code: code ) # raise error if command needs exceptions raise message if @options[:exceptions] end
ruby
{ "resource": "" }
q24850
Evnt.Command._init_command_data
train
def _init_command_data(params) # set state @state = { result: true, errors: [] } # set options initial_options = { exceptions: false, nullify_empty_params: false } default_options = _safe_default_options || {} params_options = params[:_options] || {} @options = initial_options.merge(default_options) .merge(params_options) # set other data @params = params end
ruby
{ "resource": "" }
q24851
Evnt.Command._validate_single_params
train
def _validate_single_params validations = _safe_validations validations.each do |val| value_to_validate = _value_to_validate(val) validator = Evnt::Validator.new(value_to_validate, val[:options]) if validator.passed? @params[val[:param]] = validator.value else error = val[:options][:err] || "#{val[:param].capitalize} value not accepted" err_code = val[:options][:err_code] || val[:param].to_sym err(error, code: err_code) break end end @params end
ruby
{ "resource": "" }
q24852
RubyOnAcid.Factory.choose
train
def choose(key, *choices) all_choices = choices.flatten index = (get_unit(key) * all_choices.length).floor index = all_choices.length - 1 if index > all_choices.length - 1 all_choices[index] end
ruby
{ "resource": "" }
q24853
ActionController.Permittance.permitter
train
def permitter(pclass = permitter_class) pinstance = (@permitter_class_to_permitter ||= {})[pclass] return pinstance if pinstance current_authorizer_method = ActionController::Permitter.current_authorizer_method ? ActionController::Permitter.current_authorizer_method.to_sym : nil @permitter_class_to_permitter[pclass] = pclass.new(params, defined?(current_user) ? current_user : nil, current_authorizer_method && defined?(current_authorizer_method) ? __send__(current_authorizer_method) : nil) end
ruby
{ "resource": "" }
q24854
StateMachine.Transition.handle_in_source_state
train
def handle_in_source_state if @state_machine.initial_queue.nil? raise RuntimeError, "State machine not started yet." end if Dispatch::Queue.current.to_s != @state_machine.initial_queue.to_s raise RuntimeError, "#{self.class.event_type}:#{@event_trigger_value} must be "\ "called from the queue where the state machine was started." end @source_state.send :guarded_execute, self.class.event_type, @event_trigger_value end
ruby
{ "resource": "" }
q24855
Cube.Client.actual_send
train
def actual_send(type, time, id, data) # Namespace support! prefix = "#{@namespace}_" unless @namespace.nil? # Get rid of any unwanted characters, and replace each of them with an _. type = type.to_s.gsub RESERVED_CHARS_REGEX, '_' # Start constructing the message to be sent to Cube over UDP. message = { type: "#{prefix}#{type}" } message[:time] = time.iso8601 unless time.nil? message[:id] = id unless id.nil? message[:data] = data unless data.nil? # JSONify it, log it, and send it off. message_str = message.to_json self.class.logger.debug { "Cube: #{message_str}" } if self.class.logger socket.send message_str, 0, @host, @port rescue => err self.class.logger.error { "Cube: #{err.class} #{err}" } if self.class.logger end
ruby
{ "resource": "" }
q24856
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked
train
def link_to_tracked(name, track_path = "/", options = {}, html_options = {}) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to name, options, html_options end
ruby
{ "resource": "" }
q24857
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked_if
train
def link_to_tracked_if(condition, name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick => tracking_call(track_path)}) link_to_unless !condition, name, options, html_options, &block end
ruby
{ "resource": "" }
q24858
Rubaidh.GoogleAnalyticsViewHelper.link_to_tracked_unless_current
train
def link_to_tracked_unless_current(name, track_path = "/", options = {}, html_options = {}, &block) raise AnalyticsError.new("You must set Rubaidh::GoogleAnalytics.defer_load = false to use outbound link tracking") if GoogleAnalytics.defer_load == true html_options.merge!({:onclick =>tracking_call(track_path)}) link_to_unless current_page?(options), name, options, html_options, &block end
ruby
{ "resource": "" }
q24859
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_for
train
def simple_sidekiq_delay_for(interval, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => Time.now.to_f + interval.to_f)) end
ruby
{ "resource": "" }
q24860
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_until
train
def simple_sidekiq_delay_until(timestamp, options = {}) Proxy.new(simple_delayed_worker, self, options.merge('at' => timestamp.to_f)) end
ruby
{ "resource": "" }
q24861
SidekiqSimpleDelay.DelayMethods.simple_sidekiq_delay_spread
train
def simple_sidekiq_delay_spread(options = {}) local_opts = options.dup spread_duration = Utils.extract_option(local_opts, :spread_duration, 1.hour).to_f spread_in = Utils.extract_option(local_opts, :spread_in, 0).to_f spread_at = Utils.extract_option(local_opts, :spread_at) spread_method = Utils.extract_option(local_opts, :spread_method, :rand) spread_mod_value = Utils.extract_option(local_opts, :spread_mod_value) spread_mod_method = Utils.extract_option(local_opts, :spread_mod_method) spread_duration = 0 if spread_duration < 0 spread_in = 0 if spread_in < 0 spread = # kick of immediately if the duration is 0 if spread_duration.zero? 0 else case spread_method.to_sym when :rand Utils.random_number(spread_duration) when :mod mod_value = # The mod value has been supplied if !spread_mod_value.nil? spread_mod_value # Call the supplied method on the target object to get mod value elsif !spread_mod_method.nil? send(spread_mod_method) # Call `spread_mod_method` on target object to get mod value elsif respond_to?(:spread_mod_method) send(send(:spread_mod_method)) else raise ArgumentError, 'must specify `spread_mod_value` or `spread_mod_method` or taget must respond to `spread_mod_method`' end # calculate the mod based offset mod_value % spread_duration else raise ArgumentError, "spread_method must :rand or :mod, `#{spread_method} is invalid`" end end t = if !spread_at.nil? # add spread to a timestamp spread_at.to_f + spread elsif !spread_in.nil? # add spread to no plus constant offset Time.now.to_f + spread_in.to_f + spread else # add spread to current time Time.now.to_f + spread end Proxy.new(SimpleDelayedWorker, self, local_opts.merge('at' => t)) end
ruby
{ "resource": "" }
q24862
CelluloidPubsub.WebServer.handle_dispatched_message
train
def handle_dispatched_message(reactor, data) log_debug "#{self.class} trying to dispatch message #{data.inspect}" message = reactor.parse_json_data(data) final_data = message.present? && message.is_a?(Hash) ? message.to_json : data.to_json reactor.websocket << final_data end
ruby
{ "resource": "" }
q24863
Middleman::Cli.BuildAll.build_all
train
def build_all # The first thing we want to do is create a temporary application # instance so that we can determine the valid targets. app = ::Middleman::Application.new do config[:exit_before_ready] = true end build_list = app.config[:targets].each_key.collect { |item| item.to_s } bad_builds = [] build_list.each do |target| bad_builds << target unless Build.start(['--target', target]) end unless bad_builds.count == 0 say say 'These targets produced errors during build:', :red bad_builds.each { |item| say " #{item}", :red} end bad_builds.count == 0 end
ruby
{ "resource": "" }
q24864
Datatable.Helper.ruby_aocolumns
train
def ruby_aocolumns result = [] column_def_keys = %w[ asSorting bSearchable bSortable bUseRendered bVisible fnRender iDataSort mDataProp sClass sDefaultContent sName sSortDataType sTitle sType sWidth link_to ] index = 0 @datatable.columns.each_value do |column_hash| column_result = {} column_hash.each do |key,value| if column_def_keys.include?(key.to_s) column_result[key.to_s] = value end end # rewrite any link_to values as fnRender functions if column_result.include?('link_to') column_result['fnRender'] = %Q|function(oObj) { return replace('#{column_result['link_to']}', oObj.aData);}| column_result.delete('link_to') end if column_result.empty? result << nil else result << column_result end end result end
ruby
{ "resource": "" }
q24865
Gattica.Auth.parse_tokens
train
def parse_tokens(data) tokens = {} data.split("\n").each do |t| tokens.merge!({ t.split('=').first.downcase.to_sym => t.split('=').last }) end return tokens end
ruby
{ "resource": "" }
q24866
AllscriptsApi.NamedMagicMethods.get_provider
train
def get_provider(provider_id = nil, user_name = nil) params = MagicParams.format( parameter1: provider_id, parameter2: user_name ) results = magic("GetProvider", magic_params: params) results["getproviderinfo"] end
ruby
{ "resource": "" }
q24867
AllscriptsApi.NamedMagicMethods.get_providers
train
def get_providers(security_filter = nil, name_filter = nil, show_only_providers_flag = "Y", internal_external = "I", ordering_authority = nil, real_provider = "N") params = MagicParams.format( parameter1: security_filter, parameter2: name_filter, parameter3: show_only_providers_flag, parameter4: internal_external, parameter5: ordering_authority, parameter6: real_provider ) results = magic("GetProviders", magic_params: params) results["getprovidersinfo"] end
ruby
{ "resource": "" }
q24868
AllscriptsApi.NamedMagicMethods.get_patient_problems
train
def get_patient_problems(patient_id, show_by_encounter = "N", assessed = nil, encounter_id = nil, filter_on_id = nil, display_in_progress = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: show_by_encounter, parameter2: assessed, parameter3: encounter_id, parameter4: filter_on_id, parameter5: display_in_progress ) results = magic("GetPatientProblems", magic_params: params) results["getpatientproblemsinfo"] end
ruby
{ "resource": "" }
q24869
AllscriptsApi.NamedMagicMethods.get_results
train
def get_results(patient_id, since = nil) params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: since ) results = magic("GetResults", magic_params: params) results["getresultsinfo"] end
ruby
{ "resource": "" }
q24870
AllscriptsApi.NamedMagicMethods.get_schedule
train
def get_schedule(start_date, end_date, other_username = nil) params = MagicParams.format( user_id: @allscripts_username, parameter1: format_date_range(start_date, end_date), parameter4: other_username ) results = magic("GetSchedule", magic_params: params) results["getscheduleinfo"] end
ruby
{ "resource": "" }
q24871
AllscriptsApi.NamedMagicMethods.get_encounter_list
train
def get_encounter_list(patient_id = "", encounter_type = "", when_or_limit = "", nostradamus = 0, show_past_flag = "Y", billing_provider_user_name = "") params = MagicParams.format( user_id: @allscripts_username, patient_id: patient_id, parameter1: encounter_type, # from Encounter_Type_DE parameter2: when_or_limit, parameter3: nostradamus, parameter4: show_past_flag, parameter5: billing_provider_user_name, ) results = magic("GetEncounterList", magic_params: params) results["getencounterlistinfo"] end
ruby
{ "resource": "" }
q24872
AllscriptsApi.NamedMagicMethods.get_list_of_dictionaries
train
def get_list_of_dictionaries params = MagicParams.format(user_id: @allscripts_username) results = magic("GetListOfDictionaries", magic_params: params) results["getlistofdictionariesinfo"] end
ruby
{ "resource": "" }
q24873
AllscriptsApi.NamedMagicMethods.get_dictionary
train
def get_dictionary(dictionary_name) params = MagicParams.format( user_id: @allscripts_username, parameter1: dictionary_name ) results = magic("GetDictionary", magic_params: params) results["getdictionaryinfo"] end
ruby
{ "resource": "" }
q24874
AllscriptsApi.NamedMagicMethods.get_server_info
train
def get_server_info params = MagicParams.format(user_id: @allscripts_username) results = magic("GetServerInfo", magic_params: params) results["getserverinfoinfo"][0] # infoinfo is an Allscript typo end
ruby
{ "resource": "" }
q24875
Borutus.Account.balance
train
def balance(options={}) if self.class == Borutus::Account raise(NoMethodError, "undefined method 'balance'") else if self.normal_credit_balance ^ contra credits_balance(options) - debits_balance(options) else debits_balance(options) - credits_balance(options) end end end
ruby
{ "resource": "" }
q24876
Humperdink.Tracker.shutdown
train
def shutdown(exception) begin notify_event(:shutdown, { :exception_message => exception.message }) rescue => e $stderr.puts([e.message, e.backtrace].join("\n")) rescue nil end @config = default_config @config[:enabled] = false end
ruby
{ "resource": "" }
q24877
Microdata.Item.add_itemprop
train
def add_itemprop(itemprop) properties = Itemprop.parse(itemprop, @page_url) properties.each { |name, value| (@properties[name] ||= []) << value } end
ruby
{ "resource": "" }
q24878
Microdata.Item.add_itemref_properties
train
def add_itemref_properties(element) itemref = element.attribute('itemref') if itemref itemref.value.split(' ').each {|id| parse_elements(find_with_id(id))} end end
ruby
{ "resource": "" }
q24879
RuboCopMethodOrder.MethodNodeCollection.replacements
train
def replacements nodes.reject { |node| method_order_correct?(node) }.each_with_object({}) do |node, obj| node_to_replace = nodes[expected_method_index(node)] obj[node] = { node => node_to_replace, node_to_replace => nodes[expected_method_index(node_to_replace)] } end end
ruby
{ "resource": "" }
q24880
XsdReader.Shared.class_for
train
def class_for(n) class_mapping = { "#{schema_namespace_prefix}schema" => Schema, "#{schema_namespace_prefix}element" => Element, "#{schema_namespace_prefix}attribute" => Attribute, "#{schema_namespace_prefix}choice" => Choice, "#{schema_namespace_prefix}complexType" => ComplexType, "#{schema_namespace_prefix}sequence" => Sequence, "#{schema_namespace_prefix}simpleContent" => SimpleContent, "#{schema_namespace_prefix}complexContent" => ComplexContent, "#{schema_namespace_prefix}extension" => Extension, "#{schema_namespace_prefix}import" => Import, "#{schema_namespace_prefix}simpleType" => SimpleType } return class_mapping[n.is_a?(Nokogiri::XML::Node) ? n.name : n] end
ruby
{ "resource": "" }
q24881
Aequitas.ViolationSet.full_messages
train
def full_messages violations.inject([]) do |list, (attribute_name, violations)| messages = violations messages = violations.full_messages if violations.respond_to?(:full_messages) list.concat(messages) end end
ruby
{ "resource": "" }
q24882
RubyOnAcid.MetaFactory.get_unit
train
def get_unit(key) @assigned_factories[key] ||= source_factories[rand(source_factories.length)] @assigned_factories[key].get_unit(key) end
ruby
{ "resource": "" }
q24883
RubyOnAcid.ExampleFactory.generate_factories
train
def generate_factories random_factory = RubyOnAcid::RandomFactory.new factories = [] 5.times do factory = RubyOnAcid::LoopFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 3.times do factory = RubyOnAcid::ConstantFactory.new factory.value = random_factory.get(:constant) factories << factory end factories << RubyOnAcid::FlashFactory.new( :interval => random_factory.get(:interval, :max => 100) ) 2.times do factories << RubyOnAcid::LissajousFactory.new( :interval => random_factory.get(:interval, :max => 10.0), :scale => random_factory.get(:scale, :min => 0.1, :max => 2.0) ) end factories << RubyOnAcid::RandomWalkFactory.new( :interval => random_factory.get(:interval, :max => 0.1) ) 4.times do factory = RubyOnAcid::SineFactory.new factory.interval = random_factory.get(:increment, :min => -0.1, :max => 0.1) factories << factory end 2.times do factory = RubyOnAcid::RepeatFactory.new factory.repeat_count = random_factory.get(:interval, :min => 2, :max => 100) factory.source_factories << random_element(factories) factories << factory end 2.times do factories << RubyOnAcid::RoundingFactory.new( :source_factories => [random_element(factories)], :nearest => random_factory.get(:interval, :min => 0.1, :max => 0.5) ) end combination_factory = RubyOnAcid::CombinationFactory.new combination_factory.constrain_mode = random_factory.choose(:constrain_mode, CombinationFactory::CONSTRAIN, CombinationFactory::WRAP, CombinationFactory::REBOUND ) combination_factory.operation = random_factory.choose(:operation, CombinationFactory::ADD, CombinationFactory::SUBTRACT, CombinationFactory::MULTIPLY, CombinationFactory::DIVIDE ) 2.times do combination_factory.source_factories << random_element(factories) end factories << combination_factory weighted_factory = RubyOnAcid::WeightedFactory.new 2.times do source_factory = random_element(factories) weighted_factory.source_factories << source_factory weighted_factory.weights[source_factory] = rand end factories << weighted_factory proximity_factory = RubyOnAcid::ProximityFactory.new 2.times do proximity_factory.source_factories << random_element(factories) end factories << proximity_factory 8.times do attraction_factory = RubyOnAcid::AttractionFactory.new( :attractor_factory => random_element(factories) ) attraction_factory.source_factories << random_element(factories) factories << attraction_factory end factories end
ruby
{ "resource": "" }
q24884
Aequitas.Macros.validates_acceptance_of
train
def validates_acceptance_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Acceptance, attribute_names, options) end
ruby
{ "resource": "" }
q24885
Aequitas.Macros.validates_confirmation_of
train
def validates_confirmation_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Confirmation, attribute_names, options) end
ruby
{ "resource": "" }
q24886
Aequitas.Macros.validates_numericalness_of
train
def validates_numericalness_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Value, attribute_names, options) validation_rules.add(Rule::Numericalness, attribute_names, options) end
ruby
{ "resource": "" }
q24887
Aequitas.Macros.validates_presence_of
train
def validates_presence_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::Presence::NotBlank, attribute_names, options) end
ruby
{ "resource": "" }
q24888
Aequitas.Macros.validates_primitive_type_of
train
def validates_primitive_type_of(*attribute_names) options = Macros.extract_options(attribute_names) validation_rules.add(Rule::PrimitiveType, attribute_names, options) end
ruby
{ "resource": "" }
q24889
Diane.Player.all_recordings
train
def all_recordings opts = { headers: true, header_converters: :symbol, encoding: 'utf-8' } CSV.read(DIFILE, opts).map(&:to_hash) end
ruby
{ "resource": "" }
q24890
Diane.Player.play
train
def play abort %(None from #{@user}. Fuck off.).magenta if @recordings.empty? stdout = preface @recordings.each do |r| stdout += "\n#{r[:time]} : ".cyan + "@#{r[:user]}".yellow stdout += "\n#{r[:message]}\n\n" end puts stdout stdout end
ruby
{ "resource": "" }
q24891
Schematron.Schema.rule_hits
train
def rule_hits(results_doc, instance_doc, rule_type, xpath) results = [] results_doc.root.find(xpath, NS_PREFIXES).each do |hit| context = instance_doc.root.find_first hit['location'] hit.find('svrl:text/text()', NS_PREFIXES).each do |message| results << { :rule_type => rule_type, :type => context.node_type_name, :name => context.name, :line => context.line_num, :message => message.content.strip } end end results end
ruby
{ "resource": "" }
q24892
Rlimiter.RedisClient.limit
train
def limit(key, count, duration) @key = key.to_s @duration = duration.to_i # :incr_count increases the hit count and simultaneously checks for breach if incr_count > count # :elapsed is the time window start Redis cache # If the time elapsed is less than window duration, the limit has been breached for the current window (return false). return false if @duration - elapsed > 0 # Else reset the hit count to zero and window start time. reset end true end
ruby
{ "resource": "" }
q24893
Rlimiter.RedisClient.next_in
train
def next_in(key, count, duration) @key = key @duration = duration return 0 if current_count(key) < count [@duration - elapsed, 0].max end
ruby
{ "resource": "" }
q24894
RubyOnAcid.RindaFactory.get_unit
train
def get_unit(key) @prior_values[key] ||= 0.0 begin key, value = @space.take([key, Float], @timeout) @prior_values[key] = value rescue Rinda::RequestExpiredError => exception if source_factories.empty? value = @prior_values[key] else value = super end end value end
ruby
{ "resource": "" }
q24895
ContentfulRedis.ModelBase.matching_attributes?
train
def matching_attributes?(attribute, filter) attribute.to_s.downcase == filter.to_s.delete('_').downcase end
ruby
{ "resource": "" }
q24896
Cloudster.ChefClient.add_to
train
def add_to(ec2) ec2_template = ec2.template @instance_name = ec2.name chef_client_template = template ec2.template.inner_merge(chef_client_template) end
ruby
{ "resource": "" }
q24897
Aequitas.RuleSet.validate
train
def validate(resource) rules = rules_for_resource(resource) rules.map { |rule| rule.validate(resource) }.compact # TODO: # violations = rules.map { |rule| rule.validate(resource) }.compact # ViolationSet.new(resource).concat(violations) end
ruby
{ "resource": "" }
q24898
Cloudster.Cloud.template
train
def template(options = {}) require_options(options, [:resources]) resources = options[:resources] description = options[:description] || 'This stack is created by Cloudster' resource_template = {} output_template = {} resources.each do |resource| resource_template.merge!(resource.template['Resources']) output_template.merge!(resource.template['Outputs']) unless resource.template['Outputs'].nil? end cloud_template = {'AWSTemplateFormatVersion' => '2010-09-09', 'Description' => description } cloud_template['Resources'] = resource_template if !resource_template.empty? cloud_template['Outputs'] = output_template if !output_template.empty? return cloud_template.delete_nil.to_json end
ruby
{ "resource": "" }
q24899
Cloudster.Cloud.get_rds_details
train
def get_rds_details(options = {}) stack_resources = resources(options) rds_resource_ids = get_resource_ids(stack_resources, "AWS::RDS::DBInstance") rds = Fog::AWS::RDS.new(:aws_access_key_id => @access_key_id, :aws_secret_access_key => @secret_access_key, :region => @region) rds_details = {} rds_resource_ids.each do |key, value| rds_instance_details = rds.describe_db_instances(value) rds_details[key] = rds_instance_details.body["DescribeDBInstancesResult"]["DBInstances"][0] rescue nil end return rds_details end
ruby
{ "resource": "" }