_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q5600
Saddle.Requester.delete
train
def delete(url, params={}, options={}) response = connection.delete do |req| req.saddle_options = options req.url(url, params) end handle_response(response) end
ruby
{ "resource": "" }
q5601
Saddle.Requester.connection
train
def connection @connection ||= Faraday.new(base_url, :builder_class => Saddle::RackBuilder) do |connection| # Include the requester level options connection.builder.saddle_options[:client_options] = @options # Config options connection.options[:timeout] = @timeout connection.builder.saddle_options[:request_style] = @request_style connection.builder.saddle_options[:num_retries] = @num_retries connection.builder.saddle_options[:client] = @parent_client # Support default return values upon exception connection.use(Saddle::Middleware::Response::DefaultResponse) # Hard timeout on the entire request connection.use(Saddle::Middleware::RubyTimeout) # Set up a user agent connection.use(Saddle::Middleware::Request::UserAgent) # Set up the path prefix if needed connection.use(Saddle::Middleware::Request::PathPrefix) # Apply additional implementation-specific middlewares @additional_middlewares.each do |m| m[:args] ? connection.use(m[:klass], *m[:args]) : connection.use(m[:klass]) end # Request encoding connection.use(Saddle::Middleware::Request::JsonEncoded) connection.use(Saddle::Middleware::Request::UrlEncoded) # Automatic retries connection.use(Saddle::Middleware::Request::Retry) # Raise exceptions on 4xx and 5xx errors connection.use(Saddle::Middleware::Response::RaiseError) # Handle parsing out the response if it's JSON connection.use(Saddle::Middleware::Response::ParseJson) # Set up instrumentation around the adapter for extensibility connection.use(FaradayMiddleware::Instrumentation) # Add in extra env data if needed connection.use(Saddle::Middleware::ExtraEnv) # Set up our adapter if @stubs.nil? # Use the default adapter connection.adapter(@http_adapter[:key], *@http_adapter[:args]) else # Use the test adapter connection.adapter(:test, @stubs) end end end
ruby
{ "resource": "" }
q5602
DEVS.Container.remove_child
train
def remove_child(child) child = child.name if child.is_a?(Model) children.delete(child) end
ruby
{ "resource": "" }
q5603
DEVS.Container.attach
train
def attach(p1, to:, between: nil, and: nil) p2 = to sender = between # use binding#local_variable_get because 'and:' keyword argument clashes # with the language reserved keyword. receiver = binding.local_variable_get(:and) raise ArgumentError.new("'between:' keyword was omitted, 'p1' should be a Port.") if sender.nil? && !p1.is_a?(Port) raise ArgumentError.new("'and:' keyword was omitted, 'to:' should be a Port") if receiver.nil? && !p2.is_a?(Port) a = if p1.is_a?(Port) then p1.host elsif sender.is_a?(Coupleable) then sender elsif sender == @name then self else fetch_child(sender); end b = if p2.is_a?(Port) then p2.host elsif receiver.is_a?(Coupleable) then receiver elsif receiver == @name then self else fetch_child(receiver); end if has_child?(a) && has_child?(b) # IC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.input? raise FeedbackLoopError.new("#{a} must be different than #{b}") if a.object_id == b.object_id _internal_couplings[p1] << p2 elsif a == self && has_child?(b) # EIC p1 = a.input_port(p1) unless p1.is_a?(Port) p2 = b.input_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.input? && p2.input? _input_couplings[p1] << p2 elsif has_child?(a) && b == self # EOC p1 = a.output_port(p1) unless p1.is_a?(Port) p2 = b.output_port(p2) unless p2.is_a?(Port) raise InvalidPortTypeError.new unless p1.output? && p2.output? _output_couplings[p1] << p2 else raise InvalidPortHostError.new("Illegal coupling between #{p1} and #{p2}") end end
ruby
{ "resource": "" }
q5604
AppRepo.Manifest.manifest_as_json
train
def manifest_as_json structure = { appcode: appcode, filename: filename, bundle_identifier: bundle_identifier, bundle_version: bundle_version, title: title, subtitle: subtitle, notify: notify } fputs structure end
ruby
{ "resource": "" }
q5605
Calligraphy.FileResource.copy_options
train
def copy_options(options) copy_options = { can_copy: false, ancestor_exist: false, locked: false } destination = copy_destination options to_path = join_paths @root_dir, destination to_path_exists = File.exist? to_path copy_options[:ancestor_exist] = File.exist? parent_path destination copy_options[:locked] = can_copy_locked_option to_path, to_path_exists copy_options = can_copy_option copy_options, options, to_path_exists copy_options end
ruby
{ "resource": "" }
q5606
StatModule.Process.print
train
def print(formatted = nil) result = name unless version.nil? result += ", version #{version}" end if formatted result = "#{FORMATTING_STAR.colorize(:yellow)} #{result}" end result end
ruby
{ "resource": "" }
q5607
HtmlSlicer.Interface.source
train
def source case options[:processors].present? when true then HtmlSlicer::Process.iterate(@env.send(@method_name), options[:processors]) else @env.send(@method_name) end end
ruby
{ "resource": "" }
q5608
HtmlSlicer.Interface.slice!
train
def slice!(slice = nil) raise(Exception, "Slicing unavailable!") unless sliced? if slice.present? if slice.to_i.in?(1..slice_number) @current_slice = slice.to_i else raise(ArgumentError, "Slice number must be Integer in (1..#{slice_number}). #{slice.inspect} passed.") end end self end
ruby
{ "resource": "" }
q5609
HtmlSlicer.Interface.view
train
def view(node, slice, &block) slice = slice.to_i case node when ::HTML::Tag then children_view = node.children.map {|child| view(child, slice, &block)}.compact.join if resized? resizing.resize_node(node) end if sliced? if slicing.map.get(node, slice) || children_view.present? if node.closing == :close "</#{node.name}>" else s = "<#{node.name}" node.attributes.each do |k,v| s << " #{k}" s << "=\"#{v}\"" if String === v end s << " /" if node.closing == :self s << ">" s += children_view s << "</#{node.name}>" if node.closing != :self && !node.children.empty? s end end else node.to_s end when ::HTML::Text then if sliced? if range = slicing.map.get(node, slice) (range.is_a?(Array) ? node.content[Range.new(*range)] : node.content).tap do |export| unless range == true || (range.is_a?(Array) && range.last == -1) # broken text export << slicing.options.text_break if slicing.options.text_break if block_given? yield self, export end end end end else node.to_s end when ::HTML::CDATA then node.to_s when ::HTML::Node then node.children.map {|child| view(child, slice, &block)}.compact.join end end
ruby
{ "resource": "" }
q5610
Cassie::Schema.Versioning.version
train
def version SelectVersionsQuery.new.fetch_first || Version.new('0') rescue Cassandra::Errors::InvalidError raise uninitialized_error end
ruby
{ "resource": "" }
q5611
Cassie::Schema.Versioning.record_version
train
def record_version(version, set_execution_metadata=true) time = Time.now version.id ||= Cassandra::TimeUuid::Generator.new.at(time) if set_execution_metadata version.executed_at = time version.executor = Etc.getlogin rescue '<unknown>' end InsertVersionQuery.new(version: version).execute! @applied_versions = nil rescue StandardError => e version.id = nil version.executed_at = nil version.executor = nil raise e end
ruby
{ "resource": "" }
q5612
Cassie::Schema.Versioning.load_applied_versions
train
def load_applied_versions database_versions.tap do |versions| versions.each{|v| VersionObjectLoader.new(v).load } end rescue Cassandra::Errors::InvalidError => e raise uninitialized_error end
ruby
{ "resource": "" }
q5613
SlackRTM.Client.init
train
def init return if @has_been_init @socket = init_socket(@socket) @socket.connect # costly and blocking ! internalWrapper = (Struct.new :url, :socket do def write(*args) self.socket.write(*args) end end).new @url.to_s, @socket # this, also, is costly and blocking @driver = WebSocket::Driver.client internalWrapper @driver.on :open do @connected = true unless @callbacks[:open].nil? @callbacks[:open].call end end @driver.on :error do |event| @connected = false unless @callbacks[:error].nil? @callbacks[:error].call end end @driver.on :message do |event| data = JSON.parse event.data unless @callbacks[:message].nil? @callbacks[:message].call data end end @driver.start @has_been_init = true end
ruby
{ "resource": "" }
q5614
SlackRTM.Client.inner_loop
train
def inner_loop return if @stop data = @socket.readpartial 4096 return if data.nil? or data.empty? @driver.parse data @msg_queue.each {|msg| @driver.text msg} @msg_queue.clear end
ruby
{ "resource": "" }
q5615
CLIUtils.Messenger.error
train
def error(m) puts _word_wrap(m, '# ').red @targets.each { |_, t| t.error(m) } end
ruby
{ "resource": "" }
q5616
CLIUtils.Messenger.info
train
def info(m) puts _word_wrap(m, '# ').blue @targets.each { |_, t| t.info(m) } end
ruby
{ "resource": "" }
q5617
CLIUtils.Messenger.section
train
def section(m) puts _word_wrap(m, '---> ').purple @targets.each { |_, t| t.section(m) } end
ruby
{ "resource": "" }
q5618
CLIUtils.Messenger.success
train
def success(m) puts _word_wrap(m, '# ').green @targets.each { |_, t| t.success(m) } end
ruby
{ "resource": "" }
q5619
CLIUtils.Messenger.warn
train
def warn(m) puts _word_wrap(m, '# ').yellow @targets.each { |_, t| t.warn(m) } end
ruby
{ "resource": "" }
q5620
LatexToPng.Convert.size_in_points
train
def size_in_points size_in_pixels size = Sizes.invert[size_in_pixels] return (size.nil?)? size_in_points("#{size_in_pixels.to_i + 1}px") : size end
ruby
{ "resource": "" }
q5621
Opencnam.Parsers.parse_json
train
def parse_json(json) hash = JSON.parse(json, :symbolize_names => true) # Convert hash[:created] and hash[:updated] to Time objects if hash[:created] hash.merge!({ :created => parse_iso_date_string(hash[:created]) }) end if hash[:updated] hash.merge!({ :updated => parse_iso_date_string(hash[:updated]) }) end hash end
ruby
{ "resource": "" }
q5622
Giraph.Schema.execute
train
def execute(query, **args) args = args .merge(with_giraph_root(args)) .merge(with_giraph_resolvers(args)) super(query, **args) end
ruby
{ "resource": "" }
q5623
Pod.CDNSource.specification_path
train
def specification_path(name, version) raise ArgumentError, 'No name' unless name raise ArgumentError, 'No version' unless version relative_podspec = pod_path_partial(name).join("#{version}/#{name}.podspec.json") download_file(relative_podspec) pod_path(name).join("#{version}/#{name}.podspec.json") end
ruby
{ "resource": "" }
q5624
PayDirt.UseCase.load_options
train
def load_options(*required_options, options) # Load required options required_options.each { |o| options = load_option(o, options) } # Load remaining options options.each_key { |k| options = load_option(k, options) } block_given? ? yield : options end
ruby
{ "resource": "" }
q5625
Saddle.MethodTreeBuilder.build_tree
train
def build_tree(requester) root_node = build_root_node(requester) # Search out the implementations directory structure for endpoints if defined?(self.implementation_root) # For each endpoints directory, recurse down it to load the modules endpoints_directories.each do |endpoints_directories| Dir["#{endpoints_directories}/**/*.rb"].each { |f| require(f) } end build_node_children(self.endpoints_module, root_node, requester) end root_node end
ruby
{ "resource": "" }
q5626
Saddle.MethodTreeBuilder.build_root_node
train
def build_root_node(requester) if defined?(self.implementation_root) root_endpoint_file = File.join( self.implementation_root, 'root_endpoint.rb' ) if File.file?(root_endpoint_file) warn "[DEPRECATION] `root_endpoint.rb` is deprecated. Please use `ABSOLUTE_PATH` in your endpoints." # Load it and create our base endpoint require(root_endpoint_file) # RootEndpoint is the special class name for a root endpoint root_node_class = self.implementation_module::RootEndpoint else # 'root_endpoint.rb' doesn't exist, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end else # we don't even have an implementation root, so create a dummy endpoint root_node_class = Saddle::RootEndpoint end root_node_class.new(requester, nil, self) end
ruby
{ "resource": "" }
q5627
Saddle.MethodTreeBuilder.build_node_children
train
def build_node_children(current_module, current_node, requester) return unless current_module current_module.constants.each do |const_symbol| const = current_module.const_get(const_symbol) if const.class == Module # A module means that it's a branch # Build the branch out with a base endpoint branch_node = current_node._build_and_attach_node( Saddle::TraversalEndpoint, const_symbol.to_s.underscore ) # Build out the branch's endpoints on the new branch node self.build_node_children(const, branch_node, requester) end if const < Saddle::TraversalEndpoint # A class means that it's a node # Build out this endpoint on the current node current_node._build_and_attach_node(const) end end end
ruby
{ "resource": "" }
q5628
FormAPI.Client.combine_submissions
train
def combine_submissions(options) unless options[:submission_ids].is_a?(::Array) raise InvalidDataError, "submission_ids is required, and must be an Array." end options[:source_pdfs] = options[:submission_ids].map do |id| { type: 'submission', id: id } end options.delete :submission_ids combine_pdfs(options) end
ruby
{ "resource": "" }
q5629
DEVS.AtomicModel.ensure_output_port
train
def ensure_output_port(port) raise ArgumentError, "port argument cannot be nil" if port.nil? unless port.kind_of?(Port) port = output_port(port) raise ArgumentError, "the given port doesn't exists" if port.nil? end unless port.host == self raise InvalidPortHostError, "The given port doesn't belong to this \ model" end unless port.output? raise InvalidPortTypeError, "The given port isn't an output port" end port end
ruby
{ "resource": "" }
q5630
CronSpec.CronSpecification.is_specification_in_effect?
train
def is_specification_in_effect?(time=Time.now) idx = 0 test_results = @cron_values.collect do | cvalues | time_value = time.send(TimeMethods[idx]) idx += 1 !cvalues.detect { | cv | cv.is_effective?(time_value) }.nil? end.all? end
ruby
{ "resource": "" }
q5631
Rubychain.Block.hash_block
train
def hash_block hash_string = [index,timestamp,data,prev_hash].join sha = Digest::SHA256.new sha.update(hash_string) sha.hexdigest end
ruby
{ "resource": "" }
q5632
CLIUtils.Prefs.ask
train
def ask # First, deliver all the prompts that don't have # any prerequisites. @prompts.reject { |p| p.prereqs }.each do |p| _deliver_prompt(p) end # After the "non-prerequisite" prompts are delivered, # deliver any that require prerequisites. @prompts.select { |p| p.prereqs }.each do |p| _deliver_prompt(p) if _prereqs_fulfilled?(p) end end
ruby
{ "resource": "" }
q5633
CLIUtils.Prefs._prereqs_fulfilled?
train
def _prereqs_fulfilled?(p) ret = true p.prereqs.each do |req| a = @prompts.find do |answer| answer.config_key == req[:config_key] && answer.answer == req[:config_value] end ret = false if a.nil? end ret end
ruby
{ "resource": "" }
q5634
Opee.AskQueue.ask_worker
train
def ask_worker(worker, job) raise NoMethodError.new("undefined method for #{job.class}. Expected a method invocation") unless job.is_a?(Actor::Act) worker.ask(job.op, *job.args) end
ruby
{ "resource": "" }
q5635
ISE.Project.set_property
train
def set_property(name, value, mark_non_default=true) #Set the node's property, as specified. node = get_property_node(name) node.attribute("value").value = value #If the mark non-default option is set, mark the state is not a default value. node.attribute("valueState").value = 'non-default' if mark_non_default end
ruby
{ "resource": "" }
q5636
ISE.Project.minimize_runtime!
train
def minimize_runtime! #Compute the path in which temporary synthesis files should be created. shortname = CGI::escape(get_property(ShortNameProperty)) temp_path = Dir::mktmpdir([shortname, '']) #Synthesize from RAM. set_property(WorkingDirectoryProperty, temp_path) #Ask the project to focus on runtime over performance. set_property(GoalProperty, 'Minimum Runtime') end
ruby
{ "resource": "" }
q5637
ISE.Project.top_level_file
train
def top_level_file(absolute_path=true) path = get_property(TopLevelFileProperty) #If the absolute_path flag is set, and we know how, expand the file path. if absolute_path path = File.expand_path(path, @base_path) end #Return the relevant path. path end
ruby
{ "resource": "" }
q5638
ISE.Project.bit_file
train
def bit_file #Determine ISE's working directory. working_directory = get_property(WorkingDirectoryProperty) #Find an absolute path at which the most recently generated bit file should reside. name = get_property(OutputNameProperty) name = File.expand_path("#{working_directory}/#{name}.bit", @base_path) #If it exists, return it. File::exists?(name) ? name : nil end
ruby
{ "resource": "" }
q5639
HtmlSlicer.Installer.slice
train
def slice(*args, &block) attr_name = args.first raise(NameError, "Attribute name expected!") unless attr_name options = args.extract_options! config = HtmlSlicer.config(options.delete(:config)).duplicate # Configuration instance for each single one implementation if options.present? # Accepts options from args options.each do |key, value| config.send("#{key}=", value) end end if block_given? # Accepts options from block yield config end if config.processors Array.wrap(config.processors).each do |name| HtmlSlicer.load_processor!(name) end end method_name = config.as||"#{attr_name}_slice" config.cache_to = "#{method_name}_cache" if config.cache_to == true class_eval do define_method method_name do var_name = "@_#{method_name}" instance_variable_get(var_name)||instance_variable_set(var_name, HtmlSlicer::Interface.new(self, attr_name, config.config)) end end if config.cache_to && self.superclass == ActiveRecord::Base before_save do send(method_name).load! end end end
ruby
{ "resource": "" }
q5640
Uniqable.ClassMethods.uniqable
train
def uniqable(*fields, to_param: nil) fields = [:uid] if fields.blank? fields.each do |name| before_create { |record| record.uniqable_uid(name) } end define_singleton_method :uniqable_fields do fields end return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end
ruby
{ "resource": "" }
q5641
Paperweight.Download.normalize_download
train
def normalize_download(file) return file unless file.is_a?(StringIO) # We need to open it in binary mode for Windows users. Tempfile.new('download-', binmode: true).tap do |tempfile| # IO.copy_stream is the most efficient way of data transfer. IO.copy_stream(file, tempfile.path) # We add the metadata that open-uri puts on the file # (e.g. #content_type) OpenURI::Meta.init(tempfile) end end
ruby
{ "resource": "" }
q5642
Cassie::Schema.StructureDumper.keyspace_structure
train
def keyspace_structure @keyspace_structure ||= begin args = ["-e", "'DESCRIBE KEYSPACE #{Cassie.configuration[:keyspace]}'"] runner = Cassie::Support::SystemCommand.new("cqlsh", args) runner.succeed runner.output end end
ruby
{ "resource": "" }
q5643
DocbookStatus.Status.remarks
train
def remarks(keyword=nil) if keyword.nil? @remarks else ukw = keyword.upcase @remarks.find_all {|r| r[:keyword] == (ukw)} end end
ruby
{ "resource": "" }
q5644
DocbookStatus.Status.find_section_title
train
def find_section_title(node) title = node.find_first('./db:title') if title.nil? title = node.find_first './db:info/db:title' end if title.nil? "" else title.content end end
ruby
{ "resource": "" }
q5645
DocbookStatus.Status.check_node
train
def check_node(node, level, ctr) if (@@text_elements.include? node.name) ctr << {:type => :para, :level => level, :words => count_content_words(node)} elsif (@@section_elements.include? node.name) title = find_section_title(node) ctr << {:type => :section, :level => level, :title => title, :name => node.name} node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? else node.children.each {|inner_elem| check_node(inner_elem, level+1, ctr)} if node.children? end ctr end
ruby
{ "resource": "" }
q5646
DocbookStatus.Status.is_docbook?
train
def is_docbook?(doc) dbns = doc.root.namespaces.default (!dbns.nil? && (dbns.href.casecmp(DOCBOOK_NS) == 0)) end
ruby
{ "resource": "" }
q5647
DocbookStatus.Status.has_xinclude?
train
def has_xinclude?(doc) ret = false doc.root.namespaces.each do |ns| if (ns.href.casecmp(XINCLUDE_NS) == 0) ret = true break end end ret end
ruby
{ "resource": "" }
q5648
DocbookStatus.Status.find_remarks
train
def find_remarks(filter=[]) if (@source.nil?) rfiles = find_xincludes(@doc) else @doc = XML::Document.file(@source) rfiles = [@source_file] + find_xincludes(@doc) end @remarks = rfiles.map {|rf| ind = XML::Document.file(File.expand_path(rf,@source.nil? ? '.' : @source_dir)) ind.root.namespaces.default_prefix = 'db' rems = find_remarks_in_doc(ind, rf) rems }.flatten if (filter.empty?) @remarks else filter.map {|f| @remarks.find_all {|r| f.casecmp(r[:keyword]) == 0} }.flatten end end
ruby
{ "resource": "" }
q5649
DocbookStatus.Status.sum_lower_sections
train
def sum_lower_sections(secs,start,level) i=start sum = 0 while (i < secs.length && secs[i][:level] > level) sum += secs[i][:words] i += 1 end [sum,i] end
ruby
{ "resource": "" }
q5650
DocbookStatus.Status.sum_sections
train
def sum_sections(secs, max_level) 0.upto(max_level) do |cur_level| i = 0 while i < secs.length if (secs[i][:level] == cur_level) (ctr,ni) = sum_lower_sections(secs, i+1,cur_level) secs[i][:swords] = ctr i = ni else i += 1 end end end secs end
ruby
{ "resource": "" }
q5651
DocbookStatus.Status.analyze_file
train
def analyze_file full_name = File.expand_path(@source) changed = File.mtime(@source) @doc = XML::Document.file(@source) raise ArgumentError, "Error: #{@source} is apparently not DocBook 5." unless is_docbook?(@doc) @doc.xinclude if has_xinclude?(@doc) sections = analyze_document(@doc) {:file => full_name, :modified => changed, :sections => sections} end
ruby
{ "resource": "" }
q5652
AppRepo.Runner.upload_binary
train
def upload_binary if options[:ipa] uploader = AppRepo::Uploader.new(options) result = uploader.upload msg = 'Binary upload failed. Check out the error above.' UI.user_error!(msg) unless result end end
ruby
{ "resource": "" }
q5653
AutoGraphQL.TypeBuilder.convert_type
train
def convert_type type return type if type.is_a? GraphQL::BaseType unless type.is_a? Symbol type = type.to_s.downcase.to_sym end { boolean: GraphQL::BOOLEAN_TYPE, date: GraphQL::Types::DATE, datetime: GraphQL::Types::ISO8601DateTime, decimal: GraphQL::Types::DECIMAL, float: GraphQL::FLOAT_TYPE, int: GraphQL::INT_TYPE, integer: GraphQL::INT_TYPE, json: GraphQL::Types::JSON, string: GraphQL::STRING_TYPE, text: GraphQL::STRING_TYPE, }[type] end
ruby
{ "resource": "" }
q5654
RepoManager.RepoAsset.scm
train
def scm return @scm if @scm raise NoSuchPathError unless File.exists?(path) raise InvalidRepositoryError unless File.exists?(File.join(path, '.git')) @scm = Git.open(path) end
ruby
{ "resource": "" }
q5655
Cassie::Schema.Version.next
train
def next(bump_type=nil) bump_type ||= :patch bump_index = PARTS.index(bump_type.to_sym) # 0.2.1 - > 0.2 bumped_parts = parts.take(bump_index + 1) # 0.2 - > 0.3 bumped_parts[bump_index] = bumped_parts[bump_index].to_i + 1 # 0.3 - > 0.3.0.0 bumped_parts += [0]*(PARTS.length - (bump_index + 1)) self.class.new(bumped_parts.join('.')) end
ruby
{ "resource": "" }
q5656
Git.Lib.native
train
def native(cmd, opts = [], chdir = true, redirect = '', &block) validate ENV['GIT_DIR'] = @git_dir ENV['GIT_INDEX_FILE'] = @git_index_file ENV['GIT_WORK_TREE'] = @git_work_dir path = @git_work_dir || @git_dir || @path opts = [opts].flatten.map {|s| escape(s) }.join(' ') git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1" out = nil if chdir && (Dir.getwd != path) Dir.chdir(path) { out = run_command(git_cmd, &block) } else out = run_command(git_cmd, &block) end if @logger @logger.info(git_cmd) @logger.debug(out) end if $?.exitstatus > 0 if $?.exitstatus == 1 && out == '' return '' end raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s) end out end
ruby
{ "resource": "" }
q5657
Rubychain.Chain.add_next_block
train
def add_next_block(prev_block, data) if valid_block?(prev_block) blockchain << next_block(data) else raise InvalidBlockError end end
ruby
{ "resource": "" }
q5658
GameOverseer.Service.data_to_method
train
def data_to_method(data) raise "No safe methods defined!" unless @safe_methods.size > 0 @safe_methods.each do |method| if data['mode'] == method.to_s self.send(data['mode'], data) end end end
ruby
{ "resource": "" }
q5659
GameOverseer.Service.every
train
def every(milliseconds, &block) Thread.new do loop do block.call sleep(milliseconds/1000.0) end end end
ruby
{ "resource": "" }
q5660
GameOverseer.Service.log
train
def log(string, color = Gosu::Color::RED) GameOverseer::Console.log_with_color(string, color) end
ruby
{ "resource": "" }
q5661
ServerSentEvents.Event.to_s
train
def to_s repr = "" repr += "id: #{id}\n" if id repr += "event: #{event}\n" if event if data.empty? repr += "data: \n" else data.split("\n").each { |l| repr += "data: #{l}\n" } end repr += "\n" end
ruby
{ "resource": "" }
q5662
ExecSandbox.Sandbox.push
train
def push(from, options = {}) to = File.join @path, (options[:to] || File.basename(from)) FileUtils.cp_r from, to permissions = options[:read_only] ? 0770 : 0750 FileUtils.chmod_R permissions, to FileUtils.chown_R @admin_uid, @user_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
{ "resource": "" }
q5663
ExecSandbox.Sandbox.pull
train
def pull(from, to) from = File.join @path, from return nil unless File.exist? from FileUtils.cp_r from, to FileUtils.chmod_R 0770, to FileUtils.chown_R @admin_uid, @admin_gid, to # NOTE: making a file / directory read-only is useless -- the sandboxed # process can replace the file with another copy of the file; this can # be worked around by noting the inode number of the protected file / # dir, and making a hard link to it somewhere else so the inode won't # be reused. to end
ruby
{ "resource": "" }
q5664
ExecSandbox.Sandbox.run
train
def run(command, options = {}) limits = options[:limits] || {} io = {} if options[:in] io[:in] = options[:in] in_rd = nil else in_rd, in_wr = IO.pipe in_wr.write options[:in_data] if options[:in_data] in_wr.close io[:in] = in_rd end if options[:out] io[:out] = options[:out] else out_rd, out_wr = IO.pipe io[:out] = out_wr end case options[:err] when :out io[:err] = STDOUT when :none # Don't set io[:err], so the child's stderr will be closed. else io[:err] = STDERR end pid = ExecSandbox::Spawn.spawn command, io, @principal, limits # Close the pipe ends that are meant to be used in the child. in_rd.close if in_rd out_wr.close if out_wr # Collect information about the child. if out_rd out_pieces = [] out_pieces << out_rd.read rescue nil end status = ExecSandbox::Wait4.wait4 pid if out_rd out_pieces << out_rd.read rescue nil out_rd.close status[:out_data] = out_pieces.join('') end status end
ruby
{ "resource": "" }
q5665
Scheduler.Model.ocurrences
train
def ocurrences(st, en = nil) recurrence ? recurrence.events(:starts => st, :until => en) : (start_at.to_date..end_at.to_date).to_a end
ruby
{ "resource": "" }
q5666
RakeOE.Config.dump
train
def dump puts '******************' puts '* RakeOE::Config *' puts '******************' puts "Directories : #{@directories}" puts "Suffixes : #{@suffixes}" puts "Platform : #{@platform}" puts "Release mode : #{@release}" puts "Test framework : #{@test_fw}" puts "Optimization dbg : #{@optimization_dbg}" puts "Optimization release : #{@optimization_release}" puts "Language Standard for C : #{@language_std_c}" puts "Language Standard for C++ : #{@language_std_cpp}" puts "Software version string : #{@sw_version}" puts "Generate bin file : #{@generate_bin}" puts "Generate hex file : #{@generate_hex}" puts "Generate map file : #{@generate_map}" puts "Strip objects : #{@stripped}" end
ruby
{ "resource": "" }
q5667
MinimalistAuthentication.User.authenticated?
train
def authenticated?(password) if password_object == password update_hash!(password) if password_object.stale? return true end return false end
ruby
{ "resource": "" }
q5668
CircuitB.Fuse.open
train
def open put(:state, :open) if config[:on_break] require 'timeout' handlers = [ config[:on_break] ].flatten.map { |handler| (handler.is_a?(Symbol) ? STANDARD_HANDLERS[handler] : handler) }.compact handlers.each do |handler| begin Timeout::timeout(@break_handler_timeout) { handler.call(self) } rescue Timeout::Error # We ignore handler timeouts rescue # We ignore handler errors end end end end
ruby
{ "resource": "" }
q5669
CronSpec.CronSpecificationFactory.parse
train
def parse(value_spec) case value_spec when WildcardPattern WildcardCronValue.new(@lower_limit, @upper_limit) when @single_value_pattern SingleValueCronValue.new(@lower_limit, @upper_limit, convert_value($1)) when @range_pattern RangeCronValue.new(@lower_limit, @upper_limit, convert_value($1), convert_value($2)) when @step_pattern StepCronValue.new(@lower_limit, @upper_limit, $1.to_i) else raise "Unrecognized cron specification pattern." end end
ruby
{ "resource": "" }
q5670
RepoManager.ViewHelper.path_to
train
def path_to(*args) case when args.length == 1 base_path = :repo_manager asset = args when args.length == 2 base_path, asset = *args when args.length > 2 raise ArgumentError, "Too many arguments" else raise ArgumentError, "Specify at least the file asset" end case base_path when :repo_manager root = File.expand_path('../../../../', __FILE__) else raise "unknown base_path" end File.join(root, asset) end
ruby
{ "resource": "" }
q5671
MongoidColoredLogger.LoggerDecorator.colorize_legacy_message
train
def colorize_legacy_message(message) message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} end
ruby
{ "resource": "" }
q5672
MongoidColoredLogger.LoggerDecorator.colorize_message
train
def colorize_message(message) message = message.sub('MONGODB', color('MONGODB', odd? ? CYAN : MAGENTA)). sub(%r{(?<=\[')([^']+)}) {|m| color(m, BLUE)}. sub(%r{(?<=\]\.)\w+}) {|m| color(m, YELLOW)} message.sub('MOPED:', color('MOPED:', odd? ? CYAN : MAGENTA)). sub(/\{.+?\}\s/) { |m| color(m, BLUE) }. sub(/COMMAND|QUERY|KILL_CURSORS|INSERT|DELETE|UPDATE|GET_MORE|STARTED/) { |m| color(m, YELLOW) }. sub(/SUCCEEDED/) { |m| color(m, GREEN) }. sub(/FAILED/) { |m| color(m, RED) }. sub(/[\d\.]+(s|ms)/) { |m| color(m, GREEN) } end
ruby
{ "resource": "" }
q5673
GBDispatch.Manager.get_queue
train
def get_queue(name=:default_queue) name = name.to_sym queue = @queues[name] unless queue @queues[name] = GBDispatch::Queue.new(name) queue = @queues[name] end queue end
ruby
{ "resource": "" }
q5674
GBDispatch.Manager.run_async_on_queue
train
def run_async_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.async.perform_now ->() { yield } end
ruby
{ "resource": "" }
q5675
GBDispatch.Manager.run_sync_on_queue
train
def run_sync_on_queue(queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue future = queue.await.perform_now ->() { yield } future.value end
ruby
{ "resource": "" }
q5676
GBDispatch.Manager.run_after_on_queue
train
def run_after_on_queue(time, queue) raise ArgumentError.new 'Queue must be GBDispatch::Queue' unless queue.is_a? GBDispatch::Queue queue.perform_after time, ->(){ yield } end
ruby
{ "resource": "" }
q5677
Calligraphy.Utils.map_array_of_hashes
train
def map_array_of_hashes(arr_hashes) return if arr_hashes.nil? [].tap do |output_array| arr_hashes.each do |hash| output_array.push hash.values end end end
ruby
{ "resource": "" }
q5678
Calligraphy.Utils.extract_lock_token
train
def extract_lock_token(if_header) token = if_header.scan(Calligraphy::LOCK_TOKEN_REGEX) token.flatten.first if token.is_a? Array end
ruby
{ "resource": "" }
q5679
Cassie::Statements.Execution.execute
train
def execute(opts={}) @result = result_class.new(session.execute(statement, execution_options.merge(opts)), result_opts) result.success? end
ruby
{ "resource": "" }
q5680
Cassie::Statements.Execution.execution_options
train
def execution_options {}.tap do |opts| # @todo rework consistency module to be more # abstract implementation for all execution options opts[:consistency] = consistency if consistency opts[:paging_state] = paging_state if respond_to?(:paging_state) && paging_state opts[:page_size] = stateless_page_size if respond_to?(:stateless_page_size) && stateless_page_size end end
ruby
{ "resource": "" }
q5681
RepoManager.Add.save_writable_attributes
train
def save_writable_attributes(asset, attributes) valid_keys = [:parent, :path] accessable_attributes = {} attributes.each do |key, value| accessable_attributes[key] = value.dup if valid_keys.include?(key) end asset.configuration.save(accessable_attributes) end
ruby
{ "resource": "" }
q5682
EkmOmnimeter.Meter.method_missing
train
def method_missing(method_sym, *arguments, &block) # Only refresh data if its more than 0.25 seconds old et = @last_read_timestamp.nil? ? 0 : (Time.now - @last_read_timestamp) @logger.debug "Elapsed time since last read #{et}" if et > 250 @logger.info "More than 250 milliseconds have passed since last read. Triggering refresh." read() end if @values.include? method_sym @values[method_sym] else @logger.debug "method_missing failed to find #{method_sym} in the Meter.values cache" super end end
ruby
{ "resource": "" }
q5683
EkmOmnimeter.Meter.calculate_measurement
train
def calculate_measurement(m1, m2, m3) if power_configuration == :single_phase_2wire m1 elsif power_configuration == :single_phase_3wire (m1 + m2) elsif power_configuration == :three_phase_3wire (m1 + m3) elsif power_configuration == :three_phase_4wire (m1 + m2 + m3) end end
ruby
{ "resource": "" }
q5684
EkmOmnimeter.Meter.as_datetime
train
def as_datetime(s) begin d = DateTime.new("20#{s[0,2]}".to_i, s[2,2].to_i, s[4,2].to_i, s[8,2].to_i, s[10,2].to_i, s[12,2].to_i, '-4') rescue logger.error "Could not create valid datetime from #{s}\nDateTime.new(20#{s[0,2]}, #{s[2,2]}, #{s[4,2]}, #{s[8,2]}, #{s[10,2]}, #{s[12,2]}, '-4')" d = DateTime.now() end d end
ruby
{ "resource": "" }
q5685
EkmOmnimeter.Meter.to_f_with_decimal_places
train
def to_f_with_decimal_places(s, p=1) unless s.nil? v = (s.to_f / (10 ** p)) logger.debug "Casting #{s.inspect} -> #{v.inspect}" v else logger.error "Could not cast #{s} to #{p} decimal places" end end
ruby
{ "resource": "" }
q5686
DocbookStatus.History.add
train
def add(ts, word_count) # Ruby 1.8 doesn't have DateTime#to_date, so we check that here begin k = ts.to_date rescue NoMethodError k = Date.parse(ts.to_s) end if @history[:archive][k].nil? @history[:archive][k] = { min: word_count, max: word_count, start: word_count, end: word_count, ctr: 1 } else @history[:archive][k][:min] = word_count if @history[:archive][k][:min] > word_count @history[:archive][k][:max] = word_count if @history[:archive][k][:max] < word_count @history[:archive][k][:end] = word_count @history[:archive][k][:ctr] += 1 end end
ruby
{ "resource": "" }
q5687
FalkorLib.GitFlow.command
train
def command(name, type = 'feature', action = 'start', path = Dir.pwd, optional_args = '') error "Invalid git-flow type '#{type}'" unless %w(feature release hotfix support).include?(type) error "Invalid action '#{action}'" unless %w(start finish).include?(action) error "You must provide a name" if name == '' error "The name '#{name}' cannot contain spaces" if name =~ /\s+/ exit_status = 1 Dir.chdir( FalkorLib::Git.rootdir(path) ) do exit_status = run %( git flow #{type} #{action} #{optional_args} #{name} ) end exit_status end
ruby
{ "resource": "" }
q5688
FalkorLib.GitFlow.guess_gitflow_config
train
def guess_gitflow_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) return {} if (!use_git or !FalkorLib::GitFlow.init?(path)) rootdir = FalkorLib::Git.rootdir(path) local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:gitflow] if local_config[:gitflow] config = FalkorLib::Config::GitFlow::DEFAULTS.clone [ :master, :develop ].each do |br| config[:branches][br.to_sym] = FalkorLib::Git.config("gitflow.branch.#{br}", rootdir) end [ :feature, :release, :hotfix, :support, :versiontag ].each do |p| config[:prefix][p.to_sym] = FalkorLib::Git.config("gitflow.prefix.#{p}", rootdir) end config end
ruby
{ "resource": "" }
q5689
JobmensaAssets.ImageProcessor.call
train
def call(file, *args, format: nil) img = ::MiniMagick::Image.new(file.path) img.quiet img.format(format.to_s.downcase, nil) if format send(@method, img, *args) post_processing(img) ::File.open(img.path, "rb") end
ruby
{ "resource": "" }
q5690
JobmensaAssets.ImageProcessor.post_processing
train
def post_processing(img) img.combine_options do |cmd| cmd.strip # Deletes metatags cmd.colorspace 'sRGB' # Change colorspace cmd.auto_orient # Reset rotation cmd.quiet # Suppress warnings end end
ruby
{ "resource": "" }
q5691
Gares.Train.document
train
def document if !@document @document = Nokogiri::HTML(self.class.request_sncf(number, date)) if !itinerary_available? @document = Nokogiri::HTML(self.class.request_sncf_itinerary(0)) end end if @document.at('#no_results') fail TrainNotFound, @document.at('#no_results b').inner_html end @document end
ruby
{ "resource": "" }
q5692
Securities.Stock.generate_history_url
train
def generate_history_url url = 'http://ichart.finance.yahoo.com/table.csv?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=%s&ignore=.csv' % [ @symbol, @start_date.to_date.month - 1, @start_date.to_date.day, @start_date.to_date.year, @end_date.to_date.month - 1, @end_date.to_date.day, @end_date.to_date.year, TYPE_CODES_ARRAY[@type] ] return url end
ruby
{ "resource": "" }
q5693
Securities.Stock.validate_input
train
def validate_input parameters unless parameters.is_a?(Hash) raise StockException, 'Given parameters have to be a hash.' end # Check if stock symbol is specified. unless parameters.has_key?(:symbol) raise StockException, 'No stock symbol specified.' end # Check if stock symbol is a string. unless parameters[:symbol].is_a?(String) raise StockException, 'Stock symbol must be a string.' end # Use today date if :end_date is not specified. unless parameters.has_key?(:end_date) parameters[:end_date] = Date.today.strftime("%Y-%m-%d") end unless parameters.has_key?(:start_date) raise StockException, 'Start date must be specified.' end unless DATE_REGEX.match(parameters[:start_date]) raise StockException, 'Invalid start date specified. Format YYYY-MM-DD.' end unless DATE_REGEX.match(parameters[:end_date]) raise StockException, 'Invalid end date specified. Format YYYY-MM-DD.' end unless parameters[:start_date].to_date < parameters[:end_date].to_date raise StockException, 'End date must be greater than the start date.' end unless parameters[:start_date].to_date < Date.today raise StockException, 'Start date must not be in the future.' end # Set to default :type if key isn't specified. parameters[:type] = :daily if !parameters.has_key?(:type) unless TYPE_CODES_ARRAY.has_key?(parameters[:type]) raise StockException, 'Invalid type specified.' end end
ruby
{ "resource": "" }
q5694
Praxis.Renderer.render_collection
train
def render_collection(collection, member_fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) render(collection, [member_fields], view, context: context) end
ruby
{ "resource": "" }
q5695
Praxis.Renderer.render
train
def render(object, fields, view = nil, context: Attributor::DEFAULT_ROOT_CONTEXT) if fields.is_a? Array sub_fields = fields[0] object.each_with_index.collect do |sub_object, i| sub_context = context + ["at(#{i})"] render(sub_object, sub_fields, view, context: sub_context) end elsif object.is_a? Praxis::Blueprint @cache[object.object_id][fields.object_id] ||= _render(object, fields, view, context: context) else _render(object, fields, view, context: context) end rescue SystemStackError raise CircularRenderingError.new(object, context) end
ruby
{ "resource": "" }
q5696
Opee.Log.log
train
def log(severity, message, tid) now = Time.now ss = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'][severity] ss = '' if ss.nil? if @formatter.nil? msg = "#{ss[0]}, [#{now.strftime('%Y-%m-%dT%H:%M:%S.%6N')} ##{tid}] #{ss} -- : #{message}\n" else msg = @formatter.call(ss, now, tid, message) end @logger.add(severity, msg) @forward.log(severity, message, tid) unless @forward.nil? end
ruby
{ "resource": "" }
q5697
Opee.Log.stream=
train
def stream=(stream) logger = Logger.new(stream) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
{ "resource": "" }
q5698
Opee.Log.set_filename
train
def set_filename(filename, shift_age=7, shift_size=1048576) logger = Logger.new(filename, shift_age, shift_size) logger.level = @logger.level logger.formatter = @logger.formatter @logger = logger end
ruby
{ "resource": "" }
q5699
Opee.Log.severity=
train
def severity=(level) if level.is_a?(String) severity = { 'FATAL' => Logger::Severity::FATAL, 'ERROR' => Logger::Severity::ERROR, 'WARN' => Logger::Severity::WARN, 'INFO' => Logger::Severity::INFO, 'DEBUG' => Logger::Severity::DEBUG, '4' => Logger::Severity::FATAL, '3' => Logger::Severity::ERROR, '2' => Logger::Severity::WARN, '1' => Logger::Severity::INFO, '0' => Logger::Severity::DEBUG }[level.upcase()] raise "#{level} is not a severity" if severity.nil? level = severity elsif level < Logger::Severity::DEBUG || Logger::Severity::FATAL < level raise "#{level} is not a severity" end @logger.level = level end
ruby
{ "resource": "" }