_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q8100
BitMagic.BitsGenerator.each_value
train
def each_value(each_bits = nil, &block) # Warning! This has exponential complexity (time and space) # 2**n to be precise, use sparingly yield 0 count = 1 if @options[:default] != 0 yield @options[:default] count += 1 end each_bits = self.bit...
ruby
{ "resource": "" }
q8101
BitMagic.BitsGenerator.all_values
train
def all_values(each_bits = nil, opts = {warn_threshold: 12}) # Shuffle things around so that people can call #all_values(warn_threshold: false) if each_bits.is_a?(Hash) opts = each_bits each_bits = nil end each_bits = self.bits if each_bits == nil if opts[:war...
ruby
{ "resource": "" }
q8102
BitMagic.BitsGenerator.equal_to
train
def equal_to(field_values = {}) all_num, none_num = self.equal_to_numbers(field_values) [].tap do |list| self.each_value { |num| list << num if (num & all_num) == all_num and (num & none_num) == 0 } end end
ruby
{ "resource": "" }
q8103
BitMagic.BitsGenerator.equal_to_numbers
train
def equal_to_numbers(field_values = {}) fields = {} field_values.each_pair do |field_name, v| bits = self.bits_for(field_name) fields[bits] = v if bits.length > 0 end all_num = 0 none_num = 0 fields.each_pair { |field_bits, val| field_bits.each_w...
ruby
{ "resource": "" }
q8104
LatoBlog.Category::EntityHelpers.get_all_category_children
train
def get_all_category_children direct_children = self.category_children all_children = [] direct_children.each do |direct_child| all_children.push(direct_child) all_children = all_children + direct_child.get_all_category_children end all_children end
ruby
{ "resource": "" }
q8105
ChineseLunar.Lunar.lunar_date
train
def lunar_date() l = convert(@date.year, @date.month, @date.day) l[0].to_s + "-" + l[1].to_s + "-" + (/^\d+/.match(l[2].to_s)).to_s end
ruby
{ "resource": "" }
q8106
ChineseLunar.Lunar.days_in_lunar_date
train
def days_in_lunar_date(y) sum = 348 i = 0x8000 while i > 0x8 if ((@@lunar_info[y - 1900] & i) != 0) sum += 1 end i >>= 1 end sum + leap_days(y) end
ruby
{ "resource": "" }
q8107
::Sequel::Plugins::Crushyform.ClassMethods.to_dropdown
train
def to_dropdown(selection=nil, nil_name='** UNDEFINED **') dropdown_cache.inject("<option value=''>#{nil_name}</option>\n") do |out, row| selected = 'selected' if row[0]==selection "%s%s%s%s" % [out, row[1], selected, row[2]] end end
ruby
{ "resource": "" }
q8108
::Sequel::Plugins::Crushyform.InstanceMethods.crushyfield
train
def crushyfield(col, o={}) return '' if (o[:type]==:none || model.crushyform_schema[col][:type]==:none) field_name = o[:name] || model.crushyform_schema[col][:name] || col.to_s.sub(/_id$/, '').tr('_', ' ').capitalize error_list = errors.on(col).map{|e|" - #{e}"} if !errors.on(col).nil? "<p class...
ruby
{ "resource": "" }
q8109
::Sequel::Plugins::Crushyform.InstanceMethods.to_thumb
train
def to_thumb(c) current = self.__send__(c) if model.respond_to?(:stash_reflection) && model.stash_reflection.key?(c) !current.nil? && current[:type][/^image\//] ? "<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\n" : '' else "<img src='#{current}?#{::Time....
ruby
{ "resource": "" }
q8110
Ponder.Thaum.parse
train
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}" ...
ruby
{ "resource": "" }
q8111
Ponder.Thaum.setup_default_callbacks
train
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...
ruby
{ "resource": "" }
q8112
LookUpTable.ClassMethods.lut_write_to_cache
train
def lut_write_to_cache(lut_key) if lut_options(lut_key)[:sql_mode] count = lut_write_to_cache_sql_mode(lut_key) else count = lut_write_to_cache_no_sql_mode(lut_key) end # HACK: Writing a \0 to terminate batch_items lut_write_cache_item(lut_key, count, nil) end
ruby
{ "resource": "" }
q8113
Charmkit.Helpers.template
train
def template(src, dst, **context) rendered = TemplateRenderer.render(File.read(src), context) File.write(dst, rendered) end
ruby
{ "resource": "" }
q8114
Charmkit.Helpers.inline_template
train
def inline_template(name, dst, **context) templates = {} begin app, data = File.read(caller.first.split(":").first).split("__END__", 2) rescue Errno::ENOENT app, data = nil end data.strip! if data template = nil data.each_line do |line| if l...
ruby
{ "resource": "" }
q8115
Raca.Container.delete
train
def delete(key) log "deleting #{key} from #{container_path}" object_path = File.join(container_path, Raca::Util.url_encode(key)) response = storage_client.delete(object_path) (200..299).cover?(response.code.to_i) end
ruby
{ "resource": "" }
q8116
Raca.Container.object_metadata
train
def object_metadata(key) object_path = File.join(container_path, Raca::Util.url_encode(key)) log "Requesting metadata from #{object_path}" response = storage_client.head(object_path) { :content_type => response["Content-Type"], :bytes => response["Content-Length"].to_i } ...
ruby
{ "resource": "" }
q8117
Raca.Container.download
train
def download(key, filepath) log "downloading #{key} from #{container_path}" object_path = File.join(container_path, Raca::Util.url_encode(key)) outer_response = storage_client.get(object_path) do |response| File.open(filepath, 'wb') do |io| response.read_body do |chunk| i...
ruby
{ "resource": "" }
q8118
Raca.Container.list
train
def list(options = {}) max = options.fetch(:max, 100_000_000) marker = options.fetch(:marker, nil) prefix = options.fetch(:prefix, nil) details = options.fetch(:details, nil) limit = [max, MAX_ITEMS_PER_LIST].min log "retrieving up to #{max} items from #{container_path}" reques...
ruby
{ "resource": "" }
q8119
Raca.Container.metadata
train
def metadata log "retrieving container metadata from #{container_path}" response = storage_client.head(container_path) custom = {} response.each_capitalized_name { |name| custom[name] = response[name] if name[/\AX-Container-Meta-/] } { :objects => response["X-Containe...
ruby
{ "resource": "" }
q8120
Raca.Container.set_metadata
train
def set_metadata(headers) log "setting headers for container #{container_path}" response = storage_client.post(container_path, '', headers) (200..299).cover?(response.code.to_i) end
ruby
{ "resource": "" }
q8121
Raca.Container.cdn_metadata
train
def cdn_metadata log "retrieving container CDN metadata from #{container_path}" response = cdn_client.head(container_path) { :cdn_enabled => response["X-CDN-Enabled"] == "True", :host => response["X-CDN-URI"], :ssl_host => response["X-CDN-SSL-URI"], :streaming_host => r...
ruby
{ "resource": "" }
q8122
Raca.Container.cdn_enable
train
def cdn_enable(ttl = 259200) log "enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes" response = cdn_client.put(container_path, "X-TTL" => ttl.to_i.to_s) (200..299).cover?(response.code.to_i) end
ruby
{ "resource": "" }
q8123
Raca.Container.temp_url
train
def temp_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60) private_url("GET", object_key, temp_url_key, expires_at) end
ruby
{ "resource": "" }
q8124
Raca.Container.temp_upload_url
train
def temp_upload_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60) private_url("PUT", object_key, temp_url_key, expires_at) end
ruby
{ "resource": "" }
q8125
Raca.Container.list_request_path
train
def list_request_path(marker, prefix, details, limit) query_string = "limit=#{limit}" query_string += "&marker=#{Raca::Util.url_encode(marker)}" if marker query_string += "&prefix=#{Raca::Util.url_encode(prefix)}" if prefix query_string += "&format=json" if details container_path + "?...
ruby
{ "resource": "" }
q8126
SycTimeleap.TimeLeap.method_missing
train
def method_missing(name, *args) add_regex = %r{ ^([ib])(?:n|ack)? (?:\.|_|-| )? (\d+) (?:\.|_|-| )? ([dwmy]) (?:ays?|eeks?|onths?|ears?)?$ }x weekday_regex = %r{ ^(tod|tom|y)(?:a?y?|o?r?r?o?w?|e?s?t?e?r?d?a?y?)?$ }xi next_week...
ruby
{ "resource": "" }
q8127
RUser.Person.convert
train
def convert(data) data.each do |k, v| k = KEYS[k] if KEYS.include?(k) v = v.to_s if k.eql? 'zip' if NIDT.include?(k) instance_variable_set('@nidt', k) k = 'nidn' v = v.to_s end var_set(k, v) end end
ruby
{ "resource": "" }
q8128
RUser.Person.var_set
train
def var_set(k, v) varget = proc { instance_variable_get("@#{k}") } varset = proc { |y| instance_variable_set("@#{k}", y) } v.is_a?(Hash) ? convert(v) : instance_variable_set("@#{k}", v) self.class.send(:define_method, k, varget) self.class.send(:define_method, "#{k}=", varset) end
ruby
{ "resource": "" }
q8129
HasEnumeration.AggregateConditionsOverride.expand_hash_conditions_for_aggregates
train
def expand_hash_conditions_for_aggregates(attrs) expanded_attrs = attrs.dup attr_enumeration_mapping_classes.each do |attr, klass| if expanded_attrs[attr].is_a?(Symbol) expanded_attrs[attr] = klass.from_sym(expanded_attrs[attr]) end end super(expanded_attrs) end
ruby
{ "resource": "" }
q8130
Petra.ValueComparisonError.ignore!
train
def ignore!(update_value: false) Petra.current_transaction.current_section.log_read_integrity_override(object, attribute: attribute, external_value: external...
ruby
{ "resource": "" }
q8131
Petra.WriteClashError.undo_changes!
train
def undo_changes! Petra.current_transaction.current_section.log_attribute_change_veto(object, attribute: attribute, external_value: external_value) end
ruby
{ "resource": "" }
q8132
Sem4rCli.CommandReport.download
train
def download(args) if args.length != 1 puts "missing report id for 'download' subcommand" return false end report_id = args[0].to_i report = @common_args.account.reports.find { |r| r.id == report_id } if report.nil? puts "report '#{report_id}' not found" ...
ruby
{ "resource": "" }
q8133
Sem4rCli.CommandReport.schedule
train
def schedule(argv) report = @account.report do name 'boh' type 'Url' aggregation 'Daily' cross_client true zero_impression true start_day '2010-01-01' end_day '2010-01-30' column "CustomerName" column "Extern...
ruby
{ "resource": "" }
q8134
TartanCloth::Matchers.TransformMatcher.make_patch
train
def make_patch( expected, actual ) diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"), Diff::LCS::ContextDiffCallbacks ) maxcol = diffs.flatten. collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }. flatten.max || 0 maxcol += 4 patch = "...
ruby
{ "resource": "" }
q8135
Polypaperclip.ClassMethods.initialize_polypaperclip
train
def initialize_polypaperclip if polypaperclip_definitions.nil? after_save :save_attached_files before_destroy :destroy_attached_files has_many_attachments_association write_inheritable_attribute(:polypaperclip_definitions, {}) #sequence is important...
ruby
{ "resource": "" }
q8136
Statefully.State.method_missing
train
def method_missing(name, *args, &block) sym_name = name.to_sym return fetch(sym_name) if key?(sym_name) str_name = name.to_s modifier = str_name[-1] return super unless %w[? !].include?(modifier) base = str_name[0...-1].to_sym known = key?(base) return known if modifier =...
ruby
{ "resource": "" }
q8137
Statefully.State.respond_to_missing?
train
def respond_to_missing?(name, _include_private = false) str_name = name.to_s key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super end
ruby
{ "resource": "" }
q8138
Anvil.Versioner.bump!
train
def bump!(term) fail NotSupportedTerm.new(term) unless TERMS.include?(term.to_sym) new_version = clone new_value = increment send(term) new_version.send("#{term}=", new_value) new_version.reset_terms_for(term) end
ruby
{ "resource": "" }
q8139
Anvil.Versioner.reset_terms_for
train
def reset_terms_for(term) self.minor = 0 if term == :major self.patch = 0 if term == :major || term == :minor self.pre = nil if [:major, :minor, :patch].include? term self.build = nil if [:major, :minor, :patch, :pre].include? term self end
ruby
{ "resource": "" }
q8140
Telstra.SMS.send_sms
train
def send_sms(to: sms_to, body: sms_body) [to, body] generate_token options = { body: { body: body, to: to }.to_json, headers: { "Content-Type" => "application/json", "Authorization" => "Bearer #{@token}" }} response = HT...
ruby
{ "resource": "" }
q8141
Atlas.BoxProvider.save
train
def save body = { provider: to_hash } begin response = Atlas.client.put(url_builder.box_provider_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_version_url}/providers", body: body) end ...
ruby
{ "resource": "" }
q8142
Atlas.BoxProvider.upload
train
def upload(file) # get the path for upload response = Atlas.client.get("#{url_builder.box_provider_url}/upload") # upload the file upload_url = response['upload_path'] Excon.put(upload_url, body: file) end
ruby
{ "resource": "" }
q8143
CronR.CronJob.runnable?
train
def runnable? time result = [:minute,:hour,:day,:dow,:month].map{|ct| if self[ct] == true then true else case ct when :month,:day,:hour val = time.send(ct) when :dow val = time.wday when :minute val = time.min ...
ruby
{ "resource": "" }
q8144
Permit.PermitRules.allow
train
def allow(roles, options = {}) actions = options.delete(:to) rule = PermitRule.new(roles, options) index_rule_by_actions @action_allow_rules, actions, rule return rule end
ruby
{ "resource": "" }
q8145
Tinia.ActiveRecord.indexed_with_cloud_search
train
def indexed_with_cloud_search(&block) mods = [ Tinia::Connection, Tinia::Index, Tinia::Search ] mods.each do |mod| unless self.included_modules.include?(mod) self.send(:include, mod) end end # config block yield(self) if block_given?...
ruby
{ "resource": "" }
q8146
Smsified.Subscriptions.create_inbound_subscription
train
def create_inbound_subscription(destination_address, options) query = options.merge({ :destination_address => destination_address }) Response.new self.class.post("/smsmessaging/inbound/subscriptions", :basic_auth => @auth, :body ...
ruby
{ "resource": "" }
q8147
YamledAcl.ControllerExtension.authorize_action
train
def authorize_action YamledAcl.init(current_user_group_name, params[:controller]) allowed_to?(params[:action]) or raise(YamledAcl::AccessDenied) end
ruby
{ "resource": "" }
q8148
Mysticonfig.Loader.load
train
def load config_file = find_file @filenames config = Utils.load_auto config_file config.empty? ? @default_config : @default_config.merge(config) end
ruby
{ "resource": "" }
q8149
Mysticonfig.Loader.load_json
train
def load_json json_config_file = Utils.lookup_file @filenames[:json] config = Utils.load_json json_config_file config.empty? ? @default_config : @default_config.merge(config) end
ruby
{ "resource": "" }
q8150
Mysticonfig.Loader.load_yaml
train
def load_yaml yaml_config_files = @filenames[:yaml] yaml_config_file = nil yaml_config_files.each do |file| yaml_config_file = Utils.lookup_file file unless yaml_config_file.nil? config = Utils.load_yaml(yaml_config_file) return config.empty? ? @default_config : @d...
ruby
{ "resource": "" }
q8151
VCSToolkit.Diff.new_content
train
def new_content(conflict_start='<<<', conflict_switch='>>>', conflict_end='===') flat_map do |change| if change.conflict? version_one = change.diff_one.new_content(conflict_start, conflict_switch, conflict_end) version_two = change.diff_two.new_content(conflict_start, conflict_switch, ...
ruby
{ "resource": "" }
q8152
RubyEdit.SourceFile.populate
train
def populate(content, **options) generator.create_file(RubyEdit::SOURCE_FILE_LOCATION, content, force: true, verbose: false, **options) end
ruby
{ "resource": "" }
q8153
RImageAnalysisTools.Skeletonizer.compute_n
train
def compute_n(ic) temp_ic = ImageCoordinate.cloneCoord(ic) n = -1 # compensate for 0,0 case x_off = [-1,0,1] y_off = [-1,0,1] x_off.each do |x| y_off.each do |y| temp_ic[:x] = ic[:x] + x temp_ic[:y] = ic[:y] + y if @im.inBounds(temp_ic) and @im[...
ruby
{ "resource": "" }
q8154
BoardGameGrid.SquareSet.where
train
def where(hash) res = hash.inject(squares) do |memo, (attribute, value)| memo.select { |square| square.attribute_match?(attribute, value) } end self.class.new(squares: res) end
ruby
{ "resource": "" }
q8155
BoardGameGrid.SquareSet.find_by_x_and_y
train
def find_by_x_and_y(x, y) select { |square| square.x == x && square.y == y }.first end
ruby
{ "resource": "" }
q8156
BoardGameGrid.SquareSet.in_range
train
def in_range(origin, distance) select { |square| Vector.new(origin, square).magnitude <= distance } end
ruby
{ "resource": "" }
q8157
BoardGameGrid.SquareSet.at_range
train
def at_range(origin, distance) select { |square| Vector.new(origin, square).magnitude == distance } end
ruby
{ "resource": "" }
q8158
BoardGameGrid.SquareSet.unblocked
train
def unblocked(origin, square_set) select { |destination| square_set.between(origin, destination).all?(&:unoccupied?) } end
ruby
{ "resource": "" }
q8159
BoardGameGrid.SquareSet.between
train
def between(origin, destination) vector = Vector.new(origin, destination) if vector.diagonal? || vector.orthogonal? point_counter = origin.point direction = vector.direction _squares = [] while point_counter != destination.point point_counter = point_counter + dir...
ruby
{ "resource": "" }
q8160
Derelict.Parser::Version.version
train
def version logger.debug "Parsing version from output using #{description}" matches = output.match PARSE_VERSION_FROM_OUTPUT raise InvalidFormat.new output if matches.nil? matches.captures[0] end
ruby
{ "resource": "" }
q8161
Valr.Repo.full_changelog
train
def full_changelog(first_parent: false, range: nil, branch: nil, from_ancestor_with: nil) changelog_list = changelog first_parent: first_parent, range: range, branch: branch, from_ancestor_with: from_ancestor_with if !range.nil? header = full_changelog_header_range range elsif !branch.nil? ...
ruby
{ "resource": "" }
q8162
Valr.Repo.log_messages
train
def log_messages(first_parent = false, range = nil, branch = nil, from_ancestor_with = nil) walker = Rugged::Walker.new @repo if !range.nil? begin walker.push_range range rescue Rugged::ReferenceError raise Valr::NotValidRangeError.new range end elsif !branc...
ruby
{ "resource": "" }
q8163
Valr.Repo.full_changelog_header_range
train
def full_changelog_header_range(range) from, to = range.split '..' from_commit, to_commit = [from, to].map { |ref| rev_parse ref } Koios::Doc.write { [pre(["from: #{from} <#{from_commit.oid}>", "to: #{to} <#{to_commit.oid}>"])] } end
ruby
{ "resource": "" }
q8164
Valr.Repo.full_changelog_header_branch
train
def full_changelog_header_branch(branch, ancestor) h = ["branch: #{branch} <#{@repo.references["refs/heads/#{branch}"].target_id}>"] h << "from ancestor with: #{ancestor} <#{@repo.references["refs/heads/#{ancestor}"].target_id}>" unless ancestor.nil? Koios::Doc.write {[pre(h)]} end
ruby
{ "resource": "" }
q8165
Grayskull.Validator.match_node
train
def match_node(node,expected,label) #check type if !check_type(node,expected['type'],label,expected['ok_empty']) @errors.push('Error: node ' + label + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', ')) return false end ...
ruby
{ "resource": "" }
q8166
Grayskull.Validator.check_type
train
def check_type(node,expected_type,label,accept_nil = false) valid_type = true; if(@types.has_key?(expected_type)) valid_type = match_node(node,@types[expected_type],label) elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || a...
ruby
{ "resource": "" }
q8167
MicroservicePrecompiler.Builder.cleanup
train
def cleanup(sprocket_assets = [:javascripts, :stylesheets]) # Remove previous dist path FileUtils.rm_r build_path if File.exists?(build_path) # Clean compass project Compass::Exec::SubCommandUI.new(["clean", project_root]).run! # Don't initialize Compass assets, the config will take care o...
ruby
{ "resource": "" }
q8168
MicroservicePrecompiler.Builder.sprockets_build
train
def sprockets_build(sprocket_assets = [:javascripts, :stylesheets]) sprocket_assets.each do |asset_type| load_path = File.join(@project_root, asset_type.to_s) next unless File.exists?(load_path) sprockets_env.append_path load_path Dir.new(load_path).each do |filename| fil...
ruby
{ "resource": "" }
q8169
MicroservicePrecompiler.Builder.mustache_template_build
train
def mustache_template_build(dir, template_file, logic_file) # Get the class name from an underscore-named file logic_class_name = underscore_to_camelcase(logic_file) # Output file should match the syntax of the mustaches config output_file = logic_file # Now we can name the logic_file to u...
ruby
{ "resource": "" }
q8170
MicroservicePrecompiler.Builder.underscore_to_camelcase
train
def underscore_to_camelcase(underscore_string) underscore_string = underscore_string.gsub(/(_)/,' ').split(' ').each { |word| word.capitalize! }.join("") unless underscore_string.match(/_/).nil? underscore_string = underscore_string if underscore_string.match(/_/).nil? return underscore_string end
ruby
{ "resource": "" }
q8171
MicroservicePrecompiler.Builder.sprockets_env
train
def sprockets_env @sprockets_env ||= Sprockets::Environment.new(project_root) { |env| env.logger = Logger.new(STDOUT) } end
ruby
{ "resource": "" }
q8172
MicroservicePrecompiler.Builder.minify
train
def minify(asset, format) asset = asset.to_s # Minify JS return Uglifier.compile(asset) if format.eql?("js") # Minify CSS return YUI::CssCompressor.new.compress(asset) if format.eql?("css") # Return string representation if not minimizing return asset end
ruby
{ "resource": "" }
q8173
VirtualMonkey.DeploymentRunner.launch_all
train
def launch_all @servers.each { |s| begin object_behavior(s, :start) rescue Exception => e raise e unless e.message =~ /AlreadyLaunchedError/ end } end
ruby
{ "resource": "" }
q8174
VirtualMonkey.DeploymentRunner.check_monitoring
train
def check_monitoring @servers.each do |server| server.settings response = nil count = 0 until response || count > 20 do begin response = server.monitoring rescue response = nil count += 1 sleep 10 end ...
ruby
{ "resource": "" }
q8175
RedisRecord.Model.add_attributes
train
def add_attributes(hash) hash.each_pair do |k,v| k = k.to_sym #raise DuplicateAttribute.new("#{k}") unless (k == :id or !self.respond_to?(k)) if k == :id or !self.respond_to?(k) @cached_attrs[k] = v meta = class << self; self; end meta.send(:define_method, k) ...
ruby
{ "resource": "" }
q8176
RedisRecord.Model.add_foreign_keys_as_attributes
train
def add_foreign_keys_as_attributes @@reflections[self.class.name.to_sym][:belongs_to].each do |klass| add_attribute klass.to_s.foreign_key.to_sym end end
ruby
{ "resource": "" }
q8177
Dctl.Main.image_tag
train
def image_tag(image, version: current_version_for_image(image)) org = settings.org project = settings.project tag = "#{org}/#{project}-#{env}-#{image}" if !version.nil? version = version.to_i tag += if version.negative? current_version = current_ver...
ruby
{ "resource": "" }
q8178
Dctl.Main.config_path
train
def config_path path = File.expand_path ".dctl.yml", Dir.pwd unless File.exist? path error = "Could not find config file at #{path}" puts Rainbow(error).red exit 1 end path end
ruby
{ "resource": "" }
q8179
Dctl.Main.define_custom_commands
train
def define_custom_commands(klass) Array(settings.custom_commands).each do |command, args| klass.send(:desc, command, "[Custom Command] #{command}") # Concat with string so we can use exec rather than executing multiple # subshells. Exec allows us to reuse the shell in which dctl is being ...
ruby
{ "resource": "" }
q8180
Dctl.Main.check_settings!
train
def check_settings! required_keys = %w( org project ) required_keys.each do |key| unless Settings.send key error = "Config is missing required key '#{key}'. Please add it " \ "to #{config_path} and try again." error += "\n\nFor more info, see ht...
ruby
{ "resource": "" }
q8181
Sinatra.Helpers.select_options
train
def select_options(pairs, current = nil, prompt = nil) pairs.unshift([prompt, '']) if prompt pairs.map { |label, value| tag(:option, label, :value => value, :selected => (current == value)) }.join("\n") end
ruby
{ "resource": "" }
q8182
Sinatra.Helpers.errors_on
train
def errors_on(object, options = { :class => 'errors' }, &block) return if object.errors.empty? lines = if object.errors.respond_to?(:full_messages) object.errors.full_messages else HamlErrorPresenter.new(object.errors).present(self, &block) end haml_tag(:div, options) do ...
ruby
{ "resource": "" }
q8183
Sinatra.Helpers.percentage
train
def percentage(number, precision = 2) return if number.to_s.empty? ret = "%02.#{ precision }f%" % number ret.gsub(/\.0*%$/, '%') end
ruby
{ "resource": "" }
q8184
BuoyData.NoaaBuoyObservation.google_chart_url
train
def google_chart_url max = 120 response = get_all return unless response historical_data = [] response.each_with_index do |row, index| break if index >= max next if row.match(/^#/) row = row.split(/ ?/) historical_data << row[5] end return if ...
ruby
{ "resource": "" }
q8185
Octo.ContactUs.send_email
train
def send_email # Send thankyou mail subject = 'Thanks for contacting us - Octo.ai' opts = { text: 'Hey we will get in touch with you shortly. Thanks :)', name: self.firstname + ' ' + self.lastname } Octo::Email.send(self.email, subject, opts) # Send mail to aron and param ...
ruby
{ "resource": "" }
q8186
Raca.Servers.create
train
def create(server_name, flavor_name, image_name, files = {}) request = { "server" => { "name" => server_name, "imageRef" => image_name_to_id(image_name), "flavorRef" => flavor_name_to_id(flavor_name), } } files.each do |path, blob| request['server'...
ruby
{ "resource": "" }
q8187
Codependency.Graph.require
train
def require( file ) return if key?( file ) self[ file ] = deps( file ) self[ file ].each do |dependency| self.require dependency end end
ruby
{ "resource": "" }
q8188
Codependency.Graph.scan
train
def scan( glob ) Dir[ glob ].flat_map { |f| deps( f ) }.uniq.each do |dependency| self.require dependency end end
ruby
{ "resource": "" }
q8189
Codependency.Graph.deps
train
def deps( file ) parser.parse( file ).map { |f| path_to path[ f ] } end
ruby
{ "resource": "" }
q8190
Rescuetime.Loop.run
train
def run running! @current_app = Application.create(:debug => debug?) while true sleep 1 # TODO: move to config focus_changed if @current_app.finished? || backup? end end
ruby
{ "resource": "" }
q8191
FlexibleAccessibility.ControllerMethods.has_access?
train
def has_access?(permission, user) raise UnknownUserException if user.nil? AccessProvider.action_permitted_for_user?(permission, user) end
ruby
{ "resource": "" }
q8192
PuppetBox.PuppetBox.run_puppet
train
def run_puppet(driver_instance, puppet_tests, logger:nil, reset_after_run:true) # use supplied logger in preference to the default puppetbox logger instance logger = logger || @logger logger.debug("#{driver_instance.node_name} running #{puppet_tests.size} tests") if driver_instance.open ...
ruby
{ "resource": "" }
q8193
Shapewear::Request.RequestHandler.extract_parameters
train
def extract_parameters(op_options, node) logger.debug "Operation node: #{node.inspect}" r = [] op_options[:parameters].each do |p| logger.debug " Looking for: tns:#{p.first.camelize_if_symbol(:lower)}" v = node.xpath("tns:#{p.first.camelize_if_symbol(:lower)}", namespaces).first ...
ruby
{ "resource": "" }
q8194
Shapewear::Request.RequestHandler.serialize_soap_result
train
def serialize_soap_result(op_options, r) xb = Builder::XmlMarkup.new xb.instruct! xb.Envelope :xmlns => soap_env_ns, 'xmlns:xsi' => namespaces['xsi'] do |xenv| xenv.Body do |xbody| xbody.tag! "#{op_options[:public_name]}Response", :xmlns => namespaces['tns'] do |xresp| i...
ruby
{ "resource": "" }
q8195
Shapewear::Request.RequestHandler.extract_and_serialize_value
train
def extract_and_serialize_value(builder, obj, field, type) v = if obj.is_a?(Hash) obj[field] or obj[field.to_sym] or obj[field.to_s.underscore] or obj[field.to_s.underscore.to_sym] elsif obj.respond_to?(field) obj.send(field) elsif obj.respond_to?(field.underscore) obj.send(fie...
ruby
{ "resource": "" }
q8196
Shapewear::Request.RequestHandler.serialize_soap_fault
train
def serialize_soap_fault(ex) logger.debug "Serializing SOAP Fault: #{ex.inspect}" xb = Builder::XmlMarkup.new xb.instruct! xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv| xenv.tag! 'e:Body' do |xbody| xbody.tag! 'e:Fault' do |xf| case soap_version ...
ruby
{ "resource": "" }
q8197
Sinatra.EasyBreadcrumbs.view_variables
train
def view_variables instance_variables .select { |var| additional_var?(var) } .map { |var| fetch_ivar_value(var) } end
ruby
{ "resource": "" }
q8198
Gricer.CaptureController.index
train
def index gricer_request = ::Gricer.config.request_model.first_by_id(params[:id]) gricer_session = ::Gricer.config.session_model.first_by_id(session[:gricer_session]) if gricer_session gricer_session.javascript = true gricer_session.java = params[:j] ...
ruby
{ "resource": "" }
q8199
Optser.OptSet.get
train
def get(key, default=nil, &block) value = options[key] value = default if value.nil? value = block.call if value.nil? && block return value end
ruby
{ "resource": "" }