repository_name
stringlengths
7
56
func_path_in_repository
stringlengths
10
101
func_name
stringlengths
12
78
language
stringclasses
1 value
func_code_string
stringlengths
74
11.9k
func_documentation_string
stringlengths
3
8.03k
split_name
stringclasses
1 value
func_code_url
stringlengths
98
213
enclosing_scope
stringlengths
42
98.2k
barkerest/incline
lib/incline/extensions/jbuilder_template.rb
Incline::Extensions.JbuilderTemplate.api_errors!
ruby
def api_errors!(model_name, model_errors) base_error = model_errors[:base] field_errors = model_errors.reject{ |k,_| k == :base } unless base_error.blank? set! 'error', "#{model_name.humanize} #{base_error.map{|e| h(e.to_s)}.join("<br>\n#{model_name.humanize} ")}" end unless field_...
List out the errors for the model. model_name:: The singular name for the model (e.g. - "user_account") model_errors:: The errors collection from the model. json.api_errors! "user_account", user.errors
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/jbuilder_template.rb#L17-L33
module JbuilderTemplate ## # List out the errors for the model. # # model_name:: The singular name for the model (e.g. - "user_account") # model_errors:: The errors collection from the model. # # json.api_errors! "user_account", user.errors # end
ankane/ahoy
lib/ahoy/tracker.rb
Ahoy.Tracker.track
ruby
def track(name, properties = {}, options = {}) if exclude? debug "Event excluded" elsif missing_params? debug "Missing required parameters" else data = { visit_token: visit_token, user_id: user.try(:id), name: name.to_s, properties: prope...
can't use keyword arguments here
train
https://github.com/ankane/ahoy/blob/514e4f9aed4ff87be791e4d8b73b0f2788233ba8/lib/ahoy/tracker.rb#L18-L38
class Tracker UUID_NAMESPACE = "a82ae811-5011-45ab-a728-569df7499c5f" attr_reader :request, :controller def initialize(**options) @store = Ahoy::Store.new(options.merge(ahoy: self)) @controller = options[:controller] @request = options[:request] || @controller.try(:request) @visi...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/output/html.rb
RequestLogAnalyzer::Output.HTML.tag
ruby
def tag(tag, content = nil, attributes = nil) if block_given? attributes = content.nil? ? '' : ' ' + content.map { |(key, value)| "#{key}=\"#{value}\"" }.join(' ') content_string = '' content = yield(content_string) content = content_string unless content_string.empty? "<#{...
HTML tag writer helper <tt>tag</tt> The tag to generate <tt>content</tt> The content inside the tag <tt>attributes</tt> Attributes to write in the tag
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/output/html.rb#L163-L182
class HTML < Base # def initialize(io, options = {}) # super(io, options) # end def colorize(text, *style) if style.include?(:bold) tag(:strong, text) else text end end # Print a string to the io object. def print(str) @io << str end ali...
yaauie/implements
lib/implements/implementation/registry/finder.rb
Implements.Implementation::Registry::Finder.find
ruby
def find(*args) @registry.elements(@selectors).each do |config| next unless config.check?(*args) return config.implementation end fail(Implementation::NotFound, "no compatible implementation for #{inspect}") end
Find a suitable implementation of the given interface, given the args that would be passed to its #initialize and our selectors @api private
train
https://github.com/yaauie/implements/blob/27c698d283dbf71d04721b4cf4929d53b4a99cb7/lib/implements/implementation/registry/finder.rb#L27-L35
class Implementation::Registry::Finder # @api private # @param registry [Implementation::Registry] # @param selectors [Array<#===>] Typically an array of strings def initialize(registry, selectors) @registry = registry @selectors = selectors end # Returns an instance of the @regis...
projectcypress/health-data-standards
lib/hqmf-parser/2.0/population_criteria.rb
HQMF2.PopulationCriteria.handle_observation_criteria
ruby
def handle_observation_criteria exp = @entry.at_xpath('./cda:measureObservationDefinition/cda:value/cda:expression/@value', HQMF2::Document::NAMESPACES) # Measure Observations criteria rely on computed expressions. If it doesn't have one, # then it is likely formatted impr...
extracts out any measure observation definitons, creating from them the proper criteria to generate a precondition
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/population_criteria.rb#L69-L81
class PopulationCriteria include HQMF2::Utilities attr_reader :preconditions, :id, :hqmf_id, :title, :aggregator, :comments # need to do this to allow for setting the type to OBSERV for attr_accessor :type # Create a new population criteria from the supplied HQMF entry # @param [Nokogiri::XML...
sugaryourcoffee/syclink
lib/syclink/website.rb
SycLink.Website.link_attribute_list
ruby
def link_attribute_list(attribute, separator = nil) links.map {|link| link.send(attribute).split(separator)}.flatten.uniq.sort end
List all attributes of the links
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/website.rb#L106-L108
class Website include Exporter include Formatter # The links of the website attr_reader :links # The title of the website attr_reader :title # Create a new Website def initialize(title = "Link List") @links = [] @title = title end # Add a link to the website ...
senchalabs/jsduck
lib/jsduck/type_parser.rb
JsDuck.TypeParser.type_name
ruby
def type_name name = @input.scan(/[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*|\*/) if !name return false elsif @relations[name] @out << @formatter.link(name, nil, name) elsif @primitives[name] if @relations[@primitives[name]] @out << @formatter.link(@primitives[name], nil,...
<type-name> ::= <type-application> | "*" <type-application> ::= <ident-chain> [ "." "<" <type-arguments> ">" ] <type-arguments> ::= <alteration-type> [ "," <alteration-type> ]* <ident-chain> ::= <ident> [ "." <ident> ]* <ident> ::= [a-zA-Z0-9_]+
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/type_parser.rb#L327-L356
class TypeParser # Allows to check the type of error that was encountered. # It will be either of the two: # - :syntax - type definition syntax is incorrect # - :name - one of the names of the types is unknown attr_reader :error # When parsing was successful, then contains the output HTML - t...
hashicorp/vagrant
lib/vagrant/bundler.rb
Vagrant.Bundler.generate_plugin_set
ruby
def generate_plugin_set(*args) plugin_path = args.detect{|i| i.is_a?(Pathname) } || plugin_gem_path skip = args.detect{|i| i.is_a?(Array) } || [] plugin_set = PluginSet.new @logger.debug("Generating new plugin set instance. Skip gems - #{skip}") Dir.glob(plugin_path.join('specifications/*....
Generate the plugin resolver set. Optionally provide specification names (short or full) that should be ignored @param [Pathname] path to plugins @param [Array<String>] gems to skip @return [PluginSet]
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L463-L480
class Bundler # Location of HashiCorp gem repository HASHICORP_GEMSTORE = "https://gems.hashicorp.com/".freeze # Default gem repositories DEFAULT_GEM_SOURCES = [ HASHICORP_GEMSTORE, "https://rubygems.org/".freeze ].freeze def self.instance @bundler ||= self.new end ...
agios/simple_form-dojo
lib/simple_form-dojo/form_builder.rb
SimpleFormDojo.FormBuilder.button_default_value
ruby
def button_default_value obj = object.respond_to?(:to_model) ? object.to_model : object key = obj ? (obj.persisted? ? :edit : :new) : :submit model = if obj.class.respond_to?(:model_name) obj.class.model_name.human else object_name.to_s.humanize end defaults = [] ...
Basically the same as rails submit_default_value
train
https://github.com/agios/simple_form-dojo/blob/c4b134f56f4cb68cba81d583038965360c70fba4/lib/simple_form-dojo/form_builder.rb#L62-L76
class FormBuilder < SimpleForm::FormBuilder include SimpleFormDojo::Inputs # need to include this in order to # get the html_escape method include ERB::Util attr_accessor :dojo_props map_type :currency, :to => SimpleFormDojo::Inputs::CurrencyInput map_type :d...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Draw.opacity
ruby
def opacity(opacity) if opacity.is_a?(Numeric) Kernel.raise ArgumentError, 'opacity must be >= 0 and <= 1.0' if opacity < 0 || opacity > 1.0 end primitive "opacity #{opacity}" end
Specify drawing fill and stroke opacities. If the value is a string ending with a %, the number will be multiplied by 0.01.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L418-L423
class Draw # Thse hashes are used to map Magick constant # values to the strings used in the primitives. ALIGN_TYPE_NAMES = { LeftAlign.to_i => 'left', RightAlign.to_i => 'right', CenterAlign.to_i => 'center' }.freeze ANCHOR_TYPE_NAMES = { StartAnchor.to_i => 'start', ...
mailgun/mailgun-ruby
lib/mailgun/client.rb
Mailgun.Client.post
ruby
def post(resource_path, data, headers = {}) response = @http_client[resource_path].post(data, headers) Response.new(response) rescue => err raise communication_error err end
Generic Mailgun POST Handler @param [String] resource_path This is the API resource you wish to interact with. Be sure to include your domain, where necessary. @param [Hash] data This should be a standard Hash containing required parameters for the requested resource. @param [Hash] headers Additional headers to p...
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/client.rb#L103-L108
class Client def initialize(api_key = Mailgun.api_key, api_host = 'api.mailgun.net', api_version = 'v3', ssl = true, test_mode = false, timeout = nil) endpoint = endpoint_generator(api_host, api_version, ssl) ...
dmitrizagidulin/riagent
lib/riagent/persistence.rb
Riagent.Persistence.save!
ruby
def save!(options={:validate => true}) unless save(options) raise Riagent::InvalidDocumentError.new(self) end true end
Attempts to validate and save the document just like +save+ but will raise a +Riagent::InvalidDocumentError+ exception instead of returning +false+ if the doc is not valid.
train
https://github.com/dmitrizagidulin/riagent/blob/074bbb9c354abc1ba2037d704b0706caa3f34f37/lib/riagent/persistence.rb#L73-L78
module Persistence extend ActiveSupport::Concern COLLECTION_TYPES = [:riak_kv] # Key Listing strategies for +:riak_kv+ collections VALID_KEY_LISTS = [:streaming_list_keys, :riak_dt_set] included do extend ActiveModel::Callbacks define_model_callbacks :create, :update, :...
davidbarral/sugarfree-config
lib/sugarfree-config/config.rb
SugarfreeConfig.ConfigIterator.next
ruby
def next if (value = @scoped_config[@path_elements.last]).nil? raise ConfigKeyException.new(@path_elements) elsif value.is_a?(Hash) @scoped_config = value self else value end end
Iterate to the next element in the path Algorithm: 1. Get the last element of the key path 2. Try to find it in the scoped config 3. If not present raise an error 4. If present and is a hash we are not in a config leaf, so the scoped config is reset to this new value and self is returned 5. If present and is...
train
https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L117-L126
class ConfigIterator # # Create a new iterator with a given +configuration+ and the first # element of the path to be iterated (+first_path_element+) # def initialize(configuration, first_path_element) @scoped_config = configuration @path_elements = [first_path_element.to_s] end ...
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_property_metadata
ruby
def build_property_metadata(props, keys=[]) metadata = {} props.each do |property_element| prop_meta = PropertyMetadata.new(property_element) prop_meta.is_key = keys.include?(prop_meta.name) # If this is a navigation property, we need to add the association to the property metadata prop...
Builds the metadata need for each property for things like feed customizations and navigation properties
train
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L353-L364
class Service attr_reader :classes, :class_metadata, :options, :collections, :edmx, :function_imports, :response # Creates a new instance of the Service class # # @param [String] service_uri the root URI of the OData service # @param [Hash] options the options to pass to the service # @option options [Strin...
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.reverse_each
ruby
def reverse_each return enum_for(__method__) unless block_given? each.to_a.reverse.each { |v| yield v } end
Same as {#each} but in reverse order @example Pattern.new([1, 2, 3]).reverse_each.to_a # => [3, 2, 1] @return [Enumerator] @yield [Object] value
train
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L259-L262
class Pattern extend Generators include Transforms # Array or Proc that produces values or events attr_reader :source # Event delta in terms of cycles (default: 1) attr_reader :delta # Hash that contains metadata related to pattern usage attr_reader :metadata # Size of pattern...
HewlettPackard/hpe3par_ruby_sdk
lib/Hpe3parSdk/client.rb
Hpe3parSdk.Client.create_physical_copy
ruby
def create_physical_copy(src_name, dest_name, dest_cpg, optional = nil) if @current_version < @min_version_with_compression && !optional.nil? [:compression, :allowRemoteCopyParent, :skipZero].each { |key| optional.delete key } end begin @volume.create_physical_copy(src_name, dest_name,...
Creates a physical copy of a VirtualVolume ==== Attributes * src_name - the source volume name type src_name: String * dest_name - the destination volume name type dest_name: String * dest_cpg - the destination CPG type dest_cpg: String * optional - Hash of optional parameters type option...
train
https://github.com/HewlettPackard/hpe3par_ruby_sdk/blob/f8cfc6e597741be593cf7fe013accadf982ee68b/lib/Hpe3parSdk/client.rb#L1674-L1684
class Client def initialize(api_url,debug:false, secure: false, timeout: nil, suppress_ssl_warnings: false, app_type: 'ruby_SDK_3par', log_file_path: nil) unless api_url.is_a?(String) raise Hpe3parSdk::HPE3PARException.new(nil, "'api_url' parameter i...
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.<<
ruby
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
Adds a new node to the collection. By doing so, this will also add it to the configured indices. This will also evaluate any existings contexts that match the new node.
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L85-L90
class NodeCollection include Enumerable # The machine associated with the nodes attr_reader :machine # Creates a new collection of nodes for the given state machine. By default, # the collection is empty. # # Configuration options: # * <tt>:index</tt> - One or more attributes to aut...
ideonetwork/lato-blog
app/controllers/lato_blog/back/posts_controller.rb
LatoBlog.Back::PostsController.create
ruby
def create @post = LatoBlog::Post.new(new_post_params) unless @post.save flash[:danger] = @post.errors.full_messages.to_sentence redirect_to lato_blog.new_post_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:post_create_success] redirect_to lato...
This function creates a new post.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/posts_controller.rb#L49-L60
class Back::PostsController < Back::BackController before_action do core__set_menu_active_item('blog_articles') end # This function shows the list of published posts. def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:posts]) # find correct status to show ...
chikamichi/logg
lib/logg/core.rb
Logg.Dispatcher.as
ruby
def as(method, &block) raise ArgumentError, 'Missing mandatory block' unless block_given? method = method.to_sym # Define the guard at class-level, if not already defined. if !eigenclass.respond_to?(method) eigenclass.send(:define_method, method) do |*args| Render.new.instan...
Define a custom logger, using a template. The template may be defined within the block as a (multi-line) string, or one may reference a file. # do whatever you want with data or anything else, for instance, send mails, tweet, then… Inline templates (defined within the block) make use of #render_inline (i...
train
https://github.com/chikamichi/logg/blob/fadc70f80ee48930058db131888aabf7da21da2d/lib/logg/core.rb#L138-L161
class Dispatcher class Render # Render a template. Just a mere proxy for Tilt::Template#render method, # the first argument being the filepath or file, and the latter, # the usual arguments for Tilt's #render. # # @param [String, #path, #realpath] path filepath or an object behaving ...
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.initialize_proxy
ruby
def initialize_proxy(url, options) @manual_proxy = !!options.proxy @proxy = if options.proxy ProxyOptions.from(options.proxy) else proxy_from_env(url) end @temp_proxy = @proxy end
Initializes a new Faraday::Connection. @param url [URI, String] URI or String base URL to use as a prefix for all requests (optional). @param options [Hash, Faraday::ConnectionOptions] @option options [URI, String] :url ('http:/') URI or String base URL @option options [Hash<String => String>] :params U...
train
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L94-L103
class Connection # A Set of allowed HTTP verbs. METHODS = Set.new %i[get post put delete head patch options trace connect] # @return [Hash] URI query unencoded key/value pairs. attr_reader :params # @return [Hash] unencoded HTTP header key/value pairs. attr_reader :headers # @return [St...
tbuehlmann/ponder
lib/ponder/thaum.rb
Ponder.Thaum.setup_default_callbacks
ruby
def setup_default_callbacks on :query, /^\001PING \d+\001$/ do |event_data| time = event_data[:message].scan(/\d+/)[0] notice event_data[:nick], "\001PING #{time}\001" end on :query, /^\001VERSION\001$/ do |event_data| notice event_data[:nick], "\001VERSION Ponder #{Ponder::VE...
Default callbacks for PING, VERSION, TIME and ISUPPORT processing.
train
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L135-L152
class Thaum include IRC attr_reader :config, :callbacks, :isupport, :channel_list, :user_list, :connection, :loggers attr_accessor :connected, :deferrables def initialize(&block) # default settings @config = OpenStruct.new( :server => 'chat.freenode.org', :por...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.write
ruby
def write(object, attribute, value, ivar = false) attribute = self.attribute(attribute) ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value) end
Sets a new value in the given object's attribute. For example, class Vehicle state_machine :initial => :parked do ... end end vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked"> Vehicle.state_machine.write(vehicle, :state, 'idling') # => E...
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1076-L1079
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
kontena/kontena
agent/lib/kontena/websocket_client.rb
Kontena.WebsocketClient.send_request
ruby
def send_request(id, method, params) data = MessagePack.dump([0, id, method, params]).bytes ws.send(data) rescue => exc warn exc abort exc end
Called from RpcClient, does not crash the Actor on errors. @param [Integer] id @param [String] method @param [Array] params @raise [RuntimeError] not connected
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/websocket_client.rb#L291-L297
class WebsocketClient include Celluloid include Celluloid::Notifications include Kontena::Logging STRFTIME = '%F %T.%NZ' CONNECT_INTERVAL = 1.0 RECONNECT_BACKOFF = 90.0 CONNECT_TIMEOUT = 10.0 OPEN_TIMEOUT = 10.0 PING_INTERVAL = 30.0 # seconds PING_TIMEOUT = Kernel::Float(ENV[...
mojombo/chronic
lib/chronic/handlers.rb
Chronic.Handlers.handle_sm_sy
ruby
def handle_sm_sy(tokens, options) month = tokens[0].get_tag(ScalarMonth).type year = tokens[1].get_tag(ScalarYear).type handle_year_and_month(year, month) end
Handle scalar-month/scalar-year
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L293-L297
module Handlers module_function # Handle month/day def handle_m_d(month, day, time_tokens, options) month.start = self.now span = month.this(options[:context]) year, month = span.begin.year, span.begin.month day_start = Chronic.time_class.local(year, month, day) day_start = ...
NCSU-Libraries/quick_search
app/controllers/quick_search/logging_controller.rb
QuickSearch.LoggingController.log_event
ruby
def log_event if params[:category].present? && params[:event_action].present? && params[:label].present? # if an action isn't passed in, assume that it is a click action = params.fetch(:action_type, 'click') # create a new event on the current session @session.events.create(catego...
Logs an event to the database. Typically, these can be clicks or serves. This is an API endpoint for logging an event. It requires that at least a TODO are present in the query parameters. It returns a 200 OK HTTP status if the request was successful, or an 400 BAD REQUEST HTTP status if any parameters are missing....
train
https://github.com/NCSU-Libraries/quick_search/blob/2e2c3f8682eed63a2bf2c008fa77f04ff9dd6a03/app/controllers/quick_search/logging_controller.rb#L36-L57
class LoggingController < ApplicationController include QuickSearch::OnCampus before_action :handle_session protect_from_forgery except: :log_event ## # Logs a search to the database # # This is an API endpoint for logging a search. It requires that at least a search query and a page ar...
hashicorp/vault-ruby
lib/vault/api/sys/auth.rb
Vault.Sys.auth_tune
ruby
def auth_tune(path) json = client.get("/v1/sys/auth/#{encode_path(path)}/tune") return AuthConfig.decode(json) rescue HTTPError => e return nil if e.code == 404 raise end
Read the given auth path's configuration. @example Vault.sys.auth_tune("github") #=> #<Vault::AuthConfig "default_lease_ttl"=3600, "max_lease_ttl"=7200> @param [String] path the path to retrieve configuration for @return [AuthConfig] configuration of the given auth path
train
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/auth.rb#L89-L95
class Sys # List all auths in Vault. # # @example # Vault.sys.auths #=> {:token => #<Vault::Auth type="token", description="token based credentials">} # # @return [Hash<Symbol, Auth>] def auths json = client.get("/v1/sys/auth") json = json[:data] if json[:data] return H...
NullVoxPopuli/lazy_crud
lib/lazy_crud/instance_methods.rb
LazyCrud.InstanceMethods.resource_proxy
ruby
def resource_proxy(with_deleted = false) proxy = if parent_instance.present? parent_instance.send(resource_plural_name) else self.class.resource_class end if with_deleted and proxy.respond_to?(:with_deleted) proxy = proxy.with_deleted end proxy end
determines if we want to use the parent class if available or if we just use the resource class
train
https://github.com/NullVoxPopuli/lazy_crud/blob/80997de5de9eba4f96121c2bdb11fc4e4b8b754a/lib/lazy_crud/instance_methods.rb#L95-L107
module InstanceMethods def index respond_with(set_collection_instance) end def show # instance variable set in before_action respond_with(get_resource_instance) end def new set_resource_instance(resource_proxy.new) respond_with(get_resource_instance) end d...
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions
ruby
def get_transactions(budget_id, opts = {}) data, _status_code, _headers = get_transactions_with_http_info(budget_id, opts) data end
List transactions Returns budget transactions @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param [Hash] opts the optional parameters @option opts [Date] :since_date If specified, only transactions on or after this date will be included. The date ...
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L146-L149
class TransactionsApi attr_accessor :api_client def initialize(api_client = ApiClient.default) @api_client = api_client end # Create a single transaction or multiple transactions # Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' objec...
sunspot/sunspot
sunspot/lib/sunspot/indexer.rb
Sunspot.Indexer.prepare_full_update
ruby
def prepare_full_update(model) document = document_for_full_update(model) setup = setup_for_object(model) if boost = setup.document_boost_for(model) document.attrs[:boost] = boost end setup.all_field_factories.each do |field_factory| field_factory.populate_document(document...
Convert documents into hash of indexed properties
train
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L104-L114
class Indexer #:nodoc: def initialize(connection) @connection = connection end # # Construct a representation of the model for indexing and send it to the # connection for indexing # # ==== Parameters # # model<Object>:: the model to index # def add(model) do...
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.read_string
ruby
def read_string(data: nil, stream: nil, offset: 0) if data && !stream string_length, read_length = read_varint(data: data, offset: offset) # If failed to read the length prefix, return nil. return [nil, read_length] if !string_length # Check if we have enough bytes to read the s...
Reads variable-length string from data buffer or IO stream. Either data or stream must be present (and only one of them). Returns [string, length] where length is a number of bytes read (includes length prefix and offset bytes). In case of failure, returns [nil, length] where length is a number of bytes read before ...
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L134-L163
module WireFormat extend self # Reads varint from data or stream. # Either data or stream must be present (and only one of them). # Optional offset is useful when reading from data. # Returns [value, length] where value is a decoded integer value and length is number of bytes read (including offs...
ideasasylum/tinycert
lib/tinycert/request.rb
Tinycert.Request.build_request
ruby
def build_request req = Net::HTTP::Post.new(@uri) req.add_field "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" req.body = params_string_with_digest # puts @uri # puts req.body req end
Create Request
train
https://github.com/ideasasylum/tinycert/blob/6176e740e7d14eb3e9468e442d6c3575fb5810dc/lib/tinycert/request.rb#L39-L46
class Request attr_reader :params def initialize api_key, url, params @api_key = api_key @uri = URI(url) @params = prepare_params(params) # Create client @client = Net::HTTP.new(@uri.host, @uri.port) @client.use_ssl = true @client.verify_mode = OpenSSL::SSL::VERIFY_...
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.dirty?
ruby
def dirty?(path = Dir.pwd) g = MiniGit.new(path) a = g.capturing.diff :shortstat => true #ap a !a.empty? end
Check if a git directory is in dirty mode git diff --shortstat 2> /dev/null | tail -n1
train
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L261-L266
module Git module_function ## Check if a git directory has been initialized def init?(path = Dir.pwd) begin MiniGit.new(path) rescue Exception return false end true end ## Check if the repositories already holds some commits def commits?(path) r...
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.entry_to_class
ruby
def entry_to_class(entry) # Retrieve the class name from the fully qualified name (the last string after the last dot) klass_name = entry.xpath("./atom:category/@term", @ds_namespaces).to_s.split('.')[-1] # Is the category missing? See if there is a title that we can use to build the class if klass_nam...
Converts an XML Entry into a class
train
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L433-L497
class Service attr_reader :classes, :class_metadata, :options, :collections, :edmx, :function_imports, :response # Creates a new instance of the Service class # # @param [String] service_uri the root URI of the OData service # @param [Hash] options the options to pass to the service # @option options [Strin...
hashicorp/vagrant
lib/vagrant/guest.rb
Vagrant.Guest.detect!
ruby
def detect! guest_name = @machine.config.vm.guest initialize_capabilities!(guest_name, @guests, @capabilities, @machine) rescue Errors::CapabilityHostExplicitNotDetected => e raise Errors::GuestExplicitNotDetected, value: e.extra_data[:value] rescue Errors::CapabilityHostNotDetected rais...
This will detect the proper guest OS for the machine and set up the class to actually execute capabilities.
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/guest.rb#L32-L39
class Guest include CapabilityHost def initialize(machine, guests, capabilities) @capabilities = capabilities @guests = guests @machine = machine end # This will detect the proper guest OS for the machine and set up # the class to actually execute capabilities. ...
sugaryourcoffee/syclink
lib/syclink/link.rb
SycLink.Link.match?
ruby
def match?(args) select_defined(args).reduce(true) do |sum, attribute| sum = sum && (send(attribute[0]) == attribute[1]) end end
Checks whether the link matches the values provided by args and returns true if so otherwise false link.match?(name: "Example", tag: "Test")
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/link.rb#L55-L59
class Link include LinkChecker # Attributes that are accessible ATTRS = [:url, :name, :description, :tag] # Attribute accessors generated from ATTRS attr_accessor *ATTRS # Create a new link with url and params. If params are not provided # defaults are used for name the url is used, d...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.grep
ruby
def grep(pattern = '.*') regexp = Regexp.new(pattern) fetch_items_from_filesystem_or_zip @items = items.shift(2) + items.select {|i| i.name =~ regexp} sort_items_according_to_current_direction draw_items draw_total_items switch_page 0 move_cursor 0 end
Search files and directories from the current directory, and update the screen. * +pattern+ - Search pattern against file names in Ruby Regexp string. === Example a : Search files that contains the letter "a" in their file name .*\.pdf$ : Search PDF files
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L344-L353
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightW...
sup-heliotrope/sup
lib/sup/maildir.rb
Redwood.Maildir.poll
ruby
def poll added = [] deleted = [] updated = [] @ctimes.each do |d,prev_ctime| subdir = File.join @dir, d debug "polling maildir #{subdir}" raise FatalSourceError, "#{subdir} not a directory" unless File.directory? subdir ctime = File.ctime subdir next if prev_ctime >= ctime ...
XXX use less memory
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/maildir.rb#L118-L181
class Maildir < Source include SerializeLabelsNicely MYHOSTNAME = Socket.gethostname ## remind me never to use inheritance again. yaml_properties :uri, :usual, :archived, :sync_back, :id, :labels def initialize uri, usual=true, archived=false, sync_back=true, id=nil, labels=[] super uri, usual, archived,...
state-machines/state_machines
lib/state_machines/event_collection.rb
StateMachines.EventCollection.attribute_transition_for
ruby
def attribute_transition_for(object, invalidate = false) return unless machine.action # TODO, simplify machine.read(object, :event_transition) || if event_name = machine.read(object, :event) if event = self[event_name.to_sym, :name] ...
Gets the transition that should be performed for the event stored in the given object's event attribute. This also takes an additional parameter for automatically invalidating the object if the event or transition are invalid. By default, this is turned off. *Note* that if a transition has already been generated...
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L114-L132
class EventCollection < NodeCollection def initialize(machine) #:nodoc: super(machine, :index => [:name, :qualified_name]) end # Gets the list of events that can be fired on the given object. # # Valid requirement options: # * <tt>:from</tt> - One or more states being transitioned from...
projectcypress/health-data-standards
lib/hqmf-parser/2.0/document_helpers/doc_utilities.rb
HQMF2.DocumentUtilities.complex_coverage
ruby
def complex_coverage(data_criteria, check_criteria) same_value = data_criteria.value.nil? || data_criteria.value.try(:to_model).try(:to_json) == check_criteria.value.try(:to_model).try(:to_json) same_field_values = same_field_values_check(data_criteria, check_criteria) same_negati...
Check elements that do not already exist; else, if they do, check if those elements are the same in a different, potentially matching, data criteria
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/document_helpers/doc_utilities.rb#L107-L117
module DocumentUtilities # Create grouper data criteria for encapsulating variable data criteria # and update document data criteria list and references map def handle_variable(data_criteria, collapsed_source_data_criteria) if data_criteria.is_derived_specific_occurrence_variable data_crite...
zeevex/zeevex_threadsafe
lib/zeevex_threadsafe/aliasing.rb
ZeevexThreadsafe.Aliasing.alias_method_chain
ruby
def alias_method_chain(target, feature) # Strip out punctuation on predicates or bang methods since # e.g. target?_without_feature is not a valid method name. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 yield(aliased_target, punctuation) if block_given? with_method, ...
Encapsulates the common pattern of: alias_method :foo_without_feature, :foo alias_method :foo, :foo_with_feature With this, you simply do: alias_method_chain :foo, :feature And both aliases are set up for you. Query and bang methods (foo?, foo!) keep the same punctuation: alias_method_chain :foo?, ...
train
https://github.com/zeevex/zeevex_threadsafe/blob/a486da9094204c8fb9007bf7a4668a17f97a1f22/lib/zeevex_threadsafe/aliasing.rb#L28-L47
module Aliasing # Encapsulates the common pattern of: # # alias_method :foo_without_feature, :foo # alias_method :foo, :foo_with_feature # # With this, you simply do: # # alias_method_chain :foo, :feature # # And both aliases are set up for you. # # Query and bang...
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.add_txn_opts!
ruby
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_...
Add the transactions options if applicable. @example session.add_txn_opts!(cmd) @return [ Hash, BSON::Document ] The command document. @since 2.6.0 @api private
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L263-L321
class Session extend Forwardable include Retryable include Loggable # Get the options for this session. # # @since 2.5.0 attr_reader :options # Get the client through which this session was created. # # @since 2.5.1 attr_reader :client # The cluster time for this ses...
grpc/grpc
src/ruby/lib/grpc/errors.rb
GRPC.BadStatus.to_rpc_status
ruby
def to_rpc_status status = to_status return if status.nil? GoogleRpcStatusUtils.extract_google_rpc_status(status) rescue Google::Protobuf::ParseError => parse_error GRPC.logger.warn('parse error: to_rpc_status failed') GRPC.logger.warn(parse_error) nil end
Converts the exception to a deserialized {Google::Rpc::Status} object. Returns `nil` if the `grpc-status-details-bin` trailer could not be converted to a {Google::Rpc::Status} due to the server not providing the necessary trailers. @return [Google::Rpc::Status, nil]
train
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/errors.rb#L60-L70
class BadStatus < StandardError attr_reader :code, :details, :metadata include GRPC::Core::StatusCodes # @param code [Numeric] the status code # @param details [String] the details of the exception # @param metadata [Hash] the error's metadata def initialize(code, details = 'unknown cause', ...
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_synonyms!
ruby
def copy_synonyms!(src_index, dst_index, request_options = {}) res = copy_synonyms(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
Copy an existing index synonyms and wait until the copy has been processed. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName synonyms (destination synonyms will be overriten if it already exist). @param request_options contains extra parameter...
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L265-L269
class Client attr_reader :ssl, :ssl_version, :hosts, :search_hosts, :application_id, :api_key, :headers, :connect_timeout, :send_timeout, :receive_timeout, :search_timeout, :batch_timeout DEFAULT_CONNECT_TIMEOUT = 2 DEFAULT_RECEIVE_TIMEOUT = 30 DEFAULT_SEND_TIMEOUT = 30 DEFAULT_BATCH_TIMEOUT ...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Draw.circle
ruby
def circle(origin_x, origin_y, perim_x, perim_y) primitive 'circle ' + format('%g,%g %g,%g', origin_x, origin_y, perim_x, perim_y) end
Draw a circle
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L249-L251
class Draw # Thse hashes are used to map Magick constant # values to the strings used in the primitives. ALIGN_TYPE_NAMES = { LeftAlign.to_i => 'left', RightAlign.to_i => 'right', CenterAlign.to_i => 'center' }.freeze ANCHOR_TYPE_NAMES = { StartAnchor.to_i => 'start', ...
lambda2/rice_cooker
lib/rice_cooker/base/helpers.rb
RiceCooker.Helpers.parse_sorting_param
ruby
def parse_sorting_param(sorting_param, model) return {} unless sorting_param.present? sorting_params = CSV.parse_line(URI.unescape(sorting_param)).collect do |sort| sorting_param = if sort.start_with?('-') { field: sort[1..-1].to_s.to_sym, direction: :desc } ...
------------------------ Sort helpers -------------------- model -> resource_class with inherited resources
train
https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L81-L95
module Helpers extend ActiveSupport::Concern # Overridable method for available sortable fields def sortable_fields_for(model) if model.respond_to?(:sortable_fields) model.sortable_fields.map(&:to_sym) elsif model.respond_to?(:column_names) model.column_names.map(&:to_sym) ...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.add_events
ruby
def add_events(new_events) new_events.map do |new_event| # Check for other states that use a different class type for their name. # This typically prevents string / symbol misuse. if conflict = events.detect { |event| event.name.class != new_event.class } raise ArgumentError, "#{...
Tracks the given set of events in the list of all known events for this machine
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2218-L2232
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
weshatheleopard/rubyXL
lib/rubyXL/convenience_methods/worksheet.rb
RubyXL.WorksheetConvenienceMethods.insert_row
ruby
def insert_row(row_index = 0) validate_workbook ensure_cell_exists(row_index) old_row = new_cells = nil if row_index > 0 then old_row = sheet_data.rows[row_index - 1] if old_row then new_cells = old_row.cells.collect { |c| if c.nil? then nil ...
Inserts row at row_index, pushes down, copies style from the row above (that's what Excel 2013 does!) NOTE: use of this method will break formulas which reference cells which are being "pushed down"
train
https://github.com/weshatheleopard/rubyXL/blob/e61d78de9486316cdee039d3590177dc05db0f0c/lib/rubyXL/convenience_methods/worksheet.rb#L74-L110
module WorksheetConvenienceMethods NAME = 0 SIZE = 1 COLOR = 2 ITALICS = 3 BOLD = 4 UNDERLINE = 5 STRIKETHROUGH = 6 def insert_cell(row = 0, col = 0, data = nil, formula = nil, shift = nil) validate_workbook ensure_cell_exists(row, col) case shift when nil the...
kmuto/review
lib/review/makerhelper.rb
ReVIEW.MakerHelper.copy_images_to_dir
ruby
def copy_images_to_dir(from_dir, to_dir, options = {}) image_files = [] Dir.open(from_dir) do |dir| dir.each do |fname| next if fname =~ /^\./ if FileTest.directory?("#{from_dir}/#{fname}") image_files += copy_images_to_dir("#{from_dir}/#{fname}", "#{to_dir}/#{fname}...
Copy image files under from_dir to to_dir recursively ==== Args from_dir :: path to the directory which has image files to be copied to_dir :: path to the directory to which the image files are copied options :: used to specify optional operations during copy ==== Returns list of image files ==== Options :conve...
train
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/review/makerhelper.rb#L37-L66
module MakerHelper # Return review/bin directory def bindir Pathname.new("#{Pathname.new(__FILE__).realpath.dirname}/../../bin").realpath end module_function :bindir # Copy image files under from_dir to to_dir recursively # ==== Args # from_dir :: path to the directory which has ima...
enkessler/cuke_modeler
lib/cuke_modeler/models/example.rb
CukeModeler.Example.to_s
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "#{@keyword}:#{name_output_string}" text << "\n" + description_output_string unless (description.nil? || description.empty?) text << "\n" unless (rows.empty? || description.nil? || description.empty?) tex...
Returns a string representation of this model. For an example model, this will be Gherkin text that is equivalent to the example being modeled.
train
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/models/example.rb#L104-L115
class Example < Model include Parsing include Parsed include Named include Described include Sourceable include Taggable # The example's keyword attr_accessor :keyword # The row models in the example table attr_accessor :rows # Creates a new Example object and, if *so...
kontena/kontena
agent/lib/kontena/observable.rb
Kontena.Observable.set_and_notify
ruby
def set_and_notify(value) @mutex.synchronize do @value = value @observers.each do |observer, persistent| if !observer.alive? debug { "dead: #{observer}" } @observers.delete(observer) elsif !persistent debug { "notify and drop: #{observer} ...
Send Message with given value to each Kontena::Observer that is still alive. Future calls to `add_observer` will also return the same value. Drops any observers that are dead or non-persistent. TODO: automatically clean out all observers when the observable crashes? @param value [Object, nil, Exception]
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/observable.rb#L185-L209
class Observable require_relative './observable/registry' # @return [Celluloid::Proxy::Cell<Kontena::Observable::Registry>] system registry actor def self.registry Celluloid::Actor[:observable_registry] || fail(Celluloid::DeadActorError, "Observable registry actor not running") end include...
sds/haml-lint
lib/haml_lint/cli.rb
HamlLint.CLI.configure_logger
ruby
def configure_logger(options) log.color_enabled = options.fetch(:color, log.tty?) log.summary_enabled = options.fetch(:summary, true) end
Given the provided options, configure the logger. @return [void]
train
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L60-L63
class CLI # rubocop:disable Metrics/ClassLength # Create a CLI that outputs to the specified logger. # # @param logger [HamlLint::Logger] def initialize(logger) @log = logger end # Parses the given command-line arguments and executes appropriate logic # based on those arguments. ...
caruby/core
lib/caruby/database.rb
CaRuby.Database.print_operations
ruby
def print_operations ops = @operations.reverse.map do |op| attr_s = " #{op.attribute}" if op.attribute "#{op.type.to_s.capitalize_first} #{op.subject.qp}#{attr_s}" end ops.qp end
Returns the current database operation stack as a String.
train
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database.rb#L289-L295
class Database include Reader, Writer, Persistifier # The application and database connection options. ACCESS_OPTS = [ [:user, '-u USER', '--user USER', 'the application login user'], [:password, '-p PSWD', '--password PSWD', 'the application login password'], [:host, '--host HOST', 'th...
dicom/rtp-connect
lib/rtp-connect/plan_to_dcm.rb
RTP.Plan.create_beam_limiting_device_positions
ruby
def create_beam_limiting_device_positions(cp_item, cp, options={}) dp_seq = DICOM::Sequence.new('300A,011A', :parent => cp_item) # The ASYMX item ('backup jaws') doesn't exist on all models: if ['SYM', 'ASY'].include?(cp.parent.field_x_mode.upcase) dp_item_x = create_asym_item(cp, dp_seq, axis...
Creates a beam limiting device positions sequence in the given DICOM object. @param [DICOM::Item] cp_item the DICOM control point item in which to insert the sequence @param [ControlPoint] cp the RTP control point to fetch device parameters from @return [DICOM::Sequence] the constructed beam limiting device positio...
train
https://github.com/dicom/rtp-connect/blob/e23791970218a7087a0d798aa430acf36f79d758/lib/rtp-connect/plan_to_dcm.rb#L559-L574
class Plan < Record attr_accessor :current_gantry attr_accessor :current_collimator attr_accessor :current_couch_angle attr_accessor :current_couch_pedestal attr_accessor :current_couch_lateral attr_accessor :current_couch_longitudinal attr_accessor :current_couch_vertical # Converts...
anga/extend_at
lib/extend_at/configuration.rb
ExtendModelAt.Configuration.get_value_of
ruby
def get_value_of(value, model=nil) if value.kind_of? Symbol # If the function exist, we execute it if model.respond_to? value return model.send value # if the the function not exist, whe set te symbol as a value else return value end elsif value.k...
Return the value of the execute a function inside the model, for example: :column => :function this function execute the function _function_ to get the value and set it his return to column
train
https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at/configuration.rb#L151-L165
class Configuration # def run(env=nil,model=nil) if env.kind_of? Hash hash = expand_options env, { :not_call_symbol => [:boolean], :not_expand => [:validate, :default] }, model.clone hash[:columns] = init_columns hash[:columns] @config = hash read_associations_configurat...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/tracker/hourly_spread.rb
RequestLogAnalyzer::Tracker.HourlySpread.update
ruby
def update(request) timestamp = request.first(options[:field]) @hour_frequencies[timestamp.to_s[8..9].to_i] += 1 @first = timestamp if timestamp < @first @last = timestamp if timestamp > @last end
Check if the timestamp in the request and store it. <tt>request</tt> The request.
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/tracker/hourly_spread.rb#L42-L47
class HourlySpread < Base attr_reader :hour_frequencies, :first, :last # Check if timestamp field is set in the options and prepare the result time graph. def prepare options[:field] ||= :timestamp @hour_frequencies = (0...24).map { 0 } @first, @last = 99_999_999_999_999, 0 end ...
murb/workbook
lib/workbook/table.rb
Workbook.Table.push
ruby
def push(row) row = Workbook::Row.new(row) if row.class == Array super(row) row.set_table(self) end
Add row @param [Workbook::Table, Array] row to add
train
https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/table.rb#L110-L114
class Table < Array include Workbook::Modules::TableDiffSort include Workbook::Writers::CsvTableWriter include Workbook::Writers::JsonTableWriter include Workbook::Writers::HtmlTableWriter attr_accessor :name def initialize row_cel_values=[], sheet=nil, options={} row_cel_values = [] i...
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.adapter
ruby
def adapter(adapter, options = {}, &block) case adapter when Symbol use(Adapters.const_get(adapter), options, &block) when Class use(adapter, options, &block) else raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_t...
Add adapter to stack @param [Symbol/Class/Moneta store] adapter Name of adapter class, adapter class or Moneta store @param [Hash] options Options hash @api public
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L48-L60
class Builder # @yieldparam Builder dsl code block def initialize(&block) raise ArgumentError, 'No block given' unless block_given? @proxies = [] instance_eval(&block) end # Build proxy stack # # @return [Object] Generated Moneta proxy stack # @api public def build ...
DigitPaint/roger
lib/roger/release.rb
Roger.Release.scm
ruby
def scm(force = false) return @_scm if @_scm && !force case config[:scm] when :git @_scm = Release::Scm::Git.new(path: source_path) when :fixed @_scm = Release::Scm::Fixed.new else raise "Unknown SCM #{options[:scm].inspect}" end end
Get the current SCM object
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/release.rb#L84-L95
class Release include Roger::Helpers::Logging include Roger::Helpers::GetFiles attr_reader :config, :project attr_reader :stack class << self include Roger::Helpers::GetCallable end # @option config [:git, :fixed] :scm The SCM to use (default = :git) # @option config [String, ...
documentcloud/jammit
lib/jammit/command_line.rb
Jammit.CommandLine.ensure_configuration_file
ruby
def ensure_configuration_file config = @options[:config_paths] return true if File.exists?(config) && File.readable?(config) puts "Could not find the asset configuration file \"#{config}\"" exit(1) end
Make sure that we have a readable configuration file. The @jammit@ command can't run without one.
train
https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/command_line.rb#L37-L42
class CommandLine BANNER = <<-EOS Usage: jammit OPTIONS Run jammit inside a Rails application to compresses all JS, CSS, and JST according to config/assets.yml, saving the packaged files and corresponding gzipped versions. If you're using "embed_assets", and you wish to precompile the MHTML stylesheet variant...
arbox/wlapi
lib/wlapi/api.rb
WLAPI.API.intersection
ruby
def intersection(word1, word2, limit = 10) check_params(word1, word2, limit) arg1 = ['Wort 1', word1] arg2 = ['Wort 2', word2] arg3 = ['Limit', limit] answer = query(@cl_Kookurrenzschnitt, arg1, arg2, arg3) get_answer(answer) end
Returns the intersection of the co-occurrences of the two given words. The result set is ordered according to the sum of the significances in descending order. Note that due to the join involved, this make take some time. -- let's call it intersection, not kookurrenzschnitt is being used INTERN, we need additional...
train
https://github.com/arbox/wlapi/blob/8a5b1b1bbfa58826107daeeae409e4e22b1c5236/lib/wlapi/api.rb#L345-L354
class API include REXML # SOAP Services Endpoint. ENDPOINT = 'http://wortschatz.uni-leipzig.de/axis/services' # The list of accessible services, the MARSService is excluded due # to its internal authorization. SERVICES = [ :Baseform, :Cooccurrences, :CooccurrencesAll, :Experiment...
CocoaPods/Xcodeproj
lib/xcodeproj/scheme.rb
Xcodeproj.XCScheme.save_as
ruby
def save_as(project_path, name, shared = true) scheme_folder_path = if shared self.class.shared_data_dir(project_path) else self.class.user_data_dir(project_path) end scheme_folder_path.mkpath ...
Serializes the current state of the object to a ".xcscheme" file. @param [String, Pathname] project_path The path where the ".xcscheme" file should be stored. @param [String] name The name of the scheme, to have ".xcscheme" appended. @param [Boolean] shared true => if the scheme must be a...
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/scheme.rb#L310-L322
class XCScheme # @return [REXML::Document] the XML object that will be manipulated to save # the scheme file after. # attr_reader :doc # Create a XCScheme either from scratch or using an existing file # # @param [String] file_path # The path of the existing .xcscheme fi...
xing/beetle
lib/beetle/client.rb
Beetle.Client.rpc
ruby
def rpc(message_name, data=nil, opts={}) message_name = validated_message_name(message_name) publisher.rpc(message_name, data, opts) end
sends the given message to one of the configured servers and returns the result of running the associated handler. unexpected behavior can ensue if the message gets routed to more than one recipient, so be careful.
train
https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L201-L204
class Client include Logging # the AMQP servers available for publishing attr_reader :servers # additional AMQP servers available for subscribing. useful for migration scenarios. attr_reader :additional_subscription_servers # an options hash for the configured exchanges attr_reader :exc...
hashicorp/vault-ruby
lib/vault/api/sys/audit.rb
Vault.Sys.audits
ruby
def audits json = client.get("/v1/sys/audit") json = json[:data] if json[:data] return Hash[*json.map do |k,v| [k.to_s.chomp("/").to_sym, Audit.decode(v)] end.flatten] end
List all audits for the vault. @example Vault.sys.audits #=> { :file => #<Audit> } @return [Hash<Symbol, Audit>]
train
https://github.com/hashicorp/vault-ruby/blob/02f0532a802ba1a2a0d8703a4585dab76eb9d864/lib/vault/api/sys/audit.rb#L28-L34
class Sys # List all audits for the vault. # # @example # Vault.sys.audits #=> { :file => #<Audit> } # # @return [Hash<Symbol, Audit>] # Enable a particular audit. Note: the +options+ depend heavily on the # type of audit being enabled. Please refer to audit-specific documentation ...
phallguy/scorpion
lib/scorpion/stinger.rb
Scorpion.Stinger.sting!
ruby
def sting!( object ) return object unless scorpion if object assign_scorpion object assign_scorpion_to_enumerable object end object end
Sting an object so that it will be injected with the scorpion and use it to resolve all dependencies. @param [#scorpion] object to sting. @return [object] the object that was stung.
train
https://github.com/phallguy/scorpion/blob/0bc9c1111a37e35991d48543dec88a36f16d7aee/lib/scorpion/stinger.rb#L34-L43
module Stinger @wrappers ||= {} def self.wrap( instance, stinger ) return instance unless instance klass = @wrappers[instance.class] ||= Class.new( instance.class ) do def initialize( instance, stinger ) @__instance__ = instance ...
xing/beetle
lib/beetle/client.rb
Beetle.Client.register_binding
ruby
def register_binding(queue_name, options={}) name = queue_name.to_s opts = options.symbolize_keys exchange = (opts[:exchange] || name).to_s key = (opts[:key] || name).to_s (bindings[name] ||= []) << {:exchange => exchange, :key => key} register_exchange(exchange) unless exchanges.inc...
register an additional binding for an already configured queue _name_ and an _options_ hash: [<tt>:exchange</tt>] the name of the exchange this queue will be bound to (defaults to the name of the queue) [<tt>:key</tt>] the binding key (defaults to the name of the queue) automatically registers the specified ex...
train
https://github.com/xing/beetle/blob/42322edc78e6e181b3b9ee284c3b00bddfc89108/lib/beetle/client.rb#L103-L112
class Client include Logging # the AMQP servers available for publishing attr_reader :servers # additional AMQP servers available for subscribing. useful for migration scenarios. attr_reader :additional_subscription_servers # an options hash for the configured exchanges attr_reader :exc...
dagrz/nba_stats
lib/nba_stats/stats/box_score_advanced.rb
NbaStats.BoxScoreAdvanced.box_score_advanced
ruby
def box_score_advanced( game_id, range_type=0, start_period=0, end_period=0, start_range=0, end_range=0 ) NbaStats::Resources::BoxScoreAdvanced.new( get(BOX_SCORE_ADVANCED_PATH, { :GameID => game_id, :RangeType => range_type...
Calls the boxscoreadvanced API and returns a BoxScoreAdvanced resource. @param game_id [String] @param range_type [Integer] @param start_period [Integer] @param end_period [Integer] @param start_range [Integer] @param end_range [xxxxxxxxxx] @return [NbaStats::Resources::BoxScoreAdvanced]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/box_score_advanced.rb#L19-L37
module BoxScoreAdvanced # The path of the boxscoreadvanced API BOX_SCORE_ADVANCED_PATH = '/stats/boxscoreadvanced' # Calls the boxscoreadvanced API and returns a BoxScoreAdvanced resource. # # @param game_id [String] # @param range_type [Integer] # @param start_period [Integer] # @...
kmewhort/similarity_tree
lib/similarity_tree/similarity_tree.rb
SimilarityTree.SimilarityTree.prune
ruby
def prune(nodes) nodes.each do |node| node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold) end end
prune away nodes that don't meet the configured score threshold
train
https://github.com/kmewhort/similarity_tree/blob/d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7/lib/similarity_tree/similarity_tree.rb#L75-L79
class SimilarityTree # initialize/build the tree hierarchy from an existing similarity matrix def initialize(root_id, similarity_matrix, score_threshold = 0) @nodes = similarity_matrix.map {|key, row| Node.new(key, 0)} @root = @nodes.find {|n| n.id == root_id} @root.diff_score = nil @s...
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.sighash_for_input
ruby
def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all], sig_version: :base, amount: nil, skip_separator_index: 0) raise ArgumentError, 'input_index must be specified.' unless input_index raise ArgumentError, 'does not exist input corresponding to input_inde...
get signature hash @param [Integer] input_index input index. @param [Integer] hash_type signature hash type @param [Bitcoin::Script] output_script script pubkey or script code. if script pubkey is P2WSH, set witness script to this. @param [Integer] amount bitcoin amount locked in input. required for witness input o...
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L192-L205
class Tx MAX_STANDARD_VERSION = 2 # The maximum weight for transactions we're willing to relay/mine MAX_STANDARD_TX_WEIGHT = 400000 MARKER = 0x00 FLAG = 0x01 attr_accessor :version attr_accessor :marker attr_accessor :flag attr_reader :inputs attr_reader :outputs attr_a...
davidbarral/sugarfree-config
lib/sugarfree-config/config.rb
SugarfreeConfig.Config.fetch_config
ruby
def fetch_config Rails.logger.debug "Loading #{@file}::#{@env}" if Object.const_defined?('Rails') && Rails.logger.present? YAML::load_file(@file)[@env.to_s] end
Fetch the config from the file
train
https://github.com/davidbarral/sugarfree-config/blob/76b590627d50cd50b237c21fdf8ea3022ebbdf42/lib/sugarfree-config/config.rb#L47-L50
class Config # # Creates a new config object and load the config file into memory # def initialize(options) options = default_options.merge(options) @file = options[:file] @reload = options[:reload] @env = options[:env] end # # Returns all the config as a bi...
jdigger/git-process
lib/git-process/git_remote.rb
GitProc.GitRemote.repo_name
ruby
def repo_name unless @repo_name url = config["remote.#{name}.url"] raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty? uri = Addressable::URI.parse(url) @repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '') end @repo_name end
The name of the repository @example repo_name #=> "jdigger/git-process" @return [String] the name of the repository
train
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L84-L92
class GitRemote # @param [GitProc::GitConfig] gitconfig def initialize(gitconfig) @gitconfig = gitconfig end # @return [#info, #warn, #debug, #error] def logger @logger ||= @gitconfig.logger end # @return [GitProc::GitConfig] def config @gitconfig end #...
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.ensure_group
ruby
def ensure_group(vpc, ports, sg_cidr_ips = ['0.0.0.0/0']) @logger.notify("aws-sdk: Ensure security group exists for ports #{ports.to_s}, create if not") name = group_id(ports) group = client.describe_security_groups( :filters => [ { :name => 'group-name', :values => [name] }, ...
Return an existing group, or create new one Accepts a VPC as input for checking & creation. @param vpc [Aws::EC2::VPC] the AWS vpc control object @param ports [Array<Number>] an array of port numbers @param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule @return [Aws::EC2::SecurityGroup] ...
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1007-L1023
class AwsSdk < Beaker::Hypervisor ZOMBIE = 3 #anything older than 3 hours is considered a zombie PING_SECURITY_GROUP_NAME = 'beaker-ping' attr_reader :default_region # Initialize AwsSdk hypervisor driver # # @param [Array<Beaker::Host>] hosts Array of Beaker::Host objects # @param [Hash<S...
mongodb/mongo-ruby-driver
lib/mongo/server.rb
Mongo.Server.handle_auth_failure!
ruby
def handle_auth_failure! yield rescue Mongo::Error::SocketTimeoutError # possibly cluster is slow, do not give up on it raise rescue Mongo::Error::SocketError # non-timeout network error unknown! pool.disconnect! raise rescue Auth::Unauthorized # auth error, k...
Handle authentication failure. @example Handle possible authentication failure. server.handle_auth_failure! do Auth.get(user).login(self) end @raise [ Auth::Unauthorized ] If the authentication failed. @return [ Object ] The result of the block execution. @since 2.3.0
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server.rb#L367-L381
class Server extend Forwardable include Monitoring::Publishable include Event::Publisher # The default time in seconds to timeout a connection attempt. # # @since 2.4.3 CONNECT_TIMEOUT = 10.freeze # Instantiate a new server object. Will start the background refresh and # subscrib...
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.authentication_path
ruby
def authentication_path(local_port: nil, invite_code: nil, expires_in: nil, remote: false) auth_url_params = {} if remote auth_url_params[:redirect_uri] = "/code" elsif local_port auth_url_params[:redirect_uri] = "http://localhost:#{local_port}/cb" else raise ArgumentErro...
Build a path for master authentication @param local_port [Fixnum] tcp port where localhost webserver is listening @param invite_code [String] an invitation code generated when user was invited @param expires_in [Fixnum] expiration time for the requested access token @param remote [Boolean] true when performing a l...
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L126-L138
class LoginCommand < Kontena::Command include Kontena::Cli::Common parameter "[URL]", "Kontena Master URL or name" option ['-j', '--join'], '[INVITE_CODE]', "Join master using an invitation code" option ['-t', '--token'], '[TOKEN]', 'Use a pre-generated access token', environment_variable: 'KONTENA_T...
oniram88/imdb-scan
lib/imdb/movie.rb
IMDB.Movie.title
ruby
def title doc.at("//head/meta[@name='title']")["content"].split(/\(.*\)/)[0].strip! || doc.at("h1.header").children.first.text.strip end
Get movie title @return [String]
train
https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/movie.rb#L46-L50
class Movie < IMDB::Skeleton attr_accessor :link, :imdb_id def initialize(id_of) # !!!DON'T FORGET DEFINE NEW METHODS IN SUPER!!! super("Movie", { :imdb_id => String, :poster => String, :title => String, :release_date => String,...
medcat/brandish
lib/brandish/application.rb
Brandish.Application.directory_global_option
ruby
def directory_global_option @directory = Pathname.new(Dir.pwd) global_option("--directory PATH") do |path| @directory = Pathname.new(path).expand_path(Dir.pwd) end end
Defines the directory global option. This sets {#directory} to its default value, and defines an option that can set it. @return [void]
train
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L90-L95
class Application include Commander::Methods # The name of the configure file. This should be `"brandish.config.rb"`, # but may change in the future (maybe `Brandishfile`?). # # @return [::String] attr_reader :config_file # The executing directory for the application. This is provided ...
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_encode
ruby
def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end
encode golomb rice
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L115-L124
class GCSFilter MAX_ELEMENTS_SIZE = 4294967296 # 2**32 attr_reader :p # Golomb-Rice coding parameter attr_reader :m # Inverse false positive rate attr_reader :n # Number of elements in the filter attr_reader :key # SipHash key attr_reader :encoded # encoded filter with hex format. # ini...
litaio/lita
lib/lita/user.rb
Lita.User.save
ruby
def save mention_name = metadata[:mention_name] || metadata["mention_name"] current_keys = metadata.keys redis_keys = redis.hkeys("id:#{id}") delete_keys = (redis_keys - current_keys) redis.pipelined do redis.hdel("id:#{id}", *delete_keys) if delete_keys.any? redis.hmset(...
Saves the user record to Redis, overwriting any previous data for the current ID and user name. @return [void]
train
https://github.com/litaio/lita/blob/c1a1f85f791b74e40ee6a1e2d53f19b5f7cbe0ba/lib/lita/user.rb#L112-L125
class User class << self # The +Redis::Namespace+ for user persistence. # @return [Redis::Namespace] The Redis connection. def redis @redis ||= Redis::Namespace.new("users", redis: Lita.redis) end # Creates a new user with the given ID, or merges and saves supplied # m...
alexreisner/geocoder
lib/geocoder/stores/active_record.rb
Geocoder::Store.ActiveRecord.nearbys
ruby
def nearbys(radius = 20, options = {}) return nil unless geocoded? options.merge!(:exclude => self) unless send(self.class.primary_key).nil? self.class.near(self, radius, options) end
Get nearby geocoded objects. Takes the same options hash as the near class method (scope). Returns nil if the object is not geocoded.
train
https://github.com/alexreisner/geocoder/blob/e087dc2759264ee6f307b926bb2de4ec2406859e/lib/geocoder/stores/active_record.rb#L287-L291
module ActiveRecord include Base ## # Implementation of 'included' hook method. # def self.included(base) base.extend ClassMethods base.class_eval do # scope: geocoded objects scope :geocoded, lambda { where("#{table_name}.#{geocoder_options[:latitude]} IS N...
sup-heliotrope/sup
lib/sup/modes/thread_index_mode.rb
Redwood.ThreadIndexMode.actually_toggle_starred
ruby
def actually_toggle_starred t if t.has_label? :starred # if ANY message has a star t.remove_label :starred # remove from all UpdateManager.relay self, :unstarred, t.first lambda do t.first.add_label :starred UpdateManager.relay self, :starred, t.first regen_text end ...
returns an undo lambda
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/modes/thread_index_mode.rb#L292-L310
class ThreadIndexMode < LineCursorMode DATE_WIDTH = Time::TO_NICE_S_MAX_LEN MIN_FROM_WIDTH = 15 LOAD_MORE_THREAD_NUM = 20 HookManager.register "index-mode-size-widget", <<EOS Generates the per-thread size widget for each thread. Variables: thread: The message thread to be formatted. EOS HookManager.regist...
rossf7/elasticrawl
lib/elasticrawl/job.rb
Elasticrawl.Job.confirm_message
ruby
def confirm_message cluster = Cluster.new case self.type when 'Elasticrawl::ParseJob' message = segment_list else message = [] end message.push('Job configuration') message.push(self.job_desc) message.push('') message.push(cluster.cluster_desc) ...
Displays a confirmation message showing the configuration of the Elastic MapReduce job flow and cluster.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/job.rb#L8-L24
class Job < ActiveRecord::Base has_many :job_steps # Displays a confirmation message showing the configuration of the # Elastic MapReduce job flow and cluster. # Displays the Job Name and Elastic MapReduce Job Flow ID if the job was # launched successfully. def result_message "\nJob: ...
plexus/analects
lib/analects/encoding.rb
Analects.Encoding.ratings
ruby
def ratings(str) all_valid_cjk(str).map do |enc| [ enc, recode(enc, str).codepoints.map do |point| Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx| next 6 - idx if range.include?(point) 0 end.inject(:+) e...
Crude way to guess which encoding it is
train
https://github.com/plexus/analects/blob/3ef5c9b54b5d31fd1c3b7143f9e5e4ae40185dd9/lib/analects/encoding.rb#L34-L46
module Encoding extend self GB = ::Encoding::GB18030 BIG5 = ::Encoding::BIG5_UAO def recode(enc, str) str.force_encoding(enc).encode('UTF-8') end def from_gb(str) recode(GB, str) end def from_big5(str) recode(BIG5, str) end def valid_cjk(str) [GB,...
arvicco/win_gui
lib/win_gui/window.rb
WinGui.Window.click
ruby
def click(opts={}) control = child(opts) if control left, top, right, bottom = control.get_window_rect where = opts[:point] || opts[:where] || opts[:position] point = case where when Array where # Explicit screen coords when :r...
Emulates click of the control identified by opts (:id, :title, :class). Beware of keyboard shortcuts in button titles! So, use "&Yes" instead of just "Yes". Returns screen coordinates of click point if successful, nil if control was not found :id:: integer control id (such as IDOK, IDCANCEL, etc) :title:: window ti...
train
https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/lib/win_gui/window.rb#L114-L142
class Window def initialize(handle) @handle = handle end attr_reader :handle class << self # Looks up window handle using code specified in attached block (either with or without :timeout). # Returns either Window instance (for a found handle) or nil if nothing found. # Priv...
Danieth/rb_maxima
lib/maxima/histogram.rb
Maxima.Histogram.to_percentage
ruby
def to_percentage() @to_percentage ||= begin sum = points.sum(&:last) Histogram.new( points.map do |(x,y)| [ x, y.fdiv(sum) ] end ) end end
PDF
train
https://github.com/Danieth/rb_maxima/blob/21ac2ecb2bd55a7f653ef23d7ff59f4067efdca2/lib/maxima/histogram.rb#L48-L61
class Histogram < Unit attr_accessor :points def self.between(min, max, function = ->(x) { x }, steps = 100) Histogram.new( *[].tap do |points| (min..max).step((max - min).fdiv(steps)).each do |x| points.push([x, function.call(x)]) end end ) end...
ebfjunior/juno-report
lib/juno-report/pdf.rb
JunoReport.Pdf.initialize_footer_values
ruby
def initialize_footer_values @sections[:body][:settings][:groups].each do |group| current_footer = {} @sections[:groups][group.to_sym][:footer].each { |field, settings| current_footer[field] = nil } unless @sections[:groups][group.to_sym][:footer].nil? @footer...
Create a structure to calculate the footer values for all groups. Appends the footer body to total values too.
train
https://github.com/ebfjunior/juno-report/blob/139f2a1733e0d7a68160b338cc1a4645f05d5953/lib/juno-report/pdf.rb#L197-L207
module Pdf #Responsible for generate a report, based on rules passed as parameter in Juno::Report::generate. #Juno Reports has support groups, just by especifying them at the rules file. #Receives a collection as parameter, which should be a Array of records of the report. def gener...
Plasmarobo/simpleoutput
lib/simpleoutput.rb
SimpleOutput.SimpleOutputPlugin.get_data_as_points
ruby
def get_data_as_points series_data = {} @x.each_pair do |(key, x_series)| #For each series of data y_series = @y[key] series_data[key] = [] x_series.each_with_index do |x_line, index| #For each line series_data[key...
Internal Helpers
train
https://github.com/Plasmarobo/simpleoutput/blob/bbb572355348239dea35eb364f1bf5fa7bd638fd/lib/simpleoutput.rb#L163-L181
class SimpleOutputPlugin def initialize() @x = {} @y = {} @series_names = {} @data_id = 0 @annotations = {} @current_name = "NameError" @series_id = 0 @metadata = {} end #Virtual Functions def options_callback(options) ...
xi-livecode/xi
lib/xi/pattern.rb
Xi.Pattern.each
ruby
def each return enum_for(__method__) unless block_given? each_event { |v, _, _, i| break if i > 0 yield v } end
Calls the given block once for each value in source @example Pattern.new([1, 2, 3]).each.to_a # => [1, 2, 3] @return [Enumerator] @yield [Object] value
train
https://github.com/xi-livecode/xi/blob/215dfb84899b3dd00f11089ae3eab0febf498e95/lib/xi/pattern.rb#L241-L248
class Pattern extend Generators include Transforms # Array or Proc that produces values or events attr_reader :source # Event delta in terms of cycles (default: 1) attr_reader :delta # Hash that contains metadata related to pattern usage attr_reader :metadata # Size of pattern...
forward3d/rbhive
lib/rbhive/t_c_l_i_connection.rb
RBHive.TCLIConnection.async_execute
ruby
def async_execute(query) @logger.info("Executing query asynchronously: #{query}") exec_result = @client.ExecuteStatement( Hive2::Thrift::TExecuteStatementReq.new( sessionHandle: @session.sessionHandle, statement: query, runAsync: true ) ) raise_error...
Async execute
train
https://github.com/forward3d/rbhive/blob/a630b57332f2face03501da3ecad2905c78056fa/lib/rbhive/t_c_l_i_connection.rb#L193-L211
class TCLIConnection attr_reader :client def initialize(server, port = 10_000, options = {}, logger = StdOutLogger.new) options ||= {} # backwards compatibility raise "'options' parameter must be a hash" unless options.is_a?(Hash) if options[:transport] == :sasl and options[:sasl_par...
state-machines/state_machines
lib/state_machines/machine.rb
StateMachines.Machine.transition
ruby
def transition(options) raise ArgumentError, 'Must specify :on event' unless options[:on] branches = [] options = options.dup event(*Array(options.delete(:on))) { branches << transition(options) } branches.length == 1 ? branches.first : branches end
Creates a new transition that determines what to change the current state to when an event fires. == Defining transitions The options for a new transition uses the Hash syntax to map beginning states to ending states. For example, transition :parked => :idling, :idling => :first_gear, :on => :ignite In thi...
train
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1426-L1434
class Machine include EvalHelpers include MatcherHelpers class << self # Attempts to find or create a state machine for the given class. For # example, # # StateMachines::Machine.find_or_create(Vehicle) # StateMachines::Machine.find_or_create(Vehicle, :initial => :par...
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.save_alert
ruby
def save_alert(email, type, template, _when = nil, options = {}) data = options data[:email] = email data[:type] = type data[:template] = template if (type == 'weekly' || type == 'daily') data[:when] = _when end api_post(:alert, data) end
params email, String type, String template, String _when, String options, hash Add a new alert to a user. You can add either a realtime or a summary alert (daily/weekly). _when is only required when alert type is weekly or daily
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L566-L575
class Client DEFAULT_API_URI = 'https://api.sailthru.com' include Helpers attr_accessor :verify_ssl # params: # api_key, String # secret, String # api_uri, String # # Instantiate a new client; constructor optionally takes overrides for key/secret/uri and proxy server setti...
baroquebobcat/sinatra-twitter-oauth
lib/sinatra-twitter-oauth/helpers.rb
Sinatra::TwitterOAuth.Helpers.redirect_to_twitter_auth_url
ruby
def redirect_to_twitter_auth_url request_token = get_request_token session[:request_token] = request_token.token session[:request_token_secret]= request_token.secret redirect request_token.authorize_url.gsub('authorize','authenticate') end
gets the request token and redirects to twitter's OAuth endpoint
train
https://github.com/baroquebobcat/sinatra-twitter-oauth/blob/8e11cc2a223a45b7c09152a492c48387f86cca2f/lib/sinatra-twitter-oauth/helpers.rb#L57-L64
module Helpers # The current logged in user def user @user end # Redirects to login unless there is an authenticated user def login_required setup_client @user = ::TwitterOAuth::User.new(@client, session[:user]) if session[:user] @rate_limit_status =...
rmagick/rmagick
lib/rvg/rvg.rb
Magick.RVG.background_image=
ruby
def background_image=(bg_image) warn 'background_image= has no effect in nested RVG objects' if @nested raise ArgumentError, "background image must be an Image (got #{bg_image.class})" if bg_image && !bg_image.is_a?(Magick::Image) @background_image = bg_image end
Sets an image to use as the canvas background. See background_position= for layout options.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rvg/rvg.rb#L140-L145
class RVG include Stylable include Transformable include Stretchable include Embellishable include Describable include Duplicatable private # background_fill defaults to 'none'. If background_fill has been set to something # else, combine it with the background_fill_opacity. ...
oleganza/btcruby
lib/btcruby/proof_of_work.rb
BTC.ProofOfWork.bits_from_target
ruby
def bits_from_target(target) exponent = 3 signed = (target < 0) target = -target if signed while target > 0x7fffff target >>= 8 exponent += 1 end # The 0x00800000 bit denotes the sign. # Thus, if it is already set, divide the mantissa by 256 and increase the exp...
Note on Satoshi Compact format (used for 'bits' value). The "compact" format is a representation of a whole number N using an unsigned 32bit number similar to a floating point format. The most significant 8 bits are the unsigned exponent of base 256. This exponent can be thought of as "number of bytes of N". The...
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/proof_of_work.rb#L32-L49
module ProofOfWork extend self MAX_TARGET_MAINNET = 0x00000000ffff0000000000000000000000000000000000000000000000000000 MAX_TARGET_TESTNET = 0x00000007fff80000000000000000000000000000000000000000000000000000 # Note on Satoshi Compact format (used for 'bits' value). # # The "compact" format is...
tubedude/xirr
lib/xirr/bisection.rb
Xirr.Bisection.xirr
ruby
def xirr(midpoint, options) # Initial values left = [BigDecimal.new(-0.99999999, Xirr::PRECISION), cf.irr_guess].min right = [BigDecimal.new(9.99999999, Xirr::PRECISION), cf.irr_guess + 1].max @original_right = right midpoint ||= cf.irr_guess midpoint, runs = loop_rates(left, midp...
Calculates yearly Internal Rate of Return @return [BigDecimal] @param midpoint [Float] An initial guess rate will override the {Cashflow#irr_guess}
train
https://github.com/tubedude/xirr/blob/e8488a95b217c463d54a5d311ce02a9474f22f7e/lib/xirr/bisection.rb#L11-L23
class Bisection include Base # Calculates yearly Internal Rate of Return # @return [BigDecimal] # @param midpoint [Float] # An initial guess rate will override the {Cashflow#irr_guess} private # @param midpoint [BigDecimal] # @return [Boolean] # Checks if result is the right l...
dagrz/nba_stats
lib/nba_stats/stats/draft_combine_spot_shooting.rb
NbaStats.DraftCombineSpotShooting.draft_combine_spot_shooting
ruby
def draft_combine_spot_shooting( season_year, league_id=NbaStats::Constants::LEAGUE_ID_NBA ) NbaStats::Resources::DraftCombineSpotShooting.new( get(DRAFT_COMBINE_SPOT_SHOOTING_PATH, { :LeagueID => league_id, :SeasonYear => season_year }) ) ...
Calls the draftcombinespotshooting API and returns a DraftCombineSpotShooting resource. @param season_year [String] @param league_id [String] @return [NbaStats::Resources::DraftCombineSpotShooting]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/draft_combine_spot_shooting.rb#L15-L25
module DraftCombineSpotShooting # The path of the draftcombinespotshooting API DRAFT_COMBINE_SPOT_SHOOTING_PATH = '/stats/draftcombinespotshooting' # Calls the draftcombinespotshooting API and returns a DraftCombineSpotShooting resource. # # @param season_year [String] # @param league_id [...
oleganza/btcruby
lib/btcruby/proof_of_work.rb
BTC.ProofOfWork.target_from_bits
ruby
def target_from_bits(bits) exponent = ((bits >> 24) & 0xff) mantissa = bits & 0x7fffff mantissa *= -1 if (bits & 0x800000) > 0 (mantissa * (256**(exponent-3))).to_i end
Converts 32-bit compact representation to a 256-bit integer. int32 -> bigint
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/proof_of_work.rb#L53-L58
module ProofOfWork extend self MAX_TARGET_MAINNET = 0x00000000ffff0000000000000000000000000000000000000000000000000000 MAX_TARGET_TESTNET = 0x00000007fff80000000000000000000000000000000000000000000000000000 # Note on Satoshi Compact format (used for 'bits' value). # # The "compact" format is...
murb/workbook
lib/workbook/row.rb
Workbook.Row.[]=
ruby
def []= index_or_hash, value index = index_or_hash if index_or_hash.is_a? Symbol index = table_header_keys.index(index_or_hash) elsif index_or_hash.is_a? String and index_or_hash.match(/^[A-Z]*$/) # it looks like a column indicator index = Workbook::Column.alpha_index_to_number...
Overrides normal Array's []=-function with support for symbols that identify a column based on the header-values @example Lookup using fixnum or header value encoded as symbol (strings are converted to symbols) row[1] #=> <Cell value="a"> row[:a] #=> <Cell value="a"> @param [Fixnum, Symbol, String] index_or_h...
train
https://github.com/murb/workbook/blob/2e12f43c882b7c235455192a2fc48183fe6ec965/lib/workbook/row.rb#L136-L160
class Row < Array include Workbook::Modules::Cache alias_method :compare_without_header, :<=> attr_accessor :placeholder # The placeholder attribute is used in compares (corresponds to newly created or removed lines (depending which side you're on) attr_accessor :format # Initialize a new ro...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.Draw.pattern
ruby
def pattern(name, x, y, width, height) push('defs') push("pattern #{name} #{x} #{y} #{width} #{height}") push('graphic-context') yield ensure pop('graphic-context') pop('pattern') pop('defs') end
Define a pattern. In the block, call primitive methods to draw the pattern. Reference the pattern by using its name as the argument to the 'fill' or 'stroke' methods
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L435-L444
class Draw # Thse hashes are used to map Magick constant # values to the strings used in the primitives. ALIGN_TYPE_NAMES = { LeftAlign.to_i => 'left', RightAlign.to_i => 'right', CenterAlign.to_i => 'center' }.freeze ANCHOR_TYPE_NAMES = { StartAnchor.to_i => 'start', ...
sup-heliotrope/sup
lib/sup/interactive_lock.rb
Redwood.InteractiveLock.lock_interactively
ruby
def lock_interactively stream=$stderr begin Index.lock rescue Index::LockError => e begin Process.kill 0, e.pid.to_i # 0 signal test the existence of PID stream.puts <<EOS Error: the index is locked by another process! User '#{e.user}' on host '#{e.host}' is running #{e.pname} wi...
seconds
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/interactive_lock.rb#L24-L86
module InteractiveLock def pluralize number_of, kind; "#{number_of} #{kind}" + (number_of == 1 ? "" : "s") end def time_ago_in_words time secs = (Time.now - time).to_i mins = secs / 60 time = if mins == 0 pluralize secs, "second" else pluralize mins, "minute" end end DELAY = 5 ...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.view
ruby
def view pager = ENV['PAGER'] || 'less' execute_external_command do unless in_zip? system %Q[#{pager} "#{current_item.path}"] else begin tmpdir, tmpfile_name = nil Zip::File.open(current_zip) do |zip| tmpdir = Dir.mktmpdir ...
Open current file or directory with the viewer.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L708-L728
class Controller include Rfd::Commands attr_reader :header_l, :header_r, :main, :command_line, :items, :displayed_items, :current_row, :current_page, :current_dir, :current_zip # :nodoc: def initialize @main = MainWindow.new @header_l = HeaderLeftWindow.new @header_r = HeaderRightW...
interagent/committee
lib/committee/drivers/open_api_2.rb
Committee::Drivers.OpenAPI2.parse
ruby
def parse(data) REQUIRED_FIELDS.each do |field| if !data[field] raise ArgumentError, "Committee: no #{field} section in spec data." end end if data['swagger'] != '2.0' raise ArgumentError, "Committee: driver requires OpenAPI 2.0." end schema = Schema.new...
Parses an API schema and builds a set of route definitions for use with Committee. The expected input format is a data hash with keys as strings (as opposed to symbols) like the kind produced by JSON.parse or YAML.load.
train
https://github.com/interagent/committee/blob/810fadcea1bc1c529627d47325c1008b5c33b0a4/lib/committee/drivers/open_api_2.rb#L41-L68
class OpenAPI2 < Committee::Drivers::Driver def default_coerce_date_times false end # Whether parameters that were form-encoded will be coerced by default. def default_coerce_form_params true end def default_allow_get_body true end # Whether parameters in a request...