_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q27500
Ropenstack.Image::Version2.upload_image_from_file
test
def upload_image_from_file(name, disk_format, container_format, minDisk, minRam, is_public, file) data = { "name" => name, "disk_format" => disk_format, "container_format" => container_format, "minDisk" => minDisk, "minRam" => minRam, "public" => is_public } imagesBefore = images() post_request(address("images"), data, @token, false) imagesAfter = images() foundNewImage = true image = nil imagesAfter.each do |imageA| imagesBefore.each do |imageB| if(imageA == imageB) foundNewImage = false end end if(foundNewImage) image = imageA break end end return put_octect(address(image["file"]), file.read, false) end
ruby
{ "resource": "" }
q27501
Ropenstack.Image::Version2.put_octect
test
def put_octect(uri, data, manage_errors) headers = build_headers(@token) headers["Content-Type"] = 'application/octet-stream' req = Net::HTTP::Put.new(uri.request_uri, initheader = headers) req.body = data return do_request(uri, req, manage_errors, 0) end
ruby
{ "resource": "" }
q27502
Qwiki.App.relative_path
test
def relative_path(path) path = File.expand_path(path) root = full_path("") if path.size >= root.size && path[0...root.size] == root path[0...root.size] = "" path = "/" if path.size == 0 path end end
ruby
{ "resource": "" }
q27503
Qwiki.App.index
test
def index(path) @entries = [] Dir.entries(path).each do |entry| relative_path = relative_path(File.join(path, entry)) if entry != "." && relative_path @entries << {:name => entry, :href => relative_path} end end @path = path haml :index end
ruby
{ "resource": "" }
q27504
Tabledata.Table.accessors_from_headers!
test
def accessors_from_headers! raise "Can't define accessors from headers in a table without headers" unless @has_headers self.accessors = headers.map { |val| (val && !val.empty?) ? val.to_s.downcase.tr('^a-z0-9_', '_').squeeze('_').gsub(/\A_|_\z/, '').to_sym : nil } end
ruby
{ "resource": "" }
q27505
Tabledata.Table.<<
test
def <<(row) index = @data.size begin row = row.to_ary rescue NoMethodError raise ArgumentError, "Row must be provided as Array or respond to `to_ary`, but got #{row.class} in row #{index}" unless row.respond_to?(:to_ary) raise end raise InvalidColumnCount.new(index, row.size, column_count) if @data.first && row.size != @data.first.size @data << row @rows << Row.new(self, index, row) self end
ruby
{ "resource": "" }
q27506
Hemingway.FootnoteNode.html
test
def html(id, time) inline_footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "inline-footnote-number") Build.tag("a", inline_footnote_label, :href => "#footnote#{id}#{time}") end
ruby
{ "resource": "" }
q27507
Hemingway.FootnoteNode.footnote_html
test
def footnote_html(id, time) footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "footnote-number") footnote_content = sequence.elements.map { |s| s.html }.join Build.tag("div", footnote_label + footnote_content, :id => "footnote#{id}#{time}", :class => "footnote") end
ruby
{ "resource": "" }
q27508
Ropenstack.Database::Version1.instance_action
test
def instance_action(id, action, param) case action when "RESTART" post_request(address("/instances/" + id + "/action"), {:restart => {}}, @token) when "RESIZE" if param.is_a? String post_request(address("/instances/" + id + "/action"), {:resize => {:flavorRef => param }}, @token) elsif param.is_a? Int post_request(address("/instances/" + id + "/action"), {:resize => {:volume => {:size => param }}}, @token) else raise Ropenstack::RopenstackError, "Invalid Parameter Passed" end else raise Ropenstack::RopenstackError, "Invalid Action Passed" end end
ruby
{ "resource": "" }
q27509
Revenc.Errors.add
test
def add(error_on, message = "Unknown error") # humanize error_on if error_on.is_a?(Symbol) error_on_str = error_on.to_s else error_on_str = underscore(error_on.class.name) end error_on_str = error_on_str.gsub(/\//, '_') error_on_str = error_on_str.gsub(/_/, ' ') error_on_str = error_on_str.gsub(/^revenc/, '').strip #error_on_str = error_on_str.capitalize @errors[error_on_str] ||= [] @errors[error_on_str] << message.to_s end
ruby
{ "resource": "" }
q27510
GameOfLife.Board.coords_of_neighbors
test
def coords_of_neighbors(x, y) coords_of_neighbors = [] (x - 1).upto(x + 1).each do |neighbors_x| (y - 1).upto(y + 1).each do |neighbors_y| next if (x == neighbors_x) && (y == neighbors_y) coords_of_neighbors << [neighbors_x, neighbors_y] end end coords_of_neighbors end
ruby
{ "resource": "" }
q27511
RSqoot.Merchant.merchant
test
def merchant(id, options = {}) options = update_by_expire_time options if merchant_not_latest?(id) @rsqoot_merchant = get("merchants/#{id}", options, SqootMerchant) @rsqoot_merchant = @rsqoot_merchant.merchant if @rsqoot_merchant end logger(uri: sqoot_query_uri, records: [@rsqoot_merchant], type: 'merchants', opts: options) @rsqoot_merchant end
ruby
{ "resource": "" }
q27512
EventMachine::WebSocketCodec.Encoder.encode
test
def encode data, opcode=TEXT_FRAME frame = [] frame << (opcode | 0x80) packr = "CC" if opcode == TEXT_FRAME data.force_encoding("UTF-8") if !data.valid_encoding? raise "Invalid UTF!" end end # append frame length and mask bit 0x80 len = data ? data.bytesize : 0 if len <= 125 frame << (len | 0x80) elsif len < 65536 frame << (126 | 0x80) frame << len packr << "n" else frame << (127 | 0x80) frame << len packr << "L!>" end # generate a masking key key = rand(2 ** 31) # mask each byte with the key frame << key packr << "N" #puts "op #{opcode} len #{len} bytes #{data}" # Apply the masking key to every byte len.times do |i| frame << ((data.getbyte(i) ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF) end frame.pack("#{packr}C*") end
ruby
{ "resource": "" }
q27513
Challah::Rolls.Permission.challah_permission
test
def challah_permission unless included_modules.include?(InstanceMethods) include InstanceMethods extend ClassMethods end class_eval do validates_presence_of :name, :key validates_uniqueness_of :name, :key validates_format_of :key, :with => /^([a-z0-9_])*$/, :message => :invalid_key has_many :permission_roles, :dependent => :destroy has_many :roles, :through => :permission_roles, :order => 'roles.name' has_many :permission_users, :dependent => :destroy has_many :users, :through => :permission_users, :order => 'users.last_name, users.first_name' default_scope order('permissions.name') attr_accessible :name, :description, :key, :locked after_create :add_to_admin_role end end
ruby
{ "resource": "" }
q27514
Connectors.ApiConnector.post
test
def post hash={}, payload raise 'Payload cannot be blank' if payload.nil? || payload.empty? hash.symbolize_keys! call(:post, hash[:endpoint], (hash[:args]||{}).merge({:method => :post}), payload) end
ruby
{ "resource": "" }
q27515
Ropenstack.Networking.create_network
test
def create_network(name, tenant, admin_state_up = true) data = { 'network' => { 'name' => name, 'tenant_id' => tenant, 'admin_state_up' => admin_state_up } } return post_request(address("networks"), data, @token) end
ruby
{ "resource": "" }
q27516
Ropenstack.Networking.create_port
test
def create_port(network, subnet = nil, device = nil, device_owner = nil) data = { 'port' => { 'network_id' => network, } } unless device_owner.nil? data['port']['device_owner'] = device_owner end unless device.nil? data['port']['device_id'] = device end unless subnet.nil? data['port']['fixed_ips'] = [{'subnet_id' => subnet}] end puts data return post_request(address("ports"), data, @token) end
ruby
{ "resource": "" }
q27517
Ropenstack.Networking.move_port_to_subnets
test
def move_port_to_subnets(port_id, subnet_ids) id_list = Array.new() subnet_ids.each do |id| id_list << { "subnet_id" => id } end return update_port(port_id, id_list) end
ruby
{ "resource": "" }
q27518
Rack.Action.json
test
def json(data={}, options={}) response[CONTENT_TYPE] = APPLICATION_JSON response.status = options[:status] if options.has_key?(:status) response.write self.class.json_serializer.dump(data) end
ruby
{ "resource": "" }
q27519
Rack.Action.redirect_to
test
def redirect_to(url, options={}) full_url = absolute_url(url, options) response[LOCATION] = full_url respond_with 302 full_url end
ruby
{ "resource": "" }
q27520
Ropenstack.Compute.servers
test
def servers(id) endpoint = "/servers" unless id.nil? endpoint = endpoint + "/" + id end return get_request(address(endpoint), @token) end
ruby
{ "resource": "" }
q27521
Ropenstack.Compute.create_server
test
def create_server(name, image, flavor, networks = nil, keypair = nil, security_group = nil, metadata = nil) data = { "server" => { "name" => name, "imageRef" => image, "flavorRef" => flavor, } } unless networks.nil? data["server"]["networks"] = networks end unless keypair.nil? data["server"]["key_name"] = keypair end unless security_group.nil? data["server"]["security_group"] = security_group end return post_request(address("/servers"), data, @token) end
ruby
{ "resource": "" }
q27522
Ropenstack.Compute.action
test
def action(id, act, *args) data = case act when "reboot" then {'reboot' =>{"type" => args[0]}} when "vnc" then {'os-getVNCConsole' => { "type" => "novnc" }} when "stop" then {'os-stop' => 'null'} when "start" then {'os-start' => 'null'} when "pause" then {'pause' => 'null'} when "unpause" then {'unpause' => 'null'} when "suspend" then {'suspend' => 'null'} when "resume" then {'resume' => 'null'} when "create_image" then {'createImage' => {'name' => args[0], 'metadata' => args[1]}} else raise "Invalid Action" end return post_request(address("/servers/" + id + "/action"), data, @token) end
ruby
{ "resource": "" }
q27523
Ropenstack.Compute.delete_image
test
def delete_image(id) uri = URI.parse("http://" + @location.host + ":" + @location.port.to_s + "/v2/images/" + id) return delete_request(uri, @token) end
ruby
{ "resource": "" }
q27524
RSqoot.Request.get
test
def get(path, opts = {}, wrapper = ::Hashie::Mash) uri, headers = url_generator(path, opts) begin json = JSON.parse uri.open(headers).read result = wrapper.new json @query_options = result.query result rescue => e logger(error: e) nil end end
ruby
{ "resource": "" }
q27525
Optimacms.Template.set_basepath
test
def set_basepath if self.parent.nil? self.basepath = self.basename self.basedirpath ||= '' else self.basepath = self.parent.basepath+'/'+self.basename self.basedirpath ||= self.parent.basepath+'/' end end
ruby
{ "resource": "" }
q27526
RSqoot.Commission.commissions
test
def commissions(options = {}) options = update_by_expire_time options if commissions_not_latest?(options) @rsqoot_commissions = get('commissions', options, SqootCommission) @rsqoot_commissions = @rsqoot_commissions.commissions if @rsqoot_commissions end logger(uri: sqoot_query_uri, records: @rsqoot_commissions, type: 'commissions', opts: options) @rsqoot_commissions end
ruby
{ "resource": "" }
q27527
FootballRuby.Client.leagues
test
def leagues(opts={}) season = opts.fetch(:season) { Time.now.year } json_response get("competitions/?season=#{season}") end
ruby
{ "resource": "" }
q27528
Ov.Ext.match
test
def match(*args, &block) z = Module.new do include Ov extend self def try(*args, &block) let :anon_method, *args, &block end def otherwise(&block) let :otherwise, &block end instance_eval &block end begin z.anon_method(*args) rescue Ov::NotImplementError => e z.otherwise end end
ruby
{ "resource": "" }
q27529
Tabledata.Row.fetch
test
def fetch(column, *default_value, &default_block) raise ArgumentError, "Must only provide at max one default value or one default block" if default_value.size > (block_given? ? 0 : 1) index = case column when Symbol then @table.index_for_accessor(column) when String then @table.index_for_header(column) when Integer then column else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}" end @data.fetch(index, *default_value, &default_block) end
ruby
{ "resource": "" }
q27530
Tabledata.Row.at
test
def at(column) case column when Symbol then at_accessor(column) when String then at_header(column) when Integer then at_index(column) when Range then @data[column] else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}" end end
ruby
{ "resource": "" }
q27531
Tabledata.Row.values_at
test
def values_at(*columns) result = [] columns.each do |column| data = at(column) if column.is_a?(Range) result.concat(data) if data else result << data end end result end
ruby
{ "resource": "" }
q27532
Tabledata.Row.method_missing
test
def method_missing(name, *args, &block) return super unless @table.accessors? name =~ /^(\w+)(=)?$/ name_mod, assign = $1, $2 index = @table.index_for_accessor(name_mod) arg_count = assign ? 1 : 0 return super unless index raise ArgumentError, "Wrong number of arguments (#{args.size} for #{arg_count})" if args.size > arg_count if assign then @data[index] = args.first else @data[index] end end
ruby
{ "resource": "" }
q27533
TaskMapper::Provider.Unfuddle.authorize
test
def authorize(auth = {}) @authentication ||= TaskMapper::Authenticator.new(auth) auth = @authentication if (auth.account.nil? and auth.subdomain.nil?) or auth.username.nil? or auth.password.nil? raise "Please provide at least an account (subdomain), username and password)" end UnfuddleAPI.protocol = auth.protocol if auth.protocol? UnfuddleAPI.account = auth.account || auth.subdomain UnfuddleAPI.authenticate(auth.username, auth.password) end
ruby
{ "resource": "" }
q27534
Ropenstack::Networking::Version2::Extensions.L3.routers
test
def routers(id = nil) endpoint = "routers" unless id.nil? endpoint = endpoint + "/" + id end return get_request(address(endpoint), @token) end
ruby
{ "resource": "" }
q27535
Ropenstack::Networking::Version2::Extensions.L3.create_router
test
def create_router(name, admin_state_up = true) data = { 'router' =>{ 'name' => name, 'admin_state_up' => admin_state_up, } } return post_request(address("routers"), data, @token) end
ruby
{ "resource": "" }
q27536
Ropenstack::Networking::Version2::Extensions.L3.delete_router_interface
test
def delete_router_interface(router, id, type) data = case type when 'port' then { 'port_id' => id } when 'subnet' then { 'subnet_id' => id } else raise "Invalid Interface Type" end return put_request(address("routers/" + router + "/remove_router_interface"), data, @token) end
ruby
{ "resource": "" }
q27537
Ov.OA.where
test
def where(method) @complete, @result = nil, nil z = find_or_next(method) { |method| self.find{|m| m.eql?(method) } }.find_or_next(method) { |method| self.find{|m| m.eql0?(method) } }.find_or_next(method) { |method| self.find{|m| m.like?(method) } }.find_or_next(method) {|method| self.find{|m| m.like0?(method) } }.get end
ruby
{ "resource": "" }
q27538
Semistatic.Configuration.load
test
def load config_files.each do |file| config = YAML::load(File.open(file)) @config.merge! config end end
ruby
{ "resource": "" }
q27539
RSqoot.Provider.providers
test
def providers(options = {}) options = update_by_expire_time options query = options.delete(:query) if providers_not_latest?(options) @rsqoot_providers = get('providers', options, SqootProvider) @rsqoot_providers = @rsqoot_providers.providers.map(&:provider) if @rsqoot_providers end result = query.present? ? query_providers(query) : @rsqoot_providers logger(uri: sqoot_query_uri, records: result, type: 'providers', opts: options) result end
ruby
{ "resource": "" }
q27540
RSqoot.Category.categories
test
def categories(options = {}) options = update_by_expire_time options query = options.delete(:query) if categories_not_latest?(options) @rsqoot_categories = get('categories', options, SqootCategory) @rsqoot_categories = @rsqoot_categories.categories.map(&:category) if @rsqoot_categories end result = query.present? ? query_categories(query) : @rsqoot_categories logger(uri: sqoot_query_uri, records: result, type: 'categories', opts: options) result end
ruby
{ "resource": "" }
q27541
Challah::Rolls.Role.challah_role
test
def challah_role unless included_modules.include?(InstanceMethods) include InstanceMethods extend ClassMethods end class_eval do # Validations ################################################################ validates :name, :presence => true, :uniqueness => true # Relationships ################################################################ has_many :permission_roles, :dependent => :destroy has_many :permissions, :through => :permission_roles, :order => 'permissions.name' has_many :users, :order => 'users.first_name, users.last_name' # Scoped Finders ################################################################ default_scope order('roles.name') # Callbacks ################################################################ after_save :save_permission_keys # Attributes ################################################################ attr_accessible :description, :default_path, :locked, :name end end
ruby
{ "resource": "" }
q27542
Tang.Subscription.check_for_upgrade
test
def check_for_upgrade if plan_id_changed? old_plan = Plan.find(plan_id_was) if plan_id_was.present? self.upgraded = true if old_plan.nil? || old_plan.order < plan.order end end
ruby
{ "resource": "" }
q27543
ZeevexProxy.Base.method_missing
test
def method_missing(name, *args, &block) obj = __getobj__ __substitute_self__(obj.__send__(name, *args, &block), obj) end
ruby
{ "resource": "" }
q27544
RSqoot.Deal.deals
test
def deals(options = {}) options = update_by_expire_time options if deals_not_latest?(options) uniq = !!options.delete(:uniq) @rsqoot_deals = get('deals', options, SqootDeal) || [] @rsqoot_deals = @rsqoot_deals.deals.map(&:deal) unless @rsqoot_deals.empty? @rsqoot_deals = uniq_deals(@rsqoot_deals) if uniq end logger(uri: sqoot_query_uri, records: @rsqoot_deals, type: 'deals', opts: options) @rsqoot_deals end
ruby
{ "resource": "" }
q27545
RSqoot.Deal.deal
test
def deal(id, options = {}) options = update_by_expire_time options if deal_not_latest?(id) @rsqoot_deal = get("deals/#{id}", options, SqootDeal) @rsqoot_deal = @rsqoot_deal.deal if @rsqoot_deal end logger(uri: sqoot_query_uri, records: [@rsqoot_deal], type: 'deal', opts: options) @rsqoot_deal end
ruby
{ "resource": "" }
q27546
RSqoot.Deal.total_sqoot_deals
test
def total_sqoot_deals(options = {}) @total_deals ||= [] @cached_pages ||= [] page = options[:page] || 1 check_query_change options unless page_cached? page @total_deals += deals(options) @total_deals.uniq! @cached_pages << page.to_s @cached_pages.uniq! end @total_deals end
ruby
{ "resource": "" }
q27547
RSqoot.Deal.uniq_deals
test
def uniq_deals(deals = []) titles = deals.map(&:title).uniq titles.map do |title| deals.map do |deal| deal if deal.try(:title) == title end.compact.last end.flatten end
ruby
{ "resource": "" }
q27548
Watir.Browser.load_cookies
test
def load_cookies(file) now = ::Time.now io = case file when String open(file) else file end io.each_line do |line| line.chomp! line.gsub!(/#.+/, '') fields = line.split("\t") next if fields.length != 7 name, value, domain, for_domain, path, secure, version = fields[5], fields[6], fields[0], (fields[1] == "TRUE"), fields[2], (fields[3] == "TRUE"), 0 expires_seconds = fields[4].to_i expires = (expires_seconds == 0) ? nil : ::Time.at(expires_seconds) next if expires and (expires < now) cookies.add(name, value, domain: domain, path: path, expires: expires, secure: secure) end io.close if String === file self end
ruby
{ "resource": "" }
q27549
Watir.Browser.dump_cookies
test
def dump_cookies(file) io = case file when String open(file, "w") else file end cookies.to_a.each do |cookie| io.puts([ cookie[:domain], "FALSE", # for_domain cookie[:path], cookie[:secure] ? "TRUE" : "FALSE", cookie[:expires].to_i.to_s, cookie[:name], cookie[:value] ].join("\t")) end io.close if String === file self end
ruby
{ "resource": "" }
q27550
Watir.Element.set2
test
def set2(selector, value=nil) elem = element(xpath: selector).to_subtype case elem when Watir::Radio elem.set when Watir::Select elem.select value when Watir::Input elem.set value when Watir::TextArea elem.set value else elem.click end end
ruby
{ "resource": "" }
q27551
RSqoot.Helper.update_by_expire_time
test
def update_by_expire_time(options = {}) @expired_in = options[:expired_in] if options[:expired_in].present? time = Time.now.to_i / expired_in.to_i options.merge(expired_in: time) end
ruby
{ "resource": "" }
q27552
RubyMeetup.Client.get
test
def get(options={}) uri = new_uri params = merge_params(options) uri.query = URI.encode_www_form(params) Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| request = Net::HTTP::Get.new(uri) response = http.request(request) unless response.is_a?(Net::HTTPSuccess) raise "#{response.code} #{response.message}\n#{response.body}" end return response.body end end
ruby
{ "resource": "" }
q27553
Ropenstack.Image::Version1.images
test
def images(id, tenant_id) if id.nil? return get_request(address(tenant_id, "images/detail"), @token) else return get_request(address(tenant_id, "images/" + id), @token) end end
ruby
{ "resource": "" }
q27554
Ropenstack.Image::Version1.image_create
test
def image_create(name, disk_format, container_format, create_image, tenant_id) data = { :name => name, :disk_format => disk_format, :container_format => container_format } unless create_image.nil? data[:create_image] = create_image end post_request(address(tenant_id, "images"), data, @token) end
ruby
{ "resource": "" }
q27555
Ropenstack.Image::Version1.replace_memberships
test
def replace_memberships(id, memberships, tenant_id) data = { :memberships => memberships } put_request(address(tenant_id, "images/" + id + "/members"), data, @token) end
ruby
{ "resource": "" }
q27556
Ropenstack.Image::Version1.add_member
test
def add_member(id, member_id, can_share, tenant_id) if can_share.nil? data = { :member => {:can_share => false} } else data = { :member => {:can_share => can_share} } end put_request(address(tenant_id, "images/" + id + "/members/" + member_id), data, @token) end
ruby
{ "resource": "" }
q27557
Scripto.FileCommands.mkdir
test
def mkdir(dir, owner: nil, mode: nil) FileUtils.mkdir_p(dir, verbose: verbose?) chown(dir, owner) if owner chmod(dir, mode) if mode end
ruby
{ "resource": "" }
q27558
Scripto.FileCommands.cp
test
def cp(src, dst, mkdir: false, owner: nil, mode: nil) mkdir_if_necessary(File.dirname(dst)) if mkdir FileUtils.cp_r(src, dst, preserve: true, verbose: verbose?) chown(dst, owner) if owner && !File.symlink?(dst) chmod(dst, mode) if mode end
ruby
{ "resource": "" }
q27559
Scripto.FileCommands.mv
test
def mv(src, dst, mkdir: false) mkdir_if_necessary(File.dirname(dst)) if mkdir FileUtils.mv(src, dst, verbose: verbose?) end
ruby
{ "resource": "" }
q27560
Scripto.FileCommands.ln
test
def ln(src, dst) FileUtils.ln_sf(src, dst, verbose: verbose?) rescue Errno::EEXIST => e # It's a race - this can occur because ln_sf removes the old # dst, then creates the symlink. Raise if they don't match. raise e if !(File.symlink?(dst) && src == File.readlink(dst)) end
ruby
{ "resource": "" }
q27561
Scripto.FileCommands.chmod
test
def chmod(file, mode) return if File.stat(file).mode == mode FileUtils.chmod(mode, file, verbose: verbose?) end
ruby
{ "resource": "" }
q27562
Scripto.FileCommands.rm_and_mkdir
test
def rm_and_mkdir(dir) raise "don't do this" if dir == "" FileUtils.rm_rf(dir, verbose: verbose?) mkdir(dir) end
ruby
{ "resource": "" }
q27563
Scripto.FileCommands.copy_metadata
test
def copy_metadata(src, dst) stat = File.stat(src) File.chmod(stat.mode, dst) File.utime(stat.atime, stat.mtime, dst) end
ruby
{ "resource": "" }
q27564
Scripto.FileCommands.atomic_write
test
def atomic_write(path) tmp = Tempfile.new(File.basename(path)) yield(tmp) tmp.close chmod(tmp.path, 0o644) mv(tmp.path, path) ensure rm_if_necessary(tmp.path) end
ruby
{ "resource": "" }
q27565
Capybarbecue.Server.handle_requests
test
def handle_requests until @requestmq.empty? request = @requestmq.deq(true) begin request.response = @app.call(request.env) rescue Exception => e request.exception = e ensure body = request.response.try(:last) body.close if body.respond_to? :close end end end
ruby
{ "resource": "" }
q27566
Vagrantomatic.Instance.configfile_hash
test
def configfile_hash config = {} begin json = File.read(configfile) config = JSON.parse(json) rescue Errno::ENOENT # depending on whether the instance has been saved or not, we may not # yet have a configfile - allow to proceed @logger.debug "#{configfile} does not exist" @force_save = true rescue JSON::ParserError # swallow parse errors so that we can destroy and recreate automatically @logger.debug "JSON parse error in #{configfile}" @force_save = true end config end
ruby
{ "resource": "" }
q27567
SimpleFormat.AutoLink.email_addresses
test
def email_addresses(text) text.gsub(@regex[:mail]) do text = $& if auto_linked?($`, $') text else display_text = (block_given?) ? yield(text) : text # mail_to text, display_text "<a href='mailto:#{text}'>#{display_text}</a>" end end end
ruby
{ "resource": "" }
q27568
Risky::Inflector.Inflections.plural
test
def plural(rule, replacement) @uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @plurals.insert(0, [rule, replacement]) end
ruby
{ "resource": "" }
q27569
Risky::Inflector.Inflections.singular
test
def singular(rule, replacement) @uncountables.delete(rule) if rule.is_a?(String) @uncountables.delete(replacement) @singulars.insert(0, [rule, replacement]) end
ruby
{ "resource": "" }
q27570
Risky::Inflector.Inflections.irregular
test
def irregular(singular, plural) @uncountables.delete(singular) @uncountables.delete(plural) if singular[0,1].upcase == plural[0,1].upcase plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1]) singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1]) else plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1]) plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1]) singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1]) singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1]) end end
ruby
{ "resource": "" }
q27571
Revenc.ActionFolder.execute
test
def execute raise errors.to_sentences unless valid? # default failing command result = false # protect command from recursion mutex = Mutagem::Mutex.new('revenc.lck') lock_successful = mutex.execute do result = system_cmd(cmd) end raise "action failed, lock file present" unless lock_successful result end
ruby
{ "resource": "" }
q27572
HanselCore.Hansel.output
test
def output opts = options if opts.format FileUtils.mkdir_p opts.output_dir formatted_output end @results.clear end
ruby
{ "resource": "" }
q27573
HanselCore.Hansel.run
test
def run while @jobs.length > 0 do # do a warm up run first with the highest connection rate @current_job = @jobs.pop @current_rate = @current_job.high_rate.to_i httperf true (@current_job.low_rate.to_i..@current_job.high_rate.to_i). step(@current_job.rate_step.to_i) do |rate| @current_rate = rate httperf end output end end
ruby
{ "resource": "" }
q27574
Ropenstack.Identity::Version2.authenticate
test
def authenticate(username, password, tenant = nil) data = { "auth" => { "passwordCredentials" => { "username" => username, "password" => password } } } unless tenant.nil? data["auth"]["tenantName"] = tenant end @data = post_request(address("/tokens"), data, @token) end
ruby
{ "resource": "" }
q27575
Ropenstack.Identity::Version2.add_to_services
test
def add_to_services(name, type, description) data = { 'OS-KSADM:service' => { 'name' => name, 'type' => type, 'description' => description } } return post_request(address("/OS-KSADM/services"), data, token()) end
ruby
{ "resource": "" }
q27576
Ropenstack.Identity::Version2.add_endpoint
test
def add_endpoint(region, service_id, publicurl, adminurl, internalurl) data = { 'endpoint' => { 'region' => region, 'service_id' => service_id, 'publicurl' => publicurl, 'adminurl' => adminurl, 'internalurl' => internalurl } } return post_request(address("/endpoints"), data, token()) end
ruby
{ "resource": "" }
q27577
Ropenstack.Identity::Version2.get_endpoints
test
def get_endpoints(token = nil) if token.nil? return get_request(address("/endpoints"), token()) else return get_request(address("/tokens/#{token}/endpoints"), token()) end end
ruby
{ "resource": "" }
q27578
MethodDisabling.ClassMethods.disable_method
test
def disable_method(method_name, message = nil) disabled_methods[method_name] ||= DisabledMethod.new(self, method_name, message) disabled_methods[method_name].disable! end
ruby
{ "resource": "" }
q27579
MethodDisabling.DisabledMethod.to_proc
test
def to_proc disabled_method = self # This proc will be evaluated with "self" set to the original object. Proc.new do |*args, &block| disabled_method.execute(self, *args, &block) end end
ruby
{ "resource": "" }
q27580
MethodDisabling.DisabledMethod.execute
test
def execute(object, *args, &block) if disabled? raise NoMethodError, message else object.send(aliased_name, *args, &block) end end
ruby
{ "resource": "" }
q27581
MethodDisabling.DisabledMethod.alias_method!
test
def alias_method! klass.send(:define_method, replacement_name, &self) klass.send(:alias_method, aliased_name, method_name) klass.send(:alias_method, method_name, replacement_name) end
ruby
{ "resource": "" }
q27582
Ed25519Keccak.Ed25519Base.secret_to_public
test
def secret_to_public(secret, form=:byte) publickey = p_secret_to_public( change_argument_format(secret, form) ) return change_result_format( publickey, form ) end
ruby
{ "resource": "" }
q27583
Ed25519Keccak.Ed25519Base.point_equal
test
def point_equal(pa, pb) # x1 / z1 == x2 / z2 <==> x1 * z2 == x2 * z1 return false if (pa[0] * pb[2] - pb[0] * pa[2]) % @@p != 0 return false if (pa[1] * pb[2] - pb[1] * pa[2]) % @@p != 0 return true end
ruby
{ "resource": "" }
q27584
Ed25519Keccak.Ed25519Base.recover_x
test
def recover_x(y, sign) return nil if y >= @@p # x2 means x^2 x2 = (y*y-1) * modp_inv(@@d*y*y+1) # when x2==0 and sign!=0, these combination of arguments is illegal if x2.equal? 0 then unless sign.equal? 0 then return nil else return 0 end end # Compute square root of x2 x = pow_mod(x2 , ((@@p+3) / 8) , @@p) x = x * @@modp_sqrt_m1 % @@p unless ((x*x - x2) % @@p).equal? 0 return nil unless ((x*x - x2) % @@p).equal? 0 x = @@p - x unless (x & 1).equal? sign return x end
ruby
{ "resource": "" }
q27585
Ed25519Keccak.Ed25519Base.point_decompress
test
def point_decompress(s) # check argument raise ArgumentError , "Invalid input length for decompression" unless s.length.equal? 32 y = int_form_bytes(s) sign = y >> 255 y &= (1 << 255) - 1 x = recover_x(y, sign) if x.nil? then return nil else return [x, y, 1, x*y % @@p] end end
ruby
{ "resource": "" }
q27586
Ed25519Keccak.Ed25519Base.p_secret_to_public
test
def p_secret_to_public(secret) expanded = secret_expand(secret) a = expanded.first return point_compress(point_mul(a, @@G)) end
ruby
{ "resource": "" }
q27587
Semistatic.Page.part
test
def part(name) parts.select {|p| p.name.downcase == name.to_s.downcase }.first end
ruby
{ "resource": "" }