_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 connecti...
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, 'p...
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 ...
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.") ...
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)...
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: ...
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 b...
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_is...
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}...
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_directo...
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_PAT...
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 ou...
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 :su...
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...
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.pr...
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-defa...
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 proj...
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}.bi...
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?...
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_metho...
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) ...
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...
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...
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 ...
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) ...
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::Typ...
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.lengt...
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_c...
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 usele...
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...
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] ...
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 : #{...
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::timeou...
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,...
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 ...
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| c...
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...
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 pas...
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 + m...
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')" ...
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,...
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...
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_...
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_...
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_d...
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 str...
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) ...
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, ...
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...
ruby
{ "resource": "" }