_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q17700
Webrat.RailsAdapter.normalize_url
train
def normalize_url(href) #:nodoc: uri = URI.parse(href) normalized_url = [] normalized_url << "#{uri.scheme}://" if uri.scheme normalized_url << uri.host if uri.host normalized_url << ":#{uri.port}" if uri.port && ![80,443].include?(uri.port) normalized_url << uri.path if uri.path normalized_url << "?#{uri.query}" if uri.query normalized_url.join end
ruby
{ "resource": "" }
q17701
Webrat.Form.params
train
def params query_string = [] replaces = {} fields.each do |field| next if field.to_query_string.nil? replaces.merge!({field.digest_value => field.test_uploaded_file}) if field.is_a?(FileField) query_string << field.to_query_string end query_params = self.class.query_string_to_params(query_string.join('&')) query_params = self.class.replace_params_values(query_params, replaces) self.class.unescape_params(query_params) end
ruby
{ "resource": "" }
q17702
Webrat.Matchers.assert_have_selector
train
def assert_have_selector(name, attributes = {}, &block) matcher = HaveSelector.new(name, attributes, &block) assert matcher.matches?(response_body), matcher.failure_message end
ruby
{ "resource": "" }
q17703
Pod.TrySettings.prompt_for_permission
train
def prompt_for_permission UI.titled_section 'Running Pre-Install Commands' do commands = pre_install_commands.length > 1 ? 'commands' : 'command' UI.puts "In order to try this pod, CocoaPods-Try needs to run the following #{commands}:" pre_install_commands.each { |command| UI.puts " - #{command}" } UI.puts "\nPress return to run these #{commands}, or press `ctrl + c` to stop trying this pod." end # Give an elegant exit point. UI.gets.chomp end
ruby
{ "resource": "" }
q17704
Pod.TrySettings.run_pre_install_commands
train
def run_pre_install_commands(prompt) if pre_install_commands prompt_for_permission if prompt pre_install_commands.each { |command| Executable.execute_command('bash', ['-ec', command], true) } end end
ruby
{ "resource": "" }
q17705
TorqueBox.Logger.level=
train
def level=(new_level) if new_level.respond_to?(:to_int) new_level = STD_LOGGER_LEVELS[new_level] end LogbackUtil.set_log_level(@logger, new_level) end
ruby
{ "resource": "" }
q17706
TorqueBox.Daemon.start
train
def start @java_daemon.set_action do action end @java_daemon.set_error_callback do |_, err| on_error(err) end @java_daemon.set_stop_callback do |_| on_stop end @java_daemon.start self end
ruby
{ "resource": "" }
q17707
Readthis.Entity.load
train
def load(string) marshal, compress, value = decompose(string) marshal.load(inflate(value, compress)) rescue TypeError, NoMethodError string end
ruby
{ "resource": "" }
q17708
Readthis.Entity.decompose
train
def decompose(string) flags = string[0].unpack('C').first if flags < 16 marshal = serializers.rassoc(flags) compress = (flags & COMPRESSED_FLAG) != 0 [marshal, compress, string[1..-1]] else [@options[:marshal], @options[:compress], string] end end
ruby
{ "resource": "" }
q17709
Readthis.Cache.write
train
def write(key, value, options = {}) options = merged_options(options) invoke(:write, key) do |store| write_entity(key, value, store, options) end end
ruby
{ "resource": "" }
q17710
Readthis.Cache.delete
train
def delete(key, options = {}) namespaced = namespaced_key(key, merged_options(options)) invoke(:delete, key) do |store| store.del(namespaced) > 0 end end
ruby
{ "resource": "" }
q17711
Readthis.Cache.fetch
train
def fetch(key, options = {}) options ||= {} value = read(key, options) unless options[:force] if value.nil? && block_given? value = yield(key) write(key, value, options) end value end
ruby
{ "resource": "" }
q17712
Readthis.Cache.increment
train
def increment(key, amount = 1, options = {}) invoke(:increment, key) do |store| alter(store, key, amount, options) end end
ruby
{ "resource": "" }
q17713
Readthis.Cache.decrement
train
def decrement(key, amount = 1, options = {}) invoke(:decrement, key) do |store| alter(store, key, -amount, options) end end
ruby
{ "resource": "" }
q17714
Readthis.Cache.read_multi
train
def read_multi(*keys) options = merged_options(extract_options!(keys)) mapping = keys.map { |key| namespaced_key(key, options) } return {} if keys.empty? invoke(:read_multi, keys) do |store| values = store.mget(*mapping).map { |value| entity.load(value) } refresh_entity(mapping, store, options) zipped_results(keys, values, options) end end
ruby
{ "resource": "" }
q17715
Readthis.Cache.write_multi
train
def write_multi(hash, options = {}) options = merged_options(options) invoke(:write_multi, hash.keys) do |store| store.multi do hash.each { |key, value| write_entity(key, value, store, options) } end end end
ruby
{ "resource": "" }
q17716
Readthis.Cache.fetch_multi
train
def fetch_multi(*keys) options = extract_options!(keys).merge(retain_nils: true) results = read_multi(*keys, options) missing = {} invoke(:fetch_multi, keys) do |_store| results.each do |key, value| next unless value.nil? value = yield(key) missing[key] = value results[key] = value end end write_multi(missing, options) if missing.any? results end
ruby
{ "resource": "" }
q17717
Readthis.Cache.exist?
train
def exist?(key, options = {}) invoke(:exist?, key) do |store| store.exists(namespaced_key(key, merged_options(options))) end end
ruby
{ "resource": "" }
q17718
Readthis.Cache.clear
train
def clear(options = {}) invoke(:clear, '*') do |store| if options[:async] store.flushdb(async: true) else store.flushdb end end end
ruby
{ "resource": "" }
q17719
Searchlogic.RailsHelpers.fields_for
train
def fields_for(*args, &block) if search_obj = args.find { |arg| arg.is_a?(Searchlogic::Search) } args.unshift(:search) if args.first == search_obj options = args.extract_options! if !options[:skip_order_field] concat(content_tag("div", hidden_field_tag("#{args.first}[order]", search_obj.order), :style => "display: inline")) end args << options super else super end end
ruby
{ "resource": "" }
q17720
Petrovich.RuleSet.load_case_rules!
train
def load_case_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| [:exceptions, :suffixes].each do |section| entries = rules[name_part.to_s][section.to_s] next if entries.nil? entries.each do |entry| load_case_entry(name_part, section, entry) end end end end
ruby
{ "resource": "" }
q17721
Petrovich.RuleSet.load_gender_rules!
train
def load_gender_rules!(rules) [:lastname, :firstname, :middlename].each do |name_part| Petrovich::GENDERS.each do |section| entries = rules['gender'][name_part.to_s]['suffixes'][section.to_s] Array(entries).each do |entry| load_gender_entry(name_part, section, entry) end exceptions = rules['gender'][name_part.to_s]['exceptions'] @gender_exceptions[name_part] ||= {} next if exceptions.nil? Array(exceptions[section.to_s]).each do |exception| @gender_exceptions[name_part][exception] = Gender::Rule.new(as: name_part, gender: section, suffix: exception) end end end @gender_rules.each do |_, gender_rules| gender_rules.sort_by!{ |rule| -rule.accuracy } end end
ruby
{ "resource": "" }
q17722
Pact.QueryHash.difference
train
def difference(other) require 'pact/matchers' # avoid recursive loop between this file, pact/reification and pact/matchers Pact::Matchers.diff(query, symbolize_keys(CGI::parse(other.query)), allow_unexpected_keys: false) end
ruby
{ "resource": "" }
q17723
GovukPublishingComponents.ComponentExample.html_safe_strings
train
def html_safe_strings(obj) if obj.is_a?(String) obj.html_safe elsif obj.is_a?(Hash) obj.each do |key, value| obj[key] = html_safe_strings(value) end elsif obj.is_a?(Array) obj.map! { |e| html_safe_strings(e) } else obj end end
ruby
{ "resource": "" }
q17724
RVC.CommandSlate.opts
train
def opts name, &b fail "command name must be a symbol" unless name.is_a? Symbol if name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name})" end parser = OptionParser.new name.to_s, @ns.shell.fs, &b summary = parser.summary? parser.specs.each do |opt_name,spec| if opt_name.to_s =~ /[A-Z]/ fail "Camel-casing is not allowed (#{name} option #{opt_name})" end end @ns.commands[name] = Command.new @ns, name, summary, parser end
ruby
{ "resource": "" }
q17725
Stream.Activities.get_activities
train
def get_activities(params = {}) if params[:foreign_id_times] foreign_ids = [] timestamps = [] params[:foreign_id_times].each{|e| foreign_ids << e[:foreign_id] timestamps << e[:time] } params = { foreign_ids: foreign_ids, timestamps: timestamps, } end signature = Stream::Signer.create_jwt_token('activities', '*', @api_secret, '*') make_request(:get, '/activities/', signature, params) end
ruby
{ "resource": "" }
q17726
RVC.FS.traverse
train
def traverse base, arcs objs = [base] arcs.each_with_index do |arc,i| objs.map! { |obj| traverse_one obj, arc, i==0 } objs.flatten! end objs end
ruby
{ "resource": "" }
q17727
Stream.Batch.follow_many
train
def follow_many(follows, activity_copy_limit = nil) query_params = {} unless activity_copy_limit.nil? query_params['activity_copy_limit'] = activity_copy_limit end signature = Stream::Signer.create_jwt_token('follower', '*', @api_secret, '*') make_request(:post, '/follow_many/', signature, query_params, follows) end
ruby
{ "resource": "" }
q17728
Stream.Batch.add_to_many
train
def add_to_many(activity_data, feeds) data = { :feeds => feeds, :activity => activity_data } signature = Stream::Signer.create_jwt_token('feed', '*', @api_secret, '*') make_request(:post, '/feed/add_to_many/', signature, {}, data) end
ruby
{ "resource": "" }
q17729
MaRuKu::In::Markdown::SpanLevelParser.HTMLHelper.close_script_style
train
def close_script_style tag = @tag_stack.last # See http://www.w3.org/TR/xhtml1/#C_4 for character sequences not allowed within an element body. if @already =~ /<|&|\]\]>|--/ new_already = script_style_cdata_start(tag) new_already << "\n" unless @already.start_with?("\n") new_already << @already new_already << "\n" unless @already.end_with?("\n") new_already << script_style_cdata_end(tag) @already = new_already end @before_already << @already @already = @before_already end
ruby
{ "resource": "" }
q17730
MaRuKu.Errors.maruku_error
train
def maruku_error(s, src=nil, con=nil, recover=nil) policy = get_setting(:on_error) case policy when :ignore when :raise raise_error create_frame(describe_error(s, src, con, recover)) when :warning tell_user create_frame(describe_error(s, src, con, recover)) else raise "Unknown on_error policy: #{policy.inspect}" end end
ruby
{ "resource": "" }
q17731
MaRuKu.Strings.spaces_before_first_char
train
def spaces_before_first_char(s) s = MaRuKu::MDLine.new(s.gsub(/([^\t]*)(\t)/) { $1 + " " * (TAB_SIZE - $1.length % TAB_SIZE) }) match = case s.md_type when :ulist # whitespace, followed by ('*'|'+'|'-') followed by # more whitespace, followed by an optional IAL, followed # by yet more whitespace s[/^\s*(\*|\+|\-)\s*(\{[:#\.].*?\})?\s*/] when :olist # whitespace, followed by a number, followed by a period, # more whitespace, an optional IAL, and more whitespace s[/^\s*\d+\.\s*(\{[:#\.].*?\})?\s*/] else tell_user "BUG (my bad): '#{s}' is not a list" '' end f = /\{(.*?)\}/.match(match) ial = f[1] if f [match.length, ial] end
ruby
{ "resource": "" }
q17732
MaRuKu.MDDocument.t2_parse_blocks
train
def t2_parse_blocks(src, output) while src.cur_line l = src.shift_line # ignore empty line if l.t2_empty? then src.shift_line next end # TODO: lists # TODO: xml # TODO: `==` signature, l = if l.t2_contains_signature? l.t2_get_signature else [Textile2Signature.new, l] end if handling = T2_Handling.has_key?(signature.block_name) if self.responds_to? handling.method # read as many non-empty lines that you can lines = [l] if handling.parse_lines while not src.cur_line.t2_empty? lines.push src.shift_line end end self.send(handling.method, src, output, signature, lines) else maruku_error("We don't know about method #{handling.method.inspect}") next end end end end
ruby
{ "resource": "" }
q17733
MaRuKu.NokogiriHTMLFragment.to_html
train
def to_html output_options = Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^ Nokogiri::XML::Node::SaveOptions::FORMAT @fragment.children.inject("") do |out, child| out << child.serialize(:save_with => output_options, :encoding => 'UTF-8') end end
ruby
{ "resource": "" }
q17734
MaRuKu.NokogiriHTMLFragment.span_descendents
train
def span_descendents(e) ns = Nokogiri::XML::NodeSet.new(Nokogiri::XML::Document.new) e.element_children.inject(ns) do |descendents, c| if HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end descendents end end
ruby
{ "resource": "" }
q17735
MaRuKu.REXMLHTMLFragment.span_descendents
train
def span_descendents(e) descendents = [] e.each_element do |c| name = c.respond_to?(:name) ? c.name : nil if name && HTML_INLINE_ELEMS.include?(c.name) descendents << c descendents += span_descendents(c) end end end
ruby
{ "resource": "" }
q17736
Staccato.Timing.track!
train
def track!(&block) if block_given? start_at = Time.now block.call end_at = Time.now self.options.time = (end_at - start_at).to_i*1000 end super end
ruby
{ "resource": "" }
q17737
Staccato.Hit.params
train
def params {}. merge!(base_params). merge!(tracker_default_params). merge!(global_options_params). merge!(hit_params). merge!(custom_dimensions). merge!(custom_metrics). merge!(measurement_params). reject {|_,v| v.nil?} end
ruby
{ "resource": "" }
q17738
Staccato.Hit.add_measurement
train
def add_measurement(key, options = {}) if options.is_a?(Hash) self.measurements << Measurement.lookup(key).new(options) else self.measurements << options end end
ruby
{ "resource": "" }
q17739
Staccato.Measurable.params
train
def params {}. merge!(measurable_params). merge!(custom_dimensions). merge!(custom_metrics). reject {|_,v| v.nil?} end
ruby
{ "resource": "" }
q17740
Breakfast.Manifest.clean!
train
def clean! files_to_keep = cache.keys.concat(cache.values) if (sprockets_manifest = Dir.entries("#{base_dir}").detect { |entry| entry =~ SPROCKETS_MANIFEST_REGEX }) files_to_keep.concat(JSON.parse(File.read("#{base_dir}/#{sprockets_manifest}")).fetch("files", {}).keys) end Dir["#{base_dir}/**/*"].each do |path| next if File.directory?(path) || files_to_keep.include?(Pathname(path).relative_path_from(base_dir).to_s) FileUtils.rm(path) end end
ruby
{ "resource": "" }
q17741
Breakfast.Manifest.nuke!
train
def nuke! Dir["#{base_dir}/**/*"] .select { |path| path =~ FINGERPRINT_REGEX } .each { |file| FileUtils.rm(file) } FileUtils.rm(manifest_path) end
ruby
{ "resource": "" }
q17742
XeroGateway.LineItem.valid?
train
def valid? @errors = [] if !line_item_id.nil? && line_item_id !~ GUID_REGEX @errors << ['line_item_id', 'must be blank or a valid Xero GUID'] end unless description @errors << ['description', "can't be blank"] end if tax_type && !TAX_TYPE[tax_type] @errors << ['tax_type', "must be one of #{TAX_TYPE.keys.join('/')}"] end @errors.size == 0 end
ruby
{ "resource": "" }
q17743
XeroGateway.AccountsList.find_all_by_type
train
def find_all_by_type(account_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.type == account_type list end end
ruby
{ "resource": "" }
q17744
XeroGateway.AccountsList.find_all_by_tax_type
train
def find_all_by_tax_type(tax_type) raise AccountsListNotLoadedError unless loaded? @accounts.inject([]) do | list, account | list << account if account.tax_type == tax_type list end end
ruby
{ "resource": "" }
q17745
XeroGateway.Contact.valid?
train
def valid? @errors = [] if !contact_id.nil? && contact_id !~ GUID_REGEX @errors << ['contact_id', 'must be blank or a valid Xero GUID'] end if status && !CONTACT_STATUS[status] @errors << ['status', "must be one of #{CONTACT_STATUS.keys.join('/')}"] end unless name @errors << ['name', "can't be blank"] end # Make sure all addresses are correct. unless addresses.all? { | address | address.valid? } @errors << ['addresses', 'at least one address is invalid'] end # Make sure all phone numbers are correct. unless phones.all? { | phone | phone.valid? } @errors << ['phones', 'at least one phone is invalid'] end @errors.size == 0 end
ruby
{ "resource": "" }
q17746
XeroGateway.Gateway.get_contacts
train
def get_contacts(options = {}) request_params = {} if !options[:updated_after].nil? warn '[warning] :updated_after is depracated in XeroGateway#get_contacts. Use :modified_since' options[:modified_since] = options.delete(:updated_after) end request_params[:ContactID] = options[:contact_id] if options[:contact_id] request_params[:ContactNumber] = options[:contact_number] if options[:contact_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/Contacts", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contacts'}) end
ruby
{ "resource": "" }
q17747
XeroGateway.Gateway.build_contact
train
def build_contact(contact = {}) case contact when Contact then contact.gateway = self when Hash then contact = Contact.new(contact.merge({:gateway => self})) end contact end
ruby
{ "resource": "" }
q17748
XeroGateway.Gateway.update_contact
train
def update_contact(contact) raise "contact_id or contact_number is required for updating contacts" if contact.contact_id.nil? and contact.contact_number.nil? save_contact(contact) end
ruby
{ "resource": "" }
q17749
XeroGateway.Gateway.update_contacts
train
def update_contacts(contacts) b = Builder::XmlMarkup.new request_xml = b.Contacts { contacts.each do | contact | contact.to_xml(b) end } response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'POST/contacts'}) response.contacts.each_with_index do | response_contact, index | contacts[index].contact_id = response_contact.contact_id if response_contact && response_contact.contact_id end response end
ruby
{ "resource": "" }
q17750
XeroGateway.Gateway.get_contact_groups
train
def get_contact_groups(options = {}) request_params = {} request_params[:ContactGroupID] = options[:contact_group_id] if options[:contact_group_id] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/ContactGroups", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroups'}) end
ruby
{ "resource": "" }
q17751
XeroGateway.Gateway.get_contact_group_by_id
train
def get_contact_group_by_id(contact_group_id) request_params = { :ContactGroupID => contact_group_id } response_xml = http_get(@client, "#{@xero_url}/ContactGroups/#{CGI.escape(contact_group_id)}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contactgroup'}) end
ruby
{ "resource": "" }
q17752
XeroGateway.Gateway.get_invoices
train
def get_invoices(options = {}) request_params = {} request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id] request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:IDs] = Array(options[:invoice_ids]).join(",") if options[:invoice_ids] request_params[:InvoiceNumbers] = Array(options[:invoice_numbers]).join(",") if options[:invoice_numbers] request_params[:ContactIDs] = Array(options[:contact_ids]).join(",") if options[:contact_ids] request_params[:page] = options[:page] if options[:page] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'}) end
ruby
{ "resource": "" }
q17753
XeroGateway.Gateway.get_invoice
train
def get_invoice(invoice_id_or_number, format = :xml) request_params = {} headers = {} headers.merge!("Accept" => "application/pdf") if format == :pdf url = "#{@xero_url}/Invoices/#{CGI.escape(invoice_id_or_number)}" response = http_get(@client, url, request_params, headers) if format == :pdf Tempfile.open(invoice_id_or_number) do |f| f.write(response) f end else parse_response(response, {:request_params => request_params}, {:request_signature => 'GET/Invoice'}) end end
ruby
{ "resource": "" }
q17754
XeroGateway.Gateway.build_invoice
train
def build_invoice(invoice = {}) case invoice when Invoice then invoice.gateway = self when Hash then invoice = Invoice.new(invoice.merge(:gateway => self)) end invoice end
ruby
{ "resource": "" }
q17755
XeroGateway.Gateway.create_invoices
train
def create_invoices(invoices) b = Builder::XmlMarkup.new request_xml = b.Invoices { invoices.each do | invoice | invoice.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/Invoices?SummarizeErrors=false", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'}) response.invoices.each_with_index do | response_invoice, index | invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id end response end
ruby
{ "resource": "" }
q17756
XeroGateway.Gateway.get_credit_notes
train
def get_credit_notes(options = {}) request_params = {} request_params[:CreditNoteID] = options[:credit_note_id] if options[:credit_note_id] request_params[:CreditNoteNumber] = options[:credit_note_number] if options[:credit_note_number] request_params[:order] = options[:order] if options[:order] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/CreditNotes", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNotes'}) end
ruby
{ "resource": "" }
q17757
XeroGateway.Gateway.get_credit_note
train
def get_credit_note(credit_note_id_or_number) request_params = {} url = "#{@xero_url}/CreditNotes/#{CGI.escape(credit_note_id_or_number)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/CreditNote'}) end
ruby
{ "resource": "" }
q17758
XeroGateway.Gateway.build_credit_note
train
def build_credit_note(credit_note = {}) case credit_note when CreditNote then credit_note.gateway = self when Hash then credit_note = CreditNote.new(credit_note.merge(:gateway => self)) end credit_note end
ruby
{ "resource": "" }
q17759
XeroGateway.Gateway.create_credit_note
train
def create_credit_note(credit_note) request_xml = credit_note.to_xml response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_note'}) # Xero returns credit_notes inside an <CreditNotes> tag, even though there's only ever # one for this request response.response_item = response.credit_notes.first if response.success? && response.credit_note && response.credit_note.credit_note_id credit_note.credit_note_id = response.credit_note.credit_note_id end response end
ruby
{ "resource": "" }
q17760
XeroGateway.Gateway.create_credit_notes
train
def create_credit_notes(credit_notes) b = Builder::XmlMarkup.new request_xml = b.CreditNotes { credit_notes.each do | credit_note | credit_note.to_xml(b) end } response_xml = http_put(@client, "#{@xero_url}/CreditNotes", request_xml, {}) response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/credit_notes'}) response.credit_notes.each_with_index do | response_credit_note, index | credit_notes[index].credit_note_id = response_credit_note.credit_note_id if response_credit_note && response_credit_note.credit_note_id end response end
ruby
{ "resource": "" }
q17761
XeroGateway.Gateway.get_bank_transactions
train
def get_bank_transactions(options = {}) request_params = {} request_params[:BankTransactionID] = options[:bank_transaction_id] if options[:bank_transaction_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] request_params[:page] = options[:page] if options[:page] response_xml = http_get(@client, "#{@xero_url}/BankTransactions", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransactions'}) end
ruby
{ "resource": "" }
q17762
XeroGateway.Gateway.get_bank_transaction
train
def get_bank_transaction(bank_transaction_id) request_params = {} url = "#{@xero_url}/BankTransactions/#{CGI.escape(bank_transaction_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/BankTransaction'}) end
ruby
{ "resource": "" }
q17763
XeroGateway.Gateway.get_manual_journals
train
def get_manual_journals(options = {}) request_params = {} request_params[:ManualJournalID] = options[:manual_journal_id] if options[:manual_journal_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] response_xml = http_get(@client, "#{@xero_url}/ManualJournals", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournals'}) end
ruby
{ "resource": "" }
q17764
XeroGateway.Gateway.get_manual_journal
train
def get_manual_journal(manual_journal_id) request_params = {} url = "#{@xero_url}/ManualJournals/#{CGI.escape(manual_journal_id)}" response_xml = http_get(@client, url, request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/ManualJournal'}) end
ruby
{ "resource": "" }
q17765
XeroGateway.Gateway.create_payment
train
def create_payment(payment) b = Builder::XmlMarkup.new request_xml = b.Payments do payment.to_xml(b) end response_xml = http_put(@client, "#{xero_url}/Payments", request_xml) parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/payments'}) end
ruby
{ "resource": "" }
q17766
XeroGateway.Gateway.get_payments
train
def get_payments(options = {}) request_params = {} request_params[:PaymentID] = options[:payment_id] if options[:payment_id] request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since] request_params[:order] = options[:order] if options[:order] request_params[:where] = options[:where] if options[:where] response_xml = http_get(@client, "#{@xero_url}/Payments", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
ruby
{ "resource": "" }
q17767
XeroGateway.Gateway.get_payment
train
def get_payment(payment_id, options = {}) request_params = {} response_xml = http_get(client, "#{@xero_url}/Payments/#{payment_id}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payments'}) end
ruby
{ "resource": "" }
q17768
XeroGateway.Gateway.get_payroll_calendars
train
def get_payroll_calendars(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayrollCalendars", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/payroll_calendars'}) end
ruby
{ "resource": "" }
q17769
XeroGateway.Gateway.get_pay_runs
train
def get_pay_runs(options = {}) request_params = {} response_xml = http_get(client, "#{@payroll_url}/PayRuns", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/pay_runs'}) end
ruby
{ "resource": "" }
q17770
XeroGateway.Gateway.get_report
train
def get_report(id_or_name, options={}) request_params = options.inject({}) do |params, (key, val)| xero_key = key.to_s.camelize.gsub(/id/i, "ID").to_sym params[xero_key] = val params end response_xml = http_get(@client, "#{@xero_url}/reports/#{id_or_name}", request_params) parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/reports'}) end
ruby
{ "resource": "" }
q17771
XeroGateway.Gateway.save_contact
train
def save_contact(contact) request_xml = contact.to_xml response_xml = nil create_or_save = nil if contact.contact_id.nil? && contact.contact_number.nil? # Create new contact record. response_xml = http_put(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :create else # Update existing contact record. response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/contact"}) contact.contact_id = response.contact.contact_id if response.contact && response.contact.contact_id response end
ruby
{ "resource": "" }
q17772
XeroGateway.Gateway.save_invoice
train
def save_invoice(invoice) request_xml = invoice.to_xml response_xml = nil create_or_save = nil if invoice.invoice_id.nil? # Create new invoice record. response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :create else # Update existing invoice record. response_xml = http_post(@client, "#{@xero_url}/Invoices", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/invoice"}) # Xero returns invoices inside an <Invoices> tag, even though there's only ever # one for this request response.response_item = response.invoices.first if response.success? && response.invoice && response.invoice.invoice_id invoice.invoice_id = response.invoice.invoice_id end response end
ruby
{ "resource": "" }
q17773
XeroGateway.Gateway.save_bank_transaction
train
def save_bank_transaction(bank_transaction) request_xml = bank_transaction.to_xml response_xml = nil create_or_save = nil if bank_transaction.bank_transaction_id.nil? # Create new bank transaction record. response_xml = http_put(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :create else # Update existing bank transaction record. response_xml = http_post(@client, "#{@xero_url}/BankTransactions", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/BankTransactions"}) # Xero returns bank transactions inside an <BankTransactions> tag, even though there's only ever # one for this request response.response_item = response.bank_transactions.first if response.success? && response.bank_transaction && response.bank_transaction.bank_transaction_id bank_transaction.bank_transaction_id = response.bank_transaction.bank_transaction_id end response end
ruby
{ "resource": "" }
q17774
XeroGateway.Gateway.save_manual_journal
train
def save_manual_journal(manual_journal) request_xml = manual_journal.to_xml response_xml = nil create_or_save = nil if manual_journal.manual_journal_id.nil? # Create new manual journal record. response_xml = http_put(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :create else # Update existing manual journal record. response_xml = http_post(@client, "#{@xero_url}/ManualJournals", request_xml, {}) create_or_save = :save end response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/ManualJournals"}) # Xero returns manual journals inside an <ManualJournals> tag, even though there's only ever # one for this request response.response_item = response.manual_journals.first manual_journal.manual_journal_id = response.manual_journal.manual_journal_id if response.success? && response.manual_journal && response.manual_journal.manual_journal_id response end
ruby
{ "resource": "" }
q17775
XeroGateway.CreditNote.build_contact
train
def build_contact(params = {}) self.contact = gateway ? gateway.build_contact(params) : Contact.new(params) end
ruby
{ "resource": "" }
q17776
XeroGateway.OAuth.renew_access_token
train
def renew_access_token(access_token = nil, access_secret = nil, session_handle = nil) access_token ||= @atoken access_secret ||= @asecret session_handle ||= @session_handle old_token = ::OAuth::RequestToken.new(consumer, access_token, access_secret) # Underlying oauth consumer accepts body params and headers for request via positional params - explicit nilling of # body parameters allows for correct position for headers access_token = old_token.get_access_token({ :oauth_session_handle => session_handle, :token => old_token }, nil, @base_headers) update_attributes_from_token(access_token) rescue ::OAuth::Unauthorized => e # If the original access token is for some reason invalid an OAuth::Unauthorized could be raised. # In this case raise a XeroGateway::OAuth::TokenInvalid which can be captured by the caller. In this # situation the end user will need to re-authorize the application via the request token authorization URL raise XeroGateway::OAuth::TokenInvalid.new(e.message) end
ruby
{ "resource": "" }
q17777
XeroGateway.OAuth.update_attributes_from_token
train
def update_attributes_from_token(access_token) @expires_at = Time.now + access_token.params[:oauth_expires_in].to_i @authorization_expires_at = Time.now + access_token.params[:oauth_authorization_expires_in].to_i @session_handle = access_token.params[:oauth_session_handle] @atoken, @asecret = access_token.token, access_token.secret @access_token = nil end
ruby
{ "resource": "" }
q17778
XeroGateway.BankTransaction.valid?
train
def valid? @errors = [] if !bank_transaction_id.nil? && bank_transaction_id !~ GUID_REGEX @errors << ['bank_transaction_id', 'must be blank or a valid Xero GUID'] end if type && !TYPES[type] @errors << ['type', "must be one of #{TYPES.keys.join('/')}"] end if status && !STATUSES[status] @errors << ['status', "must be one of #{STATUSES.keys.join('/')}"] end unless date @errors << ['date', "can't be blank"] end # Make sure contact is valid. unless @contact && @contact.valid? @errors << ['contact', 'is invalid'] end # Make sure all line_items are valid. unless line_items.all? { | line_item | line_item.valid? } @errors << ['line_items', "at least one line item invalid"] end @errors.size == 0 end
ruby
{ "resource": "" }
q17779
XeroGateway.ManualJournal.valid?
train
def valid? @errors = [] if !manual_journal_id.nil? && manual_journal_id !~ GUID_REGEX @errors << ['manual_journal_id', 'must be blank or a valid Xero GUID'] end if narration.blank? @errors << ['narration', "can't be blank"] end unless date @errors << ['date', "can't be blank"] end # Make sure all journal_items are valid. unless journal_lines.all? { | journal_line | journal_line.valid? } @errors << ['journal_lines', "at least one journal line invalid"] end # make sure there are at least 2 journal lines unless journal_lines.length > 1 @errors << ['journal_lines', "journal must contain at least two individual journal lines"] end if journal_lines.length > 100 @errors << ['journal_lines', "journal must contain less than one hundred journal lines"] end unless journal_lines.sum(&:line_amount).to_f == 0.0 @errors << ['journal_lines', "the total debits must be equal to total credits"] end @errors.size == 0 end
ruby
{ "resource": "" }
q17780
XeroGateway.TrackingCategory.to_xml_for_invoice_messages
train
def to_xml_for_invoice_messages(b = Builder::XmlMarkup.new) b.TrackingCategory { b.TrackingCategoryID self.tracking_category_id unless tracking_category_id.nil? b.Name self.name b.Option self.options.is_a?(Array) ? self.options.first : self.options.to_s } end
ruby
{ "resource": "" }
q17781
GoogleVisualr.BaseChart.to_js
train
def to_js(element_id) js = "" js << "\n<script type='text/javascript'>" js << load_js(element_id) js << draw_js(element_id) js << "\n</script>" js end
ruby
{ "resource": "" }
q17782
GoogleVisualr.BaseChart.draw_js
train
def draw_js(element_id) js = "" js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{@data_table.to_js}" js << "\n var chart = new google.#{chart_class}.#{chart_name}(document.getElementById('#{element_id}'));" @listeners.each do |listener| js << "\n google.visualization.events.addListener(chart, '#{listener[:event]}', #{listener[:callback]});" end js << "\n chart.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
ruby
{ "resource": "" }
q17783
GoogleVisualr.DataTable.new_columns
train
def new_columns(columns) columns.each do |column| new_column(column[:type], column[:label], column[:id], column[:role], column[:pattern]) end end
ruby
{ "resource": "" }
q17784
GoogleVisualr.DataTable.set_column
train
def set_column(column_index, column_values) if @rows.size < column_values.size 1.upto(column_values.size - @rows.size) { @rows << Array.new } end column_values.each_with_index do |column_value, row_index| set_cell(row_index, column_index, column_value) end end
ruby
{ "resource": "" }
q17785
GoogleVisualr.DataTable.add_row
train
def add_row(row_values=[]) @rows << Array.new row_index = @rows.size-1 row_values.each_with_index do |row_value, column_index| set_cell(row_index, column_index, row_value) end end
ruby
{ "resource": "" }
q17786
GoogleVisualr.DataTable.add_rows
train
def add_rows(array_or_num) if array_or_num.is_a?(Array) array_or_num.each do |row| add_row(row) end else array_or_num.times do add_row end end end
ruby
{ "resource": "" }
q17787
GoogleVisualr.DataTable.get_cell
train
def get_cell(row_index, column_index) if within_range?(row_index, column_index) @rows[row_index][column_index].v else raise RangeError, "row_index and column_index MUST be < @rows.size and @cols.size", caller end end
ruby
{ "resource": "" }
q17788
GoogleVisualr.DataTable.to_js
train
def to_js js = "var data_table = new google.visualization.DataTable();" @cols.each do |column| js << "data_table.addColumn(" js << display(column) js << ");" end @rows.each do |row| js << "data_table.addRow(" js << "[#{row.map(&:to_js).join(", ")}]" unless row.empty? js << ");" end if @formatters @formatters.each do |formatter| js << formatter.to_js end end js end
ruby
{ "resource": "" }
q17789
Sfn.Callback.run_action
train
def run_action(msg) ui.info("#{msg}... ", :nonewline) begin result = yield ui.puts ui.color("complete!", :green, :bold) result rescue => e ui.puts ui.color("error!", :red, :bold) ui.error "Reason - #{e}" raise end end
ruby
{ "resource": "" }
q17790
Sfn.Provider.save_expanded_stack
train
def save_expanded_stack(stack_id, stack_attributes) current_stacks = MultiJson.load(cached_stacks) cache.locked_action(:stacks_lock) do logger.info "Saving expanded stack attributes in cache (#{stack_id})" current_stacks[stack_id] = stack_attributes.merge("Cached" => Time.now.to_i) cache[:stacks].value = MultiJson.dump(current_stacks) end true end
ruby
{ "resource": "" }
q17791
Sfn.Provider.remove_stack
train
def remove_stack(stack_id) current_stacks = MultiJson.load(cached_stacks) logger.info "Attempting to remove stack from internal cache (#{stack_id})" cache.locked_action(:stacks_lock) do val = current_stacks.delete(stack_id) logger.info "Successfully removed stack from internal cache (#{stack_id})" cache[:stacks].value = MultiJson.dump(current_stacks) !!val end end
ruby
{ "resource": "" }
q17792
Sfn.Provider.expand_stack
train
def expand_stack(stack) logger.info "Stack expansion requested (#{stack.id})" if ((stack.in_progress? && Time.now.to_i - stack.attributes["Cached"].to_i > stack_expansion_interval) || !stack.attributes["Cached"]) begin expanded = false cache.locked_action(:stack_expansion_lock) do expanded = true stack.reload stack.data["Cached"] = Time.now.to_i end if expanded save_expanded_stack(stack.id, stack.to_json) end rescue => e logger.error "Stack expansion failed (#{stack.id}) - #{e.class}: #{e}" end else logger.info "Stack has been cached within expand interval. Expansion prevented. (#{stack.id})" end end
ruby
{ "resource": "" }
q17793
Sfn.Provider.fetch_stacks
train
def fetch_stacks(stack_id = nil) cache.locked_action(:stacks_lock) do logger.info "Lock aquired for stack update. Requesting stacks from upstream. (#{Thread.current})" if stack_id single_stack = connection.stacks.get(stack_id) stacks = single_stack ? {single_stack.id => single_stack} : {} else stacks = Hash[ connection.stacks.reload.all.map do |stack| [stack.id, stack.attributes] end ] end if cache[:stacks].value existing_stacks = MultiJson.load(cache[:stacks].value) # Force common types stacks = MultiJson.load(MultiJson.dump(stacks)) if stack_id stacks = existing_stacks.to_smash.deep_merge(stacks) else # Remove stacks that have been deleted stale_ids = existing_stacks.keys - stacks.keys stacks = existing_stacks.to_smash.deep_merge(stacks) stale_ids.each do |stale_id| stacks.delete(stale_id) end end end cache[:stacks].value = stacks.to_json logger.info "Stack list has been updated from upstream and cached locally" end @initial_fetch_complete = true end
ruby
{ "resource": "" }
q17794
Sfn.Provider.update_stack_list!
train
def update_stack_list! if updater.nil? || !updater.alive? self.updater = Thread.new { loop do begin fetch_stacks sleep(stack_list_interval) rescue => e logger.error "Failure encountered on stack fetch: #{e.class} - #{e}" end end } true else false end end
ruby
{ "resource": "" }
q17795
Sfn.Command.load_api_provider_extensions!
train
def load_api_provider_extensions! if config.get(:credentials, :provider) base_ext = Bogo::Utility.camel(config.get(:credentials, :provider)).to_sym targ_ext = self.class.name.split("::").last if ApiProvider.constants.include?(base_ext) base_module = ApiProvider.const_get(base_ext) ui.debug "Loading core provider extensions via `#{base_module}`" extend base_module if base_module.constants.include?(targ_ext) targ_module = base_module.const_get(targ_ext) ui.debug "Loading targeted provider extensions via `#{targ_module}`" extend targ_module end true end end end
ruby
{ "resource": "" }
q17796
Sfn.Command.discover_config
train
def discover_config(opts) cwd = Dir.pwd.split(File::SEPARATOR) detected_path = "" until cwd.empty? || File.exists?(detected_path.to_s) detected_path = Dir.glob( (cwd + ["#{CONFIG_BASE_NAME}{#{VALID_CONFIG_EXTENSIONS.join(",")}}"]).join( File::SEPARATOR ) ).first cwd.pop end if opts.respond_to?(:fetch_option) opts.fetch_option("config").value = detected_path if detected_path else opts["config"] = detected_path if detected_path end opts end
ruby
{ "resource": "" }
q17797
Sfn.Cache.init
train
def init(name, kind, args = {}) get_storage(self.class.type, kind, name, args) true end
ruby
{ "resource": "" }
q17798
Sfn.Cache.get_storage
train
def get_storage(store_type, data_type, name, args = {}) full_name = "#{key}_#{name}" result = nil case store_type.to_sym when :redis result = get_redis_storage(data_type, full_name.to_s, args) when :local @_local_cache ||= {} unless @_local_cache[full_name.to_s] @_local_cache[full_name.to_s] = get_local_storage(data_type, full_name.to_s, args) end result = @_local_cache[full_name.to_s] else raise TypeError.new("Unsupported caching storage type encountered: #{store_type}") end unless full_name == "#{key}_registry_#{key}" registry[name.to_s] = data_type end result end
ruby
{ "resource": "" }
q17799
Sfn.Cache.get_redis_storage
train
def get_redis_storage(data_type, full_name, args = {}) self.class.redis_ping! case data_type.to_sym when :array Redis::List.new(full_name, {:marshal => true}.merge(args)) when :hash Redis::HashKey.new(full_name) when :value Redis::Value.new(full_name, {:marshal => true}.merge(args)) when :lock Redis::Lock.new(full_name, {:expiration => 60, :timeout => 0.1}.merge(args)) when :stamped Stamped.new(full_name.sub("#{key}_", "").to_sym, get_redis_storage(:value, full_name), self) else raise TypeError.new("Unsupported caching data type encountered: #{data_type}") end end
ruby
{ "resource": "" }