_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10000
LatoBlog.Back::PostsController.destroy
train
def destroy @post = LatoBlog::Post.find_by(id: params[:id]) return unless check_post_presence unless @post.destroy flash[:danger] = @post.post_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_post_path(@post.id) return end flash[:success] = LANGU...
ruby
{ "resource": "" }
q10001
LatoBlog.Back::PostsController.destroy_all_deleted
train
def destroy_all_deleted @posts = LatoBlog::Post.deleted if !@posts || @posts.empty? flash[:warning] = LANGUAGES[:lato_blog][:flashes][:deleted_posts_not_found] redirect_to lato_blog.posts_path(status: 'deleted') return end @posts.each do |post| unless post.destr...
ruby
{ "resource": "" }
q10002
LatoBlog.Back::PostsController.update_field
train
def update_field(field, value) case field.typology when 'text' update_field_text(field, value) when 'textarea' update_field_textarea(field, value) when 'datetime' update_field_datetime(field, value) when 'editor' update_field_editor(field, value) when ...
ruby
{ "resource": "" }
q10003
BlipTV.Video.get_attributes
train
def get_attributes url = URI.parse('http://www.blip.tv/') res = Net::HTTP.start(url.host, url.port) {|http| http.get("http://www.blip.tv/file/#{@id.to_s}?skin=api") } ...
ruby
{ "resource": "" }
q10004
BlipTV.Video.delete!
train
def delete!(creds = {}, section = "file", reason = "because") BlipTV::ApiSpec.check_attributes('videos.delete', creds) reason = reason.gsub(" ", "%20") # TODO write a method to handle this and other illegalities of URL if creds[:username] && !creds[:userlogin] creds[:userlogin] =...
ruby
{ "resource": "" }
q10005
Rester.Service._response
train
def _response(status, body=nil, headers={}) body = [body].compact headers = headers.merge("Content-Type" => "application/json") Rack::Response.new(body, status, headers).finish end
ruby
{ "resource": "" }
q10006
Ablerc.DSL.option
train
def option(name, behaviors = {}, &block) Ablerc.options << Ablerc::Option.new(name, behaviors, &block) end
ruby
{ "resource": "" }
q10007
MIPPeR.Variable.value
train
def value # Model must be solved to have a value return nil unless @model && @model.status == :optimized value = @model.variable_value self case @type when :integer value.round when :binary [false, true][value.round] else value end end
ruby
{ "resource": "" }
q10008
VRTK::Applets.VersionApplet.run_parse
train
def run_parse obj = { 'name' => VRTK::NAME, 'version' => VRTK::VERSION, 'codename' => VRTK::CODENAME, 'ffmpeg' => ffmpeg_version, 'magick' => magick_version, 'license' => VRTK::LICENSE } puts JSON.pretty_unparse obj end
ruby
{ "resource": "" }
q10009
TF2R.Scraper.scrape_main_page
train
def scrape_main_page page = fetch('http://tf2r.com/raffles.html') # All raffle links begin with 'tf2r.com/k' raffle_links = page.links_with(href: /tf2r\.com\/k/) raffle_links.map! { |x| x.uri.to_s } raffle_links.reverse! end
ruby
{ "resource": "" }
q10010
TF2R.Scraper.scrape_raffle_for_creator
train
def scrape_raffle_for_creator(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # The main 'a' element, containing the creator's username. user_anchor = infos[2].css('a')[0] steam_id = extract_steam_id(user_anchor.at...
ruby
{ "resource": "" }
q10011
TF2R.Scraper.scrape_raffle_for_raffle
train
def scrape_raffle_for_raffle(page) # Reag classed some things "raffle_infomation". That's spelled right. infos = page.parser.css('.raffle_infomation') # Elements of the main raffle info table. raffle_tds = infos[3].css('td') # 'kabc123' for http://tf2r.com/kabc123.html' link_snippe...
ruby
{ "resource": "" }
q10012
TF2R.Scraper.scrape_raffle_for_participants
train
def scrape_raffle_for_participants(page) participants = [] participant_divs = page.parser.css('.pentry') participant_divs.each do |participant| user_anchor = participant.children[1] steam_id = extract_steam_id(user_anchor.to_s) username = participant.text color = extrac...
ruby
{ "resource": "" }
q10013
TF2R.Scraper.scrape_user
train
def scrape_user(user_page) if user_page.parser.css('.profile_info').empty? raise InvalidUserPage, 'The given page does not correspond to any user.' else infos = user_page.parser.css('.raffle_infomation') #sic user_anchor = infos[1].css('a')[0] steam_id = extract_steam_id(use...
ruby
{ "resource": "" }
q10014
TF2R.Scraper.scrape_ranks
train
def scrape_ranks(info_page) rank_divs = info_page.parser.css('#ranks').children ranks = rank_divs.select { |div| div.children.size == 3 } ranks.map { |div| extract_rank(div) } end
ruby
{ "resource": "" }
q10015
SlackBotManager.Connection.start
train
def start # Clear RTM connections storage.delete_all(teams_key) # Start a new connection for each team storage.get_all(tokens_key).each do |id, token| create(id, token) end end
ruby
{ "resource": "" }
q10016
SlackBotManager.Connection.stop
train
def stop # Thread wrapped to ensure no lock issues on shutdown thr = Thread.new do conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'destroy') } end info('Stopped.') end thr.join end
ruby
{ "resource": "" }
q10017
SlackBotManager.Connection.restart
train
def restart conns = storage.get_all(teams_key) storage.pipeline do conns.each { |k, _| storage.set(teams_key, k, 'restart') } end end
ruby
{ "resource": "" }
q10018
SlackBotManager.Connection.find_connection
train
def find_connection(id) connections.each do |_, conn| return (conn.connected? ? conn : false) if conn && conn.id == id end false end
ruby
{ "resource": "" }
q10019
SlackBotManager.Connection.create
train
def create(id, token) fail SlackBotManager::TokenAlreadyConnected if find_connection(id) # Create connection conn = SlackBotManager::Client.new(token) conn.connect # Add to connections using a uniq token if conn cid = [id, Time.now.to_i].join(':') connections[cid] =...
ruby
{ "resource": "" }
q10020
SlackBotManager.Connection.destroy
train
def destroy(*args) options = args.extract_options! # Get connection or search for connection with cid if options[:cid] conn = connections[options[:cid]] cid = options[:cid] elsif options[:id] conn, cid = find_connection(options[:id]) end return false unless c...
ruby
{ "resource": "" }
q10021
Controll::Flow::Action.PathAction.method_missing
train
def method_missing(method_name, *args, &block) if controller.respond_to? method_name controller.send method_name, *args, &block else super end end
ruby
{ "resource": "" }
q10022
SmartQue.Publisher.publish
train
def publish(queue, payload = {}) # Check queue name includes in the configured list # Return if queue doesn't exist if queue_list.include? queue # Publish sms to queue begin x_direct.publish( payload.to_json, mandatory: true, routing_key: g...
ruby
{ "resource": "" }
q10023
SmartQue.Publisher.unicast
train
def unicast(q_name, payload = {}) begin x_default.publish( payload.to_json, routing_key: dot_formatted(q_name) ) log_message("unicast status: success, Queue : #{q_name}, Content : #{payload}") :success rescue => ex log_message("Unicast error:#{ex.m...
ruby
{ "resource": "" }
q10024
SmartQue.Publisher.multicast
train
def multicast(topic, payload = {}) begin x_topic.publish( payload.to_json, routing_key: dot_formatted(topic) ) log_message("multicast status: success, Topic : #{topic}, Content : #{payload}") :success rescue => ex log_message("Multicast error:#{ex....
ruby
{ "resource": "" }
q10025
XS.PollItems.clean
train
def clean if @dirty @store = FFI::MemoryPointer.new @element_size, @items.size, true # copy over offset = 0 @items.each do |item| LibC.memcpy(@store + offset, item.pointer, @element_size) offset += @element_size end @dirty = false end ...
ruby
{ "resource": "" }
q10026
XES.Attribute.format_value
train
def format_value case @type when "string" @value when "date" @value.kind_of?(Time) ? @value.iso8601(3) : @value when "int" @value.kind_of?(Integer) ? @value : @value.to_i when "float" @value.kind_of?(Float) ? @value : @value.to_f when "boolean" ...
ruby
{ "resource": "" }
q10027
ActiveParams.Parser.combine_hashes
train
def combine_hashes(array_of_hashes) array_of_hashes.select {|v| v.kind_of?(Hash) }. inject({}) {|sum, hash| hash.inject(sum) {|sum,(k,v)| sum.merge(k => v) } } end
ruby
{ "resource": "" }
q10028
Citero.Base.from
train
def from format #Formats are enums in java, so they are all uppercase @citero = @citero::from(Formats::valueOf(format.upcase)) self #rescue any exceptions, if the error is not caught in JAR, most likely a #problem with the data rescue Exception => e raise TypeError, "Mismatched data...
ruby
{ "resource": "" }
q10029
Citero.Base.to
train
def to format #Formats are enums in java, so they are all uppercase if to_formats.include? format @citero::to(Formats::valueOf(format.upcase)) else @citero::to(CitationStyles::valueOf(format.upcase)) end #rescue any exceptions, if the error is not caught in JAR, most likely a...
ruby
{ "resource": "" }
q10030
DataPaths.Finders.each_data_path
train
def each_data_path(path) return enum_for(:each_data_path,path) unless block_given? DataPaths.paths.each do |dir| full_path = File.join(dir,path) yield(full_path) if File.exists?(full_path) end end
ruby
{ "resource": "" }
q10031
DataPaths.Finders.each_data_file
train
def each_data_file(path) return enum_for(:each_data_file,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.file?(full_path) end end
ruby
{ "resource": "" }
q10032
DataPaths.Finders.each_data_dir
train
def each_data_dir(path) return enum_for(:each_data_dir,path) unless block_given? each_data_path(path) do |full_path| yield(full_path) if File.directory?(full_path) end end
ruby
{ "resource": "" }
q10033
DataPaths.Finders.glob_data_paths
train
def glob_data_paths(pattern,&block) return enum_for(:glob_data_paths,pattern).to_a unless block_given? DataPaths.paths.each do |path| Dir.glob(File.join(path,pattern),&block) end end
ruby
{ "resource": "" }
q10034
Loco.Resizable.initWithFrame
train
def initWithFrame(properties={}) if properties.is_a? Hash # Set the initial property values from the given hash super(CGRect.new) initialize_bindings set_properties(properties) else super(properties) end view_setup self end
ruby
{ "resource": "" }
q10035
MultiSync.Client.add_target
train
def add_target(clazz, options = {}) # TODO: friendly pool names? pool_name = Celluloid.uuid supervisor.pool(clazz, as: pool_name, args: [options], size: MultiSync.target_pool_size) pool_name end
ruby
{ "resource": "" }
q10036
Cyclical.YearlyRule.potential_next
train
def potential_next(current, base) candidate = super(current, base) return candidate if (base.year - candidate.year).to_i % @interval == 0 years = ((base.year - candidate.year).to_i % @interval) (candidate + years.years).beginning_of_year end
ruby
{ "resource": "" }
q10037
ICU.Tournament.fed=
train
def fed=(fed) obj = ICU::Federation.find(fed) @fed = obj ? obj.code : nil raise "invalid tournament federation (#{fed})" if @fed.nil? && fed.to_s.strip.length > 0 end
ruby
{ "resource": "" }
q10038
ICU.Tournament.add_round_date
train
def add_round_date(round_date) round_date = round_date.to_s.strip parsed_date = Util::Date.parse(round_date) raise "invalid round date (#{round_date})" unless parsed_date @round_dates << parsed_date end
ruby
{ "resource": "" }
q10039
ICU.Tournament.tie_breaks=
train
def tie_breaks=(tie_breaks) raise "argument error - always set tie breaks to an array" unless tie_breaks.class == Array @tie_breaks = tie_breaks.map do |str| tb = ICU::TieBreak.identify(str) raise "invalid tie break method '#{str}'" unless tb tb.id end end
ruby
{ "resource": "" }
q10040
ICU.Tournament.add_player
train
def add_player(player) raise "invalid player" unless player.class == ICU::Player raise "player number (#{player.num}) should be unique" if @player[player.num] @player[player.num] = player end
ruby
{ "resource": "" }
q10041
ICU.Tournament.rerank
train
def rerank tie_break_methods, tie_break_order, tie_break_hash = tie_break_data @player.values.sort do |a,b| cmp = 0 tie_break_methods.each do |m| cmp = (tie_break_hash[m][a.num] <=> tie_break_hash[m][b.num]) * tie_break_order[m] if cmp == 0 end cmp end.each_wi...
ruby
{ "resource": "" }
q10042
ICU.Tournament.renumber
train
def renumber(criterion = :rank) if (criterion.class == Hash) # Undocumentted feature - supply your own hash. map = criterion else # Official way of reordering. map = Hash.new # Renumber by rank only if possible. criterion = criterion.to_s.downcase if ...
ruby
{ "resource": "" }
q10043
ICU.Tournament.validate!
train
def validate!(options={}) begin check_ranks rescue rerank end if options[:rerank] check_players check_rounds check_dates check_teams check_ranks(:allow_none => true) check_type(options[:type]) if options[:type] true end
ruby
{ "resource": "" }
q10044
ICU.Tournament.serialize
train
def serialize(format, arg={}) serializer = case format.to_s.downcase when 'krause' then ICU::Tournament::Krause.new when 'foreigncsv' then ICU::Tournament::ForeignCSV.new when 'spexport' then ICU::Tournament::SPExport.new when '' then raise "no format supplied" ...
ruby
{ "resource": "" }
q10045
ICU.Tournament.check_players
train
def check_players raise "the number of players (#{@player.size}) must be at least 2" if @player.size < 2 ids = Hash.new fide_ids = Hash.new @player.each do |num, p| if p.id raise "duplicate ICU IDs, players #{p.num} and #{ids[p.id]}" if ids[p.id] ids[p.id] = num ...
ruby
{ "resource": "" }
q10046
ICU.Tournament.check_rounds
train
def check_rounds round = Hash.new round_last = last_round @player.values.each do |p| p.results.each do |r| round[r.round] = true end end (1..round_last).each { |r| raise "there are no results for round #{r}" unless round[r] } if rounds raise "declare...
ruby
{ "resource": "" }
q10047
ICU.Tournament.check_dates
train
def check_dates raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish if @round_dates.size > 0 raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates.size == @rounds raise "t...
ruby
{ "resource": "" }
q10048
ICU.Tournament.check_type
train
def check_type(type) if type.respond_to?(:validate!) type.validate!(self) elsif klass = self.class.factory(type.to_s) klass.new.validate!(self) else raise "invalid type supplied for validation check" end end
ruby
{ "resource": "" }
q10049
ICU.Tournament.tie_break_score
train
def tie_break_score(hash, method, player, rounds) case method when :score then player.points when :wins then player.results.inject(0) { |t,r| t + (r.opponent && r.score == 'W' ? 1 : 0) } when :blacks then player.results.inject(0) { |t,r| t + (r.opponent && r.colour =...
ruby
{ "resource": "" }
q10050
Capnotify.Plugin.deployed_by
train
def deployed_by username = nil scm = fetch(:scm, nil) if scm if scm.to_sym == :git username = `git config user.name`.chomp username = nil if $? != 0 || username.strip == '' end end username || `whoami`.chomp end
ruby
{ "resource": "" }
q10051
Capnotify.Plugin.unload_plugin
train
def unload_plugin(name) p = get_plugin(name) p.unload if p.respond_to?(:unload) Capistrano.remove_plugin(name) end
ruby
{ "resource": "" }
q10052
Capnotify.Plugin.get_plugin
train
def get_plugin(name) raise "Unknown plugin: #{ name }" unless Capistrano::EXTENSIONS.keys.include?(name) self.send(name) end
ruby
{ "resource": "" }
q10053
Capnotify.Plugin.build_template
train
def build_template(template_path) # FIXME: this is called every time build_template is called. # although this is idepodent, it's got room for optimization self.build_components! ERB.new( File.open( template_path ).read, nil, '<>' ).result(self.binding) end
ruby
{ "resource": "" }
q10054
Capnotify.Plugin.component
train
def component(name) components.each { |c| return c if c.name == name.to_sym } return nil end
ruby
{ "resource": "" }
q10055
Capnotify.Plugin.insert_component_before
train
def insert_component_before(name, component) # iterate over all components, find the component with the given name # once found, insert the given component at that location and return components.each_with_index do |c, i| if c.name == name components.insert(i, component) ret...
ruby
{ "resource": "" }
q10056
Capnotify.Plugin.insert_component_after
train
def insert_component_after(name, component) # iterate over all components, find the component with the given name # once found, insert the given component at the following location and return components.each_with_index do |c, i| if c.name == name components.insert(i + 1, component) ...
ruby
{ "resource": "" }
q10057
Networkr.MultiGraph.new_edge_key
train
def new_edge_key(u, v) if @adj[u] && @adj[u][v] keys = @adj[u][v] key = keys.length while keys.include?(key) key += 1 end return key else return 0 end end
ruby
{ "resource": "" }
q10058
GhContributors.Calculator.calculated_data
train
def calculated_data @data ||= @raw_data.group_by { |contributor| contributor['login'] }.map {|login, data| log "user: #{login}" [login, user_data(login, data)] }.sort_by{|login, data| [1000000/data['contributions'], login] } end
ruby
{ "resource": "" }
q10059
Scat.Cache.start
train
def start(redis) logger.debug { "Scat is starting the Redis cache server..." } unless system(REDIS_SERVER, REDIS_CONF) then raise ScatError.new("Scat cannot start the Redis cache server.") end # Ping the server until loaded. 3.times do |n| begin redis.ping ...
ruby
{ "resource": "" }
q10060
Redlander.Model.query
train
def query(q, options = {}, &block) query = Query::Results.new(q, options) query.process(self, &block) end
ruby
{ "resource": "" }
q10061
Octo.Funnel.populate_with_fake_data
train
def populate_with_fake_data(interval_days = 7) if self.enterprise.fakedata? today = Time.now.beginning_of_day (today - interval_days.days).to(today, 24.hour).each do |ts| Octo::FunnelData.new( enterprise_id: self.enterprise_id, funnel_slug: self.name_slug, ...
ruby
{ "resource": "" }
q10062
Octo.Funnel.data
train
def data(ts = Time.now.floor) args = { enterprise_id: self.enterprise.id, funnel_slug: self.name_slug, ts: ts } res = Octo::FunnelData.where(args) if res.count > 0 res.first elsif self.enterprise.fakedata? args.merge!({ value: fake_data(self.funnel.c...
ruby
{ "resource": "" }
q10063
Octo.Funnel.fake_data
train
def fake_data(n) fun = Array.new(n) max_dropoff = 100/n n.times do |i| if i == 0 fun[i] = 100.0 else fun[i] = fun[i-1] - rand(1..max_dropoff) if fun[i] < 0 fun[i] = rand(0...fun[i].abs) end end end fun end
ruby
{ "resource": "" }
q10064
SlackBotManager.Client.handle_error
train
def handle_error(err, data = nil) case determine_error_type(err) when :token_revoked on_revoke(data) when :rate_limited on_rate_limit(data) when :closed on_close(data) else on_error(err, data) end end
ruby
{ "resource": "" }
q10065
Activr.Storage.find_activity
train
def find_activity(activity_id) activity_hash = self.driver.find_activity(activity_id) if activity_hash # run hook self.run_hook(:did_find_activity, activity_hash) # unserialize Activr::Activity.from_hash(activity_hash) else nil end end
ruby
{ "resource": "" }
q10066
Activr.Storage.find_activities
train
def find_activities(limit, options = { }) # default options options = { :skip => 0, :before => nil, :after => nil, :entities => { }, :only => [ ], :except => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:onl...
ruby
{ "resource": "" }
q10067
Activr.Storage.count_activities
train
def count_activities(options = { }) # default options options = { :before => nil, :after => nil, :entities => { }, :only => [ ], :except => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Ar...
ruby
{ "resource": "" }
q10068
Activr.Storage.count_duplicate_activities
train
def count_duplicate_activities(activity, after) entities = { } activity.entities.each do |entity_name, entity| entities[entity_name.to_sym] = entity.model_id end self.count_activities({ :only => activity.class, :entities => entities, :after => after, ...
ruby
{ "resource": "" }
q10069
Activr.Storage.delete_activities_for_entity_model
train
def delete_activities_for_entity_model(model) Activr.registry.activity_entities_for_model(model.class).each do |entity_name| self.driver.delete_activities(:entities => { entity_name => model.id }) end end
ruby
{ "resource": "" }
q10070
Activr.Storage.find_timeline_entry
train
def find_timeline_entry(timeline, tl_entry_id) timeline_entry_hash = self.driver.find_timeline_entry(timeline.kind, tl_entry_id) if timeline_entry_hash # run hook self.run_hook(:did_find_timeline_entry, timeline_entry_hash, timeline.class) # unserialize Activr::Timeline::Ent...
ruby
{ "resource": "" }
q10071
Activr.Storage.find_timeline
train
def find_timeline(timeline, limit, options = { }) options = { :skip => 0, :only => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) result = self.driver.find_timeline_entries(timeline.kind, timeline.recipient_id, limi...
ruby
{ "resource": "" }
q10072
Activr.Storage.count_timeline
train
def count_timeline(timeline, options = { }) options = { :only => [ ], }.merge(options) options[:only] = [ options[:only] ] if (options[:only] && !options[:only].is_a?(Array)) self.driver.count_timeline_entries(timeline.kind, timeline.recipient_id, options) end
ruby
{ "resource": "" }
q10073
Activr.Storage.delete_timeline
train
def delete_timeline(timeline, options = { }) # default options options = { :before => nil, :entities => { }, }.merge(options) self.driver.delete_timeline_entries(timeline.kind, timeline.recipient_id, options) end
ruby
{ "resource": "" }
q10074
Activr.Storage.delete_timeline_entries_for_entity_model
train
def delete_timeline_entries_for_entity_model(model) Activr.registry.timeline_entities_for_model(model.class).each do |timeline_class, entities| entities.each do |entity_name| self.driver.delete_timeline_entries(timeline_class.kind, nil, :entities => { entity_name => model.id }) end ...
ruby
{ "resource": "" }
q10075
Activr.Storage.run_hook
train
def run_hook(name, *args) return if @hooks[name].blank? @hooks[name].each do |hook| args.any? ? hook.call(*args) : hook.call end end
ruby
{ "resource": "" }
q10076
Formant.FormObject.reformatted!
train
def reformatted! self.class.format_fields.each do |field_name, format_method, options| formatted_value = send(format_method, get_field(field_name), options) set_field(field_name, formatted_value) end self end
ruby
{ "resource": "" }
q10077
Formant.FormObject.to_params
train
def to_params attrs = Hash.new instance_variables.each do |ivar| name = ivar[1..-1] attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}=" end attrs end
ruby
{ "resource": "" }
q10078
ParamProtected.Protector.merge_protections
train
def merge_protections(protections, protected_params) protected_params.each do |k,v| if protections[k].is_a?(Hash) merge_protections(protections[k], v) if v else protections[k] = v end end protections end
ruby
{ "resource": "" }
q10079
SoundDrop.Drop.media_url
train
def media_url begin r = HTTParty.get("https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}") r['http_mp3_128_url'] rescue Exception => ex raise SoundDrop::Exception::FailedRequest.new(ex) end end
ruby
{ "resource": "" }
q10080
ActiveAdminSimpleLife.SimpleMenu.for
train
def for(klass, options = {}, &blk) ActiveAdmin.register klass do options = {index: {}, form: {}, filter: {}}.merge options permitted_params = options.delete :permitted_params permit_params(*(klass.main_fields + (permitted_params || []))) # menu_options = options.slice(:priority, :p...
ruby
{ "resource": "" }
q10081
MissingText.Diff.generate_diff_for_language
train
def generate_diff_for_language(current_language, target_language) current_langmap = langmap[current_language] target_langmap = langmap[target_language] diffmap_key = [current_language, target_language] diffmap[diffmap_key] = current_langmap - target_langmap end
ruby
{ "resource": "" }
q10082
MissingText.Diff.make_keymap
train
def make_keymap(langmap_entry, language) language.each do |key, value| if value.is_a? Hash make_keymap_for(langmap_entry, value, [key.to_sym]) else langmap_entry << [key.to_sym] end end end
ruby
{ "resource": "" }
q10083
MissingText.Diff.make_keymap_for
train
def make_keymap_for(langmap_entry, language, key_path) language.each do |key, value| # need a new value of this for every value we are looking at because we want all route traces to have single threading for when they are called again new_path = Array.new key_path if value.is_a? Hash make_...
ruby
{ "resource": "" }
q10084
Scalaroid.TransactionSingleOp.write
train
def write(key, value, binary = false) value = @conn.class.encode_value(value, binary) result = @conn.call(:write, [key, value]) @conn.class.check_fail_abort(result) @conn.class.process_result_commit(result) end
ruby
{ "resource": "" }
q10085
Scalaroid.TransactionSingleOp.add_del_on_list
train
def add_del_on_list(key, to_add, to_remove) result = @conn.call(:add_del_on_list, [key, to_add, to_remove]) @conn.class.check_fail_abort(result) @conn.class.process_result_add_del_on_list(result) end
ruby
{ "resource": "" }
q10086
Scalaroid.TransactionSingleOp.add_on_nr
train
def add_on_nr(key, to_add) result = @conn.call(:add_on_nr, [key, to_add]) @conn.class.check_fail_abort(result) @conn.class.process_result_add_on_nr(result) end
ruby
{ "resource": "" }
q10087
Psc.Connection.has_superclass?
train
def has_superclass?(child, ancestor) if child.superclass == ancestor true elsif child.superclass.nil? false else has_superclass?(child.superclass, ancestor) end end
ruby
{ "resource": "" }
q10088
EndiFeed.News.process_news
train
def process_news(total = 25) items.map.with_index do |item, num| @headlines << format_headline(item, num) if total_met?(total) end.compact || nil end
ruby
{ "resource": "" }
q10089
Cul.LDAP.find_by_uni
train
def find_by_uni(uni) entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("uid", uni)) (entries.count == 1) ? entries.first : nil end
ruby
{ "resource": "" }
q10090
Cul.LDAP.find_by_name
train
def find_by_name(name) if name.include?(',') name = name.split(',').map(&:strip).reverse.join(" ") end entries = search(base: "ou=People,o=Columbia University, c=US", filter: Net::LDAP::Filter.eq("cn", name)) (entries.count == 1) ? entries.first : nil end
ruby
{ "resource": "" }
q10091
Glass.Client.rest_action
train
def rest_action(options, action="insert") body_object = json_content(options, action) inserting_content = { api_method: mirror_api.timeline.send(action), body_object: body_object} end
ruby
{ "resource": "" }
q10092
Glass.Client.list
train
def list(opts={as_hash: true}) page_token = nil parameters = {} self.timeline_list = [] begin parameters = {} parameters['pageToken'] = page_token if page_token.present? api_result = google_client.execute(api_method: mirror_api.timeline.list, ...
ruby
{ "resource": "" }
q10093
Handlebarer.Serialize.to_hbs
train
def to_hbs h = {:model => self.class.name.downcase} self.hbs_attributes.each do |attr| h[attr] = self.send(attr) ans = h[attr].class.ancestors if h[attr].class.respond_to?(:hbs_serializable) || ans.include?(Enumerable) || ans.include?(ActiveModel::Validations) h[attr] = h[...
ruby
{ "resource": "" }
q10094
Handlebarer.Serialize.hbs_attributes
train
def hbs_attributes s = self.class.class_variable_get(:@@serialize) if s[:merge] attrs = s[:attrs] + self.attributes.keys else attrs = s[:attrs] end attrs.collect{|attr| attr.to_sym}.uniq end
ruby
{ "resource": "" }
q10095
HashThatTree.CompareMD5.validate
train
def validate if(folder1==nil) || (folder1=="") || !Dir.exists?(folder1) puts "a valid folder path is required as argument 1" exit end if(folder2==nil) || (folder2=="") || !Dir.exists?(folder2) puts "a valid folder path is required as argument 2" exit end end
ruby
{ "resource": "" }
q10096
HashThatTree.CompareMD5.display_results_html
train
def display_results_html output ="<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>" output.concat("<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>") @filehash.each{ |key, value| ...
ruby
{ "resource": "" }
q10097
Analects.Encoding.ratings
train
def ratings(str) all_valid_cjk(str).map do |enc| [ enc, recode(enc, str).codepoints.map do |point| Analects::Models::Zi.codepoint_ranges.map.with_index do |range, idx| next 6 - idx if range.include?(point) 0 end.inject(:+) e...
ruby
{ "resource": "" }
q10098
ProjectEulerCli.Scraper.lookup_totals
train
def lookup_totals begin Timeout.timeout(4) do html = open("https://projecteuler.net/recent") fragment = Nokogiri::HTML(html) id_col = fragment.css('#problems_table td.id_column') # The newest problem is the first one listed on the recent page. The ID # of this proble...
ruby
{ "resource": "" }
q10099
ProjectEulerCli.Scraper.load_recent
train
def load_recent return if Page.visited.include?(0) html = open("https://projecteuler.net/recent") fragment = Nokogiri::HTML(html) problem_links = fragment.css('#problems_table td a') i = Problem.total problem_links.each do |link| Problem[i].title = link.text i -= 1 end Pa...
ruby
{ "resource": "" }