_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q7200
Clin::CommandMixin::Options.ClassMethods.list_option
train
def list_option(name, description, **config) add_option Clin::OptionList.new(name, description, **config) end
ruby
{ "resource": "" }
q7201
Clin::CommandMixin::Options.ClassMethods.list_flag_option
train
def list_flag_option(name, description, **config) add_option Clin::OptionList.new(name, description, **config.merge(argument: false)) end
ruby
{ "resource": "" }
q7202
Clin::CommandMixin::Options.ClassMethods.general_option
train
def general_option(option_cls, config = {}) option_cls = option_cls.constantize if option_cls.is_a? String @general_options[option_cls] = option_cls.new(config) end
ruby
{ "resource": "" }
q7203
Clin::CommandMixin::Options.ClassMethods.remove_general_option
train
def remove_general_option(option_cls) option_cls = option_cls.constantize if option_cls.is_a? String @general_options.delete(option_cls) end
ruby
{ "resource": "" }
q7204
Clin::CommandMixin::Options.ClassMethods.option_defaults
train
def option_defaults out = {} @specific_options.each do |option| option.load_default(out) end @general_options.each do |_cls, option| out.merge! option.class.option_defaults end out end
ruby
{ "resource": "" }
q7205
PhilipsHue.Bridge.add_all_lights
train
def add_all_lights all_lights = [] overview["lights"].each do |id, light| all_lights << add_light(id.to_i, light["name"]) end all_lights end
ruby
{ "resource": "" }
q7206
TableFor.Helper.table_for
train
def table_for(model_class, records, html = {}, &block) Table.new(self, model_class, records, html, block).render end
ruby
{ "resource": "" }
q7207
Jinx.Unique.uniquify_attributes
train
def uniquify_attributes(attributes) attributes.each do |ka| oldval = send(ka) next unless String === oldval newval = UniquifierCache.instance.get(self, oldval) set_property_value(ka, newval) logger.debug { "Reset #{qp} #{ka} from #{oldval} to unique value #{newval}." } end end
ruby
{ "resource": "" }
q7208
PureCDB.Writer.store
train
def store key,value # In an attempt to save memory, we pack the hash data we gather into # strings of BER compressed integers... h = hash(key) hi = (h % num_hashes) @hashes[hi] ||= "" header = build_header(key.length, value.length) @io.syswrite(header+key+value) size = header.size + key.size + value.size @hashes[hi] += [h,@pos].pack("ww") # BER compressed @pos += size end
ruby
{ "resource": "" }
q7209
ICO.Utils.png_to_sizes
train
def png_to_sizes(input_filename, sizes_array, output_dirname=nil, append_filenames=APPEND_FILE_FORMAT, force_overwrite=false, clear=true, force_clear=false) basename = File.basename(input_filename, '.*') output_dirname ||= File.join(File.expand_path(File.dirname(input_filename)), "#{basename}_sizes") # ensure dir exists FileUtils.mkdir_p(output_dirname) # ensure dir empty if clear filename_array = Dir.glob(File.join(output_dirname, '**/*')) unless force_clear # protect from destructive action raise "more than ICO format files in #{output_dirname}" if contains_other_than_ext?(filename_array, :ico) end FileUtils.rm_rf(filename_array) end # import base image img = ChunkyPNG::Image.from_file(input_filename) # resize sizes_array.each do |x,y| y ||= x img_attrs = {:x => x, :y => y} bn = basename + Kernel.sprintf(append_filenames, img_attrs) fn = File.join(output_dirname, "#{bn}.png") img_out = img.resample_nearest_neighbor(x, y) unless force_overwrite raise "File exists: #{fn}" if File.exist?(fn) end IO.write(fn, img_out) end return output_dirname end
ruby
{ "resource": "" }
q7210
Jinx.Hasher.qp
train
def qp qph = {} each { |k, v| qph[k.qp] = v.qp } qph.pp_s end
ruby
{ "resource": "" }
q7211
Cashboard.Base.update
train
def update options = self.class.merge_options() options.merge!({:body => self.to_xml}) response = self.class.put(self.href, options) begin self.class.check_status_code(response) rescue return false end return true end
ruby
{ "resource": "" }
q7212
Cashboard.Base.delete
train
def delete options = self.class.merge_options() response = self.class.delete(self.href, options) begin self.class.check_status_code(response) rescue return false end return true end
ruby
{ "resource": "" }
q7213
Cashboard.Base.to_xml
train
def to_xml(options={}) options[:indent] ||= 2 xml = options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) xml.instruct! unless options[:skip_instruct] obj_name = self.class.resource_name.singularize # Turn our OpenStruct attributes into a hash we can export to XML obj_attrs = self.marshal_dump xml.tag!(obj_name) do obj_attrs.each do |key,value| next if key.to_sym == :link # Don't feed back links to server case value when ::Hash value.to_xml( options.merge({ :root => key, :skip_instruct => true }) ) when ::Array value.to_xml( options.merge({ :root => key, :children => key.to_s.singularize, :skip_instruct => true }) ) else xml.tag!(key, value) end end end end
ruby
{ "resource": "" }
q7214
KeytechKit.ElementHandler.delete
train
def delete(element_key) parameter = { basic_auth: @auth } response = self.class.delete("/elements/#{element_key}", parameter) unless response.success? puts "Could not save element: #{response.headers['x-errordescription']}" end response end
ruby
{ "resource": "" }
q7215
KeytechKit.ElementHandler.notes
train
def notes(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/notes", parameter) if response.success? search_response_header = SearchResponseHeader.new(response) search_response_header.elementList end end
ruby
{ "resource": "" }
q7216
KeytechKit.ElementHandler.note_handler
train
def note_handler @_note_handler = NoteHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_note_handler.nil? @_note_handler end
ruby
{ "resource": "" }
q7217
KeytechKit.ElementHandler.file_handler
train
def file_handler @_element_file_handler = ElementFileHandler.new(keytechkit.base_url, keytechkit.username, keytechkit.password) if @_element_file_handler.nil? @_element_file_handler end
ruby
{ "resource": "" }
q7218
Quicky.ResultsHash.to_hash
train
def to_hash ret = {} self.each_pair do |k, v| ret[k] = v.to_hash() end ret end
ruby
{ "resource": "" }
q7219
Quicky.ResultsHash.merge!
train
def merge!(rh) rh.each_pair do |k, v| # v is a TimeCollector if self.has_key?(k) self[k].merge!(v) else self[k] = v end end end
ruby
{ "resource": "" }
q7220
ActiveSupport.Inflector.titleize
train
def titleize(word) # negative lookbehind doesn't work in Firefox / Safari # humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { |match| match.capitalize } humanized = humanize(underscore(word)) humanized.reverse.gsub(/[a-z](?!['’`])\b/) { |match| match.capitalize }.reverse end
ruby
{ "resource": "" }
q7221
FilterFactory.Filter.attributes
train
def attributes fields.each_with_object(HashWithIndifferentAccess.new) do |field, acc| acc[field.alias] = field.value end end
ruby
{ "resource": "" }
q7222
Roroacms.RoutingHelper.get_type_by_url
train
def get_type_by_url return 'P' if params[:slug].blank? # split the url up into segments segments = params[:slug].split('/') # general variables url = params[:slug] article_url = Setting.get('articles_slug') category_url = Setting.get('category_slug') tag_url = Setting.get('tag_slug') status = "(post_status = 'Published' AND post_date <= CURRENT_TIMESTAMP AND disabled = 'N')" # HACK: this needs to be optimised # is it a article post or a page post if segments[0] == article_url if !segments[1].blank? if segments[1] == category_url || segments[1] == tag_url # render a category or tag page return 'CT' elsif segments[1].match(/\A\+?\d+(?:\.\d+)?\Z/) # render the archive page return 'AR' else # otherwise render a single article page return 'A' end else # render the overall all the articles return 'C' end else # render a page return 'P' end end
ruby
{ "resource": "" }
q7223
Houston.Conversations.hear
train
def hear(message, params={}) raise ArgumentError, "`message` must respond to :channel" unless message.respond_to?(:channel) raise ArgumentError, "`message` must respond to :sender" unless message.respond_to?(:sender) listeners.hear(message).each do |match| event = Houston::Conversations::Event.new(match) if block_given? yield event, match.listener else match.listener.call_async event end # Invoke only one listener per message return true end false end
ruby
{ "resource": "" }
q7224
Mutagem.Mutex.execute
train
def execute(&block) result = false raise ArgumentError, "missing block" unless block_given? begin open(lockfile, 'w') do |f| # exclusive non-blocking lock result = lock(f, File::LOCK_EX | File::LOCK_NB) do |f| yield end end ensure # clean up but only if we have a positive result meaning we wrote the lockfile FileUtils.rm(lockfile) if (result && File.exists?(lockfile)) end result end
ruby
{ "resource": "" }
q7225
MovingsignApi.Command.to_bytes
train
def to_bytes # set defaults self.sender ||= :pc self.receiver ||= 1 bytes = [] bytes.concat [0x00] * 5 # start of command bytes.concat [0x01] # <SOH> bytes.concat self.sender.to_bytes # Sender Address bytes.concat self.receiver.to_bytes # Reciver Address bytes.concat [0x02] # <STX> bytes.concat string_to_ascii_bytes(command_code) # Command Code bytes.concat command_payload_bytes # command specific payload bytes.concat [0x03] # <ETX> bytes.concat generate_checksum_bytes(bytes[10..-1]) # Checksum bytes (4) bytes.concat [0x04] # <EOT> bytes end
ruby
{ "resource": "" }
q7226
FuturoCube.ResourceFile.records
train
def records if !@records @io.seek(44, IO::SEEK_SET) records = [] header.record_count.times do records << ResourceRecord.read(@io) end @records = records end @records end
ruby
{ "resource": "" }
q7227
FuturoCube.ResourceFile.data
train
def data(rec) @io.seek(rec.data_offset, IO::SEEK_SET) @io.read(rec.data_length) end
ruby
{ "resource": "" }
q7228
FuturoCube.ResourceFile.compute_checksum
train
def compute_checksum(&block) crc = CRC.new # Have to read this first because it might change the seek position. file_size = header.file_size @io.seek(8, IO::SEEK_SET) pos = 8 length = 4096-8 buf = nil while true buf = @io.read(length, buf) break if !buf crc.update(buf) pos += buf.size block.call(pos) if block length = 4096 end crc.crc end
ruby
{ "resource": "" }
q7229
Woro.Task.build_task_template
train
def build_task_template b = binding ERB.new(Woro::TaskHelper.read_template_file).result(b) end
ruby
{ "resource": "" }
q7230
BarkestCore.ApplicationControllerBase.authorize!
train
def authorize!(*group_list) begin # an authenticated user must exist. unless logged_in? store_location raise_not_logged_in "You need to login to access '#{request.fullpath}'.", 'nobody is logged in' end # clean up the group list. group_list ||= [] group_list.delete false group_list.delete '' if group_list.include?(true) # group_list contains "true" so only a system admin may continue. unless system_admin? if show_denial_reason? flash[:info] = 'The requested path is only available to system administrators.' end raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'.", 'requires system administrator' end log_authorize_success 'user is system admin' elsif group_list.blank? # group_list is empty or contained nothing but empty strings and boolean false. # everyone can continue. log_authorize_success 'only requires authenticated user' else # the group list contains one or more authorized groups. # we want them to all be uppercase strings. group_list = group_list.map{|v| v.to_s.upcase}.sort result = current_user.has_any_group?(*group_list) unless result message = group_list.join(', ') if show_denial_reason? flash[:info] = "The requested path requires one of these groups: #{message}" end raise_authorize_failure "You are not authorized to access '#{request.fullpath}'.", "requires one of: #{message}" end log_authorize_success "user has '#{result}' group" end rescue BarkestCore::AuthorizeFailure => err flash[:danger] = err.message redirect_to root_url and return false end true end
ruby
{ "resource": "" }
q7231
Higml.Applier.selector_matches?
train
def selector_matches?(selector) selector.any? do |group| group.keys.all? do |key| input_has_key?(key) && (@input[key] == group[key] || group[key].nil?) end end end
ruby
{ "resource": "" }
q7232
Encryptbot.Cert.ready_for_challenge
train
def ready_for_challenge(domain, dns_challenge) record = "#{dns_challenge.record_name}.#{domain}" challenge_value = dns_challenge.record_content txt_value = Resolv::DNS.open do |dns| records = dns.getresources(record, Resolv::DNS::Resource::IN::TXT); records.empty? ? nil : records.map(&:data).join(" ") end txt_value == challenge_value end
ruby
{ "resource": "" }
q7233
Kajiki.Handler.check_existing_pid
train
def check_existing_pid return false unless pid_file_exists? pid = read_pid fail 'Existing process found.' if pid > 0 && pid_exists?(pid) delete_pid end
ruby
{ "resource": "" }
q7234
Kajiki.Handler.trap_default_signals
train
def trap_default_signals Signal.trap('INT') do puts 'Interrupted. Terminating process...' exit end Signal.trap('HUP') do puts 'SIGHUP - Terminating process...' exit end Signal.trap('TERM') do puts 'SIGTERM - Terminating process...' exit end end
ruby
{ "resource": "" }
q7235
Snapshotify.Document.links
train
def links # Find all anchor elements doc.xpath('//a').map do |element| # extract all the href attributes element.attribute('href') end.compact.map(&:value).map do |href| # return them as new document objects Snapshotify::Document.new(href, url) end.compact end
ruby
{ "resource": "" }
q7236
Snapshotify.Document.write!
train
def write! writer = Snapshotify::Writer.new(self) writer.emitter = emitter writer.write end
ruby
{ "resource": "" }
q7237
SysCmd.Definition.option
train
def option(option, *args) options = args.pop if args.last.is_a?(Hash) options ||= {} raise "Invalid number of arguments (0 or 1 expected)" if args.size > 1 return unless @shell.applicable?(options) value = args.shift || options[:value] if options[:os_prefix] option = @shell.option_switch + option else option = option.dup end if @shell.requires_escaping?(option) option = @shell.escape_value(option) end option << ' ' << @shell.escape_value(value) if value option << @shell.escape_value(options[:join_value]) if options[:join_value] option << '=' << @shell.escape_value(options[:equal_value]) if options[:equal_value] if file = options[:file] file_sep = ' ' elsif file = options[:join_file] file_sep = '' elsif file = options[:equal_file] file_sep = '=' end if file option << file_sep << @shell.escape_filename(file) end @command << ' ' << option @last_arg = :option end
ruby
{ "resource": "" }
q7238
SysCmd.Definition.os_option
train
def os_option(option, *args) options = args.pop if args.last.is_a?(Hash) options ||= {} args.push options.merge(os_prefix: true) option option, *args end
ruby
{ "resource": "" }
q7239
SysCmd.Definition.argument
train
def argument(value, options = {}) return unless @shell.applicable?(options) value = value.to_s if @shell.requires_escaping?(value) value = @shell.escape_value(value) end @command << ' ' << value @last_arg = :argument end
ruby
{ "resource": "" }
q7240
SysCmd.Command.run
train
def run(options = {}) @output = @status = @error_output = @error = nil if options[:direct] command = @shell.split(@command) else command = [@command] end stdin_data = options[:stdin_data] || @input if stdin_data command << { stdin_data: stdin_data } end begin case options[:error_output] when :mix # mix stderr with stdout @output, @status = Open3.capture2e(*command) when :separate @output, @error_output, @status = Open3.capture3(*command) else # :console (do not capture stderr output) @output, @status = Open3.capture2(*command) end rescue => error @error = error.dup end case options[:return] when :status @status when :status_value status_value when :output @output when :error_output @error_output when :command self else @error ? nil : @status.success? ? true : false end end
ruby
{ "resource": "" }
q7241
Iparser.Machine.interactive_parser
train
def interactive_parser ( ) puts 'Press <Enter> to exit...' # Цикл обработки ввода. loop do str = interactive_input( ) break if str == "" # Цикл посимвольной классификаци. str.bytes.each do |c| parse( c.chr ) puts 'parser: ' + @parserstate puts 'symbol: ' + interactive_output( c.chr ).to_s puts 'state: ' + @chain.last.statename puts end end end
ruby
{ "resource": "" }
q7242
Attrtastic.SemanticAttributesBuilder.attributes
train
def attributes(*args, &block) options = args.extract_options! options[:html] ||= {} if args.first and args.first.is_a? String options[:name] = args.shift end if options[:for].blank? attributes_for(record, args, options, &block) else for_value = if options[:for].is_a? Symbol record.send(options[:for]) else options[:for] end [*for_value].map do |value| value_options = options.clone value_options[:html][:class] = [ options[:html][:class], value.class.to_s.underscore ].compact.join(" ") attributes_for(value, args, options, &block) end.join.html_safe end end
ruby
{ "resource": "" }
q7243
Attrtastic.SemanticAttributesBuilder.attribute
train
def attribute(*args, &block) options = args.extract_options! options.reverse_merge!(Attrtastic.default_options) options[:html] ||= {} method = args.shift html_label_class = [ "label", options[:html][:label_class] ].compact.join(" ") html_value_class = [ "value", options[:html][:value_class] ].compact.join(" ") html_class = [ "attribute", options[:html][:class] ].compact.join(" ") label = options.key?(:label) ? options[:label] : label_for_attribute(method) if block_given? output = template.tag(:li, {:class => html_class}, true) output << template.content_tag(:span, label, :class => html_label_class) output << template.tag(:span, {:class => html_value_class}, true) output << template.capture(&block) output.safe_concat("</span>") output.safe_concat("</li>") else value = if options.key?(:value) case options[:value] when Symbol attribute_value = value_of_attribute(method) case attribute_value when Hash attribute_value[options[:value]] else attribute_value.send(options[:value]) end else options[:value] end else value_of_attribute(method) end value = case options[:format] when false value when nil format_attribute_value(value) else format_attribute_value(value, options[:format]) end if value.present? || options[:display_empty] output = template.tag(:li, {:class => html_class}, true) output << template.content_tag(:span, label, :class => html_label_class) output << template.content_tag(:span, value, :class => html_value_class) output.safe_concat("</li>") end end end
ruby
{ "resource": "" }
q7244
Mongosteen.BaseHelpers.collection
train
def collection get_collection_ivar || begin chain = end_of_association_chain # scopes chain = apply_scopes(chain) # search if params[:search] chain = chain.search(params[:search].to_s.downcase, match: :all) end # pagination if params[:page] per_page = params[:perPage] || 20 chain = chain.page(params[:page]).per(per_page) else chain = chain.all end set_collection_ivar(chain) end end
ruby
{ "resource": "" }
q7245
Mongosteen.BaseHelpers.get_resource_version
train
def get_resource_version resource = get_resource_ivar version = params[:version].try(:to_i) if version && version > 0 && version < resource.version resource.undo(nil, from: version + 1, to: resource.version) resource.version = version end return resource end
ruby
{ "resource": "" }
q7246
KeyTree.Path.-
train
def -(other) other = other.to_key_path raise KeyError unless prefix?(other) super(other.length) end
ruby
{ "resource": "" }
q7247
KeyTree.Path.prefix?
train
def prefix?(other) other = other.to_key_path return false if other.length > length key_enum = each other.all? { |other_key| key_enum.next == other_key } end
ruby
{ "resource": "" }
q7248
StalkClimber.Climber.max_job_ids
train
def max_job_ids connection_pairs = connection_pool.connections.map do |connection| [connection, connection.max_job_id] end return Hash[connection_pairs] end
ruby
{ "resource": "" }
q7249
RoleAuth.Parser.task
train
def task(name, options = {}) options[:is] = options[:is].is_a?(Array) ? options[:is] : [options[:is]].compact @tasks[name] = Task.new(name,options) end
ruby
{ "resource": "" }
q7250
RoleAuth.Parser.add_permission
train
def add_permission(target, *args) raise '#can and #can_not have to be used inside a role block' unless @role options = args.last.is_a?(Hash) ? args.pop : {} tasks = [] models = [] models << args.pop if args.last == :any args.each {|arg| arg.is_a?(Symbol) ? tasks << arg : models << arg} tasks.each do |task| models.each do |model| if permission = target[task][model][@role] permission.load_options(options) else target[task][model][@role] = Permission.new(@role, task, model, options) end end end end
ruby
{ "resource": "" }
q7251
RoleAuth.Parser.process_tasks
train
def process_tasks @tasks.each_value do |task| task.options[:ancestors] = [] set_ancestor_tasks(task) set_alternative_tasks(task) if @permissions.key? task.name end end
ruby
{ "resource": "" }
q7252
RoleAuth.Parser.set_ancestor_tasks
train
def set_ancestor_tasks(task, ancestor = nil) task.options[:ancestors] += (ancestor || task).options[:is] (ancestor || task).options[:is].each do |parent_task| set_ancestor_tasks(task, @tasks[parent_task]) end end
ruby
{ "resource": "" }
q7253
RoleAuth.Parser.set_alternative_tasks
train
def set_alternative_tasks(task, ancestor = nil) (ancestor || task).options[:is].each do |task_name| if @permissions.key? task_name (@tasks[task_name].options[:alternatives] ||= []) << task.name else set_alternative_tasks(task, @tasks[task_name]) end end end
ruby
{ "resource": "" }
q7254
RoleAuth.Parser.set_descendant_roles
train
def set_descendant_roles(descendant_role, ancestor_role = nil) role = ancestor_role || descendant_role return unless role[:is] role[:is].each do |role_name| (@roles[role_name][:descendants] ||= []) << descendant_role[:name] set_descendant_roles(descendant_role, @roles[role_name]) end end
ruby
{ "resource": "" }
q7255
BetterRailsDebugger.GroupInstance.big_classes
train
def big_classes(max_size=1.megabytes) return @big_classes if @big_classes @big_classes = {} ObjectInformation.where(:group_instance_id => self.id, :memsize.gt => max_size).all.each do |object| @big_classes[object.class_name] ||= {total_mem: 0, average: 0, count: 0} @big_classes[object.class_name][:total_mem] += object.memsize @big_classes[object.class_name][:count] += 1 end @big_classes.each_pair do |klass, hash| @big_classes[klass][:average] = @big_classes[klass][:total_mem] / @big_classes[klass][:count] end @big_classes end
ruby
{ "resource": "" }
q7256
Roroacms.Admin::TermsController.categories
train
def categories # add breadcrumb and set title add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.categories.breadcrumb_title") set_title(I18n.t("generic.categories")) @type = 'category' @records = Term.term_cats('category', nil, true) # render view template as it is the same as the tag view render 'view' end
ruby
{ "resource": "" }
q7257
Roroacms.Admin::TermsController.create
train
def create @category = Term.new(term_params) redirect_url = Term.get_redirect_url(params) respond_to do |format| if @category.save @term_anatomy = @category.create_term_anatomy(:taxonomy => params[:type_taxonomy]) format.html { redirect_to URI.parse(redirect_url).path, only_path: true, notice: I18n.t("controllers.admin.terms.create.flash.success", term: Term.get_type_of_term(params)) } else flash[:error] = I18n.t("controllers.admin.terms.create.flash.error") format.html { redirect_to URI.parse(redirect_url).path, only_path: true } end end end
ruby
{ "resource": "" }
q7258
Roroacms.Admin::TermsController.update
train
def update @category = Term.find(params[:id]) @category.deal_with_cover(params[:has_cover_image]) respond_to do |format| # deal with abnormalaties - update the structure url if @category.update_attributes(term_params) format.html { redirect_to edit_admin_term_path(@category), notice: I18n.t("controllers.admin.terms.update.flash.success", term: Term.get_type_of_term(params)) } else format.html { render action: "edit" } end end end
ruby
{ "resource": "" }
q7259
Roroacms.Admin::TermsController.destroy
train
def destroy @term = Term.find(params[:id]) # return url will be different for either tag or category redirect_url = Term.get_redirect_url({ type_taxonomy: @term.term_anatomy.taxonomy }) @term.destroy respond_to do |format| format.html { redirect_to URI.parse(redirect_url).path, notice: I18n.t("controllers.admin.terms.destroy.flash.success") } end end
ruby
{ "resource": "" }
q7260
Roroacms.Admin::TermsController.edit_title
train
def edit_title if @category.term_anatomy.taxonomy == 'category' add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.edit_title.category.breadcrumb_title") add_breadcrumb I18n.t("controllers.admin.terms.edit_title.category.title") title = I18n.t("controllers.admin.terms.edit_title.category.title") else add_breadcrumb I18n.t("generic.tags"), :admin_article_tags_path, :title => I18n.t("controllers.admin.terms.edit_title.tag.breadcrumb_title") add_breadcrumb I18n.t("controllers.admin.terms.edit_title.tag.title") title = I18n.t("controllers.admin.terms.edit_title.tag.title") end return title end
ruby
{ "resource": "" }
q7261
YoreCore.Yore.upload
train
def upload(aFile) #ensure_bucket() logger.debug "Uploading #{aFile} to S3 bucket #{config[:bucket]} ..." logger.info "Uploading #{File.basename(aFile)} to S3 bucket #{config[:bucket]} ..." s3client.upload_backup(aFile,config[:bucket],File.basename(aFile)) end
ruby
{ "resource": "" }
q7262
YoreCore.Yore.decode_file_name
train
def decode_file_name(aFilename) prefix,date,ext = aFilename.scan(/(.*?)\-(.*?)\.(.*)/).flatten return Time.from_date_numeric(date) end
ruby
{ "resource": "" }
q7263
Fried::Schema::Attribute.DefineReader.call
train
def call(definition, klass) variable = definition.instance_variable klass.instance_eval do define_method(definition.reader) { instance_variable_get(variable) } end end
ruby
{ "resource": "" }
q7264
BarkestCore.MiscHelper.fixed
train
def fixed(value, places = 2) value = value.to_s.to_f unless value.is_a?(Float) sprintf("%0.#{places}f", value.round(places)) end
ruby
{ "resource": "" }
q7265
BarkestCore.MiscHelper.split_name
train
def split_name(name) name ||= '' if name.include?(',') last,first = name.split(',', 2) first,middle = first.to_s.strip.split(' ', 2) else first,middle,last = name.split(' ', 3) if middle && !last middle,last = last,middle end end [ first.to_s.strip, middle.to_s.strip, last.to_s.strip ] end
ruby
{ "resource": "" }
q7266
Pipio.BasicParser.parse
train
def parse if pre_parse messages = @file_reader.other_lines.map do |line| basic_message_match = @line_regex.match(line) meta_message_match = @line_regex_status.match(line) if basic_message_match create_message(basic_message_match) elsif meta_message_match create_status_or_event_message(meta_message_match) end end Chat.new(messages, @metadata) end end
ruby
{ "resource": "" }
q7267
Pipio.BasicParser.pre_parse
train
def pre_parse @file_reader.read metadata = Metadata.new(MetadataParser.new(@file_reader.first_line).parse) if metadata.valid? @metadata = metadata @alias_registry = AliasRegistry.new(@metadata.their_screen_name) @my_aliases.each do |my_alias| @alias_registry[my_alias] = @metadata.my_screen_name end end end
ruby
{ "resource": "" }
q7268
EventMachine.StatHat.time
train
def time(name, opts = {}) opts[:ez] ||= true start = Time.now yield if block_given? if opts[:ez] == true ez_value(name, (Time.now - start)) else value(name, (Time.now - start)) end end
ruby
{ "resource": "" }
q7269
Qipowl::Bowlers.Bowler.add_entity
train
def add_entity section, key, value, enclosure_value = null if (tags = self.class.const_get("#{section.upcase}_TAGS")) key = key.bowl.to_sym tags[key] = value.to_sym self.class.const_get("ENCLOSURES_TAGS")[key] = enclosure_value.to_sym if enclosure_value self.class.const_get("ENTITIES")[section.to_sym][key] = value.to_sym self.class.class_eval %Q{ alias_method :#{key}, :∀_#{section} } # unless self.class.instance_methods(true).include?(key.bowl) @shadows = nil else logger.warn "Trying to add key “#{key}” in an invalid section “#{section}”. Ignoring…" end end
ruby
{ "resource": "" }
q7270
Jinx.Property.restrict_flags
train
def restrict_flags(declarer, *flags) copy = restrict(declarer) copy.qualify(*flags) copy end
ruby
{ "resource": "" }
q7271
Jinx.Property.inverse=
train
def inverse=(attribute) return if inverse == attribute # if no attribute, then the clear the existing inverse, if any return clear_inverse if attribute.nil? # the inverse attribute meta-data begin @inv_prop = type.property(attribute) rescue NameError => e raise MetadataError.new("#{@declarer.qp}.#{self} inverse attribute #{type.qp}.#{attribute} not found") end # the inverse of the inverse inv_inv_prop = @inv_prop.inverse_property # If the inverse of the inverse is already set to a different attribute, then raise an exception. if inv_inv_prop and not (inv_inv_prop == self or inv_inv_prop.restriction?(self)) raise MetadataError.new("Cannot set #{type.qp}.#{attribute} inverse attribute to #{@declarer.qp}.#{self}@#{object_id} since it conflicts with existing inverse #{inv_inv_prop.declarer.qp}.#{inv_inv_prop}@#{inv_inv_prop.object_id}") end # Set the inverse of the inverse to this attribute. @inv_prop.inverse = @attribute # If this attribute is disjoint, then so is the inverse. @inv_prop.qualify(:disjoint) if disjoint? logger.debug { "Assigned #{@declarer.qp}.#{self} attribute inverse to #{type.qp}.#{attribute}." } end
ruby
{ "resource": "" }
q7272
Jinx.Property.owner_flag_set
train
def owner_flag_set if dependent? then raise MetadataError.new("#{declarer.qp}.#{self} cannot be set as a #{type.qp} owner since it is already defined as a #{type.qp} dependent") end inv_prop = inverse_property if inv_prop then inv_prop.qualify(:dependent) unless inv_prop.dependent? else inv_attr = type.dependent_attribute(@declarer) if inv_attr.nil? then raise MetadataError.new("The #{@declarer.qp} owner attribute #{self} of type #{type.qp} does not have an inverse") end logger.debug { "#{declarer.qp}.#{self} inverse is the #{type.qp} dependent attribute #{inv_attr}." } self.inverse = inv_attr end end
ruby
{ "resource": "" }
q7273
Truncus.Client.get_token
train
def get_token(url) req = Net::HTTP::Post.new('/', initheader = {'Content-Type' => 'application/json'}) req.body = {url: url, format: 'json'}.to_json res = @http.request(req) data = JSON::parse(res.body) data['trunct']['token'] end
ruby
{ "resource": "" }
q7274
Garcon.ThreadPoolExecutor.on_worker_exit
train
def on_worker_exit(worker) mutex.synchronize do @pool.delete(worker) if @pool.empty? && !running? stop_event.set stopped_event.set end end end
ruby
{ "resource": "" }
q7275
Garcon.ThreadPoolExecutor.execute
train
def execute(*args, &task) if ensure_capacity? @scheduled_task_count += 1 @queue << [args, task] else if @max_queue != 0 && @queue.length >= @max_queue handle_fallback(*args, &task) end end prune_pool end
ruby
{ "resource": "" }
q7276
Garcon.ThreadPoolExecutor.ensure_capacity?
train
def ensure_capacity? additional = 0 capacity = true if @pool.size < @min_length additional = @min_length - @pool.size elsif @queue.empty? && @queue.num_waiting >= 1 additional = 0 elsif @pool.size == 0 && @min_length == 0 additional = 1 elsif @pool.size < @max_length || @max_length == 0 additional = 1 elsif @max_queue == 0 || @queue.size < @max_queue additional = 0 else capacity = false end additional.times do @pool << create_worker_thread end if additional > 0 @largest_length = [@largest_length, @pool.length].max end capacity end
ruby
{ "resource": "" }
q7277
Garcon.ThreadPoolExecutor.prune_pool
train
def prune_pool if Garcon.monotonic_time - @gc_interval >= @last_gc_time @pool.delete_if { |worker| worker.dead? } # send :stop for each thread over idletime @pool.select { |worker| @idletime != 0 && Garcon.monotonic_time - @idletime > worker.last_activity }.each { @queue << :stop } @last_gc_time = Garcon.monotonic_time end end
ruby
{ "resource": "" }
q7278
Garcon.ThreadPoolExecutor.create_worker_thread
train
def create_worker_thread wrkr = ThreadPoolWorker.new(@queue, self) Thread.new(wrkr, self) do |worker, parent| Thread.current.abort_on_exception = false worker.run parent.on_worker_exit(worker) end return wrkr end
ruby
{ "resource": "" }
q7279
ComfyPress::Tag.InstanceMethods.render
train
def render ignore = [ComfyPress::Tag::Partial, ComfyPress::Tag::Helper].member?(self.class) ComfyPress::Tag.sanitize_irb(content, ignore) end
ruby
{ "resource": "" }
q7280
Jinx.Mergeable.merge_attributes
train
def merge_attributes(other, attributes=nil, matches=nil, &filter) return self if other.nil? or other.equal?(self) attributes = [attributes] if Symbol === attributes attributes ||= self.class.mergeable_attributes # If the source object is not a hash, then convert it to an attribute => value hash. vh = Hasher === other ? other : other.value_hash(attributes) # Merge the Java values hash. vh.each { |pa, value| merge_attribute(pa, value, matches, &filter) } self end
ruby
{ "resource": "" }
q7281
Layabout.SlackRequest.perform_webhook
train
def perform_webhook http_request.body = {'text' => params[:text]}.to_json.to_s http_request.query = {'token' => params[:token]} HTTPI.post(http_request) end
ruby
{ "resource": "" }
q7282
IRCSupport.Case.irc_upcase!
train
def irc_upcase!(irc_string, casemapping = :rfc1459) case casemapping when :ascii irc_string.tr!(*@@ascii_map) when :rfc1459 irc_string.tr!(*@@rfc1459_map) when :'strict-rfc1459' irc_string.tr!(*@@strict_rfc1459_map) else raise ArgumentError, "Unsupported casemapping #{casemapping}" end return irc_string end
ruby
{ "resource": "" }
q7283
IRCSupport.Case.irc_upcase
train
def irc_upcase(irc_string, casemapping = :rfc1459) result = irc_string.dup irc_upcase!(result, casemapping) return result end
ruby
{ "resource": "" }
q7284
IRCSupport.Case.irc_downcase!
train
def irc_downcase!(irc_string, casemapping = :rfc1459) case casemapping when :ascii irc_string.tr!(*@@ascii_map.reverse) when :rfc1459 irc_string.tr!(*@@rfc1459_map.reverse) when :'strict-rfc1459' irc_string.tr!(*@@strict_rfc1459_map.reverse) else raise ArgumentError, "Unsupported casemapping #{casemapping}" end return irc_string end
ruby
{ "resource": "" }
q7285
IRCSupport.Case.irc_downcase
train
def irc_downcase(irc_string, casemapping = :rfc1459) result = irc_string.dup irc_downcase!(result, casemapping) return result end
ruby
{ "resource": "" }
q7286
JsMessage.ControllerMethods.render_js_message
train
def render_js_message(type, hash = {}) unless [ :ok, :redirect, :error ].include?(type) raise "Invalid js_message response type: #{type}" end js_message = { :status => type, :html => nil, :message => nil, :to => nil }.merge(hash) render_options = {:json => js_message} render_options[:status] = 400 if type == :error render(render_options) end
ruby
{ "resource": "" }
q7287
Numerals.Format::BaseScaler.scaled_digit
train
def scaled_digit(group) unless group.size == @base_scale raise "Invalid digits group size for scaled_digit (is #{group.size}; should be #{@base_scale})" end v = 0 group.each do |digit| v *= @setter.base v += digit end v end
ruby
{ "resource": "" }
q7288
Numerals.Format::BaseScaler.grouped_digits
train
def grouped_digits(digits) unless (digits.size % @base_scale) == 0 raise "Invalid number of digits for group_digits (#{digits.size} is not a multiple of #{@base_scale})" end digits.each_slice(@base_scale).map{|group| scaled_digit(group)} end
ruby
{ "resource": "" }
q7289
NRSER.LazyAttr.call
train
def call target_method, receiver, *args, &block unless target_method.parameters.empty? raise NRSER::ArgumentError.new \ "{NRSER::LazyAttr} can only decorate methods with 0 params", receiver: receiver, target_method: target_method end unless args.empty? raise NRSER::ArgumentError.new \ "wrong number of arguments for", target_method, "(given", args.length, "expected 0)", receiver: receiver, target_method: target_method end unless block.nil? raise NRSER::ArgumentError.new \ "wrong number of arguments (given #{ args.length }, expected 0)", receiver: receiver, target_method: target_method end var_name = self.class.instance_var_name target_method unless receiver.instance_variable_defined? var_name receiver.instance_variable_set var_name, target_method.call end receiver.instance_variable_get var_name end
ruby
{ "resource": "" }
q7290
TableMe.Builder.column
train
def column name,options = {}, &block @columns << TableMe::Column.new(name,options, &block) @names << name end
ruby
{ "resource": "" }
q7291
Milenage.Kernel.op=
train
def op=(op) fail "OP must be 128 bits" unless op.each_byte.to_a.length == 16 @opc = xor(enc(op), op) end
ruby
{ "resource": "" }
q7292
Typhoeus.SpecCache.remove_unnecessary_cache_files!
train
def remove_unnecessary_cache_files! current_keys = cache_files.map do |file| get_cache_key_from_filename(file) end inmemory_keys = responses.keys unneeded_keys = current_keys - inmemory_keys unneeded_keys.each do |key| File.unlink(filepath_for(key)) end end
ruby
{ "resource": "" }
q7293
Typhoeus.SpecCache.read_cache_fixtures!
train
def read_cache_fixtures! files = cache_files files.each do |file| cache_key = get_cache_key_from_filename(file) responses[cache_key] = Marshal.load(File.read(file)) end end
ruby
{ "resource": "" }
q7294
Typhoeus.SpecCache.dump_cache_fixtures!
train
def dump_cache_fixtures! responses.each do |cache_key, response| path = filepath_for(cache_key) unless File.exist?(path) File.open(path, "wb") do |fp| fp.write(Marshal.dump(response)) end end end end
ruby
{ "resource": "" }
q7295
Roroacms.AdminRoroaHelper.get_theme_options
train
def get_theme_options hash = [] Dir.glob("#{Rails.root}/app/views/themes/*/") do |themes| opt = themes.split('/').last if File.exists?("#{themes}theme.yml") info = YAML.load(File.read("#{themes}theme.yml")) hash << info if !info['name'].blank? && !info['author'].blank? && !info['foldername'].blank? && !info['view_extension'].blank? end end hash end
ruby
{ "resource": "" }
q7296
Roroacms.AdminRoroaHelper.get_templates
train
def get_templates hash = [] current_theme = Setting.get('theme_folder') Dir.glob("#{Rails.root}/app/views/themes/#{current_theme}/template-*.html.erb") do |my_text_file| opt = my_text_file.split('/').last opt['template-'] = '' opt['.html.erb'] = '' # strips out the template- and .html.erb extention and returns the middle as the template name for the admin hash << opt.titleize end hash end
ruby
{ "resource": "" }
q7297
Roroacms.AdminRoroaHelper.theme_exists
train
def theme_exists if !Dir.exists?("app/views/themes/#{Setting.get('theme_folder')}/") html = "<div class='alert alert-danger'><strong>" + I18n.t("helpers.admin_roroa_helper.theme_exists.warning") + "!</strong> " + I18n.t("helpers.admin_roroa_helper.theme_exists.message") + "!</div>" render :inline => html.html_safe end end
ruby
{ "resource": "" }
q7298
Roroacms.AdminRoroaHelper.get_notifications
train
def get_notifications html = '' if flash[:error] html += "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.error") + "!</strong> #{flash[:error]}</div>" end if flash[:notice] html += "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.success") + "!</strong> #{flash[:notice]}</div>" end render :inline => html.html_safe end
ruby
{ "resource": "" }
q7299
Roroacms.AdminRoroaHelper.append_application_menu
train
def append_application_menu html = '' Roroacms.append_menu.each do |f| html += (render :partial => 'roroacms/admin/partials/append_sidebar_menu', :locals => { :menu_block => f }) end html.html_safe end
ruby
{ "resource": "" }