_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10200
Bixby.CommandSpec.manifest
train
def manifest if File.exists?(manifest_file) && File.readable?(manifest_file) then MultiJson.load(File.read(manifest_file)) else {} end end
ruby
{ "resource": "" }
q10201
Bixby.CommandSpec.to_s
train
def to_s # :nocov: s = [] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + (self.env.nil?() ? "" : MultiJson.dump(self.env)) s << " stdin: " + Debug.pretty_str(stdin) s.join("\n") end
ruby
{ "resource": "" }
q10202
LatoBlog.Category.check_category_father_circular_dependency
train
def check_category_father_circular_dependency return unless self.lato_blog_category_id all_children = self.get_all_category_children same_children = all_children.select { |child| child.id === self.lato_blog_category_id } if same_children.length > 0 errors.add('Category father', 'can not be a children of the category') throw :abort end end
ruby
{ "resource": "" }
q10203
LatoBlog.Category.check_lato_blog_category_parent
train
def check_lato_blog_category_parent category_parent = LatoBlog::CategoryParent.find_by(id: lato_blog_category_parent_id) if !category_parent errors.add('Category parent', 'not exist for the category') throw :abort return end same_language_category = category_parent.categories.find_by(meta_language: meta_language) if same_language_category && same_language_category.id != id errors.add('Category parent', 'has another category for the same language') throw :abort return end end
ruby
{ "resource": "" }
q10204
NSIVideoGranulate.FakeServerManager.start_server
train
def start_server(port=9886) @thread = Thread.new do Server.prepare Server.run! :port => port end sleep(1) self end
ruby
{ "resource": "" }
q10205
SycLink.Importer.links
train
def links rows.map do |row| attributes = Link::ATTRS.dup - [:url] Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }]) end end
ruby
{ "resource": "" }
q10206
Machined.Server.to_app
train
def to_app # :nodoc: Rack::Builder.new.tap do |app| app.use Middleware::Static, machined.output_path app.use Middleware::RootIndex app.run Rack::URLMap.new(sprockets_map) end end
ruby
{ "resource": "" }
q10207
Checkdin.TwitterHashtagStreams.twitter_hashtag_streams
train
def twitter_hashtag_streams(campaign_id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q10208
Checkdin.TwitterHashtagStreams.twitter_hashtag_stream
train
def twitter_hashtag_stream(campaign_id, id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}", options end return_error_or_body(response) end
ruby
{ "resource": "" }
q10209
RailsLegacyMapper.Mapper.root
train
def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end
ruby
{ "resource": "" }
q10210
LatoBlog.Back::CategoriesController.index
train
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end
ruby
{ "resource": "" }
q10211
LatoBlog.Back::CategoriesController.new
train
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end
ruby
{ "resource": "" }
q10212
LatoBlog.Back::CategoriesController.create
train
def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end
ruby
{ "resource": "" }
q10213
LatoBlog.Back::CategoriesController.edit
train
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end
ruby
{ "resource": "" }
q10214
LatoBlog.Back::CategoriesController.update
train
def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end
ruby
{ "resource": "" }
q10215
LatoBlog.Back::CategoriesController.destroy
train
def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
ruby
{ "resource": "" }
q10216
Pump.Encoder.encode
train
def encode(object, options={}) object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation) fields_to_hash(options) if object.is_a?(Array) if options[:fields] encode_partial_array(object, options) else encode_array(object, options) end elsif options[:fields] encode_partial_single(object, options) else encode_single(object, options) end end
ruby
{ "resource": "" }
q10217
NetworkExecutive.ChannelSchedule.extend_off_air
train
def extend_off_air( programs, program, stop ) prev = programs.pop + program program = prev.program occurrence = prev.occurrence remainder = time_left( occurrence.start_time, occurrence.end_time, stop ) [ program, occurrence, remainder ] end
ruby
{ "resource": "" }
q10218
Reaction.Client::Signer.outgoing
train
def outgoing(message, callback) # Allow non-data messages to pass through. return callback.call(message) if %r{^/meta/} =~ message['channel'] message['ext'] ||= {} signature = OpenSSL::HMAC.digest('sha256', @key, message['data']) message['ext']['signature'] = Base64.encode64(signature) return callback.call(message) end
ruby
{ "resource": "" }
q10219
PutText.Extractor.extract
train
def extract(path) files = files_in_path(path) supported_files = filter_files(files) parse_files(supported_files) end
ruby
{ "resource": "" }
q10220
Whowas.Validatable.validate
train
def validate(input) (check_exists(required_inputs, input) && check_format(input_formats, input)) || (raise Errors::InvalidInput, "Invalid input for #{self.class.name}") end
ruby
{ "resource": "" }
q10221
Whowas.Validatable.check_exists
train
def check_exists(required, input) required.inject(true) do |result, key| input[key] && result end end
ruby
{ "resource": "" }
q10222
MachineConfigure.Exporter.get_files
train
def get_files return @dir.values.map do |dir| next get_files_recursively_from dir end .reject { |x| !x } .flatten end
ruby
{ "resource": "" }
q10223
Kanade.Engine.deserialize_object
train
def deserialize_object(definition, hash) return nil if hash.nil? result = definition.new result.__fields.each do |field| name = field.key_json || name_to_json(field.sym) if field.options[:as] == :list value = deserialize_list(hash[name], field) elsif field.options[:as] == :dto value = deserialize_object(field.options[:of], hash[name]) else value = hash[name] end next if value.nil? result.send("#{field.key_ruby}=", value) end result end
ruby
{ "resource": "" }
q10224
CohortScope.BigCohort.reduce!
train
def reduce! @reduced_characteristics = if @reduced_characteristics.keys.length < 2 {} else most_restrictive_characteristic = @reduced_characteristics.keys.max_by do |key| conditions = CohortScope.conditions_for @reduced_characteristics.except(key) @active_record_relation.where(conditions).count end @reduced_characteristics.except most_restrictive_characteristic end end
ruby
{ "resource": "" }
q10225
Aptly.Snapshot.pull
train
def pull name, source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true if packages.length == 0 raise AptlyError.new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if !deps cmd += ' -no-remove' if !remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if !packages.empty? packages.each {|p| cmd += " #{p.quote}"} end Aptly::runcmd cmd Aptly::Snapshot.new dest end
ruby
{ "resource": "" }
q10226
Aptly.Snapshot.pull_from
train
def pull_from source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true pull @name, source, dest, :packages => packages, :deps => deps, :remove => remove end
ruby
{ "resource": "" }
q10227
Derelict.Parser::Status.exists?
train
def exists?(vm_name = nil) return (vm_names.count > 0) if vm_name.nil? vm_names.include? vm_name.to_sym end
ruby
{ "resource": "" }
q10228
Derelict.Parser::Status.state
train
def state(vm_name) unless states.include? vm_name.to_sym raise Derelict::VirtualMachine::NotFound.new vm_name end states[vm_name.to_sym] end
ruby
{ "resource": "" }
q10229
Derelict.Parser::Status.vm_lines
train
def vm_lines output.match(PARSE_LIST_FROM_OUTPUT).tap {|list| logger.debug "Parsing VM list from output using #{description}" raise InvalidFormat.new "Couldn't find VM list" if list.nil? }.captures[0].lines end
ruby
{ "resource": "" }
q10230
Mongolicious.DB.get_opts
train
def get_opts(db_uri) uri = URI.parse(db_uri) { :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password, :db => uri.path.gsub('/', '') } end
ruby
{ "resource": "" }
q10231
Mongolicious.DB.dump
train
def dump(db, path) Mongolicious.logger.info("Dumping database #{db[:db]}") cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless (db[:user].nil? || db[:user].empty?) cmd << " > /dev/null" system(cmd) raise "Error while backuing up #{db[:db]}" if $?.to_i != 0 end
ruby
{ "resource": "" }
q10232
WSOC.Runner.run
train
def run(*args) optparse(*args) options = { :env => :production, :host => @host, :port => @port } options.merge!(:server => @handler) if @handler App.run!(options) end
ruby
{ "resource": "" }
q10233
Biju.Modem.messages
train
def messages(which = "ALL") # read message from all storage in the mobile phone (sim+mem) cmd('AT+CPMS="MT"') # get message list sms = cmd('AT+CMGL="%s"' % which ) # collect messages msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) return nil unless msgs msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } end
ruby
{ "resource": "" }
q10234
GmailMailer.Mailer.send_smtp
train
def send_smtp(mail) smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT) smtp.enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY, :consumer_secret => SMTP_CONSUMER_SECRET, :token => @email_credentials[:smtp_oauth_token], :token_secret => @email_credentials[:smtp_oauth_token_secret] } smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session| print "Sending message..." session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations) puts ".sent!" end end
ruby
{ "resource": "" }
q10235
Mango.Application.render_404_public_file!
train
def render_404_public_file!(file_name) four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir) return unless File.file?(four_oh_four_path) send_file four_oh_four_path, status: 404 end
ruby
{ "resource": "" }
q10236
Mango.Application.render_404_template!
train
def render_404_template!(template_name) VIEW_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.views, template_name, engine) do |file| next unless File.file?(file) halt send(extension, template_name.to_sym, layout: false) end end end
ruby
{ "resource": "" }
q10237
Mango.Application.render_javascript_template!
train
def render_javascript_template!(uri_path) javascript_match = File.join(settings.javascripts, "*") javascript_path = File.expand_path(uri_path, settings.javascripts) return unless File.fnmatch(javascript_match, javascript_path) JAVASCRIPT_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.javascripts, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.javascripts) end end end
ruby
{ "resource": "" }
q10238
Mango.Application.render_stylesheet_template!
train
def render_stylesheet_template!(uri_path) stylesheet_match = File.join(settings.stylesheets, "*") stylesheet_path = File.expand_path(uri_path, settings.stylesheets) return unless File.fnmatch(stylesheet_match, stylesheet_path) STYLESHEET_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.stylesheets, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.stylesheets) end end end
ruby
{ "resource": "" }
q10239
Mango.Application.render_index_file!
train
def render_index_file!(uri_path) return unless URI.directory?(uri_path) index_match = File.join(settings.public_dir, "*") index_file_path = File.expand_path(uri_path + "index.html", settings.public_dir) return unless File.fnmatch(index_match, index_file_path) return unless File.file?(index_file_path) send_file index_file_path end
ruby
{ "resource": "" }
q10240
Mango.Application.render_content_page!
train
def render_content_page!(uri_path) uri_path += "index" if URI.directory?(uri_path) content_match = File.join(settings.content, "*") content_page_path = File.expand_path(uri_path, settings.content) return unless File.fnmatch(content_match, content_page_path) begin content_page = find_content_page(uri_path) rescue ContentPageNotFound return end view_template_path = File.expand_path(content_page.view, settings.views) begin engine = VIEW_TEMPLATE_ENGINES.fetch(Tilt[content_page.view]) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound, message end begin halt send(engine, content_page.view.to_s.templatize, locals: { page: content_page }) rescue Errno::ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound, message end end
ruby
{ "resource": "" }
q10241
Mango.Application.find_content_page
train
def find_content_page(uri_path) ContentPage::TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.content, uri_path, engine) do |file| next unless File.file?(file) return ContentPage.new(data: File.read(file), engine: engine) end end raise ContentPageNotFound, "Cannot find content page for path -- #{uri_path}" end
ruby
{ "resource": "" }
q10242
EstoreConventions.ClassMethods.factory_build_for_store
train
def factory_build_for_store(atts_hash, identifier_conditions = {}, full_data_object={}, &blk) if identifier_conditions.empty? record = self.new else record = self.where(identifier_conditions).first_or_initialize end record.assign_attributes(atts_hash, :without_protection => true) if block_given? yield record, full_data_object end return record end
ruby
{ "resource": "" }
q10243
Rexport.TreeNode.add_child
train
def add_child(*names) names.flatten! return unless name = names.shift node = children.find { |c| c.name == name } node ? node.add_child(names) : (children << TreeNode.new(name, names)) end
ruby
{ "resource": "" }
q10244
Bookmarks.Document.parse_a_bookmark
train
def parse_a_bookmark line line = line.strip if line =~ /^<DT><H3/ @h3_tags << h3_tags(line) elsif line =~ /^<\/DL>/ @h3_tags.pop elsif line =~ /<DT><A HREF="http/ @bookmarks << NetscapeBookmark.from_string(line) if (not @h3_tags.empty?) && (not @bookmarks.last.nil?) @bookmarks.last.add_tags @h3_tags end elsif line =~ /^<DD>/ @bookmarks.last.description = line[4..-1].chomp end end
ruby
{ "resource": "" }
q10245
Atlas.BoxVersion.save
train
def save # rubocop:disable Metrics/AbcSize body = { version: to_hash } # providers are saved seperately body[:version].delete(:providers) begin response = Atlas.client.put(url_builder.box_version_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_url}/versions", body: body) end # trigger the same on the providers providers.each(&:save) if providers update_with_response(response, [:providers]) end
ruby
{ "resource": "" }
q10246
EnchantedQuill.Label.textRectForBounds
train
def textRectForBounds(bounds, limitedToNumberOfLines: num_of_lines) required_rect = rect_fitting_text_for_container_size(bounds.size, for_number_of_line: num_of_lines) text_container.size = required_rect.size required_rect end
ruby
{ "resource": "" }
q10247
EnchantedQuill.Label.add_link_attribute
train
def add_link_attribute(mut_attr_string) range_pointer = Pointer.new(NSRange.type) attributes = mut_attr_string.attributesAtIndex(0, effectiveRange: range_pointer).dup attributes[NSFontAttributeName] = self.font attributes[NSForegroundColorAttributeName] = self.textColor mut_attr_string.addAttributes(attributes, range: range_pointer[0]) active_elements.each do |type, elements| case type when :mention then attributes[NSForegroundColorAttributeName] = mention_color when :hashtag then attributes[NSForegroundColorAttributeName] = hashtag_color when :url then attributes[NSForegroundColorAttributeName] = url_color when :category then attributes[NSForegroundColorAttributeName] = category_color end elements.each do |element| mut_attr_string.setAttributes(attributes, range: element.range) end end end
ruby
{ "resource": "" }
q10248
ShellTastic.Utils.empty_nil_blank?
train
def empty_nil_blank?(str, raize=false) result = (str !~ /[^[:space:]]/ || str.nil? || str.empty?) raise ShellTastic::CommandException.new("Command is emtpy or nil") if result and raize result end
ruby
{ "resource": "" }
q10249
Nadb.Tool.load_config
train
def load_config path = ENV['HOME'] + '/.nadb.config' if !File.exists?(path) return end @config = JSON.parse(File.read(path)) end
ruby
{ "resource": "" }
q10250
Nadb.Tool.run_adb_command
train
def run_adb_command(command, device = nil) full_command = construct_adb_command command, device puts full_command pio = IO.popen(full_command, 'w') Process.wait(pio.pid) end
ruby
{ "resource": "" }
q10251
Nadb.Tool.get_connected_devices
train
def get_connected_devices get_adb_command_output('devices') .drop(1) .map { |line| line.split[0] } .reject { |d| d.nil? || d.empty? } end
ruby
{ "resource": "" }
q10252
Jekyll.FridgeFilters.fridge_asset
train
def fridge_asset(input) return input unless input if input.respond_to?('first') input = input.first['name'] end site = @context.registers[:site] asset_dir = site.config['fridge'].config['asset_dir'] dest_path = File.join(site.dest, asset_dir, input) path = File.join(asset_dir, input) # Check if file already exists if site.keep_files.index(path) != nil return "/#{path}" end asset = site.config['fridge'].client.get("content/upload/#{input}") return input unless asset # play for keeps # this is so jekyll won't clean up the file site.keep_files << path # write file to destination FileUtils.mkdir_p(File.dirname(dest_path)) File.write(dest_path, asset) "/#{path}" end
ruby
{ "resource": "" }
q10253
Git.Trifle.cover
train
def cover(path, options={}) reset = options.delete :reset cook_layer do @dressing << Proc.new { self.reset if commits.any? } if reset Git::Base.open path if can_cover? path end end
ruby
{ "resource": "" }
q10254
ActiveCopy.Finders.matches?
train
def matches? query query.reduce(true) do |matches, (key, value)| matches = if key == 'tag' return false unless tags.present? tags.include? value else attributes[key] == value end end end
ruby
{ "resource": "" }
q10255
RailsKvsDriver.ValidationDriverConfig.validate_driver_config!
train
def validate_driver_config!(driver_config) raise_argument_error!(:host) unless driver_config.has_key? :host raise_argument_error!(:port) unless driver_config.has_key? :port raise_argument_error!(:namespace) unless driver_config.has_key? :namespace raise_argument_error!(:timeout_sec) unless driver_config.has_key? :timeout_sec raise_argument_error!(:pool_size) unless driver_config.has_key? :pool_size driver_config[:config_key] = :none unless driver_config.has_key? :config_key return driver_config end
ruby
{ "resource": "" }
q10256
Hometown.CreationTracer.update_on_instance_created
train
def update_on_instance_created(clazz, on_instance_created) return unless on_instance_created clazz.instance_eval do def instance_hooks hooks = (self.ancestors + [self]).map do |target| target.instance_variable_get(:@instance_hooks) end hooks.flatten! hooks.compact! hooks.uniq! hooks end @instance_hooks ||= [] @instance_hooks << on_instance_created end end
ruby
{ "resource": "" }
q10257
Serket.FieldEncrypter.encrypt
train
def encrypt(field) return if field !~ /\S/ aes = OpenSSL::Cipher.new(symmetric_algorithm) aes_key = aes.random_key iv = aes.random_iv encrypt_data(iv, aes_key, field.force_encoding(encoding)) end
ruby
{ "resource": "" }
q10258
Serket.FieldEncrypter.parse
train
def parse(iv, encrypted_key, encrypted_text) case @format when :delimited [iv, field_delimiter, encrypted_key, field_delimiter, encrypted_text].join('') when :json hash = {} hash['iv'] = iv hash['key'] = encrypted_key hash['message'] = encrypted_text hash.to_json end end
ruby
{ "resource": "" }
q10259
Cfror.Data.save_cfror_fields
train
def save_cfror_fields(fields) fields.each do |field, value| field = Cfror::Field.find(field) field.save_value!(self, value) end end
ruby
{ "resource": "" }
q10260
Cfror.Data.value_fields_for
train
def value_fields_for(source, order=nil) fields = self.send(source).fields fields = fields.order(order) if order fields.each do |i| i.set_value_for(self) end fields end
ruby
{ "resource": "" }
q10261
Kawaii.FormatHandler.method_missing
train
def method_missing(meth, *_args, &block) format = FormatRegistry.formats[meth] return unless format && format.match?(@route_handler.request) @candidates << format @blocks[meth] = block end
ruby
{ "resource": "" }
q10262
Kawaii.JsonFormat.parse_params
train
def parse_params(request) json = request.body.read JSON.parse(json).symbolize_keys if json.is_a?(String) && !json.empty? end
ruby
{ "resource": "" }
q10263
Kawaii.JsonFormat.encode
train
def encode(response) json = response.to_json [200, { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => json.length.to_s }, [json]] end
ruby
{ "resource": "" }
q10264
Closync.Sync.upload!
train
def upload!(local_file) @remote.directory.files.create( key: local_file.key, body: local_file.body, cache_control: "public, max-age=#{max_age(local_file)}", public: true ) end
ruby
{ "resource": "" }
q10265
ADAM6050.Password.obfuscate
train
def obfuscate(plain) codepoints = plain.codepoints raise FormatError if codepoints.length > 8 password = Array.new(8, 0x0E) codepoints.each_with_index do |c, i| password[i] = (c & 0x40) | (~c & 0x3F) end password.pack 'c*' end
ruby
{ "resource": "" }
q10266
ActiveRecord.Base.to_yaml
train
def to_yaml(opts = {}) #:nodoc: if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? super else coder = {} encode_with(coder) YAML.quick_emit(self, opts) do |out| out.map(taguri, to_yaml_style) do |map| coder.each { |k, v| map.add(k, v) } end end end end
ruby
{ "resource": "" }
q10267
CodeNode.SexpWalker.walk
train
def walk(s = nil) s ||= @root if [:module, :class].member?(s[0]) add_node s elsif find_relations? && s[0] == :call && s.length >= 4 && [:extend, :include].member?(s[2]) && !@graph.scope.empty? add_relation s else walk_siblings s.slice(1..-1) end end
ruby
{ "resource": "" }
q10268
AQL.Buffer.delimited
train
def delimited(nodes, delimiter = ', ') max = nodes.length - 1 nodes.each_with_index do |element, index| element.visit(self) append(delimiter) if index < max end self end
ruby
{ "resource": "" }
q10269
OandaRubyClient.ExchangeRatesClient.rates
train
def rates(rates_request) rates_uri = "#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}" rates_response = HTTParty.get(rates_uri, headers: oanda_headers) handle_response(rates_response.response) OpenStruct.new(rates_response.parsed_response) end
ruby
{ "resource": "" }
q10270
OandaRubyClient.ExchangeRatesClient.remaining_quotes
train
def remaining_quotes remaining_quotes_response = HTTParty.get("#{oanda_endpoint}#{REMAINING_QUOTES_PATH}", headers: oanda_headers) handle_response(remaining_quotes_response.response) remaining_quotes_response.parsed_response['remaining_quotes'] end
ruby
{ "resource": "" }
q10271
LegoNXT::LowLevel.Brick.reset_motor_position
train
def reset_motor_position port, set_relative transmit( DirectOps::NO_RESPONSE, DirectOps::RESETMOTORPOSITION, normalize_motor_port(port), normalize_boolean(set_relative) ) end
ruby
{ "resource": "" }
q10272
LegoNXT::LowLevel.Brick.run_motor
train
def run_motor port, power=100 raise ArgumentError.new("Power must be -100 through 100") if power < -100 || power > 100 transmit( DirectOps::NO_RESPONSE, DirectOps::SETOUTPUTSTATE, normalize_motor_port(port, true), sbyte(power), # power set point byte(1), # mode byte(0), # regulation mode sbyte(0), # turn ratio byte(0x20), # run state long(0), # tacho limit ) end
ruby
{ "resource": "" }
q10273
LegoNXT::LowLevel.Brick.transceive
train
def transceive *bits bitstring = bits.map(&:byte_string).join("") retval = connection.transceive bitstring # Check that it's a response bit. raise ::LegoNXT::BadResponseError unless retval[0] == "\x02" # Check that it's for this command. raise ::LegoNXT::BadResponseError unless retval[1] == bitstring[1] # Check that there is no error. # TODO: This should raise a specific error based on the status bit. raise ::LegoNXT::StatusError unless retval[2] == "\x00" return retval[3..-1] end
ruby
{ "resource": "" }
q10274
ActionView.Renderer.render_body
train
def render_body(context, options) if options.key?(:partial) [render_partial(context, options)] else StreamingTemplateRenderer.new(@lookup_context).render(context, options) end end
ruby
{ "resource": "" }
q10275
ActiveModel.AttributeMethods.attribute_missing
train
def attribute_missing(match, *args, &block) __send__(match.target, match.attr_name, *args, &block) end
ruby
{ "resource": "" }
q10276
ActiveModel.AttributeMethods.matched_attribute_method
train
def matched_attribute_method(method_name) matches = self.class.send(:attribute_method_matchers_matching, method_name) matches.detect { |match| attribute_method?(match.attr_name) } end
ruby
{ "resource": "" }
q10277
ActiveSupport.Inflector.demodulize
train
def demodulize(path) path = path.to_s if i = path.rindex("::") path[(i + 2)..-1] else path end end
ruby
{ "resource": "" }
q10278
ActiveSupport.Inflector.const_regexp
train
def const_regexp(camel_cased_word) parts = camel_cased_word.split("::") return Regexp.escape(camel_cased_word) if parts.blank? last = parts.pop parts.reverse.inject(last) do |acc, part| part.empty? ? acc : "#{part}(::#{acc})?" end end
ruby
{ "resource": "" }
q10279
ActiveSupport.Inflector.apply_inflections
train
def apply_inflections(word, rules, locale = :en) result = word.to_s.dup if word.empty? || inflections(locale).uncountables.uncountable?(result) result else rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result end end
ruby
{ "resource": "" }
q10280
ActiveSupport.Dependencies.autoload_module!
train
def autoload_module!(into, const_name, qualified_name, path_suffix) return nil unless base_path = autoloadable_module?(path_suffix) mod = Module.new into.const_set const_name, mod log("constant #{qualified_name} autoloaded (module autovivified from #{File.join(base_path, path_suffix)})") autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path) autoloaded_constants.uniq! mod end
ruby
{ "resource": "" }
q10281
ActiveSupport.XmlMini_REXML.parse
train
def parse(data) if !data.respond_to?(:read) data = StringIO.new(data || "") end if data.eof? {} else silence_warnings { require "rexml/document" } unless defined?(REXML::Document) doc = REXML::Document.new(data) if doc.root merge_element!({}, doc.root, XmlMini.depth) else raise REXML::ParseException, "The document #{doc.to_s.inspect} does not have a valid root" end end end
ruby
{ "resource": "" }
q10282
ActiveRecord.ConnectionHandling.connects_to
train
def connects_to(database: {}) connections = [] database.each do |role, database_key| config_hash = resolve_config_for_connection(database_key) handler = lookup_connection_handler(role.to_sym) connections << handler.establish_connection(config_hash) end connections end
ruby
{ "resource": "" }
q10283
ActiveRecord.ConnectionHandling.clear_query_caches_for_current_thread
train
def clear_query_caches_for_current_thread ActiveRecord::Base.connection_handlers.each_value do |handler| handler.connection_pool_list.each do |pool| pool.connection.clear_query_cache if pool.active_connection? end end end
ruby
{ "resource": "" }
q10284
ActiveRecord.SchemaDumper.formatted_version
train
def formatted_version stringified = @version.to_s return stringified unless stringified.length == 14 stringified.insert(4, "_").insert(7, "_").insert(10, "_") end
ruby
{ "resource": "" }
q10285
ActiveRecord.SchemaDumper.indexes
train
def indexes(table, stream) if (indexes = @connection.indexes(table)).any? add_index_statements = indexes.map do |index| table_name = remove_prefix_and_suffix(index.table).inspect " add_index #{([table_name] + index_parts(index)).join(', ')}" end stream.puts add_index_statements.sort.join("\n") stream.puts end end
ruby
{ "resource": "" }
q10286
ActiveSupport.TimeWithZone.formatted_offset
train
def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) end
ruby
{ "resource": "" }
q10287
ActiveSupport.TimeWithZone.advance
train
def advance(options) # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, # otherwise advance from #utc, for accuracy when moving across DST boundaries if options.values_at(:years, :weeks, :months, :days).any? method_missing(:advance, options) else utc.advance(options).in_time_zone(time_zone) end end
ruby
{ "resource": "" }
q10288
AbstractController.Base.process
train
def process(action, *args) @_action_name = action.to_s unless action_name = _find_action_name(@_action_name) raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}" end @_response_body = nil process_action(action_name, *args) end
ruby
{ "resource": "" }
q10289
ActiveSupport.ArrayInquirer.any?
train
def any?(*candidates) if candidates.none? super else candidates.any? do |candidate| include?(candidate.to_sym) || include?(candidate.to_s) end end end
ruby
{ "resource": "" }
q10290
ActiveRecord.Integration.cache_key
train
def cache_key if new_record? "#{model_name.cache_key}/new" else if cache_version "#{model_name.cache_key}/#{id}" else timestamp = max_updated_column_timestamp if timestamp timestamp = timestamp.utc.to_s(cache_timestamp_format) "#{model_name.cache_key}/#{id}-#{timestamp}" else "#{model_name.cache_key}/#{id}" end end end end
ruby
{ "resource": "" }
q10291
ActionMailer.MailHelper.format_paragraph
train
def format_paragraph(text, len = 72, indent = 2) sentences = [[]] text.split.each do |word| if sentences.first.present? && (sentences.last + [word]).join(" ").length > len sentences << [word] else sentences.last << word end end indentation = " " * indent sentences.map! { |sentence| "#{indentation}#{sentence.join(' ')}" }.join "\n" end
ruby
{ "resource": "" }
q10292
ActiveRecord.Batches.find_in_batches
train
def find_in_batches(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil) relation = self unless block_given? return to_enum(:find_in_batches, start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore) do total = apply_limits(relation, start, finish).size (total - 1).div(batch_size) + 1 end end in_batches(of: batch_size, start: start, finish: finish, load: true, error_on_ignore: error_on_ignore) do |batch| yield batch.to_a end end
ruby
{ "resource": "" }
q10293
ActiveModel.Error.match?
train
def match?(attribute, type = nil, **options) if @attribute != attribute || (type && @type != type) return false end options.each do |key, value| if @options[key] != value return false end end true end
ruby
{ "resource": "" }
q10294
ActionView.CollectionCaching.fetch_or_cache_partial
train
def fetch_or_cache_partial(cached_partials, template, order_by:) order_by.each_with_object({}) do |cache_key, hash| hash[cache_key] = if content = cached_partials[cache_key] build_rendered_template(content, template) else yield.tap do |rendered_partial| collection_cache.write(cache_key, rendered_partial.body) end end end end
ruby
{ "resource": "" }
q10295
ActiveSupport.Callbacks.run_callbacks
train
def run_callbacks(kind) callbacks = __callbacks[kind.to_sym] if callbacks.empty? yield if block_given? else env = Filters::Environment.new(self, false, nil) next_sequence = callbacks.compile invoke_sequence = Proc.new do skipped = nil while true current = next_sequence current.invoke_before(env) if current.final? env.value = !env.halted && (!block_given? || yield) elsif current.skip?(env) (skipped ||= []) << current next_sequence = next_sequence.nested next else next_sequence = next_sequence.nested begin target, block, method, *arguments = current.expand_call_template(env, invoke_sequence) target.send(method, *arguments, &block) ensure next_sequence = current end end current.invoke_after(env) skipped.pop.invoke_after(env) while skipped && skipped.first break env.value end end # Common case: no 'around' callbacks defined if next_sequence.final? next_sequence.invoke_before(env) env.value = !env.halted && (!block_given? || yield) next_sequence.invoke_after(env) env.value else invoke_sequence.call end end end
ruby
{ "resource": "" }
q10296
Rails.SourceAnnotationExtractor.extract_annotations_from
train
def extract_annotations_from(file, pattern) lineno = 0 result = File.readlines(file, encoding: Encoding::BINARY).inject([]) do |list, line| lineno += 1 next list unless line =~ pattern list << Annotation.new(lineno, $1, $2) end result.empty? ? {} : { file => result } end
ruby
{ "resource": "" }
q10297
ActionController.ParamsWrapper._wrapper_enabled?
train
def _wrapper_enabled? return false unless request.has_content_type? ref = request.content_mime_type.ref _wrapper_formats.include?(ref) && _wrapper_key && !request.parameters.key?(_wrapper_key) end
ruby
{ "resource": "" }
q10298
Rails.ConsoleMethods.new_session
train
def new_session app = Rails.application session = ActionDispatch::Integration::Session.new(app) yield session if block_given? # This makes app.url_for and app.foo_path available in the console session.extend(app.routes.url_helpers) session.extend(app.routes.mounted_helpers) session end
ruby
{ "resource": "" }
q10299
Rails.ConsoleMethods.reload!
train
def reload!(print = true) puts "Reloading..." if print Rails.application.reloader.reload! true end
ruby
{ "resource": "" }