_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q16800
FiniteMachine.EventDefinition.apply
train
def apply(event_name, silent = false) define_event_transition(event_name, silent) define_event_bang(event_name, silent) end
ruby
{ "resource": "" }
q16801
FiniteMachine.EventDefinition.define_event_transition
train
def define_event_transition(event_name, silent) machine.send(:define_singleton_method, event_name) do |*data, &block| method = silent ? :transition : :trigger machine.public_send(method, event_name, *data, &block) end end
ruby
{ "resource": "" }
q16802
FiniteMachine.DSL.initial
train
def initial(value, **options) state = (value && !value.is_a?(Hash)) ? value : raise_missing_state name, @defer_initial, @silent_initial = *parse_initial(options) @initial_event = name event(name, FiniteMachine::DEFAULT_STATE => state, silent: @silent_initial) end
ruby
{ "resource": "" }
q16803
FiniteMachine.DSL.event
train
def event(name, transitions = {}, &block) detect_event_conflict!(name) if machine.auto_methods? if block_given? merger = ChoiceMerger.new(machine, name, transitions) merger.instance_eval(&block) else transition_builder = TransitionBuilder.new(machine, name, transitions) ...
ruby
{ "resource": "" }
q16804
FiniteMachine.DSL.parse_initial
train
def parse_initial(options) [options.fetch(:event) { FiniteMachine::DEFAULT_EVENT_NAME }, options.fetch(:defer) { false }, options.fetch(:silent) { true }] end
ruby
{ "resource": "" }
q16805
FiniteMachine.StateMachine.is?
train
def is?(state) if state.is_a?(Array) state.include? current else state == current end end
ruby
{ "resource": "" }
q16806
FiniteMachine.StateMachine.can?
train
def can?(*args) event_name = args.shift events_map.can_perform?(event_name, current, *args) end
ruby
{ "resource": "" }
q16807
FiniteMachine.StateMachine.valid_state?
train
def valid_state?(event_name) current_states = events_map.states_for(event_name) current_states.any? { |state| state == current || state == ANY_STATE } end
ruby
{ "resource": "" }
q16808
FiniteMachine.StateMachine.notify
train
def notify(hook_event_type, event_name, from, *data) sync_shared do hook_event = hook_event_type.build(current, event_name, from) subscribers.visit(hook_event, *data) end end
ruby
{ "resource": "" }
q16809
FiniteMachine.StateMachine.try_trigger
train
def try_trigger(event_name) if valid_state?(event_name) yield else exception = InvalidStateError catch_error(exception) || fail(exception, "inappropriate current state '#{current}'") false end end
ruby
{ "resource": "" }
q16810
FiniteMachine.StateMachine.trigger!
train
def trigger!(event_name, *data, &block) from = current # Save away current state sync_exclusive do notify HookEvent::Before, event_name, from, *data status = try_trigger(event_name) do if can?(event_name, *data) notify HookEvent::Exit, event_name, from, *data ...
ruby
{ "resource": "" }
q16811
FiniteMachine.StateMachine.trigger
train
def trigger(event_name, *data, &block) trigger!(event_name, *data, &block) rescue InvalidStateError, TransitionError, CallbackError false end
ruby
{ "resource": "" }
q16812
FiniteMachine.StateMachine.transition!
train
def transition!(event_name, *data, &block) from_state = current to_state = events_map.move_to(event_name, from_state, *data) block.call(from_state, to_state) if block if log_transitions Logger.report_transition(event_name, from_state, to_state, *data) end try_trigger(eve...
ruby
{ "resource": "" }
q16813
FiniteMachine.StateMachine.transition_to!
train
def transition_to!(new_state) from_state = current self.state = new_state self.initial_state = new_state if from_state == DEFAULT_STATE true rescue Exception => e catch_error(e) || raise_transition_error(e) end
ruby
{ "resource": "" }
q16814
FiniteMachine.StateMachine.method_missing
train
def method_missing(method_name, *args, &block) if observer.respond_to?(method_name.to_sym) observer.public_send(method_name.to_sym, *args, &block) elsif env.aliases.include?(method_name.to_sym) env.send(:target, *args, &block) else super end end
ruby
{ "resource": "" }
q16815
FiniteMachine.StateMachine.respond_to_missing?
train
def respond_to_missing?(method_name, include_private = false) observer.respond_to?(method_name.to_sym) || env.aliases.include?(method_name.to_sym) || super end
ruby
{ "resource": "" }
q16816
FiniteMachine.Safety.detect_event_conflict!
train
def detect_event_conflict!(event_name, method_name = event_name) if method_already_implemented?(method_name) raise FiniteMachine::AlreadyDefinedError, EVENT_CONFLICT_MESSAGE % { name: event_name, type: :instance, method: method_name, source: 'FiniteMachine' ...
ruby
{ "resource": "" }
q16817
FiniteMachine.Safety.ensure_valid_callback_name!
train
def ensure_valid_callback_name!(event_type, name) message = if wrong_event_name?(name, event_type) EVENT_CALLBACK_CONFLICT_MESSAGE % { type: "on_#{event_type}", name: name } elsif wrong_state_name?(name, event_type) STATE_CALLBACK_CONFLICT_MESSAGE % { ty...
ruby
{ "resource": "" }
q16818
FiniteMachine.Safety.wrong_event_name?
train
def wrong_event_name?(name, event_type) machine.states.include?(name) && !machine.events.include?(name) && event_type < HookEvent::Anyaction end
ruby
{ "resource": "" }
q16819
FiniteMachine.Safety.wrong_state_name?
train
def wrong_state_name?(name, event_type) machine.events.include?(name) && !machine.states.include?(name) && event_type < HookEvent::Anystate end
ruby
{ "resource": "" }
q16820
FiniteMachine.MessageQueue.subscribe
train
def subscribe(*args, &block) @mutex.synchronize do listener = Listener.new(*args) listener.on_delivery(&block) @listeners << listener end end
ruby
{ "resource": "" }
q16821
FiniteMachine.MessageQueue.shutdown
train
def shutdown fail EventQueueDeadError, 'event queue already dead' if @dead queue = [] @mutex.synchronize do @dead = true @not_empty.broadcast queue = @queue @queue.clear end while !queue.empty? discard_message(queue.pop) end true en...
ruby
{ "resource": "" }
q16822
FiniteMachine.MessageQueue.process_events
train
def process_events until @dead @mutex.synchronize do while @queue.empty? break if @dead @not_empty.wait(@mutex) end event = @queue.pop break unless event notify_listeners(event) event.dispatch end end res...
ruby
{ "resource": "" }
q16823
FiniteMachine.Subscribers.visit
train
def visit(hook_event, *data) each { |subscriber| synchronize { hook_event.notify(subscriber, *data) } } end
ruby
{ "resource": "" }
q16824
FiniteMachine.TransitionBuilder.call
train
def call(transitions) StateParser.parse(transitions) do |from, to| transition = Transition.new(@machine.env.target, @name, @attributes.merge(states: { from => to })) silent = @attributes.fetch(:silent, false) @machine.events_map.add(@name, transition) ...
ruby
{ "resource": "" }
q16825
FiniteMachine.Catchable.handle
train
def handle(*exceptions, &block) options = exceptions.last.is_a?(Hash) ? exceptions.pop : {} unless options.key?(:with) if block_given? options[:with] = block else raise ArgumentError, 'Need to provide error handler.' end end evaluate_exceptions(except...
ruby
{ "resource": "" }
q16826
FiniteMachine.Catchable.catch_error
train
def catch_error(exception) if handler = handler_for_error(exception) handler.arity.zero? ? handler.call : handler.call(exception) true end end
ruby
{ "resource": "" }
q16827
FiniteMachine.Catchable.extract_const
train
def extract_const(class_name) class_name.split('::').reduce(FiniteMachine) do |constant, part| constant.const_get(part) end end
ruby
{ "resource": "" }
q16828
FiniteMachine.Catchable.evaluate_handler
train
def evaluate_handler(handler) case handler when Symbol target.method(handler) when Proc if handler.arity.zero? proc { instance_exec(&handler) } else proc { |_exception| instance_exec(_exception, &handler) } end end end
ruby
{ "resource": "" }
q16829
FiniteMachine.Catchable.evaluate_exceptions
train
def evaluate_exceptions(exceptions, options) exceptions.each do |exception| key = if exception.is_a?(Class) && exception <= Exception exception.name elsif exception.is_a?(String) exception else raise ArgumentError, "#{exception} isn't an Exception" end...
ruby
{ "resource": "" }
q16830
LitaGithub.Org.team_id_by_slug
train
def team_id_by_slug(slug, org) octo.organization_teams(org).each do |team| return team[:id] if team[:slug] == slug.downcase end nil end
ruby
{ "resource": "" }
q16831
LitaGithub.Org.team_id
train
def team_id(team, org) /^\d+$/.match(team.to_s) ? team : team_id_by_slug(team, org) end
ruby
{ "resource": "" }
q16832
LitaGithub.General.opts_parse
train
def opts_parse(cmd) o = {} cmd.scan(LitaGithub::R::OPT_REGEX).flatten.each do |opt| k, v = symbolize_opt_key(*opt.strip.split(':')) next if o.key?(k) # if it looks like we're using the extended option (first character is a " or '): # slice off the first and last character ...
ruby
{ "resource": "" }
q16833
LitaGithub.Repo.repo_has_team?
train
def repo_has_team?(full_name, team_id) octo.repository_teams(full_name).each { |t| return true if t[:id] == team_id } false end
ruby
{ "resource": "" }
q16834
TfIdfSimilarity.TfIdfModel.probabilistic_inverse_document_frequency
train
def probabilistic_inverse_document_frequency(term) count = @model.document_count(term).to_f log((documents.size - count) / count) end
ruby
{ "resource": "" }
q16835
TfIdfSimilarity.TfIdfModel.normalized_log_term_frequency
train
def normalized_log_term_frequency(document, term) count = document.term_count(term) if count > 0 (1 + log(count)) / (1 + log(document.average_term_count)) else 0 end end
ruby
{ "resource": "" }
q16836
TfIdfSimilarity.Document.set_term_counts_and_size
train
def set_term_counts_and_size tokenize(text).each do |word| token = Token.new(word) if token.valid? term = token.lowercase_filter.classic_filter.to_s @term_counts[term] += 1 @size += 1 end end end
ruby
{ "resource": "" }
q16837
TfIdfSimilarity.BM25Model.inverse_document_frequency
train
def inverse_document_frequency(term) df = @model.document_count(term) log((documents.size - df + 0.5) / (df + 0.5)) end
ruby
{ "resource": "" }
q16838
TfIdfSimilarity.BM25Model.term_frequency
train
def term_frequency(document, term) tf = document.term_count(term) (tf * 2.2) / (tf + 0.3 + 0.9 * documents.size / @model.average_document_size) end
ruby
{ "resource": "" }
q16839
Dry.View.call
train
def call(format: config.default_format, context: config.default_context, **input) ensure_config env = self.class.render_env(format: format, context: context) template_env = self.class.template_env(format: format, context: context) locals = locals(template_env, input) output = env.templat...
ruby
{ "resource": "" }
q16840
DeepCover.CoveredCode.check_node_overlap!
train
def check_node_overlap! node_to_positions = {} each_node do |node| node.proper_range.each do |position| if node_to_positions[position] already = node_to_positions[position] puts "There is a proper_range overlap between #{node} and #{already}" puts "Overl...
ruby
{ "resource": "" }
q16841
DeepCover.Tools::ContentTag.content_tag
train
def content_tag(tag, content, **options) attrs = options.map { |kind, value| %{ #{kind}="#{value}"} }.join "<#{tag}#{attrs}>#{content}</#{tag}>" end
ruby
{ "resource": "" }
q16842
DeepCover.IgnoreNodes.results
train
def results(analyser) r = analyser.results [0, nil].map do |val| r.select { |node, runs| runs == val } .keys .map(&:source) end end
ruby
{ "resource": "" }
q16843
DeepCover.Node.find_all
train
def find_all(lookup) case lookup when ::Module each_node.grep(lookup) when ::Symbol each_node.find_all { |n| n.type == lookup } when ::String each_node.find_all { |n| n.source == lookup } when ::Regexp each_node.find_all { |n| n.source =~ lookup } else...
ruby
{ "resource": "" }
q16844
DeepCover.Node.[]
train
def [](lookup) if lookup.is_a?(Integer) children.fetch(lookup) else found = find_all(lookup) case found.size when 1 found.first when 0 raise "No children of type #{lookup}" else raise "Ambiguous lookup #{lookup}, found #{found}." ...
ruby
{ "resource": "" }
q16845
DeepCover.Node.each_node
train
def each_node(&block) return to_enum :each_node unless block_given? children_nodes.each do |child| child.each_node(&block) end yield self self end
ruby
{ "resource": "" }
q16846
DeepCover.Coverage.add_missing_covered_codes
train
def add_missing_covered_codes top_level_path = DeepCover.config.paths.detect do |path| next unless path.is_a?(String) path = File.expand_path(path) File.dirname(path) == path end if top_level_path # One of the paths is a root path. # Either a mistake, or the use...
ruby
{ "resource": "" }
q16847
top_level_module::DeepCover.Persistence.load_trackers
train
def load_trackers tracker_hits_per_path_hashes = tracker_files.map do |full_path| JSON.parse(full_path.binread).transform_keys(&:to_sym).yield_self do |version:, tracker_hits_per_path:| raise "dump version mismatch: #{version}, currently #{VERSION}" unless version == VERSION tracker_hi...
ruby
{ "resource": "" }
q16848
DeepCover.AutoloadTracker.initialize_autoloaded_paths
train
def initialize_autoloaded_paths(mods = ObjectSpace.each_object(Module)) # &do_autoload_block mods.each do |mod| # Module's constants are shared with Object. But if you set autoloads directly on Module, they # appear on multiple classes. So just skip, Object will take care of those. next if...
ruby
{ "resource": "" }
q16849
DeepCover.AutoloadTracker.remove_interceptors
train
def remove_interceptors # &do_autoload_block @autoloads_by_basename.each do |basename, entries| entries.each do |entry| mod = entry.mod_if_available next unless mod # Module's constants are shared with Object. But if you set autoloads directly on Module, they # appe...
ruby
{ "resource": "" }
q16850
DeepCover.Tools::ExecuteSample.execute_sample
train
def execute_sample(to_execute, source: nil) # Disable some annoying warning by ruby. We are testing edge cases, so warnings are to be expected. Tools.silence_warnings do if to_execute.is_a?(CoveredCode) to_execute.execute_code else to_execute.call end end ...
ruby
{ "resource": "" }
q16851
Mixlib.Config.from_file
train
def from_file(filename) if %w{ .yml .yaml }.include?(File.extname(filename)) from_yaml(filename) elsif File.extname(filename) == ".json" from_json(filename) elsif File.extname(filename) == ".toml" from_toml(filename) else instance_eval(IO.read(filename), filename,...
ruby
{ "resource": "" }
q16852
Mixlib.Config.reset
train
def reset self.configuration = Hash.new config_contexts.values.each { |config_context| config_context.reset } end
ruby
{ "resource": "" }
q16853
Mixlib.Config.save
train
def save(include_defaults = false) result = configuration.dup if include_defaults (configurables.keys - result.keys).each do |missing_default| # Ask any configurables to save themselves into the result array if configurables[missing_default].has_default result[missing...
ruby
{ "resource": "" }
q16854
Mixlib.Config.restore
train
def restore(hash) self.configuration = hash.reject { |key, value| config_contexts.key?(key) } config_contexts.each do |key, config_context| if hash.key?(key) config_context.restore(hash[key]) else config_context.reset end end config_context_lists.each ...
ruby
{ "resource": "" }
q16855
Mixlib.Config.merge!
train
def merge!(hash) hash.each do |key, value| if config_contexts.key?(key) # Grab the config context and let internal_get cache it if so desired config_contexts[key].restore(value) else configuration[key] = value end end self end
ruby
{ "resource": "" }
q16856
Mixlib.Config.config_context
train
def config_context(symbol, &block) if configurables.key?(symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{symbol} with a config context" end if config_contexts.key?(symbol) context = config_contexts[symbol] else context = Class.ne...
ruby
{ "resource": "" }
q16857
Mixlib.Config.config_context_list
train
def config_context_list(plural_symbol, singular_symbol, &block) if configurables.key?(plural_symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context" end unless config_context_lists.key?(plural_symbol) config_conte...
ruby
{ "resource": "" }
q16858
Mixlib.Config.config_context_hash
train
def config_context_hash(plural_symbol, singular_symbol, &block) if configurables.key?(plural_symbol) raise ReopenedConfigurableWithConfigContextError, "Cannot redefine config value #{plural_symbol} with a config context" end unless config_context_hashes.key?(plural_symbol) config_cont...
ruby
{ "resource": "" }
q16859
Mixlib.Config.internal_set
train
def internal_set(symbol, value) if configurables.key?(symbol) configurables[symbol].set(configuration, value) elsif config_contexts.key?(symbol) config_contexts[symbol].restore(value.to_hash) else if config_strict_mode == :warn Chef::Log.warn("Setting unsupported conf...
ruby
{ "resource": "" }
q16860
NestedForm.BuilderMixin.link_to_remove
train
def link_to_remove(*args, &block) options = args.extract_options!.symbolize_keys options[:class] = [options[:class], "remove_nested_fields"].compact.join(" ") # Extracting "milestones" from "...[milestones_attributes][...]" md = object_name.to_s.match /(\w+)_attributes\](?:\[[\w\d]+\])?$/ ...
ruby
{ "resource": "" }
q16861
Lyp.DependencyResolver.resolve_tree
train
def resolve_tree permutations = permutate_simplified_tree permutations = filter_invalid_permutations(permutations) # select highest versioned dependencies (for those specified by user) user_deps = tree.dependencies.keys result = select_highest_versioned_permutation(permutations, user_deps...
ruby
{ "resource": "" }
q16862
Lyp.DependencyResolver.dependencies_array
train
def dependencies_array(leaf, processed = {}) return processed[leaf] if processed[leaf] deps_array = [] processed[leaf] = deps_array leaf.each do |pack, versions| a = [] versions.each do |version, deps| perms = [] sub_perms = dependencies_array(deps, processe...
ruby
{ "resource": "" }
q16863
Lyp.DependencyResolver.filter_invalid_permutations
train
def filter_invalid_permutations(permutations) valid = [] permutations.each do |perm| versions = {}; invalid = false perm.each do |ref| if ref =~ /(.+)@(.+)/ name, version = $1, $2 if versions[name] && versions[name] != version invalid = true ...
ruby
{ "resource": "" }
q16864
Lyp.DependencyResolver.select_highest_versioned_permutation
train
def select_highest_versioned_permutation(permutations, user_deps) sorted = sort_permutations(permutations, user_deps) sorted.empty? ? [] : sorted.last end
ruby
{ "resource": "" }
q16865
Lyp.DependencyResolver.sort_permutations
train
def sort_permutations(permutations, user_deps) # Cache for versions converted to Gem::Version instances versions = {} map = lambda do |m, p| if p =~ Lyp::PACKAGE_RE m[$1] = versions[p] ||= (Lyp.version($2 || '0.0') rescue nil) end m end compare = lambda ...
ruby
{ "resource": "" }
q16866
Lyp.DependencyResolver.find_matching_packages
train
def find_matching_packages(req) return {} unless req =~ Lyp::PACKAGE_RE req_package = $1 req_version = $2 req = nil if @opts[:forced_package_paths] && @opts[:forced_package_paths][req_package] req_version = 'forced' end req = Lyp.version_req(req_version || '>=0') res...
ruby
{ "resource": "" }
q16867
Lyp.DependencyResolver.find_package_versions
train
def find_package_versions(ref, leaf, location) return {} unless ref =~ Lyp::PACKAGE_RE ref_package = $1 version_clause = $2 matches = find_matching_packages(ref) # Raise if no match found and we're at top of the tree if matches.empty? && (leaf == tree) && !opts[:ignore_missing] ...
ruby
{ "resource": "" }
q16868
Lyp.DependencyResolver.squash_old_versions
train
def squash_old_versions specifiers = map_specifiers_to_versions compare_versions = lambda do |x, y| v_x = x =~ Lyp::PACKAGE_RE && Lyp.version($2) v_y = y =~ Lyp::PACKAGE_RE && Lyp.version($2) x <=> y end specifiers.each do |package, clauses| # Remove old version...
ruby
{ "resource": "" }
q16869
Lyp.DependencyResolver.map_specifiers_to_versions
train
def map_specifiers_to_versions specifiers = {} processed = {} l = lambda do |t| return if processed[t.object_id] processed[t.object_id] = true t.dependencies.each do |package, spec| specifiers[package] ||= {} specifiers[package][spec.clause] ||= [] ...
ruby
{ "resource": "" }
q16870
Lyp.DependencyResolver.remove_unfulfilled_dependencies
train
def remove_unfulfilled_dependencies(leaf, raise_on_missing = true, processed = {}) tree.dependencies.each do |package, dependency| dependency.versions.select! do |version, leaf| if processed[version] true else processed[version] = true # Remove unfu...
ruby
{ "resource": "" }
q16871
Airbrake.FilterChain.add_filter
train
def add_filter(filter) @filters = (@filters << filter).sort_by do |f| f.respond_to?(:weight) ? f.weight : DEFAULT_WEIGHT end.reverse! end
ruby
{ "resource": "" }
q16872
Airbrake.FilterChain.delete_filter
train
def delete_filter(filter_class) index = @filters.index { |f| f.class.name == filter_class.name } @filters.delete_at(index) if index end
ruby
{ "resource": "" }
q16873
Airbrake.Truncator.replace_invalid_characters
train
def replace_invalid_characters(str) encoding = str.encoding utf8_string = (encoding == Encoding::UTF_8 || encoding == Encoding::ASCII) return str if utf8_string && str.valid_encoding? temp_str = str.dup temp_str.encode!(TEMP_ENCODING, ENCODING_OPTIONS) if utf8_string temp_str.encode...
ruby
{ "resource": "" }
q16874
Airbrake.AsyncSender.send
train
def send(notice, promise) return will_not_deliver(notice) if @unsent.size >= @unsent.max @unsent << [notice, promise] promise end
ruby
{ "resource": "" }
q16875
Airbrake.Notice.[]=
train
def []=(key, value) raise_if_ignored unless WRITABLE_KEYS.include?(key) raise Airbrake::Error, ":#{key} is not recognized among #{WRITABLE_KEYS}" end unless value.respond_to?(:to_hash) raise Airbrake::Error, "Got #{value.class} value, wanted a Hash" end ...
ruby
{ "resource": "" }
q16876
Danger.DangerSwiftlint.run_swiftlint
train
def run_swiftlint(files, lint_all_files, options, additional_swiftlint_args) if lint_all_files result = swiftlint.lint(options, additional_swiftlint_args) if result == '' {} else JSON.parse(result).flatten end else files .map { |file| opt...
ruby
{ "resource": "" }
q16877
Danger.DangerSwiftlint.find_swift_files
train
def find_swift_files(dir_selected, files = nil, excluded_paths = [], included_paths = []) # Needs to be escaped before comparsion with escaped file paths dir_selected = Shellwords.escape(dir_selected) # Assign files to lint files = if files.nil? (git.modified_files - git.deleted...
ruby
{ "resource": "" }
q16878
Danger.DangerSwiftlint.load_config
train
def load_config(filepath) return {} if filepath.nil? || !File.exist?(filepath) config_file = File.open(filepath).read # Replace environment variables config_file = parse_environment_variables(config_file) YAML.safe_load(config_file) end
ruby
{ "resource": "" }
q16879
Danger.DangerSwiftlint.parse_environment_variables
train
def parse_environment_variables(file_contents) # Matches the file contents for environment variables defined like ${VAR_NAME}. # Replaces them with the environment variable value if it exists. file_contents.gsub(/\$\{([^{}]+)\}/) do |env_var| return env_var if ENV[Regexp.last_match[1]].nil? ...
ruby
{ "resource": "" }
q16880
Danger.DangerSwiftlint.file_exists?
train
def file_exists?(paths, file) paths.any? do |path| Find.find(path) .map { |path_file| Shellwords.escape(path_file) } .include?(file) end end
ruby
{ "resource": "" }
q16881
Danger.DangerSwiftlint.format_paths
train
def format_paths(paths, filepath) # Extract included paths paths .map { |path| File.join(File.dirname(filepath), path) } .map { |path| File.expand_path(path) } .select { |path| File.exist?(path) || Dir.exist?(path) } end
ruby
{ "resource": "" }
q16882
Danger.DangerSwiftlint.markdown_issues
train
def markdown_issues(results, heading) message = "#### #{heading}\n\n".dup message << "File | Line | Reason |\n" message << "| --- | ----- | ----- |\n" results.each do |r| filename = r['file'].split('/').last line = r['line'] reason = r['reason'] rule = r['rule_i...
ruby
{ "resource": "" }
q16883
Pusher.WebHook.check_signature
train
def check_signature(secret) digest = OpenSSL::Digest::SHA256.new expected = OpenSSL::HMAC.hexdigest(digest, secret, @body) if @signature == expected return true else Pusher.logger.warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}" retu...
ruby
{ "resource": "" }
q16884
Pusher.Client.url=
train
def url=(url) uri = URI.parse(url) @scheme = uri.scheme @app_id = uri.path.split('/').last @key = uri.user @secret = uri.password @host = uri.host @port = uri.port end
ruby
{ "resource": "" }
q16885
Pusher.Client.trigger
train
def trigger(channels, event_name, data, params = {}) post('/events', trigger_params(channels, event_name, data, params)) end
ruby
{ "resource": "" }
q16886
Pusher.Channel.trigger
train
def trigger(event_name, data, socket_id = nil) trigger!(event_name, data, socket_id) rescue Pusher::Error => e Pusher.logger.error("#{e.message} (#{e.class})") Pusher.logger.debug(e.backtrace.join("\n")) end
ruby
{ "resource": "" }
q16887
Pusher.Channel.authentication_string
train
def authentication_string(socket_id, custom_string = nil) validate_socket_id(socket_id) unless custom_string.nil? || custom_string.kind_of?(String) raise Error, 'Custom argument must be a string' end string_to_sign = [socket_id, name, custom_string]. compact.map(&:to_s).join(':...
ruby
{ "resource": "" }
q16888
Pageflow.WidgetType.render
train
def render(template, entry) template.render(File.join('pageflow', name, 'widget'), entry: entry) end
ruby
{ "resource": "" }
q16889
Pageflow.AccountRoleQuery.has_at_least_role?
train
def has_at_least_role?(role) @user .memberships .where(role: Roles.at_least(role)) .where('(entity_id = :account_id AND '\ "entity_type = 'Pageflow::Account')", account_id: @account.id) .any? end
ruby
{ "resource": "" }
q16890
Pageflow.HelpEntries.register
train
def register(name, options = {}) help_entry = HelpEntry.new(name, options) @help_entries_by_name[name] = help_entry collection = find_collection(options[:parent]) collection << help_entry collection.sort_by! { |help_entry| -help_entry.priority } end
ruby
{ "resource": "" }
q16891
Twirp.Service.call
train
def call(rack_env) begin env = {} bad_route = route_request(rack_env, env) return error_response(bad_route, env) if bad_route @before.each do |hook| result = hook.call(rack_env, env) return error_response(result, env) if result.is_a? Twirp::Error end ...
ruby
{ "resource": "" }
q16892
Twirp.Service.route_request
train
def route_request(rack_env, env) rack_request = Rack::Request.new(rack_env) if rack_request.request_method != "POST" return bad_route_error("HTTP request method must be POST", rack_request) end content_type = rack_request.get_header("CONTENT_TYPE") if !Encoding.valid_content_type...
ruby
{ "resource": "" }
q16893
Twirp.ServiceDSL.rpc
train
def rpc(rpc_method, input_class, output_class, opts) raise ArgumentError.new("rpc_method can not be empty") if rpc_method.to_s.empty? raise ArgumentError.new("input_class must be a Protobuf Message class") unless input_class.is_a?(Class) raise ArgumentError.new("output_class must be a Protobuf Message...
ruby
{ "resource": "" }
q16894
Launchy.DescendantTracker.find_child
train
def find_child( method, *args ) children.find do |child| Launchy.log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}" child.send( method, *args ) end end
ruby
{ "resource": "" }
q16895
RSpec.LoggingHelper.capture_log_messages
train
def capture_log_messages( opts = {} ) from = opts.fetch(:from, 'root') to = opts.fetch(:to, '__rspec__') exclusive = opts.fetch(:exclusive, true) appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to) logger = Logging::Logger[from] if exclusive logger.appe...
ruby
{ "resource": "" }
q16896
Logging.Repository.parent_name
train
def parent_name( key ) return if :root == key a = key.split PATH_DELIMITER p = :root while a.slice!(-1) and !a.empty? k = a.join PATH_DELIMITER if @h.has_key? k then p = k; break end end p end
ruby
{ "resource": "" }
q16897
Logging::Appenders.RollingFile.build_singleton_methods
train
def build_singleton_methods method = case @age when 'daily' -> { now = Time.now (now.day != age_fn_mtime.day) || (now - age_fn_mtime) > 86400 } when 'weekly' -> { (Time.now - age_fn_mtime) > 604800 } when 'monthly' -...
ruby
{ "resource": "" }
q16898
Logging::Appenders.Buffering.auto_flushing=
train
def auto_flushing=( period ) @auto_flushing = case period when true; 1 when false, nil, 0; DEFAULT_BUFFER_SIZE when Integer; period when String; Integer(period) else raise ArgumentError, "unrecognized auto_...
ruby
{ "resource": "" }
q16899
Logging::Appenders.Buffering._setup_async_flusher
train
def _setup_async_flusher # stop and remove any existing async flusher instance if @async_flusher @async_flusher.stop @async_flusher = nil Thread.pass end # create a new async flusher if we have a valid flush period if @flush_period || async? @auto_flushing ...
ruby
{ "resource": "" }