_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q24100
Phys.Unit.inverse
train
def inverse check_operable dims = dimension_uop{|a| -a} Unit.new(Rational(1,self.factor), dims) end
ruby
{ "resource": "" }
q24101
Phys.Unit.**
train
def **(x) check_operable m = Utils.as_numeric(x) dims = dimension_uop{|a| a*m} Unit.new(@factor**m,dims) end
ruby
{ "resource": "" }
q24102
Openfoodfacts.Country.products
train
def products(page: -1) Product.from_website_page(url, page: page, products_count: products_count) if url end
ruby
{ "resource": "" }
q24103
Jackpot.Notifier.send_receipt
train
def send_receipt(payment) @payment = payment @payment_url = public_receipt_payment_url(:payment_id => @payment.id, :public_token => @payment.public_token) mail(:to => "#{@payment.customer.email}", :from => Jackpot.configuration.mailer[:from], :subject => "Payment receipt") end
ruby
{ "resource": "" }
q24104
Plaintext.Resolver.text
train
def text if handler = find_handler and text = handler.text(@file, max_size: max_plaintext_bytes) text.gsub!(/\s+/m, ' ') text.strip! text.mb_chars.compose.limit(max_plaintext_bytes).to_s end end
ruby
{ "resource": "" }
q24105
Kondate.RoleFile.explore
train
def explore paths = if Config.explore_role_files? possible_paths else [get_path] end paths.find {|path| File.readable?(path) } || paths.last end
ruby
{ "resource": "" }
q24106
Djatoka.ViewHelpers.djatoka_init_openlayers
train
def djatoka_init_openlayers(rft_id, div_identifier, params={}) resolver = determine_resolver(params) metadata_url = resolver.metadata_url(rft_id) %Q|<script type="text/javascript"> jQuery(document).ready(function() {openlayersInit('#{resolver.scheme}://#{resolver.host}', '#{metadata_url}', '#{rft_id}', '#{div_identifier}'); }); </script> | end
ruby
{ "resource": "" }
q24107
I18nRouting.Mapper.localized_resources
train
def localized_resources(type = :resources, *resources, &block) localizable_route = nil if @locales res = resources.clone options = res.extract_options! r = res.first resource = resource_from_params(type, r, options.dup) # Check for translated resource stored_locale = I18n.locale @locales.each do |locale| I18n.locale = locale localized_path = I18nRouting.translation_for(resource.name, type) # A translated route exists : if !localized_path.blank? and String === localized_path puts("[I18n] > localize %-10s: %40s (%s) => /%s" % [type, resource.name, locale, localized_path]) if @i18n_verbose opts = options.dup opts[:path] = localized_path opts[:controller] ||= r.to_s.pluralize resource = resource_from_params(type, r, opts.dup) res = ["#{I18nRouting.locale_escaped(locale)}_#{r}".to_sym, opts] constraints = opts[:constraints] ? opts[:constraints].dup : {} constraints[:i18n_locale] = locale.to_s scope(:constraints => constraints, :path_names => I18nRouting.path_names(resource.name, @scope)) do localized_branch(locale) do send(type, *res) do # In the resource(s) block, we need to keep and restore some context : if block old_name = @scope[:i18n_real_resource_name] old = @scope[:scope_level_resource] @scope[:i18n_real_resource_name] = resource.name @scope[:i18n_scope_level_resource] = old @scope[:scope_level_resource] = resource if type == :resource and @scope[:name_prefix] # Need to fake name_prefix for singleton resource @scope[:name_prefix] = @scope[:name_prefix].gsub(Regexp.new("#{old.name}$"), resource.name) end block.call if block @scope[:scope_level_resource] = old @scope[:i18n_real_resource_name] = old_name end @scope[:i18n_scope_level_resource] = nil end end end localizable_route = resource end end I18n.locale = stored_locale end return localizable_route end
ruby
{ "resource": "" }
q24108
I18nRouting.RackMountRoute.initialize_with_i18n_routing
train
def initialize_with_i18n_routing(app, conditions, defaults, name) @locale = if conditions.key?(:i18n_locale) c = conditions.delete(:i18n_locale) # In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp (c.respond_to?(:source) ? c.source : c).to_sym else nil end initialize_without_i18n_routing(app, conditions, defaults, name) end
ruby
{ "resource": "" }
q24109
I18nRouting.RackMountRoute.generate_with_i18n_routing
train
def generate_with_i18n_routing(method, params = {}, recall = {}, options = {}) return nil if @locale and @locale != I18n.locale.to_sym generate_without_i18n_routing(method, params, recall, options) end
ruby
{ "resource": "" }
q24110
Wavefront.MaintenanceWindow.pending
train
def pending(hours = 24) cutoff = Time.now.to_i + hours * 3600 windows_in_state(:pending).tap do |r| r.response.items.delete_if { |w| w.startTimeInSeconds > cutoff } end end
ruby
{ "resource": "" }
q24111
BoxGrinder.S3Plugin.constraint_equal?
train
def constraint_equal?(region, constraint) [region, constraint].collect{ |v| v.nil? || v == '' ? 'us-east-1' : v }.reduce(:==) end
ruby
{ "resource": "" }
q24112
RbGCCXML.Type.check_sub_type_without
train
def check_sub_type_without(val, delim) return false unless val =~ delim new_val = val.gsub(delim, "").strip NodeCache.find(attributes["type"]) == new_valu end
ruby
{ "resource": "" }
q24113
CucumberAnalytics.Feature.to_s
train
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Feature:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n\n" + background_output_string if background text << "\n\n" + tests_output_string unless tests.empty? text end
ruby
{ "resource": "" }
q24114
BoxGrinder.OpenStackPlugin.get_images
train
def get_images(params = {}) @log.trace "Listing images with params = #{params.to_json}..." data = JSON.parse(RestClient.get("#{url}/v1/images", :params => params))['images'] @log.trace "Listing done." data end
ruby
{ "resource": "" }
q24115
Wavefront.Alert.versions
train
def versions(id) wf_alert_id?(id) resp = api.get([id, 'history'].uri_concat) versions = resp.response.items.map(&:version) resp.response[:items] = versions resp end
ruby
{ "resource": "" }
q24116
I18nRailsHelpers.ModelHelpers.define_enum_t_methods
train
def define_enum_t_methods defined_enums.each do |enum_attr, values| self.class.send(:define_method, "#{enum_attr}_t") { t_enum(enum_attr) } self.class.send(:define_method, "#{enum_attr.pluralize}_t") do t_enum_values(enum_attr, values) end end end
ruby
{ "resource": "" }
q24117
Wavefront.Mixins.parse_time
train
def parse_time(time, in_ms = false) return relative_time(time, in_ms) if time =~ /^[\-+]/ ParseTime.new(time, in_ms).parse! end
ruby
{ "resource": "" }
q24118
Wavefront.Mixins.relative_time
train
def relative_time(time, in_ms = false, ref = Time.now) ref = in_ms ? ref.to_datetime.strftime('%Q') : ref.to_time ref.to_i + parse_relative_time(time, in_ms) end
ruby
{ "resource": "" }
q24119
Wavefront.Mixins.time_multiplier
train
def time_multiplier(suffix) u = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_536_000 } return u[suffix.to_sym] if u.key?(suffix.to_sym) raise Wavefront::Exception::InvalidTimeUnit end
ruby
{ "resource": "" }
q24120
Echochamber.Client.create_agreement
train
def create_agreement(agreement) agreement_response = Echochamber::Request.create_agreement(agreement, token, agreement.user_id, agreement.user_email) agreement_response.fetch("agreementId") end
ruby
{ "resource": "" }
q24121
Echochamber.Client.agreement_documents
train
def agreement_documents(agreement_id, recipient_email, format, version_id=nil) result = Echochamber::Request.agreement_documents(token, agreement_id, recipient_email, format, version_id) end
ruby
{ "resource": "" }
q24122
Echochamber.Client.agreement_document_file
train
def agreement_document_file(agreement_id, document_id, file_path=nil) response = Echochamber::Request.agreement_document_file(token, agreement_id, document_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
{ "resource": "" }
q24123
Echochamber.Client.agreement_combined_pdf
train
def agreement_combined_pdf(agreement_id, file_path=nil, versionId=nil, participantEmail=nil, attachSupportingDocuments=true, auditReport=false) response = Echochamber::Request.agreement_combined_pdf(token, agreement_id, versionId, participantEmail, attachSupportingDocuments, auditReport) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
{ "resource": "" }
q24124
Wavefront.Validators.wf_link_template?
train
def wf_link_template?(template) if template.is_a?(String) && template.start_with?('http://', 'https://') return true end raise Wavefront::Exception::InvalidLinkTemplate end
ruby
{ "resource": "" }
q24125
Wavefront.Validators.wf_name?
train
def wf_name?(name) return true if name.is_a?(String) && name.size < 1024 && name =~ /^\w+$/ raise Wavefront::Exception::InvalidName end
ruby
{ "resource": "" }
q24126
Wavefront.Validators.wf_string?
train
def wf_string?(str) # # Only allows PCRE "word" characters, spaces, full-stops and # commas in tags and descriptions. This might be too restrictive, # but if it is, this is the only place we need to change it. # if str.is_a?(String) && str.size < 1024 && str =~ /^[\-\w \.,]*$/ return true end raise Wavefront::Exception::InvalidString end
ruby
{ "resource": "" }
q24127
Wavefront.Validators.wf_ts?
train
def wf_ts?(timestamp) return true if timestamp.is_a?(Time) || timestamp.is_a?(Date) raise Wavefront::Exception::InvalidTimestamp end
ruby
{ "resource": "" }
q24128
Wavefront.Validators.wf_epoch?
train
def wf_epoch?(timestamp) return true if timestamp.is_a?(Numeric) raise Wavefront::Exception::InvalidTimestamp end
ruby
{ "resource": "" }
q24129
Wavefront.Validators.wf_value?
train
def wf_value?(value) return true if value.is_a?(Numeric) raise Wavefront::Exception::InvalidMetricValue end
ruby
{ "resource": "" }
q24130
Wavefront.Validators.wf_version?
train
def wf_version?(version) version = version.to_i if version.is_a?(String) && version =~ /^\d+$/ return true if version.is_a?(Integer) && version.positive? raise Wavefront::Exception::InvalidVersion end
ruby
{ "resource": "" }
q24131
Wavefront.Validators.wf_alert_id?
train
def wf_alert_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id.match(/^\d{13}$/) raise Wavefront::Exception::InvalidAlertId end
ruby
{ "resource": "" }
q24132
Wavefront.Validators.wf_dashboard_id?
train
def wf_dashboard_id?(id) return true if id.is_a?(String) && id.size < 256 && id.match(/^[\w\-]+$/) raise Wavefront::Exception::InvalidDashboardId end
ruby
{ "resource": "" }
q24133
Wavefront.Validators.wf_derivedmetric_id?
train
def wf_derivedmetric_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidDerivedMetricId end
ruby
{ "resource": "" }
q24134
Wavefront.Validators.wf_link_id?
train
def wf_link_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidExternalLinkId end
ruby
{ "resource": "" }
q24135
Wavefront.Validators.wf_maintenance_window_id?
train
def wf_maintenance_window_id?(id) id = id.to_s if id.is_a?(Numeric) return true if id.is_a?(String) && id =~ /^\d{13}$/ raise Wavefront::Exception::InvalidMaintenanceWindowId end
ruby
{ "resource": "" }
q24136
Wavefront.Validators.wf_alert_severity?
train
def wf_alert_severity?(severity) return true if %w[INFO SMOKE WARN SEVERE].include?(severity) raise Wavefront::Exception::InvalidAlertSeverity end
ruby
{ "resource": "" }
q24137
Wavefront.Validators.wf_message_id?
train
def wf_message_id?(id) return true if id.is_a?(String) && id =~ /^\w+::\w+$/ raise Wavefront::Exception::InvalidMessageId end
ruby
{ "resource": "" }
q24138
Wavefront.Validators.wf_granularity?
train
def wf_granularity?(granularity) return true if %w[d h m s].include?(granularity.to_s) raise Wavefront::Exception::InvalidGranularity end
ruby
{ "resource": "" }
q24139
Wavefront.Validators.wf_savedsearch_id?
train
def wf_savedsearch_id?(id) return true if id.is_a?(String) && id =~ /^\w{8}$/ raise Wavefront::Exception::InvalidSavedSearchId end
ruby
{ "resource": "" }
q24140
Wavefront.Validators.wf_savedsearch_entity?
train
def wf_savedsearch_entity?(id) return true if %w[DASHBOARD ALERT MAINTENANCE_WINDOW NOTIFICANT EVENT SOURCE EXTERNAL_LINK AGENT CLOUD_INTEGRATION].include?(id) raise Wavefront::Exception::InvalidSavedSearchEntity end
ruby
{ "resource": "" }
q24141
Wavefront.Validators.wf_source_id?
train
def wf_source_id?(source) if source.is_a?(String) && source.match(/^[\w\.\-]+$/) && source.size < 1024 return true end raise Wavefront::Exception::InvalidSourceId end
ruby
{ "resource": "" }
q24142
Wavefront.Validators.wf_user_id?
train
def wf_user_id?(user) return true if user.is_a?(String) && user.length < 256 && !user.empty? raise Wavefront::Exception::InvalidUserId end
ruby
{ "resource": "" }
q24143
Wavefront.Validators.wf_webhook_id?
train
def wf_webhook_id?(id) return true if id.is_a?(String) && id =~ /^[a-zA-Z0-9]{16}$/ raise Wavefront::Exception::InvalidWebhookId end
ruby
{ "resource": "" }
q24144
Wavefront.Validators.wf_distribution?
train
def wf_distribution?(dist) wf_metric_name?(dist[:path]) wf_distribution_values?(dist[:value]) wf_epoch?(dist[:ts]) if dist[:ts] wf_source_id?(dist[:source]) if dist[:source] wf_point_tags?(dist[:tags]) if dist[:tags] true end
ruby
{ "resource": "" }
q24145
Wavefront.Validators.wf_distribution_values?
train
def wf_distribution_values?(vals) vals.each do |times, val| wf_distribution_count?(times) wf_value?(val) end true end
ruby
{ "resource": "" }
q24146
Wavefront.Validators.wf_notificant_id?
train
def wf_notificant_id?(id) return true if id.is_a?(String) && id =~ /^\w{16}$/ raise Wavefront::Exception::InvalidNotificantId end
ruby
{ "resource": "" }
q24147
Wavefront.Validators.wf_integration_id?
train
def wf_integration_id?(id) return true if id.is_a?(String) && id =~ /^[a-z0-9]+$/ raise Wavefront::Exception::InvalidIntegrationId end
ruby
{ "resource": "" }
q24148
Wavefront.Validators.wf_distribution_interval?
train
def wf_distribution_interval?(interval) return true if %i[m h d].include?(interval) raise Wavefront::Exception::InvalidDistributionInterval end
ruby
{ "resource": "" }
q24149
Wavefront.Validators.wf_distribution_count?
train
def wf_distribution_count?(count) return true if count.is_a?(Integer) && count.positive? raise Wavefront::Exception::InvalidDistributionCount end
ruby
{ "resource": "" }
q24150
Wavefront.Query.response_shim
train
def response_shim(body, status) resp, err_msg = parsed_response(body) { response: resp, status: { result: status == 200 ? 'OK' : 'ERROR', message: err_msg, code: status } }.to_json end
ruby
{ "resource": "" }
q24151
Wavefront.Query.parsed_response
train
def parsed_response(body) [JSON.parse(body), ''] rescue JSON::ParserError ['', body.match(/message='([^']+)'/).captures.first] end
ruby
{ "resource": "" }
q24152
Wavefront.Credentials.populate
train
def populate(raw) @config = Map(raw) @creds = Map(raw.select { |k, _v| %i[endpoint token].include?(k) }) @proxy = Map(raw.select { |k, _v| %i[proxy port].include?(k) }) @all = Map(raw.select do |k, _v| %i[proxy port endpoint token].include?(k) end) end
ruby
{ "resource": "" }
q24153
BoxGrinder.GuestFSHelper.log_hack
train
def log_hack read_stderr, write_stderr = IO.pipe fork do write_stderr.close read_stderr.each do |l| @log.trace "GFS: #{l.chomp.strip}" end read_stderr.close end old_stderr = STDERR.clone STDERR.reopen(write_stderr) STDERR.sync = true begin # Execute all tasks yield if block_given? ensure STDERR.reopen(old_stderr) end write_stderr.close read_stderr.close Process.wait end
ruby
{ "resource": "" }
q24154
BoxGrinder.GuestFSHelper.mount_partitions
train
def mount_partitions(device, mount_prefix = '') @log.trace "Mounting partitions..." partitions = mountable_partitions(device) mount_points = LinuxHelper.new(:log => @log).partition_mount_points(@appliance_config.hardware.partitions) # https://issues.jboss.org/browse/BGBUILD-307 # We don't want to mount swap partitions at all... mount_points.delete("swap") partitions.each_index { |i| mount_partition(partitions[i], mount_points[i], mount_prefix) } end
ruby
{ "resource": "" }
q24155
BoxGrinder.GuestFSHelper.umount_partitions
train
def umount_partitions(device) partitions = mountable_partitions(device) @log.trace "Unmounting partitions..." partitions.reverse.each { |part| umount_partition(part) } @log.trace "All partitions unmounted." end
ruby
{ "resource": "" }
q24156
Wavefront.Search.body
train
def body(query, options) ret = { limit: options[:limit] || 10, offset: options[:offset] || 0 } if query && !query.empty? ret[:query] = [query].flatten.map do |q| q.tap { |iq| iq[:matchingMethod] ||= 'CONTAINS' } end ret[:sort] = sort_field(options, query) end ret end
ruby
{ "resource": "" }
q24157
BoxGrinder.ElasticHostsPlugin.create_server
train
def create_server @log.info "Creating new server..." memory = ((is_cloudsigma? and @appliance_config.hardware.memory < 512) ? 512 : @appliance_config.hardware.memory) body = hash_to_request( 'name' => "#{@appliance_config.name}-#{@appliance_config.version}.#{@appliance_config.release}", 'cpu' => @appliance_config.hardware.cpus * 1000, # MHz 'smp' => 'auto', 'mem' => memory, 'persistent' => 'true', # hack 'ide:0:0' => @plugin_config['drive_uuid'], 'boot' => 'ide:0:0', 'nic:0:model' => 'e1000', 'nic:0:dhcp' => 'auto', 'vnc:ip' => 'auto', 'vnc:password' => (0...8).map { (('a'..'z').to_a + ('A'..'Z').to_a)[rand(52)] }.join # 8 character VNC password ) begin path = is_cloudsigma? ? '/servers/create' : '/servers/create/stopped' ret = response_to_hash(RestClient.post(api_url(path), body)) @log.info "Server was registered with '#{ret['name']}' name as '#{ret['server']}' UUID. Use web UI or API tools to start your server." rescue => e @log.error e.info raise PluginError, "An error occurred while creating the server, #{e.message}. See logs for more info." end end
ruby
{ "resource": "" }
q24158
BoxGrinder.Appliance.initialize_plugins
train
def initialize_plugins @plugin_chain = [] os_plugin, os_plugin_info = PluginManager.instance.initialize_plugin(:os, @appliance_config.os.name.to_sym) initialize_plugin(os_plugin, os_plugin_info) if platform_selected? platform_plugin, platform_plugin_info = PluginManager.instance.initialize_plugin(:platform, @config.platform) initialize_plugin(platform_plugin, platform_plugin_info) end if delivery_selected? delivery_plugin, delivery_plugin_info = PluginManager.instance.initialize_plugin(:delivery, @config.delivery) # Here we need to specify additionally the type of the plugin, as some delivery plugins # can have multiple types of delivery implemented. See s3-plugin.rb for example. initialize_plugin(delivery_plugin, delivery_plugin_info, :type => @config.delivery) end end
ruby
{ "resource": "" }
q24159
BoxGrinder.Appliance.initialize_plugin
train
def initialize_plugin(plugin, plugin_info, options = {}) options = { :log => @log }.merge(options) unless @plugin_chain.empty? options.merge!(:previous_plugin => @plugin_chain.last[:plugin]) end plugin.init(@config, @appliance_config, plugin_info, options) # Execute callbacks if implemented # # Order is very important [:after_init, :validate, :after_validate].each do |callback| plugin.send(callback) if plugin.respond_to?(callback) end param = nil # For operating system plugins we need to inject appliance definition. if plugin_info[:type] == :os param = @appliance_definition end @plugin_chain << {:plugin => plugin, :param => param} end
ruby
{ "resource": "" }
q24160
BoxGrinder.Appliance.create
train
def create @log.debug "Launching new build..." @log.trace "Used configuration: #{@config.to_yaml.gsub(/(\S*(key|account|cert|username|host|password)\S*).*:(.*)/, '\1' + ": <REDACTED>")}" # Let's load all plugins first PluginHelper.new(@config, :log => @log).load_plugins read_definition validate_definition initialize_plugins remove_old_builds if @config.force execute_plugin_chain self end
ruby
{ "resource": "" }
q24161
BoxGrinder.LibvirtCapabilities.determine_capabilities
train
def determine_capabilities(conn, previous_plugin_info) plugin = get_plugin(previous_plugin_info) root = Nokogiri::XML.parse(conn.capabilities) guests = root.xpath("//guest/arch[@name='x86_64']/..") guests = guests.sort do |a, b| dom_maps = [a,b].map { |x| plugin.domain_map[xpath_first_intern(x, './/domain/@type')] } # Handle unknown mappings next resolve_unknowns(dom_maps) if dom_maps.include?(nil) # Compare according to domain ranking dom_rank = dom_maps.map { |m| m[:rank]}.reduce(:<=>) # Compare according to virtualisation ranking virt_rank = [a,b].enum_for(:each_with_index).map do |x, i| dom_maps[i][:domain].virt_map[xpath_first_intern(x, './/os_type')] end # Handle unknown mappings next resolve_unknowns(virt_rank) if virt_rank.include?(nil) # Domain rank first next dom_rank unless dom_rank == 0 # OS type rank second virt_rank.reduce(:<=>) end # Favourite! build_guest(guests.first) end
ruby
{ "resource": "" }
q24162
BoxGrinder.LibvirtCapabilities.get_plugin
train
def get_plugin(previous_plugin_info) if previous_plugin_info[:type] == :platform if PLUGINS.has_key?(previous_plugin_info[:name]) @log.debug("Using #{previous_plugin_info[:name]} mapping") return PLUGINS[previous_plugin_info[:name]] else @log.debug("This plugin does not know what mappings to choose, so will assume default values where user values are not provided.") end end @log.debug("Using default domain mappings.") PLUGINS[:default] end
ruby
{ "resource": "" }
q24163
Spree.BitpayController.pay_now
train
def pay_now order = current_order || raise(ActiveRecord::RecordNotFound) session[:order_number] = current_order.number invoice = order.place_bitpay_order notificationURL: bitpay_notification_url @invoice_iframe_url = "#{invoice['url']}&view=iframe" render json: @invoice_iframe_url end
ruby
{ "resource": "" }
q24164
Spree.BitpayController.payment_sent
train
def payment_sent order_number = session[:order_number] session[:order_number] = nil order = Spree::Order.find_by_number(order_number) || raise(ActiveRecord::RecordNotFound) redirect_to spree.order_path(order), :notice => Spree.t(:order_processed_successfully) end
ruby
{ "resource": "" }
q24165
Spree.BitpayController.notification
train
def notification begin posData = JSON.parse(params["posData"]) order_id = posData["orderID"] payment_id = posData["paymentID"] order = Spree::Order.find_by_number(order_id) || raise(ActiveRecord::RecordNotFound) begin order.process_bitpay_ipn payment_id head :ok rescue => exception logger.debug exception head :uprocessable_entity end rescue => error logger.error "Spree_Bitpay: Unprocessable notification received from #{request.remote_ip}: #{params.inspect}" head :unprocessable_entity end end
ruby
{ "resource": "" }
q24166
Spree.BitpayController.refresh
train
def refresh payment = Spree::Payment.find(params[:payment]) # Retrieve payment by ID old_state = payment.state payment.process_bitpay_ipn new_state = payment.reload.state notice = (new_state == old_state) ? Spree.t(:bitpay_payment_not_updated) : (Spree.t(:bitpay_payment_updated) + new_state.titlecase) redirect_to (request.referrer || root_path), notice: notice end
ruby
{ "resource": "" }
q24167
BoxGrinder.EC2Plugin.add_ec2_user
train
def add_ec2_user(guestfs) @log.debug "Adding ec2-user user..." # We need to add ec2-user only when it doesn't exists # # https://issues.jboss.org/browse/BGBUILD-313 unless guestfs.fgrep("ec2-user", "/etc/passwd").empty? @log.debug("ec2-user already exists, skipping.") return end guestfs.sh("useradd ec2-user") guestfs.sh("echo -e 'ec2-user\tALL=(ALL)\tNOPASSWD: ALL' >> /etc/sudoers") @log.debug "User ec2-user added." end
ruby
{ "resource": "" }
q24168
CucumberAnalytics.Step.step_text
train
def step_text(options = {}) options = {:with_keywords => true, :with_arguments => true, :left_delimiter => self.left_delimiter, :right_delimiter => self.right_delimiter}.merge(options) final_step = [] step_text = '' step_text += "#{@keyword} " if options[:with_keywords] if options[:with_arguments] step_text += @base final_step << step_text final_step.concat(rebuild_block_text(@block)) if @block else step_text += stripped_step(@base, options[:left_delimiter], options[:right_delimiter]) final_step << step_text end final_step end
ruby
{ "resource": "" }
q24169
CucumberAnalytics.Step.scan_arguments
train
def scan_arguments(*how) if how.count == 1 pattern = how.first else left_delimiter = how[0] || self.left_delimiter right_delimiter = how[1] || self.right_delimiter return [] unless left_delimiter && right_delimiter pattern = Regexp.new(Regexp.escape(left_delimiter) + '(.*?)' + Regexp.escape(right_delimiter)) end @arguments = @base.scan(pattern).flatten end
ruby
{ "resource": "" }
q24170
CucumberAnalytics.Step.stripped_step
train
def stripped_step(step, left_delimiter, right_delimiter) unless left_delimiter.nil? || right_delimiter.nil? pattern = Regexp.new(Regexp.escape(left_delimiter) + '.*?' + Regexp.escape(right_delimiter)) step = step.gsub(pattern, left_delimiter + right_delimiter) end step end
ruby
{ "resource": "" }
q24171
BoxGrinder.RPMBasedOSPlugin.substitute_vars
train
def substitute_vars(str) return if str.nil? @appliance_config.variables.keys.each do |var| str = str.gsub("##{var}#", @appliance_config.variables[var]) end str end
ruby
{ "resource": "" }
q24172
BoxGrinder.RPMBasedOSPlugin.install_files
train
def install_files(guestfs) @log.debug "Installing files specified in appliance definition file..." @appliance_config.files.each do |dir, files| @log.debug "Proceding files for '#{dir}' destination directory..." local_files = [] # Create the directory if it doesn't exists guestfs.mkdir_p(dir) unless guestfs.exists(dir) != 0 files.each do |f| if f.match(/^(http|ftp|https):\/\//) # Remote url provided @log.trace "Remote url detected: '#{f}'." # We have a remote file, try to download it using curl! guestfs.sh("cd #{dir} && curl -O -L #{f}") else @log.trace "Local path detected: '#{f}'." file_path = (f.match(/^\//) ? f : "#{File.dirname(@appliance_definition_file)}/#{f}") # TODO validate this earlier raise ValidationError, "File '#{f}' specified in files section of appliance definition file doesn't exists." unless File.exists?(file_path) local_files << f end end next if local_files.empty? @log.trace "Tarring files..." @exec_helper.execute("cd #{File.dirname(@appliance_definition_file)} && tar -cvf /tmp/bg_install_files.tar --wildcards #{local_files.join(' ')}") @log.trace "Files tarred." @log.trace "Uploading and unpacking..." guestfs.tar_in("/tmp/bg_install_files.tar", dir) @log.trace "Files uploaded." end @log.debug "Files installed." end
ruby
{ "resource": "" }
q24173
Echochamber.Client.get_library_document_file
train
def get_library_document_file(library_document_id, file_id, file_path=nil) response = Echochamber::Request.get_library_document_file(token, library_document_id, file_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
{ "resource": "" }
q24174
Echochamber.Client.library_combined_document
train
def library_combined_document(library_document_id, file_path=nil, auditReport=false) response = Echochamber::Request.library_combined_document(token, library_document_id, auditReport) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
{ "resource": "" }
q24175
UserQ.Queue.enter_into_queue?
train
def enter_into_queue? # Check if enough space in queue current_limit = queue_constraints[:capacity].to_i current_usage = queue_constraints[:taken].to_i + UserQ::UserQueue.count_unexpired(queue_constraints[:context]) # Assess whether enough space left into queue current_usage < current_limit end
ruby
{ "resource": "" }
q24176
Kairos.Client.gallery_list_all
train
def gallery_list_all # ToDo: Research why Typhoeus works better than Faraday for this endpoint request = Typhoeus::Request.new( "#{Kairos::Configuration::GALLERY_LIST_ALL}", method: :post, headers: { "Content-Type" => "application/x-www-form-urlencoded", "app_id" => "#{@app_id}", "app_key" => "#{@app_key}" } ) response = request.run JSON.parse(response.body) rescue "INVALID_JSON: #{response.body}" end
ruby
{ "resource": "" }
q24177
RbGCCXML.QueryResult.method_missing
train
def method_missing(name, *args) if self[0].respond_to?(name) self.inject(QueryResult.new) do |memo, node| ret = node.send(name, *args) memo << ret if ret memo end else super end end
ruby
{ "resource": "" }
q24178
SyncAttr.Attributes.sync_attr_sync
train
def sync_attr_sync(attribute, &block) mutex_var_name = "@sync_attr_#{attribute}".to_sym instance_variable_set(mutex_var_name, Mutex.new) unless instance_variable_defined?(mutex_var_name) instance_variable_get(mutex_var_name).synchronize(&block) end
ruby
{ "resource": "" }
q24179
BoxGrinder.EC2Helper.wait_for_instance_death
train
def wait_for_instance_death(instance, opts={}) wait_for_instance_status(:terminated, instance, opts) if instance.exists? rescue AWS::EC2::Errors::InvalidInstanceID::NotFound end
ruby
{ "resource": "" }
q24180
Echochamber.Client.get_widget_documents
train
def get_widget_documents(widget_id, version_id=nil, participant_email=nil) Echochamber::Request.get_widget_documents(token, widget_id, version_id, participant_email) end
ruby
{ "resource": "" }
q24181
Echochamber.Client.get_widget_document_file
train
def get_widget_document_file(widget_id, document_id, file_path=nil) response = Echochamber::Request.get_widget_document_file(token, widget_id, document_id) unless file_path.nil? file = File.new(file_path, 'wb') file.write(response) file.close end response end
ruby
{ "resource": "" }
q24182
I18nRailsHelpers.ControllerHelpers.redirect_notice
train
def redirect_notice(record = nil) { notice: I18n.t("crud.notices.#{action_name}", model: helpers.t_model, record: record.present? ? "#{record} " : '') } end
ruby
{ "resource": "" }
q24183
I18nRouting.JourneyRoute.initialize_with_i18n_routing
train
def initialize_with_i18n_routing(name, app, path, constraints, defaults = {}) @locale = if constraints.key?(:i18n_locale) c = constraints.delete(:i18n_locale) # In rails 3.0 it's a regexp otherwise it's a string, so we need to call source on the regexp (c.respond_to?(:source) ? c.source : c).to_sym else nil end initialize_without_i18n_routing(name, app, path, constraints, defaults) end
ruby
{ "resource": "" }
q24184
Wavefront.Response.raw_response
train
def raw_response(json, status) json.empty? ? {} : JSON.parse(json, symbolize_names: true) rescue StandardError { message: json, code: status } end
ruby
{ "resource": "" }
q24185
Userq.InstallGenerator.do_migration
train
def do_migration migration_exists = Dir["db/migrate/*_create_user_queues.rb"].count > 0 if migration_exists and installing? puts "UserQ is already installed. Maybe a 'rake db:migrate' command might help?" return end create_migration puts "Success! UserQ is installed. You can now use it in your application." if installing? puts "UserQ has already been uninstalled. Remember the 'user_queue' table needs to be manually destroyed." if destroying? and migration_exists == false puts "Success! UserQ is uninstalled. The table 'userq_queue' needs to be destroyed manually to complete removal." if destroying? and migration_exists end
ruby
{ "resource": "" }
q24186
Echochamber.Client.create_user
train
def create_user(user) user_response = Echochamber::Request.create_user(user, token) user_response.fetch("userId") end
ruby
{ "resource": "" }
q24187
Echochamber.Client.create_transient_document
train
def create_transient_document(file_name, mime_type, file_handle) transient_document_response = Echochamber::Request.create_transient_document(token, file_name, file_handle, mime_type) transient_document_response.fetch("transientDocumentId") end
ruby
{ "resource": "" }
q24188
IRT.Utils.ask_run_new_file
train
def ask_run_new_file(new_file_path, source_path, tmp) return if tmp && IRT.rails_server original_ask_run_new_file(new_file_path, source_path, tmp) end
ruby
{ "resource": "" }
q24189
Wavefront.User.response_shim
train
def response_shim(body, status) items = JSON.parse(body, symbolize_names: true) { response: { items: items, offset: 0, limit: items.size, totalItems: items.size, modeItems: false }, status: { result: status == 200 ? 'OK' : 'ERROR', message: extract_api_message(status, items), code: status } }.to_json end
ruby
{ "resource": "" }
q24190
BoxGrinder.AWSHelper.parse_opts
train
def parse_opts(opts_in, opts_defaults) diff_id = opts_in.keys - opts_defaults.keys raise ArgumentError, "Unrecognised argument(s): #{diff_id.join(", ")}" if diff_id.any? (opts_in.keys & opts_defaults.keys).each do |k| raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil and opts_in[k] == nil end (opts_defaults.keys - opts_in.keys).each do |k| raise ArgumentError, "Argument #{k.to_s} must not be nil" if opts_defaults[k] == nil opts_in.merge!(k => opts_defaults[k]) end opts_in end
ruby
{ "resource": "" }
q24191
BoxGrinder.LibvirtPlugin.determine_remotely
train
def determine_remotely # Remove password field from URI, as libvirt doesn't support it directly. We can use it for passphrase if needed. lv_uri = URI::Generic.build(:scheme => @connection_uri.scheme, :userinfo => @connection_uri.user, :host => @connection_uri.host, :path => @connection_uri.path, :query => @connection_uri.query) # The authentication only pertains to libvirtd itself and _not_ the transport (e.g. SSH). conn = Libvirt::open_auth(lv_uri.to_s, [Libvirt::CRED_AUTHNAME, Libvirt::CRED_PASSPHRASE]) do |cred| case cred["type"] when Libvirt::CRED_AUTHNAME @connection_uri.user when Libvirt::CRED_PASSPHRASE @connection_uri.password end end if dom = get_existing_domain(conn, @appliance_name) unless @overwrite @log.fatal("A domain already exists with the name #{@appliance_name}. Set overwrite:true to automatically destroy and undefine it.") raise RuntimeError, "Domain '#{@appliance_name}' already exists" #Make better specific exception end @log.info("Undefining existing domain #{@appliance_name}") undefine_domain(dom) end guest = @libvirt_capabilities.determine_capabilities(conn, @previous_plugin_info) raise "Remote libvirt machine offered no viable guests!" if guest.nil? xml = generate_xml(guest) @log.info("Defining domain #{@appliance_name}") conn.define_domain_xml(xml) xml ensure if conn conn.close unless conn.closed? end end
ruby
{ "resource": "" }
q24192
BoxGrinder.LibvirtPlugin.determine_locally
train
def determine_locally domain = @libvirt_capabilities.get_plugin(@previous_plugin_info).domain_rank.last generate_xml(OpenStruct.new({ :domain_type => domain.name, :os_type => domain.virt_rank.last, :bus => domain.bus })) end
ruby
{ "resource": "" }
q24193
BoxGrinder.LibvirtPlugin.upload_image
train
def upload_image uploader = SFTPHelper.new(:log => @log) #SFTP library automagically uses keys registered with the OS first before trying a password. uploader.connect(@image_delivery_uri.host, (@image_delivery_uri.user || Etc.getlogin), :password => @image_delivery_uri.password) uploader.upload_files(@image_delivery_uri.path, @default_permissions, @overwrite, File.basename(@previous_deliverables.disk) => @previous_deliverables.disk) ensure uploader.disconnect if uploader.connected? end
ruby
{ "resource": "" }
q24194
BoxGrinder.LibvirtPlugin.build_xml
train
def build_xml(opts = {}) opts = {:bus => @bus, :os_type => :hvm}.merge!(opts) builder = Builder::XmlMarkup.new(:indent => 2) xml = builder.domain(:type => opts[:domain_type].to_s) do |domain| domain.name(@appliance_name) domain.description(@appliance_config.summary) domain.memory(@appliance_config.hardware.memory * 1024) #KB domain.vcpu(@appliance_config.hardware.cpus) domain.os do |os| os.type(opts[:os_type].to_s, :arch => @appliance_config.hardware.arch) os.boot(:dev => 'hd') end domain.devices do |devices| devices.disk(:type => 'file', :device => 'disk') do |disk| disk.source(:file => "#{@libvirt_image_uri}/#{File.basename(@previous_deliverables.disk)}") disk.target(:dev => 'hda', :bus => opts[:bus].to_s) end devices.interface(:type => 'network') do |interface| interface.source(:network => @network) interface.mac(:address => @mac) if @mac end devices.console(:type => 'pty') unless @noautoconsole devices.graphics(:type => 'vnc', :port => -1) unless @novnc end domain.features do |features| features.pae if @appliance_config.os.pae end end @log.debug xml # Let the user modify the XML specification to their requirements if @script @log.info "Attempting to run user provided script for modifying libVirt XML..." xml = IO::popen("#{@script} --domain '#{xml}'").read @log.debug "Response was: #{xml}" end xml end
ruby
{ "resource": "" }
q24195
BoxGrinder.LibvirtPlugin.get_existing_domain
train
def get_existing_domain(conn, name) return conn.lookup_domain_by_name(name) rescue Libvirt::Error => e return nil if e.libvirt_code == 42 # If domain not defined raise # Otherwise reraise end
ruby
{ "resource": "" }
q24196
BoxGrinder.LibvirtPlugin.undefine_domain
train
def undefine_domain(dom) case dom.info.state when Libvirt::Domain::RUNNING, Libvirt::Domain::PAUSED, Libvirt::Domain::BLOCKED dom.destroy end dom.undefine end
ruby
{ "resource": "" }
q24197
BoxGrinder.LibvirtPlugin.write_xml
train
def write_xml(xml) fname = "#{@appliance_name}.xml" File.open("#{@dir.tmp}/#{fname}", 'w'){|f| f.write(xml)} register_deliverable(:xml => fname) end
ruby
{ "resource": "" }
q24198
Ddr::Models.WithContentFile.with_temp_file
train
def with_temp_file filename = original_filename || content.default_file_name basename = [ File.basename(filename, ".*"), File.extname(filename) ] infile = Tempfile.open(basename, Ddr::Models.tempdir, encoding: 'ascii-8bit') begin infile.write(content.content) infile.close verify_checksum!(infile) yield infile.path ensure infile.close unless infile.closed? File.unlink(infile) end end
ruby
{ "resource": "" }
q24199
Ddr::Auth.AuthContext.member_of?
train
def member_of?(group) if group.is_a? Group groups.include? group else member_of? Group.new(group) end end
ruby
{ "resource": "" }