_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q19200
Ferret::Index.Index.highlight
train
def highlight(query, doc_id, options = {}) @dir.synchronize do ensure_searcher_open() @searcher.highlight(do_process_query(query), doc_id, options[:field]||@options[:default_field], options) end end
ruby
{ "resource": "" }
q19201
Ferret::Index.Index.term_vector
train
def term_vector(id, field) @dir.synchronize do ensure_reader_open() if id.kind_of?(String) or id.kind_of?(Symbol) term_doc_enum = @reader.term_docs_for(@id_field, id.to_s) if term_doc_enum.next? id = term_doc_enum.doc else return nil end end return @reader.term_vector(id, field) end end
ruby
{ "resource": "" }
q19202
Ferret::Index.Index.query_delete
train
def query_delete(query) @dir.synchronize do ensure_writer_open() ensure_searcher_open() query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |doc, score| @reader.delete(doc) end flush() if @auto_flush end end
ruby
{ "resource": "" }
q19203
Ferret::Index.Index.update
train
def update(id, new_doc) @dir.synchronize do ensure_writer_open() delete(id) if id.is_a?(String) or id.is_a?(Symbol) @writer.commit else ensure_writer_open() end @writer << new_doc flush() if @auto_flush end end
ruby
{ "resource": "" }
q19204
Ferret::Index.Index.batch_update
train
def batch_update(docs) @dir.synchronize do ids = nil case docs when Array ids = docs.collect{|doc| doc[@id_field].to_s} if ids.include?(nil) raise ArgumentError, "all documents must have an #{@id_field} " "field when doing a batch update" end when Hash ids = docs.keys docs = docs.values else raise ArgumentError, "must pass Hash or Array, not #{docs.class}" end batch_delete(ids) ensure_writer_open() docs.each {|new_doc| @writer << new_doc } flush() end end
ruby
{ "resource": "" }
q19205
Ferret::Index.Index.query_update
train
def query_update(query, new_val) @dir.synchronize do ensure_writer_open() ensure_searcher_open() docs_to_add = [] query = do_process_query(query) @searcher.search_each(query, :limit => :all) do |id, score| document = @searcher[id].load if new_val.is_a?(Hash) document.merge!(new_val) else new_val.is_a?(String) or new_val.is_a?(Symbol) document[@default_input_field] = new_val.to_s end docs_to_add << document @reader.delete(id) end ensure_writer_open() docs_to_add.each {|doc| @writer << doc } flush() if @auto_flush end end
ruby
{ "resource": "" }
q19206
Ferret::Index.Index.explain
train
def explain(query, doc) @dir.synchronize do ensure_searcher_open() query = do_process_query(query) return @searcher.explain(query, doc) end end
ruby
{ "resource": "" }
q19207
Ferret::Index.Index.ensure_reader_open
train
def ensure_reader_open(get_latest = true) raise "tried to use a closed index" if not @open if @reader if get_latest latest = false begin latest = @reader.latest? rescue Lock::LockError sleep(@options[:lock_retry_time]) # sleep for 2 seconds and try again latest = @reader.latest? end if not latest @searcher.close if @searcher @reader.close return @reader = IndexReader.new(@dir) end end else if @writer @writer.close @writer = nil end return @reader = IndexReader.new(@dir) end return false end
ruby
{ "resource": "" }
q19208
Ferret::Browser.ViewHelper.truncate
train
def truncate(str, len = 80) if str and str.length > len and (add = str[len..-1].index(' ')) str = str[0, len + add] + '&#8230;' end str end
ruby
{ "resource": "" }
q19209
Ferret::Browser.Controller.paginate
train
def paginate(idx, max, url, &b) return '' if max == 0 url = url.gsub(%r{^/?(.*?)/?$}, '\1') b ||= lambda{} link = lambda {|*args| i, title, text = args "<a href=\"/#{url}/#{i}#{'?' + @query_string if @query_string}\" " + "#{'onclick="return false;"' if (i == idx)} " + "class=\"#{'disabled ' if (i == idx)}#{b.call(i)}\" " + "title=\"#{title||"Go to page #{i}"}\">#{text||i}</a>" } res = '<div class="nav">' if (idx > 0) res << link.call(idx - 1, "Go to previous page", "&#171; Previous") else res << "<a href=\"/#{url}/0\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\">&#171; Previous</a>" end if idx < 10 idx.times {|i| res << link.call(i)} else (0..2).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((idx-4)...idx).each {|i| res << link.call(i)} end res << link.call(idx, 'Current Page') if idx > (max - 10) ((idx+1)...max).each {|i| res << link.call(i)} else ((idx+1)..(idx+4)).each {|i| res << link.call(i)} res << '&nbsp;&#8230;&nbsp;' ((max-3)...max).each {|i| res << link.call(i)} end if (idx < (max - 1)) res << link.call(idx + 1, "Go to next page", "Next &#187;") else res << "<a href=\"/#{url}/#{max-1}\" onclick=\"return false;\" " + "class=\"disabled\" title=\"Disabled\"}\">Next &#187;</a>" end res << '</div>' end
ruby
{ "resource": "" }
q19210
Rubyvis::SvgScene.PathBasis.weight
train
def weight(w) OpenStruct.new({ :x=> w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left, :y=> w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top }) end
ruby
{ "resource": "" }
q19211
ESpeak.Speech.save
train
def save(filename) speech = bytes_wav res = IO.popen(lame_command(filename, command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
{ "resource": "" }
q19212
ESpeak.Speech.bytes
train
def bytes() speech = bytes_wav res = IO.popen(std_lame_command(command_options), 'r+') do |process| process.write(speech) process.close_write process.read end res.to_s end
ruby
{ "resource": "" }
q19213
Rubyvis.Flatten.array
train
def array @entries=[] @stack=[] if @leaf recurse(@map,0) return @entries end visit(@map,0) @entries.map {|stack| m={} @keys.each_with_index {|k,i| v=stack[i] m[k.name]=k.value ? k.value.js_call(self,v) : v } m } end
ruby
{ "resource": "" }
q19214
Rubyvis.Image.bind
train
def bind mark_bind bind=self.binds mark=self begin binds.image = mark._image end while(!binds.image and (mark==mark.proto)) end
ruby
{ "resource": "" }
q19215
Rubyvis.Scale::Quantitative.scale
train
def scale(x) return nil if x.nil? x=x.to_f j=Rubyvis.search(@d, x) j=-j-2 if (j<0) j=[0,[@i.size-1,j].min].max # p @l # puts "Primero #{j}: #{@f.call(x) - @l[j]}" # puts "Segundo #{(@l[j + 1] - @l[j])}" @i[j].call((@f.call(x) - @l[j]) .quo(@l[j + 1] - @l[j])); end
ruby
{ "resource": "" }
q19216
Rubyvis.Scale::Log.ticks
train
def ticks(subdivisions=nil) d = domain n = d[0] < 0 subdivisions||=@b span=@b.to_f / subdivisions # puts "dom: #{d[0]} -> #{n}" i = (n ? -log(-d[0]) : log(d[0])).floor j = (n ? -log(-d[1]) : log(d[1])).ceil ticks = []; if n ticks.push(-pow(-i)) (i..j).each {|ii| ((@b-1)...0).each {|k| ticks.push(-pow(-ii) * k) } } else (i...j).each {|ii| (1..subdivisions).each {|k| if k==1 ticks.push(pow(ii)) else next if subdivisions==@b and k==2 ticks.push(pow(ii)*span*(k-1)) end } } ticks.push(pow(j)); end # for (i = 0; ticks[i] < d[0]; i++); // strip small values # for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values # return ticks.slice(i, j); ticks.find_all {|v| v>=d[0] and v<=d[1]} end
ruby
{ "resource": "" }
q19217
MotionKit.Parent.try
train
def try(*method_chain) obj = self.element method_chain.each do |m| # We'll break out and return nil if any part of the chain # doesn't respond properly. (obj = nil) && break unless obj.respond_to?(m) obj = obj.send(m) end obj end
ruby
{ "resource": "" }
q19218
MotionKit.BaseLayoutClassMethods.memoize
train
def memoize(klass) @memoize ||= {} @memoize[klass] ||= begin while klass break if registered_class = target_klasses[klass] klass = klass.superclass end @memoize[klass] = registered_class if registered_class end @memoize[klass] end
ruby
{ "resource": "" }
q19219
MotionKit.TreeLayout.create
train
def create(element, element_id=nil, &block) element = initialize_element(element, element_id) style_and_context(element, element_id, &block) element end
ruby
{ "resource": "" }
q19220
MotionKit.TreeLayout.reapply
train
def reapply(&block) raise ArgumentError.new('Block required') unless block raise InvalidDeferredError.new('reapply must be run inside of a context') unless @context if reapply? yield end block = block.weak! parent_layout.reapply_blocks << [@context, block] return self end
ruby
{ "resource": "" }
q19221
MotionKit.TreeLayout.get_view
train
def get_view(element_id) element = get(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19222
MotionKit.TreeLayout.last_view
train
def last_view(element_id) element = last(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19223
MotionKit.TreeLayout.all_views
train
def all_views(element_id) element = all(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19224
MotionKit.TreeLayout.nth_view
train
def nth_view(element_id, index) element = nth(element_id) if element.is_a?(Layout) element = element.view end element end
ruby
{ "resource": "" }
q19225
MotionKit.TreeLayout.forget
train
def forget(element_id) unless is_parent_layout? return parent_layout.remove(element_id) end removed = nil context(self.view) do removed = all(element_id) @elements[element_id] = nil end removed end
ruby
{ "resource": "" }
q19226
MotionKit.TreeLayout.forget_tree
train
def forget_tree(element_id, view) removed = forget_view(element_id, view) if view.subviews view.subviews.each do | sub | if (sub_ids = sub.motion_kit_meta[:motion_kit_ids]) sub_ids.each do | sub_id | forget_tree(sub_id, sub) || [] end end end end removed end
ruby
{ "resource": "" }
q19227
MotionKit.TreeLayout.build_view
train
def build_view # Only in the 'layout' method will we allow default container to be # created automatically (when 'add' is called) @assign_root = true prev_should_run = @should_run_deferred @should_run_deferred = true layout unless @view if @assign_root create_default_root_context @view = @context else NSLog('Warning! No root view was set in TreeLayout#layout. Did you mean to call `root`?') end end run_deferred(@view) @should_run_deferred = prev_should_run @assign_root = false # context can be set via the 'create_default_root_context' method, which # may be outside a 'context' block, so make sure to restore context to # it's previous value @context = nil if @preset_root @view = WeakRef.new(@view) @preset_root = nil end @view end
ruby
{ "resource": "" }
q19228
MotionKit.TreeLayout.initialize_element
train
def initialize_element(elem, element_id) if elem.is_a?(Class) && elem < TreeLayout layout = elem.new elem = layout.view elsif elem.is_a?(Class) elem = elem.new elsif elem.is_a?(TreeLayout) layout = elem elem = elem.view end if layout if element_id name_element(layout, element_id) end @child_layouts << layout elsif element_id name_element(elem, element_id) end return elem end
ruby
{ "resource": "" }
q19229
MotionKit.TreeLayout.style_and_context
train
def style_and_context(element, element_id, &block) style_method = "#{element_id}_style" if parent_layout.respond_to?(style_method) || block_given? parent_layout.context(element) do if parent_layout.respond_to?(style_method) parent_layout.send(style_method) end if block_given? yield end end end end
ruby
{ "resource": "" }
q19230
MotionKit.BaseLayout.context
train
def context(new_target, &block) return new_target unless block # this little line is incredibly important; the context is only set on # the top-level Layout object. # mp "MOTIONKIT CONTEXT is #{new_target} meta: #{new_target.motion_kit_meta}" return parent_layout.context(new_target, &block) unless is_parent_layout? if new_target.is_a?(Symbol) new_target = self.get_view(new_target) end context_was, parent_was, delegate_was = @context, @parent, @layout_delegate prev_should_run = @should_run_deferred if @should_run_deferred.nil? @should_run_deferred = true else @should_run_deferred = false end @parent = MK::Parent.new(context_was) @context = new_target @context.motion_kit_meta[:delegate] ||= Layout.layout_for(@context.class) @layout_delegate = @context.motion_kit_meta[:delegate] if @layout_delegate @layout_delegate.set_parent_layout(parent_layout) end yield @layout_delegate, @context, @parent = delegate_was, context_was, parent_was if @should_run_deferred run_deferred(new_target) end @should_run_deferred = prev_should_run new_target end
ruby
{ "resource": "" }
q19231
MotionKit.MenuLayout.root
train
def root(element, element_id=nil, &block) if element && element.is_a?(NSString) element = NSMenu.alloc.initWithTitle(element) end super(element, element_id, &block) end
ruby
{ "resource": "" }
q19232
MotionKit.MenuLayout.add
train
def add(title_or_item, element_id=nil, options={}, &block) if element_id.is_a?(NSDictionary) options = element_id element_id = nil end if title_or_item.is_a?(NSMenuItem) item = title_or_item menu = nil retval = item elsif title_or_item.is_a?(NSMenu) menu = title_or_item item = self.item(menu.title, options) item.submenu = menu retval = menu else title = title_or_item item = self.item(title, options) if block menu = create(title) item.submenu = menu retval = menu else retval = item end end self.apply(:add_child, item) if menu && block menuitem_was = @menu_item @menu_item = item context(menu, &block) @menu_item = menuitem_was end if element_id create(retval, element_id) end return retval end
ruby
{ "resource": "" }
q19233
Expeditor.Command.start_with_retry
train
def start_with_retry(current_thread: false, **retryable_options) unless started? @retryable_options.set(retryable_options) start(current_thread: current_thread) end self end
ruby
{ "resource": "" }
q19234
Expeditor.Command.on_complete
train
def on_complete(&block) on do |_, value, reason| block.call(reason == nil, value, reason) end end
ruby
{ "resource": "" }
q19235
Expeditor.Command.on_success
train
def on_success(&block) on do |_, value, reason| block.call(value) unless reason end end
ruby
{ "resource": "" }
q19236
Expeditor.Command.on_failure
train
def on_failure(&block) on do |_, _, reason| block.call(reason) if reason end end
ruby
{ "resource": "" }
q19237
Expeditor.Command.prepare
train
def prepare(executor = @service.executor) @normal_future = initial_normal(executor, &@normal_block) @normal_future.add_observer do |_, value, reason| if reason # failure if @fallback_block future = RichFuture.new(executor: executor) do success, value, reason = Concurrent::SafeTaskExecutor.new(@fallback_block, rescue_exception: true).execute(reason) if success @ivar.set(value) else @ivar.fail(reason) end end future.safe_execute else @ivar.fail(reason) end else # success @ivar.set(value) end end @dependencies.each(&:start) end
ruby
{ "resource": "" }
q19238
Expeditor.Command.initial_normal
train
def initial_normal(executor, &block) future = RichFuture.new(executor: executor) do args = wait_dependencies timeout_block(args, &block) end future.add_observer do |_, _, reason| metrics(reason) end future end
ruby
{ "resource": "" }
q19239
GDB.EvalContext.invoke_pry
train
def invoke_pry org = Pry.config.history.file # this has no effect if gdb is launched by pry Pry.config.history.file = '~/.gdb-pry_history' $stdin.cooked { pry } Pry.config.history.file = org end
ruby
{ "resource": "" }
q19240
GDB.GDB.text_base
train
def text_base check_alive! base = Integer(execute('info proc stat').scan(/Start of text: (.*)/).flatten.first) execute("set $text = #{base}") base end
ruby
{ "resource": "" }
q19241
GDB.GDB.read_memory
train
def read_memory(addr, num_elements, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).read(addr, num_elements, **options) end
ruby
{ "resource": "" }
q19242
GDB.GDB.write_memory
train
def write_memory(addr, objects, options = {}, &block) check_alive! # this would set @pid options[:as] = block if block_given? MemoryIO.attach(@pid).write(addr, objects, **options) end
ruby
{ "resource": "" }
q19243
Danger.DangerRubocop.lint
train
def lint(config = nil) config = config.is_a?(Hash) ? config : { files: config } files = config[:files] force_exclusion = config[:force_exclusion] || false report_danger = config[:report_danger] || false inline_comment = config[:inline_comment] || false fail_on_inline_comment = config[:fail_on_inline_comment] || false files_to_lint = fetch_files_to_lint(files) files_to_report = rubocop(files_to_lint, force_exclusion) return if files_to_report.empty? return report_failures files_to_report if report_danger if inline_comment add_violation_for_each_line(files_to_report, fail_on_inline_comment) else markdown offenses_message(files_to_report) end end
ruby
{ "resource": "" }
q19244
Beefcake.Generator.name_for
train
def name_for(b, mod, val) b.name_for(mod, val).to_s.gsub(/.*_/, "").downcase end
ruby
{ "resource": "" }
q19245
LiterateRandomizer.SourceParser.scrub_sentence
train
def scrub_sentence(sentence) sentence.split(/([\s]|--)+/).collect {|a| scrub_word(a)}.select {|a| a.length>0} end
ruby
{ "resource": "" }
q19246
LiterateRandomizer.MarkovModel.next_word
train
def next_word(word,randomizer=@randomizer) return if !markov_chains[word] sum = @markov_weighted_sum[word] random = randomizer.rand(sum)+1 partial_sum = 0 (markov_chains[word].find do |w, count| partial_sum += count w!=word && partial_sum >= random end||[]).first end
ruby
{ "resource": "" }
q19247
LiterateRandomizer.Randomizer.extend_trailing_preposition
train
def extend_trailing_preposition(max_words,words) while words.length < max_words && words[-1] && words[-1][PREPOSITION_REGEX] words << model.next_word(words[-1],randomizer) end words end
ruby
{ "resource": "" }
q19248
LiterateRandomizer.Randomizer.sentence
train
def sentence(options={}) word = options[:first_word] || self.first_word num_words_option = options[:words] || (3..15) count = Util.rand_count(num_words_option,randomizer) punctuation = options[:punctuation] || self.punctuation words = count.times.collect do word.tap {word = model.next_word(word,randomizer)} end.compact words = extend_trailing_preposition(Util.max(num_words_option), words) Util.capitalize words.compact.join(" ") + punctuation end
ruby
{ "resource": "" }
q19249
LiterateRandomizer.Randomizer.paragraph
train
def paragraph(options={}) count = Util.rand_count(options[:sentences] || (5..15),randomizer) count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 sentence op end.join(" ") end
ruby
{ "resource": "" }
q19250
LiterateRandomizer.Randomizer.paragraphs
train
def paragraphs(options={}) count = Util.rand_count(options[:paragraphs] || (3..5),randomizer) join_str = options[:join] res = count.times.collect do |i| op = options.clone op.delete :punctuation unless i==count-1 op.delete :first_word unless i==0 paragraph op end join_str!=false ? res.join(join_str || "\n\n") : res end
ruby
{ "resource": "" }
q19251
GLib.ArrayMethods.index
train
def index(idx) unless (0...length).cover? idx raise IndexError, "Index #{idx} outside of bounds 0..#{length - 1}" end ptr = GirFFI::InOutPointer.new element_type, data_ptr + idx * element_size ptr.to_ruby_value end
ruby
{ "resource": "" }
q19252
Rack.Tracer.call
train
def call(env) method = env[REQUEST_METHOD] context = @tracer.extract(OpenTracing::FORMAT_RACK, env) if @trust_incoming_span scope = @tracer.start_active_span( method, child_of: context, tags: { 'component' => 'rack', 'span.kind' => 'server', 'http.method' => method, 'http.url' => env[REQUEST_URI] } ) span = scope.span @on_start_span.call(span) if @on_start_span env['rack.span'] = span @app.call(env).tap do |status_code, _headers, _body| span.set_tag('http.status_code', status_code) route = route_from_env(env) span.operation_name = route if route end rescue *@errors => e span.set_tag('error', true) span.log_kv( event: 'error', :'error.kind' => e.class.to_s, :'error.object' => e, message: e.message, stack: e.backtrace.join("\n") ) raise ensure begin scope.close ensure @on_finish_span.call(span) if @on_finish_span end end
ruby
{ "resource": "" }
q19253
Minimart.Cli.mirror
train
def mirror Minimart::Commands::Mirror.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
{ "resource": "" }
q19254
Minimart.Cli.web
train
def web Minimart::Commands::Web.new(options).execute! rescue Minimart::Error::BaseError => e Minimart::Error.handle_exception(e) end
ruby
{ "resource": "" }
q19255
EM::FTPD.Authentication.cmd_pass
train
def cmd_pass(param) send_response "202 User already logged in" and return unless @user.nil? send_param_required and return if param.nil? send_response "530 password with no username" and return if @requested_user.nil? # return an error message if: # - the specified username isn't in our system # - the password is wrong @driver.authenticate(@requested_user, param) do |result| if result @name_prefix = "/" @user = @requested_user @requested_user = nil send_response "230 OK, password correct" else @user = nil send_response "530 incorrect login. not logged in." end end end
ruby
{ "resource": "" }
q19256
EM::FTPD.Files.cmd_dele
train
def cmd_dele(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.delete_file(path) do |result| if result send_response "250 File deleted" else send_action_not_taken end end end
ruby
{ "resource": "" }
q19257
EM::FTPD.Files.cmd_retr
train
def cmd_retr(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) @driver.get_file(path) do |data| if data send_response "150 Data transfer starting #{data.size} bytes" send_outofband_data(data, @restart_pos || 0) else send_response "551 file not available" end end end
ruby
{ "resource": "" }
q19258
EM::FTPD.Files.cmd_size
train
def cmd_size(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.bytes(build_path(param)) do |bytes| if bytes send_response "213 #{bytes}" else send_response "450 file not available" end end end
ruby
{ "resource": "" }
q19259
EM::FTPD.Files.cmd_stor
train
def cmd_stor(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? path = build_path(param) if @driver.respond_to?(:put_file_streamed) cmd_stor_streamed(path) elsif @driver.respond_to?(:put_file) cmd_stor_tempfile(path) else raise "driver MUST respond to put_file OR put_file_streamed" end end
ruby
{ "resource": "" }
q19260
EM::FTPD.Directories.cmd_nlst
train
def cmd_nlst(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" @driver.dir_contents(build_path(param)) do |files| send_outofband_data(files.map(&:name)) end end
ruby
{ "resource": "" }
q19261
EM::FTPD.Directories.cmd_list
train
def cmd_list(param) send_unauthorised and return unless logged_in? send_response "150 Opening ASCII mode data connection for file list" param = '' if param.to_s == '-a' @driver.dir_contents(build_path(param)) do |files| now = Time.now lines = files.map { |item| sizestr = (item.size || 0).to_s.rjust(12) "#{item.directory ? 'd' : '-'}#{item.permissions || 'rwxrwxrwx'} 1 #{item.owner || 'owner'} #{item.group || 'group'} #{sizestr} #{(item.time || now).strftime("%b %d %H:%M")} #{item.name}" } send_outofband_data(lines) end end
ruby
{ "resource": "" }
q19262
EM::FTPD.Directories.cmd_rmd
train
def cmd_rmd(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? @driver.delete_dir(build_path(param)) do |result| if result send_response "250 Directory deleted." else send_action_not_taken end end end
ruby
{ "resource": "" }
q19263
EM::FTPD.Server.parse_request
train
def parse_request(data) data.strip! space = data.index(" ") if space cmd = data[0, space] param = data[space+1, data.length - space] param = nil if param.strip.size == 0 else cmd = data param = nil end [cmd.downcase, param] end
ruby
{ "resource": "" }
q19264
EM::FTPD.Server.cmd_help
train
def cmd_help(param) send_response "214- The following commands are recognized." commands = COMMANDS str = "" commands.sort.each_slice(3) { |slice| str += " " + slice.join("\t\t") + LBRK } send_response str, true send_response "214 End of list." end
ruby
{ "resource": "" }
q19265
EM::FTPD.Server.cmd_pasv
train
def cmd_pasv(param) send_unauthorised and return unless logged_in? host, port = start_passive_socket p1, p2 = *port.divmod(256) send_response "227 Entering Passive Mode (" + host.split(".").join(",") + ",#{p1},#{p2})" end
ruby
{ "resource": "" }
q19266
EM::FTPD.Server.cmd_port
train
def cmd_port(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? nums = param.split(',') port = nums[4].to_i * 256 + nums[5].to_i host = nums[0..3].join('.') close_datasocket puts "connecting to client #{host} on #{port}" @datasocket = ActiveSocket.open(host, port) puts "Opened active connection at #{host}:#{port}" send_response "200 Connection established (#{port})" rescue puts "Error opening data connection to #{host}:#{port}" send_response "425 Data connection failed" end
ruby
{ "resource": "" }
q19267
EM::FTPD.Server.cmd_type
train
def cmd_type(param) send_unauthorised and return unless logged_in? send_param_required and return if param.nil? if param.upcase.eql?("A") send_response "200 Type set to ASCII" elsif param.upcase.eql?("I") send_response "200 Type set to binary" else send_response "500 Invalid type" end end
ruby
{ "resource": "" }
q19268
EM::FTPD.Server.send_outofband_data
train
def send_outofband_data(data, restart_pos = 0) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" else if data.is_a?(Array) data = data.join(LBRK) << LBRK end data = StringIO.new(data) if data.kind_of?(String) data.seek(restart_pos) if EM.reactor_running? # send the data out in chunks, as fast as the client can recieve it -- not blocking the reactor in the process streamer = IOStreamer.new(datasocket, data) finalize = Proc.new { close_datasocket data.close if data.respond_to?(:close) && !data.closed? } streamer.callback { send_response "226 Closing data connection, sent #{streamer.bytes_streamed} bytes" finalize.call } streamer.errback { |ex| send_response "425 Error while streaming data, sent #{streamer.bytes_streamed} bytes" finalize.call raise ex } else # blocks until all data is sent begin bytes = 0 data.each do |line| datasocket.send_data(line) bytes += line.bytesize end send_response "226 Closing data connection, sent #{bytes} bytes" ensure close_datasocket data.close if data.respond_to?(:close) end end end end end
ruby
{ "resource": "" }
q19269
EM::FTPD.Server.wait_for_datasocket
train
def wait_for_datasocket(interval = 0.1, &block) if @datasocket.nil? && interval < 25 if EM.reactor_running? EventMachine.add_timer(interval) { wait_for_datasocket(interval * 2, &block) } else sleep interval wait_for_datasocket(interval * 2, &block) end return end yield @datasocket end
ruby
{ "resource": "" }
q19270
EM::FTPD.Server.receive_outofband_data
train
def receive_outofband_data(&block) wait_for_datasocket do |datasocket| if datasocket.nil? send_response "425 Error establishing connection" yield false else # let the client know we're ready to start send_response "150 Data transfer starting" datasocket.callback do |data| block.call(data) end end end end
ruby
{ "resource": "" }
q19271
CensusApi.Client.where
train
def where(options={}) options.merge!(key: @api_key, vintage: @api_vintage) fail "Client requires a dataset (#{DATASETS})." if @dataset.nil? [:fields, :level].each do |f| fail ArgumentError, "#{f} is a requied parameter" if options[f].nil? end options[:within] = [options[:within]] unless options[:within].nil? Request.find(dataset, options) end
ruby
{ "resource": "" }
q19272
DNSBL.Client.add_dnsbl
train
def add_dnsbl(name,domain,type='ip',codes={"0"=>"OK","127.0.0.2"=>"Blacklisted"}) @dnsbls[name] = codes @dnsbls[name]['domain'] = domain @dnsbls[name]['type'] = type end
ruby
{ "resource": "" }
q19273
DNSBL.Client._encode_query
train
def _encode_query(item,itemtype,domain,apikey=nil) label = nil if itemtype == 'ip' label = item.split(/\./).reverse.join(".") elsif itemtype == 'domain' label = normalize(item) end lookup = "#{label}.#{domain}" if apikey lookup = "#{apikey}.#{lookup}" end txid = lookup.sum message = Resolv::DNS::Message.new(txid) message.rd = 1 message.add_question(lookup,Resolv::DNS::Resource::IN::A) message.encode end
ruby
{ "resource": "" }
q19274
DNSBL.Client.lookup
train
def lookup(item) # if item is an array, use it, otherwise make it one items = item if item.is_a? String items = [item] end # place the results in the results array results = [] # for each ip or hostname items.each do |item| # sent is used to determine when we have all the answers sent = 0 # record the start time @starttime = Time.now.to_f # determine the type of query itemtype = (item =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) ? 'ip' : 'domain' # for each dnsbl that supports our type, create the DNS query packet and send it # rotate across our configured name servers and increment sent @dnsbls.each do |name,config| next if config['disabled'] next unless config['type'] == itemtype begin msg = _encode_query(item,itemtype,config['domain'],config['apikey']) @sockets[@socket_index].send(msg,0) @socket_index += 1 @socket_index %= @sockets.length sent += 1 rescue Exception => e puts e puts e.backtrace.join("\n") end end # while we still expect answers while sent > 0 # wait on the socket for maximally 1.5 seconds r,_,_ = IO.select(@sockets,nil,nil,1.5) # if we time out, break out of the loop break unless r # for each reply, decode it and receive results, decrement the pending answers r.each do |s| begin response = _decode_response(s.recv(4096)) results += response rescue Exception => e puts e puts e.backtrace.join("\n") end sent -= 1 end end end results end
ruby
{ "resource": "" }
q19275
DNSBL.Client._decode_response
train
def _decode_response(buf) reply = Resolv::DNS::Message.decode(buf) results = [] reply.each_answer do |name,ttl,data| if name.to_s =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(.+)$/ ip = [$4,$3,$2,$1].join(".") domain = $5 @dnsbls.each do |dnsblname, config| next unless data.is_a? Resolv::DNS::Resource::IN::A if domain == config['domain'] meaning = config[data.address.to_s] || data.address.to_s results << DNSBLResult.new(dnsblname, ip, name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end else @dnsbls.each do |dnsblname, config| if name.to_s.end_with?(config['domain']) meaning = nil if config['decoder'] meaning = self.send(("__"+config['decoder']).to_sym, data.address.to_s) elsif config[data.address.to_s] meaning = config[data.address.to_s] else meaning = data.address.to_s end results << DNSBLResult.new(dnsblname, name.to_s.gsub("."+config['domain'],''), name.to_s, data.address.to_s, meaning, Time.now.to_f - @starttime) break end end end end results end
ruby
{ "resource": "" }
q19276
DNSBL.Client.__phpot_decoder
train
def __phpot_decoder(ip) octets = ip.split(/\./) if octets.length != 4 or octets[0] != "127" return "invalid response" elsif octets[3] == "0" search_engines = ["undocumented", "AltaVista", "Ask", "Baidu", "Excite", "Google", "Looksmart", "Lycos", "MSN", "Yahoo", "Cuil", "InfoSeek", "Miscellaneous"] sindex = octets[2].to_i if sindex >= search_engines.length return "type=search engine,engine=unknown" else return "type=search engine,engine=#{search_engines[sindex]}" end else days, threatscore, flags = octets[1,3] flags = flags.to_i types = [] if (flags & 0x1) == 0x1 types << "suspicious" end if (flags & 0x2) == 0x2 types << "harvester" end if (flags & 0x4) == 0x4 types << "comment spammer" end if (flags & 0xf8) > 0 types << "reserved" end type = types.join(",") return "days=#{days},score=#{threatscore},type=#{type}" end end
ruby
{ "resource": "" }
q19277
Flt.Support.FlagValues
train
def FlagValues(*params) if params.size==1 && params.first.kind_of?(FlagValues) params.first else FlagValues.new(*params) end end
ruby
{ "resource": "" }
q19278
Flt.Support.Flags
train
def Flags(*params) if params.size==1 && params.first.kind_of?(Flags) params.first else Flags.new(*params) end end
ruby
{ "resource": "" }
q19279
Flt.Tolerance.integer
train
def integer(x) # return integer?(x) ? x.round : nil r = x.round ((x-r).abs <= relative_to(x)) ? r : nil end
ruby
{ "resource": "" }
q19280
Gopher.DSL.mount
train
def mount(path, opts = {}) route, folder = path.first # # if path has more than the one option (:route => :folder), # then incorporate the rest of the hash into our opts # if path.size > 1 other_opts = path.dup other_opts.delete(route) opts = opts.merge(other_opts) end application.mount(route, opts.merge({:path => folder})) end
ruby
{ "resource": "" }
q19281
Gopher.Response.size
train
def size case self.body when String then self.body.length when StringIO then self.body.length when File then self.body.size else 0 end end
ruby
{ "resource": "" }
q19282
Gopher.Server.run!
train
def run! EventMachine::run do Signal.trap("INT") { puts "It's a trap!" EventMachine.stop } Signal.trap("TERM") { puts "It's a trap!" EventMachine.stop } EventMachine.kqueue = true if EventMachine.kqueue? EventMachine.epoll = true if EventMachine.epoll? STDERR.puts "start server at #{host} #{port}" if @app.non_blocking? STDERR.puts "Not blocking on requests" end EventMachine::start_server(host, port, Gopher::Dispatcher) do |conn| # # check if we should reload any scripts before moving along # @app.reload_stale # # roughly matching sinatra's style of duping the app to respond # to requests, @see http://www.sinatrarb.com/intro#Request/Instance%20Scope # # this essentially means we have 'one instance per request' # conn.app = @app.dup end end end
ruby
{ "resource": "" }
q19283
Gopher.Application.should_reload?
train
def should_reload? ! last_reload.nil? && self.scripts.any? do |f| File.mtime(f) > last_reload end end
ruby
{ "resource": "" }
q19284
Gopher.Application.reload_stale
train
def reload_stale reload_check = should_reload? self.last_reload = Time.now return if ! reload_check reset! self.scripts.each do |f| debug_log "reload #{f}" load f end end
ruby
{ "resource": "" }
q19285
Gopher.Application.mount
train
def mount(path, opts = {}, klass = Gopher::Handlers::DirectoryHandler) debug_log "MOUNT #{path} #{opts.inspect}" opts[:mount_point] = path handler = klass.new(opts) handler.application = self # # add a route for the mounted class # route(globify(path)) do # when we call, pass the params and request object for this # particular request handler.call(params, request) end end
ruby
{ "resource": "" }
q19286
Gopher.Application.lookup
train
def lookup(selector) unless routes.nil? routes.each do |pattern, keys, block| if match = pattern.match(selector) match = match.to_a url = match.shift params = to_params_hash(keys, match) # # @todo think about this # @params = params return params, block end end end unless @default_route.nil? return {}, @default_route end raise Gopher::NotFoundError end
ruby
{ "resource": "" }
q19287
Gopher.Application.dispatch
train
def dispatch(req) debug_log(req) response = Response.new @request = req if ! @request.valid? response.body = handle_invalid_request response.code = :error else begin debug_log("do lookup for #{@request.selector}") @params, block = lookup(@request.selector) # # call the block that handles this lookup # response.body = block.bind(self).call response.code = :success rescue Gopher::NotFoundError => e debug_log("#{@request.selector} -- not found") response.body = handle_not_found response.code = :missing rescue Exception => e debug_log("#{@request.selector} -- error") debug_log(e.inspect) debug_log(e.backtrace) response.body = handle_error(e) response.code = :error end end access_log(req, response) response end
ruby
{ "resource": "" }
q19288
Gopher.Application.find_template
train
def find_template(t) x = menus[t] if x return x, Gopher::Rendering::Menu end x = text_templates[t] if x return x, Gopher::Rendering::Text end end
ruby
{ "resource": "" }
q19289
Gopher.Application.render
train
def render(template, *arguments) # # find the right renderer we need # block, handler = find_template(template) raise TemplateNotFound if block.nil? ctx = handler.new(self) ctx.params = @params ctx.request = @request ctx.instance_exec(*arguments, &block) end
ruby
{ "resource": "" }
q19290
Gopher.Application.compile!
train
def compile!(path, &block) method_name = path route_method = Application.generate_method(method_name, &block) pattern, keys = compile path [ pattern, keys, route_method ] end
ruby
{ "resource": "" }
q19291
Gopher.Application.init_access_log
train
def init_access_log return if access_log_dest.nil? log = ::Logging.logger['access_log'] pattern = ::Logging.layouts.pattern(:pattern => ACCESS_LOG_PATTERN) log.add_appenders( ::Logging.appenders.rolling_file(access_log_dest, :level => :debug, :age => 'daily', :layout => pattern) ) log end
ruby
{ "resource": "" }
q19292
Gopher.Application.access_log
train
def access_log(request, response) return if access_log_dest.nil? @@access_logger ||= init_access_log code = response.respond_to?(:code) ? response.code.to_s : "success" size = response.respond_to?(:size) ? response.size : response.length output = [request.ip_address, request.selector, request.input, code.to_s, size].join("\t") @@access_logger.debug output end
ruby
{ "resource": "" }
q19293
Gopher.Application.to_params_hash
train
def to_params_hash(keys,values) hash = {} keys.size.times { |i| hash[ keys[i].to_sym ] = values[i] } hash end
ruby
{ "resource": "" }
q19294
Gopher.Dispatcher.call!
train
def call!(request) operation = proc { app.dispatch(request) } callback = proc {|result| send_response result close_connection_after_writing } # # if we don't want to block on slow calls, use EM#defer # @see http://eventmachine.rubyforge.org/EventMachine.html#M000486 # if app.non_blocking? EventMachine.defer( operation, callback ) else callback.call(operation.call) end end
ruby
{ "resource": "" }
q19295
Gopher.Dispatcher.send_response
train
def send_response(response) case response when Gopher::Response then send_response(response.body) when String then send_data(response + end_of_transmission) when StringIO then send_data(response.read + end_of_transmission) when File while chunk = response.read(8192) do send_data(chunk) end response.close end end
ruby
{ "resource": "" }
q19296
Appsignal.AuthCheck.perform_with_result
train
def perform_with_result status = perform result = case status when "200" "AppSignal has confirmed authorization!" when "401" "API key not valid with AppSignal..." else "Could not confirm authorization: " \ "#{status.nil? ? "nil" : status}" end [status, result] rescue => e result = "Something went wrong while trying to "\ "authenticate with AppSignal: #{e}" [nil, result] end
ruby
{ "resource": "" }
q19297
Appsignal.Config.maintain_backwards_compatibility
train
def maintain_backwards_compatibility(configuration) configuration.tap do |config| DEPRECATED_CONFIG_KEY_MAPPING.each do |old_key, new_key| old_config_value = config.delete(old_key) next unless old_config_value deprecation_message \ "Old configuration key found. Please update the "\ "'#{old_key}' to '#{new_key}'.", logger next if config[new_key] # Skip if new key is already in use config[new_key] = old_config_value end if config.include?(:working_dir_path) deprecation_message \ "'working_dir_path' is deprecated, please use " \ "'working_directory_path' instead and specify the " \ "full path to the working directory", logger end end end
ruby
{ "resource": "" }
q19298
Appsignal.Transaction.background_queue_start
train
def background_queue_start env = environment return unless env queue_start = env[:queue_start] return unless queue_start (queue_start.to_f * 1000.0).to_i end
ruby
{ "resource": "" }
q19299
Appsignal.Transaction.http_queue_start
train
def http_queue_start env = environment return unless env env_var = env["HTTP_X_QUEUE_START".freeze] || env["HTTP_X_REQUEST_START".freeze] return unless env_var cleaned_value = env_var.tr("^0-9".freeze, "".freeze) return if cleaned_value.empty? value = cleaned_value.to_i if value > 4_102_441_200_000 # Value is in microseconds. Transform to milliseconds. value / 1_000 elsif value < 946_681_200_000 # Value is too low to be plausible nil else # Value is in milliseconds value end end
ruby
{ "resource": "" }