_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q9500
LolitaPaypal.TransactionsController.set_active_payment
train
def set_active_payment @payment ||= session[:payment_data][:billing_class].constantize.find(session[:payment_data][:billing_id]) rescue render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end
ruby
{ "resource": "" }
q9501
DwCAContentAnalyzer.FileContents.headers
train
def headers(file) Array.new(CSV.open(file, &:readline).size) { |i| i.to_s } end
ruby
{ "resource": "" }
q9502
Machined.Sprocket.use_all_templates
train
def use_all_templates Utils.available_templates.each do |ext, template| next if engines(ext) register_engine ext, template end end
ruby
{ "resource": "" }
q9503
Fetch.Callbacks.run_callbacks_for
train
def run_callbacks_for(name, args, reverse) callbacks_for(name, reverse).map do |block| run_callback(block, args) end end
ruby
{ "resource": "" }
q9504
Announcer.Subscription._determine_path
train
def _determine_path path = File.expand_path('../..', __FILE__) # Will be something like: # "/path/to/file.rb:47:in `method_name'" non_announcer_caller = caller.find { |c| !c.start_with?(path) } unless non_announcer_caller # This is not expected to occur. raise Errors::SubscriptionError, "Could not find non-Announcer caller" end non_announcer_caller end
ruby
{ "resource": "" }
q9505
Announcer.Subscription._generate_identifier
train
def _generate_identifier # Cut off everything from the line number onward. That way, the identifier # does not change when the subscription block moves to a different line. index = _path.rindex(/:\d+:/) - 1 path = _path[0..index] raise Errors::SubscriptionError, "Invalid path: #{path}" unless File.exists?(path) Digest::MD5.hexdigest("#{path}:#{event_name}:#{name}").to_sym end
ruby
{ "resource": "" }
q9506
Announcer.Subscription._evaluate_priority_int
train
def _evaluate_priority_int(int) raise Errors::InvalidPriorityError, int unless int > 0 && int <= config.max_priority int end
ruby
{ "resource": "" }
q9507
Announcer.Subscription._evaluate_priority_symbol
train
def _evaluate_priority_symbol(sym) if (priority = _symbol_to_priority(sym)) _evaluate_priority(priority) else raise Errors::InvalidPriorityError, sym.inspect end end
ruby
{ "resource": "" }
q9508
Announcer.Subscription._evaluate_priority_nil
train
def _evaluate_priority_nil # Need to specify value explicitly here, otherwise in the call to # _evaluate_priority, the case statement won't recognize it as a Symbol. # That's because when calls Symbol::=== to evaluate a match. priority = config.default_priority if priority _evaluate_priority(priority) else raise Errors::InvalidPriorityError, priority.inspect end end
ruby
{ "resource": "" }
q9509
LolitaPaypal.ApplicationHelper.encrypt_request
train
def encrypt_request(payment_request) variables = payment_request.request_variables.reverse_merge({ 'notify_url'=> answer_paypal_url(protocol: 'https') }) LolitaPaypal::Request.encrypt_for_paypal variables ensure LolitaPaypal.logger.info "[#{payment_request.payment_id}] #{variables}" end
ruby
{ "resource": "" }
q9510
Musako.Configuration.read_config_file
train
def read_config_file c = clone config = YAML.load_file(File.join(DEFAULTS[:source], "config.yml")) unless config.is_a? Hash raise ArgumentError.new("Configuration file: invalid #{file}") end c.merge(config) rescue SystemCallError raise LoadError, "Configuration file: not found #{file}" end
ruby
{ "resource": "" }
q9511
Ichiban.Helpers.path_with_slashes
train
def path_with_slashes(path) path = '/' + path unless path.start_with?('/') path << '/' unless path.end_with?('/') path end
ruby
{ "resource": "" }
q9512
Checkdin.Votes.votes
train
def votes(options={}) response = connection.get do |req| req.url "votes", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q9513
FentonShell.Client.create
train
def create(global_options, options) status, body = client_create(global_options, options) if status == 201 save_message('Client': ['created!']) true else save_message(body) false end end
ruby
{ "resource": "" }
q9514
FentonShell.Client.create_with_organization
train
def create_with_organization(global_options, options) create(global_options, options) if Organization.new.create(global_options, name: options[:username], key: options[:username]) save_message('Organization': ['created!']) true else save_message('Organization': ['not created!']) false end end
ruby
{ "resource": "" }
q9515
FentonShell.Client.client_json
train
def client_json(options) { client: { username: options[:username], name: options[:name], email: options[:email], public_key: File.read(options[:public_key]) } }.to_json end
ruby
{ "resource": "" }
q9516
Scat.Authorization.perform!
train
def perform!(email, password, &block) login_required CaTissue::Database.current.open(email, password, &block) end
ruby
{ "resource": "" }
q9517
Attention.Publisher.publish
train
def publish(channel, value) redis = Attention.redis.call yield redis if block_given? redis.publish channel, payload_for(value) end
ruby
{ "resource": "" }
q9518
Attention.Publisher.payload_for
train
def payload_for(value) case value when Array, Hash JSON.dump value else value end rescue value end
ruby
{ "resource": "" }
q9519
AzureJwtAuth.JwtManager.custom_valid?
train
def custom_valid? @provider.validations.each do |key, value| return false unless payload[key] == value end true end
ruby
{ "resource": "" }
q9520
AzureJwtAuth.JwtManager.rsa_decode
train
def rsa_decode kid = header['kid'] try = false begin rsa = @provider.keys[kid] raise KidNotFound, 'kid not found into provider keys' unless rsa JWT.decode(@jwt, rsa.public_key, true, algorithm: 'RS256') rescue JWT::VerificationError, KidNotFound raise if try @provider.load_keys # maybe keys have been changed try = true retry end end
ruby
{ "resource": "" }
q9521
Vigilem::Core.Hooks.run_hook
train
def run_hook(hook_name, *args, &block) hooks.find {|hook| hook.name == hook_name }.run(self, *args, &block) end
ruby
{ "resource": "" }
q9522
StixSchemaSpy.ComplexType.vocab_values
train
def vocab_values type = Schema.find(self.schema.prefix, stix_version).find_type(name.gsub("Vocab", "Enum")) if type type.enumeration_values else raise "Unable to find corresponding enumeration for vocabulary" end end
ruby
{ "resource": "" }
q9523
Coach.Entity.fetch
train
def fetch assert_has_uri! response = client.get clean_uri, query: { start: 0, size: 10000 } update_attributes! filter_response_body(JSON.parse(response.body)) self end
ruby
{ "resource": "" }
q9524
Funl.Message.to_msgpack
train
def to_msgpack(pk = nil) case pk when MessagePack::Packer pk.write_array_header(6) pk.write @client_id pk.write @local_tick pk.write @global_tick pk.write @delta pk.write @tags pk.write @blob return pk else # nil or IO MessagePack.pack(self, pk) end end
ruby
{ "resource": "" }
q9525
Retentiongrid.Resource.attributes
train
def attributes self.class::ATTRIBUTES_NAMES.inject({}) do |attribs, attrib_name| value = self.send(attrib_name) attribs[attrib_name] = value unless value.nil? attribs end end
ruby
{ "resource": "" }
q9526
ODBA.Persistable.odba_cut_connection
train
def odba_cut_connection(remove_object) odba_potentials.each { |name| var = instance_variable_get(name) if(var.eql?(remove_object)) instance_variable_set(name, nil) end } end
ruby
{ "resource": "" }
q9527
ODBA.Persistable.odba_take_snapshot
train
def odba_take_snapshot @odba_snapshot_level ||= 0 snapshot_level = @odba_snapshot_level.next current_level = [self] tree_level = 0 while(!current_level.empty?) tree_level += 1 obj_count = 0 next_level = [] current_level.each { |item| if(item.odba_unsaved?(snapshot_level)) obj_count += 1 next_level += item.odba_unsaved_neighbors(snapshot_level) item.odba_snapshot(snapshot_level) end } current_level = next_level #.uniq end end
ruby
{ "resource": "" }
q9528
Scholar.Citation.to_hash
train
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash end
ruby
{ "resource": "" }
q9529
Notifaction.Helpers.deprecation_notice
train
def deprecation_notice(version, config = {}) handler = Notifaction::Type::Terminal.new handler.warning( "Deprecated as of #{version}, current #{Notifaction::VERSION}", config ) handler.quit_soft end
ruby
{ "resource": "" }
q9530
Mysql2Model.Composer.compose_sql
train
def compose_sql(*statement) raise PreparedStatementInvalid, "Statement is blank!" if statement.blank? if statement.is_a?(Array) if statement.size == 1 #strip the outer array compose_sql_array(statement.first) else compose_sql_array(statement) end else statement end end
ruby
{ "resource": "" }
q9531
Mysql2Model.Composer.compose_sql_array
train
def compose_sql_array(ary) statement, *values = ary if values.first.is_a?(Hash) and statement =~ /:\w+/ replace_named_bind_variables(statement, values.first) elsif statement.include?('?') replace_bind_variables(statement, values) else statement % values.collect { |value| client.escape(value.to_s) } end end
ruby
{ "resource": "" }
q9532
LatoBlog.Tag::SerializerHelpers.serialize
train
def serialize serialized = {} # set basic info serialized[:id] = id serialized[:title] = title serialized[:meta_language] = meta_language serialized[:meta_permalink] = meta_permalink # add tag parent informations serialized[:other_informations] = serialize_other_informations # return serialized post serialized end
ruby
{ "resource": "" }
q9533
Ichiban.Deleter.delete_dest
train
def delete_dest(path) file = Ichiban::ProjectFile.from_abs(path) # file will be nil if the path doesn't map to a known subclass of IchibanFile. Furthermore, # even if file is not nil, it may be a kind of IchibanFile that does not have a destination. if file and file.has_dest? dest = file.dest else dest = nil end if dest and File.exist?(dest) FileUtils.rm(dest) end # Log the deletion(s) Ichiban.logger.deletion(path, dest) end
ruby
{ "resource": "" }
q9534
Couchbase.Model.delete
train
def delete(options = {}) raise Couchbase::Error::MissingId, 'missing id attribute' unless @id model.bucket.delete(@id, options) @id = nil @meta = nil self end
ruby
{ "resource": "" }
q9535
Couchbase.Model.reload
train
def reload raise Couchbase::Error::MissingId, 'missing id attribute' unless @id pristine = model.find(@id) update_attributes(pristine.attributes) @meta[:cas] = pristine.meta[:cas] self end
ruby
{ "resource": "" }
q9536
Orchestrate::API.Request.perform
train
def perform uri = URI(url) response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https' ) { |http| Orchestrate.config.logger.debug "Performing #{method.to_s.upcase} request to \"#{url}\"" http.request(request(uri)) } Response.new(response) end
ruby
{ "resource": "" }
q9537
Octo.Trendable.aggregate_sum
train
def aggregate_sum(aggr) sum = {} aggr.each do |ts, counterVals| sum[ts] = {} unless sum.has_key?ts counterVals.each do |obj, count| if obj.respond_to?(:enterprise_id) eid = obj.public_send(:enterprise_id).to_s sum[ts][eid] = sum[ts].fetch(eid, 0) + count end end end sum end
ruby
{ "resource": "" }
q9538
Sortifiable.InstanceMethods.add_to_list
train
def add_to_list if in_list? move_to_bottom else list_class.transaction do ids = lock_list! last_position = ids.size if persisted? update_position last_position + 1 else set_position last_position + 1 end end end end
ruby
{ "resource": "" }
q9539
LatoBlog.FieldsHelper.render_post_fields
train
def render_post_fields(post) post_fields = post.post_fields.visibles.roots.order('position ASC') render 'lato_blog/back/posts/shared/fields', post_fields: post_fields end
ruby
{ "resource": "" }
q9540
LatoBlog.FieldsHelper.render_post_field
train
def render_post_field(post_field, key_parent = 'fields') # define key key = "#{key_parent}[#{post_field.id}]" # render correct field case post_field.typology when 'text' render_post_field_text(post_field, key) when 'textarea' render_post_field_textarea(post_field, key) when 'datetime' render_post_field_datetime(post_field, key) when 'editor' render_post_field_editor(post_field, key) when 'geolocalization' render_post_field_geolocalization(post_field, key) when 'image' render_post_field_image(post_field, key) when 'gallery' render_post_field_gallery(post_field, key) when 'youtube' render_post_field_youtube(post_field, key) when 'composed' render_post_field_composed(post_field, key) when 'relay' render_post_field_relay(post_field, key) end end
ruby
{ "resource": "" }
q9541
Stylesheet.FakeRequest.get
train
def get(url) begin uri = URI.parse(url.strip) rescue URI::InvalidURIError uri = URI.parse(URI.escape(url.strip)) end # simple hack to read in fixtures instead of url for tests fixture = "#{File.dirname(__FILE__)}/../fixtures#{uri.path}" File.read(fixture) if File.exist?(fixture) end
ruby
{ "resource": "" }
q9542
ICU.Player.renumber
train
def renumber(map) raise "player number #{@num} not found in renumbering hash" unless map[@num] self.num = map[@num] @results.each{ |r| r.renumber(map) } self end
ruby
{ "resource": "" }
q9543
ICU.Player.merge
train
def merge(other) raise "cannot merge two players that are not equal" unless self == other [:id, :fide_id, :rating, :fide_rating, :title, :fed, :gender].each do |m| self.send("#{m}=", other.send(m)) unless self.send(m) end end
ruby
{ "resource": "" }
q9544
Kawaii.ServerMethods.start!
train
def start!(port) # @todo Support other handlers http://www.rubydoc.info/github/rack/rack/Rack/Handler Rack::Handler.get(WEBRICK).run(self, Port: port) do |s| @server = s at_exit { stop! } [:INT, :TERM].each do |signal| old = trap(signal) do stop! old.call if old.respond_to?(:call) end end end end
ruby
{ "resource": "" }
q9545
RsMule.RunExecutable.run_executable
train
def run_executable(tags, executable, options={}) options = { :executable_type => "auto", :right_script_revision => "latest", :tag_match_strategy => "all", :inputs => {}, :update_inputs => [] }.merge(options) execute_params = {} tags = [tags] unless tags.is_a?(Array) options[:update_inputs] = [options[:update_inputs]] unless options[:update_inputs].is_a?(Array) case options[:executable_type] when "right_script_href" execute_params[:right_script_href] = executable when "right_script_name" scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href when "recipe_name" execute_params[:recipe_name] = executable when "auto" is_recipe = executable =~ /.*::.*/ is_href = executable =~ /^\/api\/right_scripts\/[a-zA-Z0-9]*/ if is_recipe execute_params[:recipe_name] = executable else if is_href execute_params[:right_script_href] = executable else scripts = find_right_script_lineage_by_name(executable) execute_params[:right_script_href] = right_script_revision_from_lineage(scripts, options[:right_script_revision]).href end end else raise ArgumentError.new("Unknown executable_type (#{options[:executable_type]})") end if options[:inputs].length > 0 execute_params[:inputs] = options[:inputs] end resources_by_tag = @right_api_client.tags.by_tag( :resource_type => "instances", :tags => tags, :match_all => options[:tag_match_strategy] == "all" ? "true" : "false" ) resources_by_tag.each do |res| instance = @right_api_client.resource(res.links.first["href"]) instance.run_executable(execute_params) options[:update_inputs].each do |update_type| update_inputs(instance, options[:inputs], update_type) end end end
ruby
{ "resource": "" }
q9546
RsMule.RunExecutable.right_script_revision_from_lineage
train
def right_script_revision_from_lineage(lineage, revision="latest") right_script = nil if revision == "latest" latest_script = lineage.max_by{|rs| rs.revision} right_script = latest_script else desired_script = lineage.select{|rs| rs.revision == revision} if desired_script.length == 0 raise Exception::RightScriptNotFound.new("RightScript revision (#{revision}) was not found. Available revisions are (#{lineage.map{|rs| rs.revision}})") end right_script = desired_script.first end right_script end
ruby
{ "resource": "" }
q9547
StorageRoom.Array.each_page_each_resource
train
def each_page_each_resource(args={}) self.each_page(args) do |page| page.resources.each do |item| yield(item) end end end
ruby
{ "resource": "" }
q9548
Diffbot.Article.extract_article
train
def extract_article api_response = request.get article_endpoint, token: Diffbot.token, url: @url @response = JSON.parse(api_response.body) end
ruby
{ "resource": "" }
q9549
Vigilem.Assembly.find_stat
train
def find_stat(opts={}, &block) stats = Core::Stat.all_available # @fixme just grabs first stat = if stats.size > 1 [*opts[:platform_defaults]].map do |os_pattern, gem_name| if System.check[:os][os_pattern] stats.select {|stat| stat.gem_name == gem_name } if stats.size > 1 raise ArgumentError, "multiple handlers match :platform_defaults"\ "#{os_pattern} => #{gem_name} matches #{stats}" else stats.first end end end.flatten.compact.first else stats.first end end
ruby
{ "resource": "" }
q9550
ChoresKit.Chore.task
train
def task(options, &block) name, params = *options raise "Couldn't create task without a name" if name.nil? raise "Couldn't create task without a block" unless block_given? task = Task.new(name, params) task.instance_eval(&block) @dag.add_vertex(name: name, task: task) end
ruby
{ "resource": "" }
q9551
JiraIssues.JiraQuery.jql_query
train
def jql_query(query) result = adapter.jql(query, fields:[:description, :summary, :created, :status, :issuetype, :priority, :resolutiondate], max_results: @query_max_results) JiraIssuesNavigator.new(result.map{|i| JiraIssueMapper.new.call(i) }) end
ruby
{ "resource": "" }
q9552
Mongolicious.Filesystem.compress
train
def compress(path, compress_tar_file) Mongolicious.logger.info("Compressing database #{path}") system("cd #{path} && tar -cpf#{compress_tar_file ? 'j' : ''} #{path}.tar.bz2 .") raise "Error while compressing #{path}" if $?.to_i != 0 # Remove mongo dump now that we have the bzip FileUtils.rm_rf(path) return "#{path}.tar.bz2" end
ruby
{ "resource": "" }
q9553
Mongolicious.Filesystem.cleanup_tar_file
train
def cleanup_tar_file(path) Mongolicious.logger.info("Cleaning up local path #{path}") begin File.delete(path) rescue => exception Mongolicious.logger.error("Error trying to delete: #{path}") Mongolicious.logger.info(exception.message) end end
ruby
{ "resource": "" }
q9554
Mongolicious.Filesystem.cleanup_parts
train
def cleanup_parts(file_parts) Mongolicious.logger.info("Cleaning up file parts.") if file_parts file_parts.each do |part| Mongolicious.logger.info("Deleting part: #{part}") begin File.delete(part) rescue => exception Mongolicious.logger.error("Error trying to delete part: #{part}") Mongolicious.logger.error(exception.message) Mongolicious.logger.error(exception.backtrace) end end end end
ruby
{ "resource": "" }
q9555
DealRedemptions.RedeemController.validate_code
train
def validate_code redeem_code = DealRedemptions::RedeemCode.find_by_code(params[:code]) if redeem_code @redeem = redeem_code.validate_code(params) else @redeem = false end end
ruby
{ "resource": "" }
q9556
FlexibleApi.ClassMethods.define_request_level
train
def define_request_level(name, &block) level = RequestLevel.new(name, self) level.instance_eval &block @levels ||= {} @levels[name] = level end
ruby
{ "resource": "" }
q9557
FlexibleApi.ClassMethods.find_hash
train
def find_hash(id, options = {}) options.assert_valid_keys(:request_level) level = find_level(options[:request_level]) record = self.find(id, :select => level.select_field.join(', '), :include => level.include_field) level.receive record end
ruby
{ "resource": "" }
q9558
FlexibleApi.ClassMethods.find_level
train
def find_level(name = nil) @levels ||= {} level = name.nil? ? load_default_request_level : @levels[name.to_sym] level = superclass.find_level(name) and @levels[name.to_sym] = level if level.nil? && superclass.present? raise NoSuchRequestLevelError.new(name, self.name) if level.nil? level end
ruby
{ "resource": "" }
q9559
ActionDispatch::Routing.Mapper.use_reaction
train
def use_reaction(opts = {}) raise RuntimeError, 'Already using Reaction.' if Reaction.client opts = use_reaction_defaults opts EM.next_tick { faye = Faye::Client.new(opts[:at] + '/bayeux') signer = Reaction::Client::Signer.new opts[:key] faye.add_extension signer Reaction.client = Reaction::Client.new faye, opts[:key] } end
ruby
{ "resource": "" }
q9560
CloudCrooner.Storage.upload_files
train
def upload_files files_to_upload = local_compiled_assets.reject { |f| exists_on_remote?(f) } files_to_upload.each do |asset| upload_file(asset) end end
ruby
{ "resource": "" }
q9561
CloudCrooner.Storage.upload_file
train
def upload_file(f) # grabs the compiled asset from public_path full_file_path = File.join(File.dirname(@manifest.dir), f) one_year = 31557600 mime = Rack::Mime.mime_type(File.extname(f)) file = { :key => f, :public => true, :content_type => mime, :cache_control => "public, max-age=#{one_year}", :expires => CGI.rfc1123_date(Time.now + one_year) } gzipped = "#{full_file_path}.gz" if File.exists?(gzipped) original_size = File.size(full_file_path) gzipped_size = File.size(gzipped) if gzipped_size < original_size file.merge!({ :body => File.open(gzipped), :content_encoding => 'gzip' }) log "Uploading #{gzipped} in place of #{f}" else file.merge!({ :body => File.open(full_file_path) }) log "Gzip exists but has larger file size, uploading #{f}" end else file.merge!({ :body => File.open(full_file_path) }) log "Uploading #{f}" end # put in reduced redundancy option here later if desired file = bucket.files.create( file ) end
ruby
{ "resource": "" }
q9562
Undies.API.__yield
train
def __yield return if (source = @_undies_source_stack.pop).nil? if source.file? instance_eval(source.data, source.source, 1) else instance_eval(&source.data) end end
ruby
{ "resource": "" }
q9563
Rink.Console.apply_options
train
def apply_options(options) return unless options options.each do |key, value| options[key] = value.call if value.kind_of?(Proc) end @_options ||= {} @_options.merge! options @input = setup_input_method(options[:input] || @input) @output = setup_output_method(options[:output] || @output) @output.silenced = options.key?(:silent) ? options[:silent] : !@output || @output.silenced? @line_processor = options[:processor] || options[:line_processor] || @line_processor @allow_ruby = options.key?(:allow_ruby) ? options[:allow_ruby] : @allow_ruby if options[:namespace] ns = options[:namespace] == :self ? self : options[:namespace] @namespace.replace(ns) end if @input @input.output = @output @input.prompt = prompt if @input.respond_to?(:completion_proc) @input.completion_proc = proc { |line| autocomplete(line) } end end end
ruby
{ "resource": "" }
q9564
Rink.Console.autocomplete
train
def autocomplete(line) return [] unless @line_processor result = @line_processor.autocomplete(line, namespace) case result when String [result] when nil [] when Array result else result.to_a end end
ruby
{ "resource": "" }
q9565
Maestro.MaestroWorker.perform
train
def perform(action, workitem) @action, @workitem = action, workitem send(action) write_output('') # Triggers any remaining buffered output to be sent run_callbacks rescue MaestroDev::Plugin::PluginError => e write_output('') # Triggers any remaining buffered output to be sent set_error(e.message) rescue Exception => e write_output('') # Triggers any remaining buffered output to be sent lowerstack = e.backtrace.find_index(caller[0]) stack = lowerstack ? e.backtrace[0..lowerstack - 1] : e.backtrace msg = "Unexpected error executing task: #{e.class} #{e} at\n" + stack.join("\n") Maestro.log.warn("#{msg}\nFull stack:\n" + e.backtrace.join("\n")) # Let user-supplied exception handler do its thing handle_exception(e) set_error(msg) ensure # Older agents expected this method to *maybe* return something # .. something that no longer exists, but if we return anything # it will be *wrong* :P return nil end
ruby
{ "resource": "" }
q9566
Maestro.MaestroWorker.handle_exception
train
def handle_exception(e) if self.class.exception_handler_method send(self.class.exception_handler_method, e) elsif self.class.exception_handler_block self.class.exception_handler_block.call(e, self) end end
ruby
{ "resource": "" }
q9567
Maestro.MaestroWorker.save_output_value
train
def save_output_value(name, value) set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil? get_field(CONTEXT_OUTPUTS_META)[name] = value end
ruby
{ "resource": "" }
q9568
Maestro.MaestroWorker.read_output_value
train
def read_output_value(name) if get_field(PREVIOUS_CONTEXT_OUTPUTS_META).nil? set_field(CONTEXT_OUTPUTS_META, {}) if get_field(CONTEXT_OUTPUTS_META).nil? get_field(CONTEXT_OUTPUTS_META)[name] else get_field(PREVIOUS_CONTEXT_OUTPUTS_META)[name] end end
ruby
{ "resource": "" }
q9569
Maestro.MaestroWorker.set_waiting
train
def set_waiting(should_wait) workitem[WAITING_META] = should_wait send_workitem_message rescue Exception => e Maestro.log.warn "Failed To Send Waiting Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}" ensure workitem.delete(WAITING_META) unless should_wait end
ruby
{ "resource": "" }
q9570
Maestro.MaestroWorker.cancel
train
def cancel workitem[CANCEL_META] = true send_workitem_message rescue Exception => e Maestro.log.warn "Failed To Send Cancel Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}" ensure workitem.delete(CANCEL_META) end
ruby
{ "resource": "" }
q9571
Maestro.MaestroWorker.not_needed
train
def not_needed workitem[NOT_NEEDED] = true send_workitem_message rescue Exception => e Maestro.log.warn "Failed To Send Not Needed Message To Server #{e.class} #{e}: #{e.backtrace.join("\n")}" ensure workitem.delete(NOT_NEEDED) end
ruby
{ "resource": "" }
q9572
Maestro.MaestroWorker.update_fields_in_record
train
def update_fields_in_record(model, name_or_id, record_field, record_value) workitem[PERSIST_META] = true workitem[UPDATE_META] = true workitem[MODEL_META] = model workitem[RECORD_ID_META] = name_or_id.to_s workitem[RECORD_FIELD_META] = record_field workitem[RECORD_VALUE_META] = record_value send_workitem_message workitem.delete(PERSIST_META) workitem.delete(UPDATE_META) end
ruby
{ "resource": "" }
q9573
Maestro.MaestroWorker.get_field
train
def get_field(field, default = nil) value = fields[field] value = default if !default.nil? && (value.nil? || (value.respond_to?(:empty?) && value.empty?)) value end
ruby
{ "resource": "" }
q9574
Maestro.MaestroWorker.add_link
train
def add_link(name, url) set_field(LINKS_META, []) if fields[LINKS_META].nil? fields[LINKS_META] << {'name' => name, 'url' => url} end
ruby
{ "resource": "" }
q9575
Maestro.MaestroWorker.as_int
train
def as_int(value, default = 0) res = default if value if value.is_a?(Fixnum) res = value elsif value.respond_to?(:to_i) res = value.to_i end end res end
ruby
{ "resource": "" }
q9576
Maestro.MaestroWorker.as_boolean
train
def as_boolean(value) res = false if value if value.is_a?(TrueClass) || value.is_a?(FalseClass) res = value elsif value.is_a?(Fixnum) res = value != 0 elsif value.respond_to?(:to_s) value = value.to_s.downcase res = (value == 't' || value == 'true') end end res end
ruby
{ "resource": "" }
q9577
SortRank.Solver.parse
train
def parse(args={}) string_block = args.fetch(:text, nil) string_block = sample_string_block if !string_block.present? result_hash = {results: count_strings(string_block), text: string_block } end
ruby
{ "resource": "" }
q9578
DSLKit.ThreadLocal.instance_thread_local
train
def instance_thread_local(name, value = nil) sc = class << self extend DSLKit::ThreadLocal self end sc.thread_local name, value self end
ruby
{ "resource": "" }
q9579
DSLKit.ThreadGlobal.instance_thread_global
train
def instance_thread_global(name, value = nil) sc = class << self extend DSLKit::ThreadGlobal self end sc.thread_global name, value self end
ruby
{ "resource": "" }
q9580
DSLKit.Deflect.deflect_start
train
def deflect_start(from, id, deflector) @@sync.synchronize do Deflect.deflecting ||= DeflectorCollection.new Deflect.deflecting.member?(from, id) and raise DeflectError, "#{from}##{id} is already deflected" Deflect.deflecting.add(from, id, deflector) from.class_eval do define_method(id) do |*args| if Deflect.deflecting and d = Deflect.deflecting.find(self.class, id) d.call(self, id, *args) else super(*args) end end end end end
ruby
{ "resource": "" }
q9581
DSLKit.Deflect.deflect
train
def deflect(from, id, deflector) @@sync.synchronize do begin deflect_start(from, id, deflector) yield ensure deflect_stop(from, id) end end end
ruby
{ "resource": "" }
q9582
DSLKit.Deflect.deflect_stop
train
def deflect_stop(from, id) @@sync.synchronize do Deflect.deflecting.delete(from, id) or raise DeflectError, "#{from}##{id} is not deflected from" from.instance_eval { remove_method id } end end
ruby
{ "resource": "" }
q9583
DSLKit.MethodMissingDelegator.method_missing
train
def method_missing(id, *a, &b) unless method_missing_delegator.nil? method_missing_delegator.__send__(id, *a, &b) else super end end
ruby
{ "resource": "" }
q9584
Redlander.Statement.subject
train
def subject if instance_variable_defined?(:@subject) @subject else rdf_node = Redland.librdf_statement_get_subject(rdf_statement) @subject = rdf_node.null? ? nil : Node.new(rdf_node) end end
ruby
{ "resource": "" }
q9585
Redlander.Statement.predicate
train
def predicate if instance_variable_defined?(:@predicate) @predicate else rdf_node = Redland.librdf_statement_get_predicate(rdf_statement) @predicate = rdf_node.null? ? nil : Node.new(rdf_node) end end
ruby
{ "resource": "" }
q9586
Redlander.Statement.object
train
def object if instance_variable_defined?(:@object) @object else rdf_node = Redland.librdf_statement_get_object(rdf_statement) @object = rdf_node.null? ? nil : Node.new(rdf_node) end end
ruby
{ "resource": "" }
q9587
Redlander.Statement.rdf_node_from
train
def rdf_node_from(source) case source when NilClass nil when Node Redland.librdf_new_node_from_node(source.rdf_node) else Redland.librdf_new_node_from_node(Node.new(source).rdf_node) end end
ruby
{ "resource": "" }
q9588
Datacraft.Runner.run
train
def run(instruction) @inst = instruction measurements = [] # run pre_build hooks if @inst.respond_to? :pre_hooks measurements << Benchmark.measure('pre build:') do @inst.pre_hooks.each(&:call) end end # process the rows measurements << Benchmark.measure('process rows:') do @inst.options[:parallel] ? pprocess_rows : process_rows end # build measurements << Benchmark.measure('build:') do build @inst.consumers end # run post_build hooks if @inst.respond_to? :post_hooks measurements << Benchmark.measure('post build:') do @inst.post_hooks.each(&:call) end end report measurements if @inst.options[:benchmark] end
ruby
{ "resource": "" }
q9589
Datacraft.Runner.report
train
def report(measurements) width = measurements.max_by { |m| m.label.size }.label.size + 1 puts "#{' ' * width}#{Benchmark::CAPTION}" measurements.each do |m| puts "#{m.label.to_s.ljust width} #{m}" end end
ruby
{ "resource": "" }
q9590
Datacraft.Runner.process
train
def process(row) @inst.tweakers.each do |tweaker| row = tweaker.tweak row return nil unless row end @inst.consumers.each do |consumer| consumer << row end end
ruby
{ "resource": "" }
q9591
Datacraft.Runner.pprocess_rows
train
def pprocess_rows thread_number = [@inst.sources.size, @inst.options[:n_threads]].min queue = Queue.new @inst.sources.each { |p| queue << p } threads = thread_number.times.map do Thread.new do begin while p = queue.pop(true) p.each { |row| process row } end rescue ThreadError end end end threads.each(&:join) end
ruby
{ "resource": "" }
q9592
Datacraft.Runner.build
train
def build(consumers) consumers.each do |consumer| consumer.build if consumer.respond_to? :build consumer.close if consumer.respond_to? :close end end
ruby
{ "resource": "" }
q9593
Checkdin.Campaigns.campaigns
train
def campaigns(options={}) response = connection.get do |req| req.url "campaigns", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q9594
Clea.Sender.get_sender_alias
train
def get_sender_alias puts "What is your name?" while @from_alias = gets.chomp catch :badalias do puts "Are you sure your name is #{@from_alias}? [y/n]:" while alias_confirmation = gets.chomp case alias_confirmation when 'y' return else puts "Please re-enter your name:" throw :badalias end end end end end
ruby
{ "resource": "" }
q9595
Clea.Sender.get_sender_gmail
train
def get_sender_gmail puts "Enter your gmail address:" while @from_address = gets.chomp catch :badfrom do if ValidateEmail.validate(@from_address) == true puts "Is your email address #{@from_address}? [y/n]:" while address_confirmation = gets.chomp case address_confirmation when 'y' return else puts "Please re-enter your gmail address:" throw :badfrom end end else puts "Email invalid! Please enter a valid email address:" end end end end
ruby
{ "resource": "" }
q9596
Clea.Sender.get_sender_password
train
def get_sender_password puts "Enter your password:" while @password = gets.chomp catch :badpass do puts "Are you sure your password is #{@password}? [y/n]:" while pass_confirmation = gets.chomp case pass_confirmation when 'y' return else puts "Please re-enter your password:" throw :badpass end end end end end
ruby
{ "resource": "" }
q9597
Clea.Sender.get_recipient_data
train
def get_recipient_data puts "Enter the recipient's email address:" while @to_address = gets.chomp catch :badto do if ValidateEmail.validate(@to_address) == true puts "Is the recipient's email address #{@to_address}? [y/n]:" while to_address_confirmation = gets.chomp case to_address_confirmation when 'y' return else puts "Please re-enter the recipient's email address:" throw :badto end end else puts "Email invalid! Please enter a valid email address:" end end end end
ruby
{ "resource": "" }
q9598
Clea.Sender.send_message
train
def send_message # Read the user's password from the persistent hash stored_password = @sender_info.transaction { @sender_info[:password] } # Initialize the gmail SMTP connection and upgrade to SSL/TLS smtp = Net::SMTP.new('smtp.gmail.com', 587) smtp.enable_starttls # Open SMTP connection, send message, close the connection smtp.start('gmail.com', @stored_from_address, stored_password, :login) do smtp.send_message(@msg, @_stored_from_address, @to_address) end end
ruby
{ "resource": "" }
q9599
Socketlab.SocketlabRequest.set_response
train
def set_response(item_class_name) if @api_response.success? @total_count = @api_response["totalCount"] @total_pages = @api_response["totalPages"] @count = @api_response["count"] @timestamp = @api_response["timestamp"] @items = [] unless @api_response["collection"].nil? @api_response["collection"].each do |attr_item| item = item_class_name.new item.set_item(attr_item) @items << item end end else @error = @api_response.parsed_response end end
ruby
{ "resource": "" }