repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
WinRb/Viewpoint
lib/ews/soap/exchange_notification.rb
Viewpoint::EWS::SOAP.ExchangeNotification.subscribe
def subscribe(subscriptions) req = build_soap! do |type, builder| if(type == :header) else builder.nbuild.Subscribe { builder.nbuild.parent.default_namespace = @default_ns subscriptions.each do |sub| subtype = sub.keys.first if(builder.respond_to?(subtype)) builder.send subtype, sub[subtype] else raise EwsBadArgumentError, "Bad subscription type. #{subtype}" end end } end end do_soap_request(req, response_class: EwsResponse) end
ruby
def subscribe(subscriptions) req = build_soap! do |type, builder| if(type == :header) else builder.nbuild.Subscribe { builder.nbuild.parent.default_namespace = @default_ns subscriptions.each do |sub| subtype = sub.keys.first if(builder.respond_to?(subtype)) builder.send subtype, sub[subtype] else raise EwsBadArgumentError, "Bad subscription type. #{subtype}" end end } end end do_soap_request(req, response_class: EwsResponse) end
[ "def", "subscribe", "(", "subscriptions", ")", "req", "=", "build_soap!", "do", "|", "type", ",", "builder", "|", "if", "(", "type", "==", ":header", ")", "else", "builder", ".", "nbuild", ".", "Subscribe", "{", "builder", ".", "nbuild", ".", "parent", ...
Used to subscribe client applications to either push, pull or stream notifications. @see http://msdn.microsoft.com/en-us/library/aa566188(v=EXCHG.140).aspx @param [Array<Hash>] subscriptions An array of Hash objects that describe each subscription. Ex: [ {:pull_subscription_request => { :subscribe_to_all_folders => false, :folder_ids => [ {:id => 'id', :change_key => 'ck'} ], :event_types=> %w{CopiedEvent CreatedEvent}, :watermark => 'watermark id', :timeout => intval }}, {:push_subscription_request => { :subscribe_to_all_folders => true, :event_types=> %w{CopiedEvent CreatedEvent}, :status_frequency => 15, :uRL => 'http://my.endpoint.for.updates/', }}, {:streaming_subscription_request => { :subscribe_to_all_folders => false, :folder_ids => [ {:id => 'id', :change_key => 'ck'} ], :event_types=> %w{NewMailEvent DeletedEvent}, }}, ]
[ "Used", "to", "subscribe", "client", "applications", "to", "either", "push", "pull", "or", "stream", "notifications", "." ]
e8fec4ab1af25fc128062cd96770afdb9fc38c68
https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_notification.rb#L49-L67
valid
WinRb/Viewpoint
lib/ews/soap/exchange_notification.rb
Viewpoint::EWS::SOAP.ExchangeNotification.push_subscribe_folder
def push_subscribe_folder(folder, evtypes, url, status_frequency = nil, watermark = nil) status_frequency ||= 30 psr = { :subscribe_to_all_folders => false, :folder_ids => [ {:id => folder[:id], :change_key => folder[:change_key]} ], :event_types=> evtypes, :status_frequency => status_frequency, :uRL => url.to_s } psr[:watermark] = watermark if watermark subscribe([{push_subscription_request: psr}]) end
ruby
def push_subscribe_folder(folder, evtypes, url, status_frequency = nil, watermark = nil) status_frequency ||= 30 psr = { :subscribe_to_all_folders => false, :folder_ids => [ {:id => folder[:id], :change_key => folder[:change_key]} ], :event_types=> evtypes, :status_frequency => status_frequency, :uRL => url.to_s } psr[:watermark] = watermark if watermark subscribe([{push_subscription_request: psr}]) end
[ "def", "push_subscribe_folder", "(", "folder", ",", "evtypes", ",", "url", ",", "status_frequency", "=", "nil", ",", "watermark", "=", "nil", ")", "status_frequency", "||=", "30", "psr", "=", "{", ":subscribe_to_all_folders", "=>", "false", ",", ":folder_ids", ...
Create a push subscription to a single folder @param folder [Hash] a hash with the folder :id and :change_key @param evtypes [Array] the events you would like to subscribe to. @param url [String,URI] http://msdn.microsoft.com/en-us/library/aa566309.aspx @param watermark [String] http://msdn.microsoft.com/en-us/library/aa565886.aspx @param status_frequency [Fixnum] http://msdn.microsoft.com/en-us/library/aa564048.aspx
[ "Create", "a", "push", "subscription", "to", "a", "single", "folder" ]
e8fec4ab1af25fc128062cd96770afdb9fc38c68
https://github.com/WinRb/Viewpoint/blob/e8fec4ab1af25fc128062cd96770afdb9fc38c68/lib/ews/soap/exchange_notification.rb#L131-L142
valid
contentful/contentful.rb
lib/contentful/coercions.rb
Contentful.DateCoercion.coerce
def coerce(*) return nil if value.nil? return value if value.is_a?(Date) DateTime.parse(value) end
ruby
def coerce(*) return nil if value.nil? return value if value.is_a?(Date) DateTime.parse(value) end
[ "def", "coerce", "(", "*", ")", "return", "nil", "if", "value", ".", "nil?", "return", "value", "if", "value", ".", "is_a?", "(", "Date", ")", "DateTime", ".", "parse", "(", "value", ")", "end" ]
Coerces value to DateTime
[ "Coerces", "value", "to", "DateTime" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/coercions.rb#L62-L67
valid
contentful/contentful.rb
lib/contentful/resource_references.rb
Contentful.ResourceReferences.incoming_references
def incoming_references(client = nil, query = {}) return false unless client query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id) client.entries(query) end
ruby
def incoming_references(client = nil, query = {}) return false unless client query = is_a?(Contentful::Entry) ? query.merge(links_to_entry: id) : query.merge(links_to_asset: id) client.entries(query) end
[ "def", "incoming_references", "(", "client", "=", "nil", ",", "query", "=", "{", "}", ")", "return", "false", "unless", "client", "query", "=", "is_a?", "(", "Contentful", "::", "Entry", ")", "?", "query", ".", "merge", "(", "links_to_entry", ":", "id", ...
Gets a collection of entries which links to current entry @param [Contentful::Client] client @param [Hash] query @return [Contentful::Array<Contentful::Entry>, false]
[ "Gets", "a", "collection", "of", "entries", "which", "links", "to", "current", "entry" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/resource_references.rb#L10-L16
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.entry
def entry(id, query = {}) normalize_select!(query) query['sys.id'] = id entries = Request.new(self, environment_url('/entries'), query).get return entries if configuration[:raw_mode] entries.first end
ruby
def entry(id, query = {}) normalize_select!(query) query['sys.id'] = id entries = Request.new(self, environment_url('/entries'), query).get return entries if configuration[:raw_mode] entries.first end
[ "def", "entry", "(", "id", ",", "query", "=", "{", "}", ")", "normalize_select!", "(", "query", ")", "query", "[", "'sys.id'", "]", "=", "id", "entries", "=", "Request", ".", "new", "(", "self", ",", "environment_url", "(", "'/entries'", ")", ",", "q...
Gets a specific entry @param [String] id @param [Hash] query @return [Contentful::Entry]
[ "Gets", "a", "specific", "entry" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L170-L178
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.os_info
def os_info os_name = case ::RbConfig::CONFIG['host_os'] when /(cygwin|mingw|mswin|windows)/i then 'Windows' when /(darwin|macruby|mac os)/i then 'macOS' when /(linux|bsd|aix|solarix)/i then 'Linux' end { name: os_name, version: Gem::Platform.local.version } end
ruby
def os_info os_name = case ::RbConfig::CONFIG['host_os'] when /(cygwin|mingw|mswin|windows)/i then 'Windows' when /(darwin|macruby|mac os)/i then 'macOS' when /(linux|bsd|aix|solarix)/i then 'Linux' end { name: os_name, version: Gem::Platform.local.version } end
[ "def", "os_info", "os_name", "=", "case", "::", "RbConfig", "::", "CONFIG", "[", "'host_os'", "]", "when", "/", "/i", "then", "'Windows'", "when", "/", "/i", "then", "'macOS'", "when", "/", "/i", "then", "'Linux'", "end", "{", "name", ":", "os_name", "...
Returns the X-Contentful-User-Agent os data @private
[ "Returns", "the", "X", "-", "Contentful", "-", "User", "-", "Agent", "os", "data" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L265-L272
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.contentful_user_agent
def contentful_user_agent header = { 'sdk' => sdk_info, 'app' => app_info, 'integration' => integration_info, 'platform' => platform_info, 'os' => os_info } result = [] header.each do |key, values| next unless values[:name] result << format_user_agent_header(key, values) end result.join(' ') end
ruby
def contentful_user_agent header = { 'sdk' => sdk_info, 'app' => app_info, 'integration' => integration_info, 'platform' => platform_info, 'os' => os_info } result = [] header.each do |key, values| next unless values[:name] result << format_user_agent_header(key, values) end result.join(' ') end
[ "def", "contentful_user_agent", "header", "=", "{", "'sdk'", "=>", "sdk_info", ",", "'app'", "=>", "app_info", ",", "'integration'", "=>", "integration_info", ",", "'platform'", "=>", "platform_info", ",", "'os'", "=>", "os_info", "}", "result", "=", "[", "]",...
Returns the X-Contentful-User-Agent @private
[ "Returns", "the", "X", "-", "Contentful", "-", "User", "-", "Agent" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L276-L291
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.request_headers
def request_headers headers = { 'X-Contentful-User-Agent' => contentful_user_agent } headers['Authorization'] = "Bearer #{configuration[:access_token]}" if configuration[:authentication_mechanism] == :header headers['Content-Type'] = "application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json" if configuration[:api_version] headers['Accept-Encoding'] = 'gzip' if configuration[:gzip_encoded] headers end
ruby
def request_headers headers = { 'X-Contentful-User-Agent' => contentful_user_agent } headers['Authorization'] = "Bearer #{configuration[:access_token]}" if configuration[:authentication_mechanism] == :header headers['Content-Type'] = "application/vnd.contentful.delivery.v#{configuration[:api_version].to_i}+json" if configuration[:api_version] headers['Accept-Encoding'] = 'gzip' if configuration[:gzip_encoded] headers end
[ "def", "request_headers", "headers", "=", "{", "'X-Contentful-User-Agent'", "=>", "contentful_user_agent", "}", "headers", "[", "'Authorization'", "]", "=", "\"Bearer #{configuration[:access_token]}\"", "if", "configuration", "[", ":authentication_mechanism", "]", "==", ":h...
Returns the headers used for the HTTP requests @private
[ "Returns", "the", "headers", "used", "for", "the", "HTTP", "requests" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L295-L301
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.run_request
def run_request(request) url = request.absolute? ? request.url : base_url + request.url logger.info(request: { url: url, query: request.query, header: request_headers }) if logger Response.new( self.class.get_http( url, request_query(request.query), request_headers, proxy_params, timeout_params ), request ) end
ruby
def run_request(request) url = request.absolute? ? request.url : base_url + request.url logger.info(request: { url: url, query: request.query, header: request_headers }) if logger Response.new( self.class.get_http( url, request_query(request.query), request_headers, proxy_params, timeout_params ), request ) end
[ "def", "run_request", "(", "request", ")", "url", "=", "request", ".", "absolute?", "?", "request", ".", "url", ":", "base_url", "+", "request", ".", "url", "logger", ".", "info", "(", "request", ":", "{", "url", ":", "url", ",", "query", ":", "reque...
Runs request and parses Response @private
[ "Runs", "request", "and", "parses", "Response" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L367-L379
valid
contentful/contentful.rb
lib/contentful/client.rb
Contentful.Client.do_build_resource
def do_build_resource(response) logger.debug(response: response) if logger configuration[:resource_builder].new( response.object, configuration.merge(endpoint: response.request.endpoint), (response.request.query || {}).fetch(:locale, nil) == '*', 0 ).run end
ruby
def do_build_resource(response) logger.debug(response: response) if logger configuration[:resource_builder].new( response.object, configuration.merge(endpoint: response.request.endpoint), (response.request.query || {}).fetch(:locale, nil) == '*', 0 ).run end
[ "def", "do_build_resource", "(", "response", ")", "logger", ".", "debug", "(", "response", ":", "response", ")", "if", "logger", "configuration", "[", ":resource_builder", "]", ".", "new", "(", "response", ".", "object", ",", "configuration", ".", "merge", "...
Runs Resource Builder @private
[ "Runs", "Resource", "Builder" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/client.rb#L383-L391
valid
contentful/contentful.rb
lib/contentful/link.rb
Contentful.Link.resolve
def resolve(client, query = {}) id_and_query = [(id unless link_type == 'Space')].compact + [query] client.public_send( Contentful::Support.snakify(link_type).to_sym, *id_and_query ) end
ruby
def resolve(client, query = {}) id_and_query = [(id unless link_type == 'Space')].compact + [query] client.public_send( Contentful::Support.snakify(link_type).to_sym, *id_and_query ) end
[ "def", "resolve", "(", "client", ",", "query", "=", "{", "}", ")", "id_and_query", "=", "[", "(", "id", "unless", "link_type", "==", "'Space'", ")", "]", ".", "compact", "+", "[", "query", "]", "client", ".", "public_send", "(", "Contentful", "::", "...
Queries contentful for the Resource the Link is refering to Takes an optional query hash
[ "Queries", "contentful", "for", "the", "Resource", "the", "Link", "is", "refering", "to", "Takes", "an", "optional", "query", "hash" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/link.rb#L9-L15
valid
contentful/contentful.rb
lib/contentful/fields_resource.rb
Contentful.FieldsResource.fields_with_locales
def fields_with_locales remapped_fields = {} locales.each do |locale| fields(locale).each do |name, value| remapped_fields[name] ||= {} remapped_fields[name][locale.to_sym] = value end end remapped_fields end
ruby
def fields_with_locales remapped_fields = {} locales.each do |locale| fields(locale).each do |name, value| remapped_fields[name] ||= {} remapped_fields[name][locale.to_sym] = value end end remapped_fields end
[ "def", "fields_with_locales", "remapped_fields", "=", "{", "}", "locales", ".", "each", "do", "|", "locale", "|", "fields", "(", "locale", ")", ".", "each", "do", "|", "name", ",", "value", "|", "remapped_fields", "[", "name", "]", "||=", "{", "}", "re...
Returns all fields of the asset with locales nested by field @return [Hash] fields for Resource grouped by field name
[ "Returns", "all", "fields", "of", "the", "asset", "with", "locales", "nested", "by", "field" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/fields_resource.rb#L32-L42
valid
contentful/contentful.rb
lib/contentful/base_resource.rb
Contentful.BaseResource.reload
def reload(client = nil) return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil? false end
ruby
def reload(client = nil) return client.send(Support.snakify(self.class.name.split('::').last), id) unless client.nil? false end
[ "def", "reload", "(", "client", "=", "nil", ")", "return", "client", ".", "send", "(", "Support", ".", "snakify", "(", "self", ".", "class", ".", "name", ".", "split", "(", "'::'", ")", ".", "last", ")", ",", "id", ")", "unless", "client", ".", "...
Issues the request that was made to fetch this response again. Only works for Entry, Asset, ContentType and Space
[ "Issues", "the", "request", "that", "was", "made", "to", "fetch", "this", "response", "again", ".", "Only", "works", "for", "Entry", "Asset", "ContentType", "and", "Space" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/base_resource.rb#L52-L56
valid
contentful/contentful.rb
lib/contentful/content_type.rb
Contentful.ContentType.field_for
def field_for(field_id) fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) } end
ruby
def field_for(field_id) fields.detect { |f| Support.snakify(f.id) == Support.snakify(field_id) } end
[ "def", "field_for", "(", "field_id", ")", "fields", ".", "detect", "{", "|", "f", "|", "Support", ".", "snakify", "(", "f", ".", "id", ")", "==", "Support", ".", "snakify", "(", "field_id", ")", "}", "end" ]
Field definition for field
[ "Field", "definition", "for", "field" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/content_type.rb#L21-L23
valid
contentful/contentful.rb
lib/contentful/sync.rb
Contentful.Sync.each_page
def each_page page = first_page yield page if block_given? until completed? page = page.next_page yield page if block_given? end end
ruby
def each_page page = first_page yield page if block_given? until completed? page = page.next_page yield page if block_given? end end
[ "def", "each_page", "page", "=", "first_page", "yield", "page", "if", "block_given?", "until", "completed?", "page", "=", "page", ".", "next_page", "yield", "page", "if", "block_given?", "end", "end" ]
Iterates over all pages of the current sync @note Please Keep in Mind: Iterating fires a new request for each page @yield [Contentful::SyncPage]
[ "Iterates", "over", "all", "pages", "of", "the", "current", "sync" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/sync.rb#L23-L31
valid
contentful/contentful.rb
lib/contentful/field.rb
Contentful.Field.coerce
def coerce(value, configuration) return value if type.nil? return value if value.nil? options = {} options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil? KNOWN_TYPES[type].new(value, options).coerce(configuration) end
ruby
def coerce(value, configuration) return value if type.nil? return value if value.nil? options = {} options[:coercion_class] = KNOWN_TYPES[items.type] unless items.nil? KNOWN_TYPES[type].new(value, options).coerce(configuration) end
[ "def", "coerce", "(", "value", ",", "configuration", ")", "return", "value", "if", "type", ".", "nil?", "return", "value", "if", "value", ".", "nil?", "options", "=", "{", "}", "options", "[", ":coercion_class", "]", "=", "KNOWN_TYPES", "[", "items", "."...
Coerces value to proper type
[ "Coerces", "value", "to", "proper", "type" ]
bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7
https://github.com/contentful/contentful.rb/blob/bdf5ca61f99ee8b8bfa449ab5ba22b7698f607f7/lib/contentful/field.rb#L38-L45
valid
instructure/ims-lti
lib/ims/lti/services/tool_config.rb
IMS::LTI::Services.ToolConfig.set_ext_params
def set_ext_params(ext_key, ext_params) raise ArgumentError unless ext_params.is_a?(Hash) @extensions[ext_key] = ext_params end
ruby
def set_ext_params(ext_key, ext_params) raise ArgumentError unless ext_params.is_a?(Hash) @extensions[ext_key] = ext_params end
[ "def", "set_ext_params", "(", "ext_key", ",", "ext_params", ")", "raise", "ArgumentError", "unless", "ext_params", ".", "is_a?", "(", "Hash", ")", "@extensions", "[", "ext_key", "]", "=", "ext_params", "end" ]
Set the extension parameters for a specific vendor @param ext_key [String] The identifier for the vendor-specific parameters @param ext_params [Hash] The parameters, this is allowed to be two-levels deep
[ "Set", "the", "extension", "parameters", "for", "a", "specific", "vendor" ]
969613a50f3a43345a8b0c92ca5f0e9d0251d5b7
https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L62-L65
valid
instructure/ims-lti
lib/ims/lti/services/tool_config.rb
IMS::LTI::Services.ToolConfig.process_xml
def process_xml(xml) doc = REXML::Document.new xml if root = REXML::XPath.first(doc, 'xmlns:cartridge_basiclti_link') @title = get_node_text(root, 'blti:title') @description = get_node_text(root, 'blti:description') @launch_url = get_node_text(root, 'blti:launch_url') @secure_launch_url = get_node_text(root, 'blti:secure_launch_url') @icon = get_node_text(root, 'blti:icon') @secure_icon = get_node_text(root, 'blti:secure_icon') @cartridge_bundle = get_node_att(root, 'xmlns:cartridge_bundle', 'identifierref') @cartridge_icon = get_node_att(root, 'xmlns:cartridge_icon', 'identifierref') if vendor = REXML::XPath.first(root, 'blti:vendor') @vendor_code = get_node_text(vendor, 'lticp:code') @vendor_description = get_node_text(vendor, 'lticp:description') @vendor_name = get_node_text(vendor, 'lticp:name') @vendor_url = get_node_text(vendor, 'lticp:url') @vendor_contact_email = get_node_text(vendor, '//lticp:contact/lticp:email') @vendor_contact_name = get_node_text(vendor, '//lticp:contact/lticp:name') end if custom = REXML::XPath.first(root, 'blti:custom', LTI_NAMESPACES) set_properties(@custom_params, custom) end REXML::XPath.each(root, 'blti:extensions', LTI_NAMESPACES) do |vendor_ext_node| platform = vendor_ext_node.attributes['platform'] properties = {} set_properties(properties, vendor_ext_node) REXML::XPath.each(vendor_ext_node, 'lticm:options', LTI_NAMESPACES) do |options_node| opt_name = options_node.attributes['name'] options = {} set_properties(options, options_node) properties[opt_name] = options end self.set_ext_params(platform, properties) end end end
ruby
def process_xml(xml) doc = REXML::Document.new xml if root = REXML::XPath.first(doc, 'xmlns:cartridge_basiclti_link') @title = get_node_text(root, 'blti:title') @description = get_node_text(root, 'blti:description') @launch_url = get_node_text(root, 'blti:launch_url') @secure_launch_url = get_node_text(root, 'blti:secure_launch_url') @icon = get_node_text(root, 'blti:icon') @secure_icon = get_node_text(root, 'blti:secure_icon') @cartridge_bundle = get_node_att(root, 'xmlns:cartridge_bundle', 'identifierref') @cartridge_icon = get_node_att(root, 'xmlns:cartridge_icon', 'identifierref') if vendor = REXML::XPath.first(root, 'blti:vendor') @vendor_code = get_node_text(vendor, 'lticp:code') @vendor_description = get_node_text(vendor, 'lticp:description') @vendor_name = get_node_text(vendor, 'lticp:name') @vendor_url = get_node_text(vendor, 'lticp:url') @vendor_contact_email = get_node_text(vendor, '//lticp:contact/lticp:email') @vendor_contact_name = get_node_text(vendor, '//lticp:contact/lticp:name') end if custom = REXML::XPath.first(root, 'blti:custom', LTI_NAMESPACES) set_properties(@custom_params, custom) end REXML::XPath.each(root, 'blti:extensions', LTI_NAMESPACES) do |vendor_ext_node| platform = vendor_ext_node.attributes['platform'] properties = {} set_properties(properties, vendor_ext_node) REXML::XPath.each(vendor_ext_node, 'lticm:options', LTI_NAMESPACES) do |options_node| opt_name = options_node.attributes['name'] options = {} set_properties(options, options_node) properties[opt_name] = options end self.set_ext_params(platform, properties) end end end
[ "def", "process_xml", "(", "xml", ")", "doc", "=", "REXML", "::", "Document", ".", "new", "xml", "if", "root", "=", "REXML", "::", "XPath", ".", "first", "(", "doc", ",", "'xmlns:cartridge_basiclti_link'", ")", "@title", "=", "get_node_text", "(", "root", ...
Parse tool configuration data out of the Common Cartridge LTI link XML
[ "Parse", "tool", "configuration", "data", "out", "of", "the", "Common", "Cartridge", "LTI", "link", "XML" ]
969613a50f3a43345a8b0c92ca5f0e9d0251d5b7
https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L89-L129
valid
instructure/ims-lti
lib/ims/lti/services/tool_config.rb
IMS::LTI::Services.ToolConfig.to_xml
def to_xml(opts = {}) builder = Builder::XmlMarkup.new(:indent => opts[:indent] || 0) builder.instruct! builder.cartridge_basiclti_link("xmlns" => "http://www.imsglobal.org/xsd/imslticc_v1p0", "xmlns:blti" => 'http://www.imsglobal.org/xsd/imsbasiclti_v1p0', "xmlns:lticm" => 'http://www.imsglobal.org/xsd/imslticm_v1p0', "xmlns:lticp" => 'http://www.imsglobal.org/xsd/imslticp_v1p0', "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation" => "http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd" ) do |blti_node| %w{title description launch_url secure_launch_url icon secure_icon}.each do |key| blti_node.blti key.to_sym, self.send(key) if self.send(key) end vendor_keys = %w{name code description url} if vendor_keys.any? { |k| self.send("vendor_#{k}") } || vendor_contact_email blti_node.blti :vendor do |v_node| vendor_keys.each do |key| v_node.lticp key.to_sym, self.send("vendor_#{key}") if self.send("vendor_#{key}") end if vendor_contact_email v_node.lticp :contact do |c_node| c_node.lticp :name, vendor_contact_name c_node.lticp :email, vendor_contact_email end end end end if !@custom_params.empty? blti_node.tag!("blti:custom") do |custom_node| @custom_params.keys.sort.each do |key| val = @custom_params[key] custom_node.lticm :property, val, 'name' => key end end end if !@extensions.empty? @extensions.keys.sort.each do |ext_platform| ext_params = @extensions[ext_platform] blti_node.blti(:extensions, :platform => ext_platform) do |ext_node| ext_params.keys.sort.each do |key| val = ext_params[key] if val.is_a?(Hash) ext_node.lticm(:options, :name => key) do |type_node| val.keys.sort.each do |p_key| p_val = val[p_key] type_node.lticm :property, p_val, 'name' => p_key end end else ext_node.lticm :property, val, 'name' => key end end end end end blti_node.cartridge_bundle(:identifierref => @cartridge_bundle) if @cartridge_bundle blti_node.cartridge_icon(:identifierref => @cartridge_icon) if @cartridge_icon end end
ruby
def to_xml(opts = {}) builder = Builder::XmlMarkup.new(:indent => opts[:indent] || 0) builder.instruct! builder.cartridge_basiclti_link("xmlns" => "http://www.imsglobal.org/xsd/imslticc_v1p0", "xmlns:blti" => 'http://www.imsglobal.org/xsd/imsbasiclti_v1p0', "xmlns:lticm" => 'http://www.imsglobal.org/xsd/imslticm_v1p0', "xmlns:lticp" => 'http://www.imsglobal.org/xsd/imslticp_v1p0', "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation" => "http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd" ) do |blti_node| %w{title description launch_url secure_launch_url icon secure_icon}.each do |key| blti_node.blti key.to_sym, self.send(key) if self.send(key) end vendor_keys = %w{name code description url} if vendor_keys.any? { |k| self.send("vendor_#{k}") } || vendor_contact_email blti_node.blti :vendor do |v_node| vendor_keys.each do |key| v_node.lticp key.to_sym, self.send("vendor_#{key}") if self.send("vendor_#{key}") end if vendor_contact_email v_node.lticp :contact do |c_node| c_node.lticp :name, vendor_contact_name c_node.lticp :email, vendor_contact_email end end end end if !@custom_params.empty? blti_node.tag!("blti:custom") do |custom_node| @custom_params.keys.sort.each do |key| val = @custom_params[key] custom_node.lticm :property, val, 'name' => key end end end if !@extensions.empty? @extensions.keys.sort.each do |ext_platform| ext_params = @extensions[ext_platform] blti_node.blti(:extensions, :platform => ext_platform) do |ext_node| ext_params.keys.sort.each do |key| val = ext_params[key] if val.is_a?(Hash) ext_node.lticm(:options, :name => key) do |type_node| val.keys.sort.each do |p_key| p_val = val[p_key] type_node.lticm :property, p_val, 'name' => p_key end end else ext_node.lticm :property, val, 'name' => key end end end end end blti_node.cartridge_bundle(:identifierref => @cartridge_bundle) if @cartridge_bundle blti_node.cartridge_icon(:identifierref => @cartridge_icon) if @cartridge_icon end end
[ "def", "to_xml", "(", "opts", "=", "{", "}", ")", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "opts", "[", ":indent", "]", "||", "0", ")", "builder", ".", "instruct!", "builder", ".", "cartridge_basiclti_link", "(", ...
Generate XML from the current settings
[ "Generate", "XML", "from", "the", "current", "settings" ]
969613a50f3a43345a8b0c92ca5f0e9d0251d5b7
https://github.com/instructure/ims-lti/blob/969613a50f3a43345a8b0c92ca5f0e9d0251d5b7/lib/ims/lti/services/tool_config.rb#L132-L196
valid
mbleigh/seed-fu
lib/seed-fu/active_record_extension.rb
SeedFu.ActiveRecordExtension.seed
def seed(*args, &block) SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block)).seed end
ruby
def seed(*args, &block) SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block)).seed end
[ "def", "seed", "(", "*", "args", ",", "&", "block", ")", "SeedFu", "::", "Seeder", ".", "new", "(", "self", ",", "*", "parse_seed_fu_args", "(", "args", ",", "block", ")", ")", ".", "seed", "end" ]
Load some seed data. There are two ways to do this. Verbose syntax -------------- This will seed a single record. The `:id` parameter ensures that if a record already exists in the database with the same id, then it will be updated with the name and age, rather than created from scratch. Person.seed(:id) do |s| s.id = 1 s.name = "Jon" s.age = 21 end Note that `:id` is the default attribute used to identify a seed, so it need not be specified. Terse syntax ------------ This is a more succinct way to load multiple records. Note that both `:x` and `:y` are being used to identify a seed here. Point.seed(:x, :y, { :x => 3, :y => 10, :name => "Home" }, { :x => 5, :y => 9, :name => "Office" } )
[ "Load", "some", "seed", "data", ".", "There", "are", "two", "ways", "to", "do", "this", "." ]
34c054c914858c3d7685f83d16dea5c0e2114561
https://github.com/mbleigh/seed-fu/blob/34c054c914858c3d7685f83d16dea5c0e2114561/lib/seed-fu/active_record_extension.rb#L31-L33
valid
janko/image_processing
lib/image_processing/pipeline.rb
ImageProcessing.Pipeline.call
def call(save: true) if save == false call_processor elsif destination handle_destination do call_processor(destination: destination) end else create_tempfile do |tempfile| call_processor(destination: tempfile.path) end end end
ruby
def call(save: true) if save == false call_processor elsif destination handle_destination do call_processor(destination: destination) end else create_tempfile do |tempfile| call_processor(destination: tempfile.path) end end end
[ "def", "call", "(", "save", ":", "true", ")", "if", "save", "==", "false", "call_processor", "elsif", "destination", "handle_destination", "do", "call_processor", "(", "destination", ":", "destination", ")", "end", "else", "create_tempfile", "do", "|", "tempfile...
Initializes the pipeline with all the processing options. Determines the destination and calls the processor.
[ "Initializes", "the", "pipeline", "with", "all", "the", "processing", "options", ".", "Determines", "the", "destination", "and", "calls", "the", "processor", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L19-L31
valid
janko/image_processing
lib/image_processing/pipeline.rb
ImageProcessing.Pipeline.destination_format
def destination_format format = File.extname(destination)[1..-1] if destination format ||= self.format format ||= File.extname(source_path)[1..-1] if source_path format || DEFAULT_FORMAT end
ruby
def destination_format format = File.extname(destination)[1..-1] if destination format ||= self.format format ||= File.extname(source_path)[1..-1] if source_path format || DEFAULT_FORMAT end
[ "def", "destination_format", "format", "=", "File", ".", "extname", "(", "destination", ")", "[", "1", "..", "-", "1", "]", "if", "destination", "format", "||=", "self", ".", "format", "format", "||=", "File", ".", "extname", "(", "source_path", ")", "["...
Determines the appropriate destination image format.
[ "Determines", "the", "appropriate", "destination", "image", "format", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L39-L45
valid
janko/image_processing
lib/image_processing/pipeline.rb
ImageProcessing.Pipeline.create_tempfile
def create_tempfile tempfile = Tempfile.new(["image_processing", ".#{destination_format}"], binmode: true) yield tempfile tempfile.open tempfile rescue tempfile.close! if tempfile raise end
ruby
def create_tempfile tempfile = Tempfile.new(["image_processing", ".#{destination_format}"], binmode: true) yield tempfile tempfile.open tempfile rescue tempfile.close! if tempfile raise end
[ "def", "create_tempfile", "tempfile", "=", "Tempfile", ".", "new", "(", "[", "\"image_processing\"", ",", "\".#{destination_format}\"", "]", ",", "binmode", ":", "true", ")", "yield", "tempfile", "tempfile", ".", "open", "tempfile", "rescue", "tempfile", ".", "c...
Creates a new tempfile for the destination file, yields it, and refreshes the file descriptor to get the updated file.
[ "Creates", "a", "new", "tempfile", "for", "the", "destination", "file", "yields", "it", "and", "refreshes", "the", "file", "descriptor", "to", "get", "the", "updated", "file", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L61-L71
valid
janko/image_processing
lib/image_processing/pipeline.rb
ImageProcessing.Pipeline.handle_destination
def handle_destination destination_existed = File.exist?(destination) yield rescue File.delete(destination) if File.exist?(destination) && !destination_existed raise end
ruby
def handle_destination destination_existed = File.exist?(destination) yield rescue File.delete(destination) if File.exist?(destination) && !destination_existed raise end
[ "def", "handle_destination", "destination_existed", "=", "File", ".", "exist?", "(", "destination", ")", "yield", "rescue", "File", ".", "delete", "(", "destination", ")", "if", "File", ".", "exist?", "(", "destination", ")", "&&", "!", "destination_existed", ...
In case of processing errors, both libvips and imagemagick will leave the empty destination file they created, so this method makes sure it is deleted in case an exception is raised on saving the image.
[ "In", "case", "of", "processing", "errors", "both", "libvips", "and", "imagemagick", "will", "leave", "the", "empty", "destination", "file", "they", "created", "so", "this", "method", "makes", "sure", "it", "is", "deleted", "in", "case", "an", "exception", "...
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/pipeline.rb#L76-L82
valid
janko/image_processing
lib/image_processing/chainable.rb
ImageProcessing.Chainable.apply
def apply(operations) operations.inject(self) do |builder, (name, argument)| if argument == true || argument == nil builder.send(name) elsif argument.is_a?(Array) builder.send(name, *argument) else builder.send(name, argument) end end end
ruby
def apply(operations) operations.inject(self) do |builder, (name, argument)| if argument == true || argument == nil builder.send(name) elsif argument.is_a?(Array) builder.send(name, *argument) else builder.send(name, argument) end end end
[ "def", "apply", "(", "operations", ")", "operations", ".", "inject", "(", "self", ")", "do", "|", "builder", ",", "(", "name", ",", "argument", ")", "|", "if", "argument", "==", "true", "||", "argument", "==", "nil", "builder", ".", "send", "(", "nam...
Add multiple operations as a hash or an array. .apply(resize_to_limit: [400, 400], strip: true) # or .apply([[:resize_to_limit, [400, 400]], [:strip, true])
[ "Add", "multiple", "operations", "as", "a", "hash", "or", "an", "array", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L29-L39
valid
janko/image_processing
lib/image_processing/chainable.rb
ImageProcessing.Chainable.call
def call(file = nil, destination: nil, **call_options) options = {} options = options.merge(source: file) if file options = options.merge(destination: destination) if destination branch(options).call!(**call_options) end
ruby
def call(file = nil, destination: nil, **call_options) options = {} options = options.merge(source: file) if file options = options.merge(destination: destination) if destination branch(options).call!(**call_options) end
[ "def", "call", "(", "file", "=", "nil", ",", "destination", ":", "nil", ",", "**", "call_options", ")", "options", "=", "{", "}", "options", "=", "options", ".", "merge", "(", "source", ":", "file", ")", "if", "file", "options", "=", "options", ".", ...
Call the defined processing and get the result. Allows specifying the source file and destination.
[ "Call", "the", "defined", "processing", "and", "get", "the", "result", ".", "Allows", "specifying", "the", "source", "file", "and", "destination", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L57-L63
valid
janko/image_processing
lib/image_processing/chainable.rb
ImageProcessing.Chainable.branch
def branch(loader: nil, saver: nil, operations: nil, **other_options) options = respond_to?(:options) ? self.options : DEFAULT_OPTIONS options = options.merge(loader: options[:loader].merge(loader)) if loader options = options.merge(saver: options[:saver].merge(saver)) if saver options = options.merge(operations: options[:operations] + operations) if operations options = options.merge(processor: self::Processor) unless self.is_a?(Builder) options = options.merge(other_options) options.freeze Builder.new(options) end
ruby
def branch(loader: nil, saver: nil, operations: nil, **other_options) options = respond_to?(:options) ? self.options : DEFAULT_OPTIONS options = options.merge(loader: options[:loader].merge(loader)) if loader options = options.merge(saver: options[:saver].merge(saver)) if saver options = options.merge(operations: options[:operations] + operations) if operations options = options.merge(processor: self::Processor) unless self.is_a?(Builder) options = options.merge(other_options) options.freeze Builder.new(options) end
[ "def", "branch", "(", "loader", ":", "nil", ",", "saver", ":", "nil", ",", "operations", ":", "nil", ",", "**", "other_options", ")", "options", "=", "respond_to?", "(", ":options", ")", "?", "self", ".", "options", ":", "DEFAULT_OPTIONS", "options", "="...
Creates a new builder object, merging current options with new options.
[ "Creates", "a", "new", "builder", "object", "merging", "current", "options", "with", "new", "options", "." ]
4b4917d88bab1f73ebdc733f8a583734322e5226
https://github.com/janko/image_processing/blob/4b4917d88bab1f73ebdc733f8a583734322e5226/lib/image_processing/chainable.rb#L66-L78
valid
postmodern/spidr
lib/spidr/page/cookies.rb
Spidr.Page.cookie_params
def cookie_params params = {} cookies.each do |value| value.split(';').each do |param| param.strip! name, value = param.split('=',2) unless name =~ RESERVED_COOKIE_NAMES params[name] = (value || '') end end end return params end
ruby
def cookie_params params = {} cookies.each do |value| value.split(';').each do |param| param.strip! name, value = param.split('=',2) unless name =~ RESERVED_COOKIE_NAMES params[name] = (value || '') end end end return params end
[ "def", "cookie_params", "params", "=", "{", "}", "cookies", ".", "each", "do", "|", "value", "|", "value", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "param", "|", "param", ".", "strip!", "name", ",", "value", "=", "param", ".", "split"...
The Cookie key -> value pairs returned with the response. @return [Hash{String => String}] The cookie keys and values. @since 0.2.2
[ "The", "Cookie", "key", "-", ">", "value", "pairs", "returned", "with", "the", "response", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/cookies.rb#L42-L58
valid
postmodern/spidr
lib/spidr/session_cache.rb
Spidr.SessionCache.active?
def active?(url) # normalize the url url = URI(url) # session key key = key_for(url) return @sessions.has_key?(key) end
ruby
def active?(url) # normalize the url url = URI(url) # session key key = key_for(url) return @sessions.has_key?(key) end
[ "def", "active?", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "key", "=", "key_for", "(", "url", ")", "return", "@sessions", ".", "has_key?", "(", "key", ")", "end" ]
Creates a new session cache. @param [Hash] options Configuration options. @option [Hash] :proxy (Spidr.proxy) Proxy options. @option [Integer] :open_timeout (Spidr.open_timeout) Optional open timeout. @option [Integer] :ssl_timeout (Spidr.ssl_timeout) Optional ssl timeout. @option [Integer] :read_timeout (Spidr.read_timeout) Optional read timeout. @option [Integer] :continue_timeout (Spidr.continue_timeout) Optional `Continue` timeout. @option [Integer] :keep_alive_timeout (Spidr.keep_alive_timeout) Optional `Keep-Alive` timeout. @since 0.6.0 Determines if there is an active HTTP session for a given URL. @param [URI::HTTP, String] url The URL that represents a session. @return [Boolean] Specifies whether there is an active HTTP session. @since 0.2.3
[ "Creates", "a", "new", "session", "cache", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L66-L74
valid
postmodern/spidr
lib/spidr/session_cache.rb
Spidr.SessionCache.[]
def [](url) # normalize the url url = URI(url) # session key key = key_for(url) unless @sessions[key] session = Net::HTTP::Proxy( @proxy.host, @proxy.port, @proxy.user, @proxy.password ).new(url.host,url.port) session.open_timeout = @open_timeout if @open_timeout session.read_timeout = @read_timeout if @read_timeout session.continue_timeout = @continue_timeout if @continue_timeout session.keep_alive_timeout = @keep_alive_timeout if @keep_alive_timeout if url.scheme == 'https' session.use_ssl = true session.verify_mode = OpenSSL::SSL::VERIFY_NONE session.ssl_timeout = @ssl_timeout session.start end @sessions[key] = session end return @sessions[key] end
ruby
def [](url) # normalize the url url = URI(url) # session key key = key_for(url) unless @sessions[key] session = Net::HTTP::Proxy( @proxy.host, @proxy.port, @proxy.user, @proxy.password ).new(url.host,url.port) session.open_timeout = @open_timeout if @open_timeout session.read_timeout = @read_timeout if @read_timeout session.continue_timeout = @continue_timeout if @continue_timeout session.keep_alive_timeout = @keep_alive_timeout if @keep_alive_timeout if url.scheme == 'https' session.use_ssl = true session.verify_mode = OpenSSL::SSL::VERIFY_NONE session.ssl_timeout = @ssl_timeout session.start end @sessions[key] = session end return @sessions[key] end
[ "def", "[]", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "key", "=", "key_for", "(", "url", ")", "unless", "@sessions", "[", "key", "]", "session", "=", "Net", "::", "HTTP", "::", "Proxy", "(", "@proxy", ".", "host", ",", "@proxy", ".", ...
Provides an active HTTP session for a given URL. @param [URI::HTTP, String] url The URL which will be requested later. @return [Net::HTTP] The active HTTP session object.
[ "Provides", "an", "active", "HTTP", "session", "for", "a", "given", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L85-L116
valid
postmodern/spidr
lib/spidr/session_cache.rb
Spidr.SessionCache.kill!
def kill!(url) # normalize the url url = URI(url) # session key key = key_for(url) if (sess = @sessions[key]) begin sess.finish rescue IOError end @sessions.delete(key) end end
ruby
def kill!(url) # normalize the url url = URI(url) # session key key = key_for(url) if (sess = @sessions[key]) begin sess.finish rescue IOError end @sessions.delete(key) end end
[ "def", "kill!", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "key", "=", "key_for", "(", "url", ")", "if", "(", "sess", "=", "@sessions", "[", "key", "]", ")", "begin", "sess", ".", "finish", "rescue", "IOError", "end", "@sessions", ".", ...
Destroys an HTTP session for the given scheme, host and port. @param [URI::HTTP, String] url The URL of the requested session. @return [nil] @since 0.2.2
[ "Destroys", "an", "HTTP", "session", "for", "the", "given", "scheme", "host", "and", "port", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/session_cache.rb#L128-L143
valid
postmodern/spidr
lib/spidr/agent/sanitizers.rb
Spidr.Agent.sanitize_url
def sanitize_url(url) url = URI(url) url.fragment = nil if @strip_fragments url.query = nil if @strip_query return url end
ruby
def sanitize_url(url) url = URI(url) url.fragment = nil if @strip_fragments url.query = nil if @strip_query return url end
[ "def", "sanitize_url", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "url", ".", "fragment", "=", "nil", "if", "@strip_fragments", "url", ".", "query", "=", "nil", "if", "@strip_query", "return", "url", "end" ]
Sanitizes a URL based on filtering options. @param [URI::HTTP, URI::HTTPS, String] url The URL to be sanitized @return [URI::HTTP, URI::HTTPS] The new sanitized URL. @since 0.2.2
[ "Sanitizes", "a", "URL", "based", "on", "filtering", "options", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/sanitizers.rb#L23-L30
valid
postmodern/spidr
lib/spidr/page.rb
Spidr.Page.doc
def doc unless body.empty? doc_class = if html? Nokogiri::HTML::Document elsif rss? || atom? || xml? || xsl? Nokogiri::XML::Document end if doc_class begin @doc ||= doc_class.parse(body, @url.to_s, content_charset) rescue end end end end
ruby
def doc unless body.empty? doc_class = if html? Nokogiri::HTML::Document elsif rss? || atom? || xml? || xsl? Nokogiri::XML::Document end if doc_class begin @doc ||= doc_class.parse(body, @url.to_s, content_charset) rescue end end end end
[ "def", "doc", "unless", "body", ".", "empty?", "doc_class", "=", "if", "html?", "Nokogiri", "::", "HTML", "::", "Document", "elsif", "rss?", "||", "atom?", "||", "xml?", "||", "xsl?", "Nokogiri", "::", "XML", "::", "Document", "end", "if", "doc_class", "...
Returns a parsed document object for HTML, XML, RSS and Atom pages. @return [Nokogiri::HTML::Document, Nokogiri::XML::Document, nil] The document that represents HTML or XML pages. Returns `nil` if the page is neither HTML, XML, RSS, Atom or if the page could not be parsed properly. @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/HTML/Document.html
[ "Returns", "a", "parsed", "document", "object", "for", "HTML", "XML", "RSS", "and", "Atom", "pages", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page.rb#L55-L70
valid
postmodern/spidr
lib/spidr/page/content_types.rb
Spidr.Page.content_charset
def content_charset content_types.each do |value| if value.include?(';') value.split(';').each do |param| param.strip! if param.start_with?('charset=') return param.split('=',2).last end end end end return nil end
ruby
def content_charset content_types.each do |value| if value.include?(';') value.split(';').each do |param| param.strip! if param.start_with?('charset=') return param.split('=',2).last end end end end return nil end
[ "def", "content_charset", "content_types", ".", "each", "do", "|", "value", "|", "if", "value", ".", "include?", "(", "';'", ")", "value", ".", "split", "(", "';'", ")", ".", "each", "do", "|", "param", "|", "param", ".", "strip!", "if", "param", "."...
The charset included in the Content-Type. @return [String, nil] The charset of the content. @since 0.4.0
[ "The", "charset", "included", "in", "the", "Content", "-", "Type", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/content_types.rb#L33-L47
valid
postmodern/spidr
lib/spidr/page/content_types.rb
Spidr.Page.is_content_type?
def is_content_type?(type) if type.include?('/') # otherwise only match the first param content_types.any? do |value| value = value.split(';',2).first value == type end else # otherwise only match the sub-type content_types.any? do |value| value = value.split(';',2).first value = value.split('/',2).last value == type end end end
ruby
def is_content_type?(type) if type.include?('/') # otherwise only match the first param content_types.any? do |value| value = value.split(';',2).first value == type end else # otherwise only match the sub-type content_types.any? do |value| value = value.split(';',2).first value = value.split('/',2).last value == type end end end
[ "def", "is_content_type?", "(", "type", ")", "if", "type", ".", "include?", "(", "'/'", ")", "content_types", ".", "any?", "do", "|", "value", "|", "value", "=", "value", ".", "split", "(", "';'", ",", "2", ")", ".", "first", "value", "==", "type", ...
Determines if any of the content-types of the page include a given type. @param [String] type The content-type to test for. @return [Boolean] Specifies whether the page includes the given content-type. @example Match the Content-Type page.is_content_type?('application/json') @example Match the sub-type of the Content-Type page.is_content_type?('json') @since 0.4.0
[ "Determines", "if", "any", "of", "the", "content", "-", "types", "of", "the", "page", "include", "a", "given", "type", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/content_types.rb#L67-L84
valid
postmodern/spidr
lib/spidr/cookie_jar.rb
Spidr.CookieJar.[]=
def []=(host,cookies) collected = self[host] cookies.each do |key,value| if collected[key] != value collected.merge!(cookies) @dirty << host break end end return cookies end
ruby
def []=(host,cookies) collected = self[host] cookies.each do |key,value| if collected[key] != value collected.merge!(cookies) @dirty << host break end end return cookies end
[ "def", "[]=", "(", "host", ",", "cookies", ")", "collected", "=", "self", "[", "host", "]", "cookies", ".", "each", "do", "|", "key", ",", "value", "|", "if", "collected", "[", "key", "]", "!=", "value", "collected", ".", "merge!", "(", "cookies", ...
Add a cookie to the jar for a particular domain. @param [String] host Host or domain name to associate with the cookie. @param [Hash{String => String}] cookies Cookie params. @since 0.2.2
[ "Add", "a", "cookie", "to", "the", "jar", "for", "a", "particular", "domain", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L73-L86
valid
postmodern/spidr
lib/spidr/cookie_jar.rb
Spidr.CookieJar.from_page
def from_page(page) cookies = page.cookie_params unless cookies.empty? self[page.url.host] = cookies return true end return false end
ruby
def from_page(page) cookies = page.cookie_params unless cookies.empty? self[page.url.host] = cookies return true end return false end
[ "def", "from_page", "(", "page", ")", "cookies", "=", "page", ".", "cookie_params", "unless", "cookies", ".", "empty?", "self", "[", "page", ".", "url", ".", "host", "]", "=", "cookies", "return", "true", "end", "return", "false", "end" ]
Retrieve cookies for a domain from a page response header. @param [Page] page The response page from which to extract cookie data. @return [Boolean] Specifies whether cookies were added from the page. @since 0.2.2
[ "Retrieve", "cookies", "for", "a", "domain", "from", "a", "page", "response", "header", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L99-L108
valid
postmodern/spidr
lib/spidr/cookie_jar.rb
Spidr.CookieJar.for_host
def for_host(host) if @dirty.include?(host) values = [] cookies_for_host(host).each do |name,value| values << "#{name}=#{value}" end @cookies[host] = values.join('; ') @dirty.delete(host) end return @cookies[host] end
ruby
def for_host(host) if @dirty.include?(host) values = [] cookies_for_host(host).each do |name,value| values << "#{name}=#{value}" end @cookies[host] = values.join('; ') @dirty.delete(host) end return @cookies[host] end
[ "def", "for_host", "(", "host", ")", "if", "@dirty", ".", "include?", "(", "host", ")", "values", "=", "[", "]", "cookies_for_host", "(", "host", ")", ".", "each", "do", "|", "name", ",", "value", "|", "values", "<<", "\"#{name}=#{value}\"", "end", "@c...
Returns the pre-encoded Cookie for a given host. @param [String] host The name of the host. @return [String] The encoded Cookie. @since 0.2.2
[ "Returns", "the", "pre", "-", "encoded", "Cookie", "for", "a", "given", "host", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/cookie_jar.rb#L121-L134
valid
postmodern/spidr
lib/spidr/auth_store.rb
Spidr.AuthStore.[]
def [](url) # normalize the url url = URI(url) key = [url.scheme, url.host, url.port] paths = @credentials[key] return nil unless paths # longest path first ordered_paths = paths.keys.sort_by { |path_key| -path_key.length } # directories of the path path_dirs = URI.expand_path(url.path).split('/') ordered_paths.each do |path| return paths[path] if path_dirs[0,path.length] == path end return nil end
ruby
def [](url) # normalize the url url = URI(url) key = [url.scheme, url.host, url.port] paths = @credentials[key] return nil unless paths # longest path first ordered_paths = paths.keys.sort_by { |path_key| -path_key.length } # directories of the path path_dirs = URI.expand_path(url.path).split('/') ordered_paths.each do |path| return paths[path] if path_dirs[0,path.length] == path end return nil end
[ "def", "[]", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "key", "=", "[", "url", ".", "scheme", ",", "url", ".", "host", ",", "url", ".", "port", "]", "paths", "=", "@credentials", "[", "key", "]", "return", "nil", "unless", "paths", "...
Creates a new auth store. @since 0.2.2 Given a URL, return the most specific matching auth credential. @param [URI] url A fully qualified url including optional path. @return [AuthCredential, nil] Closest matching {AuthCredential} values for the URL, or `nil` if nothing matches. @since 0.2.2
[ "Creates", "a", "new", "auth", "store", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/auth_store.rb#L35-L55
valid
postmodern/spidr
lib/spidr/auth_store.rb
Spidr.AuthStore.[]=
def []=(url,auth) # normalize the url url = URI(url) # normalize the URL path path = URI.expand_path(url.path) key = [url.scheme, url.host, url.port] @credentials[key] ||= {} @credentials[key][path.split('/')] = auth return auth end
ruby
def []=(url,auth) # normalize the url url = URI(url) # normalize the URL path path = URI.expand_path(url.path) key = [url.scheme, url.host, url.port] @credentials[key] ||= {} @credentials[key][path.split('/')] = auth return auth end
[ "def", "[]=", "(", "url", ",", "auth", ")", "url", "=", "URI", "(", "url", ")", "path", "=", "URI", ".", "expand_path", "(", "url", ".", "path", ")", "key", "=", "[", "url", ".", "scheme", ",", "url", ".", "host", ",", "url", ".", "port", "]"...
Add an auth credential to the store for supplied base URL. @param [URI] url A URL pattern to associate with a set of auth credentials. @param [AuthCredential] auth The auth credential for this URL pattern. @return [AuthCredential] The newly added auth credential. @since 0.2.2
[ "Add", "an", "auth", "credential", "to", "the", "store", "for", "supplied", "base", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/auth_store.rb#L71-L83
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.run
def run(&block) @running = true until (@queue.empty? || paused? || limit_reached?) begin visit_page(dequeue,&block) rescue Actions::Paused return self rescue Actions::Action end end @running = false @sessions.clear return self end
ruby
def run(&block) @running = true until (@queue.empty? || paused? || limit_reached?) begin visit_page(dequeue,&block) rescue Actions::Paused return self rescue Actions::Action end end @running = false @sessions.clear return self end
[ "def", "run", "(", "&", "block", ")", "@running", "=", "true", "until", "(", "@queue", ".", "empty?", "||", "paused?", "||", "limit_reached?", ")", "begin", "visit_page", "(", "dequeue", ",", "&", "block", ")", "rescue", "Actions", "::", "Paused", "retur...
Start spidering until the queue becomes empty or the agent is paused. @yield [page] If a block is given, it will be passed every page visited. @yieldparam [Page] page A page which has been visited.
[ "Start", "spidering", "until", "the", "queue", "becomes", "empty", "or", "the", "agent", "is", "paused", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L368-L383
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.enqueue
def enqueue(url,level=0) url = sanitize_url(url) if (!(queued?(url)) && visit?(url)) link = url.to_s begin @every_url_blocks.each { |url_block| url_block.call(url) } @every_url_like_blocks.each do |pattern,url_blocks| match = case pattern when Regexp link =~ pattern else (pattern == link) || (pattern == url) end if match url_blocks.each { |url_block| url_block.call(url) } end end rescue Actions::Paused => action raise(action) rescue Actions::SkipLink return false rescue Actions::Action end @queue << url @levels[url] = level return true end return false end
ruby
def enqueue(url,level=0) url = sanitize_url(url) if (!(queued?(url)) && visit?(url)) link = url.to_s begin @every_url_blocks.each { |url_block| url_block.call(url) } @every_url_like_blocks.each do |pattern,url_blocks| match = case pattern when Regexp link =~ pattern else (pattern == link) || (pattern == url) end if match url_blocks.each { |url_block| url_block.call(url) } end end rescue Actions::Paused => action raise(action) rescue Actions::SkipLink return false rescue Actions::Action end @queue << url @levels[url] = level return true end return false end
[ "def", "enqueue", "(", "url", ",", "level", "=", "0", ")", "url", "=", "sanitize_url", "(", "url", ")", "if", "(", "!", "(", "queued?", "(", "url", ")", ")", "&&", "visit?", "(", "url", ")", ")", "link", "=", "url", ".", "to_s", "begin", "@ever...
Enqueues a given URL for visiting, only if it passes all of the agent's rules for visiting a given URL. @param [URI::HTTP, String] url The URL to enqueue for visiting. @return [Boolean] Specifies whether the URL was enqueued, or ignored.
[ "Enqueues", "a", "given", "URL", "for", "visiting", "only", "if", "it", "passes", "all", "of", "the", "agent", "s", "rules", "for", "visiting", "a", "given", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L534-L568
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.get_page
def get_page(url) url = URI(url) prepare_request(url) do |session,path,headers| new_page = Page.new(url,session.get(path,headers)) # save any new cookies @cookies.from_page(new_page) yield new_page if block_given? return new_page end end
ruby
def get_page(url) url = URI(url) prepare_request(url) do |session,path,headers| new_page = Page.new(url,session.get(path,headers)) # save any new cookies @cookies.from_page(new_page) yield new_page if block_given? return new_page end end
[ "def", "get_page", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "prepare_request", "(", "url", ")", "do", "|", "session", ",", "path", ",", "headers", "|", "new_page", "=", "Page", ".", "new", "(", "url", ",", "session", ".", "get", "(", ...
Requests and creates a new Page object from a given URL. @param [URI::HTTP] url The URL to request. @yield [page] If a block is given, it will be passed the page that represents the response. @yieldparam [Page] page The page for the response. @return [Page, nil] The page for the response, or `nil` if the request failed.
[ "Requests", "and", "creates", "a", "new", "Page", "object", "from", "a", "given", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L586-L598
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.post_page
def post_page(url,post_data='') url = URI(url) prepare_request(url) do |session,path,headers| new_page = Page.new(url,session.post(path,post_data,headers)) # save any new cookies @cookies.from_page(new_page) yield new_page if block_given? return new_page end end
ruby
def post_page(url,post_data='') url = URI(url) prepare_request(url) do |session,path,headers| new_page = Page.new(url,session.post(path,post_data,headers)) # save any new cookies @cookies.from_page(new_page) yield new_page if block_given? return new_page end end
[ "def", "post_page", "(", "url", ",", "post_data", "=", "''", ")", "url", "=", "URI", "(", "url", ")", "prepare_request", "(", "url", ")", "do", "|", "session", ",", "path", ",", "headers", "|", "new_page", "=", "Page", ".", "new", "(", "url", ",", ...
Posts supplied form data and creates a new Page object from a given URL. @param [URI::HTTP] url The URL to request. @param [String] post_data Form option data. @yield [page] If a block is given, it will be passed the page that represents the response. @yieldparam [Page] page The page for the response. @return [Page, nil] The page for the response, or `nil` if the request failed. @since 0.2.2
[ "Posts", "supplied", "form", "data", "and", "creates", "a", "new", "Page", "object", "from", "a", "given", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L621-L633
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.visit_page
def visit_page(url) url = sanitize_url(url) get_page(url) do |page| @history << page.url begin @every_page_blocks.each { |page_block| page_block.call(page) } yield page if block_given? rescue Actions::Paused => action raise(action) rescue Actions::SkipPage return nil rescue Actions::Action end page.each_url do |next_url| begin @every_link_blocks.each do |link_block| link_block.call(page.url,next_url) end rescue Actions::Paused => action raise(action) rescue Actions::SkipLink next rescue Actions::Action end if (@max_depth.nil? || @max_depth > @levels[url]) enqueue(next_url,@levels[url] + 1) end end end end
ruby
def visit_page(url) url = sanitize_url(url) get_page(url) do |page| @history << page.url begin @every_page_blocks.each { |page_block| page_block.call(page) } yield page if block_given? rescue Actions::Paused => action raise(action) rescue Actions::SkipPage return nil rescue Actions::Action end page.each_url do |next_url| begin @every_link_blocks.each do |link_block| link_block.call(page.url,next_url) end rescue Actions::Paused => action raise(action) rescue Actions::SkipLink next rescue Actions::Action end if (@max_depth.nil? || @max_depth > @levels[url]) enqueue(next_url,@levels[url] + 1) end end end end
[ "def", "visit_page", "(", "url", ")", "url", "=", "sanitize_url", "(", "url", ")", "get_page", "(", "url", ")", "do", "|", "page", "|", "@history", "<<", "page", ".", "url", "begin", "@every_page_blocks", ".", "each", "{", "|", "page_block", "|", "page...
Visits a given URL, and enqueus the links recovered from the URL to be visited later. @param [URI::HTTP, String] url The URL to visit. @yield [page] If a block is given, it will be passed the page which was visited. @yieldparam [Page] page The page which was visited. @return [Page, nil] The page that was visited. If `nil` is returned, either the request for the page failed, or the page was skipped.
[ "Visits", "a", "given", "URL", "and", "enqueus", "the", "links", "recovered", "from", "the", "URL", "to", "be", "visited", "later", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L652-L686
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.prepare_request_headers
def prepare_request_headers(url) # set any additional HTTP headers headers = @default_headers.dup unless @host_headers.empty? @host_headers.each do |name,header| if url.host.match(name) headers['Host'] = header break end end end headers['Host'] ||= @host_header if @host_header headers['User-Agent'] = @user_agent if @user_agent headers['Referer'] = @referer if @referer if (authorization = @authorized.for_url(url)) headers['Authorization'] = "Basic #{authorization}" end if (header_cookies = @cookies.for_host(url.host)) headers['Cookie'] = header_cookies end return headers end
ruby
def prepare_request_headers(url) # set any additional HTTP headers headers = @default_headers.dup unless @host_headers.empty? @host_headers.each do |name,header| if url.host.match(name) headers['Host'] = header break end end end headers['Host'] ||= @host_header if @host_header headers['User-Agent'] = @user_agent if @user_agent headers['Referer'] = @referer if @referer if (authorization = @authorized.for_url(url)) headers['Authorization'] = "Basic #{authorization}" end if (header_cookies = @cookies.for_host(url.host)) headers['Cookie'] = header_cookies end return headers end
[ "def", "prepare_request_headers", "(", "url", ")", "headers", "=", "@default_headers", ".", "dup", "unless", "@host_headers", ".", "empty?", "@host_headers", ".", "each", "do", "|", "name", ",", "header", "|", "if", "url", ".", "host", ".", "match", "(", "...
Prepares request headers for the given URL. @param [URI::HTTP] url The URL to prepare the request headers for. @return [Hash{String => String}] The prepared headers. @since 0.6.0
[ "Prepares", "request", "headers", "for", "the", "given", "URL", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L712-L738
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.prepare_request
def prepare_request(url,&block) path = unless url.path.empty? url.path else '/' end # append the URL query to the path path += "?#{url.query}" if url.query headers = prepare_request_headers(url) begin sleep(@delay) if @delay > 0 yield @sessions[url], path, headers rescue SystemCallError, Timeout::Error, SocketError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Zlib::Error @sessions.kill!(url) failed(url) return nil end end
ruby
def prepare_request(url,&block) path = unless url.path.empty? url.path else '/' end # append the URL query to the path path += "?#{url.query}" if url.query headers = prepare_request_headers(url) begin sleep(@delay) if @delay > 0 yield @sessions[url], path, headers rescue SystemCallError, Timeout::Error, SocketError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Zlib::Error @sessions.kill!(url) failed(url) return nil end end
[ "def", "prepare_request", "(", "url", ",", "&", "block", ")", "path", "=", "unless", "url", ".", "path", ".", "empty?", "url", ".", "path", "else", "'/'", "end", "path", "+=", "\"?#{url.query}\"", "if", "url", ".", "query", "headers", "=", "prepare_reque...
Normalizes the request path and grabs a session to handle page get and post requests. @param [URI::HTTP] url The URL to request. @yield [request] A block whose purpose is to make a page request. @yieldparam [Net::HTTP] session An HTTP session object. @yieldparam [String] path Normalized URL string. @yieldparam [Hash] headers A Hash of request header options. @since 0.2.2
[ "Normalizes", "the", "request", "path", "and", "grabs", "a", "session", "to", "handle", "page", "get", "and", "post", "requests", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L761-L790
valid
postmodern/spidr
lib/spidr/agent.rb
Spidr.Agent.visit?
def visit?(url) !visited?(url) && visit_scheme?(url.scheme) && visit_host?(url.host) && visit_port?(url.port) && visit_link?(url.to_s) && visit_url?(url) && visit_ext?(url.path) && robot_allowed?(url.to_s) end
ruby
def visit?(url) !visited?(url) && visit_scheme?(url.scheme) && visit_host?(url.host) && visit_port?(url.port) && visit_link?(url.to_s) && visit_url?(url) && visit_ext?(url.path) && robot_allowed?(url.to_s) end
[ "def", "visit?", "(", "url", ")", "!", "visited?", "(", "url", ")", "&&", "visit_scheme?", "(", "url", ".", "scheme", ")", "&&", "visit_host?", "(", "url", ".", "host", ")", "&&", "visit_port?", "(", "url", ".", "port", ")", "&&", "visit_link?", "(",...
Determines if a given URL should be visited. @param [URI::HTTP] url The URL in question. @return [Boolean] Specifies whether the given URL should be visited.
[ "Determines", "if", "a", "given", "URL", "should", "be", "visited", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent.rb#L822-L831
valid
postmodern/spidr
lib/spidr/rules.rb
Spidr.Rules.accept?
def accept?(data) unless @accept.empty? @accept.any? { |rule| test_data(data,rule) } else !@reject.any? { |rule| test_data(data,rule) } end end
ruby
def accept?(data) unless @accept.empty? @accept.any? { |rule| test_data(data,rule) } else !@reject.any? { |rule| test_data(data,rule) } end end
[ "def", "accept?", "(", "data", ")", "unless", "@accept", ".", "empty?", "@accept", ".", "any?", "{", "|", "rule", "|", "test_data", "(", "data", ",", "rule", ")", "}", "else", "!", "@reject", ".", "any?", "{", "|", "rule", "|", "test_data", "(", "d...
Creates a new Rules object. @param [Hash] options Additional options. @option options [Array<String, Regexp, Proc>] :accept The patterns to accept data with. @option options [Array<String, Regexp, Proc>] :reject The patterns to reject data with. Determines whether the data should be accepted or rejected. @return [Boolean] Specifies whether the given data was accepted, using the rules acceptance patterns.
[ "Creates", "a", "new", "Rules", "object", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/rules.rb#L41-L47
valid
postmodern/spidr
lib/spidr/agent/events.rb
Spidr.Agent.every_html_doc
def every_html_doc every_page do |page| if (block_given? && page.html?) if (doc = page.doc) yield doc end end end end
ruby
def every_html_doc every_page do |page| if (block_given? && page.html?) if (doc = page.doc) yield doc end end end end
[ "def", "every_html_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "html?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end" ]
Pass every HTML document that the agent parses to a given block. @yield [doc] The block will be passed every HTML document parsed. @yieldparam [Nokogiri::HTML::Document] doc A parsed HTML document. @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/HTML/Document.html
[ "Pass", "every", "HTML", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L302-L310
valid
postmodern/spidr
lib/spidr/agent/events.rb
Spidr.Agent.every_xml_doc
def every_xml_doc every_page do |page| if (block_given? && page.xml?) if (doc = page.doc) yield doc end end end end
ruby
def every_xml_doc every_page do |page| if (block_given? && page.xml?) if (doc = page.doc) yield doc end end end end
[ "def", "every_xml_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "xml?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end" ]
Pass every XML document that the agent parses to a given block. @yield [doc] The block will be passed every XML document parsed. @yieldparam [Nokogiri::XML::Document] doc A parsed XML document. @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html
[ "Pass", "every", "XML", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L323-L331
valid
postmodern/spidr
lib/spidr/agent/events.rb
Spidr.Agent.every_rss_doc
def every_rss_doc every_page do |page| if (block_given? && page.rss?) if (doc = page.doc) yield doc end end end end
ruby
def every_rss_doc every_page do |page| if (block_given? && page.rss?) if (doc = page.doc) yield doc end end end end
[ "def", "every_rss_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "rss?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end" ]
Pass every RSS document that the agent parses to a given block. @yield [doc] The block will be passed every RSS document parsed. @yieldparam [Nokogiri::XML::Document] doc A parsed XML document. @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html
[ "Pass", "every", "RSS", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L366-L374
valid
postmodern/spidr
lib/spidr/agent/events.rb
Spidr.Agent.every_atom_doc
def every_atom_doc every_page do |page| if (block_given? && page.atom?) if (doc = page.doc) yield doc end end end end
ruby
def every_atom_doc every_page do |page| if (block_given? && page.atom?) if (doc = page.doc) yield doc end end end end
[ "def", "every_atom_doc", "every_page", "do", "|", "page", "|", "if", "(", "block_given?", "&&", "page", ".", "atom?", ")", "if", "(", "doc", "=", "page", ".", "doc", ")", "yield", "doc", "end", "end", "end", "end" ]
Pass every Atom document that the agent parses to a given block. @yield [doc] The block will be passed every Atom document parsed. @yieldparam [Nokogiri::XML::Document] doc A parsed XML document. @see http://nokogiri.rubyforge.org/nokogiri/Nokogiri/XML/Document.html
[ "Pass", "every", "Atom", "document", "that", "the", "agent", "parses", "to", "a", "given", "block", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/events.rb#L387-L395
valid
postmodern/spidr
lib/spidr/agent/filters.rb
Spidr.Agent.initialize_filters
def initialize_filters(options={}) @schemes = [] if options[:schemes] self.schemes = options[:schemes] else @schemes << 'http' begin require 'net/https' @schemes << 'https' rescue Gem::LoadError => e raise(e) rescue ::LoadError warn "Warning: cannot load 'net/https', https support disabled" end end @host_rules = Rules.new( accept: options[:hosts], reject: options[:ignore_hosts] ) @port_rules = Rules.new( accept: options[:ports], reject: options[:ignore_ports] ) @link_rules = Rules.new( accept: options[:links], reject: options[:ignore_links] ) @url_rules = Rules.new( accept: options[:urls], reject: options[:ignore_urls] ) @ext_rules = Rules.new( accept: options[:exts], reject: options[:ignore_exts] ) if options[:host] visit_hosts_like(options[:host]) end end
ruby
def initialize_filters(options={}) @schemes = [] if options[:schemes] self.schemes = options[:schemes] else @schemes << 'http' begin require 'net/https' @schemes << 'https' rescue Gem::LoadError => e raise(e) rescue ::LoadError warn "Warning: cannot load 'net/https', https support disabled" end end @host_rules = Rules.new( accept: options[:hosts], reject: options[:ignore_hosts] ) @port_rules = Rules.new( accept: options[:ports], reject: options[:ignore_ports] ) @link_rules = Rules.new( accept: options[:links], reject: options[:ignore_links] ) @url_rules = Rules.new( accept: options[:urls], reject: options[:ignore_urls] ) @ext_rules = Rules.new( accept: options[:exts], reject: options[:ignore_exts] ) if options[:host] visit_hosts_like(options[:host]) end end
[ "def", "initialize_filters", "(", "options", "=", "{", "}", ")", "@schemes", "=", "[", "]", "if", "options", "[", ":schemes", "]", "self", ".", "schemes", "=", "options", "[", ":schemes", "]", "else", "@schemes", "<<", "'http'", "begin", "require", "'net...
Initializes filtering rules. @param [Hash] options Additional options. @option options [Array] :schemes (['http', 'https']) The list of acceptable URI schemes to visit. The `https` scheme will be ignored if `net/https` cannot be loaded. @option options [String] :host The host-name to visit. @option options [Array<String, Regexp, Proc>] :hosts The patterns which match the host-names to visit. @option options [Array<String, Regexp, Proc>] :ignore_hosts The patterns which match the host-names to not visit. @option options [Array<Integer, Regexp, Proc>] :ports The patterns which match the ports to visit. @option options [Array<Integer, Regexp, Proc>] :ignore_ports The patterns which match the ports to not visit. @option options [Array<String, Regexp, Proc>] :links The patterns which match the links to visit. @option options [Array<String, Regexp, Proc>] :ignore_links The patterns which match the links to not visit. @option options [Array<String, Regexp, Proc>] :urls The patterns which match the URLs to visit. @option options [Array<String, Regexp, Proc>] :ignore_urls The patterns which match the URLs to not visit. @option options [Array<String, Regexp, Proc>] :exts The patterns which match the URI path extensions to visit. @option options [Array<String, Regexp, Proc>] :ignore_exts The patterns which match the URI path extensions to not visit.
[ "Initializes", "filtering", "rules", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/agent/filters.rb#L399-L442
valid
postmodern/spidr
lib/spidr/page/html.rb
Spidr.Page.each_meta_redirect
def each_meta_redirect return enum_for(__method__) unless block_given? if (html? && doc) search('//meta[@http-equiv and @content]').each do |node| if node.get_attribute('http-equiv') =~ /refresh/i content = node.get_attribute('content') if (redirect = content.match(/url=(\S+)$/)) yield redirect[1] end end end end end
ruby
def each_meta_redirect return enum_for(__method__) unless block_given? if (html? && doc) search('//meta[@http-equiv and @content]').each do |node| if node.get_attribute('http-equiv') =~ /refresh/i content = node.get_attribute('content') if (redirect = content.match(/url=(\S+)$/)) yield redirect[1] end end end end end
[ "def", "each_meta_redirect", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "if", "(", "html?", "&&", "doc", ")", "search", "(", "'//meta[@http-equiv and @content]'", ")", ".", "each", "do", "|", "node", "|", "if", "node", ".", "get_at...
Enumerates over the meta-redirect links in the page. @yield [link] If a block is given, it will be passed every meta-redirect link from the page. @yieldparam [String] link A meta-redirect link from the page. @return [Enumerator] If no block is given, an enumerator object will be returned. @since 0.3.0
[ "Enumerates", "over", "the", "meta", "-", "redirect", "links", "in", "the", "page", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L35-L49
valid
postmodern/spidr
lib/spidr/page/html.rb
Spidr.Page.each_redirect
def each_redirect(&block) return enum_for(__method__) unless block if (locations = @response.get_fields('Location')) # Location headers override any meta-refresh redirects in the HTML locations.each(&block) else # check page-level meta redirects if there isn't a location header each_meta_redirect(&block) end end
ruby
def each_redirect(&block) return enum_for(__method__) unless block if (locations = @response.get_fields('Location')) # Location headers override any meta-refresh redirects in the HTML locations.each(&block) else # check page-level meta redirects if there isn't a location header each_meta_redirect(&block) end end
[ "def", "each_redirect", "(", "&", "block", ")", "return", "enum_for", "(", "__method__", ")", "unless", "block", "if", "(", "locations", "=", "@response", ".", "get_fields", "(", "'Location'", ")", ")", "locations", ".", "each", "(", "&", "block", ")", "...
Enumerates over every HTTP or meta-redirect link in the page. @yield [link] The given block will be passed every redirection link from the page. @yieldparam [String] link A HTTP or meta-redirect link from the page. @return [Enumerator] If no block is given, an enumerator object will be returned. @since 0.3.0
[ "Enumerates", "over", "every", "HTTP", "or", "meta", "-", "redirect", "link", "in", "the", "page", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L105-L115
valid
postmodern/spidr
lib/spidr/page/html.rb
Spidr.Page.each_link
def each_link return enum_for(__method__) unless block_given? filter = lambda { |url| yield url unless (url.nil? || url.empty?) } each_redirect(&filter) if is_redirect? if (html? && doc) doc.search('//a[@href]').each do |a| filter.call(a.get_attribute('href')) end doc.search('//frame[@src]').each do |iframe| filter.call(iframe.get_attribute('src')) end doc.search('//iframe[@src]').each do |iframe| filter.call(iframe.get_attribute('src')) end doc.search('//link[@href]').each do |link| filter.call(link.get_attribute('href')) end doc.search('//script[@src]').each do |script| filter.call(script.get_attribute('src')) end end end
ruby
def each_link return enum_for(__method__) unless block_given? filter = lambda { |url| yield url unless (url.nil? || url.empty?) } each_redirect(&filter) if is_redirect? if (html? && doc) doc.search('//a[@href]').each do |a| filter.call(a.get_attribute('href')) end doc.search('//frame[@src]').each do |iframe| filter.call(iframe.get_attribute('src')) end doc.search('//iframe[@src]').each do |iframe| filter.call(iframe.get_attribute('src')) end doc.search('//link[@href]').each do |link| filter.call(link.get_attribute('href')) end doc.search('//script[@src]').each do |script| filter.call(script.get_attribute('src')) end end end
[ "def", "each_link", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "filter", "=", "lambda", "{", "|", "url", "|", "yield", "url", "unless", "(", "url", ".", "nil?", "||", "url", ".", "empty?", ")", "}", "each_redirect", "(", "&",...
Enumerates over every link in the page. @yield [link] The given block will be passed every non-empty link in the page. @yieldparam [String] link A link in the page. @return [Enumerator] If no block is given, an enumerator object will be returned. @since 0.3.0
[ "Enumerates", "over", "every", "link", "in", "the", "page", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L178-L208
valid
postmodern/spidr
lib/spidr/page/html.rb
Spidr.Page.each_url
def each_url return enum_for(__method__) unless block_given? each_link do |link| if (url = to_absolute(link)) yield url end end end
ruby
def each_url return enum_for(__method__) unless block_given? each_link do |link| if (url = to_absolute(link)) yield url end end end
[ "def", "each_url", "return", "enum_for", "(", "__method__", ")", "unless", "block_given?", "each_link", "do", "|", "link", "|", "if", "(", "url", "=", "to_absolute", "(", "link", ")", ")", "yield", "url", "end", "end", "end" ]
Enumerates over every absolute URL in the page. @yield [url] The given block will be passed every URL in the page. @yieldparam [URI::HTTP] url An absolute URL in the page. @return [Enumerator] If no block is given, an enumerator object will be returned. @since 0.3.0
[ "Enumerates", "over", "every", "absolute", "URL", "in", "the", "page", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L235-L243
valid
postmodern/spidr
lib/spidr/page/html.rb
Spidr.Page.to_absolute
def to_absolute(link) link = link.to_s new_url = begin url.merge(link) rescue Exception return end if (!new_url.opaque) && (path = new_url.path) # ensure that paths begin with a leading '/' for URI::FTP if (new_url.scheme == 'ftp' && !path.start_with?('/')) path.insert(0,'/') end # make sure the path does not contain any .. or . directories, # since URI::Generic#merge cannot normalize paths such as # "/stuff/../" new_url.path = URI.expand_path(path) end return new_url end
ruby
def to_absolute(link) link = link.to_s new_url = begin url.merge(link) rescue Exception return end if (!new_url.opaque) && (path = new_url.path) # ensure that paths begin with a leading '/' for URI::FTP if (new_url.scheme == 'ftp' && !path.start_with?('/')) path.insert(0,'/') end # make sure the path does not contain any .. or . directories, # since URI::Generic#merge cannot normalize paths such as # "/stuff/../" new_url.path = URI.expand_path(path) end return new_url end
[ "def", "to_absolute", "(", "link", ")", "link", "=", "link", ".", "to_s", "new_url", "=", "begin", "url", ".", "merge", "(", "link", ")", "rescue", "Exception", "return", "end", "if", "(", "!", "new_url", ".", "opaque", ")", "&&", "(", "path", "=", ...
Normalizes and expands a given link into a proper URI. @param [String] link The link to normalize and expand. @return [URI::HTTP] The normalized URI.
[ "Normalizes", "and", "expands", "a", "given", "link", "into", "a", "proper", "URI", "." ]
ae885272619f74c69d43ec77852f158768c6d804
https://github.com/postmodern/spidr/blob/ae885272619f74c69d43ec77852f158768c6d804/lib/spidr/page/html.rb#L266-L287
valid
trailblazer/roar
lib/roar/http_verbs.rb
Roar.HttpVerbs.post
def post(options={}, &block) response = http.post_uri(options.merge(:body => serialize), &block) handle_response(response) end
ruby
def post(options={}, &block) response = http.post_uri(options.merge(:body => serialize), &block) handle_response(response) end
[ "def", "post", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "post_uri", "(", "options", ".", "merge", "(", ":body", "=>", "serialize", ")", ",", "&", "block", ")", "handle_response", "(", "response", ")", "end"...
Serializes the object, POSTs it to +url+ with +format+, deserializes the returned document and updates properties accordingly.
[ "Serializes", "the", "object", "POSTs", "it", "to", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "." ]
2dcc627c4884cd87619c321bc98edeb1c5549093
https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L32-L35
valid
trailblazer/roar
lib/roar/http_verbs.rb
Roar.HttpVerbs.get
def get(options={}, &block) response = http.get_uri(options, &block) handle_response(response) end
ruby
def get(options={}, &block) response = http.get_uri(options, &block) handle_response(response) end
[ "def", "get", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "get_uri", "(", "options", ",", "&", "block", ")", "handle_response", "(", "response", ")", "end" ]
GETs +url+ with +format+, deserializes the returned document and updates properties accordingly.
[ "GETs", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "." ]
2dcc627c4884cd87619c321bc98edeb1c5549093
https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L38-L41
valid
trailblazer/roar
lib/roar/http_verbs.rb
Roar.HttpVerbs.put
def put(options={}, &block) response = http.put_uri(options.merge(:body => serialize), &block) handle_response(response) self end
ruby
def put(options={}, &block) response = http.put_uri(options.merge(:body => serialize), &block) handle_response(response) self end
[ "def", "put", "(", "options", "=", "{", "}", ",", "&", "block", ")", "response", "=", "http", ".", "put_uri", "(", "options", ".", "merge", "(", ":body", "=>", "serialize", ")", ",", "&", "block", ")", "handle_response", "(", "response", ")", "self",...
Serializes the object, PUTs it to +url+ with +format+, deserializes the returned document and updates properties accordingly.
[ "Serializes", "the", "object", "PUTs", "it", "to", "+", "url", "+", "with", "+", "format", "+", "deserializes", "the", "returned", "document", "and", "updates", "properties", "accordingly", "." ]
2dcc627c4884cd87619c321bc98edeb1c5549093
https://github.com/trailblazer/roar/blob/2dcc627c4884cd87619c321bc98edeb1c5549093/lib/roar/http_verbs.rb#L45-L49
valid
chain/chain
sdk/ruby/lib/chain/query.rb
Chain.Query.each
def each page = fetch(@first_query) loop do if page['items'].empty? # we consume this array as we iterate break if page['last_page'] page = fetch(page['next']) # The second predicate (empty?) *should* be redundant, but we check it # anyway as a defensive measure. break if page['items'].empty? end item = page['items'].shift yield translate(item) end end
ruby
def each page = fetch(@first_query) loop do if page['items'].empty? # we consume this array as we iterate break if page['last_page'] page = fetch(page['next']) # The second predicate (empty?) *should* be redundant, but we check it # anyway as a defensive measure. break if page['items'].empty? end item = page['items'].shift yield translate(item) end end
[ "def", "each", "page", "=", "fetch", "(", "@first_query", ")", "loop", "do", "if", "page", "[", "'items'", "]", ".", "empty?", "break", "if", "page", "[", "'last_page'", "]", "page", "=", "fetch", "(", "page", "[", "'next'", "]", ")", "break", "if", ...
Iterate through objects in response, fetching the next page of results from the API as needed. Implements required method {https://ruby-doc.org/core/Enumerable.html Enumerable#each}. @return [void]
[ "Iterate", "through", "objects", "in", "response", "fetching", "the", "next", "page", "of", "results", "from", "the", "API", "as", "needed", "." ]
4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c
https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/query.rb#L19-L35
valid
chain/chain
sdk/ruby/lib/chain/hsm_signer.rb
Chain.HSMSigner.sign
def sign(tx_template) return tx_template if @xpubs_by_signer.empty? @xpubs_by_signer.each do |signer_conn, xpubs| tx_template = signer_conn.singleton_batch_request( '/sign-transaction', transactions: [tx_template], xpubs: xpubs, ) { |item| Transaction::Template.new(item) } end tx_template end
ruby
def sign(tx_template) return tx_template if @xpubs_by_signer.empty? @xpubs_by_signer.each do |signer_conn, xpubs| tx_template = signer_conn.singleton_batch_request( '/sign-transaction', transactions: [tx_template], xpubs: xpubs, ) { |item| Transaction::Template.new(item) } end tx_template end
[ "def", "sign", "(", "tx_template", ")", "return", "tx_template", "if", "@xpubs_by_signer", ".", "empty?", "@xpubs_by_signer", ".", "each", "do", "|", "signer_conn", ",", "xpubs", "|", "tx_template", "=", "signer_conn", ".", "singleton_batch_request", "(", "'/sign-...
Sign a single transaction @param [Hash] tx_template A single transaction template.
[ "Sign", "a", "single", "transaction" ]
4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c
https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/hsm_signer.rb#L25-L37
valid
chain/chain
sdk/ruby/lib/chain/hsm_signer.rb
Chain.HSMSigner.sign_batch
def sign_batch(tx_templates) if @xpubs_by_signer.empty? # Treat all templates as if signed successfully. successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)| memo[i] = t memo end BatchResponse.new(successes: successes) end # We need to work towards a single, final BatchResponse that uses the # original indexes. For the next cycle, we should retain only those # templates for which the most recent sign response was successful, and # maintain a mapping of each template's index in the upcoming request # to its original index. orig_index = (0...tx_templates.size).to_a errors = {} @xpubs_by_signer.each do |signer_conn, xpubs| next_tx_templates = [] next_orig_index = [] batch = signer_conn.batch_request( '/sign-transaction', transactions: tx_templates, xpubs: xpubs, ) { |item| Transaction::Template.new(item) } batch.successes.each do |i, template| next_tx_templates << template next_orig_index << orig_index[i] end batch.errors.each do |i, err| errors[orig_index[i]] = err end tx_templates = next_tx_templates orig_index = next_orig_index # Early-exit if all templates have encountered an error. break if tx_templates.empty? end successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)| memo[orig_index[i]] = t memo end BatchResponse.new( successes: successes, errors: errors, ) end
ruby
def sign_batch(tx_templates) if @xpubs_by_signer.empty? # Treat all templates as if signed successfully. successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)| memo[i] = t memo end BatchResponse.new(successes: successes) end # We need to work towards a single, final BatchResponse that uses the # original indexes. For the next cycle, we should retain only those # templates for which the most recent sign response was successful, and # maintain a mapping of each template's index in the upcoming request # to its original index. orig_index = (0...tx_templates.size).to_a errors = {} @xpubs_by_signer.each do |signer_conn, xpubs| next_tx_templates = [] next_orig_index = [] batch = signer_conn.batch_request( '/sign-transaction', transactions: tx_templates, xpubs: xpubs, ) { |item| Transaction::Template.new(item) } batch.successes.each do |i, template| next_tx_templates << template next_orig_index << orig_index[i] end batch.errors.each do |i, err| errors[orig_index[i]] = err end tx_templates = next_tx_templates orig_index = next_orig_index # Early-exit if all templates have encountered an error. break if tx_templates.empty? end successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)| memo[orig_index[i]] = t memo end BatchResponse.new( successes: successes, errors: errors, ) end
[ "def", "sign_batch", "(", "tx_templates", ")", "if", "@xpubs_by_signer", ".", "empty?", "successes", "=", "tx_templates", ".", "each_with_index", ".", "reduce", "(", "{", "}", ")", "do", "|", "memo", ",", "(", "t", ",", "i", ")", "|", "memo", "[", "i",...
Sign a batch of transactions @param [Array<Hash>] tx_templates Array of transaction templates.
[ "Sign", "a", "batch", "of", "transactions" ]
4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c
https://github.com/chain/chain/blob/4e9b90d76fe9a4c53adadf03cf8db96a0a5ff38c/sdk/ruby/lib/chain/hsm_signer.rb#L41-L95
valid
fhir-crucible/fhir_client
lib/fhir_client/client.rb
FHIR.Client.set_no_auth
def set_no_auth FHIR.logger.info 'Configuring the client to use no authentication.' @use_oauth2_auth = false @use_basic_auth = false @security_headers = {} @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
ruby
def set_no_auth FHIR.logger.info 'Configuring the client to use no authentication.' @use_oauth2_auth = false @use_basic_auth = false @security_headers = {} @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
[ "def", "set_no_auth", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use no authentication.'", "@use_oauth2_auth", "=", "false", "@use_basic_auth", "=", "false", "@security_headers", "=", "{", "}", "@client", "=", "RestClient", "@client", ".", "proxy", ...
Set the client to use no authentication mechanisms
[ "Set", "the", "client", "to", "use", "no", "authentication", "mechanisms" ]
19891520a1af0d42a3a985c9afebc68d717f51cc
https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L112-L120
valid
fhir-crucible/fhir_client
lib/fhir_client/client.rb
FHIR.Client.set_basic_auth
def set_basic_auth(client, secret) FHIR.logger.info 'Configuring the client to use HTTP Basic authentication.' token = Base64.encode64("#{client}:#{secret}") value = "Basic #{token}" @security_headers = { 'Authorization' => value } @use_oauth2_auth = false @use_basic_auth = true @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
ruby
def set_basic_auth(client, secret) FHIR.logger.info 'Configuring the client to use HTTP Basic authentication.' token = Base64.encode64("#{client}:#{secret}") value = "Basic #{token}" @security_headers = { 'Authorization' => value } @use_oauth2_auth = false @use_basic_auth = true @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
[ "def", "set_basic_auth", "(", "client", ",", "secret", ")", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use HTTP Basic authentication.'", "token", "=", "Base64", ".", "encode64", "(", "\"#{client}:#{secret}\"", ")", "value", "=", "\"Basic #{token}\""...
Set the client to use HTTP Basic Authentication
[ "Set", "the", "client", "to", "use", "HTTP", "Basic", "Authentication" ]
19891520a1af0d42a3a985c9afebc68d717f51cc
https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L123-L133
valid
fhir-crucible/fhir_client
lib/fhir_client/client.rb
FHIR.Client.set_bearer_token
def set_bearer_token(token) FHIR.logger.info 'Configuring the client to use Bearer Token authentication.' value = "Bearer #{token}" @security_headers = { 'Authorization' => value } @use_oauth2_auth = false @use_basic_auth = true @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
ruby
def set_bearer_token(token) FHIR.logger.info 'Configuring the client to use Bearer Token authentication.' value = "Bearer #{token}" @security_headers = { 'Authorization' => value } @use_oauth2_auth = false @use_basic_auth = true @client = RestClient @client.proxy = proxy unless proxy.nil? @client end
[ "def", "set_bearer_token", "(", "token", ")", "FHIR", ".", "logger", ".", "info", "'Configuring the client to use Bearer Token authentication.'", "value", "=", "\"Bearer #{token}\"", "@security_headers", "=", "{", "'Authorization'", "=>", "value", "}", "@use_oauth2_auth", ...
Set the client to use Bearer Token Authentication
[ "Set", "the", "client", "to", "use", "Bearer", "Token", "Authentication" ]
19891520a1af0d42a3a985c9afebc68d717f51cc
https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L136-L145
valid
fhir-crucible/fhir_client
lib/fhir_client/client.rb
FHIR.Client.request_payload
def request_payload(resource, headers) if headers format_specified = headers['Content-Type'] if format_specified.nil? resource.to_xml elsif format_specified.downcase.include?('xml') resource.to_xml elsif format_specified.downcase.include?('json') resource.to_json else resource.to_xml end else resource.to_xml end end
ruby
def request_payload(resource, headers) if headers format_specified = headers['Content-Type'] if format_specified.nil? resource.to_xml elsif format_specified.downcase.include?('xml') resource.to_xml elsif format_specified.downcase.include?('json') resource.to_json else resource.to_xml end else resource.to_xml end end
[ "def", "request_payload", "(", "resource", ",", "headers", ")", "if", "headers", "format_specified", "=", "headers", "[", "'Content-Type'", "]", "if", "format_specified", ".", "nil?", "resource", ".", "to_xml", "elsif", "format_specified", ".", "downcase", ".", ...
Extract the request payload in the specified format, defaults to XML
[ "Extract", "the", "request", "payload", "in", "the", "specified", "format", "defaults", "to", "XML" ]
19891520a1af0d42a3a985c9afebc68d717f51cc
https://github.com/fhir-crucible/fhir_client/blob/19891520a1af0d42a3a985c9afebc68d717f51cc/lib/fhir_client/client.rb#L378-L393
valid
ipaddress-gem/ipaddress
lib/ipaddress/ipv4.rb
IPAddress.IPv4.split
def split(subnets=2) unless (1..(2**@prefix.host_prefix)).include? subnets raise ArgumentError, "Value #{subnets} out of range" end networks = subnet(newprefix(subnets)) until networks.size == subnets networks = sum_first_found(networks) end return networks end
ruby
def split(subnets=2) unless (1..(2**@prefix.host_prefix)).include? subnets raise ArgumentError, "Value #{subnets} out of range" end networks = subnet(newprefix(subnets)) until networks.size == subnets networks = sum_first_found(networks) end return networks end
[ "def", "split", "(", "subnets", "=", "2", ")", "unless", "(", "1", "..", "(", "2", "**", "@prefix", ".", "host_prefix", ")", ")", ".", "include?", "subnets", "raise", "ArgumentError", ",", "\"Value #{subnets} out of range\"", "end", "networks", "=", "subnet"...
Splits a network into different subnets If the IP Address is a network, it can be divided into multiple networks. If +self+ is not a network, this method will calculate the network from the IP and then subnet it. If +subnets+ is an power of two number, the resulting networks will be divided evenly from the supernet. network = IPAddress("172.16.10.0/24") network / 4 # implies map{|i| i.to_string} #=> ["172.16.10.0/26", #=> "172.16.10.64/26", #=> "172.16.10.128/26", #=> "172.16.10.192/26"] If +num+ is any other number, the supernet will be divided into some networks with a even number of hosts and other networks with the remaining addresses. network = IPAddress("172.16.10.0/24") network / 3 # implies map{|i| i.to_string} #=> ["172.16.10.0/26", #=> "172.16.10.64/26", #=> "172.16.10.128/25"] Returns an array of IPv4 objects
[ "Splits", "a", "network", "into", "different", "subnets" ]
a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b
https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L734-L743
valid
ipaddress-gem/ipaddress
lib/ipaddress/ipv4.rb
IPAddress.IPv4.supernet
def supernet(new_prefix) raise ArgumentError, "New prefix must be smaller than existing prefix" if new_prefix >= @prefix.to_i return self.class.new("0.0.0.0/0") if new_prefix < 1 return self.class.new(@address+"/#{new_prefix}").network end
ruby
def supernet(new_prefix) raise ArgumentError, "New prefix must be smaller than existing prefix" if new_prefix >= @prefix.to_i return self.class.new("0.0.0.0/0") if new_prefix < 1 return self.class.new(@address+"/#{new_prefix}").network end
[ "def", "supernet", "(", "new_prefix", ")", "raise", "ArgumentError", ",", "\"New prefix must be smaller than existing prefix\"", "if", "new_prefix", ">=", "@prefix", ".", "to_i", "return", "self", ".", "class", ".", "new", "(", "\"0.0.0.0/0\"", ")", "if", "new_prefi...
Returns a new IPv4 object from the supernetting of the instance network. Supernetting is similar to subnetting, except that you getting as a result a network with a smaller prefix (bigger host space). For example, given the network ip = IPAddress("172.16.10.0/24") you can supernet it with a new /23 prefix ip.supernet(23).to_string #=> "172.16.10.0/23" However if you supernet it with a /22 prefix, the network address will change: ip.supernet(22).to_string #=> "172.16.8.0/22" If +new_prefix+ is less than 1, returns 0.0.0.0/0
[ "Returns", "a", "new", "IPv4", "object", "from", "the", "supernetting", "of", "the", "instance", "network", "." ]
a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b
https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L770-L774
valid
ipaddress-gem/ipaddress
lib/ipaddress/ipv4.rb
IPAddress.IPv4.subnet
def subnet(subprefix) unless ((@prefix.to_i)..32).include? subprefix raise ArgumentError, "New prefix must be between #@prefix and 32" end Array.new(2**(subprefix-@prefix.to_i)) do |i| self.class.parse_u32(network_u32+(i*(2**(32-subprefix))), subprefix) end end
ruby
def subnet(subprefix) unless ((@prefix.to_i)..32).include? subprefix raise ArgumentError, "New prefix must be between #@prefix and 32" end Array.new(2**(subprefix-@prefix.to_i)) do |i| self.class.parse_u32(network_u32+(i*(2**(32-subprefix))), subprefix) end end
[ "def", "subnet", "(", "subprefix", ")", "unless", "(", "(", "@prefix", ".", "to_i", ")", "..", "32", ")", ".", "include?", "subprefix", "raise", "ArgumentError", ",", "\"New prefix must be between #@prefix and 32\"", "end", "Array", ".", "new", "(", "2", "**",...
This method implements the subnetting function similar to the one described in RFC3531. By specifying a new prefix, the method calculates the network number for the given IPv4 object and calculates the subnets associated to the new prefix. For example, given the following network: ip = IPAddress "172.16.10.0/24" we can calculate the subnets with a /26 prefix ip.subnet(26).map{&:to_string) #=> ["172.16.10.0/26", "172.16.10.64/26", "172.16.10.128/26", "172.16.10.192/26"] The resulting number of subnets will of course always be a power of two.
[ "This", "method", "implements", "the", "subnetting", "function", "similar", "to", "the", "one", "described", "in", "RFC3531", "." ]
a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b
https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/ipv4.rb#L798-L805
valid
ipaddress-gem/ipaddress
lib/ipaddress/prefix.rb
IPAddress.Prefix.-
def -(oth) if oth.is_a? Integer self.prefix - oth else (self.prefix - oth.prefix).abs end end
ruby
def -(oth) if oth.is_a? Integer self.prefix - oth else (self.prefix - oth.prefix).abs end end
[ "def", "-", "(", "oth", ")", "if", "oth", ".", "is_a?", "Integer", "self", ".", "prefix", "-", "oth", "else", "(", "self", ".", "prefix", "-", "oth", ".", "prefix", ")", ".", "abs", "end", "end" ]
Returns the difference between two prefixes, or a prefix and a number, as a Integer
[ "Returns", "the", "difference", "between", "two", "prefixes", "or", "a", "prefix", "and", "a", "number", "as", "a", "Integer" ]
a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b
https://github.com/ipaddress-gem/ipaddress/blob/a8eb06d418efc1b3bb036c849c95cf0ce4b7e18b/lib/ipaddress/prefix.rb#L73-L79
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.bot
def bot return @bot unless @bot.nil? @bot_command = nil # # parse any command-line options and use them to initialize the bot # params = {} #:nocov: opts = OptionParser.new opts.banner = "Usage: #{File.basename($0)} [options]" opts.separator "" opts.separator "Specific options:" opts.on('-c', '--config [ARG]', "Specify a config file to use") { |c| ENV["chatterbot_config"] = c } opts.on('-t', '--test', "Run the bot without actually sending any tweets") { params[:debug_mode] = true } opts.on('-v', '--verbose', "verbose output to stdout") { params[:verbose] = true } opts.on('--dry-run', "Run the bot in test mode, and also don't update the database") { params[:debug_mode] = true ; params[:no_update] = true } opts.on('-r', '--reset', "Reset your bot to ignore old tweets") { @bot_command = :reset_since_id_counters } opts.on('--profile [ARG]', "get/set your bot's profile text") { |p| @bot_command = :profile_text @bot_command_args = [ p ] } opts.on('--website [ARG]', "get/set your bot's profile URL") { |u| @bot_command = :profile_website @bot_command_args = [ u ] } opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.parse!(ARGV) #:nocov: @bot = Chatterbot::Bot.new(params) if @bot_command != nil @bot.skip_run = true result = @bot.send(@bot_command, *@bot_command_args) puts result end @bot end
ruby
def bot return @bot unless @bot.nil? @bot_command = nil # # parse any command-line options and use them to initialize the bot # params = {} #:nocov: opts = OptionParser.new opts.banner = "Usage: #{File.basename($0)} [options]" opts.separator "" opts.separator "Specific options:" opts.on('-c', '--config [ARG]', "Specify a config file to use") { |c| ENV["chatterbot_config"] = c } opts.on('-t', '--test', "Run the bot without actually sending any tweets") { params[:debug_mode] = true } opts.on('-v', '--verbose', "verbose output to stdout") { params[:verbose] = true } opts.on('--dry-run', "Run the bot in test mode, and also don't update the database") { params[:debug_mode] = true ; params[:no_update] = true } opts.on('-r', '--reset', "Reset your bot to ignore old tweets") { @bot_command = :reset_since_id_counters } opts.on('--profile [ARG]', "get/set your bot's profile text") { |p| @bot_command = :profile_text @bot_command_args = [ p ] } opts.on('--website [ARG]', "get/set your bot's profile URL") { |u| @bot_command = :profile_website @bot_command_args = [ u ] } opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.parse!(ARGV) #:nocov: @bot = Chatterbot::Bot.new(params) if @bot_command != nil @bot.skip_run = true result = @bot.send(@bot_command, *@bot_command_args) puts result end @bot end
[ "def", "bot", "return", "@bot", "unless", "@bot", ".", "nil?", "@bot_command", "=", "nil", "params", "=", "{", "}", "opts", "=", "OptionParser", ".", "new", "opts", ".", "banner", "=", "\"Usage: #{File.basename($0)} [options]\"", "opts", ".", "separator", "\"\...
generate a Bot object. if the DSL is being called from a Bot object, just return it otherwise create a bot and return that
[ "generate", "a", "Bot", "object", ".", "if", "the", "DSL", "is", "being", "called", "from", "a", "Bot", "object", "just", "return", "it", "otherwise", "create", "a", "bot", "and", "return", "that" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L159-L213
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.blocklist
def blocklist(*args) list = flatten_list_of_strings(args) if list.nil? || list.empty? bot.blocklist = [] else bot.blocklist += list end end
ruby
def blocklist(*args) list = flatten_list_of_strings(args) if list.nil? || list.empty? bot.blocklist = [] else bot.blocklist += list end end
[ "def", "blocklist", "(", "*", "args", ")", "list", "=", "flatten_list_of_strings", "(", "args", ")", "if", "list", ".", "nil?", "||", "list", ".", "empty?", "bot", ".", "blocklist", "=", "[", "]", "else", "bot", ".", "blocklist", "+=", "list", "end", ...
specify a bot-specific blocklist of users. accepts an array, or a comma-delimited string. when called, any subsequent calls to search or replies will filter out these users. @param [Array, String] args list of usernames @example blocklist "mean_user, private_user"
[ "specify", "a", "bot", "-", "specific", "blocklist", "of", "users", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "calls", "to", "search", "or", "replies", "will", "filter", "out"...
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L251-L259
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.safelist
def safelist(*args) list = flatten_list_of_strings(args) if list.nil? || list.empty? bot.safelist = [] else bot.safelist += list end end
ruby
def safelist(*args) list = flatten_list_of_strings(args) if list.nil? || list.empty? bot.safelist = [] else bot.safelist += list end end
[ "def", "safelist", "(", "*", "args", ")", "list", "=", "flatten_list_of_strings", "(", "args", ")", "if", "list", ".", "nil?", "||", "list", ".", "empty?", "bot", ".", "safelist", "=", "[", "]", "else", "bot", ".", "safelist", "+=", "list", "end", "e...
specify a bot-specific safelist of users. accepts an array, or a comma-delimited string. when called, any subsequent calls to search or replies will only act upon these users. @param [Array, String] args list of usernames or Twitter::User objects @example safelist "mean_user, private_user"
[ "specify", "a", "bot", "-", "specific", "safelist", "of", "users", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "calls", "to", "search", "or", "replies", "will", "only", "act", ...
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L272-L280
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.exclude
def exclude(*args) e = flatten_list_of_strings(args) if e.nil? || e.empty? bot.exclude = [] else bot.exclude += e end end
ruby
def exclude(*args) e = flatten_list_of_strings(args) if e.nil? || e.empty? bot.exclude = [] else bot.exclude += e end end
[ "def", "exclude", "(", "*", "args", ")", "e", "=", "flatten_list_of_strings", "(", "args", ")", "if", "e", ".", "nil?", "||", "e", ".", "empty?", "bot", ".", "exclude", "=", "[", "]", "else", "bot", ".", "exclude", "+=", "e", "end", "end" ]
specify list of strings we will check when deciding to respond to a tweet or not. accepts an array or a comma-delimited string. when called, any subsequent calls to search or replies will filter out tweets with these strings @param [Array, String] args list of usernames @example exclude "spam, junk, something"
[ "specify", "list", "of", "strings", "we", "will", "check", "when", "deciding", "to", "respond", "to", "a", "tweet", "or", "not", ".", "accepts", "an", "array", "or", "a", "comma", "-", "delimited", "string", ".", "when", "called", "any", "subsequent", "c...
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L374-L381
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.consumer_secret
def consumer_secret(s) bot.deprecated "Setting consumer_secret outside of your config file is deprecated!", Kernel.caller.first bot.config[:consumer_secret] = s end
ruby
def consumer_secret(s) bot.deprecated "Setting consumer_secret outside of your config file is deprecated!", Kernel.caller.first bot.config[:consumer_secret] = s end
[ "def", "consumer_secret", "(", "s", ")", "bot", ".", "deprecated", "\"Setting consumer_secret outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":consumer_secret", "]", "=", "s", "end" ]
set the consumer secret @param s [String] the consumer secret
[ "set", "the", "consumer", "secret" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L397-L400
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.consumer_key
def consumer_key(k) bot.deprecated "Setting consumer_key outside of your config file is deprecated!", Kernel.caller.first bot.config[:consumer_key] = k end
ruby
def consumer_key(k) bot.deprecated "Setting consumer_key outside of your config file is deprecated!", Kernel.caller.first bot.config[:consumer_key] = k end
[ "def", "consumer_key", "(", "k", ")", "bot", ".", "deprecated", "\"Setting consumer_key outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":consumer_key", "]", "=", "k", "end" ]
set the consumer key @param k [String] the consumer key
[ "set", "the", "consumer", "key" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L405-L408
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.secret
def secret(s) bot.deprecated "Setting access_token_secret outside of your config file is deprecated!", Kernel.caller.first bot.config[:access_token_secret] = s end
ruby
def secret(s) bot.deprecated "Setting access_token_secret outside of your config file is deprecated!", Kernel.caller.first bot.config[:access_token_secret] = s end
[ "def", "secret", "(", "s", ")", "bot", ".", "deprecated", "\"Setting access_token_secret outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":access_token_secret", "]", "=", "s", "end" ]
set the secret @param s [String] the secret
[ "set", "the", "secret" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L413-L416
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.token
def token(s) bot.deprecated "Setting access_token outside of your config file is deprecated!", Kernel.caller.first bot.config[:access_token] = s end
ruby
def token(s) bot.deprecated "Setting access_token outside of your config file is deprecated!", Kernel.caller.first bot.config[:access_token] = s end
[ "def", "token", "(", "s", ")", "bot", ".", "deprecated", "\"Setting access_token outside of your config file is deprecated!\"", ",", "Kernel", ".", "caller", ".", "first", "bot", ".", "config", "[", ":access_token", "]", "=", "s", "end" ]
set the token @param s [String] the token
[ "set", "the", "token" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L421-L424
valid
muffinista/chatterbot
lib/chatterbot/dsl.rb
Chatterbot.DSL.flatten_list_of_strings
def flatten_list_of_strings(args) args.collect do |b| if b.is_a?(String) # string, split on commas and turn into array b.split(",").collect { |s| s.strip } else # presumably an array b end end.flatten end
ruby
def flatten_list_of_strings(args) args.collect do |b| if b.is_a?(String) # string, split on commas and turn into array b.split(",").collect { |s| s.strip } else # presumably an array b end end.flatten end
[ "def", "flatten_list_of_strings", "(", "args", ")", "args", ".", "collect", "do", "|", "b", "|", "if", "b", ".", "is_a?", "(", "String", ")", "b", ".", "split", "(", "\",\"", ")", ".", "collect", "{", "|", "s", "|", "s", ".", "strip", "}", "else"...
take a variable list of strings and possibly arrays and turn them into a single flat array of strings
[ "take", "a", "variable", "list", "of", "strings", "and", "possibly", "arrays", "and", "turn", "them", "into", "a", "single", "flat", "array", "of", "strings" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/dsl.rb#L447-L457
valid
muffinista/chatterbot
lib/chatterbot/favorite.rb
Chatterbot.Favorite.favorite
def favorite(id=@current_tweet) return if require_login == false id = id_from_tweet(id) #:nocov: if debug_mode? debug "I'm in debug mode, otherwise I would favorite tweet id: #{id}" return end #:nocov: client.favorite id end
ruby
def favorite(id=@current_tweet) return if require_login == false id = id_from_tweet(id) #:nocov: if debug_mode? debug "I'm in debug mode, otherwise I would favorite tweet id: #{id}" return end #:nocov: client.favorite id end
[ "def", "favorite", "(", "id", "=", "@current_tweet", ")", "return", "if", "require_login", "==", "false", "id", "=", "id_from_tweet", "(", "id", ")", "if", "debug_mode?", "debug", "\"I'm in debug mode, otherwise I would favorite tweet id: #{id}\"", "return", "end", "c...
simple wrapper for favoriting a message @param [id] id A tweet or the ID of a tweet. if not specified, tries to use the current tweet if available
[ "simple", "wrapper", "for", "favoriting", "a", "message" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/favorite.rb#L9-L21
valid
muffinista/chatterbot
lib/chatterbot/home_timeline.rb
Chatterbot.HomeTimeline.home_timeline
def home_timeline(*args, &block) return unless require_login debug "check for home_timeline tweets since #{since_id_home_timeline}" opts = { :since_id => since_id_home_timeline, :count => 200 } results = client.home_timeline(opts) @current_tweet = nil results.each { |s| update_since_id_home_timeline(s) if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
ruby
def home_timeline(*args, &block) return unless require_login debug "check for home_timeline tweets since #{since_id_home_timeline}" opts = { :since_id => since_id_home_timeline, :count => 200 } results = client.home_timeline(opts) @current_tweet = nil results.each { |s| update_since_id_home_timeline(s) if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
[ "def", "home_timeline", "(", "*", "args", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for home_timeline tweets since #{since_id_home_timeline}\"", "opts", "=", "{", ":since_id", "=>", "since_id_home_timeline", ",", ":count", "=>", "200...
handle the bots timeline
[ "handle", "the", "bots", "timeline" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/home_timeline.rb#L8-L27
valid
muffinista/chatterbot
lib/chatterbot/safelist.rb
Chatterbot.Safelist.on_safelist?
def on_safelist?(s) search = from_user(s).downcase safelist.any? { |b| search.include?(b.downcase) } end
ruby
def on_safelist?(s) search = from_user(s).downcase safelist.any? { |b| search.include?(b.downcase) } end
[ "def", "on_safelist?", "(", "s", ")", "search", "=", "from_user", "(", "s", ")", ".", "downcase", "safelist", ".", "any?", "{", "|", "b", "|", "search", ".", "include?", "(", "b", ".", "downcase", ")", "}", "end" ]
Is this tweet from a user on our safelist?
[ "Is", "this", "tweet", "from", "a", "user", "on", "our", "safelist?" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/safelist.rb#L28-L31
valid
muffinista/chatterbot
lib/chatterbot/search.rb
Chatterbot.Search.search
def search(queries, opts = {}, &block) debug "check for tweets since #{since_id}" max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS exact_match = if opts.key?(:exact) opts.delete(:exact) else true end if queries.is_a?(String) queries = [ queries ] end query = queries.map { |q| if exact_match == true q = wrap_search_query(q) end q }.join(" OR ") # # search twitter # debug "search: #{query} #{default_opts.merge(opts)}" @current_tweet = nil client.search( query, default_opts.merge(opts) ).take(max_tweets).each { |s| update_since_id(s) debug s.text if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
ruby
def search(queries, opts = {}, &block) debug "check for tweets since #{since_id}" max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS exact_match = if opts.key?(:exact) opts.delete(:exact) else true end if queries.is_a?(String) queries = [ queries ] end query = queries.map { |q| if exact_match == true q = wrap_search_query(q) end q }.join(" OR ") # # search twitter # debug "search: #{query} #{default_opts.merge(opts)}" @current_tweet = nil client.search( query, default_opts.merge(opts) ).take(max_tweets).each { |s| update_since_id(s) debug s.text if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
[ "def", "search", "(", "queries", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "debug", "\"check for tweets since #{since_id}\"", "max_tweets", "=", "opts", ".", "delete", "(", ":limit", ")", "||", "MAX_SEARCH_TWEETS", "exact_match", "=", "if", "opts", ...
internal search code
[ "internal", "search", "code" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/search.rb#L44-L87
valid
muffinista/chatterbot
lib/chatterbot/tweet.rb
Chatterbot.Tweet.tweet
def tweet(txt, params = {}, original = nil) return if require_login == false txt = replace_variables(txt, original) if debug_mode? debug "I'm in debug mode, otherwise I would tweet: #{txt}" else debug txt if params.has_key?(:media) file = params.delete(:media) if ! file.is_a?(File) file = File.new(file) end client.update_with_media txt, file, params else client.update txt, params end end rescue Twitter::Error::Forbidden => e #:nocov: debug e false #:nocov: end
ruby
def tweet(txt, params = {}, original = nil) return if require_login == false txt = replace_variables(txt, original) if debug_mode? debug "I'm in debug mode, otherwise I would tweet: #{txt}" else debug txt if params.has_key?(:media) file = params.delete(:media) if ! file.is_a?(File) file = File.new(file) end client.update_with_media txt, file, params else client.update txt, params end end rescue Twitter::Error::Forbidden => e #:nocov: debug e false #:nocov: end
[ "def", "tweet", "(", "txt", ",", "params", "=", "{", "}", ",", "original", "=", "nil", ")", "return", "if", "require_login", "==", "false", "txt", "=", "replace_variables", "(", "txt", ",", "original", ")", "if", "debug_mode?", "debug", "\"I'm in debug mod...
simple wrapper for sending a message
[ "simple", "wrapper", "for", "sending", "a", "message" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/tweet.rb#L7-L32
valid
muffinista/chatterbot
lib/chatterbot/tweet.rb
Chatterbot.Tweet.reply
def reply(txt, source, params = {}) debug txt params = {:in_reply_to_status_id => source.id}.merge(params) tweet txt, params, source end
ruby
def reply(txt, source, params = {}) debug txt params = {:in_reply_to_status_id => source.id}.merge(params) tweet txt, params, source end
[ "def", "reply", "(", "txt", ",", "source", ",", "params", "=", "{", "}", ")", "debug", "txt", "params", "=", "{", ":in_reply_to_status_id", "=>", "source", ".", "id", "}", ".", "merge", "(", "params", ")", "tweet", "txt", ",", "params", ",", "source"...
reply to a tweet
[ "reply", "to", "a", "tweet" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/tweet.rb#L36-L40
valid
muffinista/chatterbot
lib/chatterbot/direct_messages.rb
Chatterbot.DirectMessages.direct_message
def direct_message(txt, user=nil) return unless require_login if user.nil? user = current_user end client.create_direct_message(user, txt) end
ruby
def direct_message(txt, user=nil) return unless require_login if user.nil? user = current_user end client.create_direct_message(user, txt) end
[ "def", "direct_message", "(", "txt", ",", "user", "=", "nil", ")", "return", "unless", "require_login", "if", "user", ".", "nil?", "user", "=", "current_user", "end", "client", ".", "create_direct_message", "(", "user", ",", "txt", ")", "end" ]
send a direct message
[ "send", "a", "direct", "message" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/direct_messages.rb#L8-L15
valid
muffinista/chatterbot
lib/chatterbot/direct_messages.rb
Chatterbot.DirectMessages.direct_messages
def direct_messages(opts = {}, &block) return unless require_login debug "check for DMs since #{since_id_dm}" # # search twitter # @current_tweet = nil client.direct_messages_received(since_id:since_id_dm, count:200).each { |s| update_since_id_dm(s) debug s.text if has_safelist? && !on_safelist?(s.sender) debug "skipping because user not on safelist" elsif block_given? && !on_blocklist?(s.sender) && !skip_me?(s) @current_tweet = s yield s end } @current_tweet = nil rescue Twitter::Error::Forbidden => e puts "sorry, looks like we're not allowed to check DMs for this account" end
ruby
def direct_messages(opts = {}, &block) return unless require_login debug "check for DMs since #{since_id_dm}" # # search twitter # @current_tweet = nil client.direct_messages_received(since_id:since_id_dm, count:200).each { |s| update_since_id_dm(s) debug s.text if has_safelist? && !on_safelist?(s.sender) debug "skipping because user not on safelist" elsif block_given? && !on_blocklist?(s.sender) && !skip_me?(s) @current_tweet = s yield s end } @current_tweet = nil rescue Twitter::Error::Forbidden => e puts "sorry, looks like we're not allowed to check DMs for this account" end
[ "def", "direct_messages", "(", "opts", "=", "{", "}", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for DMs since #{since_id_dm}\"", "@current_tweet", "=", "nil", "client", ".", "direct_messages_received", "(", "since_id", ":", "sinc...
check direct messages for the bot
[ "check", "direct", "messages", "for", "the", "bot" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/direct_messages.rb#L20-L42
valid
muffinista/chatterbot
lib/chatterbot/ui.rb
Chatterbot.UI.get_oauth_verifier
def get_oauth_verifier green "****************************************" green "****************************************" green "**** BOT AUTH TIME! ****" green "****************************************" green "****************************************" puts "You need to authorize your bot with Twitter.\n\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\n\nYour browser will open with the following URL, where you can authorize the bot.\n\n" url = request_token.authorize_url puts url puts "\nIf that doesn't work, you can open the URL in your browser manually." puts "\n\nHit enter to start.\n\n" STDIN.readline.chomp Launchy.open(url) # sleep here so that if launchy has any output (which it does # sometimes), it doesn't interfere with our input prompt sleep(2) puts "Paste your PIN and hit enter when you have completed authorization.\n\n" print "> " STDIN.readline.chomp.strip rescue Interrupt => e exit end
ruby
def get_oauth_verifier green "****************************************" green "****************************************" green "**** BOT AUTH TIME! ****" green "****************************************" green "****************************************" puts "You need to authorize your bot with Twitter.\n\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\n\nYour browser will open with the following URL, where you can authorize the bot.\n\n" url = request_token.authorize_url puts url puts "\nIf that doesn't work, you can open the URL in your browser manually." puts "\n\nHit enter to start.\n\n" STDIN.readline.chomp Launchy.open(url) # sleep here so that if launchy has any output (which it does # sometimes), it doesn't interfere with our input prompt sleep(2) puts "Paste your PIN and hit enter when you have completed authorization.\n\n" print "> " STDIN.readline.chomp.strip rescue Interrupt => e exit end
[ "def", "get_oauth_verifier", "green", "\"****************************************\"", "green", "\"****************************************\"", "green", "\"**** BOT AUTH TIME! ****\"", "green", "\"****************************************\"", "green", "\"*************************...
print out a message about getting a PIN from twitter, then output the URL the user needs to visit to authorize
[ "print", "out", "a", "message", "about", "getting", "a", "PIN", "from", "twitter", "then", "output", "the", "URL", "the", "user", "needs", "to", "visit", "to", "authorize" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/ui.rb#L30-L62
valid
muffinista/chatterbot
lib/chatterbot/ui.rb
Chatterbot.UI.get_api_key
def get_api_key green "****************************************" green "****************************************" green "**** API SETUP TIME! ****" green "****************************************" green "****************************************" puts "\n\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\n\n" # # At this point, we don't have any API credentials at all for # this bot, but it's possible the user has already setup an app. # Let's ask! # puts "Hey, looks like you need to get an API key from Twitter before you can get started.\n\n" app_already_exists = ask_yes_no("Have you already set up an app with Twitter?") if app_already_exists puts "Terrific! Let's get your bot running!\n\n" else puts "OK, I can help with that!\n\n" send_to_app_creation end print "\n\nPaste the 'Consumer Key' here: " STDOUT.flush config[:consumer_key] = STDIN.readline.chomp.strip print "Paste the 'Consumer Secret' here: " STDOUT.flush config[:consumer_secret] = STDIN.readline.chomp.strip puts "\n\nNow it's time to authorize your bot!\n\n" if ! app_already_exists && ask_yes_no("Do you want to authorize a bot using the account that created the app?") puts "OK, on the app page, you can click the 'Create my access token' button to proceed.\n\n" print "Paste the 'Access Token' here: " STDOUT.flush config[:access_token] = STDIN.readline.chomp.strip print "\n\nPaste the 'Access Token Secret' here: " STDOUT.flush config[:access_token_secret] = STDIN.readline.chomp.strip # reset the client so we can re-init with new OAuth credentials reset_client # at this point we should have a fully validated client, so grab # the screen name @screen_name = client.user.screen_name rescue nil else reset_client end # # capture ctrl-c and exit without a stack trace # rescue Interrupt => e exit end
ruby
def get_api_key green "****************************************" green "****************************************" green "**** API SETUP TIME! ****" green "****************************************" green "****************************************" puts "\n\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\n\n" # # At this point, we don't have any API credentials at all for # this bot, but it's possible the user has already setup an app. # Let's ask! # puts "Hey, looks like you need to get an API key from Twitter before you can get started.\n\n" app_already_exists = ask_yes_no("Have you already set up an app with Twitter?") if app_already_exists puts "Terrific! Let's get your bot running!\n\n" else puts "OK, I can help with that!\n\n" send_to_app_creation end print "\n\nPaste the 'Consumer Key' here: " STDOUT.flush config[:consumer_key] = STDIN.readline.chomp.strip print "Paste the 'Consumer Secret' here: " STDOUT.flush config[:consumer_secret] = STDIN.readline.chomp.strip puts "\n\nNow it's time to authorize your bot!\n\n" if ! app_already_exists && ask_yes_no("Do you want to authorize a bot using the account that created the app?") puts "OK, on the app page, you can click the 'Create my access token' button to proceed.\n\n" print "Paste the 'Access Token' here: " STDOUT.flush config[:access_token] = STDIN.readline.chomp.strip print "\n\nPaste the 'Access Token Secret' here: " STDOUT.flush config[:access_token_secret] = STDIN.readline.chomp.strip # reset the client so we can re-init with new OAuth credentials reset_client # at this point we should have a fully validated client, so grab # the screen name @screen_name = client.user.screen_name rescue nil else reset_client end # # capture ctrl-c and exit without a stack trace # rescue Interrupt => e exit end
[ "def", "get_api_key", "green", "\"****************************************\"", "green", "\"****************************************\"", "green", "\"**** API SETUP TIME! ****\"", "green", "\"****************************************\"", "green", "\"********************************...
Ask the user to get an API key from Twitter.
[ "Ask", "the", "user", "to", "get", "an", "API", "key", "from", "Twitter", "." ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/ui.rb#L103-L173
valid
muffinista/chatterbot
lib/chatterbot/config.rb
Chatterbot.Config.max_id_from
def max_id_from(s) if ! s.respond_to?(:max) if s.respond_to?(:id) return s.id else return s end end sorted = s.max { |a, b| a.id.to_i <=> b.id.to_i } sorted && sorted.id end
ruby
def max_id_from(s) if ! s.respond_to?(:max) if s.respond_to?(:id) return s.id else return s end end sorted = s.max { |a, b| a.id.to_i <=> b.id.to_i } sorted && sorted.id end
[ "def", "max_id_from", "(", "s", ")", "if", "!", "s", ".", "respond_to?", "(", ":max", ")", "if", "s", ".", "respond_to?", "(", ":id", ")", "return", "s", ".", "id", "else", "return", "s", "end", "end", "sorted", "=", "s", ".", "max", "{", "|", ...
given an array or object, return the highest id we can find @param [Enumerable] s the array to check
[ "given", "an", "array", "or", "object", "return", "the", "highest", "id", "we", "can", "find" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L125-L137
valid
muffinista/chatterbot
lib/chatterbot/config.rb
Chatterbot.Config.slurp_file
def slurp_file(f) f = File.expand_path(f) tmp = {} if File.exist?(f) File.open( f ) { |yf| tmp = YAML::load( yf ) } end tmp.symbolize_keys! unless tmp == false end
ruby
def slurp_file(f) f = File.expand_path(f) tmp = {} if File.exist?(f) File.open( f ) { |yf| tmp = YAML::load( yf ) } end tmp.symbolize_keys! unless tmp == false end
[ "def", "slurp_file", "(", "f", ")", "f", "=", "File", ".", "expand_path", "(", "f", ")", "tmp", "=", "{", "}", "if", "File", ".", "exist?", "(", "f", ")", "File", ".", "open", "(", "f", ")", "{", "|", "yf", "|", "tmp", "=", "YAML", "::", "l...
load in a config file
[ "load", "in", "a", "config", "file" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L170-L180
valid
muffinista/chatterbot
lib/chatterbot/config.rb
Chatterbot.Config.global_config
def global_config tmp = {} global_config_files.each { |f| tmp.merge!(slurp_file(f) || {}) } tmp end
ruby
def global_config tmp = {} global_config_files.each { |f| tmp.merge!(slurp_file(f) || {}) } tmp end
[ "def", "global_config", "tmp", "=", "{", "}", "global_config_files", ".", "each", "{", "|", "f", "|", "tmp", ".", "merge!", "(", "slurp_file", "(", "f", ")", "||", "{", "}", ")", "}", "tmp", "end" ]
get any config from our global config files
[ "get", "any", "config", "from", "our", "global", "config", "files" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L199-L205
valid
muffinista/chatterbot
lib/chatterbot/config.rb
Chatterbot.Config.bot_config
def bot_config { :consumer_key => ENV["chatterbot_consumer_key"], :consumer_secret => ENV["chatterbot_consumer_secret"], :access_token => ENV["chatterbot_access_token"], :access_token_secret => ENV["chatterbot_access_secret"] || ENV["chatterbot_access_token_secret"] }.delete_if { |k, v| v.nil? }.merge(slurp_file(config_file) || {}) end
ruby
def bot_config { :consumer_key => ENV["chatterbot_consumer_key"], :consumer_secret => ENV["chatterbot_consumer_secret"], :access_token => ENV["chatterbot_access_token"], :access_token_secret => ENV["chatterbot_access_secret"] || ENV["chatterbot_access_token_secret"] }.delete_if { |k, v| v.nil? }.merge(slurp_file(config_file) || {}) end
[ "def", "bot_config", "{", ":consumer_key", "=>", "ENV", "[", "\"chatterbot_consumer_key\"", "]", ",", ":consumer_secret", "=>", "ENV", "[", "\"chatterbot_consumer_secret\"", "]", ",", ":access_token", "=>", "ENV", "[", "\"chatterbot_access_token\"", "]", ",", ":access...
bot-specific config settings
[ "bot", "-", "specific", "config", "settings" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L209-L216
valid
muffinista/chatterbot
lib/chatterbot/config.rb
Chatterbot.Config.load_config
def load_config(params={}) read_only_data = global_config.merge(bot_config).merge(params) @config = Chatterbot::ConfigManager.new(config_file, read_only_data) end
ruby
def load_config(params={}) read_only_data = global_config.merge(bot_config).merge(params) @config = Chatterbot::ConfigManager.new(config_file, read_only_data) end
[ "def", "load_config", "(", "params", "=", "{", "}", ")", "read_only_data", "=", "global_config", ".", "merge", "(", "bot_config", ")", ".", "merge", "(", "params", ")", "@config", "=", "Chatterbot", "::", "ConfigManager", ".", "new", "(", "config_file", ",...
load in the config from the assortment of places it can be specified.
[ "load", "in", "the", "config", "from", "the", "assortment", "of", "places", "it", "can", "be", "specified", "." ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/config.rb#L221-L224
valid
muffinista/chatterbot
lib/chatterbot/retweet.rb
Chatterbot.Retweet.retweet
def retweet(id=@current_tweet) return if require_login == false || id.nil? id = id_from_tweet(id) #:nocov: if debug_mode? debug "I'm in debug mode, otherwise I would retweet with tweet id: #{id}" return end #:nocov: client.retweet id end
ruby
def retweet(id=@current_tweet) return if require_login == false || id.nil? id = id_from_tweet(id) #:nocov: if debug_mode? debug "I'm in debug mode, otherwise I would retweet with tweet id: #{id}" return end #:nocov: client.retweet id end
[ "def", "retweet", "(", "id", "=", "@current_tweet", ")", "return", "if", "require_login", "==", "false", "||", "id", ".", "nil?", "id", "=", "id_from_tweet", "(", "id", ")", "if", "debug_mode?", "debug", "\"I'm in debug mode, otherwise I would retweet with tweet id:...
simple wrapper for retweeting a message @param [id] id A tweet or the ID of a tweet. if not specified, tries to use the current tweet if available
[ "simple", "wrapper", "for", "retweeting", "a", "message" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/retweet.rb#L9-L21
valid
muffinista/chatterbot
lib/chatterbot/bot.rb
Chatterbot.Bot.run!
def run! before_run HANDLER_CALLS.each { |c| if (h = @handlers[c]) send(c, *(h.opts)) do |obj| h.call(obj) end end } after_run end
ruby
def run! before_run HANDLER_CALLS.each { |c| if (h = @handlers[c]) send(c, *(h.opts)) do |obj| h.call(obj) end end } after_run end
[ "def", "run!", "before_run", "HANDLER_CALLS", ".", "each", "{", "|", "c", "|", "if", "(", "h", "=", "@handlers", "[", "c", "]", ")", "send", "(", "c", ",", "*", "(", "h", ".", "opts", ")", ")", "do", "|", "obj", "|", "h", ".", "call", "(", ...
run the bot with the REST API
[ "run", "the", "bot", "with", "the", "REST", "API" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/bot.rb#L60-L72
valid
muffinista/chatterbot
lib/chatterbot/reply.rb
Chatterbot.Reply.replies
def replies(*args, &block) return unless require_login debug "check for replies since #{since_id_reply}" opts = { :since_id => since_id_reply, :count => 200 } results = client.mentions_timeline(opts) @current_tweet = nil results.each { |s| update_since_id_reply(s) if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
ruby
def replies(*args, &block) return unless require_login debug "check for replies since #{since_id_reply}" opts = { :since_id => since_id_reply, :count => 200 } results = client.mentions_timeline(opts) @current_tweet = nil results.each { |s| update_since_id_reply(s) if block_given? && valid_tweet?(s) @current_tweet = s yield s end } @current_tweet = nil end
[ "def", "replies", "(", "*", "args", ",", "&", "block", ")", "return", "unless", "require_login", "debug", "\"check for replies since #{since_id_reply}\"", "opts", "=", "{", ":since_id", "=>", "since_id_reply", ",", ":count", "=>", "200", "}", "results", "=", "cl...
handle replies for the bot
[ "handle", "replies", "for", "the", "bot" ]
e98ebb4e23882a9aa078bc5f749a6d045c35e9be
https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/reply.rb#L8-L28
valid