id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
14,700
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.analyze_source_codes
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
ruby
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
[ "def", "analyze_source_codes", "@bar", "=", "ProgressBar", ".", "create", "(", "title", ":", "'Source Code'", ",", "total", ":", "parse_files", ".", "size", "*", "3", ")", "if", "display_bar?", "%w[", "lexical", "prepare", "review", "]", ".", "each", "{", "|", "process", "|", "send", "(", ":process", ",", "process", ")", "}", "@bar", ".", "finish", "if", "display_bar?", "end" ]
analyze source codes.
[ "analyze", "source", "codes", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L317-L321
14,701
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks._run_callbacks
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callback.call(*args) unless invalid end end
ruby
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callback.call(*args) unless invalid end end
[ "def", "_run_callbacks", "(", "kind", ",", "*", "args", ")", "#:nodoc:", "options", "=", "args", ".", "last", "# Last callback arg MUST be a Hash", "send", "(", "\"_#{kind}\"", ")", ".", "each", "do", "|", "callback", ",", "conditions", "|", "invalid", "=", "conditions", ".", "find", "do", "|", "key", ",", "value", "|", "value", ".", "is_a?", "(", "Array", ")", "?", "!", "value", ".", "include?", "(", "options", "[", "key", "]", ")", ":", "(", "value", "!=", "options", "[", "key", "]", ")", "end", "callback", ".", "call", "(", "args", ")", "unless", "invalid", "end", "end" ]
Hook to _run_callbacks asserting for conditions.
[ "Hook", "to", "_run_callbacks", "asserting", "for", "conditions", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L7-L17
14,702
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.after_failed_fetch
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
ruby
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
[ "def", "after_failed_fetch", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_after_failed_fetch", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs if no user could be fetched, meaning there is now no user logged in. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameters: |user, auth, scope| user - The authenticated user for the current scope auth - The warden proxy object opts - any options passed into the authenticate call including :scope Example: Warden::Manager.after_failed_fetch do |user, auth, opts| I18n.locale = :en end :api: public
[ "A", "callback", "that", "runs", "if", "no", "user", "could", "be", "fetched", "meaning", "there", "is", "now", "no", "user", "logged", "in", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L138-L141
14,703
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.before_logout
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
ruby
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
[ "def", "before_logout", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_before_logout", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs just prior to the logout of each scope. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameters: |user, auth, scope| user - The authenticated user for the current scope auth - The warden proxy object opts - any options passed into the authenticate call including :scope Example: Warden::Manager.before_logout do |user, auth, opts| user.forget_me! end :api: public
[ "A", "callback", "that", "runs", "just", "prior", "to", "the", "logout", "of", "each", "scope", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L166-L169
14,704
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.on_request
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
ruby
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
[ "def", "on_request", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_on_request", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs on each request, just after the proxy is initialized Parameters: <block> A block to contain logic for the callback Block Parameters: |proxy| proxy - The warden proxy object for the request Example: user = "A User" Warden::Manager.on_request do |proxy| proxy.set_user = user end :api: public
[ "A", "callback", "that", "runs", "on", "each", "request", "just", "after", "the", "proxy", "is", "initialized" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L191-L194
14,705
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.user
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks end @users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil end end
ruby
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callbacks, true) manager._run_callbacks(:after_failed_fetch, user, self, :scope => scope) if run_callbacks end @users[scope] = user ? set_user(user, opts.merge(:event => :fetch)) : nil end end
[ "def", "user", "(", "argument", "=", "{", "}", ")", "opts", "=", "argument", ".", "is_a?", "(", "Hash", ")", "?", "argument", ":", "{", ":scope", "=>", "argument", "}", "scope", "=", "(", "opts", "[", ":scope", "]", "||=", "@config", ".", "default_scope", ")", "if", "@users", ".", "has_key?", "(", "scope", ")", "@users", "[", "scope", "]", "else", "unless", "user", "=", "session_serializer", ".", "fetch", "(", "scope", ")", "run_callbacks", "=", "opts", ".", "fetch", "(", ":run_callbacks", ",", "true", ")", "manager", ".", "_run_callbacks", "(", ":after_failed_fetch", ",", "user", ",", "self", ",", ":scope", "=>", "scope", ")", "if", "run_callbacks", "end", "@users", "[", "scope", "]", "=", "user", "?", "set_user", "(", "user", ",", "opts", ".", "merge", "(", ":event", "=>", ":fetch", ")", ")", ":", "nil", "end", "end" ]
Provides access to the user object in a given scope for a request. Will be nil if not logged in. Please notice that this method does not perform strategies. Example: # without scope (default user) env['warden'].user # with scope env['warden'].user(:admin) # as a Hash env['warden'].user(:scope => :admin) # with default scope and run_callbacks option env['warden'].user(:run_callbacks => false) # with a scope and run_callbacks option env['warden'].user(:scope => :admin, :run_callbacks => true) :api: public
[ "Provides", "access", "to", "the", "user", "object", "in", "a", "given", "scope", "for", "a", "request", ".", "Will", "be", "nil", "if", "not", "logged", "in", ".", "Please", "notice", "that", "this", "method", "does", "not", "perform", "strategies", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L217-L231
14,706
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.logout
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil? session_serializer.delete(scope, user) end reset_session! if reset_session end
ruby
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless raw_session.nil? session_serializer.delete(scope, user) end reset_session! if reset_session end
[ "def", "logout", "(", "*", "scopes", ")", "if", "scopes", ".", "empty?", "scopes", "=", "@users", ".", "keys", "reset_session", "=", "true", "end", "scopes", ".", "each", "do", "|", "scope", "|", "user", "=", "@users", ".", "delete", "(", "scope", ")", "manager", ".", "_run_callbacks", "(", ":before_logout", ",", "user", ",", "self", ",", ":scope", "=>", "scope", ")", "raw_session", ".", "delete", "(", "\"warden.user.#{scope}.session\"", ")", "unless", "raw_session", ".", "nil?", "session_serializer", ".", "delete", "(", "scope", ",", "user", ")", "end", "reset_session!", "if", "reset_session", "end" ]
Provides logout functionality. The logout also manages any authenticated data storage and clears it when a user logs out. Parameters: scopes - a list of scopes to logout Example: # Logout everyone and clear the session env['warden'].logout # Logout the default user but leave the rest of the session alone env['warden'].logout(:default) # Logout the :publisher and :admin user env['warden'].logout(:publisher, :admin) :api: public
[ "Provides", "logout", "functionality", ".", "The", "logout", "also", "manages", "any", "authenticated", "data", "storage", "and", "clears", "it", "when", "a", "user", "logs", "out", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L266-L281
14,707
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._run_strategies_for
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategies = defaults[scope] || defaults[:_all] end (strategies || args).each do |name| strategy = _fetch_strategy(name, scope) next unless strategy && !strategy.performed? && strategy.valid? strategy._run! self.winning_strategy = @winning_strategies[scope] = strategy break if strategy.halted? end end
ruby
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategies = defaults[scope] || defaults[:_all] end (strategies || args).each do |name| strategy = _fetch_strategy(name, scope) next unless strategy && !strategy.performed? && strategy.valid? strategy._run! self.winning_strategy = @winning_strategies[scope] = strategy break if strategy.halted? end end
[ "def", "_run_strategies_for", "(", "scope", ",", "args", ")", "#:nodoc:", "self", ".", "winning_strategy", "=", "@winning_strategies", "[", "scope", "]", "return", "if", "winning_strategy", "&&", "winning_strategy", ".", "halted?", "# Do not run any strategy if locked", "return", "if", "@locked", "if", "args", ".", "empty?", "defaults", "=", "@config", "[", ":default_strategies", "]", "strategies", "=", "defaults", "[", "scope", "]", "||", "defaults", "[", ":_all", "]", "end", "(", "strategies", "||", "args", ")", ".", "each", "do", "|", "name", "|", "strategy", "=", "_fetch_strategy", "(", "name", ",", "scope", ")", "next", "unless", "strategy", "&&", "!", "strategy", ".", "performed?", "&&", "strategy", ".", "valid?", "strategy", ".", "_run!", "self", ".", "winning_strategy", "=", "@winning_strategies", "[", "scope", "]", "=", "strategy", "break", "if", "strategy", ".", "halted?", "end", "end" ]
Run the strategies for a given scope
[ "Run", "the", "strategies", "for", "a", "given", "scope" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L353-L373
14,708
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._fetch_strategy
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
ruby
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
[ "def", "_fetch_strategy", "(", "name", ",", "scope", ")", "@strategies", "[", "scope", "]", "[", "name", "]", "||=", "if", "klass", "=", "Warden", "::", "Strategies", "[", "name", "]", "klass", ".", "new", "(", "@env", ",", "scope", ")", "elsif", "@config", ".", "silence_missing_strategies?", "nil", "else", "raise", "\"Invalid strategy #{name}\"", "end", "end" ]
Fetches strategies and keep them in a hash cache.
[ "Fetches", "strategies", "and", "keep", "them", "in", "a", "hash", "cache", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L376-L384
14,709
qpowell/google_places
lib/google_places/request.rb
GooglePlaces.Request.parsed_response
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response when 'OVER_QUERY_LIMIT' raise OverQueryLimitError.new(@response) when 'REQUEST_DENIED' raise RequestDeniedError.new(@response) when 'INVALID_REQUEST' raise InvalidRequestError.new(@response) when 'UNKNOWN_ERROR' raise UnknownError.new(@response) when 'NOT_FOUND' raise NotFoundError.new(@response) end end
ruby
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response when 'OVER_QUERY_LIMIT' raise OverQueryLimitError.new(@response) when 'REQUEST_DENIED' raise RequestDeniedError.new(@response) when 'INVALID_REQUEST' raise InvalidRequestError.new(@response) when 'UNKNOWN_ERROR' raise UnknownError.new(@response) when 'NOT_FOUND' raise NotFoundError.new(@response) end end
[ "def", "parsed_response", "return", "@response", ".", "headers", "[", "\"location\"", "]", "if", "@response", ".", "code", ">=", "300", "&&", "@response", ".", "code", "<", "400", "raise", "APIConnectionError", ".", "new", "(", "@response", ")", "if", "@response", ".", "code", ">=", "500", "&&", "@response", ".", "code", "<", "600", "case", "@response", ".", "parsed_response", "[", "'status'", "]", "when", "'OK'", ",", "'ZERO_RESULTS'", "@response", ".", "parsed_response", "when", "'OVER_QUERY_LIMIT'", "raise", "OverQueryLimitError", ".", "new", "(", "@response", ")", "when", "'REQUEST_DENIED'", "raise", "RequestDeniedError", ".", "new", "(", "@response", ")", "when", "'INVALID_REQUEST'", "raise", "InvalidRequestError", ".", "new", "(", "@response", ")", "when", "'UNKNOWN_ERROR'", "raise", "UnknownError", ".", "new", "(", "@response", ")", "when", "'NOT_FOUND'", "raise", "NotFoundError", ".", "new", "(", "@response", ")", "end", "end" ]
Parse errors from the server respons, if any @raise [OverQueryLimitError] when server response object includes status 'OVER_QUERY_LIMIT' @raise [RequestDeniedError] when server response object includes 'REQUEST_DENIED' @raise [InvalidRequestError] when server response object includes 'INVALID_REQUEST' @raise [UnknownError] when server response object includes 'UNKNOWN_ERROR' @raise [NotFoundError] when server response object includes 'NOT_FOUND' @return [String] the response from the server as JSON
[ "Parse", "errors", "from", "the", "server", "respons", "if", "any" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/request.rb#L361-L378
14,710
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
ruby
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
[ "def", "spots", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list", "(", "lat", ",", "lng", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Creates a new Client instance which proxies the requests to the certain classes @param [String] api_key The api key to use for the requests @param [Hash] options An options hash for requests. Is used as the query parameters on server requests @option options [String,Integer] lat the latitude for the search @option options [String,Integer] lng the longitude for the search @option options [Integer] :radius Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if <b>:rankby</b> is specified @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options A Hash containing parameters for search retries @option options [Object] :retry_options[:status] @option options [Integer] :retry_options[:max] the maximum retries @option options [Integer] :retry_options[:delay] the delay between each retry in seconds @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types Search for Spots at the provided location @return [Array<Spot>] @param [String,Integer] lat the latitude for the search @param [String,Integer] lng the longitude for the search @param [Hash] options @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if :rankby => 'distance' (described below) is specified. <b>Note that this is a mandatory parameter</b> @option options [String] :rankby Specifies the order in which results are listed. Possible values are: - prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors. - distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Creates", "a", "new", "Client", "instance", "which", "proxies", "the", "requests", "to", "the", "certain", "classes" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L95-L102
14,711
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_query
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
ruby
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
[ "def", "spots_by_query", "(", "query", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_query", "(", "query", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots with a query @return [Array<Spot>] @param [String] query the query to search for @param [Hash] options @option options [String,Integer] lat the latitude for the search @option options [String,Integer] lng the longitude for the search @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. Note that radius must not be included if :rankby => 'distance' (described below) is specified. <b>Note that this is a mandatory parameter</b> @option options [String] :rankby Specifies the order in which results are listed. Possible values are: - prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors. - distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. distance. This option sorts results in ascending order by their distance from the specified location. Ranking results by distance will set a fixed search radius of 50km. One or more of keyword, name, or types is required. @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see http://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 List of supported languages @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "with", "a", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L160-L167
14,712
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_bounds
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
ruby
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
[ "def", "spots_by_bounds", "(", "bounds", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_bounds", "(", "bounds", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots within a give SW|NE bounds with query @return [Array<Spot>] @param [Hash] bounds @param [String] api_key the provided api key @param [Hash] options @option bounds [String, Array] :start_point An array that contains the lat/lng pair for the first point in the bounds (rectangle) @option bounds [:start_point][String, Integer] :lat The starting point coordinates latitude value @option bounds [:start_point][String, Integer] :lng The starting point coordinates longitude value @option bounds [String, Array] :end_point An array that contains the lat/lng pair for the end point in the bounds (rectangle) @option bounds [:end_point][String, Integer] :lat The end point coordinates latitude value @option bounds [:end_point][String, Integer] :lng The end point coordinates longitude value @option options [String,Array] :query Restricts the results to Spots matching term(s) in the specified query @option options [String] :language The language code, indicating in which language the results should be returned, if possible. @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "within", "a", "give", "SW|NE", "bounds", "with", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L204-L211
14,713
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_pagetoken
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
ruby
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
[ "def", "spots_by_pagetoken", "(", "pagetoken", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_pagetoken", "(", "pagetoken", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Search for Spots with a pagetoken @return [Array<Spot>] @param [String] pagetoken the next page token to search for @param [Hash] options @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/maps/documentation/places/supported_types List of supported types
[ "Search", "for", "Spots", "with", "a", "pagetoken" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L229-L236
14,714
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_radar
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
ruby
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
[ "def", "spots_by_radar", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_radar", "(", "lat", ",", "lng", ",", "@api_key", ",", "options", ")", ",", "detail", ")", "end" ]
Radar Search Service allows you to search for up to 200 Places at once, but with less detail than is typically returned from a Text Search or Nearby Search request. The search response will include up to 200 Places, identified only by their geographic coordinates and reference. You can send a Place Details request for more information about any of them. @return [Array<Spot>] @param [String,Integer] lat the latitude for the search @param [String,Integer] lng the longitude for the search @param [Hash] options @option options [Integer] :radius (1000) Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50,000 meters. <b>Note that this is a mandatory parameter</b> @option options [String,Array] :types Restricts the results to Spots matching at least one of the specified types @option options [String] :name A term to be matched against the names of Places. Results will be restricted to those containing the passed name value. @option options [String] :keyword A term to be matched against all content that Google has indexed for this Spot, including but not limited to name, type, and address, as well as customer reviews and other third-party content. @option options [Integer] :minprice Restricts results to only those places within the specified price range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. @option options [Integer] :maxprice Restricts results to only those places within the specified price range. Valid values range between 0 (most affordable) to 4 (most expensive), inclusive. @option options [Boolean] :opennow Retricts results to those Places that are open for business at the time the query is sent. Places that do not specify opening hours in the Google Places database will not be returned if you include this parameter in your query. Setting openNow to false has no effect. @option options [Boolean] :zagatselected Restrict your search to only those locations that are Zagat selected businesses. This parameter does not require a true or false value, simply including the parameter in the request is sufficient to restrict your search. The zagatselected parameter is experimental, and only available to Places API enterprise customers. @option options [Boolean] :detail A boolean to return spots with full detail information(its complete address, phone number, user rating, reviews, etc) Note) This makes an extra call for each spot for more information. @see https://developers.google.com/places/documentation/search#RadarSearchRequests
[ "Radar", "Search", "Service", "allows", "you", "to", "search", "for", "up", "to", "200", "Places", "at", "once", "but", "with", "less", "detail", "than", "is", "typically", "returned", "from", "a", "Text", "Search", "or", "Nearby", "Search", "request", ".", "The", "search", "response", "will", "include", "up", "to", "200", "Places", "identified", "only", "by", "their", "geographic", "coordinates", "and", "reference", ".", "You", "can", "send", "a", "Place", "Details", "request", "for", "more", "information", "about", "any", "of", "them", "." ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L274-L281
14,715
qpowell/google_places
lib/google_places/photo.rb
GooglePlaces.Photo.fetch_url
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, :retry_options => retry_options ) end @fetched_url end
ruby
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, :retry_options => retry_options ) end @fetched_url end
[ "def", "fetch_url", "(", "maxwidth", ",", "options", "=", "{", "}", ")", "language", "=", "options", ".", "delete", "(", ":language", ")", "retry_options", "=", "options", ".", "delete", "(", ":retry_options", ")", "||", "{", "}", "unless", "@fetched_url", "@fetched_url", "=", "Request", ".", "photo_url", "(", ":maxwidth", "=>", "maxwidth", ",", ":photoreference", "=>", "@photo_reference", ",", ":key", "=>", "@api_key", ",", ":retry_options", "=>", "retry_options", ")", "end", "@fetched_url", "end" ]
Search for a Photo's url with its reference key @return [URL] @param [String] api_key the provided api key @param [Hash] options @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_options[:max] (0) the maximum retries @option options [Integer] :retry_options[:delay] (5) the delay between each retry in seconds
[ "Search", "for", "a", "Photo", "s", "url", "with", "its", "reference", "key" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/photo.rb#L23-L36
14,716
solnic/virtus
lib/virtus/const_missing_extensions.rb
Virtus.ConstMissingExtensions.const_missing
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
ruby
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
[ "def", "const_missing", "(", "name", ")", "Attribute", "::", "Builder", ".", "determine_type", "(", "name", ")", "or", "Axiom", "::", "Types", ".", "const_defined?", "(", "name", ")", "&&", "Axiom", "::", "Types", ".", "const_get", "(", "name", ")", "or", "super", "end" ]
Hooks into const missing process to determine types of attributes @param [String] name @return [Class] @api private
[ "Hooks", "into", "const", "missing", "process", "to", "determine", "types", "of", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/const_missing_extensions.rb#L11-L15
14,717
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.each
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
ruby
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "@index", ".", "each", "{", "|", "name", ",", "attribute", "|", "yield", "attribute", "if", "name", ".", "kind_of?", "(", "Symbol", ")", "}", "self", "end" ]
Initialize an AttributeSet @param [AttributeSet] parent @param [Array] attributes @return [undefined] @api private Iterate over each attribute in the set @example attribute_set = AttributeSet.new(attributes, parent) attribute_set.each { |attribute| ... } @yield [attribute] @yieldparam [Attribute] attribute each attribute in the set @return [self] @api public
[ "Initialize", "an", "AttributeSet" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L44-L48
14,718
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_reader_method
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
ruby
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
[ "def", "define_reader_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "attribute", ".", "get", "(", "self", ")", "}", "send", "(", "visibility", ",", "method_name", ")", "end" ]
Defines an attribute reader method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "reader", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L131-L134
14,719
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_writer_method
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
ruby
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
[ "def", "define_writer_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "|", "value", "|", "attribute", ".", "set", "(", "self", ",", "value", ")", "}", "send", "(", "visibility", ",", "method_name", ")", "end" ]
Defines an attribute writer method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "writer", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L145-L148
14,720
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.get
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
ruby
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
[ "def", "get", "(", "object", ")", "each_with_object", "(", "{", "}", ")", "do", "|", "attribute", ",", "attributes", "|", "name", "=", "attribute", ".", "name", "attributes", "[", "name", "]", "=", "object", ".", "__send__", "(", "name", ")", "if", "attribute", ".", "public_reader?", "end", "end" ]
Get values of all attributes defined for this class, ignoring privacy @return [Hash] @api private
[ "Get", "values", "of", "all", "attributes", "defined", "for", "this", "class", "ignoring", "privacy" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L155-L160
14,721
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
ruby
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
[ "def", "set", "(", "object", ",", "attributes", ")", "coerce", "(", "attributes", ")", ".", "each", "do", "|", "name", ",", "value", "|", "writer_name", "=", "\"#{name}=\"", "if", "object", ".", "allowed_writer_methods", ".", "include?", "(", "writer_name", ")", "object", ".", "__send__", "(", "writer_name", ",", "value", ")", "end", "end", "end" ]
Mass-assign attribute values @see Virtus::InstanceMethods#attributes= @return [Hash] @api private
[ "Mass", "-", "assign", "attribute", "values" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L169-L176
14,722
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set_defaults
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
ruby
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
[ "def", "set_defaults", "(", "object", ",", "filter", "=", "method", "(", ":skip_default?", ")", ")", "each", "do", "|", "attribute", "|", "next", "if", "filter", ".", "call", "(", "object", ",", "attribute", ")", "attribute", ".", "set_default_value", "(", "object", ")", "end", "end" ]
Set default attributes @return [self] @api private
[ "Set", "default", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L183-L188
14,723
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_primitive
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive end type end
ruby
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive end type end
[ "def", "determine_type_from_primitive", "(", "primitive", ")", "type", "=", "nil", "descendants", ".", "select", "(", ":primitive", ")", ".", "reverse_each", "do", "|", "descendant", "|", "descendant_primitive", "=", "descendant", ".", "primitive", "next", "unless", "primitive", "<=", "descendant_primitive", "type", "=", "descendant", "if", "type", ".", "nil?", "or", "type", ".", "primitive", ">", "descendant_primitive", "end", "type", "end" ]
Return the class given a primitive @param [Class] primitive @return [Class] @return [nil] nil if the type cannot be determined by the primitive @api private
[ "Return", "the", "class", "given", "a", "primitive" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L82-L90
14,724
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_string
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
ruby
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
[ "def", "determine_type_from_string", "(", "string", ")", "if", "string", "=~", "TYPE_FORMAT", "and", "const_defined?", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "const_get", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "end", "end" ]
Return the class given a string @param [String] string @return [Class] @return [nil] nil if the type cannot be determined by the string @api private
[ "Return", "the", "class", "given", "a", "string" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L102-L106
14,725
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.extended
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
ruby
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
[ "def", "extended", "(", "object", ")", "super", "@inclusions", ".", "each", "{", "|", "mod", "|", "object", ".", "extend", "(", "mod", ")", "}", "define_attributes", "(", "object", ")", "object", ".", "set_default_attributes", "end" ]
Extend an object with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "an", "object", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L44-L49
14,726
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.included
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtensions.setup(object, @inclusions, @attribute_definitions) end end
ruby
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtensions.setup(object, @inclusions, @attribute_definitions) end end
[ "def", "included", "(", "object", ")", "super", "if", "Class", "===", "object", "@inclusions", ".", "reject", "do", "|", "mod", "|", "object", ".", "ancestors", ".", "include?", "(", "mod", ")", "end", ".", "each", "do", "|", "mod", "|", "object", ".", "send", "(", ":include", ",", "mod", ")", "end", "define_attributes", "(", "object", ")", "else", "object", ".", "extend", "(", "ModuleExtensions", ")", "ModuleExtensions", ".", "setup", "(", "object", ",", "@inclusions", ",", "@attribute_definitions", ")", "end", "end" ]
Extend a class with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "a", "class", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L58-L72
14,727
solnic/virtus
lib/virtus/builder.rb
Virtus.Builder.add_included_hook
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_method) end end end
ruby
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_method) end end end
[ "def", "add_included_hook", "with_hook_context", "do", "|", "context", "|", "mod", ".", "define_singleton_method", ":included", "do", "|", "object", "|", "Builder", ".", "pending", "<<", "object", "unless", "context", ".", "finalize?", "context", ".", "modules", ".", "each", "{", "|", "mod", "|", "object", ".", "send", "(", ":include", ",", "mod", ")", "}", "object", ".", "define_singleton_method", "(", ":attribute", ",", "context", ".", "attribute_method", ")", "end", "end", "end" ]
Adds the .included hook to the anonymous module which then defines the .attribute method to override the default. @return [Module] @api private
[ "Adds", "the", ".", "included", "hook", "to", "the", "anonymous", "module", "which", "then", "defines", "the", ".", "attribute", "method", "to", "override", "the", "default", "." ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/builder.rb#L68-L76
14,728
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.options
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
ruby
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
[ "def", "options", "accepted_options", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "option_name", ",", "options", "|", "option_value", "=", "send", "(", "option_name", ")", "options", "[", "option_name", "]", "=", "option_value", "unless", "option_value", ".", "nil?", "end", "end" ]
Returns default options hash for a given attribute class @example Virtus::Attribute::String.options # => {:primitive => String} @return [Hash] a hash of default option values @api public
[ "Returns", "default", "options", "hash", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L16-L21
14,729
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.accept_options
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
ruby
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
[ "def", "accept_options", "(", "*", "new_options", ")", "add_accepted_options", "(", "new_options", ")", "new_options", ".", "each", "{", "|", "option", "|", "define_option_method", "(", "option", ")", "}", "descendants", ".", "each", "{", "|", "descendant", "|", "descendant", ".", "add_accepted_options", "(", "new_options", ")", "}", "self", "end" ]
Defines which options are valid for a given attribute class @example class MyAttribute < Virtus::Attribute accept_options :foo, :bar end @return [self] @api public
[ "Defines", "which", "options", "are", "valid", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L47-L52
14,730
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.verify
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) end result end
ruby
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) end result end
[ "def", "verify", "(", "otp", ",", "drift_ahead", ":", "0", ",", "drift_behind", ":", "0", ",", "after", ":", "nil", ",", "at", ":", "Time", ".", "now", ")", "timecodes", "=", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "timecodes", "=", "timecodes", ".", "select", "{", "|", "t", "|", "t", ">", "timecode", "(", "after", ")", "}", "if", "after", "result", "=", "nil", "timecodes", ".", "each", "do", "|", "t", "|", "result", "=", "t", "*", "interval", "if", "super", "(", "otp", ",", "generate_otp", "(", "t", ")", ")", "end", "result", "end" ]
Verifies the OTP passed in against the current time OTP and adjacent intervals up to +drift+. Excludes OTPs from `after` and earlier. Returns time value of matching OTP code for use in subsequent call. @param otp [String] the one time password to verify @param drift_behind [Integer] how many seconds to look back @param drift_ahead [Integer] how many seconds to look ahead @param after [Integer] prevent token reuse, last login timestamp @param at [Time] time at which to generate and verify a particular otp. default Time.now @return [Integer, nil] the last successful timestamp interval
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP", "and", "adjacent", "intervals", "up", "to", "+", "drift", "+", ".", "Excludes", "OTPs", "from", "after", "and", "earlier", ".", "Returns", "time", "value", "of", "matching", "OTP", "code", "for", "use", "in", "subsequent", "call", "." ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L39-L49
14,731
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.get_timecodes
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
ruby
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
[ "def", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "now", "=", "timeint", "(", "at", ")", "timecode_start", "=", "timecode", "(", "now", "-", "drift_behind", ")", "timecode_end", "=", "timecode", "(", "now", "+", "drift_ahead", ")", "(", "timecode_start", "..", "timecode_end", ")", ".", "step", "(", "1", ")", ".", "to_a", "end" ]
Get back an array of timecodes for a period
[ "Get", "back", "an", "array", "of", "timecodes", "for", "a", "period" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L75-L80
14,732
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.encode_params
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
ruby
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
[ "def", "encode_params", "(", "uri", ",", "params", ")", "params_str", "=", "String", ".", "new", "(", "'?'", ")", "params", ".", "each", "do", "|", "k", ",", "v", "|", "params_str", "<<", "\"#{k}=#{CGI.escape(v.to_s)}&\"", "if", "v", "end", "params_str", ".", "chop!", "uri", "+", "params_str", "end" ]
A very simple param encoder
[ "A", "very", "simple", "param", "encoder" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L70-L77
14,733
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.time_constant_compare
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
ruby
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
[ "def", "time_constant_compare", "(", "a", ",", "b", ")", "return", "false", "if", "a", ".", "empty?", "||", "b", ".", "empty?", "||", "a", ".", "bytesize", "!=", "b", ".", "bytesize", "l", "=", "a", ".", "unpack", "\"C#{a.bytesize}\"", "res", "=", "0", "b", ".", "each_byte", "{", "|", "byte", "|", "res", "|=", "byte", "^", "l", ".", "shift", "}", "res", "==", "0", "end" ]
constant-time compare the strings
[ "constant", "-", "time", "compare", "the", "strings" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L80-L87
14,734
mdp/rotp
lib/rotp/hotp.rb
ROTP.HOTP.verify
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
ruby
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
[ "def", "verify", "(", "otp", ",", "counter", ",", "retries", ":", "0", ")", "counters", "=", "(", "counter", "..", "counter", "+", "retries", ")", ".", "to_a", "counters", ".", "find", "do", "|", "c", "|", "super", "(", "otp", ",", "at", "(", "c", ")", ")", "end", "end" ]
Verifies the OTP passed in against the current time OTP @param otp [String/Integer] the OTP to check against @param counter [Integer] the counter of the OTP @param retries [Integer] number of counters to incrementally retry
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/hotp.rb#L14-L19
14,735
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.ec2_metadata
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/instance-identity/document') do |f| contents = f.read @ec2_metadata = JSON.parse(contents) end end @ec2_metadata end
ruby
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/instance-identity/document') do |f| contents = f.read @ec2_metadata = JSON.parse(contents) end end @ec2_metadata end
[ "def", "ec2_metadata", "raise", "\"Called ec2_metadata with platform=#{@platform}\"", "unless", "@platform", "==", "Platform", "::", "EC2", "unless", "@ec2_metadata", "# See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html", "open", "(", "'http://'", "+", "METADATA_SERVICE_ADDR", "+", "'/latest/dynamic/instance-identity/document'", ")", "do", "|", "f", "|", "contents", "=", "f", ".", "read", "@ec2_metadata", "=", "JSON", ".", "parse", "(", "contents", ")", "end", "end", "@ec2_metadata", "end" ]
EC2 Metadata server returns everything in one call. Store it after the first fetch to avoid making multiple calls.
[ "EC2", "Metadata", "server", "returns", "everything", "in", "one", "call", ".", "Store", "it", "after", "the", "first", "fetch", "to", "avoid", "making", "multiple", "calls", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1081-L1094
14,736
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_required_metadata_variables
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing << 'vm_id' unless @vm_id end return if missing.empty? raise Fluent::ConfigError, "Unable to obtain metadata parameters: #{missing.join(' ')}" end
ruby
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing << 'vm_id' unless @vm_id end return if missing.empty? raise Fluent::ConfigError, "Unable to obtain metadata parameters: #{missing.join(' ')}" end
[ "def", "set_required_metadata_variables", "set_project_id", "set_vm_id", "set_vm_name", "set_location", "# All metadata parameters must now be set.", "missing", "=", "[", "]", "missing", "<<", "'project_id'", "unless", "@project_id", "if", "@platform", "!=", "Platform", "::", "OTHER", "missing", "<<", "'zone'", "unless", "@zone", "missing", "<<", "'vm_id'", "unless", "@vm_id", "end", "return", "if", "missing", ".", "empty?", "raise", "Fluent", "::", "ConfigError", ",", "\"Unable to obtain metadata parameters: #{missing.join(' ')}\"", "end" ]
Set required variables like @project_id, @vm_id, @vm_name and @zone.
[ "Set", "required", "variables", "like" ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1114-L1130
14,737
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_vm_id
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
ruby
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
[ "def", "set_vm_id", "@vm_id", "||=", "fetch_gce_metadata", "(", "'instance/id'", ")", "if", "@platform", "==", "Platform", "::", "GCE", "@vm_id", "||=", "ec2_metadata", "[", "'instanceId'", "]", "if", "@platform", "==", "Platform", "::", "EC2", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to obtain vm_id: '", ",", "error", ":", "e", "end" ]
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it by calling metadata servers directly.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "by", "calling", "metadata", "servers", "directly", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1143-L1148
14,738
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_location
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else 'region' end @zone ||= 'aws:' + ec2_metadata[aws_location_key] if @platform == Platform::EC2 && ec2_metadata.key?(aws_location_key) rescue StandardError => e @log.error 'Failed to obtain location: ', error: e end
ruby
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else 'region' end @zone ||= 'aws:' + ec2_metadata[aws_location_key] if @platform == Platform::EC2 && ec2_metadata.key?(aws_location_key) rescue StandardError => e @log.error 'Failed to obtain location: ', error: e end
[ "def", "set_location", "# Response format: \"projects/<number>/zones/<zone>\"", "@zone", "||=", "fetch_gce_metadata", "(", "'instance/zone'", ")", ".", "rpartition", "(", "'/'", ")", "[", "2", "]", "if", "@platform", "==", "Platform", "::", "GCE", "aws_location_key", "=", "if", "@use_aws_availability_zone", "'availabilityZone'", "else", "'region'", "end", "@zone", "||=", "'aws:'", "+", "ec2_metadata", "[", "aws_location_key", "]", "if", "@platform", "==", "Platform", "::", "EC2", "&&", "ec2_metadata", ".", "key?", "(", "aws_location_key", ")", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to obtain location: '", ",", "error", ":", "e", "end" ]
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it locally.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "locally", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1160-L1173
14,739
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_via_legacy
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource end
ruby
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource end
[ "def", "determine_agent_level_monitored_resource_via_legacy", "resource", "=", "Google", "::", "Apis", "::", "LoggingV2", "::", "MonitoredResource", ".", "new", "(", "labels", ":", "{", "}", ")", "resource", ".", "type", "=", "determine_agent_level_monitored_resource_type", "resource", ".", "labels", "=", "determine_agent_level_monitored_resource_labels", "(", "resource", ".", "type", ")", "resource", "end" ]
Retrieve monitored resource via the legacy way. Note: This is just a failover plan if we fail to get metadata from Metadata Agent. Thus it should be equivalent to what Metadata Agent returns.
[ "Retrieve", "monitored", "resource", "via", "the", "legacy", "way", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1180-L1187
14,740
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_type
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Resource types determined by @subservice_name config. return SUBSERVICE_MAP[@subservice_name] if @subservice_name # Resource types determined by @detect_subservice config. if @detect_subservice begin attributes = fetch_gce_metadata('instance/attributes/').split.to_set SUBSERVICE_METADATA_ATTRIBUTES.each do |resource_type, expected| return resource_type if attributes.superset?(expected) end rescue StandardError => e @log.error 'Failed to detect subservice: ', error: e end end # GCE instance. return COMPUTE_CONSTANTS[:resource_type] end end
ruby
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Resource types determined by @subservice_name config. return SUBSERVICE_MAP[@subservice_name] if @subservice_name # Resource types determined by @detect_subservice config. if @detect_subservice begin attributes = fetch_gce_metadata('instance/attributes/').split.to_set SUBSERVICE_METADATA_ATTRIBUTES.each do |resource_type, expected| return resource_type if attributes.superset?(expected) end rescue StandardError => e @log.error 'Failed to detect subservice: ', error: e end end # GCE instance. return COMPUTE_CONSTANTS[:resource_type] end end
[ "def", "determine_agent_level_monitored_resource_type", "case", "@platform", "when", "Platform", "::", "OTHER", "# Unknown platform will be defaulted to GCE instance.", "return", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "when", "Platform", "::", "EC2", "return", "EC2_CONSTANTS", "[", ":resource_type", "]", "when", "Platform", "::", "GCE", "# Resource types determined by @subservice_name config.", "return", "SUBSERVICE_MAP", "[", "@subservice_name", "]", "if", "@subservice_name", "# Resource types determined by @detect_subservice config.", "if", "@detect_subservice", "begin", "attributes", "=", "fetch_gce_metadata", "(", "'instance/attributes/'", ")", ".", "split", ".", "to_set", "SUBSERVICE_METADATA_ATTRIBUTES", ".", "each", "do", "|", "resource_type", ",", "expected", "|", "return", "resource_type", "if", "attributes", ".", "superset?", "(", "expected", ")", "end", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to detect subservice: '", ",", "error", ":", "e", "end", "end", "# GCE instance.", "return", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "end", "end" ]
Determine agent level monitored resource type.
[ "Determine", "agent", "level", "monitored", "resource", "type", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1190-L1218
14,741
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_labels
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/attributes/gae_backend_version') } # GCE. when COMPUTE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone } # GKE container. when GKE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone, 'cluster_name' => fetch_gce_metadata('instance/attributes/cluster-name') } # Cloud Dataproc. when DATAPROC_CONSTANTS[:resource_type] return { 'cluster_uuid' => fetch_gce_metadata('instance/attributes/dataproc-cluster-uuid'), 'cluster_name' => fetch_gce_metadata('instance/attributes/dataproc-cluster-name'), 'region' => fetch_gce_metadata('instance/attributes/dataproc-region') } # EC2. when EC2_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone labels = { 'instance_id' => @vm_id, 'region' => @zone } labels['aws_account'] = ec2_metadata['accountId'] if ec2_metadata.key?('accountId') return labels end {} rescue StandardError => e @log.error "Failed to set monitored resource labels for #{type}: ", error: e {} end
ruby
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/attributes/gae_backend_version') } # GCE. when COMPUTE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone } # GKE container. when GKE_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone return { 'instance_id' => @vm_id, 'zone' => @zone, 'cluster_name' => fetch_gce_metadata('instance/attributes/cluster-name') } # Cloud Dataproc. when DATAPROC_CONSTANTS[:resource_type] return { 'cluster_uuid' => fetch_gce_metadata('instance/attributes/dataproc-cluster-uuid'), 'cluster_name' => fetch_gce_metadata('instance/attributes/dataproc-cluster-name'), 'region' => fetch_gce_metadata('instance/attributes/dataproc-region') } # EC2. when EC2_CONSTANTS[:resource_type] raise "Cannot construct a #{type} resource without vm_id and zone" \ unless @vm_id && @zone labels = { 'instance_id' => @vm_id, 'region' => @zone } labels['aws_account'] = ec2_metadata['accountId'] if ec2_metadata.key?('accountId') return labels end {} rescue StandardError => e @log.error "Failed to set monitored resource labels for #{type}: ", error: e {} end
[ "def", "determine_agent_level_monitored_resource_labels", "(", "type", ")", "case", "type", "# GAE app.", "when", "APPENGINE_CONSTANTS", "[", ":resource_type", "]", "return", "{", "'module_id'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/gae_backend_name'", ")", ",", "'version_id'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/gae_backend_version'", ")", "}", "# GCE.", "when", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "return", "{", "'instance_id'", "=>", "@vm_id", ",", "'zone'", "=>", "@zone", "}", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "return", "{", "'instance_id'", "=>", "@vm_id", ",", "'zone'", "=>", "@zone", ",", "'cluster_name'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/cluster-name'", ")", "}", "# Cloud Dataproc.", "when", "DATAPROC_CONSTANTS", "[", ":resource_type", "]", "return", "{", "'cluster_uuid'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-cluster-uuid'", ")", ",", "'cluster_name'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-cluster-name'", ")", ",", "'region'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/dataproc-region'", ")", "}", "# EC2.", "when", "EC2_CONSTANTS", "[", ":resource_type", "]", "raise", "\"Cannot construct a #{type} resource without vm_id and zone\"", "unless", "@vm_id", "&&", "@zone", "labels", "=", "{", "'instance_id'", "=>", "@vm_id", ",", "'region'", "=>", "@zone", "}", "labels", "[", "'aws_account'", "]", "=", "ec2_metadata", "[", "'accountId'", "]", "if", "ec2_metadata", ".", "key?", "(", "'accountId'", ")", "return", "labels", "end", "{", "}", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "\"Failed to set monitored resource labels for #{type}: \"", ",", "error", ":", "e", "{", "}", "end" ]
Determine agent level monitored resource labels based on the resource type. Each resource type has its own labels that need to be filled in.
[ "Determine", "agent", "level", "monitored", "resource", "labels", "based", "on", "the", "resource", "type", ".", "Each", "resource", "type", "has", "its", "own", "labels", "that", "need", "to", "be", "filled", "in", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1222-L1282
14,742
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_common_labels
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], DATAFLOW_CONSTANTS[:resource_type], DATAPROC_CONSTANTS[:resource_type], ML_CONSTANTS[:resource_type] labels.merge!( "#{COMPUTE_CONSTANTS[:service]}/resource_id" => @vm_id, "#{COMPUTE_CONSTANTS[:service]}/resource_name" => @vm_name, "#{COMPUTE_CONSTANTS[:service]}/zone" => @zone ) # GCE instance and GKE container. when COMPUTE_CONSTANTS[:resource_type], GKE_CONSTANTS[:resource_type] labels["#{COMPUTE_CONSTANTS[:service]}/resource_name"] = @vm_name # EC2. when EC2_CONSTANTS[:resource_type] labels["#{EC2_CONSTANTS[:service]}/resource_name"] = @vm_name end labels end
ruby
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], DATAFLOW_CONSTANTS[:resource_type], DATAPROC_CONSTANTS[:resource_type], ML_CONSTANTS[:resource_type] labels.merge!( "#{COMPUTE_CONSTANTS[:service]}/resource_id" => @vm_id, "#{COMPUTE_CONSTANTS[:service]}/resource_name" => @vm_name, "#{COMPUTE_CONSTANTS[:service]}/zone" => @zone ) # GCE instance and GKE container. when COMPUTE_CONSTANTS[:resource_type], GKE_CONSTANTS[:resource_type] labels["#{COMPUTE_CONSTANTS[:service]}/resource_name"] = @vm_name # EC2. when EC2_CONSTANTS[:resource_type] labels["#{EC2_CONSTANTS[:service]}/resource_name"] = @vm_name end labels end
[ "def", "determine_agent_level_common_labels", "labels", "=", "{", "}", "# User can specify labels via config. We want to capture those as well.", "labels", ".", "merge!", "(", "@labels", ")", "if", "@labels", "case", "@resource", ".", "type", "# GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML.", "when", "APPENGINE_CONSTANTS", "[", ":resource_type", "]", ",", "DATAFLOW_CONSTANTS", "[", ":resource_type", "]", ",", "DATAPROC_CONSTANTS", "[", ":resource_type", "]", ",", "ML_CONSTANTS", "[", ":resource_type", "]", "labels", ".", "merge!", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_id\"", "=>", "@vm_id", ",", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", "=>", "@vm_name", ",", "\"#{COMPUTE_CONSTANTS[:service]}/zone\"", "=>", "@zone", ")", "# GCE instance and GKE container.", "when", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", ",", "GKE_CONSTANTS", "[", ":resource_type", "]", "labels", "[", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", "]", "=", "@vm_name", "# EC2.", "when", "EC2_CONSTANTS", "[", ":resource_type", "]", "labels", "[", "\"#{EC2_CONSTANTS[:service]}/resource_name\"", "]", "=", "@vm_name", "end", "labels", "end" ]
Determine the common labels that should be added to all log entries processed by this logging agent.
[ "Determine", "the", "common", "labels", "that", "should", "be", "added", "to", "all", "log", "entries", "processed", "by", "this", "logging", "agent", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1286-L1313
14,743
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.group_log_entries_by_tag_and_local_resource_id
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in JSON format.' next end sanitized_tag = sanitize_tag(tag) if sanitized_tag.nil? @log.warn "Dropping log entries with invalid tag: '#{tag.inspect}'." \ ' A tag should be a string with utf8 characters.' next end local_resource_id = record.delete(LOCAL_RESOURCE_ID_KEY) # A nil local_resource_id means "fall back to legacy". hash_key = [sanitized_tag, local_resource_id].freeze groups[hash_key] ||= [] groups[hash_key].push([time, record]) end groups end
ruby
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in JSON format.' next end sanitized_tag = sanitize_tag(tag) if sanitized_tag.nil? @log.warn "Dropping log entries with invalid tag: '#{tag.inspect}'." \ ' A tag should be a string with utf8 characters.' next end local_resource_id = record.delete(LOCAL_RESOURCE_ID_KEY) # A nil local_resource_id means "fall back to legacy". hash_key = [sanitized_tag, local_resource_id].freeze groups[hash_key] ||= [] groups[hash_key].push([time, record]) end groups end
[ "def", "group_log_entries_by_tag_and_local_resource_id", "(", "chunk", ")", "groups", "=", "{", "}", "chunk", ".", "msgpack_each", "do", "|", "tag", ",", "time", ",", "record", "|", "unless", "record", ".", "is_a?", "(", "Hash", ")", "@log", ".", "warn", "'Dropping log entries with malformed record: '", "\"'#{record.inspect}'. \"", "'A log record should be in JSON format.'", "next", "end", "sanitized_tag", "=", "sanitize_tag", "(", "tag", ")", "if", "sanitized_tag", ".", "nil?", "@log", ".", "warn", "\"Dropping log entries with invalid tag: '#{tag.inspect}'.\"", "' A tag should be a string with utf8 characters.'", "next", "end", "local_resource_id", "=", "record", ".", "delete", "(", "LOCAL_RESOURCE_ID_KEY", ")", "# A nil local_resource_id means \"fall back to legacy\".", "hash_key", "=", "[", "sanitized_tag", ",", "local_resource_id", "]", ".", "freeze", "groups", "[", "hash_key", "]", "||=", "[", "]", "groups", "[", "hash_key", "]", ".", "push", "(", "[", "time", ",", "record", "]", ")", "end", "groups", "end" ]
Group the log entries by tag and local_resource_id pairs. Also filter out invalid non-Hash entries.
[ "Group", "the", "log", "entries", "by", "tag", "and", "local_resource_id", "pairs", ".", "Also", "filter", "out", "invalid", "non", "-", "Hash", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1317-L1339
14,744
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_group_level_monitored_resource_and_labels
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group if the tag matches # certain regexp. matched_regexp_group = nil # @tag_regexp_list can be an empty list. @tag_regexp_list.each do |derived_type, tag_regexp| matched_regexp_group = tag_regexp.match(tag) if matched_regexp_group resource.type = derived_type break end end # Determine the monitored resource based on the local_resource_id. # Different monitored resource types have unique ids in different format. # We will query Metadata Agent for the monitored resource. Return the # legacy monitored resource (either the instance resource or the resource # inferred from the tag) if failed to get a monitored resource from # Metadata Agent with this key. # # Examples: # "container.<container_id>" // Docker container. # "k8s_pod.<namespace_name>.<pod_name>" // GKE pod. if local_resource_id converted_resource = monitored_resource_from_local_resource_id( local_resource_id) resource = converted_resource if converted_resource end # Once the resource type is settled down, determine the labels. case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] resource.labels.merge!( 'region' => @gcf_region, 'function_name' => decode_cloudfunctions_function_name( matched_regexp_group['encoded_function_name']) ) instance_id = resource.labels.delete('instance_id') common_labels.merge!( "#{GKE_CONSTANTS[:service]}/instance_id" => instance_id, "#{COMPUTE_CONSTANTS[:service]}/resource_id" => instance_id, "#{GKE_CONSTANTS[:service]}/cluster_name" => resource.labels.delete('cluster_name'), "#{COMPUTE_CONSTANTS[:service]}/zone" => resource.labels.delete('zone') ) # GKE container. when GKE_CONSTANTS[:resource_type] if matched_regexp_group # We only expect one occurrence of each key in the match group. resource_labels_candidates = matched_regexp_group.names.zip(matched_regexp_group.captures).to_h common_labels_candidates = resource_labels_candidates.dup resource.labels.merge!( delete_and_extract_labels( resource_labels_candidates, # The kubernetes_tag_regexp is poorly named. 'namespace_name' is # in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'. # TODO(qingling128): Figure out how to put this map into # constants like GKE_CONSTANTS[:extra_resource_labels]. 'container_name' => 'container_name', 'namespace_name' => 'namespace_id', 'pod_name' => 'pod_id')) common_labels.merge!( delete_and_extract_labels( common_labels_candidates, GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) end # Docker container. # TODO(qingling128): Remove this logic once the resource is retrieved at a # proper time (b/65175256). when DOCKER_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") # TODO(qingling128): Temporary fallback for metadata agent restarts. # K8s resources. when K8S_CONTAINER_CONSTANTS[:resource_type], K8S_POD_CONSTANTS[:resource_type], K8S_NODE_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") end # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' option. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end resource.freeze resource.labels.freeze common_labels.freeze [resource, common_labels] end
ruby
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group if the tag matches # certain regexp. matched_regexp_group = nil # @tag_regexp_list can be an empty list. @tag_regexp_list.each do |derived_type, tag_regexp| matched_regexp_group = tag_regexp.match(tag) if matched_regexp_group resource.type = derived_type break end end # Determine the monitored resource based on the local_resource_id. # Different monitored resource types have unique ids in different format. # We will query Metadata Agent for the monitored resource. Return the # legacy monitored resource (either the instance resource or the resource # inferred from the tag) if failed to get a monitored resource from # Metadata Agent with this key. # # Examples: # "container.<container_id>" // Docker container. # "k8s_pod.<namespace_name>.<pod_name>" // GKE pod. if local_resource_id converted_resource = monitored_resource_from_local_resource_id( local_resource_id) resource = converted_resource if converted_resource end # Once the resource type is settled down, determine the labels. case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] resource.labels.merge!( 'region' => @gcf_region, 'function_name' => decode_cloudfunctions_function_name( matched_regexp_group['encoded_function_name']) ) instance_id = resource.labels.delete('instance_id') common_labels.merge!( "#{GKE_CONSTANTS[:service]}/instance_id" => instance_id, "#{COMPUTE_CONSTANTS[:service]}/resource_id" => instance_id, "#{GKE_CONSTANTS[:service]}/cluster_name" => resource.labels.delete('cluster_name'), "#{COMPUTE_CONSTANTS[:service]}/zone" => resource.labels.delete('zone') ) # GKE container. when GKE_CONSTANTS[:resource_type] if matched_regexp_group # We only expect one occurrence of each key in the match group. resource_labels_candidates = matched_regexp_group.names.zip(matched_regexp_group.captures).to_h common_labels_candidates = resource_labels_candidates.dup resource.labels.merge!( delete_and_extract_labels( resource_labels_candidates, # The kubernetes_tag_regexp is poorly named. 'namespace_name' is # in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'. # TODO(qingling128): Figure out how to put this map into # constants like GKE_CONSTANTS[:extra_resource_labels]. 'container_name' => 'container_name', 'namespace_name' => 'namespace_id', 'pod_name' => 'pod_id')) common_labels.merge!( delete_and_extract_labels( common_labels_candidates, GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) end # Docker container. # TODO(qingling128): Remove this logic once the resource is retrieved at a # proper time (b/65175256). when DOCKER_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") # TODO(qingling128): Temporary fallback for metadata agent restarts. # K8s resources. when K8S_CONTAINER_CONSTANTS[:resource_type], K8S_POD_CONSTANTS[:resource_type], K8S_NODE_CONSTANTS[:resource_type] common_labels.delete("#{COMPUTE_CONSTANTS[:service]}/resource_name") end # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' option. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end resource.freeze resource.labels.freeze common_labels.freeze [resource, common_labels] end
[ "def", "determine_group_level_monitored_resource_and_labels", "(", "tag", ",", "local_resource_id", ")", "resource", "=", "@resource", ".", "dup", "resource", ".", "labels", "=", "@resource", ".", "labels", ".", "dup", "common_labels", "=", "@common_labels", ".", "dup", "# Change the resource type and set matched_regexp_group if the tag matches", "# certain regexp.", "matched_regexp_group", "=", "nil", "# @tag_regexp_list can be an empty list.", "@tag_regexp_list", ".", "each", "do", "|", "derived_type", ",", "tag_regexp", "|", "matched_regexp_group", "=", "tag_regexp", ".", "match", "(", "tag", ")", "if", "matched_regexp_group", "resource", ".", "type", "=", "derived_type", "break", "end", "end", "# Determine the monitored resource based on the local_resource_id.", "# Different monitored resource types have unique ids in different format.", "# We will query Metadata Agent for the monitored resource. Return the", "# legacy monitored resource (either the instance resource or the resource", "# inferred from the tag) if failed to get a monitored resource from", "# Metadata Agent with this key.", "#", "# Examples:", "# \"container.<container_id>\" // Docker container.", "# \"k8s_pod.<namespace_name>.<pod_name>\" // GKE pod.", "if", "local_resource_id", "converted_resource", "=", "monitored_resource_from_local_resource_id", "(", "local_resource_id", ")", "resource", "=", "converted_resource", "if", "converted_resource", "end", "# Once the resource type is settled down, determine the labels.", "case", "resource", ".", "type", "# Cloud Functions.", "when", "CLOUDFUNCTIONS_CONSTANTS", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "'region'", "=>", "@gcf_region", ",", "'function_name'", "=>", "decode_cloudfunctions_function_name", "(", "matched_regexp_group", "[", "'encoded_function_name'", "]", ")", ")", "instance_id", "=", "resource", ".", "labels", ".", "delete", "(", "'instance_id'", ")", "common_labels", ".", "merge!", "(", "\"#{GKE_CONSTANTS[:service]}/instance_id\"", "=>", "instance_id", ",", "\"#{COMPUTE_CONSTANTS[:service]}/resource_id\"", "=>", "instance_id", ",", "\"#{GKE_CONSTANTS[:service]}/cluster_name\"", "=>", "resource", ".", "labels", ".", "delete", "(", "'cluster_name'", ")", ",", "\"#{COMPUTE_CONSTANTS[:service]}/zone\"", "=>", "resource", ".", "labels", ".", "delete", "(", "'zone'", ")", ")", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "if", "matched_regexp_group", "# We only expect one occurrence of each key in the match group.", "resource_labels_candidates", "=", "matched_regexp_group", ".", "names", ".", "zip", "(", "matched_regexp_group", ".", "captures", ")", ".", "to_h", "common_labels_candidates", "=", "resource_labels_candidates", ".", "dup", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "resource_labels_candidates", ",", "# The kubernetes_tag_regexp is poorly named. 'namespace_name' is", "# in fact 'namespace_id'. 'pod_name' is in fact 'pod_id'.", "# TODO(qingling128): Figure out how to put this map into", "# constants like GKE_CONSTANTS[:extra_resource_labels].", "'container_name'", "=>", "'container_name'", ",", "'namespace_name'", "=>", "'namespace_id'", ",", "'pod_name'", "=>", "'pod_id'", ")", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels_candidates", ",", "GKE_CONSTANTS", "[", ":extra_common_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "\"#{GKE_CONSTANTS[:service]}/#{l}\"", "]", "}", ".", "to_h", ")", ")", "end", "# Docker container.", "# TODO(qingling128): Remove this logic once the resource is retrieved at a", "# proper time (b/65175256).", "when", "DOCKER_CONSTANTS", "[", ":resource_type", "]", "common_labels", ".", "delete", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", ")", "# TODO(qingling128): Temporary fallback for metadata agent restarts.", "# K8s resources.", "when", "K8S_CONTAINER_CONSTANTS", "[", ":resource_type", "]", ",", "K8S_POD_CONSTANTS", "[", ":resource_type", "]", ",", "K8S_NODE_CONSTANTS", "[", ":resource_type", "]", "common_labels", ".", "delete", "(", "\"#{COMPUTE_CONSTANTS[:service]}/resource_name\"", ")", "end", "# Cloud Dataflow and Cloud ML.", "# These labels can be set via the 'labels' option.", "# Report them as monitored resource labels instead of common labels.", "# e.g. \"dataflow.googleapis.com/job_id\" => \"job_id\"", "[", "DATAFLOW_CONSTANTS", ",", "ML_CONSTANTS", "]", ".", "each", "do", "|", "service_constants", "|", "next", "unless", "resource", ".", "type", "==", "service_constants", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels", ",", "service_constants", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "\"#{service_constants[:service]}/#{l}\"", ",", "l", "]", "}", ".", "to_h", ")", ")", "end", "resource", ".", "freeze", "resource", ".", "labels", ".", "freeze", "common_labels", ".", "freeze", "[", "resource", ",", "common_labels", "]", "end" ]
Determine the group level monitored resource and common labels shared by a collection of entries.
[ "Determine", "the", "group", "level", "monitored", "resource", "and", "common", "labels", "shared", "by", "a", "collection", "of", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1343-L1452
14,745
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.monitored_resource_from_local_resource_id
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( local_resource_id) @log.debug 'Retrieved monitored resource from metadata agent: ' \ "#{resource.inspect}." if resource # TODO(qingling128): Fix this temporary renaming from 'gke_container' # to 'container'. resource.type = 'container' if resource.type == 'gke_container' return resource end end # Fall back to constructing monitored resource locally. # TODO(qingling128): This entire else clause is temporary until we # implement buffering and caching. @log.debug('Failed to retrieve monitored resource from Metadata' \ " Agent with local_resource_id #{local_resource_id}.") construct_k8s_resource_locally(local_resource_id) end
ruby
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( local_resource_id) @log.debug 'Retrieved monitored resource from metadata agent: ' \ "#{resource.inspect}." if resource # TODO(qingling128): Fix this temporary renaming from 'gke_container' # to 'container'. resource.type = 'container' if resource.type == 'gke_container' return resource end end # Fall back to constructing monitored resource locally. # TODO(qingling128): This entire else clause is temporary until we # implement buffering and caching. @log.debug('Failed to retrieve monitored resource from Metadata' \ " Agent with local_resource_id #{local_resource_id}.") construct_k8s_resource_locally(local_resource_id) end
[ "def", "monitored_resource_from_local_resource_id", "(", "local_resource_id", ")", "return", "unless", "local_resource_id", "if", "@enable_metadata_agent", "@log", ".", "debug", "'Calling metadata agent with local_resource_id: '", "\"#{local_resource_id}.\"", "resource", "=", "query_metadata_agent_for_monitored_resource", "(", "local_resource_id", ")", "@log", ".", "debug", "'Retrieved monitored resource from metadata agent: '", "\"#{resource.inspect}.\"", "if", "resource", "# TODO(qingling128): Fix this temporary renaming from 'gke_container'", "# to 'container'.", "resource", ".", "type", "=", "'container'", "if", "resource", ".", "type", "==", "'gke_container'", "return", "resource", "end", "end", "# Fall back to constructing monitored resource locally.", "# TODO(qingling128): This entire else clause is temporary until we", "# implement buffering and caching.", "@log", ".", "debug", "(", "'Failed to retrieve monitored resource from Metadata'", "\" Agent with local_resource_id #{local_resource_id}.\"", ")", "construct_k8s_resource_locally", "(", "local_resource_id", ")", "end" ]
Take a locally unique resource id and convert it to the globally unique monitored resource.
[ "Take", "a", "locally", "unique", "resource", "id", "and", "convert", "it", "to", "the", "globally", "unique", "monitored", "resource", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1456-L1478
14,746
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_entry_level_monitored_resource_and_labels
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] if record.key?('log') @cloudfunctions_log_match = @compiled_cloudfunctions_log_regexp.match(record['log']) common_labels['execution_id'] = @cloudfunctions_log_match['execution_id'] if @cloudfunctions_log_match && @cloudfunctions_log_match['execution_id'] end # GKE container. when GKE_CONSTANTS[:resource_type] # Move the stdout/stderr annotation from the record into a label. common_labels.merge!( delete_and_extract_labels( record, 'stream' => "#{GKE_CONSTANTS[:service]}/stream")) # If the record has been annotated by the kubernetes_metadata_filter # plugin, then use that metadata. Otherwise, rely on commonLabels # populated from the group's tag. if record.key?('kubernetes') resource.labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_resource_labels] .map { |l| [l, l] }.to_h)) common_labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) # Prepend label/ to all user-defined labels' keys. if record['kubernetes'].key?('labels') common_labels.merge!( delete_and_extract_labels( record['kubernetes']['labels'], record['kubernetes']['labels'] .map { |key, _| [key, "label/#{key}"] }.to_h)) end # We've explicitly consumed all the fields we care about -- don't # litter the log entries with the remaining fields that the kubernetes # metadata filter plugin includes (or an empty 'kubernetes' field). record.delete('kubernetes') record.delete('docker') end end # If the name of a field in the record is present in the @label_map # configured by users, report its value as a label and do not send that # field as part of the payload. common_labels.merge!(delete_and_extract_labels(record, @label_map)) # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' or 'label_map' options. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end [resource, common_labels] end
ruby
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions. when CLOUDFUNCTIONS_CONSTANTS[:resource_type] if record.key?('log') @cloudfunctions_log_match = @compiled_cloudfunctions_log_regexp.match(record['log']) common_labels['execution_id'] = @cloudfunctions_log_match['execution_id'] if @cloudfunctions_log_match && @cloudfunctions_log_match['execution_id'] end # GKE container. when GKE_CONSTANTS[:resource_type] # Move the stdout/stderr annotation from the record into a label. common_labels.merge!( delete_and_extract_labels( record, 'stream' => "#{GKE_CONSTANTS[:service]}/stream")) # If the record has been annotated by the kubernetes_metadata_filter # plugin, then use that metadata. Otherwise, rely on commonLabels # populated from the group's tag. if record.key?('kubernetes') resource.labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_resource_labels] .map { |l| [l, l] }.to_h)) common_labels.merge!( delete_and_extract_labels( record['kubernetes'], GKE_CONSTANTS[:extra_common_labels] .map { |l| [l, "#{GKE_CONSTANTS[:service]}/#{l}"] }.to_h)) # Prepend label/ to all user-defined labels' keys. if record['kubernetes'].key?('labels') common_labels.merge!( delete_and_extract_labels( record['kubernetes']['labels'], record['kubernetes']['labels'] .map { |key, _| [key, "label/#{key}"] }.to_h)) end # We've explicitly consumed all the fields we care about -- don't # litter the log entries with the remaining fields that the kubernetes # metadata filter plugin includes (or an empty 'kubernetes' field). record.delete('kubernetes') record.delete('docker') end end # If the name of a field in the record is present in the @label_map # configured by users, report its value as a label and do not send that # field as part of the payload. common_labels.merge!(delete_and_extract_labels(record, @label_map)) # Cloud Dataflow and Cloud ML. # These labels can be set via the 'labels' or 'label_map' options. # Report them as monitored resource labels instead of common labels. # e.g. "dataflow.googleapis.com/job_id" => "job_id" [DATAFLOW_CONSTANTS, ML_CONSTANTS].each do |service_constants| next unless resource.type == service_constants[:resource_type] resource.labels.merge!( delete_and_extract_labels( common_labels, service_constants[:extra_resource_labels] .map { |l| ["#{service_constants[:service]}/#{l}", l] }.to_h)) end [resource, common_labels] end
[ "def", "determine_entry_level_monitored_resource_and_labels", "(", "group_level_resource", ",", "group_level_common_labels", ",", "record", ")", "resource", "=", "group_level_resource", ".", "dup", "resource", ".", "labels", "=", "group_level_resource", ".", "labels", ".", "dup", "common_labels", "=", "group_level_common_labels", ".", "dup", "case", "resource", ".", "type", "# Cloud Functions.", "when", "CLOUDFUNCTIONS_CONSTANTS", "[", ":resource_type", "]", "if", "record", ".", "key?", "(", "'log'", ")", "@cloudfunctions_log_match", "=", "@compiled_cloudfunctions_log_regexp", ".", "match", "(", "record", "[", "'log'", "]", ")", "common_labels", "[", "'execution_id'", "]", "=", "@cloudfunctions_log_match", "[", "'execution_id'", "]", "if", "@cloudfunctions_log_match", "&&", "@cloudfunctions_log_match", "[", "'execution_id'", "]", "end", "# GKE container.", "when", "GKE_CONSTANTS", "[", ":resource_type", "]", "# Move the stdout/stderr annotation from the record into a label.", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", ",", "'stream'", "=>", "\"#{GKE_CONSTANTS[:service]}/stream\"", ")", ")", "# If the record has been annotated by the kubernetes_metadata_filter", "# plugin, then use that metadata. Otherwise, rely on commonLabels", "# populated from the group's tag.", "if", "record", ".", "key?", "(", "'kubernetes'", ")", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", ",", "GKE_CONSTANTS", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "l", "]", "}", ".", "to_h", ")", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", ",", "GKE_CONSTANTS", "[", ":extra_common_labels", "]", ".", "map", "{", "|", "l", "|", "[", "l", ",", "\"#{GKE_CONSTANTS[:service]}/#{l}\"", "]", "}", ".", "to_h", ")", ")", "# Prepend label/ to all user-defined labels' keys.", "if", "record", "[", "'kubernetes'", "]", ".", "key?", "(", "'labels'", ")", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", "[", "'kubernetes'", "]", "[", "'labels'", "]", ",", "record", "[", "'kubernetes'", "]", "[", "'labels'", "]", ".", "map", "{", "|", "key", ",", "_", "|", "[", "key", ",", "\"label/#{key}\"", "]", "}", ".", "to_h", ")", ")", "end", "# We've explicitly consumed all the fields we care about -- don't", "# litter the log entries with the remaining fields that the kubernetes", "# metadata filter plugin includes (or an empty 'kubernetes' field).", "record", ".", "delete", "(", "'kubernetes'", ")", "record", ".", "delete", "(", "'docker'", ")", "end", "end", "# If the name of a field in the record is present in the @label_map", "# configured by users, report its value as a label and do not send that", "# field as part of the payload.", "common_labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "record", ",", "@label_map", ")", ")", "# Cloud Dataflow and Cloud ML.", "# These labels can be set via the 'labels' or 'label_map' options.", "# Report them as monitored resource labels instead of common labels.", "# e.g. \"dataflow.googleapis.com/job_id\" => \"job_id\"", "[", "DATAFLOW_CONSTANTS", ",", "ML_CONSTANTS", "]", ".", "each", "do", "|", "service_constants", "|", "next", "unless", "resource", ".", "type", "==", "service_constants", "[", ":resource_type", "]", "resource", ".", "labels", ".", "merge!", "(", "delete_and_extract_labels", "(", "common_labels", ",", "service_constants", "[", ":extra_resource_labels", "]", ".", "map", "{", "|", "l", "|", "[", "\"#{service_constants[:service]}/#{l}\"", ",", "l", "]", "}", ".", "to_h", ")", ")", "end", "[", "resource", ",", "common_labels", "]", "end" ]
Extract entry level monitored resource and common labels that should be applied to individual entries.
[ "Extract", "entry", "level", "monitored", "resource", "and", "common", "labels", "that", "should", "be", "applied", "to", "individual", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1482-L1552
14,747
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.query_metadata_agent
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid json ' \ "format: '#{response.inspect}'." return nil end @log.debug "Response from Metadata Agent: #{parsed_hash}" return parsed_hash end rescue StandardError => e @log.error "Error calling Metadata Agent at #{url}.", error: e nil end
ruby
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid json ' \ "format: '#{response.inspect}'." return nil end @log.debug "Response from Metadata Agent: #{parsed_hash}" return parsed_hash end rescue StandardError => e @log.error "Error calling Metadata Agent at #{url}.", error: e nil end
[ "def", "query_metadata_agent", "(", "path", ")", "url", "=", "\"#{@metadata_agent_url}/#{path}\"", "@log", ".", "debug", "(", "\"Calling Metadata Agent: #{url}\"", ")", "open", "(", "url", ")", "do", "|", "f", "|", "response", "=", "f", ".", "read", "parsed_hash", "=", "parse_json_or_nil", "(", "response", ")", "if", "parsed_hash", ".", "nil?", "@log", ".", "error", "'Response from Metadata Agent is not in valid json '", "\"format: '#{response.inspect}'.\"", "return", "nil", "end", "@log", ".", "debug", "\"Response from Metadata Agent: #{parsed_hash}\"", "return", "parsed_hash", "end", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "\"Error calling Metadata Agent at #{url}.\"", ",", "error", ":", "e", "nil", "end" ]
Issue a request to the Metadata Agent's local API and parse the response to JSON. Return nil in case of failure.
[ "Issue", "a", "request", "to", "the", "Metadata", "Agent", "s", "local", "API", "and", "parse", "the", "response", "to", "JSON", ".", "Return", "nil", "in", "case", "of", "failure", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1578-L1595
14,748
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.parse_labels
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil end non_string_keys = payload_labels.each_with_object([]) do |(k, v), a| a << k unless k.is_a?(String) && v.is_a?(String) end unless non_string_keys.empty? @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need string values for all " \ "keys; keys #{non_string_keys} don't." return nil end payload_labels rescue StandardError => err @log.error "Failed to extract '#{@labels_key}' from payload.", err return nil end
ruby
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil end non_string_keys = payload_labels.each_with_object([]) do |(k, v), a| a << k unless k.is_a?(String) && v.is_a?(String) end unless non_string_keys.empty? @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need string values for all " \ "keys; keys #{non_string_keys} don't." return nil end payload_labels rescue StandardError => err @log.error "Failed to extract '#{@labels_key}' from payload.", err return nil end
[ "def", "parse_labels", "(", "record", ")", "payload_labels", "=", "record", ".", "delete", "(", "@labels_key", ")", "return", "nil", "unless", "payload_labels", "unless", "payload_labels", ".", "is_a?", "(", "Hash", ")", "@log", ".", "error", "\"Invalid value of '#{@labels_key}' in the payload: \"", "\"#{payload_labels}. Labels need to be a JSON object.\"", "return", "nil", "end", "non_string_keys", "=", "payload_labels", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "(", "k", ",", "v", ")", ",", "a", "|", "a", "<<", "k", "unless", "k", ".", "is_a?", "(", "String", ")", "&&", "v", ".", "is_a?", "(", "String", ")", "end", "unless", "non_string_keys", ".", "empty?", "@log", ".", "error", "\"Invalid value of '#{@labels_key}' in the payload: \"", "\"#{payload_labels}. Labels need string values for all \"", "\"keys; keys #{non_string_keys} don't.\"", "return", "nil", "end", "payload_labels", "rescue", "StandardError", "=>", "err", "@log", ".", "error", "\"Failed to extract '#{@labels_key}' from payload.\"", ",", "err", "return", "nil", "end" ]
Parse labels. Return nil if not set.
[ "Parse", "labels", ".", "Return", "nil", "if", "not", "set", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1797-L1819
14,749
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.sanitize_tag
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
ruby
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
[ "def", "sanitize_tag", "(", "tag", ")", "if", "@require_valid_tags", "&&", "(", "!", "tag", ".", "is_a?", "(", "String", ")", "||", "tag", "==", "''", "||", "convert_to_utf8", "(", "tag", ")", "!=", "tag", ")", "return", "nil", "end", "tag", "=", "convert_to_utf8", "(", "tag", ".", "to_s", ")", "tag", "=", "'_'", "if", "tag", "==", "''", "tag", "end" ]
Given a tag, returns the corresponding valid tag if possible, or nil if the tag should be rejected. If 'require_valid_tags' is false, non-string tags are converted to strings, and invalid characters are sanitized; otherwise such tags are rejected.
[ "Given", "a", "tag", "returns", "the", "corresponding", "valid", "tag", "if", "possible", "or", "nil", "if", "the", "tag", "should", "be", "rejected", ".", "If", "require_valid_tags", "is", "false", "non", "-", "string", "tags", "are", "converted", "to", "strings", "and", "invalid", "characters", "are", "sanitized", ";", "otherwise", "such", "tags", "are", "rejected", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1976-L1984
14,750
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.delete_and_extract_labels
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_labels[new_label] = convert_to_utf8(value.to_s) if value end end
ruby
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_labels[new_label] = convert_to_utf8(value.to_s) if value end end
[ "def", "delete_and_extract_labels", "(", "hash", ",", "label_map", ")", "return", "{", "}", "if", "label_map", ".", "nil?", "||", "!", "label_map", ".", "is_a?", "(", "Hash", ")", "||", "hash", ".", "nil?", "||", "!", "hash", ".", "is_a?", "(", "Hash", ")", "label_map", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "original_label", ",", "new_label", ")", ",", "extracted_labels", "|", "value", "=", "hash", ".", "delete", "(", "original_label", ")", "extracted_labels", "[", "new_label", "]", "=", "convert_to_utf8", "(", "value", ".", "to_s", ")", "if", "value", "end", "end" ]
For every original_label => new_label pair in the label_map, delete the original_label from the hash map if it exists, and extract the value to form a map with the new_label as the key.
[ "For", "every", "original_label", "=", ">", "new_label", "pair", "in", "the", "label_map", "delete", "the", "original_label", "from", "the", "hash", "map", "if", "it", "exists", "and", "extract", "the", "value", "to", "form", "a", "map", "with", "the", "new_label", "as", "the", "key", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1989-L1997
14,751
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.convert_to_utf8
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered encoding issues potentially due to non ' \ 'UTF-8 characters. To allow non-UTF-8 characters and ' \ 'replace them with spaces, please set "coerce_to_utf8" ' \ 'to true.' raise end end end
ruby
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered encoding issues potentially due to non ' \ 'UTF-8 characters. To allow non-UTF-8 characters and ' \ 'replace them with spaces, please set "coerce_to_utf8" ' \ 'to true.' raise end end end
[ "def", "convert_to_utf8", "(", "input", ")", "if", "@coerce_to_utf8", "input", ".", "encode", "(", "'utf-8'", ",", "invalid", ":", ":replace", ",", "undef", ":", ":replace", ",", "replace", ":", "@non_utf8_replacement_string", ")", "else", "begin", "input", ".", "encode", "(", "'utf-8'", ")", "rescue", "EncodingError", "@log", ".", "error", "'Encountered encoding issues potentially due to non '", "'UTF-8 characters. To allow non-UTF-8 characters and '", "'replace them with spaces, please set \"coerce_to_utf8\" '", "'to true.'", "raise", "end", "end", "end" ]
Encode as UTF-8. If 'coerce_to_utf8' is set to true in the config, any non-UTF-8 character would be replaced by the string specified by 'non_utf8_replacement_string'. If 'coerce_to_utf8' is set to false, any non-UTF-8 character would trigger the plugin to error out.
[ "Encode", "as", "UTF", "-", "8", ".", "If", "coerce_to_utf8", "is", "set", "to", "true", "in", "the", "config", "any", "non", "-", "UTF", "-", "8", "character", "would", "be", "replaced", "by", "the", "string", "specified", "by", "non_utf8_replacement_string", ".", "If", "coerce_to_utf8", "is", "set", "to", "false", "any", "non", "-", "UTF", "-", "8", "character", "would", "trigger", "the", "plugin", "to", "error", "out", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2162-L2180
14,752
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.construct_k8s_resource_locally
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_node) \.(?<node_name>[0-9a-z-]+)$/x =~ local_resource_id # Clear name and location if they're explicitly set to empty. @k8s_cluster_name = nil if @k8s_cluster_name == '' @k8s_cluster_location = nil if @k8s_cluster_location == '' begin @k8s_cluster_name ||= fetch_gce_metadata( 'instance/attributes/cluster-name') @k8s_cluster_location ||= fetch_gce_metadata( 'instance/attributes/cluster-location') rescue StandardError => e @log.error 'Failed to retrieve k8s cluster name and location.', \ error: e end case resource_type when K8S_CONTAINER_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'container_name' => container_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_POD_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_NODE_CONSTANTS[:resource_type] labels = { 'node_name' => node_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = COMPUTE_CONSTANTS[:resource_type] end unless @k8s_cluster_name && @k8s_cluster_location @log.error "Failed to construct #{resource_type} resource locally." \ ' Falling back to writing logs against' \ " #{fallback_resource} resource.", error: e return end constructed_resource = Google::Apis::LoggingV2::MonitoredResource.new( type: resource_type, labels: labels) @log.debug("Constructed #{resource_type} resource locally: " \ "#{constructed_resource.inspect}") constructed_resource end
ruby
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_node) \.(?<node_name>[0-9a-z-]+)$/x =~ local_resource_id # Clear name and location if they're explicitly set to empty. @k8s_cluster_name = nil if @k8s_cluster_name == '' @k8s_cluster_location = nil if @k8s_cluster_location == '' begin @k8s_cluster_name ||= fetch_gce_metadata( 'instance/attributes/cluster-name') @k8s_cluster_location ||= fetch_gce_metadata( 'instance/attributes/cluster-location') rescue StandardError => e @log.error 'Failed to retrieve k8s cluster name and location.', \ error: e end case resource_type when K8S_CONTAINER_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'container_name' => container_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_POD_CONSTANTS[:resource_type] labels = { 'namespace_name' => namespace_name, 'pod_name' => pod_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = GKE_CONSTANTS[:resource_type] when K8S_NODE_CONSTANTS[:resource_type] labels = { 'node_name' => node_name, 'cluster_name' => @k8s_cluster_name, 'location' => @k8s_cluster_location } fallback_resource = COMPUTE_CONSTANTS[:resource_type] end unless @k8s_cluster_name && @k8s_cluster_location @log.error "Failed to construct #{resource_type} resource locally." \ ' Falling back to writing logs against' \ " #{fallback_resource} resource.", error: e return end constructed_resource = Google::Apis::LoggingV2::MonitoredResource.new( type: resource_type, labels: labels) @log.debug("Constructed #{resource_type} resource locally: " \ "#{constructed_resource.inspect}") constructed_resource end
[ "def", "construct_k8s_resource_locally", "(", "local_resource_id", ")", "return", "unless", "/", "\\.", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "/x", "=~", "local_resource_id", "# Clear name and location if they're explicitly set to empty.", "@k8s_cluster_name", "=", "nil", "if", "@k8s_cluster_name", "==", "''", "@k8s_cluster_location", "=", "nil", "if", "@k8s_cluster_location", "==", "''", "begin", "@k8s_cluster_name", "||=", "fetch_gce_metadata", "(", "'instance/attributes/cluster-name'", ")", "@k8s_cluster_location", "||=", "fetch_gce_metadata", "(", "'instance/attributes/cluster-location'", ")", "rescue", "StandardError", "=>", "e", "@log", ".", "error", "'Failed to retrieve k8s cluster name and location.'", ",", "error", ":", "e", "end", "case", "resource_type", "when", "K8S_CONTAINER_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'namespace_name'", "=>", "namespace_name", ",", "'pod_name'", "=>", "pod_name", ",", "'container_name'", "=>", "container_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "GKE_CONSTANTS", "[", ":resource_type", "]", "when", "K8S_POD_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'namespace_name'", "=>", "namespace_name", ",", "'pod_name'", "=>", "pod_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "GKE_CONSTANTS", "[", ":resource_type", "]", "when", "K8S_NODE_CONSTANTS", "[", ":resource_type", "]", "labels", "=", "{", "'node_name'", "=>", "node_name", ",", "'cluster_name'", "=>", "@k8s_cluster_name", ",", "'location'", "=>", "@k8s_cluster_location", "}", "fallback_resource", "=", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "end", "unless", "@k8s_cluster_name", "&&", "@k8s_cluster_location", "@log", ".", "error", "\"Failed to construct #{resource_type} resource locally.\"", "' Falling back to writing logs against'", "\" #{fallback_resource} resource.\"", ",", "error", ":", "e", "return", "end", "constructed_resource", "=", "Google", "::", "Apis", "::", "LoggingV2", "::", "MonitoredResource", ".", "new", "(", "type", ":", "resource_type", ",", "labels", ":", "labels", ")", "@log", ".", "debug", "(", "\"Constructed #{resource_type} resource locally: \"", "\"#{constructed_resource.inspect}\"", ")", "constructed_resource", "end" ]
Construct monitored resource locally for k8s resources.
[ "Construct", "monitored", "resource", "locally", "for", "k8s", "resources", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2349-L2415
14,753
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/monitoring.rb
Monitoring.PrometheusMonitoringRegistry.counter
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
ruby
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
[ "def", "counter", "(", "name", ",", "desc", ")", "return", "@registry", ".", "counter", "(", "name", ",", "desc", ")", "rescue", "Prometheus", "::", "Client", "::", "Registry", "::", "AlreadyRegisteredError", "return", "@registry", ".", "get", "(", "name", ")", "end" ]
Exception-driven behavior to avoid synchronization errors.
[ "Exception", "-", "driven", "behavior", "to", "avoid", "synchronization", "errors", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/monitoring.rb#L36-L40
14,754
rossta/serviceworker-rails
lib/serviceworker/middleware.rb
ServiceWorker.Middleware.call
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
ruby
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
[ "def", "call", "(", "env", ")", "case", "env", "[", "REQUEST_METHOD", "]", "when", "GET", ",", "HEAD", "route_match", "=", "@router", ".", "match_route", "(", "env", ")", "return", "respond_to_match", "(", "route_match", ",", "env", ")", "if", "route_match", "end", "@app", ".", "call", "(", "env", ")", "end" ]
Initialize the Rack middleware for responding to serviceworker asset requests @app [#call] middleware stack @opts [Hash] options to inject @param opts [#match_route] :routes matches routes on PATH_INFO @param opts [Hash] :headers default headers to use for matched routes @param opts [#call] :handler resolves response from matched asset name @param opts [#info] :logger logs requests
[ "Initialize", "the", "Rack", "middleware", "for", "responding", "to", "serviceworker", "asset", "requests" ]
757db5354c9e47a144397c4655f3d1cab6046bc0
https://github.com/rossta/serviceworker-rails/blob/757db5354c9e47a144397c4655f3d1cab6046bc0/lib/serviceworker/middleware.rb#L28-L36
14,755
glebm/i18n-tasks
lib/i18n/tasks/used_keys.rb
I18n::Tasks.UsedKeys.used_tree
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } resolved_refs.leaves { |node| node.data[:ref_type] = :reference_usage_resolved } used_refs.leaves { |node| node.data[:ref_type] = :reference_usage_key } src_tree.tap do |result| tree = result['used'].children tree.subtract_by_key!(raw_refs) tree.merge!(raw_refs) if include_raw_references tree.merge!(used_refs).merge!(resolved_refs) end end
ruby
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } resolved_refs.leaves { |node| node.data[:ref_type] = :reference_usage_resolved } used_refs.leaves { |node| node.data[:ref_type] = :reference_usage_key } src_tree.tap do |result| tree = result['used'].children tree.subtract_by_key!(raw_refs) tree.merge!(raw_refs) if include_raw_references tree.merge!(used_refs).merge!(resolved_refs) end end
[ "def", "used_tree", "(", "key_filter", ":", "nil", ",", "strict", ":", "nil", ",", "include_raw_references", ":", "false", ")", "src_tree", "=", "used_in_source_tree", "(", "key_filter", ":", "key_filter", ",", "strict", ":", "strict", ")", "raw_refs", ",", "resolved_refs", ",", "used_refs", "=", "process_references", "(", "src_tree", "[", "'used'", "]", ".", "children", ")", "raw_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage", "}", "resolved_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage_resolved", "}", "used_refs", ".", "leaves", "{", "|", "node", "|", "node", ".", "data", "[", ":ref_type", "]", "=", ":reference_usage_key", "}", "src_tree", ".", "tap", "do", "|", "result", "|", "tree", "=", "result", "[", "'used'", "]", ".", "children", "tree", ".", "subtract_by_key!", "(", "raw_refs", ")", "tree", ".", "merge!", "(", "raw_refs", ")", "if", "include_raw_references", "tree", ".", "merge!", "(", "used_refs", ")", ".", "merge!", "(", "resolved_refs", ")", "end", "end" ]
Find all keys in the source and return a forest with the keys in absolute form and their occurrences. @param key_filter [String] only return keys matching this pattern. @param strict [Boolean] if true, dynamic keys are excluded (e.g. `t("category.#{ category.key }")`) @param include_raw_references [Boolean] if true, includes reference usages as they appear in the source @return [Data::Tree::Siblings]
[ "Find", "all", "keys", "in", "the", "source", "and", "return", "a", "forest", "with", "the", "keys", "in", "absolute", "form", "and", "their", "occurrences", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/used_keys.rb#L36-L48
14,756
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_key_literals.rb
I18n::Tasks::Scanners.RubyKeyLiterals.strip_literal
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
ruby
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
[ "def", "strip_literal", "(", "literal", ")", "literal", "=", "literal", "[", "1", "..", "-", "1", "]", "if", "literal", "[", "0", "]", "==", "':'", "literal", "=", "literal", "[", "1", "..", "-", "2", "]", "if", "literal", "[", "0", "]", "==", "\"'\"", "||", "literal", "[", "0", "]", "==", "'\"'", "literal", "end" ]
remove the leading colon and unwrap quotes from the key match @param literal [String] e.g: "key", 'key', or :key. @return [String] key
[ "remove", "the", "leading", "colon", "and", "unwrap", "quotes", "from", "the", "key", "match" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_key_literals.rb#L17-L21
14,757
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.load_rails_i18n_pluralization!
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
ruby
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
[ "def", "load_rails_i18n_pluralization!", "(", "locale", ")", "path", "=", "File", ".", "join", "(", "Gem", "::", "Specification", ".", "find_by_name", "(", "'rails-i18n'", ")", ".", "gem_dir", ",", "'rails'", ",", "'pluralization'", ",", "\"#{locale}.rb\"", ")", "eval", "(", "File", ".", "read", "(", "path", ")", ",", "binding", ",", "path", ")", "# rubocop:disable Security/Eval", "end" ]
Loads rails-i18n pluralization config for the given locale.
[ "Loads", "rails", "-", "i18n", "pluralization", "config", "for", "the", "given", "locale", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L91-L94
14,758
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_diff_tree
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: locale, missing_diff_locale: node.data[:locale] } if node.data.key?(:path) data[:path] = LocalePathname.replace_locale(node.data[:path], node.data[:locale], locale) end node.data.update data end end
ruby
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: locale, missing_diff_locale: node.data[:locale] } if node.data.key?(:path) data[:path] = LocalePathname.replace_locale(node.data[:path], node.data[:locale], locale) end node.data.update data end end
[ "def", "missing_diff_tree", "(", "locale", ",", "compared_to", "=", "base_locale", ")", "data", "[", "compared_to", "]", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "locale", ",", "depluralize_key", "(", "key", ",", "compared_to", ")", "end", ".", "set_root_key!", "(", "locale", ",", "type", ":", ":missing_diff", ")", ".", "keys", "do", "|", "_key", ",", "node", "|", "# change path and locale to base", "data", "=", "{", "locale", ":", "locale", ",", "missing_diff_locale", ":", "node", ".", "data", "[", ":locale", "]", "}", "if", "node", ".", "data", ".", "key?", "(", ":path", ")", "data", "[", ":path", "]", "=", "LocalePathname", ".", "replace_locale", "(", "node", ".", "data", "[", ":path", "]", ",", "node", ".", "data", "[", ":locale", "]", ",", "locale", ")", "end", "node", ".", "data", ".", "update", "data", "end", "end" ]
keys present in compared_to, but not in locale
[ "keys", "present", "in", "compared_to", "but", "not", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L97-L108
14,759
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_used_tree
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
ruby
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
[ "def", "missing_used_tree", "(", "locale", ")", "used_tree", "(", "strict", ":", "true", ")", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "(", "locale", ",", "key", ")", "end", ".", "set_root_key!", "(", "locale", ",", "type", ":", ":missing_used", ")", "end" ]
keys used in the code missing translations in locale
[ "keys", "used", "in", "the", "code", "missing", "translations", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L111-L115
14,760
glebm/i18n-tasks
lib/i18n/tasks/scanners/pattern_scanner.rb
I18n::Tasks::Scanners.PatternScanner.scan_file
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = match_to_key(match, path, location) next unless key key += ':' if key.end_with?('.') next unless valid_key?(key) keys << [key, location] end keys rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
ruby
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = match_to_key(match, path, location) next unless key key += ':' if key.end_with?('.') next unless valid_key?(key) keys << [key, location] end keys rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
[ "def", "scan_file", "(", "path", ")", "keys", "=", "[", "]", "text", "=", "read_file", "(", "path", ")", "text", ".", "scan", "(", "@pattern", ")", "do", "|", "match", "|", "src_pos", "=", "Regexp", ".", "last_match", ".", "offset", "(", "0", ")", ".", "first", "location", "=", "occurrence_from_position", "(", "path", ",", "text", ",", "src_pos", ",", "raw_key", ":", "strip_literal", "(", "match", "[", "0", "]", ")", ")", "next", "if", "exclude_line?", "(", "location", ".", "line", ",", "path", ")", "key", "=", "match_to_key", "(", "match", ",", "path", ",", "location", ")", "next", "unless", "key", "key", "+=", "':'", "if", "key", ".", "end_with?", "(", "'.'", ")", "next", "unless", "valid_key?", "(", "key", ")", "keys", "<<", "[", "key", ",", "location", "]", "end", "keys", "rescue", "Exception", "=>", "e", "# rubocop:disable Lint/RescueException", "raise", "::", "I18n", "::", "Tasks", "::", "CommandError", ".", "new", "(", "e", ",", "\"Error scanning #{path}: #{e.message}\"", ")", "end" ]
Extract i18n keys from file based on the pattern which must capture the key literal. @return [Array<[key, Results::Occurrence]>] each occurrence found in the file
[ "Extract", "i18n", "keys", "from", "file", "based", "on", "the", "pattern", "which", "must", "capture", "the", "key", "literal", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/pattern_scanner.rb#L39-L55
14,761
glebm/i18n-tasks
lib/i18n/tasks/translators/google_translator.rb
I18n::Tasks::Translators.GoogleTranslator.to_google_translate_compatible_locale
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
ruby
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
[ "def", "to_google_translate_compatible_locale", "(", "locale", ")", "return", "locale", "unless", "locale", ".", "include?", "(", "'-'", ")", "&&", "!", "SUPPORTED_LOCALES_WITH_REGION", ".", "include?", "(", "locale", ")", "locale", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "end" ]
Convert 'es-ES' to 'es'
[ "Convert", "es", "-", "ES", "to", "es" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/translators/google_translator.rb#L47-L50
14,762
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.scan_file
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text =~ MAGIC_COMMENT_PREFIX } comment_to_node = Parser::Source::Comment.associate_locations(ast, magic_comments).tap do |h| # transform_values is only available in ActiveSupport 4.2+ h.each { |k, v| h[k] = v.first } end.invert results + (magic_comments.flat_map do |comment| @parser.reset associated_node = comment_to_node[comment] @call_finder.collect_calls( @parser.parse(make_buffer(path, comment.text.sub(MAGIC_COMMENT_PREFIX, '').split(/\s+(?=t)/).join('; '))) ) do |send_node, _method_name| # method_name is not available at this stage send_node_to_key_occurrence(send_node, nil, location: associated_node || comment.location) end end) rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
ruby
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text =~ MAGIC_COMMENT_PREFIX } comment_to_node = Parser::Source::Comment.associate_locations(ast, magic_comments).tap do |h| # transform_values is only available in ActiveSupport 4.2+ h.each { |k, v| h[k] = v.first } end.invert results + (magic_comments.flat_map do |comment| @parser.reset associated_node = comment_to_node[comment] @call_finder.collect_calls( @parser.parse(make_buffer(path, comment.text.sub(MAGIC_COMMENT_PREFIX, '').split(/\s+(?=t)/).join('; '))) ) do |send_node, _method_name| # method_name is not available at this stage send_node_to_key_occurrence(send_node, nil, location: associated_node || comment.location) end end) rescue Exception => e # rubocop:disable Lint/RescueException raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}") end
[ "def", "scan_file", "(", "path", ")", "@parser", ".", "reset", "ast", ",", "comments", "=", "@parser", ".", "parse_with_comments", "(", "make_buffer", "(", "path", ")", ")", "results", "=", "@call_finder", ".", "collect_calls", "ast", "do", "|", "send_node", ",", "method_name", "|", "send_node_to_key_occurrence", "(", "send_node", ",", "method_name", ")", "end", "magic_comments", "=", "comments", ".", "select", "{", "|", "comment", "|", "comment", ".", "text", "=~", "MAGIC_COMMENT_PREFIX", "}", "comment_to_node", "=", "Parser", "::", "Source", "::", "Comment", ".", "associate_locations", "(", "ast", ",", "magic_comments", ")", ".", "tap", "do", "|", "h", "|", "# transform_values is only available in ActiveSupport 4.2+", "h", ".", "each", "{", "|", "k", ",", "v", "|", "h", "[", "k", "]", "=", "v", ".", "first", "}", "end", ".", "invert", "results", "+", "(", "magic_comments", ".", "flat_map", "do", "|", "comment", "|", "@parser", ".", "reset", "associated_node", "=", "comment_to_node", "[", "comment", "]", "@call_finder", ".", "collect_calls", "(", "@parser", ".", "parse", "(", "make_buffer", "(", "path", ",", "comment", ".", "text", ".", "sub", "(", "MAGIC_COMMENT_PREFIX", ",", "''", ")", ".", "split", "(", "/", "\\s", "/", ")", ".", "join", "(", "'; '", ")", ")", ")", ")", "do", "|", "send_node", ",", "_method_name", "|", "# method_name is not available at this stage", "send_node_to_key_occurrence", "(", "send_node", ",", "nil", ",", "location", ":", "associated_node", "||", "comment", ".", "location", ")", "end", "end", ")", "rescue", "Exception", "=>", "e", "# rubocop:disable Lint/RescueException", "raise", "::", "I18n", "::", "Tasks", "::", "CommandError", ".", "new", "(", "e", ",", "\"Error scanning #{path}: #{e.message}\"", ")", "end" ]
Extract all occurrences of translate calls from the file at the given path. @return [Array<[key, Results::KeyOccurrence]>] each occurrence found in the file
[ "Extract", "all", "occurrences", "of", "translate", "calls", "from", "the", "file", "at", "the", "given", "path", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L34-L59
14,763
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_hash_pair
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
ruby
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
[ "def", "extract_hash_pair", "(", "node", ",", "key", ")", "node", ".", "children", ".", "detect", "do", "|", "child", "|", "next", "unless", "child", ".", "type", "==", ":pair", "key_node", "=", "child", ".", "children", "[", "0", "]", "%i[", "sym", "str", "]", ".", "include?", "(", "key_node", ".", "type", ")", "&&", "key_node", ".", "children", "[", "0", "]", ".", "to_s", "==", "key", "end", "end" ]
Extract a hash pair with a given literal key. @param node [AST::Node] a node of type `:hash`. @param key [String] node key as a string (indifferent symbol-string matching). @return [AST::Node, nil] a node of type `:pair` or nil.
[ "Extract", "a", "hash", "pair", "with", "a", "given", "literal", "key", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L95-L101
14,764
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_array_as_string
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynamic argument in strict mode return nil if config[:strict] if %i[dsym dstr].include?(child.type) || (child.type == :array && array_flatten) extract_string(child, array_join_with: array_join_with) else "\#{#{child.loc.expression.source}}" end end end if array_reject_blank children_strings.reject! do |x| # empty strings and nils in the scope argument are ignored by i18n x == '' end end children_strings.join(array_join_with) end
ruby
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynamic argument in strict mode return nil if config[:strict] if %i[dsym dstr].include?(child.type) || (child.type == :array && array_flatten) extract_string(child, array_join_with: array_join_with) else "\#{#{child.loc.expression.source}}" end end end if array_reject_blank children_strings.reject! do |x| # empty strings and nils in the scope argument are ignored by i18n x == '' end end children_strings.join(array_join_with) end
[ "def", "extract_array_as_string", "(", "node", ",", "array_join_with", ":", ",", "array_flatten", ":", "false", ",", "array_reject_blank", ":", "false", ")", "children_strings", "=", "node", ".", "children", ".", "map", "do", "|", "child", "|", "if", "%i[", "sym", "str", "int", "true", "false", "]", ".", "include?", "(", "child", ".", "type", ")", "# rubocop:disable Lint/BooleanSymbol", "extract_string", "child", "else", "# ignore dynamic argument in strict mode", "return", "nil", "if", "config", "[", ":strict", "]", "if", "%i[", "dsym", "dstr", "]", ".", "include?", "(", "child", ".", "type", ")", "||", "(", "child", ".", "type", "==", ":array", "&&", "array_flatten", ")", "extract_string", "(", "child", ",", "array_join_with", ":", "array_join_with", ")", "else", "\"\\#{#{child.loc.expression.source}}\"", "end", "end", "end", "if", "array_reject_blank", "children_strings", ".", "reject!", "do", "|", "x", "|", "# empty strings and nils in the scope argument are ignored by i18n", "x", "==", "''", "end", "end", "children_strings", ".", "join", "(", "array_join_with", ")", "end" ]
Extract an array as a single string. @param array_join_with [String] joiner of the array elements. @param array_flatten [Boolean] if true, nested arrays are flattened, otherwise their source is copied and surrounded by #{}. @param array_reject_blank [Boolean] if true, empty strings and `nil`s are skipped. @return [String, nil] `nil` is returned only when a dynamic value is encountered in strict mode.
[ "Extract", "an", "array", "as", "a", "single", "string", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L150-L171
14,765
glebm/i18n-tasks
lib/i18n/tasks/data/tree/siblings.rb
I18n::Tasks::Data::Tree.Siblings.add_ancestors_that_only_contain_nodes!
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
ruby
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
[ "def", "add_ancestors_that_only_contain_nodes!", "(", "nodes", ")", "levels", ".", "reverse_each", "do", "|", "level_nodes", "|", "level_nodes", ".", "each", "{", "|", "node", "|", "nodes", "<<", "node", "if", "node", ".", "children?", "&&", "node", ".", "children", ".", "all?", "{", "|", "c", "|", "nodes", ".", "include?", "(", "c", ")", "}", "}", "end", "end" ]
Adds all the ancestors that only contain the given nodes as descendants to the given nodes. @param nodes [Set] Modified in-place.
[ "Adds", "all", "the", "ancestors", "that", "only", "contain", "the", "given", "nodes", "as", "descendants", "to", "the", "given", "nodes", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data/tree/siblings.rb#L226-L230
14,766
glebm/i18n-tasks
lib/i18n/tasks/reports/base.rb
I18n::Tasks::Reports.Base.sort_by_attr!
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
ruby
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
[ "def", "sort_by_attr!", "(", "objects", ",", "order", "=", "{", "locale", ":", ":asc", ",", "key", ":", ":asc", "}", ")", "order_keys", "=", "order", ".", "keys", "objects", ".", "sort!", "do", "|", "a", ",", "b", "|", "by", "=", "order_keys", ".", "detect", "{", "|", "k", "|", "a", "[", "k", "]", "!=", "b", "[", "k", "]", "}", "order", "[", "by", "]", "==", ":desc", "?", "b", "[", "by", "]", "<=>", "a", "[", "by", "]", ":", "a", "[", "by", "]", "<=>", "b", "[", "by", "]", "end", "objects", "end" ]
Sort keys by their attributes in order @param [Hash] order e.g. {locale: :asc, type: :desc, key: :asc}
[ "Sort", "keys", "by", "their", "attributes", "in", "order" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/reports/base.rb#L44-L51
14,767
glebm/i18n-tasks
lib/i18n/tasks/data.rb
I18n::Tasks.Data.data
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapter_class = adapter_class.to_s adapter_class = 'I18n::Tasks::Data::FileSystem' if adapter_class == 'file_system' data_config.except!(:adapter, :class) ActiveSupport::Inflector.constantize(adapter_class).new data_config end end
ruby
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapter_class = adapter_class.to_s adapter_class = 'I18n::Tasks::Data::FileSystem' if adapter_class == 'file_system' data_config.except!(:adapter, :class) ActiveSupport::Inflector.constantize(adapter_class).new data_config end end
[ "def", "data", "@data", "||=", "begin", "data_config", "=", "(", "config", "[", ":data", "]", "||", "{", "}", ")", ".", "deep_symbolize_keys", "data_config", "[", ":base_locale", "]", "=", "base_locale", "data_config", "[", ":locales", "]", "=", "config", "[", ":locales", "]", "adapter_class", "=", "data_config", "[", ":adapter", "]", ".", "presence", "||", "data_config", "[", ":class", "]", ".", "presence", "||", "DATA_DEFAULTS", "[", ":adapter", "]", "adapter_class", "=", "adapter_class", ".", "to_s", "adapter_class", "=", "'I18n::Tasks::Data::FileSystem'", "if", "adapter_class", "==", "'file_system'", "data_config", ".", "except!", "(", ":adapter", ",", ":class", ")", "ActiveSupport", "::", "Inflector", ".", "constantize", "(", "adapter_class", ")", ".", "new", "data_config", "end", "end" ]
I18n data provider @see I18n::Tasks::Data::FileSystem
[ "I18n", "data", "provider" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data.rb#L13-L24
14,768
glebm/i18n-tasks
lib/i18n/tasks/references.rb
I18n::Tasks.References.merge_reference_trees
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end end forest.merge!( root.children, on_leaves_merge: lambda do |node, other| if node.value != other.value log_warn( 'Conflicting references: '\ "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\ " but ⮕ #{other.value} in #{other.data[:locale]}" ) end end ) end end
ruby
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end end forest.merge!( root.children, on_leaves_merge: lambda do |node, other| if node.value != other.value log_warn( 'Conflicting references: '\ "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\ " but ⮕ #{other.value} in #{other.data[:locale]}" ) end end ) end end
[ "def", "merge_reference_trees", "(", "roots", ")", "roots", ".", "inject", "(", "empty_forest", ")", "do", "|", "forest", ",", "root", "|", "root", ".", "keys", "do", "|", "full_key", ",", "node", "|", "if", "full_key", "==", "node", ".", "value", ".", "to_s", "log_warn", "(", "\"Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}\"", ")", "end", "end", "forest", ".", "merge!", "(", "root", ".", "children", ",", "on_leaves_merge", ":", "lambda", "do", "|", "node", ",", "other", "|", "if", "node", ".", "value", "!=", "other", ".", "value", "log_warn", "(", "'Conflicting references: '", "\"#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},\"\\", "\" but ⮕ #{other.value} in #{other.data[:locale]}\"", ")", "end", "end", ")", "end", "end" ]
Given a forest of references, merge trees into one tree, ensuring there are no conflicting references. @param roots [I18n::Tasks::Data::Tree::Siblings] @return [I18n::Tasks::Data::Tree::Siblings]
[ "Given", "a", "forest", "of", "references", "merge", "trees", "into", "one", "tree", "ensuring", "there", "are", "no", "conflicting", "references", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/references.rb#L77-L99
14,769
glebm/i18n-tasks
lib/i18n/tasks/scanners/files/file_reader.rb
I18n::Tasks::Scanners::Files.FileReader.read_file
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
ruby
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
[ "def", "read_file", "(", "path", ")", "result", "=", "nil", "File", ".", "open", "(", "path", ",", "'rb'", ",", "encoding", ":", "'UTF-8'", ")", "{", "|", "f", "|", "result", "=", "f", ".", "read", "}", "result", "end" ]
Return the contents of the file at the given path. The file is read in the 'rb' mode and UTF-8 encoding. @param path [String] Path to the file, absolute or relative to the working directory. @return [String] file contents
[ "Return", "the", "contents", "of", "the", "file", "at", "the", "given", "path", ".", "The", "file", "is", "read", "in", "the", "rb", "mode", "and", "UTF", "-", "8", "encoding", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/files/file_reader.rb#L13-L17
14,770
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.pos
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' end end positions.flatten! positions.size == 1 ? positions.first : positions.sort end
ruby
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' end end positions.flatten! positions.size == 1 ? positions.first : positions.sort end
[ "def", "pos", "*", "indexes", "positions", "=", "indexes", ".", "map", "do", "|", "index", "|", "if", "include?", "index", "@cat_hash", "[", "index", "]", "elsif", "index", ".", "is_a?", "(", "Numeric", ")", "&&", "index", "<", "@array", ".", "size", "index", "else", "raise", "IndexError", ",", "\"#{index.inspect} is neither a valid category\"", "' nor a valid position'", "end", "end", "positions", ".", "flatten!", "positions", ".", "size", "==", "1", "?", "positions", ".", "first", ":", "positions", ".", "sort", "end" ]
Returns positions given categories or positions @note If the argument does not a valid category it treats it as position value and return it as it is. @param indexes [Array<object>] categories or positions @example x = Daru::CategoricalIndex.new [:a, 1, :a, 1, :c] x.pos :a, 1 # => [0, 1, 2, 3]
[ "Returns", "positions", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L53-L67
14,771
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.subset
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
ruby
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
[ "def", "subset", "*", "indexes", "positions", "=", "pos", "(", "indexes", ")", "new_index", "=", "positions", ".", "map", "{", "|", "pos", "|", "index_from_pos", "pos", "}", "Daru", "::", "CategoricalIndex", ".", "new", "new_index", ".", "flatten", "end" ]
Return subset given categories or positions @param indexes [Array<object>] categories or positions @return [Daru::CategoricalIndex] subset of the self containing the mentioned categories or positions @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.subset :a, :b # => #<Daru::CategoricalIndex(4): {a, b, a, b}>
[ "Return", "subset", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L155-L160
14,772
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.at
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
ruby
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
[ "def", "at", "*", "positions", "positions", "=", "preprocess_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "index_from_pos", "(", "positions", ")", "else", "Daru", "::", "CategoricalIndex", ".", "new", "positions", ".", "map", "(", "method", "(", ":index_from_pos", ")", ")", "end", "end" ]
Takes positional values and returns subset of the self capturing the categories at mentioned positions @param positions [Array<Integer>] positional values @return [object] index object @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.at 0, 1 # => #<Daru::CategoricalIndex(2): {a, b}>
[ "Takes", "positional", "values", "and", "returns", "subset", "of", "the", "self", "capturing", "the", "categories", "at", "mentioned", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L170-L178
14,773
SciRuby/daru
lib/daru/index/multi_index.rb
Daru.MultiIndex.validate_name
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say level 'i') then put empty string on index 'i' of the 'name' Array." raise SizeError, error_msg if names.size > levels.size raise SizeError, [error_msg, suggestion_msg].join("\n") if names.size < levels.size end
ruby
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say level 'i') then put empty string on index 'i' of the 'name' Array." raise SizeError, error_msg if names.size > levels.size raise SizeError, [error_msg, suggestion_msg].join("\n") if names.size < levels.size end
[ "def", "validate_name", "names", ",", "levels", "error_msg", "=", "\"'names' and 'levels' should be of same size. Size of the \"", "\"'name' array is #{names.size} and size of the MultiIndex 'levels' and \"", "\"'labels' is #{labels.size}.\"", "suggestion_msg", "=", "\"If you don\\'t want to set name for particular level \"", "\"(say level 'i') then put empty string on index 'i' of the 'name' Array.\"", "raise", "SizeError", ",", "error_msg", "if", "names", ".", "size", ">", "levels", ".", "size", "raise", "SizeError", ",", "[", "error_msg", ",", "suggestion_msg", "]", ".", "join", "(", "\"\\n\"", ")", "if", "names", ".", "size", "<", "levels", ".", "size", "end" ]
Array `name` must have same length as levels and labels.
[ "Array", "name", "must", "have", "same", "length", "as", "levels", "and", "labels", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/multi_index.rb#L266-L275
14,774
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.[]
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[loc] }, name: @name, index: @index.subset(*input_indexes), dtype: @dtype ) end
ruby
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[loc] }, name: @name, index: @index.subset(*input_indexes), dtype: @dtype ) end
[ "def", "[]", "(", "*", "input_indexes", ")", "# Get array of positions indexes", "positions", "=", "@index", ".", "pos", "(", "input_indexes", ")", "# If one object is asked return it", "return", "@data", "[", "positions", "]", "if", "positions", ".", "is_a?", "Numeric", "# Form a new Vector using positional indexes", "Daru", "::", "Vector", ".", "new", "(", "positions", ".", "map", "{", "|", "loc", "|", "@data", "[", "loc", "]", "}", ",", "name", ":", "@name", ",", "index", ":", "@index", ".", "subset", "(", "input_indexes", ")", ",", "dtype", ":", "@dtype", ")", "end" ]
Get one or more elements with specified index or a range. == Usage # For vectors employing single layer Index v[:one, :two] # => Daru::Vector with indexes :one and :two v[:one] # => Single element v[:one..:three] # => Daru::Vector with indexes :one, :two and :three # For vectors employing hierarchial multi index
[ "Get", "one", "or", "more", "elements", "with", "specified", "index", "or", "a", "range", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L238-L251
14,775
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.at
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new values, index: @index.at(*original_positions), dtype: dtype end end
ruby
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new values, index: @index.at(*original_positions), dtype: dtype end end
[ "def", "at", "*", "positions", "# to be used to form index", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "@data", "[", "positions", "]", "else", "values", "=", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", "}", "Daru", "::", "Vector", ".", "new", "values", ",", "index", ":", "@index", ".", "at", "(", "original_positions", ")", ",", "dtype", ":", "dtype", "end", "end" ]
Returns vector of values given positional values @param positions [Array<object>] positional values @return [object] vector @example dv = Daru::Vector.new 'a'..'e' dv.at 0, 1, 2 # => #<Daru::Vector(3)> # 0 a # 1 b # 2 c
[ "Returns", "vector", "of", "values", "given", "positional", "values" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L263-L275
14,776
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.set_at
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
ruby
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
[ "def", "set_at", "positions", ",", "val", "validate_positions", "(", "positions", ")", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", "=", "val", "}", "update_position_cache", "end" ]
Change value at given positions @param positions [Array<object>] positional values @param [object] val value to assign @example dv = Daru::Vector.new 'a'..'e' dv.set_at [0, 1], 'x' dv # => #<Daru::Vector(5)> # 0 x # 1 x # 2 c # 3 d # 4 e
[ "Change", "value", "at", "given", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L290-L294
14,777
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.concat
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
ruby
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
[ "def", "concat", "element", ",", "index", "raise", "IndexError", ",", "'Expected new unique index'", "if", "@index", ".", "include?", "index", "@index", "|=", "[", "index", "]", "@data", "[", "@index", "[", "index", "]", "]", "=", "element", "update_position_cache", "end" ]
Append an element to the vector by specifying the element and index
[ "Append", "an", "element", "to", "the", "vector", "by", "specifying", "the", "element", "and", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L509-L516
14,778
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cast
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
ruby
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
[ "def", "cast", "opts", "=", "{", "}", "dt", "=", "opts", "[", ":dtype", "]", "raise", "ArgumentError", ",", "\"Unsupported dtype #{opts[:dtype]}\"", "unless", "%i[", "array", "nmatrix", "gsl", "]", ".", "include?", "(", "dt", ")", "@data", "=", "cast_vector_to", "dt", "unless", "@dtype", "==", "dt", "end" ]
Cast a vector to a new data type. == Options * +:dtype+ - :array for Ruby Array. :nmatrix for NMatrix.
[ "Cast", "a", "vector", "to", "a", "new", "data", "type", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L525-L530
14,779
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_at
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
ruby
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
[ "def", "delete_at", "index", "@data", ".", "delete_at", "@index", "[", "index", "]", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "@index", ".", "to_a", "-", "[", "index", "]", ")", "update_position_cache", "end" ]
Delete element by index
[ "Delete", "element", "by", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L538-L543
14,780
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.index_of
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
ruby
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
[ "def", "index_of", "element", "case", "dtype", "when", ":array", "then", "@index", ".", "key", "(", "@data", ".", "index", "{", "|", "x", "|", "x", ".", "eql?", "element", "}", ")", "else", "@index", ".", "key", "@data", ".", "index", "(", "element", ")", "end", "end" ]
Get index of element
[ "Get", "index", "of", "element" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L578-L583
14,781
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.uniq
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
ruby
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
[ "def", "uniq", "uniq_vector", "=", "@data", ".", "uniq", "new_index", "=", "uniq_vector", ".", "map", "{", "|", "element", "|", "index_of", "(", "element", ")", "}", "Daru", "::", "Vector", ".", "new", "uniq_vector", ",", "name", ":", "@name", ",", "index", ":", "new_index", ",", "dtype", ":", "@dtype", "end" ]
Keep only unique elements of the vector alongwith their indexes.
[ "Keep", "only", "unique", "elements", "of", "the", "vector", "alongwith", "their", "indexes", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L586-L591
14,782
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.sort_by_index
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
ruby
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
[ "def", "sort_by_index", "opts", "=", "{", "}", "opts", "=", "{", "ascending", ":", "true", "}", ".", "merge", "(", "opts", ")", "_", ",", "new_order", "=", "resort_index", "(", "@index", ".", "each_with_index", ",", "opts", ")", ".", "transpose", "reorder", "new_order", "end" ]
Sorts the vector according to it's`Index` values. Defaults to ascending order sorting. @param [Hash] opts the options for sort_by_index method. @option opts [Boolean] :ascending false, will sort `index` in descending order. @return [Vector] new sorted `Vector` according to the index values. @example dv = Daru::Vector.new [11, 13, 12], index: [23, 21, 22] # Say you want to sort index in ascending order dv.sort_by_index(ascending: true) #=> Daru::Vector.new [13, 12, 11], index: [21, 22, 23] # Say you want to sort index in descending order dv.sort_by_index(ascending: false) #=> Daru::Vector.new [11, 12, 13], index: [23, 22, 21]
[ "Sorts", "the", "vector", "according", "to", "it", "s", "Index", "values", ".", "Defaults", "to", "ascending", "order", "sorting", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L646-L651
14,783
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.recode!
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
ruby
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
[ "def", "recode!", "dt", "=", "nil", ",", "&", "block", "return", "to_enum", "(", ":recode!", ")", "unless", "block_given?", "@data", ".", "map!", "(", "block", ")", ".", "data", "@data", "=", "cast_vector_to", "(", "dt", "||", "@dtype", ")", "self", "end" ]
Destructive version of recode!
[ "Destructive", "version", "of", "recode!" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L682-L688
14,784
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_if
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
ruby
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
[ "def", "delete_if", "return", "to_enum", "(", ":delete_if", ")", "unless", "block_given?", "keep_e", ",", "keep_i", "=", "each_with_index", ".", "reject", "{", "|", "n", ",", "_i", "|", "yield", "(", "n", ")", "}", ".", "transpose", "@data", "=", "cast_vector_to", "@dtype", ",", "keep_e", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "keep_i", ")", "update_position_cache", "self", "end" ]
Delete an element if block returns true. Destructive.
[ "Delete", "an", "element", "if", "block", "returns", "true", ".", "Destructive", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L691-L702
14,785
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.verify
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
ruby
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
[ "def", "verify", "(", "0", "...", "size", ")", ".", "map", "{", "|", "i", "|", "[", "i", ",", "@data", "[", "i", "]", "]", "}", ".", "reject", "{", "|", "_i", ",", "val", "|", "yield", "(", "val", ")", "}", ".", "to_h", "end" ]
Reports all values that doesn't comply with a condition. Returns a hash with the index of data and the invalid data.
[ "Reports", "all", "values", "that", "doesn", "t", "comply", "with", "a", "condition", ".", "Returns", "a", "hash", "with", "the", "index", "of", "data", "and", "the", "invalid", "data", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L713-L718
14,786
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.lag
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
ruby
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
[ "def", "lag", "k", "=", "1", "case", "k", "when", "0", "then", "dup", "when", "1", "...", "size", "copy", "(", "[", "nil", "]", "*", "k", "+", "data", ".", "to_a", ")", "when", "-", "size", "..", "-", "1", "copy", "(", "data", ".", "to_a", "[", "k", ".", "abs", "...", "size", "]", ")", "else", "copy", "(", "[", "]", ")", "end", "end" ]
Lags the series by `k` periods. Lags the series by `k` periods, "shifting" data and inserting `nil`s from beginning or end of a vector, while preserving original vector's size. `k` can be positive or negative integer. If `k` is positive, `nil`s are inserted at the beginning of the vector, otherwise they are inserted at the end. @param [Integer] k "shift" the series by `k` periods. `k` can be positive or negative. (default = 1) @return [Daru::Vector] a new vector with "shifted" inital values and `nil` values inserted. The return vector is the same length as the orignal vector. @example Lag a vector with different periods `k` ts = Daru::Vector.new(1..5) # => [1, 2, 3, 4, 5] ts.lag # => [nil, 1, 2, 3, 4] ts.lag(1) # => [nil, 1, 2, 3, 4] ts.lag(2) # => [nil, nil, 1, 2, 3] ts.lag(-1) # => [2, 3, 4, 5, nil]
[ "Lags", "the", "series", "by", "k", "periods", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L851-L861
14,787
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_matrix
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
ruby
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
[ "def", "to_matrix", "axis", "=", ":horizontal", "if", "axis", "==", ":horizontal", "Matrix", "[", "to_a", "]", "elsif", "axis", "==", ":vertical", "Matrix", ".", "columns", "(", "[", "to_a", "]", ")", "else", "raise", "ArgumentError", ",", "\"axis should be either :horizontal or :vertical, not #{axis}\"", "end", "end" ]
Convert Vector to a horizontal or vertical Ruby Matrix. == Arguments * +axis+ - Specify whether you want a *:horizontal* or a *:vertical* matrix.
[ "Convert", "Vector", "to", "a", "horizontal", "or", "vertical", "Ruby", "Matrix", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L920-L928
14,788
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_nmatrix
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a else raise ArgumentError, 'Invalid axis specified. '\ 'Valid axis are :horizontal and :vertical' end end
ruby
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a else raise ArgumentError, 'Invalid axis specified. '\ 'Valid axis are :horizontal and :vertical' end end
[ "def", "to_nmatrix", "axis", "=", ":horizontal", "unless", "numeric?", "&&", "!", "include?", "(", "nil", ")", "raise", "ArgumentError", ",", "'Can not convert to nmatrix'", "'because the vector is numeric'", "end", "case", "axis", "when", ":horizontal", "NMatrix", ".", "new", "[", "1", ",", "size", "]", ",", "to_a", "when", ":vertical", "NMatrix", ".", "new", "[", "size", ",", "1", "]", ",", "to_a", "else", "raise", "ArgumentError", ",", "'Invalid axis specified. '", "'Valid axis are :horizontal and :vertical'", "end", "end" ]
Convert vector to nmatrix object @param [Symbol] axis :horizontal or :vertical @return [NMatrix] NMatrix object containing all values of the vector @example dv = Daru::Vector.new [1, 2, 3] dv.to_nmatrix # => # [ # [1, 2, 3] ]
[ "Convert", "vector", "to", "nmatrix", "object" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L939-L954
14,789
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.object_summary
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? 1 : v.quo(nval))*100)] end summary + Formatters::Table.format(data) end
ruby
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? 1 : v.quo(nval))*100)] end summary + Formatters::Table.format(data) end
[ "def", "object_summary", "nval", "=", "count_values", "(", "Daru", "::", "MISSING_VALUES", ")", "summary", "=", "\"\\n factors: #{factors.to_a.join(',')}\"", "\"\\n mode: #{mode.to_a.join(',')}\"", "\"\\n Distribution\\n\"", "data", "=", "frequencies", ".", "sort", ".", "each_with_index", ".", "map", "do", "|", "v", ",", "k", "|", "[", "k", ",", "v", ",", "'%0.2f%%'", "%", "(", "(", "nval", ".", "zero?", "?", "1", ":", "v", ".", "quo", "(", "nval", ")", ")", "*", "100", ")", "]", "end", "summary", "+", "Formatters", "::", "Table", ".", "format", "(", "data", ")", "end" ]
Displays summary for an object type Vector @return [String] String containing object vector summary
[ "Displays", "summary", "for", "an", "object", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1050-L1061
14,790
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.numeric_summary
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + "\n kurtosis: %0.4f" % kurtosis end summary end
ruby
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + "\n kurtosis: %0.4f" % kurtosis end summary end
[ "def", "numeric_summary", "summary", "=", "\"\\n median: #{median}\"", "+", "\"\\n mean: %0.4f\"", "%", "mean", "if", "sd", "summary", "<<", "\"\\n std.dev.: %0.4f\"", "%", "sd", "+", "\"\\n std.err.: %0.4f\"", "%", "se", "end", "if", "count_values", "(", "Daru", "::", "MISSING_VALUES", ")", ".", "zero?", "summary", "<<", "\"\\n skew: %0.4f\"", "%", "skew", "+", "\"\\n kurtosis: %0.4f\"", "%", "kurtosis", "end", "summary", "end" ]
Displays summary for an numeric type Vector @return [String] String containing numeric vector summary
[ "Displays", "summary", "for", "an", "numeric", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1065-L1078
14,791
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.inspect
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_headers, threshold: threshold, spacing: spacing ) end
ruby
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_headers, threshold: threshold, spacing: spacing ) end
[ "def", "inspect", "spacing", "=", "20", ",", "threshold", "=", "15", "row_headers", "=", "index", ".", "is_a?", "(", "MultiIndex", ")", "?", "index", ".", "sparse_tuples", ":", "index", ".", "to_a", "\"#<#{self.class}(#{size})#{':category' if category?}>\\n\"", "+", "Formatters", "::", "Table", ".", "format", "(", "to_a", ".", "lazy", ".", "map", "{", "|", "v", "|", "[", "v", "]", "}", ",", "headers", ":", "@name", "&&", "[", "@name", "]", ",", "row_headers", ":", "row_headers", ",", "threshold", ":", "threshold", ",", "spacing", ":", "spacing", ")", "end" ]
Over rides original inspect for pretty printing in irb
[ "Over", "rides", "original", "inspect", "for", "pretty", "printing", "in", "irb" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1081-L1092
14,792
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.reindex!
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache self end
ruby
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache self end
[ "def", "reindex!", "new_index", "values", "=", "[", "]", "each_with_index", "do", "|", "val", ",", "i", "|", "values", "[", "new_index", "[", "i", "]", "]", "=", "val", "if", "new_index", ".", "include?", "(", "i", ")", "end", "values", ".", "fill", "(", "nil", ",", "values", ".", "size", ",", "new_index", ".", "size", "-", "values", ".", "size", ")", "@data", "=", "cast_vector_to", "@dtype", ",", "values", "@index", "=", "new_index", "update_position_cache", "self", "end" ]
Sets new index for vector. Preserves index->value correspondence. Sets nil for new index keys absent from original index. @note Unlike #reorder! which takes positions as input it takes index as an input to reorder the vector @param [Daru::Index, Daru::MultiIndex] new_index new index to order with @return [Daru::Vector] vector reindexed with new index
[ "Sets", "new", "index", "for", "vector", ".", "Preserves", "index", "-", ">", "value", "correspondence", ".", "Sets", "nil", "for", "new", "index", "keys", "absent", "from", "original", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1100-L1113
14,793
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_valid
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[idx] } if as_a == :vector Daru::Vector.new new_vector, index: new_index, name: @name, dtype: dtype else new_vector end end
ruby
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[idx] } if as_a == :vector Daru::Vector.new new_vector, index: new_index, name: @name, dtype: dtype else new_vector end end
[ "def", "only_valid", "as_a", "=", ":vector", ",", "_duplicate", "=", "true", "# FIXME: Now duplicate is just ignored.", "# There are no spec that fail on this case, so I'll leave it", "# this way for now - zverok, 2016-05-07", "new_index", "=", "@index", ".", "to_a", "-", "indexes", "(", "Daru", "::", "MISSING_VALUES", ")", "new_vector", "=", "new_index", ".", "map", "{", "|", "idx", "|", "self", "[", "idx", "]", "}", "if", "as_a", "==", ":vector", "Daru", "::", "Vector", ".", "new", "new_vector", ",", "index", ":", "new_index", ",", "name", ":", "@name", ",", "dtype", ":", "dtype", "else", "new_vector", "end", "end" ]
Creates a new vector consisting only of non-nil data == Arguments @param as_a [Symbol] Passing :array will return only the elements as an Array. Otherwise will return a Daru::Vector. @param _duplicate [Symbol] In case no missing data is found in the vector, setting this to false will return the same vector. Otherwise, a duplicate will be returned irrespective of presence of missing data.
[ "Creates", "a", "new", "vector", "consisting", "only", "of", "non", "-", "nil", "data" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1267-L1280
14,794
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_numerics
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
ruby
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
[ "def", "only_numerics", "numeric_indexes", "=", "each_with_index", ".", "select", "{", "|", "v", ",", "_i", "|", "v", ".", "is_a?", "(", "Numeric", ")", "||", "v", ".", "nil?", "}", ".", "map", "(", ":last", ")", "self", "[", "numeric_indexes", "]", "end" ]
Returns a Vector with only numerical data. Missing data is included but non-Numeric objects are excluded. Preserves index.
[ "Returns", "a", "Vector", "with", "only", "numerical", "data", ".", "Missing", "data", "is", "included", "but", "non", "-", "Numeric", "objects", "are", "excluded", ".", "Preserves", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1353-L1360
14,795
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.db_type
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end end
ruby
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end end
[ "def", "db_type", "# first, detect any character not number", "case", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "DATE_REGEXP", "}", "'DATE'", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", "/", "}", "'VARCHAR (255)'", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", "\\.", "/", "}", "'DOUBLE'", "else", "'INTEGER'", "end", "end" ]
Returns the database type for the vector, according to its content
[ "Returns", "the", "database", "type", "for", "the", "vector", "according", "to", "its", "content" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1365-L1377
14,796
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_category
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
ruby
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
[ "def", "to_category", "opts", "=", "{", "}", "dv", "=", "Daru", "::", "Vector", ".", "new", "to_a", ",", "type", ":", ":category", ",", "name", ":", "@name", ",", "index", ":", "@index", "dv", ".", "ordered", "=", "opts", "[", ":ordered", "]", "||", "false", "dv", ".", "categories", "=", "opts", "[", ":categories", "]", "if", "opts", "[", ":categories", "]", "dv", "end" ]
Converts a non category type vector to category type vector. @param [Hash] opts options to convert to category @option opts [true, false] :ordered Specify if vector is ordered or not. If it is ordered, it can be sorted and min, max like functions would work @option opts [Array] :categories set categories in the specified order @return [Daru::Vector] vector with type category
[ "Converts", "a", "non", "category", "type", "vector", "to", "category", "type", "vector", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1417-L1422
14,797
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cut
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, type: :category, categories: cats # Rename categories if new labels provided if labels dv.rename_categories Hash[cats.zip(labels)] else dv end end
ruby
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, type: :category, categories: cats # Rename categories if new labels provided if labels dv.rename_categories Hash[cats.zip(labels)] else dv end end
[ "def", "cut", "partitions", ",", "opts", "=", "{", "}", "close_at", ",", "labels", "=", "opts", "[", ":close_at", "]", "||", ":right", ",", "opts", "[", ":labels", "]", "partitions", "=", "partitions", ".", "to_a", "values", "=", "to_a", ".", "map", "{", "|", "val", "|", "cut_find_category", "partitions", ",", "val", ",", "close_at", "}", "cats", "=", "cut_categories", "(", "partitions", ",", "close_at", ")", "dv", "=", "Daru", "::", "Vector", ".", "new", "values", ",", "index", ":", "@index", ",", "type", ":", ":category", ",", "categories", ":", "cats", "# Rename categories if new labels provided", "if", "labels", "dv", ".", "rename_categories", "Hash", "[", "cats", ".", "zip", "(", "labels", ")", "]", "else", "dv", "end", "end" ]
Partition a numeric variable into categories. @param [Array<Numeric>] partitions an array whose consecutive elements provide intervals for categories @param [Hash] opts options to cut the partition @option opts [:left, :right] :close_at specifies whether the interval closes at the right side of left side @option opts [Array] :labels names of the categories @return [Daru::Vector] numeric variable converted to categorical variable @example heights = Daru::Vector.new [30, 35, 32, 50, 42, 51] height_cat = heights.cut [30, 40, 50, 60], labels=['low', 'medium', 'high'] # => #<Daru::Vector(6)> # 0 low # 1 low # 2 low # 3 high # 4 medium # 5 high
[ "Partition", "a", "numeric", "variable", "into", "categories", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1458-L1475
14,798
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.valid_value?
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
ruby
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
[ "def", "valid_value?", "(", "v", ")", "v", ".", "respond_to?", "(", ":nan?", ")", "&&", "v", ".", "nan?", "||", "v", ".", "nil?", "?", "false", ":", "true", "end" ]
Helper method returning validity of arbitrary value
[ "Helper", "method", "returning", "validity", "of", "arbitrary", "value" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1520-L1522
14,799
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.prepare_bootstrap
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to_h [h_est, h_est.keys, bss] end
ruby
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to_h [h_est, h_est.keys, bss] end
[ "def", "prepare_bootstrap", "(", "estimators", ")", "h_est", "=", "estimators", "h_est", "=", "[", "h_est", "]", "unless", "h_est", ".", "is_a?", "(", "Array", ")", "||", "h_est", ".", "is_a?", "(", "Hash", ")", "if", "h_est", ".", "is_a?", "Array", "h_est", "=", "h_est", ".", "map", "do", "|", "est", "|", "[", "est", ",", "->", "(", "v", ")", "{", "Daru", "::", "Vector", ".", "new", "(", "v", ")", ".", "send", "(", "est", ")", "}", "]", "end", ".", "to_h", "end", "bss", "=", "h_est", ".", "keys", ".", "map", "{", "|", "v", "|", "[", "v", ",", "[", "]", "]", "}", ".", "to_h", "[", "h_est", ",", "h_est", ".", "keys", ",", "bss", "]", "end" ]
For an array or hash of estimators methods, returns an array with three elements 1.- A hash with estimators names as keys and lambdas as values 2.- An array with estimators names 3.- A Hash with estimators names as keys and empty arrays as values
[ "For", "an", "array", "or", "hash", "of", "estimators", "methods", "returns", "an", "array", "with", "three", "elements", "1", ".", "-", "A", "hash", "with", "estimators", "names", "as", "keys", "and", "lambdas", "as", "values", "2", ".", "-", "An", "array", "with", "estimators", "names", "3", ".", "-", "A", "Hash", "with", "estimators", "names", "as", "keys", "and", "empty", "arrays", "as", "values" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1572-L1584