_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q4600
GeoKit.LatLng.wgs84_to_google
train
def wgs84_to_google ActiveSupport::Deprecation.warn "use Point geometry which supports srid" self.class.from_pro4j Proj4::Projection.wgs84.transform Proj4::Projection.google, self.proj4_point(Math::PI / 180).x, self.proj4_point(Math::PI / 180).y end
ruby
{ "resource": "" }
q4601
Unipept.ServerMessage.print
train
def print return unless $stdout.tty? return if recently_fetched? resp = fetch_server_message update_fetched puts resp unless resp.empty? end
ruby
{ "resource": "" }
q4602
RailsPaginate::Renderers.HtmlDefault.render
train
def render content_tag(:ul) do html = "\n" if show_first_page? html += content_tag(:li, :class => "first_page") do link_to_page collection.first_page, 'paginate.first_page_label' end html += "\n" end if show_previous_page? html += content_tag(:li, :class => "previous_page") do link_to_page collection.previous_page, 'paginate.previous_page_label' end html += "\n" end html += render_pager if show_next_page? html += content_tag(:li, :class => "next_page") do link_to_page collection.next_page, 'paginate.next_page_label' end html += "\n" end if show_last_page? html += content_tag(:li, :class => "last_page") do link_to_page collection.last_page, 'paginate.last_page_label' end html += "\n" end html.html_safe end end
ruby
{ "resource": "" }
q4603
Squire.Configuration.namespace
train
def namespace(namespace = nil, options = {}) return @namespace unless namespace @namespace = namespace.to_sym if namespace @base_namespace = options[:base].to_sym if options[:base] end
ruby
{ "resource": "" }
q4604
Squire.Configuration.source
train
def source(source = nil, options = {}) return @source unless source @source = source @parser = options[:parser] @type = options[:type] @type ||= source.is_a?(Hash) ? :hash : File.extname(@source)[1..-1].to_sym end
ruby
{ "resource": "" }
q4605
Squire.Configuration.settings
train
def settings(&block) @settings ||= setup settings = instance_variable_defined?(:@namespace) ? @settings.get_value(@namespace) : @settings if block_given? block.arity == 0 ? settings.instance_eval(&block) : block.call(settings) end settings end
ruby
{ "resource": "" }
q4606
Squire.Configuration.setup
train
def setup return Squire::Settings.new unless @source parser = Squire::Parser.of(@type) hash = parser.parse(source).with_indifferent_access if base_namespace hash.except(base_namespace).each do |key, values| # favours value from namespace over value from defaults hash[key] = hash[base_namespace].deep_merge(values) { |_, default, value| value.nil? ? default : value } end end Squire::Settings.from_hash(hash) end
ruby
{ "resource": "" }
q4607
Mercurial.CommitFactory.count_range
train
def count_range(hash_a, hash_b, cmd_options={}) hg_to_array([%Q[log -r ?:? --template "{node}\n"], hash_a, hash_b], {}, cmd_options) do |line| line end.size end
ruby
{ "resource": "" }
q4608
Adfly.API.create_link
train
def create_link data body = http_get URL_API, {key: @key, uid: @uid}.merge(data) raise ArgumentError if body.nil? || body.empty? body end
ruby
{ "resource": "" }
q4609
Mongoid::Globalize.FieldsBuilder.field
train
def field(name, *params) @model.translated_attribute_names.push name.to_sym @model.translated_attr_accessor(name) @model.translation_class.field name, *params end
ruby
{ "resource": "" }
q4610
Danger.DangerSimpleCovJson.report
train
def report(coverage_path, sticky: true) if File.exist? coverage_path coverage_json = JSON.parse(File.read(coverage_path), symbolize_names: true) metrics = coverage_json[:metrics] percentage = metrics[:covered_percent] lines = metrics[:covered_lines] total_lines = metrics[:total_lines] formatted_percentage = format('%.02f', percentage) message("Code coverage is now at #{formatted_percentage}% (#{lines}/#{total_lines} lines)", sticky: sticky) else fail('Code coverage data not found') end end
ruby
{ "resource": "" }
q4611
Danger.DangerSimpleCovJson.individual_coverage_message
train
def individual_coverage_message(covered_files) require 'terminal-table' message = "### Code Coverage\n\n" table = Terminal::Table.new( headings: %w(File Coverage), style: { border_i: '|' }, rows: covered_files.map do |file| [file[:filename], "#{format('%.02f', file[:covered_percent])}%"] end ).to_s message + table.split("\n")[1..-2].join("\n") end
ruby
{ "resource": "" }
q4612
KnifeCommunity.CommunityRelease.validate_args
train
def validate_args if name_args.size < 1 ui.error('No cookbook has been specified') show_usage exit 1 end if name_args.size > 2 ui.error('Too many arguments are being passed. Please verify.') show_usage exit 1 end end
ruby
{ "resource": "" }
q4613
KnifeCommunity.CommunityRelease.validate_repo_clean
train
def validate_repo_clean @gitrepo = Grit::Repo.new(@repo_root) status = @gitrepo.status if !status.changed.nil? || status.changed.size != 0 # This has to be a convoluted way to determine a non-empty... # Test each for the magic sha_index. Ref: https://github.com/mojombo/grit/issues/142 status.changed.each do |file| case file[1].sha_index when '0' * 40 ui.error 'There seem to be unstaged changes in your repo. Either stash or add them.' exit 4 else ui.msg 'There are modified files that have been staged, and will be included in the push.' end end elsif status.untracked.size > 0 ui.warn 'There are untracked files in your repo. You might want to look into that.' end end
ruby
{ "resource": "" }
q4614
KnifeCommunity.CommunityRelease.validate_no_existing_tag
train
def validate_no_existing_tag(tag_string) existing_tags = [] @gitrepo.tags.each { |tag| existing_tags << tag.name } if existing_tags.include?(tag_string) ui.error 'This version tag has already been committed to the repo.' ui.error "Are you sure you haven't released this already?" exit 6 end end
ruby
{ "resource": "" }
q4615
KnifeCommunity.CommunityRelease.validate_target_remote_branch
train
def validate_target_remote_branch remote_path = File.join(config[:remote], config[:branch]) remotes = [] @gitrepo.remotes.each { |remote| remotes << remote.name } unless remotes.include?(remote_path) ui.error 'The remote/branch specified does not seem to exist.' exit 7 end end
ruby
{ "resource": "" }
q4616
Munin.Node.nodes
train
def nodes nodes = [] cache 'nodes' do connection.send_data("nodes") while ( ( line = connection.read_line ) != "." ) nodes << line end nodes end end
ruby
{ "resource": "" }
q4617
Munin.Node.list
train
def list(node = "") cache "list_#{node.empty? ? 'default' : node}" do connection.send_data("list #{node}") if ( line = connection.read_line ) != "." line.split else connection.read_line.split end end end
ruby
{ "resource": "" }
q4618
Munin.Node.config
train
def config(services, raw=false) unless [String, Array].include?(services.class) raise ArgumentError, "Service(s) argument required" end results = {} names = [services].flatten.uniq if names.empty? raise ArgumentError, "Service(s) argument required" end key = 'config_' + Digest::MD5.hexdigest(names.to_s) + "_#{raw}" cache(key) do names.each do |service| begin connection.send_data("config #{service}") lines = connection.read_packet results[service] = raw ? lines.join("\n") : parse_config(lines) rescue UnknownService, BadExit # TODO end end results end end
ruby
{ "resource": "" }
q4619
Munin.Node.fetch
train
def fetch(services) unless [String, Array].include?(services.class) raise ArgumentError, "Service(s) argument required" end results = {} names = [services].flatten if names.empty? raise ArgumentError, "Service(s) argument required" end names.each do |service| begin connection.send_data("fetch #{service}") lines = connection.read_packet results[service] = parse_fetch(lines) rescue UnknownService, BadExit # TODO end end results end
ruby
{ "resource": "" }
q4620
Squire.Settings.get_value
train
def get_value(key, &block) key = key.to_sym value = @table[key] if block_given? block.arity == 0 ? value.instance_eval(&block) : block.call(value) end value end
ruby
{ "resource": "" }
q4621
Squire.Settings.to_hash
train
def to_hash result = ::Hash.new @table.each do |key, value| if value.is_a? Settings value = value.to_hash end result[key] = value end result end
ruby
{ "resource": "" }
q4622
QuestionproRails.Question.choices
train
def choices extracted_choices = [] unless self.qp_answers.nil? self.qp_answers.each do |choice| extracted_choices.push(Choice.new(choice)) end end return extracted_choices end
ruby
{ "resource": "" }
q4623
Rtasklib.Helpers.filter
train
def filter ids: nil, tags: nil, dom: nil id_s = tag_s = dom_s = "" id_s = process_ids(ids) unless ids.nil? tag_s = process_tags(tags) unless tags.nil? dom_s = process_dom(dom) unless dom.nil? return "#{id_s} #{tag_s} #{dom_s}".strip end
ruby
{ "resource": "" }
q4624
Rtasklib.Helpers.process_ids
train
def process_ids ids case ids when Range return id_range_to_s(ids) when Array return id_a_to_s(ids) when String return ids.delete(" ") when Fixnum return ids end end
ruby
{ "resource": "" }
q4625
Rtasklib.Helpers.process_tags
train
def process_tags tags case tags when String tags.split(" ").map { |t| process_tag t }.join(" ") when Array tags.map { |t| process_tags t }.join(" ") end end
ruby
{ "resource": "" }
q4626
Rtasklib.Helpers.json?
train
def json? value begin return false unless value.is_a? String MultiJson.load(value) true rescue MultiJson::ParseError false end end
ruby
{ "resource": "" }
q4627
CouchRest.Property.cast_value
train
def cast_value(parent, value) raise "An array inside an array cannot be casted, use CastedModel" if value.is_a?(Array) value = typecast_value(value, self) associate_casted_value_to_parent(parent, value) end
ruby
{ "resource": "" }
q4628
CouchRest.Property.type_class
train
def type_class return String unless casted # This is rubbish, to handle validations return @type_class unless @type_class.nil? base = @type.is_a?(Array) ? @type.first : @type base = String if base.nil? base = TrueClass if base.is_a?(String) && base.downcase == 'boolean' @type_class = base.is_a?(Class) ? base : base.constantize end
ruby
{ "resource": "" }
q4629
Unipept.BatchIterator.fasta_iterator
train
def fasta_iterator(first_line, next_lines) current_fasta_header = first_line.chomp next_lines.each_slice(batch_size).with_index do |slice, i| fasta_mapper = [] input_set = Set.new slice.each do |line| line.chomp! if fasta? line current_fasta_header = line else fasta_mapper << [current_fasta_header, line] input_set << line end end yield(input_set.to_a, i, fasta_mapper) end end
ruby
{ "resource": "" }
q4630
AdbSdkLib.Device.properties
train
def properties convert_map_to_hash(@device.getProperties) do |hash, key, value| hash[key.toString] = value.toString end end
ruby
{ "resource": "" }
q4631
AdbSdkLib.Device.shell
train
def shell(command, &block) capture = CommandCapture.new(block_given? ? block : nil) receiver = Rjb::bind(capture, 'com.android.ddmlib.IShellOutputReceiver') @device.executeShellCommand(command.to_s, receiver) block_given? ? self : capture.to_s end
ruby
{ "resource": "" }
q4632
AdbSdkLib.Device.push
train
def push(localfile, remotefile) raise ArgumentError, "Not found #{localfile}" unless File.exist?(localfile) if remotefile.end_with?('/') remotefile = "#{remotefile}#{File.basename(localfile)}" end @device.pushFile(localfile, remotefile) self end
ruby
{ "resource": "" }
q4633
AdbSdkLib.Device.pull
train
def pull(remotefile, localfile) if localfile.end_with?('/') || File.directory?(localfile) localdir = localfile.chomp('/') localfilename = nil else localdir = File.dirname(localfile) localfilename = File.basename(localfile) end unless File.exist?(localdir) FileUtils.mkdir_p(localdir) end localfilename = File.basename(remotefile) if localfilename.nil? @device.pullFile(remotefile, "#{localdir}/#{localfilename}") self end
ruby
{ "resource": "" }
q4634
GeoWorks.RasterFileBehavior.raster_work
train
def raster_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::RasterWorkBehavior) end.to_a end
ruby
{ "resource": "" }
q4635
AdbSdkLib.RawImage.pixel
train
def pixel(x,y) Pixel.new(x,y,@image.getARGB(point_to_index(x,y))) end
ruby
{ "resource": "" }
q4636
AdbSdkLib.RawImage.each_pixel
train
def each_pixel() return to_enum :each_pixel unless block_given? @image.height.times do |y| @image.width.times do |x| yield pixel(x,y) end end self end
ruby
{ "resource": "" }
q4637
QuestionproRails.ApiRequest.options
train
def options {id: self.survey_id, surveyID: self.survey_id, responseID: self.response_id, resultMode: self.result_mode, startDate: self.start_date, userID: self.user_id, endDate: self.end_date, startingResponseCounter: self.starting_response_counter, emailGroupID: self.email_group_id, templateID: self.template_id}.compact.to_json end
ruby
{ "resource": "" }
q4638
QuestionproRails.ApiRequest.list_surveys
train
def list_surveys url = ApiRequest.base_path("questionpro.survey.getAllSurveys") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] surveys = [] result_surveys = result['response']['surveys'] result_surveys.each do |survey| surveys.push(Survey.new(survey)) end return surveys end
ruby
{ "resource": "" }
q4639
QuestionproRails.ApiRequest.get_survey
train
def get_survey url = ApiRequest.base_path("questionpro.survey.getSurvey") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] survey = Survey.new(result['response']) return survey end
ruby
{ "resource": "" }
q4640
QuestionproRails.ApiRequest.get_survey_responses
train
def get_survey_responses url = ApiRequest.base_path("questionpro.survey.surveyResponses") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] survey_responses = [] result_responses = result['response']['responses'] result_responses.each do |response| survey_responses.push(SurveyResponse.new(response)) end return survey_responses end
ruby
{ "resource": "" }
q4641
QuestionproRails.ApiRequest.get_survey_reponse
train
def get_survey_reponse url = ApiRequest.base_path("questionpro.survey.surveyResponse") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] response = SurveyResponse.new(result['response']['surveyResponse']) return response end
ruby
{ "resource": "" }
q4642
QuestionproRails.ApiRequest.get_survey_response_count
train
def get_survey_response_count url = ApiRequest.base_path("questionpro.survey.responseCount") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] response_count = SurveyResponseCount.new(result['response']) return response_count end
ruby
{ "resource": "" }
q4643
QuestionproRails.ApiRequest.delete_response
train
def delete_response url = ApiRequest.base_path("questionpro.survey.deleteResponse") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] self.success = result['response']['success'] return self end
ruby
{ "resource": "" }
q4644
QuestionproRails.ApiRequest.get_email_lists
train
def get_email_lists url = ApiRequest.base_path("questionpro.survey.getEmailLists") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_lists = [] result_email_lists = result['response']['emailLists'] result_email_lists.each do |email_list| email_lists.push(EmailList.new(email_list)) end return email_lists end
ruby
{ "resource": "" }
q4645
QuestionproRails.ApiRequest.get_email_list
train
def get_email_list url = ApiRequest.base_path("questionpro.survey.getEmailList") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_list = EmailList.new(result['response']['emailList']) return email_list end
ruby
{ "resource": "" }
q4646
QuestionproRails.ApiRequest.get_email_templates
train
def get_email_templates url = ApiRequest.base_path("questionpro.survey.getEmailTemplates") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_templates = [] result_email_templates = result['response']['emailTemplates'] result_email_templates.each do |email_template| email_templates.push(EmailTemplate.new(email_template)) end return email_templates end
ruby
{ "resource": "" }
q4647
QuestionproRails.ApiRequest.get_email_template
train
def get_email_template url = ApiRequest.base_path("questionpro.survey.getEmailTemplate") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_template = EmailTemplate.new(result['response']['emailTemplate']) return email_template end
ruby
{ "resource": "" }
q4648
QuestionproRails.ApiRequest.get_all_accounts
train
def get_all_accounts url = ApiRequest.base_path("questionpro.survey.getAllAccounts") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] accounts = [] result_accounts = result['response']['accounts'] result_accounts.each do |account| accounts.push(Account.new(account)) end return accounts end
ruby
{ "resource": "" }
q4649
QuestionproRails.ApiRequest.get_account
train
def get_account url = ApiRequest.base_path("questionpro.survey.getAccount") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] account = Account.new(result['response']['account']) return account end
ruby
{ "resource": "" }
q4650
QuestionproRails.ApiRequest.get_unsubscribers
train
def get_unsubscribers url = ApiRequest.base_path("questionpro.survey.getUnsubscribedEmailAddresses") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] unsubscribers = [] result_unsubscribers = result['response']['response'] result_unsubscribers.each do |unsubscriber| unsubscribers.push(UnsubscribedEmail.new(unsubscriber)) end return unsubscribers end
ruby
{ "resource": "" }
q4651
QuestionproRails.ApiRequest.get_survey_meta
train
def get_survey_meta url = ApiRequest.base_path("questionpro.survey.sendSurveyMetaData") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] survey_meta = SurveyMeta.new(result['response']) return survey_meta end
ruby
{ "resource": "" }
q4652
QuestionproRails.ApiRequest.send_survey
train
def send_survey(mode = 1, emails = nil, template_id = nil) url = ApiRequest.base_path("questionpro.survey.sendSurvey") result = self.class.get(url, body: {surveyID: self.survey_id, mode: mode, emailGroupID: self.email_group_id, emails: emails, templateID: self.template_id, template: template_id}.compact.to_json) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
ruby
{ "resource": "" }
q4653
QuestionproRails.ApiRequest.get_send_history
train
def get_send_history url = ApiRequest.base_path("questionpro.survey.emailBatchStatistics") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] email_batches = [] result_email_batches = result['response']['emailBatches'] result_email_batches.each do |email_batch| email_batches.push(EmailBatch.new(email_batch)) end return email_batches end
ruby
{ "resource": "" }
q4654
QuestionproRails.ApiRequest.send_reminders
train
def send_reminders url = ApiRequest.base_path("questionpro.survey.sendReminder") result = self.class.get(url, body: self.options) self.full_response = result self.status = result['status'] self.message = result['response']['result'] end
ruby
{ "resource": "" }
q4655
QuestionproRails.ApiRequest.create_email_list
train
def create_email_list (emails = [], email_group_name = nil) url = ApiRequest.base_path("questionpro.survey.createEmailGroup") result = self.class.get(url, body: {id: self.survey_id, emails: emails, emailGroupName: email_group_name}.compact.to_json) self.full_response = result self.status = result['status'] unless result['response']['result']['emailGroupID'].nil? self.email_group_id = result['response']['result']['emailGroupID'] end end
ruby
{ "resource": "" }
q4656
QuestionproRails.Section.questions
train
def questions extracted_questions = [] unless self.qp_questions.nil? self.qp_questions.each do |question| extracted_questions.push(Question.new(question)) end end return extracted_questions end
ruby
{ "resource": "" }
q4657
Xcop.Document.ldiff
train
def ldiff(license) xml = Nokogiri::XML(File.open(@path), &:noblanks) comment = xml.xpath('/comment()')[0] now = comment.nil? ? '' : comment.text.to_s.strip ideal = license.strip differ(ideal, now) end
ruby
{ "resource": "" }
q4658
Xcop.Document.fix
train
def fix(license = '') xml = Nokogiri::XML(File.open(@path), &:noblanks) unless license.empty? xml.xpath('/comment()').remove xml.children.before( Nokogiri::XML::Comment.new(xml, "\n#{license.strip}\n") ) end ideal = xml.to_xml(indent: 2) File.write(@path, ideal) end
ruby
{ "resource": "" }
q4659
XO.Init.start
train
def start(turn) game_context.check_turn(turn) game_context.set_turn_and_clear_grid(turn) engine.transition_to_state_and_send_event(Playing, :game_started) end
ruby
{ "resource": "" }
q4660
QuestionproRails.Survey.sections
train
def sections extracted_sections = [] unless self.qp_sections.nil? self.qp_sections.each do |section| extracted_sections.push(Section.new(section)) end end return extracted_sections end
ruby
{ "resource": "" }
q4661
Mercurial.Commit.stats
train
def stats(cmd_options={}) raw = hg(["log -r ? --stat --template '{node}\n'", hash_id], cmd_options) result = raw.scan(/(\d+) files changed, (\d+) insertions\(\+\), (\d+) deletions\(\-\)$/).flatten.map{|r| r.to_i} return {} if result.empty? # that commit has no stats { 'files' => result[0], 'additions' => result[1], 'deletions' => result[2], 'total' => result[1] + result[2] } end
ruby
{ "resource": "" }
q4662
HoneyFormat.RowBuilder.build
train
def build(row) build_row!(row) rescue ArgumentError => e raise unless e.message == 'struct size differs' raise_invalid_row_length!(e, row) end
ruby
{ "resource": "" }
q4663
Mercurial.ConfigFile.find_header
train
def find_header(header) {}.tap do |returning| contents.scan(header_with_content_regexp(header)).flatten.first.split("\n").each do |setting| name, value = *setting.split('=').map(&:strip) returning[name] = value end end end
ruby
{ "resource": "" }
q4664
Mercurial.ConfigFile.find_setting
train
def find_setting(header, setting) #:nodoc: return nil if contents.nil? contents.scan(setting_regexp(header, setting)).flatten.first end
ruby
{ "resource": "" }
q4665
Mercurial.HookFactory.add
train
def add(name, value) build(name, value).tap do |hook| hook.save end end
ruby
{ "resource": "" }
q4666
CouchRest.ExtendedDocument.create_without_callbacks
train
def create_without_callbacks(bulk =false) raise ArgumentError, "a document requires a database to be created to (The document or the #{self.class} default database were not set)" unless database set_unique_id if new? && self.respond_to?(:set_unique_id) result = database.save_doc(self, bulk) (result["ok"] == true) ? self : false end
ruby
{ "resource": "" }
q4667
Doorkeeper.AccessToken.save
train
def save(**options) if use_refresh_token? options[:ttl] = self.created_at + 6.months else options[:ttl] = self.created_at + self.expires_in + 30 end super(**options) end
ruby
{ "resource": "" }
q4668
HoneyFormat.Row.to_csv
train
def to_csv(columns: nil) attributes = members attributes = columns & attributes if columns row = attributes.map! { |column| to_csv_value(column) } ::CSV.generate_line(row) end
ruby
{ "resource": "" }
q4669
HoneyFormat.Row.inspect
train
def inspect attributes = members.map do |field| value = self[field] value = "\"#{value}\"" if value.is_a?(String) [field, value].join('=') end.join(', ') "#<Row #{attributes}>" end
ruby
{ "resource": "" }
q4670
HoneyFormat.Row.to_csv_value
train
def to_csv_value(column) value = public_send(column) return if value.nil? return value.to_csv if value.respond_to?(:to_csv) value.to_s end
ruby
{ "resource": "" }
q4671
Mercurial.FileIndex.update
train
def update(oldrev=nil, newrev=nil) if index_file_exists? && oldrev != "0"*40 hg([ "log --debug -r ?:? --style ? >> ?", oldrev, newrev, Style.file_index, path ]) else hg(["log --debug -r : --style ? > ?", Style.file_index, path]) end end
ruby
{ "resource": "" }
q4672
Mercurial.FileIndex.commits_from
train
def commits_from(commit_sha) raise UnsupportedRef if commit_sha.is_a? Array read_if_needed already = {} final = [] left_to_do = [commit_sha] while commit_sha = left_to_do.shift next if already[commit_sha] final << commit_sha already[commit_sha] = true commit = @commit_index[commit_sha] commit[:parents].each do |sha| left_to_do << sha end if commit end sort_commits(final) end
ruby
{ "resource": "" }
q4673
CouchRest.CastedModel.update_attributes_without_saving
train
def update_attributes_without_saving(hash) hash.each do |k, v| raise NoMethodError, "#{k}= method not available, use property :#{k}" unless self.respond_to?("#{k}=") end hash.each do |k, v| self.send("#{k}=",v) end end
ruby
{ "resource": "" }
q4674
OboParser.OboParser.term_hash
train
def term_hash @terms.inject({}) {|sum, t| sum.update(t.name.value => t.id.value)} end
ruby
{ "resource": "" }
q4675
QuestionproRails.ResponseSet.answers
train
def answers extracted_answers = [] unless self.qp_values.nil? self.qp_values.each do |answer| extracted_answers.push(ResponseAnswer.new(answer)) end end return extracted_answers end
ruby
{ "resource": "" }
q4676
ActsAsApprovable.Model.acts_as_approvable
train
def acts_as_approvable(options = {}) extend ClassMethods include InstanceMethods cattr_accessor :approvable_on self.approvable_on = Array.wrap(options.delete(:on) { [:create, :update, :destroy] }) cattr_accessor :approvable_field self.approvable_field = options.delete(:state_field) cattr_accessor :approvable_ignore ignores = Array.wrap(options.delete(:ignore) { [] }) ignores.push('created_at', 'updated_at', primary_key, self.approvable_field) self.approvable_ignore = ignores.compact.uniq.map(&:to_s) cattr_accessor :approvable_only self.approvable_only = Array.wrap(options.delete(:only) { [] }).uniq.map(&:to_s) cattr_accessor :approvals_disabled self.approvals_disabled = false has_many :approvals, :as => :item, :dependent => :destroy if approvable_on?(:update) include UpdateInstanceMethods before_update :approvable_update, :if => :approvable_update? end if approvable_on?(:create) include CreateInstanceMethods before_create :approvable_create, :if => :approvable_create? end if approvable_on?(:destroy) include DestroyInstanceMethods end after_save :approvable_save, :if => :approvals_enabled? end
ruby
{ "resource": "" }
q4677
Traject.HorizonReader.require_jars!
train
def require_jars! require 'jruby' # ask marc-marc4j gem to load the marc4j jars MARC::MARC4J.new(:jardir => settings['marc4j_reader.jar_dir']) # For some reason we seem to need to java_import it, and use # a string like this. can't just refer to it by full # qualified name, not sure why, but this seems to work. java_import "org.marc4j.converter.impl.AnselToUnicode" unless defined? Java::net.sourceforge.jtds.jdbc.Driver jtds_jar_dir = settings["jtds.jar_path"] || File.expand_path("../../vendor/jtds", File.dirname(__FILE__)) Dir.glob("#{jtds_jar_dir}/*.jar") do |x| require x end # For confusing reasons, in normal Java need to # Class.forName("net.sourceforge.jtds.jdbc.Driver") # to get the jtds driver to actually be recognized by JDBC. # # In Jruby, Class.forName doesn't work, but this seems # to do the same thing: Java::net.sourceforge.jtds.jdbc.Driver end # So we can refer to these classes as just ResultSet, etc. java_import java.sql.ResultSet, java.sql.PreparedStatement, java.sql.Driver end
ruby
{ "resource": "" }
q4678
Traject.HorizonReader.convert_text!
train
def convert_text!(text, error_handler) text = AnselToUnicode.new(error_handler, true).convert(text) if convert_marc8_to_utf8? # Turn Horizon's weird escaping into UTF8: <U+nnnn> where nnnn is a hex unicode # codepoint, turn it UTF8 for that codepoint if settings["horizon.destination_encoding"] == "UTF8" && (settings["horizon.codepoint_translate"].to_s == "true" || settings["horizon.character_reference_translate"].to_s == "true") regexp = if settings["horizon.codepoint_translate"].to_s == "true" && settings["horizon.character_reference_translate"].to_s == "true" # unicode codepoint in either HTML char reference form OR # weird horizon form. /(?:\<U\+|&#x)([0-9A-Fa-f]{4})(?:\>|;)/ elsif settings["horizon.codepoint_translate"].to_s == "true" # just weird horizon form /\<U\+([0-9A-Fa-f]{4})\>/ else # just character references /&#x([0-9A-Fa-f]{4});/ end text.gsub!(regexp) do [$1.hex].pack("U") end end # eliminate illegal control chars. All ASCII less than 0x20 # _except_ for four legal ones (including MARC delimiters). # http://www.loc.gov/marc/specifications/specchargeneral.html#controlfunction # this is all bytes from 0x00 to 0x19 except for the allowed 1B, 1D, 1E, 1F. text.gsub!(/[\x00-\x1A\x1C]/, '') return text end
ruby
{ "resource": "" }
q4679
Traject.HorizonReader.fix_leader!
train
def fix_leader!(leader) if leader.length < 24 # pad it to 24 bytes, leader is supposed to be 24 bytes leader.replace( leader.ljust(24, ' ') ) elsif leader.length > 24 # Also a problem, slice it leader.replace( leader.byteslice(0, 24)) end # http://www.loc.gov/marc/bibliographic/ecbdldrd.html leader[10..11] = '22' leader[20..23] = '4500' if settings['horizon.destination_encoding'] == "UTF8" leader[9] = 'a' end # leader should only have ascii chars in it; invalid non-ascii # chars can cause ruby encoding problems down the line. # additionally, a force_encoding may be neccesary to # deal with apparent weird hard to isolate jruby bug prob same one # as at https://github.com/jruby/jruby/issues/886 leader.force_encoding('ascii') unless leader.valid_encoding? # replace any non-ascii chars with a space. # Can't access leader.chars when it's not a valid encoding # without a weird index out of bounds exception, think it's # https://github.com/jruby/jruby/issues/886 # Grr. #leader.replace( leader.chars.collect { |c| c.valid_encoding? ? c : ' ' }.join('') ) leader.replace(leader.split('').collect { |c| c.valid_encoding? ? c : ' ' }.join('')) end end
ruby
{ "resource": "" }
q4680
Smalltext.Classifier.softmax
train
def softmax(w) e = Numo::NMath.exp(w - (w.max)) dist = e / (e.sum) return dist end
ruby
{ "resource": "" }
q4681
Gitolite.Config.normalize_name
train
def normalize_name(context, constant = nil) case context when constant context.name when Symbol context.to_s else context end end
ruby
{ "resource": "" }
q4682
Cborb::Decoding.State.<<
train
def <<(cbor) @buffer.write(cbor) @decoding_fiber.resume rescue FiberError => e msg = e.message # umm... if msg.include?("dead") raise Cborb::InvalidByteSequenceError elsif msg.include?("threads") raise Cborb::DecodingError, "Can't decode across threads" else raise end end
ruby
{ "resource": "" }
q4683
Cborb::Decoding.State.consume
train
def consume(size) data = @buffer.read(size).to_s # If buffered data is not enought, yield fiber until new data will be buffered. if data.size < size @buffer.reset! while data.size != size Fiber.yield data += @buffer.read(size - data.size) end end data end
ruby
{ "resource": "" }
q4684
QuestionproRails.SurveyMeta.email_groups
train
def email_groups extracted_groups = [] unless self.email_groups_list.nil? self.email_groups_list.each do |email_group| extracted_groups.push(EmailGroup.new(email_group)) end end return extracted_groups end
ruby
{ "resource": "" }
q4685
QuestionproRails.SurveyMeta.templates
train
def templates extracted_templates = [] unless self.templates_list.nil? self.templates_list.each do |template| extracted_templates.push(Template.new(template)) end end return extracted_templates end
ruby
{ "resource": "" }
q4686
Stagehand.Production.matching
train
def matching(staging_record, table_name = nil) table_name, id = Stagehand::Key.generate(staging_record, :table_name => table_name) prepare_to_modify(table_name) return Record.where(:id => id) end
ruby
{ "resource": "" }
q4687
Rydux.Store.subscribe
train
def subscribe(caller = nil, &block) if block_given? notify_when = block.call(state) @listeners << { obj: block.binding.receiver, notify_when: notify_when } else @listeners << { obj: caller } end end
ruby
{ "resource": "" }
q4688
Rydux.Store.strap_reducers
train
def strap_reducers(reducers) reducers.each {|k, reducer| set_state *[k, reducer.map_state(type: nil)]} reducers end
ruby
{ "resource": "" }
q4689
Silo.Repository.add
train
def add(path, prefix = nil) path = File.expand_path path prefix ||= '/' in_work_tree File.dirname(path) do index = @git.index index.read_tree 'HEAD' add = lambda do |f, p| file = File.basename f pre = (p == '/') ? file : File.join(p, file) dir = File.stat(f).directory? if dir (Dir.entries(f) - %w{. ..}).each do |child| add.call File.join(f, child), pre end else index.add pre, IO.read(f) end dir end dir = add.call path, prefix type = dir ? 'directory' : 'file' commit_msg = "Added #{type} #{path} into '#{prefix}'" index.commit commit_msg, [@git.head.commit.sha] end end
ruby
{ "resource": "" }
q4690
Silo.Repository.add_remote
train
def add_remote(name, url) @remotes[name] = Remote::Git.new(self, name, url) @remotes[name].add end
ruby
{ "resource": "" }
q4691
Silo.Repository.contents
train
def contents(path = nil) contents = [] object = find_object(path || '/') contents << path unless path.nil? || object.nil? if object.is_a? Grit::Tree (object.blobs + object.trees).each do |obj| contents += contents(path.nil? ? obj.basename : File.join(path, obj.basename)) end end contents end
ruby
{ "resource": "" }
q4692
Silo.Repository.git_remotes
train
def git_remotes remotes = {} @git.git.remote.split.each do |remote| url = @git.git.config({}, '--get', "remote.#{remote}.url").strip remotes[remote] = Remote::Git.new(self, remote, url) end remotes end
ruby
{ "resource": "" }
q4693
Silo.Repository.history
train
def history(path = nil) params = ['--format=raw'] params += ['--', path] unless path.nil? output = @git.git.log({}, *params) Grit::Commit.list_from_string @git, output end
ruby
{ "resource": "" }
q4694
Silo.Repository.info
train
def info(path) info = {} object = object! path info[:history] = history path info[:mode] = object.mode info[:name] = object.name info[:path] = path info[:sha] = object.id info[:created] = info[:history].last.committed_date info[:modified] = info[:history].first.committed_date if object.is_a? Grit::Blob info[:mime] = object.mime_type info[:size] = object.size info[:type] = :blob else info[:path] += '/' info[:type] = :tree end info end
ruby
{ "resource": "" }
q4695
Silo.Repository.prepare
train
def prepare raise AlreadyPreparedError.new(@path) if prepared? in_work_tree :tmp do FileUtils.touch '.silo' @git.add '.silo' @git.commit_index 'Enabled Silo for this repository' end end
ruby
{ "resource": "" }
q4696
Silo.Repository.purge
train
def purge(path, prune = true) object = object! path if object.is_a? Grit::Tree (object.blobs + object.trees).each do |blob| purge File.join(path, blob.basename), prune end else params = ['-f', '--index-filter', "git rm --cached --ignore-unmatch #{path}"] params << '--prune-empty' if prune params << 'HEAD' @git.git.filter_branch({}, *params) end end
ruby
{ "resource": "" }
q4697
Silo.Repository.remove
train
def remove(path) object = object! path path += '/' if object.is_a?(Grit::Tree) && path[-1].chr != '/' index = @git.index index.read_tree 'HEAD' index.delete path type = object.is_a?(Grit::Tree) ? 'directory' : 'file' commit_msg = "Removed #{type} #{path}" index.commit commit_msg, [@git.head.commit.sha] end
ruby
{ "resource": "" }
q4698
Silo.Repository.remove_remote
train
def remove_remote(name) remote = @remotes[name] raise UndefinedRemoteError.new(name) if remote.nil? remote.remove @remotes[name] = nil end
ruby
{ "resource": "" }
q4699
Silo.Repository.restore
train
def restore(path, prefix = '.') object = object! path prefix = File.expand_path prefix FileUtils.mkdir_p prefix unless File.exists? prefix file_path = File.join prefix, File.basename(path) if object.is_a? Grit::Tree FileUtils.mkdir file_path unless File.directory? file_path (object.blobs + object.trees).each do |obj| restore File.join(path, obj.basename), file_path end else file = File.new file_path, 'w' file.write object.data file.close end end
ruby
{ "resource": "" }