_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q3200
Phonology.Inventory.without
train
def without(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| !features.subset?(key)}] end
ruby
{ "resource": "" }
q3201
Phonology.Inventory.without_any
train
def without_any(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| key.intersection(features).empty?}] end
ruby
{ "resource": "" }
q3202
Hicube.BaseController.check_resource_params
train
def check_resource_params(options = {}) # Determine the name based on the current controller if not specified. resource_name = options[:name] || controller_name.singularize # Determine the class based on the resource name if not provided. #FIXME: Do not hardcode engine name resource_class = options[:class] || "Hicube::#{resource_name.singularize.camelize}".classify.constantize unless params.key?(resource_name) notify :error, ::I18n.t('messages.resource.missing_parameters', :type => resource_class.model_name.human ) case action_name.to_sym when :create redirect_to :action => :new when :update redirect_to :action => :edit, :id => params[:id] else redirect_to :action => :index end end end
ruby
{ "resource": "" }
q3203
Gitter.Column.order_params
train
def order_params desc = !desc? p = grid.params.dup if ordered? p[:desc] = desc else p = p.merge order: name, desc: desc end grid.scoped_params p end
ruby
{ "resource": "" }
q3204
Charisma.Curator.characteristics
train
def characteristics return @characteristics if @characteristics hsh = Hash.new do |_, key| if characterization = subject.class.characterization[key] Curation.new nil, characterization end end hsh.extend LooseEquality @characteristics = hsh end
ruby
{ "resource": "" }
q3205
Charisma.Curator.[]=
train
def []=(key, value) characteristics[key] = Curation.new value, subject.class.characterization[key] end
ruby
{ "resource": "" }
q3206
Units.Measure.detailed_units
train
def detailed_units(all_levels = false) mag = @magnitude prev_units = self.units units = {} loop do compound = false prev_units.each_pair do |dim, (unit,mul)| ud = Units.unit(unit) if ud.decomposition compound = true mag *= ud.decomposition.magnitude ud.decomposition.units.each_pair do |d, (u,m)| mag *= self.class.combine(units, d, u, m*mul) end else mag *= self.class.combine(units, dim, unit, mul) end end if all_levels && compound prev_units = units units = {} else break end end Measure.new mag, units end
ruby
{ "resource": "" }
q3207
SocialSnippet.Resolvers::InsertResolver.insert
train
def insert(text) raise "must be passed string" unless text.is_a?(String) snippet = Snippet.new_text(core, text) snippet.snippet_tags.each do |tag_info| visit tag_info[:tag] end context = Context.new(nil) insert_func(snippet, context).join($/) end
ruby
{ "resource": "" }
q3208
SocialSnippet.Resolvers::InsertResolver.insert_by_tag_and_context!
train
def insert_by_tag_and_context!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) src = insert_func(snippet, context, tag) options[:margin_top].times { inserter.insert "" } # @snip -> @snippet inserter.insert tag.to_snippet_tag unless snippet.no_tag? # insert snippet text inserter.insert src options[:margin_bottom].times { inserter.insert "" } visit tag end
ruby
{ "resource": "" }
q3209
SocialSnippet.Resolvers::InsertResolver.insert_depended_snippets!
train
def insert_depended_snippets!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) dep_tags = deps_resolver.find(snippet, context, tag) dep_tags = sort_dep_tags_by_dep(dep_tags) dep_tags.each do |tag_info| sub_t = tag_info[:tag] sub_c = tag_info[:context] resolve_tag_repo_ref! sub_t visit(tag) if is_self(sub_t, sub_c) next if is_visited(sub_t) next_snippet = core.repo_manager.get_snippet(sub_c, sub_t) insert_by_tag_and_context! inserter, next_snippet, sub_c, sub_t end end
ruby
{ "resource": "" }
q3210
SocialSnippet.Resolvers::InsertResolver.sort_dep_tags_by_dep
train
def sort_dep_tags_by_dep(dep_tags) dep_tags_index = {} # map tag to index dep_tags.each.with_index do |tag_info, k| tag = tag_info[:tag] dep_tags_index[tag.to_path] = k end # generate dependency graph dep_tags_hash = TSortableHash.new dep_tags.each do |tag_info| tag = tag_info[:tag].to_path dep_ind = dep_tags_index[tag] dep_tags_hash[dep_ind] = deps_resolver.dep_to[tag].to_a.map {|tag| dep_tags_index[tag] }.reject(&:nil?) end dep_tags_hash.tsort.map {|k| dep_tags[k] } end
ruby
{ "resource": "" }
q3211
UOM.UnitFactory.create
train
def create(label) create_atomic(label.to_s) or create_composite(label.to_s) or raise MeasurementError.new("Unit '#{label}' not found") end
ruby
{ "resource": "" }
q3212
UOM.UnitFactory.slice_atomic_unit
train
def slice_atomic_unit(str) label = '' str.scan(/_?[^_]+/) do |chunk| label << chunk unit = create_atomic(label) return label, unit if unit end raise MeasurementError.new("Unit '#{str}' not found") end
ruby
{ "resource": "" }
q3213
UOM.UnitFactory.match_scalar
train
def match_scalar(label) label = label.to_sym Factor.detect do |factor| return factor if factor.label == label or factor.abbreviation == label end end
ruby
{ "resource": "" }
q3214
UOM.UnitFactory.suffix?
train
def suffix?(suffix, text) len = suffix.length len <= text.length and suffix == text[-len, len] end
ruby
{ "resource": "" }
q3215
Octoauth.ConfigFile.write
train
def write new = get new[@note] = @token File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml } end
ruby
{ "resource": "" }
q3216
SwhdApi.Manager.fetch
train
def fetch(resource, params = {}) method = :get page = 1 params[:page] = page partial = request(resource, method, params) while partial.is_a?(Array) && !partial.empty? results ||= [] results += partial page += 1 params[:page] = page partial = request(resource, method, params) end results = partial unless partial.nil? || partial.empty? results end
ruby
{ "resource": "" }
q3217
MoresMarvel.Resource.fetch_by_id
train
def fetch_by_id(model, id, filters = {}) get_resource("/v1/public/#{model}/#{id}", filters) if model_exists?(model) && validate_filters(filters) end
ruby
{ "resource": "" }
q3218
Tily.Tily.processing_hint_str
train
def processing_hint_str number, level total = (@ts.tile_size(level) ** 2).to_s now = (number + 1).to_s.rjust(total.length, " ") "#{now}/#{total}" end
ruby
{ "resource": "" }
q3219
SoapyCake.Campaigns.patch
train
def patch(campaign_id, opts = {}) campaign = get(campaign_id: campaign_id).first opts = NO_CHANGE_VALUES .merge( affiliate_id: campaign.fetch(:affiliate).fetch(:affiliate_id), media_type_id: campaign.fetch(:media_type).fetch(:media_type_id), offer_contract_id: campaign.fetch(:offer_contract).fetch(:offer_contract_id), offer_id: campaign.fetch(:offer).fetch(:offer_id), payout: campaign.fetch(:payout).fetch(:amount), payout_update_option: 'do_not_change', pixel_html: campaign.dig(:pixel_info, :pixel_html) || '', postback_url: campaign.dig(:pixel_info, :postback_url) || '', redirect_domain: campaign.fetch(:redirect_domain, ''), test_link: campaign[:test_link] || '', unique_key_hash: campaign.dig(:pixel_info, :hash_type, :hash_type_id) || 'none', third_party_name: campaign.fetch(:third_party_name, '') ) .merge(opts) update(campaign_id, opts) nil end
ruby
{ "resource": "" }
q3220
ManaMana.Steps.call
train
def call(step_name) vars = nil step = steps.find { |s| vars = s[:pattern].match(step_name) } raise "Undefined step '#{ step_name }'" unless step if vars.length > 1 step[:block].call(*vars[1..-1]) else step[:block].call end end
ruby
{ "resource": "" }
q3221
Gitable.URI.equivalent?
train
def equivalent?(other_uri) other = Gitable::URI.parse_when_valid(other_uri) return false unless other return false unless normalized_host.to_s == other.normalized_host.to_s if github? || bitbucket? # github doesn't care about relative vs absolute paths in scp uris org_project == other.org_project else # if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match). normalized_path.sub(/\/$/,'') == other.normalized_path.sub(/\/$/,'') && (path[0] == '/' || normalized_user == other.normalized_user) end end
ruby
{ "resource": "" }
q3222
Rworkflow.Flow.counters!
train
def counters! the_counters = { processing: 0 } names = @lifecycle.states.keys results = RedisRds::Object.connection.multi do self.class::STATES_TERMINAL.each { |name| get_list(name).size } names.each { |name| get_list(name).size } @processing.getall end (self.class::STATES_TERMINAL + names).each do |name| the_counters[name] = results.shift.to_i end the_counters[:processing] = results.shift.reduce(0) { |sum, pair| sum + pair.last.to_i } return the_counters end
ruby
{ "resource": "" }
q3223
KaminariRoutePrefix.ActionViewExtension.link_to_previous_page
train
def link_to_previous_page(scope, name, options = {}, &block) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.prev_page.present?, name, prev_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'prev') do block.call if block end end
ruby
{ "resource": "" }
q3224
KaminariRoutePrefix.ActionViewExtension.link_to_next_page
train
def link_to_next_page(scope, name, options = {}, &block) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.next_page.present?, name, next_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'next') do block.call if block end end
ruby
{ "resource": "" }
q3225
KaminariRoutePrefix.ActionViewExtension.rel_next_prev_link_tags
train
def rel_next_prev_link_tags(scope, options = {}) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) output = String.new output << tag(:link, :rel => "next", :href => next_page.url) if scope.next_page.present? output << tag(:link, :rel => "prev", :href => prev_page.url) if scope.prev_page.present? output.html_safe end
ruby
{ "resource": "" }
q3226
WCAGColorContrast.Ratio.ratio
train
def ratio(rgb1, rgb2) raise InvalidColorError, rgb1 unless valid_rgb?(rgb1) raise InvalidColorError, rgb2 unless valid_rgb?(rgb2) srgb1 = rgb_to_srgba(rgb1) srgb2 = rgb_to_srgba(rgb2) l1 = srgb_lightness(srgb1) l2 = srgb_lightness(srgb2) l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05) end
ruby
{ "resource": "" }
q3227
WCAGColorContrast.Ratio.relative_luminance
train
def relative_luminance(rgb) raise InvalidColorError, rgb unless valid_rgb?(rgb) srgb = rgb_to_srgba(rgb) srgb_lightness(srgb) end
ruby
{ "resource": "" }
q3228
WCAGColorContrast.Ratio.rgb_to_srgba
train
def rgb_to_srgba(rgb) rgb << rgb if rgb.size == 3 [ rgb.slice(0,2).to_i(16) / 255.0, rgb.slice(2,2).to_i(16) / 255.0, rgb.slice(4,2).to_i(16) / 255.0 ] end
ruby
{ "resource": "" }
q3229
WCAGColorContrast.Ratio.srgb_lightness
train
def srgb_lightness(srgb) r, g, b = srgb 0.2126 * (r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4) + 0.7152 * (g <= 0.03928 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4) + 0.0722 * (b <= 0.03928 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4) end
ruby
{ "resource": "" }
q3230
Frankenstein.Server.run
train
def run @op_mutex.synchronize do return AlreadyRunningError if @server @server_thread = Thread.new do @op_mutex.synchronize do begin wrapped_logger = Frankenstein::Server::WEBrickLogger.new(logger: @logger, progname: "Frankenstein::Server") @server = WEBrick::HTTPServer.new(Logger: wrapped_logger, BindAddress: nil, Port: @port, AccessLog: [[wrapped_logger, WEBrick::AccessLog::COMMON_LOG_FORMAT]]) @server.mount "/", Rack::Handler::WEBrick, app rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: ensure @op_cv.signal end end begin @server.start if @server rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: end end end @op_mutex.synchronize { @op_cv.wait(@op_mutex) until @server } end
ruby
{ "resource": "" }
q3231
Outbox.MessageTypes.assign_message_type_values
train
def assign_message_type_values(values) values.each do |key, value| public_send(key, value) if respond_to?(key) end end
ruby
{ "resource": "" }
q3232
Esearch.Request.run
train
def run(connection) connection.public_send(verb, path) do |request| request.params = params request.headers[:content_type] = Command::JSON_CONTENT_TYPE request.body = MultiJson.dump(body) end end
ruby
{ "resource": "" }
q3233
Modelish.Validations.validate
train
def validate errors = {} call_validators do |name, message| errors[name] ||= [] errors[name] << to_error(message) end errors end
ruby
{ "resource": "" }
q3234
ParallelAppium.ParallelAppium.load_capabilities
train
def load_capabilities(caps) device = @server.device_data unless device.nil? caps[:caps][:udid] = device.fetch('udid', nil) caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion]) caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName]) caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil) caps[:caps][:avd] = device.fetch('avd', nil) end caps[:appium_lib][:server_url] = ENV['SERVER_URL'] caps end
ruby
{ "resource": "" }
q3235
ParallelAppium.ParallelAppium.initialize_appium
train
def initialize_appium(**args) platform = args[:platform] caps = args[:caps] platform = ENV['platform'] if platform.nil? if platform.nil? puts 'Platform not found in environment variable' exit end caps = Appium.load_appium_txt file: File.new("#{Dir.pwd}/appium-#{platform}.txt") if caps.nil? if caps.nil? puts 'No capabilities specified' exit end puts 'Preparing to load capabilities' capabilities = load_capabilities(caps) puts 'Loaded capabilities' @driver = Appium::Driver.new(capabilities, true) puts 'Created driver' Appium.promote_appium_methods Object Appium.promote_appium_methods RSpec::Core::ExampleGroup @driver end
ruby
{ "resource": "" }
q3236
ParallelAppium.ParallelAppium.setup_signal_handler
train
def setup_signal_handler(ios_pid = nil, android_pid = nil) Signal.trap('INT') do Process.kill('INT', ios_pid) unless ios_pid.nil? Process.kill('INT', android_pid) unless android_pid.nil? # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' # Terminate ourself exit 1 end end
ruby
{ "resource": "" }
q3237
ParallelAppium.ParallelAppium.execute_specs
train
def execute_specs(platform, threads, spec_path, parallel = false) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
ruby
{ "resource": "" }
q3238
ParallelAppium.ParallelAppium.setup
train
def setup(platform, file_path, threads, parallel) spec_path = 'spec/' spec_path = file_path.to_s unless file_path.nil? puts "SPEC PATH:#{spec_path}" unless %w[ios android].include? platform puts "Invalid platform #{platform}" exit end execute_specs platform, threads, spec_path, parallel end
ruby
{ "resource": "" }
q3239
ParallelAppium.ParallelAppium.start
train
def start(**args) platform = args[:platform] file_path = args[:file_path] # Validate environment variable if ENV['platform'].nil? if platform.nil? puts 'No platform detected in environment and none passed to start...' exit end ENV['platform'] = platform end sleep 3 # Appium ports ios_port = 4725 android_port = 4727 default_port = 4725 platform = ENV['platform'] # Platform is required check_platform platform platform = platform.downcase ENV['BASE_DIR'] = Dir.pwd # Check if multithreaded for distributing tests across devices threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i parallel = threads != 1 if platform != 'all' pid = fork do if !parallel ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub" @server.start_single_appium platform, default_port else ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' @server.launch_hub_and_nodes platform end setup(platform, file_path, threads, parallel) end puts "PID: #{pid}" setup_signal_handler(pid) Process.waitpid(pid) else # Spin off 2 sub-processes, one for Android connections and another for iOS, # each with redefining environment variables for the server url, number of threads and platform ios_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start iOS' @server.launch_hub_and_nodes 'ios' else ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub" puts 'Start iOS' @server.start_single_appium 'ios', ios_port end setup('ios', file_path, threads, parallel) end android_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start Android' @server.launch_hub_and_nodes 'android' else ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub" puts 'Start Android' @server.start_single_appium 'android', android_port end setup('android', file_path, threads, parallel) end puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}" setup_signal_handler(ios_pid, android_pid) [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) } end # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' end
ruby
{ "resource": "" }
q3240
GAAPI.Query.execute
train
def execute uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true # https.set_debug_output($stdout) request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{access_token}") request.body = query.to_json Response.new(https.request(request)) end
ruby
{ "resource": "" }
q3241
GAAPI.Query.stringify_keys
train
def stringify_keys(object) case object when Hash object.each_with_object({}) do |(key, value), result| result[key.to_s] = stringify_keys(value) end when Array object.map { |e| stringify_keys(e) } else object end end
ruby
{ "resource": "" }
q3242
Esearch.Command.raise_status_error
train
def raise_status_error message = format( 'expected response stati: %s but got: %s, remote message: %s', expected_response_stati, response.status, remote_message.inspect ) fail ProtocolError, message end
ruby
{ "resource": "" }
q3243
ShakeTheCounter.Performance.sections
train
def sections return @sections if @sections @sections = [] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event.client.call(path, http_method: :get) for section in result @sections << ShakeTheCounter::Section.new(section, performance: self) end return @sections end
ruby
{ "resource": "" }
q3244
Modernize.VersionParsingContext.method_missing
train
def method_missing(method, *args, &block) raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 raise NoMethodError.new("Undefined translation method #{method}") unless MapMethods.respond_to?(method) @maps << {name: method, field: args[0], block: block} end
ruby
{ "resource": "" }
q3245
FiatPublication.Comment.mention_users
train
def mention_users mentions ||= begin regex = /@([\w]+)/ self.body.scan(regex).flatten end mentioned_users ||= User.where(username: mentions) if mentioned_users.any? mentioned_users.each do |i| FiatNotifications::Notification::CreateNotificationJob.set(wait: 5.seconds).perform_later( self, self.authorable, i, action: "mentioned", notified_type: "User", notified_ids: [i.id], email_template_id: FiatNotifications.email_template_id, email_subject: "You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}", email_body: "#{self.body}", reply_to_address: FiatNotifications.reply_to_email_address ) end end end
ruby
{ "resource": "" }
q3246
Assignment.Attributes.assign_attributes
train
def assign_attributes(new_attributes) if !new_attributes.respond_to?(:stringify_keys) raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." end return if new_attributes.nil? || new_attributes.empty? attributes = new_attributes.stringify_keys _assign_attributes(attributes) end
ruby
{ "resource": "" }
q3247
Hoiio.ResponseUtil.create_hash
train
def create_hash(response) begin JSON.parse response rescue JSON::ParserError response rescue StandardError response end end
ruby
{ "resource": "" }
q3248
GbAgencies.Agencies.standard_agency1
train
def standard_agency1(scope, prefix, mandate) case scope when "national" ret = NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil ret = ret.join(" ") if ret && ret.is_a?(Array) ret when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" LOCAL&.dig(@lang, prefix.to_sym) || nil when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
ruby
{ "resource": "" }
q3249
GbAgencies.Agencies.standard_agency
train
def standard_agency(scope, prefix, mandate) case scope when "national" NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" "#{LOCAL&.dig(@lang, prefix.to_sym) || 'XXXX'}#{@labels["local_issuer"]}" when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
ruby
{ "resource": "" }
q3250
Scheduler.MainProcess.start_loop
train
def start_loop loop do begin # Loads up a job queue. queue = [] # Counts jobs to schedule. running_jobs = @job_class.running.entries schedulable_jobs = @job_class.queued.order_by(scheduled_at: :asc).entries jobs_to_schedule = @max_concurrent_jobs - running_jobs.count jobs_to_schedule = 0 if jobs_to_schedule < 0 # Finds out scheduled jobs waiting to be performed. scheduled_jobs = [] schedulable_jobs.first(jobs_to_schedule).each do |job| job_pid = Process.fork do begin job.perform_now rescue StandardError => e @logger.error "[Scheduler:#{@pid}] Error #{e.class}: #{e.message} "\ "(#{e.backtrace.select { |l| l.include?('app') }.first}).".red end end Process.detach(job_pid) job.update_attribute(:pid, job_pid) scheduled_jobs << job queue << job.id.to_s end # Logs launched jobs if scheduled_jobs.any? @logger.info "[Scheduler:#{@pid}] Launched #{scheduled_jobs.count} "\ "jobs: #{scheduled_jobs.map(&:id).map(&:to_s).join(', ')}.".cyan else if schedulable_jobs.count == 0 @logger.info "[Scheduler:#{@pid}] No jobs in queue.".cyan else @logger.warn "[Scheduler:#{@pid}] No jobs launched, reached maximum "\ "number of concurrent jobs. Jobs in queue: #{schedulable_jobs.count}.".yellow end end # Checks for completed jobs: clears up queue and kills any zombie pid queue.delete_if do |job_id| job = @job_class.find(job_id) if job.present? and job.status.in? [ :completed, :error ] begin @logger.info "[Scheduler:#{@pid}] Rimosso processo #{job.pid} per lavoro completato".cyan Process.kill :QUIT, job.pid rescue Errno::ENOENT, Errno::ESRCH end true else false end end # Waits the specified amount of time before next iteration sleep @polling_interval rescue StandardError => error @logger.error "[Scheduler:#{@pid}] Error #{error.message}".red @logger.error error.backtrace.select { |line| line.include?('app') }.join("\n").red rescue SignalException => signal if signal.message.in? [ 'SIGINT', 'SIGTERM', 'SIGQUIT' ] @logger.warn "[Scheduler:#{@pid}] Received interrupt, terminating scheduler..".yellow reschedule_running_jobs break end end end end
ruby
{ "resource": "" }
q3251
Scheduler.MainProcess.reschedule_running_jobs
train
def reschedule_running_jobs @job_class.running.each do |job| begin Process.kill :QUIT, job.pid if job.pid.present? rescue Errno::ESRCH, Errno::EPERM ensure job.schedule end end end
ruby
{ "resource": "" }
q3252
ParallelAppium.Server.device_data
train
def device_data JSON.parse(ENV['DEVICES']).find { |t| t['thread'].eql? thread } unless ENV['DEVICES'].nil? end
ruby
{ "resource": "" }
q3253
ParallelAppium.Server.save_device_data
train
def save_device_data(dev_array) dev_array.each do |device| device_hash = {} device.each do |key, value| device_hash[key] = value end # Delete and create output folder `rm -rf output` `mkdir output` device.each do |k, v| open("output/specs-#{device_hash[:udid]}.log", 'a') do |file| file << "#{k}: #{v}\n" end end end end
ruby
{ "resource": "" }
q3254
ParallelAppium.Server.get_devices
train
def get_devices(platform) ENV['THREADS'] = '1' if ENV['THREADS'].nil? if platform == 'android' Android.new.devices elsif platform == 'ios' IOS.new.devices end end
ruby
{ "resource": "" }
q3255
ParallelAppium.Server.appium_server_start
train
def appium_server_start(**options) command = +'appium' command << " --nodeconfig #{options[:config]}" if options.key?(:config) command << " -p #{options[:port]}" if options.key?(:port) command << " -bp #{options[:bp]}" if options.key?(:bp) command << " --log #{Dir.pwd}/output/#{options[:log]}" if options.key?(:log) command << " --tmp #{ENV['BASE_DIR']}/tmp/#{options[:tmp]}" if options.key?(:tmp) Dir.chdir('.') do puts(command) pid = spawn(command, out: '/dev/null') puts 'Waiting for Appium to start up...' sleep 10 puts "Appium PID: #{pid}" puts 'Appium server did not start' if pid.nil? end end
ruby
{ "resource": "" }
q3256
ParallelAppium.Server.generate_node_config
train
def generate_node_config(file_name, appium_port, device) system 'mkdir node_configs >> /dev/null 2>&1' f = File.new("#{Dir.pwd}/node_configs/#{file_name}", 'w') f.write(JSON.generate( capabilities: [{ browserName: device[:udid], maxInstances: 5, platform: device[:platform] }], configuration: { cleanUpCycle: 2000, timeout: 1_800_000, registerCycle: 5000, proxy: 'org.openqa.grid.selenium.proxy.DefaultRemoteProxy', url: "http://127.0.0.1:#{appium_port}/wd/hub", host: '127.0.0.1', port: appium_port, maxSession: 5, register: true, hubPort: 4444, hubHost: 'localhost' } )) f.close end
ruby
{ "resource": "" }
q3257
ParallelAppium.Server.start_single_appium
train
def start_single_appium(platform, port) puts 'Getting Device data' devices = get_devices(platform)[0] if devices.nil? puts "No devices for #{platform}, Exiting..." exit else udid = devices[:udid] save_device_data [devices] end ENV['UDID'] = udid appium_server_start udid: udid, log: "appium-#{udid}.log", port: port end
ruby
{ "resource": "" }
q3258
ParallelAppium.Server.launch_hub_and_nodes
train
def launch_hub_and_nodes(platform) start_hub unless port_open?('localhost', 4444) devices = get_devices(platform) if devices.nil? puts "No devices for #{platform}, Exiting...." exit else save_device_data [devices] end threads = ENV['THREADS'].to_i if devices.size < threads puts "Not enough available devices, reducing to #{devices.size} threads" ENV['THREADS'] = devices.size.to_s else puts "Using #{threads} of the available #{devices.size} devices" devices = devices[0, threads] end Parallel.map_with_index(devices, in_processes: devices.size) do |device, index| offset = platform == 'android' ? 0 : threads port = 4000 + index + offset bp = 2250 + index + offset config_name = "#{device[:udid]}.json" generate_node_config config_name, port, device node_config = "#{Dir.pwd}/node_configs/#{config_name}" puts port appium_server_start config: node_config, port: port, bp: bp, udid: device[:udid], log: "appium-#{device[:udid]}.log", tmp: device[:udid] end end
ruby
{ "resource": "" }
q3259
Mb.Service.build_request
train
def build_request(options = {}) src_creds_name = SRC_CREDS options = options.dup #Don't clobber the original hash #NOTE: Could extend this to read WSDL document or using Savon client to tell which nodes are allowed in the request #performing the same type of test against passed in variables on each and replacing with the appropriate value final_opts = options.dup options.keys.each do |key| orig_key = key new_key = orig_key.to_s.gsub("_", "").downcase if (new_key == src_creds_name.downcase) final_opts[src_creds_name] = final_opts[key] #Set "SourceCredentials" to hash referenced by similarly named final_opts.delete(orig_key) end end opts = {}; final_opts.each do |key, value| new_val = value if value.kind_of?(Array) tranformed = {} if item[0].kind_of? Integer transformed[:int] = value elsif item[0].kind_of? String transformed[:string] = value else break #Don't know how to deal with it, return regular end new_val = transformed end opts[key] = new_val end request_body = { "PageSize" => 10, "CurrentPageIndex" => 0 } request_body["XMLDetail"] = "Bare" unless opts["Fields"] request_body[src_creds_name] = @src_creds.to_hash if @src_creds request_body["UserCredentials"] = @usr_creds.to_hash if @usr_creds return request_body.merge!(opts) end
ruby
{ "resource": "" }
q3260
Mb.Service.get_service
train
def get_service(service_symbol, options, unwrap_bool) raise "No SOAP client instantiated" unless @client request_options = build_request(options) raise "No SourceCredentials supplied" if !@src_creds || !request_options[SRC_CREDS] #Just checking for :source_credentials does not #check all possiblities as "SourceCredentials", response = @client.request Mb::Meta::NS, service_symbol do soap.body = { "Request" => request_options } end if unwrap_bool #Unwrap response to hash array underneath) plural = service_symbol.to_s.gsub("get_", "") singular =plural[0..-2] #Remove last r = response.to_hash basify = lambda {|enda| (service_symbol.to_s + "_" + enda).to_sym } r = r[basify.call('response')][basify.call('result')] return [] if r[:result_count] == "0" r = r[plural.to_sym][singular.to_sym] return r end response end
ruby
{ "resource": "" }
q3261
Malcolm.SOAPParser.on_complete
train
def on_complete(env) env[:body] = Nori.new( strip_namespaces: true, convert_tags_to: ->(tag) { tag.snakecase.to_sym } ).parse(env[:body]) raise SOAPError, "Invalid SOAP response" if env[:body].empty? env[:body] = env[:body][:envelope][:body] env[:body] = find_key_in_hash(env[:body], @key) end
ruby
{ "resource": "" }
q3262
Malcolm.SOAPParser.find_key_in_hash
train
def find_key_in_hash(hash, index) hash.each do |key, val| if val.respond_to? :has_key? if val.has_key? index return val[index] else return find_key_in_hash val, index end else val end end end
ruby
{ "resource": "" }
q3263
Zyps.GameObject.<<
train
def <<(item) if item.kind_of? Zyps::Location self.location = item elsif item.kind_of? Zyps::Color self.color = item elsif item.kind_of? Zyps::Vector self.vector = item else raise "Invalid item: #{item.class}" end self end
ruby
{ "resource": "" }
q3264
Zyps.Behavior.<<
train
def <<(item) if item.kind_of? Condition add_condition(item) elsif item.kind_of? Action add_action(item) else raise "Invalid item: #{item.class}" end self end
ruby
{ "resource": "" }
q3265
Zyps.Vector.+
train
def +(vector2) #Get the x and y components of the new vector. new_x = (self.x + vector2.x) new_y = (self.y + vector2.y) new_length_squared = new_x ** 2 + new_y ** 2 new_length = (new_length_squared == 0 ? 0 : Math.sqrt(new_length_squared)) new_angle = (new_x == 0 ? 0 : Utility.to_degrees(Math.atan2(new_y, new_x))) #Calculate speed and angle of new vector with components. Vector.new(new_length, new_angle) end
ruby
{ "resource": "" }
q3266
Charisma.Measurement.method_missing
train
def method_missing(*args) if Conversions.conversions[units.to_sym][args.first] to_f.send(units.to_sym).to(args.first) else super end end
ruby
{ "resource": "" }
q3267
Rdio.Artist.albums
train
def albums(featuring=nil,extras=nil,start=nil,count=nil) api.getAlbumsForArtist self,featuring,extras,start,count end
ruby
{ "resource": "" }
q3268
Rdio.Playlist.tracks
train
def tracks ids = track_keys return [] if not ids return ids.map {|id| Track.get id} end
ruby
{ "resource": "" }
q3269
Hyperb.Funcs.create_func
train
def create_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/create' body = {} body.merge!(prepare_json(params)) Hyperb::Request.new(self, path, {}, 'post', body).perform end
ruby
{ "resource": "" }
q3270
Hyperb.Funcs.remove_func
train
def remove_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/' + params[:name] Hyperb::Request.new(self, path, {}, 'delete').perform end
ruby
{ "resource": "" }
q3271
Hyperb.Funcs.call_func
train
def call_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name', 'uuid') path = "call/#{params[:name]}/#{params[:uuid]}" path.concat('/sync') if params.key?(:sync) && params[:sync] Hyperb::FuncCallRequest.new(self, path, {}, 'post').perform end
ruby
{ "resource": "" }
q3272
OpenQq.Gateway.wrap
train
def wrap(http_method, url, params) params = params.merge(:appid => @appid) params[:sig] = Gateway.signature( "#{@appkey}&", Gateway.make_source(http_method.to_s.upcase, url, params) ) params end
ruby
{ "resource": "" }
q3273
WillowRun.Sniffer.default_ip
train
def default_ip begin orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect rand_routable_daddr.to_s, rand_port s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end
ruby
{ "resource": "" }
q3274
WillowRun.Sniffer.default_interface
train
def default_interface ip = default_ip Socket.getifaddrs.each do |ifaddr| next unless ifaddr.addr.ip? return ifaddr.name if ifaddr.addr.ip_address == ip end # Fall back to libpcap as last resort return Pcap.lookupdev end
ruby
{ "resource": "" }
q3275
Trebuchet.Runner.run
train
def run(config, operation_name=nil) config = config.with_indifferent_access config.merge!(load_config(config[:config])) if config[:config] operation_run = false gather_operations.each do |operation| if operation_name.nil? || operation_name == operation.name op = operation.new(config) op.debrief = Trebuchet::Debrief.new({ :operation => op.class.name, :name => config['name'] }) op.run op.save_debrief operation_run = true end end raise "No Operation Run!" unless operation_run end
ruby
{ "resource": "" }
q3276
Ecic.SourceFileInfo.find_sources_file_dir
train
def find_sources_file_dir(dir = @relative_path_from_project.dirname) return nil if is_outside_project? file = File.join(@project.root, dir, "sources.rb") if dir.root? or dir.to_s == "." return nil elsif File.exists?(file) return dir else return find_sources_file_dir(dir.parent) end end
ruby
{ "resource": "" }
q3277
Zyps.ProximityCondition.select
train
def select(actor, targets) targets.find_all {|target| Utility.find_distance(actor.location, target.location) <= @distance} end
ruby
{ "resource": "" }
q3278
Zyps.CollisionCondition.select
train
def select(actor, targets) return [] unless targets.length > 0 #The size of the largest other object max_size = targets.map{|t| t.size}.max #The maximum distance on a straight line the largest object and self could be and still be touching. max_diff = Math.sqrt(actor.size / Math::PI) + Math.sqrt(max_size / Math::PI) x_range = (actor.location.x - max_diff .. actor.location.x + max_diff) y_range = (actor.location.y - max_diff .. actor.location.y + max_diff) targets.select do | target | x_range.include?(target.location.x) and y_range.include?(target.location.y) and Utility.collided?(actor, target) end end
ruby
{ "resource": "" }
q3279
Zyps.StrengthCondition.select
train
def select(actor, targets) targets.find_all {|target| actor.size >= target.size} end
ruby
{ "resource": "" }
q3280
Salesforce.SfBase.logout
train
def logout(session_ids=Hash.new) result = SfBase.connection.binding.invalidateSessions(session_ids) if"invalidateSessionsResponse" == result.to_s return true else return false end #result this.connection.binding.logout(Hash.new) end
ruby
{ "resource": "" }
q3281
UOM.Measurement.as
train
def as(unit) unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit return self if @unit == unit Measurement.new(unit, @unit.as(quantity, unit)) end
ruby
{ "resource": "" }
q3282
UOM.Measurement.apply_to_quantity
train
def apply_to_quantity(method, other) other = other.as(unit).quantity if Measurement === other new_quantity = block_given? ? yield(to_f, other) : to_f.send(method, other) Measurement.new(unit, new_quantity) end
ruby
{ "resource": "" }
q3283
UOM.Measurement.compose
train
def compose(method, other) return apply_to_quantity(method, other) unless Measurement === other other = other.as(unit) if other.unit.axis == unit.axis new_quantity = quantity.zero? ? 0.0 : quantity.to_f.send(method, other.quantity) Measurement.new(unit.send(method, other.unit), new_quantity) end
ruby
{ "resource": "" }
q3284
Rworkflow.SidekiqFlow.continue
train
def continue return if self.finished? || !self.valid? || !self.paused? if @flow_data.decr(:paused) == 0 workers = Hash[self.counters.select { |name, _| !self.class.terminal?(name) && name != :processing }] # enqueue jobs workers.each { |worker, num_objects| create_jobs(worker, num_objects) } end rescue StandardError => e Rails.logger.error("Error continuing flow #{self.id}: #{e.message}") end
ruby
{ "resource": "" }
q3285
Logmsg.LogFile.init_formatter
train
def init_formatter @formatter = proc do |s, d, p, m| "#{@format}\n" % { severity: s, datetime: d, progname: p, msg: m } end end
ruby
{ "resource": "" }
q3286
Logmsg.LogFile.init_logger
train
def init_logger @logger = case @path when STDOUT_STREAM then Logger.new(STDOUT) when STDERR_STREAM then Logger.new(STDERR) else Logger.new(File.open(@path, 'a')) end @logger.datetime_format = @datetime_format @logger.sev_threshold = @threshold unless @severities.any? @logger.formatter = @formatter unless @formatter.nil? end
ruby
{ "resource": "" }
q3287
Logmsg.LogFile.log
train
def log(message, severity = DEFAULT_SEVERITY) fail 'Logfile not registered' unless @registered return if message.nil? @logger.add(severity, message, @name) if should_log?(severity) end
ruby
{ "resource": "" }
q3288
Hoiio.IVR.set_up
train
def set_up @start = Hoiio::IVRBlock::Start.new @client @middle = Hoiio::IVRBlock::Middle.new @client @end = Hoiio::IVRBlock::End.new @client end
ruby
{ "resource": "" }
q3289
Hyperb.Network.fips_ls
train
def fips_ls(params = {}) path = '/fips' query = {} query[:filters] = params[:filters] if params.key?(:filters) downcase_symbolize(JSON.parse(Hyperb::Request.new(self, path, query, 'get').perform)) end
ruby
{ "resource": "" }
q3290
Hyperb.Network.fip_release
train
def fip_release(params = {}) path = '/fips/release' query = {} query[:ip] = params[:ip] if params.key?(:ip) Hyperb::Request.new(self, path, query, 'post').perform end
ruby
{ "resource": "" }
q3291
Hyperb.Network.fip_allocate
train
def fip_allocate(params = {}) raise ArgumentError, 'Invalid Arguments' unless check_arguments(params, 'count') path = '/fips/allocate' query = {} query[:count] = params[:count] if params.key?(:count) fips = JSON.parse(Hyperb::Request.new(self, path, query, 'post').perform) fips end
ruby
{ "resource": "" }
q3292
Zyps.SpeedLimit.act
train
def act(environment) environment.objects.each do |object| object.vector.speed = Utility.constrain_value(object.vector.speed, @maximum) end end
ruby
{ "resource": "" }
q3293
Zyps.Accelerator.act
train
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Push on object. object.vector += Vector.new(@vector.speed * elapsed_time, @vector.pitch) end end
ruby
{ "resource": "" }
q3294
Zyps.Friction.act
train
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Slow object. acceleration = @force * elapsed_time speed = object.vector.speed if speed > 0 speed -= acceleration speed = 0 if speed < 0 elsif speed < 0 speed += acceleration speed = 0 if speed > 0 end object.vector.speed = speed end end
ruby
{ "resource": "" }
q3295
Zyps.PopulationLimit.act
train
def act(environment) excess = environment.object_count - @count if excess > 0 objects_for_removal = [] environment.objects.each do |object| objects_for_removal << object break if objects_for_removal.length >= excess end objects_for_removal.each {|object| environment.remove_object(object.identifier)} end end
ruby
{ "resource": "" }
q3296
Charisma.Characterization.has
train
def has(name, options = {}, &blk) name = name.to_sym self[name] = Characteristic.new(name, options, &blk) end
ruby
{ "resource": "" }
q3297
ActsAsStaticRecord.ClassMethods.define_static_cache_key_finder
train
def define_static_cache_key_finder#:nodoc: return unless acts_as_static_record_options[:find_by_attribute_support] #define the key column if it is not a hash column if ((key_column = acts_as_static_record_options[:key]) && (!column_methods_hash.include?(key_column.to_sym))) class_eval %{ def self.find_by_#{key_column}(arg) self.static_record_cache[:key][arg.to_s] end }, __FILE__, __LINE__ end end
ruby
{ "resource": "" }
q3298
ActsAsStaticRecord.SingletonMethods.static_record_lookup_key
train
def static_record_lookup_key(value)#:nodoc: if value.is_a? self static_record_lookup_key( value.send( acts_as_static_record_options[:lookup_key] || acts_as_static_record_options[:key] || primary_key ) ) else value.to_s.gsub(' ', '_').gsub(/\W/, "").underscore end end
ruby
{ "resource": "" }
q3299
ActsAsStaticRecord.SingletonMethods.find_in_static_record_cache
train
def find_in_static_record_cache(finder, attributes)#:nodoc: list = static_record_cache[:primary_key].values.inject([]) do |list, record| unless attributes.select{|k,v| record.send(k).to_s != v.to_s}.any? return record if finder == :first list << record end list end finder == :all ? list : list.last end
ruby
{ "resource": "" }