_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q18500
Goodreads.Groups.group
train
def group(group_id) data = request("/group/show", id: group_id) Hashie::Mash.new(data["group"]) end
ruby
{ "resource": "" }
q18501
Goodreads.Groups.group_list
train
def group_list(user_id, sort = "my_activity") data = request("/group/list", id: user_id, sort: sort) Hashie::Mash.new(data["groups"]["list"]) end
ruby
{ "resource": "" }
q18502
Goodreads.Users.user
train
def user(id) data = request("/user/show", id: id) Hashie::Mash.new(data["user"]) end
ruby
{ "resource": "" }
q18503
Goodreads.Friends.friends
train
def friends(user_id, options={}) data = oauth_request("/friend/user/#{user_id}", options) Hashie::Mash.new(data["friends"]) end
ruby
{ "resource": "" }
q18504
Goodreads.Reviews.recent_reviews
train
def recent_reviews(params = {}) skip_cropped = params.delete(:skip_cropped) || false data = request("/review/recent_reviews", params) return unless data["reviews"] && data["reviews"].key?("review") reviews = data["reviews"]["review"].map { |r| Hashie::Mash.new(r) } reviews = reviews.select { |r| !r.body.include?(r.url) } if skip_cropped reviews end
ruby
{ "resource": "" }
q18505
Goodreads.Reviews.review
train
def review(id) data = request("/review/show", id: id) Hashie::Mash.new(data["review"]) end
ruby
{ "resource": "" }
q18506
Goodreads.Reviews.reviews
train
def reviews(params = {}) data = request("/review/list", params.merge(v: "2")) reviews = data["reviews"]["review"] if reviews.present? reviews.map { |review| Hashie::Mash.new(review) } else [] end end
ruby
{ "resource": "" }
q18507
Goodreads.Reviews.user_review
train
def user_review(user_id, book_id, params = {}) data = request('/review/show_by_user_and_book.xml', params.merge(v: "2", user_id: user_id, book_id: book_id)) Hashie::Mash.new(data["review"]) end
ruby
{ "resource": "" }
q18508
Goodreads.Reviews.create_review
train
def create_review(book_id, params = {}) params = params.merge(book_id: book_id, v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] data = oauth_request_method(:post, '/review.xml', params) Hashie::Mash.new(data["review"]) end
ruby
{ "resource": "" }
q18509
Goodreads.Reviews.edit_review
train
def edit_review(review_id, params = {}) params = params.merge(v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] # Documentation says that you should use HTTP PUT, but API returns # 401 Unauthorized when PUT is used instead of POST data = oauth_request_method(:post, "/review/#{review_id}.xml", params) Hashie::Mash.new(data["review"]) end
ruby
{ "resource": "" }
q18510
Goodreads.Books.search_books
train
def search_books(query, params = {}) params[:q] = query.to_s.strip data = request("/search/index", params) Hashie::Mash.new(data["search"]) end
ruby
{ "resource": "" }
q18511
Goodreads.Authors.author
train
def author(id, params = {}) params[:id] = id data = request("/author/show", params) Hashie::Mash.new(data["author"]) end
ruby
{ "resource": "" }
q18512
Goodreads.Authors.author_by_name
train
def author_by_name(name, params = {}) params[:id] = name name_encoded = URI.encode(name) data = request("/api/author_url/#{name_encoded}", params) Hashie::Mash.new(data["author"]) end
ruby
{ "resource": "" }
q18513
PacketGen.Packet.insert
train
def insert(prev, protocol, options={}) klass = check_protocol(protocol) nxt = prev.body header = klass.new(options.merge!(packet: self)) add_header header, previous_header: prev idx = headers.index(prev) + 1 headers[idx, 0] = header header[:body] = nxt self end
ruby
{ "resource": "" }
q18514
PacketGen.Packet.encapsulate
train
def encapsulate(other, parsing: false) other.headers.each_with_index do |h, i| add_header h, parsing: (i > 0) || parsing end end
ruby
{ "resource": "" }
q18515
PacketGen.Packet.decapsulate
train
def decapsulate(*hdrs) hdrs.each do |hdr| idx = headers.index(hdr) raise FormatError, 'header not in packet!' if idx.nil? prev_hdr = idx > 0 ? headers[idx - 1] : nil next_hdr = (idx + 1) < headers.size ? headers[idx + 1] : nil headers.delete_at(idx) add_header(next_hdr, previous_header: prev_hdr) if prev_hdr && next_hdr end rescue ArgumentError => ex raise FormatError, ex.message end
ruby
{ "resource": "" }
q18516
PacketGen.Packet.parse
train
def parse(binary_str, first_header: nil) headers.clear if first_header.nil? # No decoding forced for first header. Have to guess it! first_header = guess_first_header(binary_str) if first_header.nil? raise ParseError, 'cannot identify first header in string' end end add first_header headers[-1, 1] = last_header.read(binary_str) # Decode upper headers recursively decode_bottom_up self end
ruby
{ "resource": "" }
q18517
PacketGen.Packet.inspect
train
def inspect str = Inspect.dashed_line(self.class) headers.each do |header| str << header.inspect end str << Inspect.inspect_body(body) end
ruby
{ "resource": "" }
q18518
PacketGen.Packet.check_protocol
train
def check_protocol(protocol) klass = Header.get_header_class_by_name(protocol) raise ArgumentError, "unknown #{protocol} protocol" if klass.nil? klass end
ruby
{ "resource": "" }
q18519
PacketGen.Packet.add_header
train
def add_header(header, previous_header: nil, parsing: false) prev_header = previous_header || last_header if prev_header bindings = prev_header.class.known_headers[header.class] bindings = prev_header.class.known_headers[header.class.superclass] if bindings.nil? if bindings.nil? msg = "#{prev_header.class} knowns no layer association with #{header.protocol_name}. ".dup msg << "Try #{prev_header.class}.bind_layer(#{header.class}, " msg << "#{prev_header.method_name}_proto_field: " msg << "value_for_#{header.method_name})" raise ArgumentError, msg end bindings.set(prev_header) if !bindings.empty? && !parsing prev_header[:body] = header end header.packet = self headers << header unless previous_header return if respond_to? header.method_name add_magic_header_method header end
ruby
{ "resource": "" }
q18520
PacketGen.Packet.guess_first_header
train
def guess_first_header(binary_str) first_header = nil Header.all.each do |hklass| hdr = hklass.new(packet: self) # #read may return another object (more specific class) hdr = hdr.read(binary_str) # First header is found when, for one known header, # * +#parse?+ is true # * it exists a known binding with a upper header next unless hdr.parse? first_header = hklass.to_s.gsub(/.*::/, '') if search_upper_header(hdr) break unless first_header.nil? end first_header end
ruby
{ "resource": "" }
q18521
PacketGen.Packet.decode_bottom_up
train
def decode_bottom_up loop do last_known_hdr = last_header break if !last_known_hdr.respond_to?(:body) || last_known_hdr.body.empty? nh = search_upper_header(last_known_hdr) break if nh.nil? nheader = nh.new(packet: self) nheader = nheader.read(last_known_hdr.body) next unless nheader.parse? add_header nheader, parsing: true break if last_header == last_known_hdr end end
ruby
{ "resource": "" }
q18522
PacketGen.Packet.search_upper_header
train
def search_upper_header(hdr) hdr.class.known_headers.each do |nh, bindings| return nh if bindings.check?(hdr) end nil end
ruby
{ "resource": "" }
q18523
RailsWorkflow.ProcessTemplate.dependent_operations
train
def dependent_operations(operation) operations.select do |top| top.dependencies.select do |dp| dp['id'] == operation.template.id && dp['statuses'].include?(operation.status) end.present? end end
ruby
{ "resource": "" }
q18524
RailsWorkflow.ErrorBuilder.target
train
def target @target ||= begin parent = context[:parent] if parent.is_a? RailsWorkflow::Operation parent.becomes(RailsWorkflow::Operation) elsif parent.is_a? RailsWorkflow::Process parent.becomes(RailsWorkflow::Process) end end end
ruby
{ "resource": "" }
q18525
Natto.MeCabStruct.method_missing
train
def method_missing(attr_name) member_sym = attr_name.id2name.to_sym self[member_sym] rescue ArgumentError # `member_sym` field doesn't exist. raise(NoMethodError.new("undefined method '#{attr_name}' for #{self}")) end
ruby
{ "resource": "" }
q18526
Natto.MeCab.parse
train
def parse(text, constraints={}) if text.nil? raise ArgumentError.new 'Text to parse cannot be nil' elsif constraints[:boundary_constraints] if !(constraints[:boundary_constraints].is_a?(Regexp) || constraints[:boundary_constraints].is_a?(String)) raise ArgumentError.new 'boundary constraints must be a Regexp or String' end elsif constraints[:feature_constraints] && !constraints[:feature_constraints].is_a?(Hash) raise ArgumentError.new 'feature constraints must be a Hash' elsif @options[:partial] && !text.end_with?("\n") raise ArgumentError.new 'partial parsing requires new-line char at end of text' end if block_given? @parse_tonodes.call(text, constraints).each {|n| yield n } else @parse_tostr.call(text, constraints) end end
ruby
{ "resource": "" }
q18527
Flapjack.Utility.truncate
train
def truncate(str, length, options = {}) text = str.dup options[:omission] ||= "..." length_with_room_for_omission = length - options[:omission].length stop = options[:separator] ? (text.rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission (text.length > length ? text[0...stop] + options[:omission] : text).to_s end
ruby
{ "resource": "" }
q18528
Flapjack.Notifier.process_notification
train
def process_notification(notification) Flapjack.logger.debug { "Processing notification: #{notification.inspect}" } check = notification.check check_name = check.name # TODO check whether time should come from something stored in the notification alerts = alerts_for(notification, check, :time => Time.now) if alerts.nil? || alerts.empty? Flapjack.logger.info { "No alerts" } else Flapjack.logger.info { "Alerts: #{alerts.size}" } alerts.each do |alert| medium = alert.medium Flapjack.logger.info { "#{check_name} | #{medium.contact.id} | " \ "#{medium.transport} | #{medium.address}\n" \ "Enqueueing #{medium.transport} alert for " \ "#{check_name} to #{medium.address} " \ " rollup: #{alert.rollup || '-'}" } @queues[medium.transport].push(alert) end end notification.destroy end
ruby
{ "resource": "" }
q18529
Flapjack.Coordinator.setup_signals
train
def setup_signals Kernel.trap('INT') { Thread.new { @shutdown.call(Signal.list['INT']) }.join } Kernel.trap('TERM') { Thread.new { @shutdown.call(Signal.list['TERM']) }.join } unless RbConfig::CONFIG['host_os'] =~ /mswin|windows|cygwin/i Kernel.trap('HUP') { Thread.new { @reload.call }.join } end end
ruby
{ "resource": "" }
q18530
Khipu.BaseObject.build_from_hash
train
def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else # data not found in attributes(hash), not an issue as the data can be optional end end self end
ruby
{ "resource": "" }
q18531
Khipu.BaseObject.to_hash
train
def to_hash hash = {} attributes = self.class.attribute_map.sort_by {|key,value| key} attributes.each { |attr, param| value = self.send(attr) next if value.nil? if value.is_a?(Array) hash[param] = value.compact.map{ |v| _to_hash(v) } else hash[param] = _to_hash(value) end } hash end
ruby
{ "resource": "" }
q18532
Heroics.CLI.run
train
def run(*parameters) name = parameters.shift if name.nil? || name == 'help' if command_name = parameters.first command = @commands[command_name] command.usage else usage end else command = @commands[name] if command.nil? @output.write("There is no command called '#{name}'.\n") else command.run(*parameters) end end end
ruby
{ "resource": "" }
q18533
Heroics.Command.run
train
def run(*parameters) resource_name = @link_schema.resource_name name = @link_schema.name result = @client.send(resource_name).send(name, *parameters) result = result.to_a if result.instance_of?(Enumerator) if result && !result.instance_of?(String) result = MultiJson.dump(result, pretty: true) end @output.puts(result) unless result.nil? end
ruby
{ "resource": "" }
q18534
Heroics.Link.run
train
def run(*parameters) path, body = @link_schema.format_path(parameters) path = "#{@path_prefix}#{path}" unless @path_prefix == '/' headers = @default_headers if body case @link_schema.method when :put, :post, :patch headers = headers.merge({'Content-Type' => @link_schema.content_type}) body = @link_schema.encode(body) when :get, :delete if body.is_a?(Hash) query = body else query = MultiJson.load(body) end body = nil end end connection = Excon.new(@root_url, thread_safe_sockets: true) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, body: body, query: query, expects: [200, 201, 202, 204, 206]) content_type = response.headers['Content-Type'] if content_type && content_type =~ /application\/.*json/ body = MultiJson.load(response.body) if response.status == 206 next_range = response.headers['Next-Range'] Enumerator.new do |yielder| while true do # Yield the results we got in the body. body.each do |item| yielder << item end # Only make a request to get the next page if we have a valid # next range. break unless next_range headers = headers.merge({'Range' => next_range}) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, expects: [200, 201, 206]) body = MultiJson.load(response.body) next_range = response.headers['Next-Range'] end end else body end elsif !response.body.empty? response.body end end
ruby
{ "resource": "" }
q18535
Heroics.Link.unpack_url
train
def unpack_url(url) root_url = [] path_prefix = '' parts = URI.split(url) root_url << "#{parts[0]}://" root_url << "#{parts[1]}@" unless parts[1].nil? root_url << "#{parts[2]}" root_url << ":#{parts[3]}" unless parts[3].nil? path_prefix = parts[5] return root_url.join(''), path_prefix end
ruby
{ "resource": "" }
q18536
Heroics.Client.method_missing
train
def method_missing(name) name = name.to_s resource = @resources[name] if resource.nil? # Find the name using the same ruby_name replacement semantics as when # we set up the @resources hash name = Heroics.ruby_name(name) resource = @resources[name] if resource.nil? raise NoMethodError.new("undefined method `#{name}' for #{to_s}") end end resource end
ruby
{ "resource": "" }
q18537
Heroics.Resource.method_missing
train
def method_missing(name, *parameters) link = @links[name.to_s] if link.nil? address = "<#{self.class.name}:0x00#{(self.object_id << 1).to_s(16)}>" raise NoMethodError.new("undefined method `#{name}' for ##{address}") end link.run(*parameters) end
ruby
{ "resource": "" }
q18538
Heroics.Schema.resource
train
def resource(name) if @schema['definitions'].has_key?(name) ResourceSchema.new(@schema, name) else raise SchemaError.new("Unknown resource '#{name}'.") end end
ruby
{ "resource": "" }
q18539
Heroics.LinkSchema.example_body
train
def example_body if body_schema = link_schema['schema'] definitions = @schema['definitions'][@resource_name]['definitions'] Hash[body_schema['properties'].keys.map do |property| # FIXME This is wrong! -jkakar if definitions.has_key?(property) example = definitions[property]['example'] else example = '' end [property, example] end] end end
ruby
{ "resource": "" }
q18540
Heroics.LinkSchema.format_path
train
def format_path(parameters) path = link_schema['href'] parameter_size = path.scan(PARAMETER_REGEX).size too_few_parameters = parameter_size > parameters.size # FIXME We should use the schema to detect when a request body is # permitted and do the calculation correctly here. -jkakar too_many_parameters = parameter_size < (parameters.size - 1) if too_few_parameters || too_many_parameters raise ArgumentError.new("wrong number of arguments " + "(#{parameters.size} for #{parameter_size})") end (0...parameter_size).each do |i| path = path.sub(PARAMETER_REGEX, format_parameter(parameters[i])) end body = parameters.slice(parameter_size) return path, body end
ruby
{ "resource": "" }
q18541
Heroics.LinkSchema.resolve_parameters
train
def resolve_parameters(parameters) properties = @schema['definitions'][@resource_name]['properties'] return [''] if properties.nil? definitions = Hash[properties.each_pair.map do |key, value| [value['$ref'], key] end] parameters.map do |parameter| definition_name = URI.unescape(parameter[2..-3]) if definitions.has_key?(definition_name) definitions[definition_name] else definition_name = definition_name.split('/')[-1] resource_definitions = @schema[ 'definitions'][@resource_name]['definitions'][definition_name] if resource_definitions.has_key?('anyOf') resource_definitions['anyOf'].map do |property| definitions[property['$ref']] end.join('|') else resource_definitions['oneOf'].map do |property| definitions[property['$ref']] end.join('|') end end end end
ruby
{ "resource": "" }
q18542
Heroics.LinkSchema.resolve_parameter_details
train
def resolve_parameter_details(parameters) parameters.map do |parameter| # URI decode parameters and strip the leading '{(' and trailing ')}'. parameter = URI.unescape(parameter[2..-3]) # Split the path into components and discard the leading '#' that # represents the root of the schema. path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) # The reference can be one of several values. resource_name = path[1].gsub('-', '_') if info.has_key?('anyOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['anyOf'])) elsif info.has_key?('oneOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['oneOf'])) else name = path[-1] Parameter.new(resource_name, name, info['description']) end end end
ruby
{ "resource": "" }
q18543
Heroics.LinkSchema.unpack_multiple_parameters
train
def unpack_multiple_parameters(parameters) parameters.map do |info| parameter = info['$ref'] path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) resource_name = path.size > 2 ? path[1].gsub('-', '_') : nil name = path[-1] Parameter.new(resource_name, name, info['description']) end end
ruby
{ "resource": "" }
q18544
Heroics.LinkSchema.lookup_parameter
train
def lookup_parameter(path, schema) key = path[0] remaining = path[1..-1] if remaining.empty? return schema[key] else lookup_parameter(remaining, schema[key]) end end
ruby
{ "resource": "" }
q18545
Heroics.LinkSchema.format_parameter
train
def format_parameter(parameter) formatted_parameter = parameter.instance_of?(Time) ? iso_format(parameter) : parameter.to_s WEBrick::HTTPUtils.escape formatted_parameter end
ruby
{ "resource": "" }
q18546
Heroics.GeneratorLink.method_signature
train
def method_signature @parameters.map { |info| info.name == 'body' ? "body = {}" : Heroics.ruby_name(info.name) }.join(', ') end
ruby
{ "resource": "" }
q18547
Cri.CommandDSL.option
train
def option(short, long, desc, argument: :forbidden, multiple: false, hidden: false, default: nil, transform: nil, &block) @command.option_definitions << Cri::OptionDefinition.new( short: short&.to_s, long: long&.to_s, desc: desc, argument: argument, multiple: multiple, hidden: hidden, default: default, transform: transform, block: block, ) end
ruby
{ "resource": "" }
q18548
Cri.CommandDSL.param
train
def param(name, transform: nil) if @command.explicitly_no_params? raise AlreadySpecifiedAsNoParams.new(name, @command) end @command.parameter_definitions << Cri::ParamDefinition.new( name: name, transform: transform, ) end
ruby
{ "resource": "" }
q18549
Cri.CommandDSL.required
train
def required(short, long, desc, params = {}, &block) params = params.merge(argument: :required) option(short, long, desc, params, &block) end
ruby
{ "resource": "" }
q18550
Cri.Parser.run
train
def run @running = true while running? # Get next item e = @unprocessed_arguments_and_options.shift break if e.nil? if e == '--' handle_dashdash(e) elsif e =~ /^--./ && !@no_more_options handle_dashdash_option(e) elsif e =~ /^-./ && !@no_more_options handle_dash_option(e) else add_argument(e) end end add_defaults self ensure @running = false end
ruby
{ "resource": "" }
q18551
Cri.StringFormatter.wrap_and_indent
train
def wrap_and_indent(str, width, indentation, first_line_already_indented = false) indented_width = width - indentation indent = ' ' * indentation # Split into paragraphs paragraphs = to_paragraphs(str) # Wrap and indent each paragraph text = paragraphs.map do |paragraph| # Initialize lines = [] line = '' # Split into words paragraph.split(/\s/).each do |word| # Begin new line if it's too long if (line + ' ' + word).length >= indented_width lines << line line = '' end # Add word to line line += (line == '' ? '' : ' ') + word end lines << line # Join lines lines.map { |l| indent + l }.join("\n") end.join("\n\n") if first_line_already_indented text[indentation..-1] else text end end
ruby
{ "resource": "" }
q18552
Cri.HelpRenderer.render
train
def render text = +'' append_summary(text) append_usage(text) append_description(text) append_subcommands(text) append_options(text) text end
ruby
{ "resource": "" }
q18553
Cri.Command.modify
train
def modify(&block) dsl = Cri::CommandDSL.new(self) if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end self end
ruby
{ "resource": "" }
q18554
Cri.Command.define_command
train
def define_command(name = nil, &block) # Execute DSL dsl = Cri::CommandDSL.new dsl.name name unless name.nil? if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end # Create command cmd = dsl.command add_command(cmd) cmd end
ruby
{ "resource": "" }
q18555
Cri.Command.commands_named
train
def commands_named(name) # Find by exact name or alias @commands.each do |cmd| found = cmd.name == name || cmd.aliases.include?(name) return [cmd] if found end # Find by approximation @commands.select do |cmd| cmd.name[0, name.length] == name end end
ruby
{ "resource": "" }
q18556
Cri.Command.run
train
def run(opts_and_args, parent_opts = {}, hard_exit: true) # Parse up to command name stuff = partition(opts_and_args) opts_before_subcmd, subcmd_name, opts_and_args_after_subcmd = *stuff if subcommands.empty? || (subcmd_name.nil? && !block.nil?) run_this(opts_and_args, parent_opts) else # Handle options handle_options(opts_before_subcmd) # Get command if subcmd_name.nil? if default_subcommand_name subcmd_name = default_subcommand_name else warn "#{name}: no command given" raise CriExitException.new(is_error: true) end end subcommand = command_named(subcmd_name, hard_exit: hard_exit) return if subcommand.nil? # Run subcommand.run(opts_and_args_after_subcmd, parent_opts.merge(opts_before_subcmd), hard_exit: hard_exit) end rescue CriExitException => e exit(e.error? ? 1 : 0) if hard_exit end
ruby
{ "resource": "" }
q18557
Cri.Command.run_this
train
def run_this(opts_and_args, parent_opts = {}) if all_opts_as_args? args = opts_and_args global_opts = parent_opts else # Parse parser = Cri::Parser.new( opts_and_args, global_option_definitions, parameter_definitions, explicitly_no_params?, ) handle_errors_while { parser.run } local_opts = parser.options global_opts = parent_opts.merge(parser.options) # Handle options handle_options(local_opts) args = handle_errors_while { parser.gen_argument_list } end # Execute if block.nil? raise NotImplementedError, "No implementation available for '#{name}'" end block.call(global_opts, args, self) end
ruby
{ "resource": "" }
q18558
PuppetDebugger.Support.parse_error
train
def parse_error(error) case error when SocketError PuppetDebugger::Exception::ConnectError.new(message: "Unknown host: #{Puppet[:server]}") when Net::HTTPError PuppetDebugger::Exception::AuthError.new(message: error.message) when Errno::ECONNREFUSED PuppetDebugger::Exception::ConnectError.new(message: error.message) when Puppet::Error if error.message =~ /could\ not\ find\ class/i PuppetDebugger::Exception::NoClassError.new(default_modules_paths: default_modules_paths, message: error.message) elsif error.message =~ /default\ node/i PuppetDebugger::Exception::NodeDefinitionError.new(default_site_manifest: default_site_manifest, message: error.message) else error end else error end end
ruby
{ "resource": "" }
q18559
PuppetDebugger.Support.puppet_repl_lib_dir
train
def puppet_repl_lib_dir File.expand_path(File.join(File.dirname(File.dirname(File.dirname(__FILE__))), 'lib')) end
ruby
{ "resource": "" }
q18560
PuppetDebugger.Support.do_initialize
train
def do_initialize Puppet.initialize_settings Puppet[:parser] = 'future' # this is required in order to work with puppet 3.8 Puppet[:trusted_node_data] = true rescue ArgumentError => e rescue Puppet::DevError => e # do nothing otherwise calling init twice raises an error end
ruby
{ "resource": "" }
q18561
PuppetDebugger.Cli.key_words
train
def key_words # because dollar signs don't work we can't display a $ sign in the keyword # list so its not explicitly clear what the keyword variables = scope.to_hash.keys # prepend a :: to topscope variables scoped_vars = variables.map { |k, _v| scope.compiler.topscope.exist?(k) ? "$::#{k}" : "$#{k}" } # append a () to functions so we know they are functions funcs = function_map.keys.map { |k| "#{k.split('::').last}()" } PuppetDebugger::InputResponders::Datatypes.instance.debugger = self (scoped_vars + funcs + static_responder_list + PuppetDebugger::InputResponders::Datatypes.instance.all_data_types).uniq.sort end
ruby
{ "resource": "" }
q18562
PuppetDebugger.Cli.to_resource_declaration
train
def to_resource_declaration(type) if type.respond_to?(:type_name) && type.respond_to?(:title) title = type.title type_name = type.type_name elsif type_result = /(\w+)\['?(\w+)'?\]/.match(type.to_s) # not all types have a type_name and title so we # output to a string and parse the results title = type_result[2] type_name = type_result[1] else return type end res = scope.catalog.resource(type_name, title) return res.to_ral if res # don't return anything or returns nil if item is not in the catalog end
ruby
{ "resource": "" }
q18563
PuppetDebugger.Cli.expand_resource_type
train
def expand_resource_type(types) output = [types].flatten.map do |t| if t.class.to_s =~ /Puppet::Pops::Types/ to_resource_declaration(t) else t end end output end
ruby
{ "resource": "" }
q18564
PuppetDebugger.Cli.handle_input
train
def handle_input(input) raise ArgumentError unless input.instance_of?(String) begin output = '' case input.strip when PuppetDebugger::InputResponders::Commands.command_list_regex args = input.split(' ') command = args.shift plugin = PuppetDebugger::InputResponders::Commands.plugin_from_command(command) output = plugin.execute(args, self) return out_buffer.puts output when '_' output = " => #{@last_item}" else result = puppet_eval(input) @last_item = result output = normalize_output(result) output = output.nil? ? '' : output.ai end rescue PuppetDebugger::Exception::InvalidCommand => e output = e.message.fatal rescue LoadError => e output = e.message.fatal rescue Errno::ETIMEDOUT => e output = e.message.fatal rescue ArgumentError => e output = e.message.fatal rescue Puppet::ResourceError => e output = e.message.fatal rescue Puppet::Error => e output = e.message.fatal rescue Puppet::ParseErrorWithIssue => e output = e.message.fatal rescue PuppetDebugger::Exception::FatalError => e output = e.message.fatal out_buffer.puts output exit 1 # this can sometimes causes tests to fail rescue PuppetDebugger::Exception::Error => e output = e.message.fatal end unless output.empty? out_buffer.print ' => ' out_buffer.puts output unless output.empty? exec_hook :after_output, out_buffer, self, self end end
ruby
{ "resource": "" }
q18565
PuppetDebugger.Cli.read_loop
train
def read_loop line_number = 1 full_buffer = '' while buf = Readline.readline("#{line_number}:#{extra_prompt}>> ", true) begin full_buffer += buf # unless this is puppet code, otherwise skip repl keywords unless PuppetDebugger::InputResponders::Commands.command_list_regex.match(buf) line_number = line_number.next begin parser.parse_string(full_buffer) rescue Puppet::ParseErrorWithIssue => e if multiline_input?(e) out_buffer.print ' ' full_buffer += "\n" next end end end handle_input(full_buffer) full_buffer = '' end end end
ruby
{ "resource": "" }
q18566
OEmbed.HttpHelper.http_get
train
def http_get(uri, options = {}) found = false remaining_redirects = options[:max_redirects] ? options[:max_redirects].to_i : 4 until found http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.read_timeout = http.open_timeout = options[:timeout] if options[:timeout] methods = if RUBY_VERSION < "2.2" %w{scheme userinfo host port registry} else %w{scheme userinfo host port} end methods.each { |method| uri.send("#{method}=", nil) } req = Net::HTTP::Get.new(uri.to_s) req['User-Agent'] = "Mozilla/5.0 (compatible; ruby-oembed/#{OEmbed::VERSION})" res = http.request(req) if remaining_redirects == 0 found = true elsif res.is_a?(Net::HTTPRedirection) && res.header['location'] uri = URI.parse(res.header['location']) remaining_redirects -= 1 else found = true end end case res when Net::HTTPNotImplemented raise OEmbed::UnknownFormat when Net::HTTPNotFound raise OEmbed::NotFound, uri when Net::HTTPSuccess res.body else raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' end rescue StandardError # Convert known errors into OEmbed::UnknownResponse for easy catching # up the line. This is important if given a URL that doesn't support # OEmbed. The following are known errors: # * Net::* errors like Net::HTTPBadResponse # * JSON::JSONError errors like JSON::ParserError if defined?(::JSON) && $!.is_a?(::JSON::JSONError) || $!.class.to_s =~ /\ANet::/ raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' else raise $! end end
ruby
{ "resource": "" }
q18567
AwesomePrint.Puppet.cast_with_puppet_resource
train
def cast_with_puppet_resource(object, type) cast = cast_without_puppet_resource(object, type) # check the object to see if it has an acestor (< ) of the specified type if defined?(::Puppet::Type) && (object.class < ::Puppet::Type) cast = :puppet_type elsif defined?(::Puppet::Pops::Types) && (object.class < ::Puppet::Pops::Types) cast = :puppet_type elsif defined?(::Puppet::Parser::Resource) && (object.class < ::Puppet::Parser::Resource) cast = :puppet_resource elsif /Puppet::Pops::Types/.match(object.class.to_s) cast = :puppet_type end cast end
ruby
{ "resource": "" }
q18568
PuppetDebugger.Hooks.initialize_copy
train
def initialize_copy(orig) hooks_dup = @hooks.dup @hooks.each do |k, v| hooks_dup[k] = v.dup end @hooks = hooks_dup end
ruby
{ "resource": "" }
q18569
PuppetDebugger.Hooks.add_hook
train
def add_hook(event_name, hook_name, callable=nil, &block) event_name = event_name.to_s # do not allow duplicates, but allow multiple `nil` hooks # (anonymous hooks) if hook_exists?(event_name, hook_name) && !hook_name.nil? raise ArgumentError, "Hook with name '#{hook_name}' already defined!" end if !block && !callable raise ArgumentError, "Must provide a block or callable." end # ensure we only have one anonymous hook @hooks[event_name].delete_if { |h, k| h.nil? } if hook_name.nil? if block @hooks[event_name] << [hook_name, block] elsif callable @hooks[event_name] << [hook_name, callable] end self end
ruby
{ "resource": "" }
q18570
PuppetDebugger.Hooks.exec_hook
train
def exec_hook(event_name, *args, &block) @hooks[event_name.to_s].map do |hook_name, callable| begin callable.call(*args, &block) rescue PuppetDebugger::Exception::Error, ::RuntimeError => e errors << e e end end.last end
ruby
{ "resource": "" }
q18571
SFRest.Task.task_status
train
def task_status(task_id) current_path = "/api/v1/wip/task/#{task_id}/status" res = @conn.get(current_path) raise InvalidDataError, "No wip task returned for task id #{task_id}" if res['wip_task'].nil? raise InvalidDataError, "No task status returned for task id #{task_id}" if res['wip_task']['status'].nil? res['wip_task']['status'] end
ruby
{ "resource": "" }
q18572
SFRest.Task.find_task_ids
train
def find_task_ids(limit = nil, page = nil, group = nil, klass = nil, status = nil) res = find_tasks limit: limit, page: page, group: group, klass: klass, status: status task_ids = [] i = 0 res.each do |task| task_ids[i] = task['id'] i += 1 end task_ids end
ruby
{ "resource": "" }
q18573
SFRest.Task.find_tasks
train
def find_tasks(datum = nil) current_path = '/api/v1/tasks' pb = SFRest::Pathbuilder.new @conn.get URI.parse(pb.build_url_query(current_path, datum)).to_s end
ruby
{ "resource": "" }
q18574
SFRest.Task.globally_paused?
train
def globally_paused? paused = false current_path = '/api/v1/variables?name=wip_pause_global' begin res = @conn.get(current_path) paused = res['wip_pause_global'] rescue SFRest::SFError => error paused = false if error.message =~ /Variable not found/ end paused end
ruby
{ "resource": "" }
q18575
SFRest.Task.pause_task
train
def pause_task(task_id, level = 'family') current_path = '/api/v1/pause/' << task_id.to_s payload = { 'paused' => true, 'level' => level }.to_json @conn.post(current_path, payload) end
ruby
{ "resource": "" }
q18576
SFRest.Task.resume_task
train
def resume_task(task_id, level = 'family') current_path = '/api/v1/pause/' << task_id.to_s payload = { 'paused' => false, 'level' => level }.to_json @conn.post(current_path, payload) end
ruby
{ "resource": "" }
q18577
SFRest.Task.wait_until_state
train
def wait_until_state(task_id, state, max_nap) blink_time = 5 # wake up and scan nap_start = Time.now state_method = method("task_#{state}?".to_sym) loop do break if state_method.call(task_id) raise TaskNotDoneError, "Task: #{task_id} has taken too long to complete!" if Time.new > (nap_start + max_nap) sleep blink_time end task_id end
ruby
{ "resource": "" }
q18578
SFRest.Collection.collection_list
train
def collection_list page = 1 not_done = true count = 0 while not_done current_path = '/api/v1/collections?page=' << page.to_s res = @conn.get(current_path) if res['collections'] == [] not_done = false elsif !res['message'].nil? return { 'message' => res['message'] } elsif page == 1 count = res['count'] collections = res['collections'] else res['collections'].each do |collection| collections << collection end end page += 1 end { 'count' => count, 'collections' => collections } end
ruby
{ "resource": "" }
q18579
SFRest.Collection.create
train
def create(name, sites, groups, internal_domain_prefix = nil) sites = Array(sites) groups = Array(groups) current_path = '/api/v1/collections' payload = { 'name' => name, 'site_ids' => sites, 'group_ids' => groups, 'internal_domain_prefix' => internal_domain_prefix }.to_json @conn.post(current_path, payload) end
ruby
{ "resource": "" }
q18580
SFRest.Collection.set_primary_site
train
def set_primary_site(id, site) payload = { 'site_id' => site }.to_json current_path = "/api/v1/collections/#{id}/set-primary" @conn.post(current_path, payload) end
ruby
{ "resource": "" }
q18581
SFRest.Update.modify_status
train
def modify_status(site_creation, site_duplication, domain_management, bulk_operations) current_path = '/api/v1/status' payload = { 'site_creation' => site_creation, 'site_duplication' => site_duplication, 'domain_management' => domain_management, 'bulk_operations' => bulk_operations }.to_json @conn.put(current_path, payload) end
ruby
{ "resource": "" }
q18582
SFRest.Update.start_update
train
def start_update(ref) if update_version == 'v2' raise InvalidApiVersion, 'There is more than one codebase use sfrest.update.update directly.' end update_data = { scope: 'sites', sites_type: 'code, db', sites_ref: ref } update(update_data) end
ruby
{ "resource": "" }
q18583
SFRest.Group.group_list
train
def group_list page = 1 not_done = true count = 0 while not_done current_path = '/api/v1/groups?page=' << page.to_s res = @conn.get(current_path) if res['groups'] == [] not_done = false elsif !res['message'].nil? return { 'message' => res['message'] } elsif page == 1 count = res['count'] groups = res['groups'] else res['groups'].each do |group| groups << group end end page += 1 end { 'count' => count, 'groups' => groups } end
ruby
{ "resource": "" }
q18584
SFRest.User.get_user_id
train
def get_user_id(username) pglimit = 100 res = @conn.get('/api/v1/users&limit=' + pglimit.to_s) usercount = res['count'].to_i id = user_data_from_results(res, username, 'uid') return id if id pages = (usercount / pglimit) + 1 2.upto(pages) do |i| res = @conn.get('/api/v1/users&limit=' + pglimit.to_s + '?page=' + i.to_s) id = user_data_from_results(res, username, 'uid') return id if id end nil end
ruby
{ "resource": "" }
q18585
SFRest.User.user_data_from_results
train
def user_data_from_results(res, username, key) users = res['users'] users.each do |user| return user[key] if user['name'] == username end nil end
ruby
{ "resource": "" }
q18586
SFRest.User.create_user
train
def create_user(name, email, datum = nil) current_path = '/api/v1/users' payload = { name: name, mail: email } payload.merge!(datum) unless datum.nil? @conn.post(current_path, payload.to_json) end
ruby
{ "resource": "" }
q18587
SFRest.Stage.staging_versions
train
def staging_versions possible_versions = [1, 2] @versions ||= [] possible_versions.each do |version| begin @conn.get "/api/v#{version}/stage" @versions.push version rescue SFRest::InvalidResponse nil end end @versions end
ruby
{ "resource": "" }
q18588
SFRest.Connection.put
train
def put(uri, payload) headers = { 'Content-Type' => 'application/json' } res = Excon.put(@base_url + uri.to_s, headers: headers, user: username, password: password, ssl_verify_peer: false, body: payload) api_response res end
ruby
{ "resource": "" }
q18589
SFRest.Connection.delete
train
def delete(uri) headers = { 'Content-Type' => 'application/json' } res = Excon.delete(@base_url + uri.to_s, headers: headers, user: username, password: password, ssl_verify_peer: false) api_response res end
ruby
{ "resource": "" }
q18590
SFRest.Connection.api_response
train
def api_response(res, return_status = false) data = access_check JSON(res.body), res.status return_status ? [res.status, data] : data rescue JSON::ParserError message = "Invalid data, status #{res.status}, body: #{res.body}" raise SFRest::InvalidResponse, message end
ruby
{ "resource": "" }
q18591
SFRest.Pathbuilder.build_url_query
train
def build_url_query(current_path, datum = nil) unless datum.nil? current_path += '?' current_path += URI.encode_www_form datum end current_path end
ruby
{ "resource": "" }
q18592
SFRest.Variable.set_variable
train
def set_variable(name, value) current_path = '/api/v1/variables' payload = { 'name' => name, 'value' => value }.to_json @conn.put(current_path, payload) end
ruby
{ "resource": "" }
q18593
SFRest.Site.site_list
train
def site_list(show_incomplete = true) page = 1 not_done = true count = 0 sites = [] while not_done current_path = '/api/v1/sites?page=' << page.to_s current_path <<= '&show_incomplete=true' if show_incomplete res = @conn.get(current_path) if res['sites'] == [] not_done = false elsif !res['message'].nil? return { 'message' => res['message'] } elsif page == 1 count = res['count'] sites = res['sites'] else res['sites'].each do |site| sites << site end end page += 1 end { 'count' => count, 'sites' => sites } end
ruby
{ "resource": "" }
q18594
SFRest.Site.create_site
train
def create_site(sitename, group_id, install_profile = nil, codebase = nil) current_path = '/api/v1/sites' payload = { 'site_name' => sitename, 'group_ids' => [group_id], 'install_profile' => install_profile, 'codebase' => codebase }.to_json @conn.post(current_path, payload) end
ruby
{ "resource": "" }
q18595
SFRest.Role.get_role_id
train
def get_role_id(rolename) pglimit = 100 res = @conn.get('/api/v1/roles&limit=' + pglimit.to_s) rolecount = res['count'].to_i id = role_data_from_results(res, rolename) return id if id pages = (rolecount / pglimit) + 1 2.upto(pages) do |i| res = @conn.get('/api/v1/roles&limit=' + pglimit.to_s + '?page=' + i.to_s) id = role_data_from_results(res, rolename) return id if id end nil end
ruby
{ "resource": "" }
q18596
SFRest.Role.role_data_from_results
train
def role_data_from_results(res, rolename) roles = res['roles'] roles.each do |role| return role[0].to_i if role[1] == rolename end nil end
ruby
{ "resource": "" }
q18597
Spree.BannerBox.duplicate
train
def duplicate enhance_settings p = self.dup p.category = 'COPY OF ' + category p.created_at = p.updated_at = nil p.url = url p.attachment = attachment # allow site to do some customization p.send(:duplicate_extra, self) if p.respond_to?(:duplicate_extra) p.save! p end
ruby
{ "resource": "" }
q18598
Learn.OptionsSanitizer.handle_missing_or_unknown_args
train
def handle_missing_or_unknown_args if first_arg_not_a_flag_or_file? exit_with_unknown_command elsif has_output_flag? || has_format_flag? check_for_output_file if has_output_flag? check_for_format_type if has_format_flag? elsif only_has_flag_arguments? add_test_command else exit_with_cannot_understand end end
ruby
{ "resource": "" }
q18599
Origin.Selectable.between
train
def between(criterion = nil) selection(criterion) do |selector, field, value| selector.store( field, { "$gte" => value.min, "$lte" => value.max } ) end end
ruby
{ "resource": "" }