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
wied03/opal-factory_girl
opal/opal/active_support/inflector/methods.rb
ActiveSupport.Inflector.titleize
ruby
def titleize(word) # negative lookbehind doesn't work in Firefox / Safari # humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize } humanized = humanize(underscore(word)) humanized.reverse.gsub(/[a-z](?!['’`])\b/) { |match| match.capitalize }.reverse end
Capitalizes all the words and replaces some characters in the string to create a nicer looking title. +titleize+ is meant for creating pretty output. It is not used in the Rails internals. +titleize+ is also aliased as +titlecase+. titleize('man from the boondocks') # => "Man From The Boondocks" titleize('...
train
https://github.com/wied03/opal-factory_girl/blob/697114a8c63f4cba38b84d27d1f7b823c8d0bb38/opal/opal/active_support/inflector/methods.rb#L160-L165
module Inflector extend self # Returns the plural form of the word in the string. # # If passed an optional +locale+ parameter, the word will be # pluralized using rules defined for that language. By default, # this parameter is set to <tt>:en</tt>. # # pluralize('post') ...
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/teams.rb
BitBucket.Teams.followers
ruby
def followers(team_name) response = get_request("/2.0/teams/#{team_name.to_s}/followers") return response["values"] unless block_given? response["values"].each { |el| yield el } end
List followers of the provided team = Examples bitbucket = BitBucket.new :oauth_token => '...', :oauth_secret => '...' bitbucket.teams.followers(:team_name_here) bitbucket.teams.followers(:team_name_here) { |follower| ... }
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/teams.rb#L54-L58
class Teams < API extend AutoloadHelper def initialize(options = { }) super(options) end # List teams for the authenticated user where the user has the provided role # Roles are :admin, :contributor, :member # # = Examples # bitbucket = BitBucket.new :oauth_token => '...', :o...
senchalabs/jsduck
lib/jsduck/news.rb
JsDuck.News.filter_new_members
ruby
def filter_new_members(cls) members = cls.all_local_members.find_all do |m| visible?(m) && (m[:new] || new_params?(m)) end members = discard_accessors(members) members.sort! {|a, b| a[:name] <=> b[:name] } end
Returns all members of a class that have been marked as new, or have parameters marked as new.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/news.rb#L68-L74
class News # Creates News object from relations data when --import option # specified. def self.create(relations, doc_formatter, opts) if opts.import.length > 0 News.new(relations, doc_formatter) else Util::NullObject.new(:to_html => "") end end # Generates list ...
rossf7/elasticrawl
lib/elasticrawl/config.rb
Elasticrawl.Config.load_config
ruby
def load_config(config_file) if dir_exists? begin config_file = File.join(config_dir, "#{config_file}.yml") config = YAML::load(File.open(config_file)) rescue StandardError => e raise FileAccessError, e.message end else raise ConfigDirMissingErr...
Loads a YAML configuration file.
train
https://github.com/rossf7/elasticrawl/blob/db70bb6819c86805869f389daf1920f3acc87cef/lib/elasticrawl/config.rb#L57-L69
class Config CONFIG_DIR = '.elasticrawl' DATABASE_FILE = 'elasticrawl.sqlite3' TEMPLATES_DIR = '../../templates' TEMPLATE_FILES = ['aws.yml', 'cluster.yml', 'jobs.yml'] attr_reader :access_key_id attr_reader :secret_access_key # Sets the AWS access credentials needed for the S3 and EMR A...
tarcieri/cool.io
lib/cool.io/meta.rb
Coolio.Meta.watcher_delegate
ruby
def watcher_delegate(proxy_var) %w{attach attached? detach enable disable}.each do |method| module_eval <<-EOD def #{method}(*args) if defined? #{proxy_var} and #{proxy_var} #{proxy_var}.#{method}(*args) return self end super ...
Use an alternate watcher with the attach/detach/enable/disable methods if it is presently assigned. This is useful if you are waiting for an event to occur before the current watcher can be used in earnest, such as making an outgoing TCP connection.
train
https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/meta.rb#L13-L26
module Meta # Use an alternate watcher with the attach/detach/enable/disable methods # if it is presently assigned. This is useful if you are waiting for # an event to occur before the current watcher can be used in earnest, # such as making an outgoing TCP connection. # Define callbacks whose ...
dennisreimann/masq
app/controllers/masq/server_controller.rb
Masq.ServerController.decide
ruby
def decide @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root) @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request end
Displays the decision page on that the user can confirm the request and choose which data should be transfered to the relying party.
train
https://github.com/dennisreimann/masq/blob/bc6b6d84fe06811b9de19e7863c53c6bfad201fe/app/controllers/masq/server_controller.rb#L64-L67
class ServerController < BaseController # CSRF-protection must be skipped, because incoming # OpenID requests lack an authenticity token skip_before_filter :verify_authenticity_token # Error handling rescue_from OpenID::Server::ProtocolError, :with => :render_openid_error # Actions other than ...
arvicco/win_gui
old_code/lib/win_gui/def_api.rb
WinGui.DefApi.def_api
ruby
def def_api(function, params, returns, options={}, &define_block) name, aliases = generate_names(function, options) boolean = options[:boolean] zeronil = options[:zeronil] proto = params.respond_to?(:join) ? params.join : params # Convert params into prototype string api = Win32::API.new(f...
Defines new method wrappers for Windows API function call: - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) - Defines method with snake_case name (converted from CamelCase function name) with enhanced API signature When the defined wrapper metho...
train
https://github.com/arvicco/win_gui/blob/a3a4c18db2391144fcb535e4be2f0fb47e9dcec7/old_code/lib/win_gui/def_api.rb#L36-L56
module DefApi # DLL to use with API decarations by default ('user32') DEFAULT_DLL = 'user32' ## # Defines new method wrappers for Windows API function call: # - Defines method with original (CamelCase) API function name and original signature (matches MSDN description) # - Defines method ...
sup-heliotrope/sup
lib/sup/index.rb
Redwood.Index.parse_query
ruby
def parse_query s query = {} subs = HookManager.run("custom-search", :subs => s) || s begin subs = SearchManager.expand subs rescue SearchManager::ExpansionError => e raise ParseError, e.message end subs = subs.gsub(/\b(to|from):(\S+)\b/) do field, value = $1, $2 email_f...
parse a query string from the user. returns a query object that can be passed to any index method with a 'query' argument. raises a ParseError if something went wrong.
train
https://github.com/sup-heliotrope/sup/blob/36f95462e3014c354c577d63a78ba030c4b84474/lib/sup/index.rb#L405-L548
class Index include InteractiveLock INDEX_VERSION = '4' ## dates are converted to integers for xapian, and are used for document ids, ## so we must ensure they're reasonably valid. this typically only affect ## spam. MIN_DATE = Time.at 0 MAX_DATE = Time.at(2**31-1) HookManager.register "custom-search...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.method_missing
ruby
def method_missing(meth_id, *args, &block) if @scene @images[@scene].send(meth_id, *args, &block) else super end rescue NoMethodError Kernel.raise NoMethodError, "undefined method `#{meth_id.id2name}' for #{self.class}" rescue Exception $ERROR_POSITION.delete_if { |...
The ImageList class supports the Magick::Image class methods by simply sending the method to the current image. If the method isn't explicitly supported, send it to the current image in the array. If there are no images, send it up the line. Catch a NameError and emit a useful message.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1603-L1614
class ImageList include Comparable include Enumerable attr_reader :scene private def get_current @images[@scene].__id__ rescue StandardError nil end protected def is_an_image(obj) Kernel.raise ArgumentError, "Magick::Image required (#{obj.class} given)" unless...
documentcloud/jammit
lib/jammit/helper.rb
Jammit.Helper.tags_with_options
ruby
def tags_with_options(packages, options) packages.dup.map {|package| yield package }.flatten.map {|package| stylesheet_link_tag package, options }.join("\n") end
Generate the stylesheet tags for a batch of packages, with options, by yielding each package to a block.
train
https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/helper.rb#L76-L82
module Helper DATA_URI_START = "<!--[if (!IE)|(gte IE 8)]><!-->" unless defined?(DATA_URI_START) DATA_URI_END = "<!--<![endif]-->" unless defined?(DATA_URI_END) MHTML_START = "<!--[if lte IE 7]>" unless defined?(MHTML_START) MHTML_END = "<![endif]-->" ...
quixoten/queue_to_the_future
lib/queue_to_the_future/job.rb
QueueToTheFuture.Job.method_missing
ruby
def method_missing(*args, &block) Thread.pass until defined?(@result) case @result when Exception def self.method_missing(*args, &block); raise @result; end else def self.method_missing(*args, &block); @result.send(*args, &block); end end self.method_mis...
Allows the job to behave as the return value of the block. Accessing any method on the job will cause code to block until the job is completed.
train
https://github.com/quixoten/queue_to_the_future/blob/dd8260fa165ee42b95e6d76bc665fdf68339dfd6/lib/queue_to_the_future/job.rb#L34-L45
class Job instance_methods.each { |meth| undef_method(meth) unless %w(__send__ __id__ object_id inspect).include?(meth.to_s) } # Creates a job and schedules it by calling {Coordinator#schedule}. # # @param [List] *args The list of arguments to pass to the given block # @param [Proc] &block Th...
simplymadeapps/simple_scheduler
lib/simple_scheduler/task.rb
SimpleScheduler.Task.future_run_times
ruby
def future_run_times future_run_times = existing_run_times.dup last_run_time = future_run_times.last || at - frequency last_run_time = last_run_time.in_time_zone(time_zone) # Ensure there are at least two future jobs scheduled and that the queue ahead time is filled while future_run_times...
Returns an array Time objects for future run times based on the current time and the given minutes to look ahead. @return [Array<Time>] rubocop:disable Metrics/AbcSize
train
https://github.com/simplymadeapps/simple_scheduler/blob/4d186042507c1397ee79a5e8fe929cc14008c026/lib/simple_scheduler/task.rb#L67-L82
class Task attr_reader :job_class, :params DEFAULT_QUEUE_AHEAD_MINUTES = 360 # Initializes a task by parsing the params so the task can be queued in the future. # @param params [Hash] # @option params [String] :class The class of the Active Job or Sidekiq Worker # @option params [String] :ev...
SamSaffron/message_bus
lib/message_bus/http_client.rb
MessageBus.HTTPClient.start
ruby
def start @mutex.synchronize do return if started? @status = STARTED thread = Thread.new do begin while started? unless @channels.empty? poll @stats.success += 1 @stats.failed = 0 end ...
@param base_url [String] Base URL of the message_bus server to connect to @param enable_long_polling [Boolean] Enable long polling @param enable_chunked_encoding [Boolean] Enable chunk encoding @param min_poll_interval [Float, Integer] Min poll interval when long polling in seconds @param max_poll_interval [Float, ...
train
https://github.com/SamSaffron/message_bus/blob/90fba639eb5d332ca8e87fd35f1d603a5743076d/lib/message_bus/http_client.rb#L96-L127
class HTTPClient class InvalidChannel < StandardError; end class MissingBlock < StandardError; end attr_reader :channels, :stats attr_accessor :enable_long_polling, :status, :enable_chunked_encoding, :min_poll_interval, ...
bitbucket-rest-api/bitbucket
lib/bitbucket_rest_api/issues/components.rb
BitBucket.Issues::Components.get
ruby
def get(user_name, repo_name, component_id, params={}) _update_user_repo_params(user_name, repo_name) _validate_user_repo_params(user, repo) unless user? && repo? _validate_presence_of component_id normalize! params get_request("/1.0/repositories/#{user}/#{repo.downcase}/issues/components...
Get a single component = Examples bitbucket = BitBucket.new bitbucket.issues.components.find 'user-name', 'repo-name', 'component-id'
train
https://github.com/bitbucket-rest-api/bitbucket/blob/e03b6935104d59b3d9a922474c3dc210a5ef76d2/lib/bitbucket_rest_api/issues/components.rb#L36-L43
class Issues::Components < API VALID_COMPONENT_INPUTS = %w[ name ].freeze # Creates new Issues::Components API def initialize(options = {}) super(options) end # List all components for a repository # # = Examples # bitbucket = BitBucket.new :user => 'user-name', :repo => 'repo...
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.Task.add_trial
ruby
def add_trial(trial) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'trial'), trial.key) end
Public: Add a trial of the task.
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L640-L643
class Task attr_reader :key def initialize(task_key) @key = task_key end def self.create(taskset, estimate_sec, spec_file) task_key = RRRSpec.make_key(taskset.key, 'task', spec_file) RRRSpec.redis.hmset( task_key, 'taskset', taskset.key, 'estimate_sec', esti...
ImpressCMS/vagrant-impressbox
lib/vagrant-impressbox/provisioner.rb
Impressbox.Provisioner.xaml_config
ruby
def xaml_config require_relative File.join('objects', 'config_file') file = detect_file(config.file) @machine.ui.info "\t" + I18n.t('config.loaded_from_file', file: file) Impressbox::Objects::ConfigFile.new file end
Loads xaml config @return [::Impressbox::Objects::ConfigFile]
train
https://github.com/ImpressCMS/vagrant-impressbox/blob/78dcd119a15ea6fbfd1f28c1e78f1cbf371bc6a2/lib/vagrant-impressbox/provisioner.rb#L81-L86
class Provisioner < Vagrant.plugin('2', :provisioner) # Stores loaded ConfigFile instance # #@return [::Impressbox::Objects::ConfigFile,nil] @@__loaded_config = nil # Object with loaded config from file # #@return [::Impressbox::Objects::ConfigFile,nil] def self.loaded_config @...
grpc/grpc
src/ruby/lib/grpc/generic/client_stub.rb
GRPC.ClientStub.request_response
ruby
def request_response(method, req, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}) c = new_active_call(method, marshal, unmarshal, ...
Creates a new ClientStub. Minimally, a stub is created with the just the host of the gRPC service it wishes to access, e.g., my_stub = ClientStub.new(example.host.com:50505, :this_channel_is_insecure) If a channel_override argument is passed, it will be used as the underlying chann...
train
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/client_stub.rb#L148-L181
class ClientStub include Core::StatusCodes include Core::TimeConsts # Default timeout is infinity. DEFAULT_TIMEOUT = INFINITE_FUTURE # setup_channel is used by #initialize to constuct a channel from its # arguments. def self.setup_channel(alt_chan, host, creds, channel_args = {}) u...
CocoaPods/Xcodeproj
lib/xcodeproj/workspace.rb
Xcodeproj.Workspace.save_as
ruby
def save_as(path) FileUtils.mkdir_p(path) File.open(File.join(path, 'contents.xcworkspacedata'), 'w') do |out| out << to_s end end
Saves the workspace at the given `xcworkspace` path. @param [String] path the path where to save the project. @return [void]
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/workspace.rb#L179-L184
class Workspace # @return [REXML::Document] the parsed XML model for the workspace contents attr_reader :document # @return [Hash<String => String>] a mapping from scheme name to project full path # containing the scheme attr_reader :schemes # @return [Array<FileReference>] the paths...
puppetlabs/beaker-aws
lib/beaker/hypervisor/aws_sdk.rb
Beaker.AwsSdk.create_group
ruby
def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0']) name = group_id(ports) @logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}") @logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}") cl = region_or_vpc.is_a?(String) ? client(regio...
Create a new security group Accepts a region or VPC for group creation. @param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or 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::EC...
train
https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1068-L1094
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...
phatworx/rails_paginate
lib/rails_paginate/renderers/base.rb
RailsPaginate::Renderers.Base.link_to_page
ruby
def link_to_page(page, key, link_options = {}) css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}" if key.nil? content_tag :span, "..", :class => "spacer" elsif page.nil? content_tag :span, t(key), :class => "#{css_class} unavailable" else link_...
link to page with i18n support
train
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/base.rb#L30-L39
class Base attr_reader :view, :collection, :options, :pager # setup rails_paginate collection def initialize(view, collection, pager, options = {}) raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless collection.is_a? RailsPaginate::Collection raise ArgumentError, ...
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.WorkerLog.to_h
ruby
def to_h h = RRRSpec.redis.hgetall(key) h['key'] = key h['log'] = log h['worker'] = { 'key' => h['worker'] } h['taskset'] = { 'key' => h['taskset'] } RRRSpec.convert_if_present(h, 'started_at') { |v| Time.zone.parse(v) } RRRSpec.convert_if_present(h, 'rsync_finished_at') { |v| ...
========================================================================== Serialize
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L553-L564
class WorkerLog attr_reader :key def initialize(worker_log_key) @key = worker_log_key end # Public: Create a new worker_log. # This method will call Taskset#add_worker_log def self.create(worker, taskset) worker_log_key = RRRSpec.make_key(taskset.key, worker.key) RRRSpec.re...
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write_str
ruby
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_line...
Write out a simple string with no embedded new-lines.
train
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L34-L50
class OutputPager # Set up the initial values. def initialize(options={}) @options = options @lines = 0 @chars = 0 end # Write out a general string with page pauses. def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unle...
oleganza/btcruby
lib/btcruby/open_assets/asset_transaction_builder.rb
BTC.AssetTransactionBuilder.validate_bitcoin_change_address!
ruby
def validate_bitcoin_change_address! addr = self.bitcoin_change_address raise ArgumentError, "Missing bitcoin_change_address" if !addr raise ArgumentError, "bitcoin_change_address must be an instance of BTC::Address" if !addr.is_a?(Address) raise ArgumentError, "bitcoin_change_address must not b...
Validation Methods
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_transaction_builder.rb#L379-L384
class AssetTransactionBuilder # Network to validate provided addresses against. # Default value is `Network.default`. attr_accessor :network # Must be a subclass of a BTC::BitcoinPaymentAddress attr_accessor :bitcoin_change_address # Must be a subclass of a BTC::AssetAddress attr_access...
metanorma/isodoc
lib/isodoc/function/i18n.rb
IsoDoc::Function.I18n.eref_localities1_zh
ruby
def eref_localities1_zh(target, type, from, to) ret = ", 第#{from.text}" if from ret += "&ndash;#{to}" if to loc = (@locality[type] || type.sub(/^locality:/, "").capitalize ) ret += " #{loc}" ret end
TODO: move to localization file
train
https://github.com/metanorma/isodoc/blob/b8b51a28f9aecb7ce3ec1028317e94d0d623036a/lib/isodoc/function/i18n.rb#L79-L85
module I18n def load_yaml(lang, script) if @i18nyaml then YAML.load_file(@i18nyaml) elsif lang == "en" YAML.load_file(File.join(File.dirname(__FILE__), "../../isodoc-yaml/i18n-en.yaml")) elsif lang == "fr" YAML.load_file(File.join(File.dirname(__F...
ynab/ynab-sdk-ruby
lib/ynab/models/account.rb
YNAB.Account.valid?
ruby
def valid? return false if @id.nil? return false if @name.nil? return false if @type.nil? type_validator = EnumAttributeValidator.new('String', ['checking', 'savings', 'cash', 'creditCard', 'lineOfCredit', 'otherAsset', 'otherLiability', 'payPal', 'merchantAccount', 'investmentAccount', 'mortgag...
Check to see if the all the properties in the model are valid @return true if the model is valid
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/models/account.rb#L209-L224
class Account attr_accessor :id attr_accessor :name # The type of account. Note: payPal, merchantAccount, investmentAccount, and mortgage types have been deprecated and will be removed in the future. attr_accessor :type # Whether this account is on budget or not attr_accessor :on_budget ...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.draw_total_items
ruby
def draw_total_items header_r.draw_total_items count: items.size, size: items.inject(0) {|sum, i| sum += i.size} end
Update the header information concerning total files and directories in the current directory.
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L616-L618
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...
moneta-rb/moneta
lib/moneta/builder.rb
Moneta.Builder.build
ruby
def build adapter = @proxies.first if Array === adapter klass, options, block = adapter adapter = new_proxy(klass, options, &block) check_arity(klass, adapter, 1) end @proxies[1..-1].inject([adapter]) do |result, proxy| klass, options, block = proxy proxy ...
@yieldparam Builder dsl code block Build proxy stack @return [Object] Generated Moneta proxy stack @api public
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/builder.rb#L16-L29
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 # Add pro...
dagrz/nba_stats
lib/nba_stats/stats/team_year_by_year_stats.rb
NbaStats.TeamYearByYearStats.team_year_by_year_stats
ruby
def team_year_by_year_stats( team_id, season, per_mode=NbaStats::Constants::PER_MODE_TOTALS, season_type=NbaStats::Constants::SEASON_TYPE_REGULAR, league_id=NbaStats::Constants::LEAGUE_ID_NBA ) NbaStats::Resources::TeamYearByYearStats.new( get(TEAM_YEAR_BY_YEA...
Calls the teamyearbyyearstats API and returns a TeamYearByYearStats resource. @param team_id [Integer] @param season [String] @param per_mode [String] @param season_type [String] @param league_id [String] @return [NbaStats::Resources::TeamYearByYearStats]
train
https://github.com/dagrz/nba_stats/blob/d6fe6cf81f74a2ce7a054aeec5e9db59a6ec42aa/lib/nba_stats/stats/team_year_by_year_stats.rb#L18-L34
module TeamYearByYearStats # The path of the teamyearbyyearstats API TEAM_YEAR_BY_YEAR_STATS_PATH = '/stats/teamyearbyyearstats' # Calls the teamyearbyyearstats API and returns a TeamYearByYearStats resource. # # @param team_id [Integer] # @param season [String] # @param per_mode [Stri...
sunspot/sunspot
sunspot/lib/sunspot/schema.rb
Sunspot.Schema.variant_combinations
ruby
def variant_combinations combinations = [] 0.upto(2 ** FIELD_VARIANTS.length - 1) do |b| combinations << combination = [] FIELD_VARIANTS.each_with_index do |variant, i| combination << variant if b & 1<<i > 0 end end combinations end
All of the possible combinations of variants
train
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/schema.rb#L108-L117
class Schema #:nodoc:all FieldType = Struct.new(:name, :class_name, :suffix) FieldVariant = Struct.new(:attribute, :suffix) DEFAULT_TOKENIZER = 'solr.StandardTokenizerFactory' DEFAULT_FILTERS = %w(solr.StandardFilterFactory solr.LowerCaseFilterFactory) FIELD_TYPES = [ FieldType.new('boolea...
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.workdir=
ruby
def workdir=(dir) workdir = GitLib.find_workdir(dir) if workdir.nil? @workdir = dir logger.info { "Initializing new repository at #{dir}" } return command(:init) else @workdir = workdir logger.debug { "Opening existing repository at #{dir}" } end end
Sets the working directory to use for the (non-bare) repository. If the directory is *not* part of an existing repository, a new repository is created. (i.e., "git init") @param [Dir] dir the working directory @return [void]
train
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L98-L108
class GitLib # @param [Dir] dir the work dir # @param [Hash] logging_opts see {log_level} def initialize(dir, logging_opts) self.log_level = GitLib.log_level(logging_opts) self.workdir = dir end # @return [GitLogger] the logger to use def logger if @logger.nil? @lo...
CocoaPods/Xcodeproj
lib/xcodeproj/project.rb
Xcodeproj.Project.save
ruby
def save(save_path = nil) save_path ||= path @dirty = false if save_path == path FileUtils.mkdir_p(save_path) file = File.join(save_path, 'project.pbxproj') Atomos.atomic_write(file) do |f| Nanaimo::Writer::PBXProjWriter.new(to_ascii_plist, :pretty => true, :output => f, :strict =>...
Serializes the project in the xcodeproj format using the path provided during initialization or the given path (`xcodeproj` file). If a path is provided file references depending on the root of the project are not updated automatically, thus clients are responsible to perform any needed modification before saving. ...
train
https://github.com/CocoaPods/Xcodeproj/blob/3be1684437a6f8e69c7836ad4c85a2b78663272f/lib/xcodeproj/project.rb#L358-L366
class Project include Object # @return [Pathname] the path of the project. # attr_reader :path # @return [Pathname] the directory of the project # attr_reader :project_dir # @param [Pathname, String] path @see path # The path provided will be expanded to an absolute pat...
treeder/quicky
lib/quicky/results_hash.rb
Quicky.ResultsHash.to_hash
ruby
def to_hash ret = {} self.each_pair do |k, v| ret[k] = v.to_hash() end ret end
returns results in a straight up hash.
train
https://github.com/treeder/quicky/blob/4ac89408c28ca04745280a4cef2db4f97ed5b6d2/lib/quicky/results_hash.rb#L6-L12
class ResultsHash < Hash # returns results in a straight up hash. # if given the same results from to_hash, this will recreate the ResultsHash def self.from_hash(h) rh = ResultsHash.new h.each_pair do |k, v| rh[k] = TimeCollector.from_hash(v) end rh end # merges...
iyuuya/jkf
lib/jkf/parser/ki2.rb
Jkf::Parser.Ki2.transform_fugou
ruby
def transform_fugou(pl, pi, sou, dou, pro, da) ret = { "piece" => pi } if pl["same"] ret["same"] = true else ret["to"] = pl end ret["promote"] = (pro == "成") if pro if da ret["relative"] = "H" else rel = soutai2relative(sou) + dousa2relative(dou)...
transfrom fugou to jkf
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/ki2.rb#L373-L388
class Ki2 < Base include Kifuable protected # kifu : header* initialboard? header* moves fork* def parse_root s0 = @current_pos s1 = [] s2 = parse_header while s2 != :failed s1 << s2 s2 = parse_header end if s1 != :failed s2 = parse_initial...
mailgun/mailgun-ruby
lib/mailgun/messages/message_builder.rb
Mailgun.MessageBuilder.add_file
ruby
def add_file(disposition, filedata, filename) attachment = File.open(filedata, 'r') if filedata.is_a?(String) attachment = filedata.dup unless attachment fail(Mailgun::ParameterError, 'Unable to access attachment file object.' ) unless attachment.respond_to?(:read) unless filenam...
Private: Adds a file to the message. @param [Symbol] disposition The type of file: :attachment or :inline @param [String|File] attachment A file object for attaching as an attachment. @param [String] filename The filename you wish the attachment to be. @return [void] Returns nothing
train
https://github.com/mailgun/mailgun-ruby/blob/265efffd51209b0170a3225bbe945b649643465a/lib/mailgun/messages/message_builder.rb#L404-L417
class MessageBuilder attr_reader :message, :counters # Public: Creates a new MessageBuilder object. def initialize @message = Hash.new { |hash, key| hash[key] = [] } @counters = { recipients: { to: 0, cc: 0, bcc: 0 }, attributes: { attachment: 0, campaign_id: 0, custom_optio...
zhimin/rwebspec
lib/rwebspec-watir/driver.rb
RWebSpec.Driver.take_screenshot
ruby
def take_screenshot(to_file = nil, opts = {}) # puts "calling new take screenshot: #{$screenshot_supported}" # unless $screenshot_supported # puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" # return # end if to_file screenshot_image_fil...
TODO: Common driver module => this is shared by both Watir and Selenium TODO: Common driver module => this is shared by both Watir and Selenium use win32screenshot library or Selenium to save curernt active window opts[:to_dir] => the direcotry to save image under
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L783-L818
module Driver include RWebSpec::TestWisePlugin include RWebSpec::Popup # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080 # # There are 3 ways to set base url # 1. pass as first argument # 2. I...
billychan/simple_activity
lib/simple_activity/models/activity.rb
SimpleActivity.Activity.update_cache
ruby
def update_cache(cache_rule) cache_rule.each do |type, type_methods| type_methods.each do |method| value = self.send(type).send(method) self.cache["#{type}_#{method}"] = value end end save end
TODO: Untested
train
https://github.com/billychan/simple_activity/blob/fd24768908393e6aeae285834902be05c7b8ce42/lib/simple_activity/models/activity.rb#L48-L56
class Activity < ActiveRecord::Base self.table_name = "simple_activity_activities" # cache can cache rule when necessary, for third party lib speeding # us processing. if Rails::VERSION::MAJOR == 3 attr_accessible :actor_type, :actor_id, :target_type, :target_id, :action_key, :display, :cache ...
postmodern/rprogram
lib/rprogram/program.rb
RProgram.Program.sudo
ruby
def sudo(*arguments) options = case arguments.last when Hash then arguments.pop else {} end task = SudoTask.new(options.delete(:sudo) || {}) task.command = [@path] + arguments arguments = task.arguments arguments << options unless...
Runs the program under sudo. @overload sudo(*arguments) Run the program under `sudo` with the given arguments. @param [Array] arguments Additional arguments to run the program with. @overload sudo(*arguments,options) Run the program under `sudo` with the given arguments and options. @param [Ar...
train
https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/program.rb#L341-L354
class Program # Path to the program attr_reader :path # Name of the program attr_reader :name # # Creates a new Program object. # # @param [String] path # The full-path of the program. # # @yield [prog] # If a block is given, it will be passed the newly created P...
senchalabs/jsduck
lib/jsduck/guides.rb
JsDuck.Guides.fix_icon
ruby
def fix_icon(dir) if File.exists?(dir+"/icon.png") # All ok elsif File.exists?(dir+"/icon-lg.png") FileUtils.mv(dir+"/icon-lg.png", dir+"/icon.png") else FileUtils.cp(@opts.template+"/resources/images/default-guide.png", dir+"/icon.png") end end
Ensures the guide dir contains icon.png. When there isn't looks for icon-lg.png and renames it to icon.png. When neither exists, copies over default icon.
train
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guides.rb#L145-L153
class Guides < GroupedAsset # Creates Guides object from filename and formatter def self.create(filename, formatter, opts) if filename Guides.new(filename, formatter, opts) else Util::NullObject.new(:to_array => [], :to_html => "", :[] => nil) end end # Parses guides...
mojombo/chronic
lib/chronic/handlers.rb
Chronic.Handlers.handle_sd_sm_sy
ruby
def handle_sd_sm_sy(tokens, options) new_tokens = [tokens[1], tokens[0], tokens[2]] time_tokens = tokens.last(tokens.size - 3) handle_sm_sd_sy(new_tokens + time_tokens, options) end
Handle scalar-day/scalar-month/scalar-year (endian little)
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L231-L235
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 = ...
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.process_job
ruby
def process_job(job, options = {}, report_email = nil, postback_url = nil, binary_key = nil) data = options data['job'] = job if !report_email.nil? data['report_email'] = report_email end if !postback_url.nil? data['postback_url'] = postback_url end api_post(:j...
params job, String options, hash report_email, String postback_url, String binary_key, String interface for making request to job call
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L595-L606
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...
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.add_udas_to_model!
ruby
def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel uda_hash.each do |attr, val| val.each do |k, v| type = Helpers.determine_type(v) if type.nil? model.attribute attr, type end end end
Add new found udas to our internal TaskModel @param uda_hash [Hash{Symbol=>Hash}] @param type [Class, nil] @param model [Models::TaskModel, Class] @api protected
train
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L325-L332
module Controller extend self # Retrieves the current task list from the TaskWarrior database. Defaults # to just show active (waiting & pending) tasks, which is usually what is # exposed to the end user through the default reports. To see everything # including completed, deleted, and parent rec...
Thermatix/ruta
lib/ruta/context.rb
Ruta.Context.component
ruby
def component id,attribs={}, &block self.elements[id] = { attributes: attribs, type: :element, content: block } end
@see #Context#handle_render define a component of the composition @param [Symbol] id of element to mount element contents to @param [{Symbol => String,Number,Boolean}] list of attributes to attach to tag @yield block containing component to be rendered to page @yieldreturn [Object] a component that will be passed...
train
https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/context.rb#L37-L43
class Context # @!attribute [r] elements # @return [{ref => { attributes: {},type: Symbol, content: Proc,Symbol}] Hash of all elements defined # @!attribute [r] ref # @return [Symbol] this contexts reference in (see #Context#collection) # @!attribute [r,w] handlers # @return [{ref => Proc}]...
ikayzo/SDL.rb
lib/sdl4r/parser.rb
SDL4R.Parser.add_tag_attributes
ruby
def add_tag_attributes(tag, tokens, start) i = start size = tokens.size while i < size token = tokens[i] if token.type != :IDENTIFIER expecting_but_got("IDENTIFIER", token.type, token.line, token.position) end name_or_namespace = token.text; ...
Add attributes to the given tag
train
https://github.com/ikayzo/SDL.rb/blob/1663b9f5aa95d8d6269f060e343c2d2fd9309259/lib/sdl4r/parser.rb#L265-L413
class Parser # Passed to parse_error() in order to specify an error that occured on no specific position # (column). UNKNOWN_POSITION = -2 # Creates an SDL parser on the specified +IO+. # # IO.open("path/to/sdl_file") { |io| # parser = SDL4R::Parser.new(io) # tags = p...
etewiah/property_web_builder
app/services/pwb/page_part_manager.rb
Pwb.PagePartManager.rebuild_page_content
ruby
def rebuild_page_content(locale) unless page_part && page_part.template raise "page_part with valid template not available" end # page_part = self.page_parts.find_by_page_part_key page_part_key if page_part.present? l_template = Liquid::Template.parse(page_part.template) ...
Will retrieve saved page_part blocks and use that along with template to rebuild page_content html
train
https://github.com/etewiah/property_web_builder/blob/fba4e6d4ffa7bc1f4d3b50dfa5a6a9fbfee23f21/app/services/pwb/page_part_manager.rb#L153-L183
class PagePartManager attr_accessor :page_part_key, :page_part, :container def initialize(page_part_key, container) raise "Please provide valid container" unless container.present? self.page_part_key = page_part_key # container can be either a page or the website self.container = cont...
osulp/triplestore-adapter
lib/triplestore_adapter/providers/blazegraph.rb
TriplestoreAdapter::Providers.Blazegraph.delete
ruby
def delete(statements) raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any? #TODO: Evaluate that all statements are singular, and without bnodes? writer = RDF::Writer.for(:jsonld) uri = URI.parse("#{@uri}?delete") request = ...
Delete the provided statements from the triplestore @param [RDF::Enumerable] statements to delete from the triplestore @return [Boolean] true if the delete was successful
train
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L39-L50
class Blazegraph attr_reader :url, :sparql_client ## # @param [String] url of SPARQL endpoint def initialize(url) @http = Net::HTTP::Persistent.new(self.class) @url = url @uri = URI.parse(@url.to_s) @sparql_client = SPARQL::Client.new(@uri) end ## # Insert the pro...
visoft/ruby_odata
lib/ruby_odata/service.rb
OData.Service.build_collection_query_object
ruby
def build_collection_query_object(name, additional_parameters, *args) root = "/#{name.to_s}" if args.empty? #nothing to add elsif args.size == 1 if args.first.to_s =~ /\d+/ id_metadata = find_id_metadata(name.to_s) root << build_id_path(args.first, id_metadata) else ...
Constructs a QueryBuilder instance for a collection using the arguments provided. @param [String] name the name of the collection @param [Hash] additional_parameters the additional parameters @param [Array] args the arguments to use for query
train
https://github.com/visoft/ruby_odata/blob/ca3d441494aa2f745c7f7fb2cd90173956f73663/lib/ruby_odata/service.rb#L178-L193
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...
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ObjectConvenienceMethods.spork_loop
ruby
def spork_loop(delay_or_event = nil, clock = nil, &block) shred = Shred.new do while Shred.current.running? if delay_or_event if delay_or_event.is_a?(Numeric) Shred.yield(delay_or_event, clock) else Shred.wait_on(delay_or_event) end...
creates a new Shred with the given block on the global Shreduler, automatically surrounded by loop { }. If the delay_or_event parameter is given, a Shred.yield(delay) or Shred.wait_on(event) is inserted before the call to your block.
train
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L133-L148
module ObjectConvenienceMethods # creates a new Shred with the given block on the global Shreduler def spork(&block) $shreduler.shredule(Shred.new(&block)) end # creates a new Shred with the given block on the global Shreduler, # automatically surrounded by loop { }. If the delay_or_eve...
DigitPaint/roger
lib/roger/renderer.rb
Roger.Renderer.find_partial
ruby
def find_partial(name) current_path, current_ext = current_template_path_and_extension # Try to find _ named partials first. # This will alaso search for partials relative to the current path local_name = [File.dirname(name), "_" + File.basename(name)].join("/") resolver = Resolver.new([F...
Find a partial
train
https://github.com/DigitPaint/roger/blob/1153119f170d1b0289b659a52fcbf054df2d9633/lib/roger/renderer.rb#L288-L302
class Renderer MAX_ALLOWED_TEMPLATE_NESTING = 10 class << self # Register a helper module that should be included in # every template context. def helper(mod) @helpers ||= [] @helpers << mod end def helpers @helpers || [] end # Will the rend...
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.clear_rules!
ruby
def clear_rules!(forward_to_replicas = false, request_options = {}) res = clear_rules(forward_to_replicas, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) return res end
Clear all rules and wait the end of indexing @param forward_to_replicas should we forward the delete to replica indices @param request_options contains extra parameters to send with your query
train
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L1133-L1137
class Index attr_accessor :name, :client def initialize(name, client = nil) self.name = name self.client = client || Algolia.client end # # Delete an index # # @param request_options contains extra parameters to send with your query # # return an hash of the form { "d...
kontena/kontena
cli/lib/kontena/cli/services/update_command.rb
Kontena::Cli::Services.UpdateCommand.parse_service_data_from_options
ruby
def parse_service_data_from_options data = {} data[:strategy] = deploy_strategy if deploy_strategy data[:ports] = parse_ports(ports_list) unless ports_list.empty? data[:links] = parse_links(link_list) unless link_list.empty? data[:memory] = parse_memory(memory) if memory data[:memory...
parse given options to hash @return [Hash]
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/services/update_command.rb#L61-L92
class UpdateCommand < Kontena::Command include Kontena::Cli::Common include Kontena::Cli::GridOptions include ServicesHelper parameter "NAME", "Service name" option "--image", "IMAGE", "Docker image to use" option ["-p", "--ports"], "PORT", "Publish a service's port to the host", multivalued...
kmuto/review
lib/epubmaker/epubcommon.rb
EPUBMaker.EPUBCommon.colophon
ruby
def colophon @title = CGI.escapeHTML(@producer.res.v('colophontitle')) @body = <<EOT <div class="colophon"> EOT if @producer.config['subtitle'].nil? @body << <<EOT <p class="title">#{CGI.escapeHTML(@producer.config.name_of('title'))}</p> EOT else @body << <<EOT <p clas...
Return colophon content.
train
https://github.com/kmuto/review/blob/77d1273e671663f05db2992281fd891b776badf0/lib/epubmaker/epubcommon.rb#L211-L254
class EPUBCommon # Construct object with parameter hash +config+ and message resource hash +res+. def initialize(producer) @body_ext = '' @producer = producer @body_ext = nil end # Return mimetype content. def mimetype 'application/epub+zip' end def opf_path ...
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.run_install
ruby
def run_install(install_path) require 'fileutils' install_path ||= '.' FileUtils.mkdir_p install_path unless File.exists?(install_path) install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml" install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/con...
Install the required CloudCrowd configuration files into the specified directory, or the current one.
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L143-L151
class CommandLine # Configuration files required for the `crowd` command to function. CONFIG_FILES = ['config.yml', 'config.ru', 'database.yml'] # Reference the absolute path to the root. CC_ROOT = File.expand_path(File.dirname(__FILE__) + '/../..') # Command-line banner for the usage message. ...
zhimin/rwebspec
lib/rwebspec-common/assert.rb
RWebSpec.Assert.assert
ruby
def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true end
own assert method
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-common/assert.rb#L6-L14
module Assert # own assert method def assert test, msg = nil msg ||= "Failed assertion, no message given." # comment out self.assertions += 1 to counting assertions unless test then msg = msg.call if Proc === msg raise RWebSpec::Assertion, msg end true en...
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.witness_commitment
ruby
def witness_commitment return nil unless coinbase_tx? outputs.each do |output| commitment = output.script_pubkey.witness_commitment return commitment if commitment end nil end
get the witness commitment of coinbase tx. if this tx does not coinbase or not have commitment, return nil.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L94-L101
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...
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.create_transaction
ruby
def create_transaction(budget_id, data, opts = {}) data, _status_code, _headers = create_transaction_with_http_info(budget_id, data, opts) data end
Create a single transaction or multiple transactions Creates a single transaction or multiple transactions. If you provide a body containing a 'transaction' object, a single transaction will be created and if you provide a body containing a 'transactions' array, multiple transactions will be created. @param budget_i...
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L28-L31
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...
mongodb/mongo-ruby-driver
lib/mongo/uri.rb
Mongo.URI.inverse_bool
ruby
def inverse_bool(name, value) b = convert_bool(name, value) if b.nil? nil else !b end end
Parses a boolean value and returns its inverse. @param value [ String ] The URI option value. @return [ true | false | nil ] The inverse of the boolean value parsed out, otherwise nil (and a warning will be logged).
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/uri.rb#L872-L880
class URI include Loggable # The uri parser object options. # # @since 2.0.0 attr_reader :options # The options specified in the uri. # # @since 2.1.0 attr_reader :uri_options # The servers specified in the uri. # # @since 2.0.0 attr_reader :servers # The mo...
rjoberon/bibsonomy-ruby
lib/bibsonomy/api.rb
BibSonomy.API.get_posts_for_group
ruby
def get_posts_for_group(group_name, resource_type, tags = nil, start = 0, endc = $MAX_POSTS_PER_REQUEST) return get_posts("group", group_name, resource_type, tags, start, endc) end
Get the posts of the users of a group, optionally filtered by tags. @param group_name [String] the name of the group @param resource_type [String] the type of the post. Currently supported are 'bookmark' and 'publication'. @param tags [Array<String>] the tags that all posts must contain (can be empty) @param start...
train
https://github.com/rjoberon/bibsonomy-ruby/blob/15afed3f32e434d28576ac62ecf3cfd8a392e055/lib/bibsonomy/api.rb#L114-L116
class API # Initializes the client with the given credentials. # # @param user_name [String] the name of the user account used for accessing the API # @param api_key [String] the API key corresponding to the user account - can be obtained from http://www.bibsonomy.org/settings?selTab=1 # # @p...
hashicorp/vagrant
lib/vagrant/box_collection.rb
Vagrant.BoxCollection.with_temp_dir
ruby
def with_temp_dir(dir=nil) dir ||= Dir.mktmpdir(TEMP_PREFIX, @temp_root) dir = Pathname.new(dir) yield dir ensure FileUtils.rm_rf(dir.to_s) end
This is a helper that makes sure that our temporary directories are cleaned up no matter what. @param [String] dir Path to a temporary directory @return [Object] The result of whatever the yield is
train
https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L466-L473
class BoxCollection TEMP_PREFIX = "vagrant-box-add-temp-".freeze VAGRANT_SLASH = "-VAGRANTSLASH-".freeze VAGRANT_COLON = "-VAGRANTCOLON-".freeze # The directory where the boxes in this collection are stored. # # A box collection matches a very specific folder structure that Vagrant # expe...
wvanbergen/request-log-analyzer
lib/request_log_analyzer/file_format.rb
RequestLogAnalyzer::FileFormat.CommonRegularExpressions.hostname_or_ip_address
ruby
def hostname_or_ip_address(blank = false) regexp = Regexp.union(hostname, ip_address) add_blank_option(regexp, blank) end
Creates a regular expression to match a hostname or ip address
train
https://github.com/wvanbergen/request-log-analyzer/blob/b83865d440278583ac8e4901bb33878244fd7c75/lib/request_log_analyzer/file_format.rb#L134-L137
module CommonRegularExpressions TIMESTAMP_PARTS = { 'a' => '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)', 'b' => '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)', 'y' => '\d{2}', 'Y' => '\d{4}', 'm' => '\d{2}', 'd' => '\d{2}', 'H' => '\d{2}', 'M' => '\d{2}', 'S' => '\d{2}', 'k' => '(?:\d| )\d', ...
metanorma/relaton
lib/relaton/db_cache.rb
Relaton.DbCache.valid_entry?
ruby
def valid_entry?(key, year) datestr = fetched key return false unless datestr date = Date.parse datestr year || Date.today - date < 60 end
if cached reference is undated, expire it after 60 days @param key [String] @param year [String]
train
https://github.com/metanorma/relaton/blob/2fac19da2f3ef3c30b8e8d8815a14d2115df0be6/lib/relaton/db_cache.rb#L82-L87
class DbCache # @return [String] attr_reader :dir # @param dir [String] DB directory def initialize(dir) @dir = dir FileUtils::mkdir_p @dir file_version = "#{@dir}/version" File.write file_version, VERSION, encoding: "utf-8" unless File.exist? file_version end # Save ...
grempe/opensecrets
lib/opensecrets.rb
OpenSecrets.Committee.by_industry
ruby
def by_industry(options = {}) raise ArgumentError, 'You must provide a :cmte option' if options[:cmte].nil? || options[:cmte].empty? raise ArgumentError, 'You must provide a :congno option' if options[:congno].nil? || options[:congno].empty? raise ArgumentError, 'You must provide a :indus option' if o...
Provides summary fundraising information for a specific committee, industry and Congress number. See : http://www.opensecrets.org/api/?method=congCmteIndus&output=doc @option options [String] :cmte ("") Committee ID in CQ format @option options [String] :congno ("") Congress Number (like 110) @option options [Str...
train
https://github.com/grempe/opensecrets/blob/2f507e214de716ce7b23831e056160b1384bff78/lib/opensecrets.rb#L138-L144
class Committee < OpenSecrets::Base # Provides summary fundraising information for a specific committee, industry and Congress number. # # See : http://www.opensecrets.org/api/?method=congCmteIndus&output=doc # # @option options [String] :cmte ("") Committee ID in CQ format # @option options ...
anthonator/dirigible
lib/dirigible/request.rb
Dirigible.Request.request
ruby
def request(method, path, options, headers) headers.merge!({ 'User-Agent' => user_agent, 'Accept' => 'application/vnd.urbanairship+json; version=3;', }) response = connection.send(method) do |request| request.url("#{endpoint}#{path}/") if [:post, :put].member?(method)...
Perform an HTTP request.
train
https://github.com/anthonator/dirigible/blob/829b265ae4e54e3d4b284900b2a51a707afb6105/lib/dirigible/request.rb#L21-L42
module Request def get(path, options = {}, headers = {}) request(:get, path, options, headers) end def post(path, options = {}, headers = {}) request(:post, path, options, headers) end def put(path, options = {}, headers = {}) request(:put, path, options, headers) end ...
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.process_snapshot_job
ruby
def process_snapshot_job(query = {}, report_email = nil, postback_url = nil, options = {}) data = options data['query'] = query process_job(:snapshot, data, report_email, postback_url) end
implementation for snapshot job
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L641-L645
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...
barkerest/incline
app/controllers/incline/users_controller.rb
Incline.UsersController.promote
ruby
def promote # add the administrator flag to the selected user. if @user.system_admin? flash[:warning] = "User #{@user} is already an administrator." unless inline_request? redirect_to users_path and return end else if @user.update(system_admin: true) ...
PUT /incline/users/1/promote
train
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/controllers/incline/users_controller.rb#L182-L202
class UsersController < ApplicationController before_action :set_user, except: [ :index, :new, :create, :api ] before_action :set_dt_request, only: [ :index, :locate ] before_action :set_disable_info, only: [ :disable_confirm, :disable ] before_action :not_current, only: [ :destroy...
DavidEGrayson/ruby_ecdsa
lib/ecdsa/prime_field.rb
ECDSA.PrimeField.square_roots_for_p_5_mod_8
ruby
def square_roots_for_p_5_mod_8(n) case power n, (prime - 1) / 4 when 1 candidate = power n, (prime + 3) / 8 when prime - 1 candidate = mod 2 * n * power(4 * n, (prime - 5) / 8) else # I think this can happen because we are not checking the Jacobi. return [] ...
This is Algorithm 3.37 from http://cacr.uwaterloo.ca/hac/
train
https://github.com/DavidEGrayson/ruby_ecdsa/blob/2216043b38170b9603c05bf1d4e43e184fc6181e/lib/ecdsa/prime_field.rb#L151-L162
class PrimeField # @return (Integer) the prime number that the field is based on. attr_reader :prime def initialize(prime) raise ArgumentError, "Invalid prime #{prime.inspect}" if !prime.is_a?(Integer) @prime = prime end # Returns true if the given object is an integer and a member o...
oleganza/btcruby
lib/btcruby/script/cltv_extension.rb
BTC.CLTVExtension.handle_opcode
ruby
def handle_opcode(interpreter: nil, opcode: nil) # We are not supposed to handle any other opcodes here. return false if opcode != OP_CHECKLOCKTIMEVERIFY if interpreter.stack.size < 1 return interpreter.set_error(SCRIPT_ERR_INVALID_STACK_OPERATION) end # Note that elsewhere numer...
Returns `false` if failed to execute the opcode.
train
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/cltv_extension.rb#L22-L60
class CLTVExtension include ScriptInterpreterExtension # Default `locktime_max_size` is 5. # Default `lock_time_checker` equals current interpreter's signature checker. def initialize(locktime_max_size: nil, lock_time_checker: nil) @locktime_max_size = locktime_max_size || 5 @lock_time_ch...
ynab/ynab-sdk-ruby
lib/ynab/api/transactions_api.rb
YNAB.TransactionsApi.get_transactions_by_category
ruby
def get_transactions_by_category(budget_id, category_id, opts = {}) data, _status_code, _headers = get_transactions_by_category_with_http_info(budget_id, category_id, opts) data end
List category transactions Returns all transactions for a specified category @param budget_id The id of the budget (\&quot;last-used\&quot; can also be used to specify the last used budget) @param category_id The id of the category @param [Hash] opts the optional parameters @option opts [Date] :since_date If speci...
train
https://github.com/ynab/ynab-sdk-ruby/blob/389a959e482b6fa9643c7e7bfb55d8640cc952fd/lib/ynab/api/transactions_api.rb#L281-L284
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...
zhimin/rwebspec
lib/rwebspec-watir/driver.rb
RWebSpec.Driver.enter_text_with_id
ruby
def enter_text_with_id(textfield_id, value, opts = {}) # For IE10, it seems unable to identify HTML5 elements # # However for IE10, the '.' is omitted. if opts.nil? || opts.empty? # for Watir, default is clear opts[:appending] = false end perform_oper...
for text field can be easier to be identified by attribute "id" instead of "name", not recommended though params opts takes :appending => true or false, if true, won't clear the text field.
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/driver.rb#L319-L340
module Driver include RWebSpec::TestWisePlugin include RWebSpec::Popup # open a browser, and set base_url via hash, but does not acually # # example: # open_browser :base_url => http://localhost:8080 # # There are 3 ways to set base url # 1. pass as first argument # 2. I...
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.schedule_blast_from_blast
ruby
def schedule_blast_from_blast(blast_id, schedule_time, options={}) post = options ? options : {} post[:copy_blast] = blast_id #post[:name] = name post[:schedule_time] = schedule_time api_post(:blast, post) end
Schedule a mass mail blast from previous blast
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L117-L123
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...
rmagick/rmagick
lib/rmagick_internal.rb
Magick.ImageList.scene=
ruby
def scene=(n) if n.nil? Kernel.raise IndexError, 'scene number out of bounds' unless @images.length.zero? @scene = nil return @scene elsif @images.length.zero? Kernel.raise IndexError, 'scene number out of bounds' end n = Integer(n) Kernel.raise IndexError,...
Allow scene to be set to nil
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rmagick_internal.rb#L1271-L1284
class ImageList include Comparable include Enumerable attr_reader :scene private def get_current @images[@scene].__id__ rescue StandardError nil end protected def is_an_image(obj) Kernel.raise ArgumentError, "Magick::Image required (#{obj.class} given)" unless...
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.find_one_and_replace
ruby
def find_one_and_replace(filter, replacement, options = {}) find(filter, options).find_one_and_update(replacement, options) end
Finds a single document and replaces it, returning the original doc unless otherwise specified. @example Find a document and replace it, returning the original. collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }) @example Find a document and replace it, returning the new document. collection...
train
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L759-L761
class Collection extend Forwardable include Retryable # The capped option. # # @since 2.1.0 CAPPED = 'capped'.freeze # The ns field constant. # # @since 2.1.0 NS = 'ns'.freeze # @return [ Mongo::Database ] The database the collection resides in. attr_reader :database...
bmuller/bandit
lib/bandit/extensions/view_concerns.rb
Bandit.ViewConcerns.bandit_sticky_choose
ruby
def bandit_sticky_choose(exp) name = "bandit_#{exp}".intern # choose url param with preference value = params[name].nil? ? cookies.signed[name] : params[name] # sticky choice may outlast a given alternative alternative = if Bandit.get_experiment(exp).alternatives.include?(value) ...
stick to one alternative until user deletes cookies or changes browser
train
https://github.com/bmuller/bandit/blob/4c2528adee6ed761b3298f5b8889819ed9e04483/lib/bandit/extensions/view_concerns.rb#L27-L39
module ViewConcerns extend ActiveSupport::Concern # default choose is a session based choice def bandit_choose(exp) bandit_session_choose(exp) end # always choose something new and increase the participant count def bandit_simple_choose(exp) Bandit.get_experiment(exp).choose(nil)...
rmagick/rmagick
lib/rvg/rvg.rb
Magick.RVG.ref
ruby
def ref(x, y, rw, rh) #:nodoc: translate(x, y) if x != 0 || y != 0 @width = rw if rw @height = rh if rh end
Accept #use arguments. Use (x,y) to generate an additional translate. Override @width and @height if new values are supplied.
train
https://github.com/rmagick/rmagick/blob/ef6688ed9d76bf123c2ea1a483eff8635051adb7/lib/rvg/rvg.rb#L245-L249
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. ...
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_decode
ruby
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
decode golomb rice
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L127-L134
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...
documentcloud/jammit
lib/jammit/compressor.rb
Jammit.Compressor.concatenate_and_tag_assets
ruby
def concatenate_and_tag_assets(paths, variant=nil) stylesheets = [paths].flatten.map do |css_path| contents = read_binary_file(css_path) contents.gsub(EMBED_DETECTOR) do |url| ipath, cpath = Pathname.new($1), Pathname.new(File.expand_path(css_path)) is_url = URI.parse($1).absol...
In order to support embedded assets from relative paths, we need to expand the paths before contatenating the CSS together and losing the location of the original stylesheet path. Validate the assets while we're at it.
train
https://github.com/documentcloud/jammit/blob/dc866f1ac3eb069d65215599c451db39d66119a7/lib/jammit/compressor.rb#L153-L163
class Compressor # Mapping from extension to mime-type of all embeddable assets. EMBED_MIME_TYPES = { '.png' => 'image/png', '.jpg' => 'image/jpeg', '.jpeg' => 'image/jpeg', '.gif' => 'image/gif', '.tif' => 'image/tiff', '.tiff' => 'image/tiff', '.ttf' => 'appli...
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.fire_callback
ruby
def fire_callback begin response = RestClient.post(callback_url, {:job => self.to_json}) CloudCrowd.defer { self.destroy } if response && response.code == 201 rescue RestClient::Exception => e CloudCrowd.log "Job ##{id} (#{action}) failed to fire callback: #{callback_url}\n#{e.backtr...
If a <tt>callback_url</tt> is defined, post the Job's JSON to it upon completion. The <tt>callback_url</tt> may include HTTP basic authentication, if you like: http://user:password@example.com/job_complete If the callback URL returns a '201 Created' HTTP status code, CloudCrowd will assume that the resource has ...
train
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L89-L96
class Job < ActiveRecord::Base include ModelStatus CLEANUP_GRACE_PERIOD = 7 # That's a week. has_many :work_units, :dependent => :destroy validates_presence_of :status, :inputs, :action, :options # Set initial status # A Job starts out either splitting or processing, depending on its actio...
mojombo/chronic
lib/chronic/handlers.rb
Chronic.Handlers.handle_o_r_g_r
ruby
def handle_o_r_g_r(tokens, options) outer_span = get_anchor(tokens[2..3], options) handle_orr(tokens[0..1], outer_span, options) end
Handle ordinal/repeater/grabber/repeater
train
https://github.com/mojombo/chronic/blob/2b1eae7ec440d767c09e0b1a7f0e9bcf30ce1d6c/lib/chronic/handlers.rb#L513-L516
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 = ...
kontena/kontena
cli/lib/kontena/cli/master/login_command.rb
Kontena::Cli::Master.LoginCommand.auth_works?
ruby
def auth_works?(server) return false unless (server && server.token && server.token.access_token) vspinner "Testing if authentication works using current access token" do Kontena::Client.new(server.url, server.token).authentication_ok?(master_account.userinfo_endpoint) end end
Check if the existing (or --token) authentication works without reauthenticating
train
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/master/login_command.rb#L112-L117
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...
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.parent_task
ruby
def parent_task(name) task name do Rake::Task .tasks .select { |t| t.name =~ /^#{name}:/ } .sort_by(&:name) .each(&:execute) end end
Define a task named `name` that runs all tasks under an identically named `namespace`.
train
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L28-L36
module DSL # Create and manage a temp file, replacing `fname` with the temp file, if `fname` is provided. def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end # Write an a...
mongodb/mongoid
lib/mongoid/findable.rb
Mongoid.Findable.find_by
ruby
def find_by(attrs = {}) result = where(attrs).find_first if result.nil? && Mongoid.raise_not_found_error raise(Errors::DocumentNotFound.new(self, attrs)) end yield(result) if result && block_given? result end
Find the first +Document+ given the conditions. If a matching Document is not found and Mongoid.raise_not_found_error is true it raises Mongoid::Errors::DocumentNotFound, return null nil elsewise. @example Find the document by attribute other than id Person.find_by(:username => "superuser") @param [ Hash ] at...
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/findable.rb#L114-L121
module Findable extend Mongoid::Criteria::Queryable::Forwardable select_with :with_default_scope # These are methods defined on the criteria that should also be accessible # directly from the class level. delegate \ :aggregates, :avg, :create_with, :distinct, :each,...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chown
ruby
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
Change the file owner of the selected files and directories. ==== Parameters * +user_and_group+ - user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L250-L255
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...
sugaryourcoffee/syclink
lib/syclink/designer.rb
SycLink.Designer.create_website
ruby
def create_website(directory, template_filename) template = File.read(template_filename) File.open(html_file(directory, website.title), 'w') do |f| f.puts website.to_html(template) end end
Creates the html representation of the website. The website is saved to the directory with websites title and needs an erb-template where the links are integrated to. An example template can be found at templates/syclink.html.erb
train
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/designer.rb#L152-L157
class Designer # extend Forwardable # def_delegators :@website, :report_links_availability include Infrastructure # The website the designer is working on attr_accessor :website # Creates a new website where designer can operate on def new_website(title = "SYC LINK") @website = Web...
iyuuya/jkf
lib/jkf/parser/kifuable.rb
Jkf::Parser.Kifuable.parse_pointer
ruby
def parse_pointer s0 = @current_pos s1 = match_str("&") if s1 != :failed s2 = parse_nonls s3 = parse_nl if s3 != :failed s0 = [s1, s2, s3] else @current_pos = s0 s0 = :failed end else @current_pos = s0 s0 = :fa...
pointer : "&" nonls nl
train
https://github.com/iyuuya/jkf/blob/4fd229c50737cab7b41281238880f1414e55e061/lib/jkf/parser/kifuable.rb#L151-L168
module Kifuable protected # initialboard : (" " nonls nl)? ("+" nonls nl)? ikkatsuline+ ("+" nonls nl)? def parse_initialboard s0 = s1 = @current_pos if match_space != :failed parse_nonls s2 = parse_nl @current_pos = s1 if s2 == :failed else @current_pos ...
cookpad/rrrspec
rrrspec-client/lib/rrrspec/redis_models.rb
RRRSpec.Taskset.add_task
ruby
def add_task(task) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'tasks'), task.key) RRRSpec.redis.rpush(RRRSpec.make_key(key, 'tasks_left'), task.key) end
========================================================================== Tasks Public: Add a task. NOTE: This method does **NOT** enqueue to the task_queue
train
https://github.com/cookpad/rrrspec/blob/a5bde2b062ce68b1e32b8caddf194389c2ce28b0/rrrspec-client/lib/rrrspec/redis_models.rb#L301-L304
class Taskset attr_reader :key def initialize(taskset_key) @key = taskset_key end # Public: Create a new taskset. # NOTE: This method will **NOT** call ActiveTaskset.add. def self.create(rsync_name, setup_command, slave_command, worker_type, taskset_class, max_worke...
moneta-rb/moneta
lib/moneta/cache.rb
Moneta.Cache.store
ruby
def store(key, value, options = {}) @cache.store(key, value, options) @adapter.store(key, value, options) end
(see Proxy#store)
train
https://github.com/moneta-rb/moneta/blob/26a118c8b2c93d11257f4a5fe9334a8157f4db47/lib/moneta/cache.rb#L64-L67
class Cache include Defaults # @api private class DSL def initialize(store, &block) @store = store instance_eval(&block) end # @api public def adapter(store = nil, &block) raise 'Adapter already set' if @store.adapter raise ArgumentError, 'Only arg...
rakeoe/rakeoe
lib/rakeoe/binary_base.rb
RakeOE.BinaryBase.read_prj_settings
ruby
def read_prj_settings(file) unless File.file?(file) file = File.dirname(__FILE__)+'/prj.rake' end KeyValueReader.new(file) end
Read project file if it exists @param [String] file Filename of project file @return [KeyValueReader] New KeyValueReader object with values provided via read project file
train
https://github.com/rakeoe/rakeoe/blob/af7713fb238058509a34103829e37a62873c4ecb/lib/rakeoe/binary_base.rb#L239-L244
class BinaryBase include Rake::DSL attr_reader :build_dir, :src_dir, :src_dirs, :inc_dirs, :test_dirs, :obj_dirs attr_accessor :name, :bin_dir, :test_dir, :settings, :tc, :prj_file, :binary, :objs, :deps, :test_deps, :test_binary, :test_objs # # The following parameters are ...
etewiah/property_web_builder
app/controllers/pwb/api/v1/properties_controller.rb
Pwb.Api::V1::PropertiesController.bulk_create
ruby
def bulk_create propertiesJSON = params["propertiesJSON"] unless propertiesJSON.is_a? Array propertiesJSON = JSON.parse propertiesJSON end new_props = [] existing_props = [] errors = [] properties_params(propertiesJSON).each_with_index do |property_params, index| ...
def set_default_currency @model end
train
https://github.com/etewiah/property_web_builder/blob/fba4e6d4ffa7bc1f4d3b50dfa5a6a9fbfee23f21/app/controllers/pwb/api/v1/properties_controller.rb#L12-L78
class Api::V1::PropertiesController < JSONAPI::ResourceController # Skipping action below allows me to browse to endpoint # without having set mime type skip_before_action :ensure_valid_accept_media_type # def set_default_currency # @model # end # TODO: rename to update_features: ...
projectcypress/health-data-standards
lib/hqmf-parser/2.0/data_criteria_helpers/dc_definition_from_template_or_type_extract.rb
HQMF2.DataCriteriaTypeAndDefinitionExtraction.handle_known_template_id
ruby
def handle_known_template_id(template_id) case template_id when VARIABLE_TEMPLATE @derivation_operator = HQMF::DataCriteria::INTERSECT if @derivation_operator == HQMF::DataCriteria::XPRODUCT @definition ||= 'derived' @variable = true @negation = false when SATISFIES_ANY...
Given a template id, modify the variables inside this data criteria to reflect the template
train
https://github.com/projectcypress/health-data-standards/blob/252d4f0927c513eacde6b9ea41b76faa1423c34b/lib/hqmf-parser/2.0/data_criteria_helpers/dc_definition_from_template_or_type_extract.rb#L36-L54
module DataCriteriaTypeAndDefinitionExtraction VARIABLE_TEMPLATE = '0.1.2.3.4.5.6.7.8.9.1' SATISFIES_ANY_TEMPLATE = '2.16.840.1.113883.10.20.28.3.108' SATISFIES_ALL_TEMPLATE = '2.16.840.1.113883.10.20.28.3.109' def extract_definition_from_template_or_type # Try to determine what kind of data cri...
koraktor/metior
lib/metior/report.rb
Metior.Report.render
ruby
def render Mustache.view_namespace = self.class result = {} self.class.views.each do |view_name| template = File.join 'templates', "#{view_name}.mustache" template_path = self.class.find template view = File.join 'views', "#{view_name}.rb" view_path = self.class.find ...
Renders the views of this report (or the its ancestors) and returns them in a hash @return [Hash<Symbol, String>] The names of the views and the corresponding rendered content
train
https://github.com/koraktor/metior/blob/02da0f330774c91e1a7325a5a7edbe696f389f95/lib/metior/report.rb#L191-L209
module Report # The path where the reports bundled with Metior live REPORTS_PATH = File.expand_path File.join File.dirname(__FILE__), '..', '..', 'reports' # Returns the commits analyzed by this report # # @return [CommitCollection] The commits analyzed by this report attr_reader :commits ...
tbuehlmann/ponder
lib/ponder/thaum.rb
Ponder.Thaum.parse
ruby
def parse(message) message.chomp! if message =~ /^PING \S+$/ if @config.hide_ping_pongs send_data message.sub(/PING/, 'PONG') else @loggers.info "<< #{message}" raw message.sub(/PING/, 'PONG') end else @loggers.info "<< #{message}" ...
parsing incoming traffic
train
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L79-L94
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...
sunspot/sunspot
sunspot/lib/sunspot/session.rb
Sunspot.Session.remove
ruby
def remove(*objects, &block) if block types = objects conjunction = Query::Connective::Conjunction.new if types.length == 1 conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::EqualTo, types.first) else conjunction.add_positive_restricti...
See Sunspot.remove
train
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L137-L156
class Session class <<self attr_writer :connection_class #:nodoc: # # For testing purposes # def connection_class #:nodoc: @connection_class ||= RSolr end end # # Sunspot::Configuration object for this session # attr_reader :config # # Ses...
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.new_category_params
ruby
def new_category_params # take params from front-end request category_params = params.require(:category).permit(:title, :lato_blog_category_id).to_h # add current superuser id category_params[:lato_core_superuser_creator_id] = @core__current_superuser.id # add post parent id ...
Params helpers: This function generate params for a new category.
train
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L116-L127
class Back::CategoriesController < Back::BackController before_action do core__set_menu_active_item('blog_articles') end # This function shows the list of possible categories. def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories...
sailthru/sailthru-ruby-client
lib/sailthru/client.rb
Sailthru.Client.receive_verify_post
ruby
def receive_verify_post(params, request) if request.post? [:action, :email, :send_id, :sig].each { |key| return false unless params.has_key?(key) } return false unless params[:action] == :verify sig = params.delete(:sig) params.delete(:controller) return false unless sig ...
params: params, Hash request, String returns: boolean, Returns true if the incoming request is an authenticated verify post.
train
https://github.com/sailthru/sailthru-ruby-client/blob/978deed2b25769a73de14107cb2a0c93143522e4/lib/sailthru/client.rb#L285-L304
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...
tdg5/tco_method
lib/tco_method/block_extractor.rb
TCOMethod.BlockExtractor.determine_end_offset
ruby
def determine_end_offset(block, tokens, source, expected_matcher) lines = source.lines last_line_number = lines.length end_offset = nil tokens.reverse_each do |token| # Break once we're through with the last line. break if token[0][0] != last_line_number # Look for expec...
Encapsulates the logic required to determine the offset of the end of the block. The end of the block is characterized by a matching curly brace (`}`) or the `end` keyword.
train
https://github.com/tdg5/tco_method/blob/fc89b884b68ce2a4bc58abb22270b1f7685efbe9/lib/tco_method/block_extractor.rb#L27-L47
class BlockExtractor DO_STR = "do".freeze END_STR = "end".freeze attr_reader :source def initialize(block) source = block.source type = block.lambda? ? :lambda : :proc start_offset, end_offset = determine_offsets(block, source) @source = "#{type} #{source[start_offset..end_of...
amatsuda/rfd
lib/rfd.rb
Rfd.Controller.chmod
ruby
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
Change the file permission of the selected files and directories. ==== Parameters * +mode+ - Unix chmod string (e.g. +w, g-r, 755, 0644)
train
https://github.com/amatsuda/rfd/blob/403c0bc0ff0a9da1d21220b479d5a42008512b78/lib/rfd.rb#L235-L244
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...
zhimin/rwebspec
lib/rwebspec-watir/web_browser.rb
RWebSpec.WebBrowser.element_by_id
ruby
def element_by_id(elem_id) if is_firefox? # elem = @browser.document.getElementById(elem_id) # elem = div(:id, elem_id) || label(:id, elem_id) || button(:id, elem_id) || # span(:id, elem_id) || hidden(:id, elem_id) || link(:id, elem_id) || radio(:id, elem_id) elem = browser.element_...
Deprecated: using Watir style directly instead
train
https://github.com/zhimin/rwebspec/blob/aafccee2ba66d17d591d04210067035feaf2f892/lib/rwebspec-watir/web_browser.rb#L456-L465
class WebBrowser attr_accessor :context def initialize(base_url = nil, existing_browser = nil, options = {}) default_options = {:speed => "zippy", :visible => true, :highlight_colour => 'yellow', :close_others => true } options = default_options.merge options ...
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2pkh?
ruby
def p2pkh? return false unless chunks.size == 5 [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] == (chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21 end
whether this script is a P2PKH format script.
train
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L169-L173
class Script include Bitcoin::Opcodes attr_accessor :chunks def initialize @chunks = [] end # generate P2PKH script def self.to_p2pkh(pubkey_hash) new << OP_DUP << OP_HASH160 << pubkey_hash << OP_EQUALVERIFY << OP_CHECKSIG end # generate P2WPKH script def self.to_p2...
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.booker_must_be_booker
ruby
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
Validation method. Check if the booker model is actually a booker
train
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L48-L52
class Booking < ::ActiveRecord::Base self.table_name = 'acts_as_bookable_bookings' belongs_to :bookable, polymorphic: true belongs_to :booker, polymorphic: true validates_presence_of :bookable validates_presence_of :booker validate :bookable_must_be_bookable, :booker_must_be...
willfore/cp_mgmt_ruby
lib/cp_mgmt/host.rb
CpMgmt.Host.show
ruby
def show(name) client = CpMgmt.configuration.client CpMgmt.logged_in? body = {name: name}.to_json response = client.post do |req| req.url '/web_api/show-host' req.headers['Content-Type'] = 'application/json' req.headers['X-chkp-sid'] = ENV.fetch("sid") req.body =...
Shows a host
train
https://github.com/willfore/cp_mgmt_ruby/blob/d25f169561f254bd13cc6fa5afa6b362637c1f65/lib/cp_mgmt/host.rb#L35-L47
class Host # Adds a host def add(name, ip_address, options={}) client = CpMgmt.configuration.client CpMgmt.logged_in? params = {name: name, "ip-address": ip_address} body = params.merge(options).to_json response = client.post do |req| req.url '/web_api/add-host' ...
mongodb/mongoid
lib/mongoid/fields.rb
Mongoid.Fields.apply_default
ruby
def apply_default(name) unless attributes.key?(name) if field = fields[name] default = field.eval_default(self) unless default.nil? || field.lazy? attribute_will_change!(name) attributes[name] = default end end end end
Applies a single default value for the given name. @example Apply a single default. model.apply_default("name") @param [ String ] name The name of the field. @since 2.4.0
train
https://github.com/mongodb/mongoid/blob/56976e32610f4c2450882b0bfe14da099f0703f4/lib/mongoid/fields.rb#L101-L111
module Fields extend ActiveSupport::Concern # For fields defined with symbols use the correct class. # # @since 4.0.0 TYPE_MAPPINGS = { array: Array, big_decimal: BigDecimal, binary: BSON::Binary, boolean: Mongoid::Boolean, date: Date, date_time: DateTime, ...