id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
3,200
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.without
def without(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| !features.subset?(key)}] end
ruby
def without(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| !features.subset?(key)}] end
[ "def", "without", "(", "*", "features", ")", "features", "=", "setify", "(", "features", ")", "self", ".", "class", ".", "new", "Hash", "[", "@sets", ".", "select", "{", "|", "key", ",", "val", "|", "!", "features", ".", "subset?", "(", "key", ")", "}", "]", "end" ]
Return an instance of Sounds whose sets exclude any of the given features.
[ "Return", "an", "instance", "of", "Sounds", "whose", "sets", "exclude", "any", "of", "the", "given", "features", "." ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L65-L68
3,201
norman/phonology
lib/phonology/inventory.rb
Phonology.Inventory.without_any
def without_any(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| key.intersection(features).empty?}] end
ruby
def without_any(*features) features = setify(*features) self.class.new Hash[@sets.select {|key, val| key.intersection(features).empty?}] end
[ "def", "without_any", "(", "*", "features", ")", "features", "=", "setify", "(", "features", ")", "self", ".", "class", ".", "new", "Hash", "[", "@sets", ".", "select", "{", "|", "key", ",", "val", "|", "key", ".", "intersection", "(", "features", ")", ".", "empty?", "}", "]", "end" ]
Return an instance of Sounds whose sets exclude all of the given features.
[ "Return", "an", "instance", "of", "Sounds", "whose", "sets", "exclude", "all", "of", "the", "given", "features", "." ]
910207237aecbcd8e1a464a9148d9b3fd4d1f3e4
https://github.com/norman/phonology/blob/910207237aecbcd8e1a464a9148d9b3fd4d1f3e4/lib/phonology/inventory.rb#L72-L75
3,202
tecfoundary/hicube
app/controllers/hicube/base_controller.rb
Hicube.BaseController.check_resource_params
def check_resource_params(options = {}) # Determine the name based on the current controller if not specified. resource_name = options[:name] || controller_name.singularize # Determine the class based on the resource name if not provided. #FIXME: Do not hardcode engine name resource_class = options[:class] || "Hicube::#{resource_name.singularize.camelize}".classify.constantize unless params.key?(resource_name) notify :error, ::I18n.t('messages.resource.missing_parameters', :type => resource_class.model_name.human ) case action_name.to_sym when :create redirect_to :action => :new when :update redirect_to :action => :edit, :id => params[:id] else redirect_to :action => :index end end end
ruby
def check_resource_params(options = {}) # Determine the name based on the current controller if not specified. resource_name = options[:name] || controller_name.singularize # Determine the class based on the resource name if not provided. #FIXME: Do not hardcode engine name resource_class = options[:class] || "Hicube::#{resource_name.singularize.camelize}".classify.constantize unless params.key?(resource_name) notify :error, ::I18n.t('messages.resource.missing_parameters', :type => resource_class.model_name.human ) case action_name.to_sym when :create redirect_to :action => :new when :update redirect_to :action => :edit, :id => params[:id] else redirect_to :action => :index end end end
[ "def", "check_resource_params", "(", "options", "=", "{", "}", ")", "# Determine the name based on the current controller if not specified.", "resource_name", "=", "options", "[", ":name", "]", "||", "controller_name", ".", "singularize", "# Determine the class based on the resource name if not provided.", "#FIXME: Do not hardcode engine name", "resource_class", "=", "options", "[", ":class", "]", "||", "\"Hicube::#{resource_name.singularize.camelize}\"", ".", "classify", ".", "constantize", "unless", "params", ".", "key?", "(", "resource_name", ")", "notify", ":error", ",", "::", "I18n", ".", "t", "(", "'messages.resource.missing_parameters'", ",", ":type", "=>", "resource_class", ".", "model_name", ".", "human", ")", "case", "action_name", ".", "to_sym", "when", ":create", "redirect_to", ":action", "=>", ":new", "when", ":update", "redirect_to", ":action", "=>", ":edit", ",", ":id", "=>", "params", "[", ":id", "]", "else", "redirect_to", ":action", "=>", ":index", "end", "end", "end" ]
Check resource params are present based on the current controller name.
[ "Check", "resource", "params", "are", "present", "based", "on", "the", "current", "controller", "name", "." ]
57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe
https://github.com/tecfoundary/hicube/blob/57e0e6bd2d6400dd6c7027deaeffbd95a175bbfe/app/controllers/hicube/base_controller.rb#L31-L55
3,203
tsonntag/gitter
lib/gitter/column.rb
Gitter.Column.order_params
def order_params desc = !desc? p = grid.params.dup if ordered? p[:desc] = desc else p = p.merge order: name, desc: desc end grid.scoped_params p end
ruby
def order_params desc = !desc? p = grid.params.dup if ordered? p[:desc] = desc else p = p.merge order: name, desc: desc end grid.scoped_params p end
[ "def", "order_params", "desc", "=", "!", "desc?", "p", "=", "grid", ".", "params", ".", "dup", "if", "ordered?", "p", "[", ":desc", "]", "=", "desc", "else", "p", "=", "p", ".", "merge", "order", ":", "name", ",", "desc", ":", "desc", "end", "grid", ".", "scoped_params", "p", "end" ]
if current params contain order for this column then revert direction else add order_params for this column to current params
[ "if", "current", "params", "contain", "order", "for", "this", "column", "then", "revert", "direction", "else", "add", "order_params", "for", "this", "column", "to", "current", "params" ]
55c79a5d8012129517510d1d1758621f4baf5344
https://github.com/tsonntag/gitter/blob/55c79a5d8012129517510d1d1758621f4baf5344/lib/gitter/column.rb#L126-L134
3,204
faradayio/charisma
lib/charisma/curator.rb
Charisma.Curator.characteristics
def characteristics return @characteristics if @characteristics hsh = Hash.new do |_, key| if characterization = subject.class.characterization[key] Curation.new nil, characterization end end hsh.extend LooseEquality @characteristics = hsh end
ruby
def characteristics return @characteristics if @characteristics hsh = Hash.new do |_, key| if characterization = subject.class.characterization[key] Curation.new nil, characterization end end hsh.extend LooseEquality @characteristics = hsh end
[ "def", "characteristics", "return", "@characteristics", "if", "@characteristics", "hsh", "=", "Hash", ".", "new", "do", "|", "_", ",", "key", "|", "if", "characterization", "=", "subject", ".", "class", ".", "characterization", "[", "key", "]", "Curation", ".", "new", "nil", ",", "characterization", "end", "end", "hsh", ".", "extend", "LooseEquality", "@characteristics", "=", "hsh", "end" ]
Create a Curator. Typically this is done automatically when <tt>#characteristics</tt> is called on an instance of a characterized class for the first time. @param [Object] The subject of the curation -- an instance of a characterized class @see Charisma::Base#characteristics The special hash wrapped by the curator that actually stores the computed characteristics.
[ "Create", "a", "Curator", "." ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/curator.rb#L28-L38
3,205
faradayio/charisma
lib/charisma/curator.rb
Charisma.Curator.[]=
def []=(key, value) characteristics[key] = Curation.new value, subject.class.characterization[key] end
ruby
def []=(key, value) characteristics[key] = Curation.new value, subject.class.characterization[key] end
[ "def", "[]=", "(", "key", ",", "value", ")", "characteristics", "[", "key", "]", "=", "Curation", ".", "new", "value", ",", "subject", ".", "class", ".", "characterization", "[", "key", "]", "end" ]
Store a late-defined characteristic, with a Charisma wrapper. @param [Symbol] key The name of the characteristic, which must match one defined in the class's characterization @param value The value of the characteristic
[ "Store", "a", "late", "-", "defined", "characteristic", "with", "a", "Charisma", "wrapper", "." ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/curator.rb#L43-L45
3,206
jgoizueta/units-system
lib/units/measure.rb
Units.Measure.detailed_units
def detailed_units(all_levels = false) mag = @magnitude prev_units = self.units units = {} loop do compound = false prev_units.each_pair do |dim, (unit,mul)| ud = Units.unit(unit) if ud.decomposition compound = true mag *= ud.decomposition.magnitude ud.decomposition.units.each_pair do |d, (u,m)| mag *= self.class.combine(units, d, u, m*mul) end else mag *= self.class.combine(units, dim, unit, mul) end end if all_levels && compound prev_units = units units = {} else break end end Measure.new mag, units end
ruby
def detailed_units(all_levels = false) mag = @magnitude prev_units = self.units units = {} loop do compound = false prev_units.each_pair do |dim, (unit,mul)| ud = Units.unit(unit) if ud.decomposition compound = true mag *= ud.decomposition.magnitude ud.decomposition.units.each_pair do |d, (u,m)| mag *= self.class.combine(units, d, u, m*mul) end else mag *= self.class.combine(units, dim, unit, mul) end end if all_levels && compound prev_units = units units = {} else break end end Measure.new mag, units end
[ "def", "detailed_units", "(", "all_levels", "=", "false", ")", "mag", "=", "@magnitude", "prev_units", "=", "self", ".", "units", "units", "=", "{", "}", "loop", "do", "compound", "=", "false", "prev_units", ".", "each_pair", "do", "|", "dim", ",", "(", "unit", ",", "mul", ")", "|", "ud", "=", "Units", ".", "unit", "(", "unit", ")", "if", "ud", ".", "decomposition", "compound", "=", "true", "mag", "*=", "ud", ".", "decomposition", ".", "magnitude", "ud", ".", "decomposition", ".", "units", ".", "each_pair", "do", "|", "d", ",", "(", "u", ",", "m", ")", "|", "mag", "*=", "self", ".", "class", ".", "combine", "(", "units", ",", "d", ",", "u", ",", "m", "mul", ")", "end", "else", "mag", "*=", "self", ".", "class", ".", "combine", "(", "units", ",", "dim", ",", "unit", ",", "mul", ")", "end", "end", "if", "all_levels", "&&", "compound", "prev_units", "=", "units", "units", "=", "{", "}", "else", "break", "end", "end", "Measure", ".", "new", "mag", ",", "units", "end" ]
decompose compound units
[ "decompose", "compound", "units" ]
7e9ee9fe217e399ef1950337a75be5a7473dff2a
https://github.com/jgoizueta/units-system/blob/7e9ee9fe217e399ef1950337a75be5a7473dff2a/lib/units/measure.rb#L87-L113
3,207
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert
def insert(text) raise "must be passed string" unless text.is_a?(String) snippet = Snippet.new_text(core, text) snippet.snippet_tags.each do |tag_info| visit tag_info[:tag] end context = Context.new(nil) insert_func(snippet, context).join($/) end
ruby
def insert(text) raise "must be passed string" unless text.is_a?(String) snippet = Snippet.new_text(core, text) snippet.snippet_tags.each do |tag_info| visit tag_info[:tag] end context = Context.new(nil) insert_func(snippet, context).join($/) end
[ "def", "insert", "(", "text", ")", "raise", "\"must be passed string\"", "unless", "text", ".", "is_a?", "(", "String", ")", "snippet", "=", "Snippet", ".", "new_text", "(", "core", ",", "text", ")", "snippet", ".", "snippet_tags", ".", "each", "do", "|", "tag_info", "|", "visit", "tag_info", "[", ":tag", "]", "end", "context", "=", "Context", ".", "new", "(", "nil", ")", "insert_func", "(", "snippet", ",", "context", ")", ".", "join", "(", "$/", ")", "end" ]
Insert snippets to given text @param text [String] The text of source code
[ "Insert", "snippets", "to", "given", "text" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L67-L77
3,208
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert_by_tag_and_context!
def insert_by_tag_and_context!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) src = insert_func(snippet, context, tag) options[:margin_top].times { inserter.insert "" } # @snip -> @snippet inserter.insert tag.to_snippet_tag unless snippet.no_tag? # insert snippet text inserter.insert src options[:margin_bottom].times { inserter.insert "" } visit tag end
ruby
def insert_by_tag_and_context!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) src = insert_func(snippet, context, tag) options[:margin_top].times { inserter.insert "" } # @snip -> @snippet inserter.insert tag.to_snippet_tag unless snippet.no_tag? # insert snippet text inserter.insert src options[:margin_bottom].times { inserter.insert "" } visit tag end
[ "def", "insert_by_tag_and_context!", "(", "inserter", ",", "snippet", ",", "context", ",", "tag", ")", "raise", "\"must be passed snippet\"", "unless", "snippet", ".", "is_a?", "(", "Snippet", ")", "src", "=", "insert_func", "(", "snippet", ",", "context", ",", "tag", ")", "options", "[", ":margin_top", "]", ".", "times", "{", "inserter", ".", "insert", "\"\"", "}", "# @snip -> @snippet", "inserter", ".", "insert", "tag", ".", "to_snippet_tag", "unless", "snippet", ".", "no_tag?", "# insert snippet text", "inserter", ".", "insert", "src", "options", "[", ":margin_bottom", "]", ".", "times", "{", "inserter", ".", "insert", "\"\"", "}", "visit", "tag", "end" ]
Insert snippet by tag and context
[ "Insert", "snippet", "by", "tag", "and", "context" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L104-L117
3,209
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.insert_depended_snippets!
def insert_depended_snippets!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) dep_tags = deps_resolver.find(snippet, context, tag) dep_tags = sort_dep_tags_by_dep(dep_tags) dep_tags.each do |tag_info| sub_t = tag_info[:tag] sub_c = tag_info[:context] resolve_tag_repo_ref! sub_t visit(tag) if is_self(sub_t, sub_c) next if is_visited(sub_t) next_snippet = core.repo_manager.get_snippet(sub_c, sub_t) insert_by_tag_and_context! inserter, next_snippet, sub_c, sub_t end end
ruby
def insert_depended_snippets!(inserter, snippet, context, tag) raise "must be passed snippet" unless snippet.is_a?(Snippet) dep_tags = deps_resolver.find(snippet, context, tag) dep_tags = sort_dep_tags_by_dep(dep_tags) dep_tags.each do |tag_info| sub_t = tag_info[:tag] sub_c = tag_info[:context] resolve_tag_repo_ref! sub_t visit(tag) if is_self(sub_t, sub_c) next if is_visited(sub_t) next_snippet = core.repo_manager.get_snippet(sub_c, sub_t) insert_by_tag_and_context! inserter, next_snippet, sub_c, sub_t end end
[ "def", "insert_depended_snippets!", "(", "inserter", ",", "snippet", ",", "context", ",", "tag", ")", "raise", "\"must be passed snippet\"", "unless", "snippet", ".", "is_a?", "(", "Snippet", ")", "dep_tags", "=", "deps_resolver", ".", "find", "(", "snippet", ",", "context", ",", "tag", ")", "dep_tags", "=", "sort_dep_tags_by_dep", "(", "dep_tags", ")", "dep_tags", ".", "each", "do", "|", "tag_info", "|", "sub_t", "=", "tag_info", "[", ":tag", "]", "sub_c", "=", "tag_info", "[", ":context", "]", "resolve_tag_repo_ref!", "sub_t", "visit", "(", "tag", ")", "if", "is_self", "(", "sub_t", ",", "sub_c", ")", "next", "if", "is_visited", "(", "sub_t", ")", "next_snippet", "=", "core", ".", "repo_manager", ".", "get_snippet", "(", "sub_c", ",", "sub_t", ")", "insert_by_tag_and_context!", "inserter", ",", "next_snippet", ",", "sub_c", ",", "sub_t", "end", "end" ]
Insert depended snippet
[ "Insert", "depended", "snippet" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L120-L137
3,210
social-snippet/social-snippet
lib/social_snippet/resolvers/insert_resolver.rb
SocialSnippet.Resolvers::InsertResolver.sort_dep_tags_by_dep
def sort_dep_tags_by_dep(dep_tags) dep_tags_index = {} # map tag to index dep_tags.each.with_index do |tag_info, k| tag = tag_info[:tag] dep_tags_index[tag.to_path] = k end # generate dependency graph dep_tags_hash = TSortableHash.new dep_tags.each do |tag_info| tag = tag_info[:tag].to_path dep_ind = dep_tags_index[tag] dep_tags_hash[dep_ind] = deps_resolver.dep_to[tag].to_a.map {|tag| dep_tags_index[tag] }.reject(&:nil?) end dep_tags_hash.tsort.map {|k| dep_tags[k] } end
ruby
def sort_dep_tags_by_dep(dep_tags) dep_tags_index = {} # map tag to index dep_tags.each.with_index do |tag_info, k| tag = tag_info[:tag] dep_tags_index[tag.to_path] = k end # generate dependency graph dep_tags_hash = TSortableHash.new dep_tags.each do |tag_info| tag = tag_info[:tag].to_path dep_ind = dep_tags_index[tag] dep_tags_hash[dep_ind] = deps_resolver.dep_to[tag].to_a.map {|tag| dep_tags_index[tag] }.reject(&:nil?) end dep_tags_hash.tsort.map {|k| dep_tags[k] } end
[ "def", "sort_dep_tags_by_dep", "(", "dep_tags", ")", "dep_tags_index", "=", "{", "}", "# map tag to index", "dep_tags", ".", "each", ".", "with_index", "do", "|", "tag_info", ",", "k", "|", "tag", "=", "tag_info", "[", ":tag", "]", "dep_tags_index", "[", "tag", ".", "to_path", "]", "=", "k", "end", "# generate dependency graph", "dep_tags_hash", "=", "TSortableHash", ".", "new", "dep_tags", ".", "each", "do", "|", "tag_info", "|", "tag", "=", "tag_info", "[", ":tag", "]", ".", "to_path", "dep_ind", "=", "dep_tags_index", "[", "tag", "]", "dep_tags_hash", "[", "dep_ind", "]", "=", "deps_resolver", ".", "dep_to", "[", "tag", "]", ".", "to_a", ".", "map", "{", "|", "tag", "|", "dep_tags_index", "[", "tag", "]", "}", ".", "reject", "(", ":nil?", ")", "end", "dep_tags_hash", ".", "tsort", ".", "map", "{", "|", "k", "|", "dep_tags", "[", "k", "]", "}", "end" ]
Sort by dependency
[ "Sort", "by", "dependency" ]
46ae25b3e8ced2c8b5b4923ed9e1a019c9835367
https://github.com/social-snippet/social-snippet/blob/46ae25b3e8ced2c8b5b4923ed9e1a019c9835367/lib/social_snippet/resolvers/insert_resolver.rb#L140-L158
3,211
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.create
def create(label) create_atomic(label.to_s) or create_composite(label.to_s) or raise MeasurementError.new("Unit '#{label}' not found") end
ruby
def create(label) create_atomic(label.to_s) or create_composite(label.to_s) or raise MeasurementError.new("Unit '#{label}' not found") end
[ "def", "create", "(", "label", ")", "create_atomic", "(", "label", ".", "to_s", ")", "or", "create_composite", "(", "label", ".", "to_s", ")", "or", "raise", "MeasurementError", ".", "new", "(", "\"Unit '#{label}' not found\"", ")", "end" ]
Returns the unit with the given label. Creates a new unit if necessary. Raises MeasurementError if the unit could not be created.
[ "Returns", "the", "unit", "with", "the", "given", "label", ".", "Creates", "a", "new", "unit", "if", "necessary", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L14-L16
3,212
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.slice_atomic_unit
def slice_atomic_unit(str) label = '' str.scan(/_?[^_]+/) do |chunk| label << chunk unit = create_atomic(label) return label, unit if unit end raise MeasurementError.new("Unit '#{str}' not found") end
ruby
def slice_atomic_unit(str) label = '' str.scan(/_?[^_]+/) do |chunk| label << chunk unit = create_atomic(label) return label, unit if unit end raise MeasurementError.new("Unit '#{str}' not found") end
[ "def", "slice_atomic_unit", "(", "str", ")", "label", "=", "''", "str", ".", "scan", "(", "/", "/", ")", "do", "|", "chunk", "|", "label", "<<", "chunk", "unit", "=", "create_atomic", "(", "label", ")", "return", "label", ",", "unit", "if", "unit", "end", "raise", "MeasurementError", ".", "new", "(", "\"Unit '#{str}' not found\"", ")", "end" ]
Returns the Unit which matches the str prefix. Raises MeasurementError if the unit could not be determined.
[ "Returns", "the", "Unit", "which", "matches", "the", "str", "prefix", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L69-L77
3,213
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.match_scalar
def match_scalar(label) label = label.to_sym Factor.detect do |factor| return factor if factor.label == label or factor.abbreviation == label end end
ruby
def match_scalar(label) label = label.to_sym Factor.detect do |factor| return factor if factor.label == label or factor.abbreviation == label end end
[ "def", "match_scalar", "(", "label", ")", "label", "=", "label", ".", "to_sym", "Factor", ".", "detect", "do", "|", "factor", "|", "return", "factor", "if", "factor", ".", "label", "==", "label", "or", "factor", ".", "abbreviation", "==", "label", "end", "end" ]
Returns the Factor which matches the label, or nil if no match.
[ "Returns", "the", "Factor", "which", "matches", "the", "label", "or", "nil", "if", "no", "match", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L132-L137
3,214
caruby/uom
lib/uom/unit_factory.rb
UOM.UnitFactory.suffix?
def suffix?(suffix, text) len = suffix.length len <= text.length and suffix == text[-len, len] end
ruby
def suffix?(suffix, text) len = suffix.length len <= text.length and suffix == text[-len, len] end
[ "def", "suffix?", "(", "suffix", ",", "text", ")", "len", "=", "suffix", ".", "length", "len", "<=", "text", ".", "length", "and", "suffix", "==", "text", "[", "-", "len", ",", "len", "]", "end" ]
Returns whether text ends in suffix.
[ "Returns", "whether", "text", "ends", "in", "suffix", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/unit_factory.rb#L140-L143
3,215
akerl/octoauth
lib/octoauth/configfile.rb
Octoauth.ConfigFile.write
def write new = get new[@note] = @token File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml } end
ruby
def write new = get new[@note] = @token File.open(@file, 'w', 0o0600) { |fh| fh.write new.to_yaml } end
[ "def", "write", "new", "=", "get", "new", "[", "@note", "]", "=", "@token", "File", ".", "open", "(", "@file", ",", "'w'", ",", "0o0600", ")", "{", "|", "fh", "|", "fh", ".", "write", "new", ".", "to_yaml", "}", "end" ]
Create new Config object, either ephemerally or from a file
[ "Create", "new", "Config", "object", "either", "ephemerally", "or", "from", "a", "file" ]
160bf0e86d82ce63a39e3c4b28abc429c5ea7aa9
https://github.com/akerl/octoauth/blob/160bf0e86d82ce63a39e3c4b28abc429c5ea7aa9/lib/octoauth/configfile.rb#L27-L31
3,216
KPB-US/swhd-api
lib/swhd_api.rb
SwhdApi.Manager.fetch
def fetch(resource, params = {}) method = :get page = 1 params[:page] = page partial = request(resource, method, params) while partial.is_a?(Array) && !partial.empty? results ||= [] results += partial page += 1 params[:page] = page partial = request(resource, method, params) end results = partial unless partial.nil? || partial.empty? results end
ruby
def fetch(resource, params = {}) method = :get page = 1 params[:page] = page partial = request(resource, method, params) while partial.is_a?(Array) && !partial.empty? results ||= [] results += partial page += 1 params[:page] = page partial = request(resource, method, params) end results = partial unless partial.nil? || partial.empty? results end
[ "def", "fetch", "(", "resource", ",", "params", "=", "{", "}", ")", "method", "=", ":get", "page", "=", "1", "params", "[", ":page", "]", "=", "page", "partial", "=", "request", "(", "resource", ",", "method", ",", "params", ")", "while", "partial", ".", "is_a?", "(", "Array", ")", "&&", "!", "partial", ".", "empty?", "results", "||=", "[", "]", "results", "+=", "partial", "page", "+=", "1", "params", "[", ":page", "]", "=", "page", "partial", "=", "request", "(", "resource", ",", "method", ",", "params", ")", "end", "results", "=", "partial", "unless", "partial", ".", "nil?", "||", "partial", ".", "empty?", "results", "end" ]
fetch all pages of results
[ "fetch", "all", "pages", "of", "results" ]
f4cd031d4ace7253d8e1943a81eb300121eb4f68
https://github.com/KPB-US/swhd-api/blob/f4cd031d4ace7253d8e1943a81eb300121eb4f68/lib/swhd_api.rb#L84-L100
3,217
ManojmoreS/mores_marvel
lib/mores_marvel/resource.rb
MoresMarvel.Resource.fetch_by_id
def fetch_by_id(model, id, filters = {}) get_resource("/v1/public/#{model}/#{id}", filters) if model_exists?(model) && validate_filters(filters) end
ruby
def fetch_by_id(model, id, filters = {}) get_resource("/v1/public/#{model}/#{id}", filters) if model_exists?(model) && validate_filters(filters) end
[ "def", "fetch_by_id", "(", "model", ",", "id", ",", "filters", "=", "{", "}", ")", "get_resource", "(", "\"/v1/public/#{model}/#{id}\"", ",", "filters", ")", "if", "model_exists?", "(", "model", ")", "&&", "validate_filters", "(", "filters", ")", "end" ]
fetch a record by id
[ "fetch", "a", "record", "by", "id" ]
b14b1305b51e311ca10ad1c1462361f6e04a95e5
https://github.com/ManojmoreS/mores_marvel/blob/b14b1305b51e311ca10ad1c1462361f6e04a95e5/lib/mores_marvel/resource.rb#L12-L14
3,218
void-main/tily.rb
lib/tily.rb
Tily.Tily.processing_hint_str
def processing_hint_str number, level total = (@ts.tile_size(level) ** 2).to_s now = (number + 1).to_s.rjust(total.length, " ") "#{now}/#{total}" end
ruby
def processing_hint_str number, level total = (@ts.tile_size(level) ** 2).to_s now = (number + 1).to_s.rjust(total.length, " ") "#{now}/#{total}" end
[ "def", "processing_hint_str", "number", ",", "level", "total", "=", "(", "@ts", ".", "tile_size", "(", "level", ")", "**", "2", ")", ".", "to_s", "now", "=", "(", "number", "+", "1", ")", ".", "to_s", ".", "rjust", "(", "total", ".", "length", ",", "\" \"", ")", "\"#{now}/#{total}\"", "end" ]
Format a beautiful hint string
[ "Format", "a", "beautiful", "hint", "string" ]
5ff21e172ef0d62eaea59573aa429522080ae326
https://github.com/void-main/tily.rb/blob/5ff21e172ef0d62eaea59573aa429522080ae326/lib/tily.rb#L64-L68
3,219
ad2games/soapy_cake
lib/soapy_cake/campaigns.rb
SoapyCake.Campaigns.patch
def patch(campaign_id, opts = {}) campaign = get(campaign_id: campaign_id).first opts = NO_CHANGE_VALUES .merge( affiliate_id: campaign.fetch(:affiliate).fetch(:affiliate_id), media_type_id: campaign.fetch(:media_type).fetch(:media_type_id), offer_contract_id: campaign.fetch(:offer_contract).fetch(:offer_contract_id), offer_id: campaign.fetch(:offer).fetch(:offer_id), payout: campaign.fetch(:payout).fetch(:amount), payout_update_option: 'do_not_change', pixel_html: campaign.dig(:pixel_info, :pixel_html) || '', postback_url: campaign.dig(:pixel_info, :postback_url) || '', redirect_domain: campaign.fetch(:redirect_domain, ''), test_link: campaign[:test_link] || '', unique_key_hash: campaign.dig(:pixel_info, :hash_type, :hash_type_id) || 'none', third_party_name: campaign.fetch(:third_party_name, '') ) .merge(opts) update(campaign_id, opts) nil end
ruby
def patch(campaign_id, opts = {}) campaign = get(campaign_id: campaign_id).first opts = NO_CHANGE_VALUES .merge( affiliate_id: campaign.fetch(:affiliate).fetch(:affiliate_id), media_type_id: campaign.fetch(:media_type).fetch(:media_type_id), offer_contract_id: campaign.fetch(:offer_contract).fetch(:offer_contract_id), offer_id: campaign.fetch(:offer).fetch(:offer_id), payout: campaign.fetch(:payout).fetch(:amount), payout_update_option: 'do_not_change', pixel_html: campaign.dig(:pixel_info, :pixel_html) || '', postback_url: campaign.dig(:pixel_info, :postback_url) || '', redirect_domain: campaign.fetch(:redirect_domain, ''), test_link: campaign[:test_link] || '', unique_key_hash: campaign.dig(:pixel_info, :hash_type, :hash_type_id) || 'none', third_party_name: campaign.fetch(:third_party_name, '') ) .merge(opts) update(campaign_id, opts) nil end
[ "def", "patch", "(", "campaign_id", ",", "opts", "=", "{", "}", ")", "campaign", "=", "get", "(", "campaign_id", ":", "campaign_id", ")", ".", "first", "opts", "=", "NO_CHANGE_VALUES", ".", "merge", "(", "affiliate_id", ":", "campaign", ".", "fetch", "(", ":affiliate", ")", ".", "fetch", "(", ":affiliate_id", ")", ",", "media_type_id", ":", "campaign", ".", "fetch", "(", ":media_type", ")", ".", "fetch", "(", ":media_type_id", ")", ",", "offer_contract_id", ":", "campaign", ".", "fetch", "(", ":offer_contract", ")", ".", "fetch", "(", ":offer_contract_id", ")", ",", "offer_id", ":", "campaign", ".", "fetch", "(", ":offer", ")", ".", "fetch", "(", ":offer_id", ")", ",", "payout", ":", "campaign", ".", "fetch", "(", ":payout", ")", ".", "fetch", "(", ":amount", ")", ",", "payout_update_option", ":", "'do_not_change'", ",", "pixel_html", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":pixel_html", ")", "||", "''", ",", "postback_url", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":postback_url", ")", "||", "''", ",", "redirect_domain", ":", "campaign", ".", "fetch", "(", ":redirect_domain", ",", "''", ")", ",", "test_link", ":", "campaign", "[", ":test_link", "]", "||", "''", ",", "unique_key_hash", ":", "campaign", ".", "dig", "(", ":pixel_info", ",", ":hash_type", ",", ":hash_type_id", ")", "||", "'none'", ",", "third_party_name", ":", "campaign", ".", "fetch", "(", ":third_party_name", ",", "''", ")", ")", ".", "merge", "(", "opts", ")", "update", "(", "campaign_id", ",", "opts", ")", "nil", "end" ]
The default for `display_link_type_id` is "Fallback" in Cake, which doesn't have an ID and, hence, cannot be set via the API. In order to not change it, it has to be absent from the request.
[ "The", "default", "for", "display_link_type_id", "is", "Fallback", "in", "Cake", "which", "doesn", "t", "have", "an", "ID", "and", "hence", "cannot", "be", "set", "via", "the", "API", ".", "In", "order", "to", "not", "change", "it", "it", "has", "to", "be", "absent", "from", "the", "request", "." ]
1120e0f645cfbe8f74ad08038cc7d77d6dcf1d05
https://github.com/ad2games/soapy_cake/blob/1120e0f645cfbe8f74ad08038cc7d77d6dcf1d05/lib/soapy_cake/campaigns.rb#L60-L80
3,220
ManaManaFramework/manamana
lib/manamana/steps.rb
ManaMana.Steps.call
def call(step_name) vars = nil step = steps.find { |s| vars = s[:pattern].match(step_name) } raise "Undefined step '#{ step_name }'" unless step if vars.length > 1 step[:block].call(*vars[1..-1]) else step[:block].call end end
ruby
def call(step_name) vars = nil step = steps.find { |s| vars = s[:pattern].match(step_name) } raise "Undefined step '#{ step_name }'" unless step if vars.length > 1 step[:block].call(*vars[1..-1]) else step[:block].call end end
[ "def", "call", "(", "step_name", ")", "vars", "=", "nil", "step", "=", "steps", ".", "find", "{", "|", "s", "|", "vars", "=", "s", "[", ":pattern", "]", ".", "match", "(", "step_name", ")", "}", "raise", "\"Undefined step '#{ step_name }'\"", "unless", "step", "if", "vars", ".", "length", ">", "1", "step", "[", ":block", "]", ".", "call", "(", "vars", "[", "1", "..", "-", "1", "]", ")", "else", "step", "[", ":block", "]", ".", "call", "end", "end" ]
The step_name variable below is a string that may or may not match the regex pattern of one of the hashes in the steps array.
[ "The", "step_name", "variable", "below", "is", "a", "string", "that", "may", "or", "may", "not", "match", "the", "regex", "pattern", "of", "one", "of", "the", "hashes", "in", "the", "steps", "array", "." ]
af7c0715c2b28d1220cfaee2a2fec8f008e37e36
https://github.com/ManaManaFramework/manamana/blob/af7c0715c2b28d1220cfaee2a2fec8f008e37e36/lib/manamana/steps.rb#L29-L40
3,221
martinemde/gitable
lib/gitable/uri.rb
Gitable.URI.equivalent?
def equivalent?(other_uri) other = Gitable::URI.parse_when_valid(other_uri) return false unless other return false unless normalized_host.to_s == other.normalized_host.to_s if github? || bitbucket? # github doesn't care about relative vs absolute paths in scp uris org_project == other.org_project else # if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match). normalized_path.sub(/\/$/,'') == other.normalized_path.sub(/\/$/,'') && (path[0] == '/' || normalized_user == other.normalized_user) end end
ruby
def equivalent?(other_uri) other = Gitable::URI.parse_when_valid(other_uri) return false unless other return false unless normalized_host.to_s == other.normalized_host.to_s if github? || bitbucket? # github doesn't care about relative vs absolute paths in scp uris org_project == other.org_project else # if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match). normalized_path.sub(/\/$/,'') == other.normalized_path.sub(/\/$/,'') && (path[0] == '/' || normalized_user == other.normalized_user) end end
[ "def", "equivalent?", "(", "other_uri", ")", "other", "=", "Gitable", "::", "URI", ".", "parse_when_valid", "(", "other_uri", ")", "return", "false", "unless", "other", "return", "false", "unless", "normalized_host", ".", "to_s", "==", "other", ".", "normalized_host", ".", "to_s", "if", "github?", "||", "bitbucket?", "# github doesn't care about relative vs absolute paths in scp uris", "org_project", "==", "other", ".", "org_project", "else", "# if the path is absolute, we can assume it's the same for all users (so the user doesn't have to match).", "normalized_path", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "==", "other", ".", "normalized_path", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "&&", "(", "path", "[", "0", "]", "==", "'/'", "||", "normalized_user", "==", "other", ".", "normalized_user", ")", "end", "end" ]
Detect if two URIs are equivalent versions of the same uri. When both uris are github repositories, uses a more lenient matching system is used that takes github's repository organization into account. For non-github URIs this method requires the two URIs to have the same host, equivalent paths, and either the same user or an absolute path. @return [Boolean] true if the URI probably indicates the same repository.
[ "Detect", "if", "two", "URIs", "are", "equivalent", "versions", "of", "the", "same", "uri", "." ]
5005bf9056b86c96373e92879a14083b667fe7be
https://github.com/martinemde/gitable/blob/5005bf9056b86c96373e92879a14083b667fe7be/lib/gitable/uri.rb#L199-L212
3,222
barcoo/rworkflow
lib/rworkflow/flow.rb
Rworkflow.Flow.counters!
def counters! the_counters = { processing: 0 } names = @lifecycle.states.keys results = RedisRds::Object.connection.multi do self.class::STATES_TERMINAL.each { |name| get_list(name).size } names.each { |name| get_list(name).size } @processing.getall end (self.class::STATES_TERMINAL + names).each do |name| the_counters[name] = results.shift.to_i end the_counters[:processing] = results.shift.reduce(0) { |sum, pair| sum + pair.last.to_i } return the_counters end
ruby
def counters! the_counters = { processing: 0 } names = @lifecycle.states.keys results = RedisRds::Object.connection.multi do self.class::STATES_TERMINAL.each { |name| get_list(name).size } names.each { |name| get_list(name).size } @processing.getall end (self.class::STATES_TERMINAL + names).each do |name| the_counters[name] = results.shift.to_i end the_counters[:processing] = results.shift.reduce(0) { |sum, pair| sum + pair.last.to_i } return the_counters end
[ "def", "counters!", "the_counters", "=", "{", "processing", ":", "0", "}", "names", "=", "@lifecycle", ".", "states", ".", "keys", "results", "=", "RedisRds", "::", "Object", ".", "connection", ".", "multi", "do", "self", ".", "class", "::", "STATES_TERMINAL", ".", "each", "{", "|", "name", "|", "get_list", "(", "name", ")", ".", "size", "}", "names", ".", "each", "{", "|", "name", "|", "get_list", "(", "name", ")", ".", "size", "}", "@processing", ".", "getall", "end", "(", "self", ".", "class", "::", "STATES_TERMINAL", "+", "names", ")", ".", "each", "do", "|", "name", "|", "the_counters", "[", "name", "]", "=", "results", ".", "shift", ".", "to_i", "end", "the_counters", "[", ":processing", "]", "=", "results", ".", "shift", ".", "reduce", "(", "0", ")", "{", "|", "sum", ",", "pair", "|", "sum", "+", "pair", ".", "last", ".", "to_i", "}", "return", "the_counters", "end" ]
fetches counters atomically
[ "fetches", "counters", "atomically" ]
1dccaabd47144c846e3d87e65c11ee056ae597a1
https://github.com/barcoo/rworkflow/blob/1dccaabd47144c846e3d87e65c11ee056ae597a1/lib/rworkflow/flow.rb#L107-L124
3,223
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.link_to_previous_page
def link_to_previous_page(scope, name, options = {}, &block) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.prev_page.present?, name, prev_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'prev') do block.call if block end end
ruby
def link_to_previous_page(scope, name, options = {}, &block) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.prev_page.present?, name, prev_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'prev') do block.call if block end end
[ "def", "link_to_previous_page", "(", "scope", ",", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "prev_page", "=", "Kaminari", "::", "Helpers", "::", "PrevPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "link_to_if", "scope", ".", "prev_page", ".", "present?", ",", "name", ",", "prev_page", ".", "url", ",", "options", ".", "except", "(", ":params", ",", ":param_name", ")", ".", "reverse_merge", "(", ":rel", "=>", "'prev'", ")", "do", "block", ".", "call", "if", "block", "end", "end" ]
A simple "Twitter like" pagination link that creates a link to the previous page. ==== Examples Basic usage: <%= link_to_previous_page @items, 'Previous Page' %> Ajax: <%= link_to_previous_page @items, 'Previous Page', :remote => true %> By default, it renders nothing if there are no more results on the previous page. You can customize this output by passing a block. <%= link_to_previous_page @users, 'Previous Page' do %> <span>At the Beginning</span> <% end %>
[ "A", "simple", "Twitter", "like", "pagination", "link", "that", "creates", "a", "link", "to", "the", "previous", "page", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L42-L48
3,224
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.link_to_next_page
def link_to_next_page(scope, name, options = {}, &block) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.next_page.present?, name, next_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'next') do block.call if block end end
ruby
def link_to_next_page(scope, name, options = {}, &block) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) link_to_if scope.next_page.present?, name, next_page.url, options.except(:params, :param_name).reverse_merge(:rel => 'next') do block.call if block end end
[ "def", "link_to_next_page", "(", "scope", ",", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "next_page", "=", "Kaminari", "::", "Helpers", "::", "NextPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "link_to_if", "scope", ".", "next_page", ".", "present?", ",", "name", ",", "next_page", ".", "url", ",", "options", ".", "except", "(", ":params", ",", ":param_name", ")", ".", "reverse_merge", "(", ":rel", "=>", "'next'", ")", "do", "block", ".", "call", "if", "block", "end", "end" ]
A simple "Twitter like" pagination link that creates a link to the next page. ==== Examples Basic usage: <%= link_to_next_page @items, 'Next Page' %> Ajax: <%= link_to_next_page @items, 'Next Page', :remote => true %> By default, it renders nothing if there are no more results on the next page. You can customize this output by passing a block. <%= link_to_next_page @users, 'Next Page' do %> <span>No More Pages</span> <% end %>
[ "A", "simple", "Twitter", "like", "pagination", "link", "that", "creates", "a", "link", "to", "the", "next", "page", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L67-L73
3,225
cbeer/kaminari_route_prefix
lib/kaminari_route_prefix/actionview/action_view_extension.rb
KaminariRoutePrefix.ActionViewExtension.rel_next_prev_link_tags
def rel_next_prev_link_tags(scope, options = {}) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) output = String.new output << tag(:link, :rel => "next", :href => next_page.url) if scope.next_page.present? output << tag(:link, :rel => "prev", :href => prev_page.url) if scope.prev_page.present? output.html_safe end
ruby
def rel_next_prev_link_tags(scope, options = {}) next_page = Kaminari::Helpers::NextPage.new self, options.reverse_merge(:current_page => scope.current_page) prev_page = Kaminari::Helpers::PrevPage.new self, options.reverse_merge(:current_page => scope.current_page) output = String.new output << tag(:link, :rel => "next", :href => next_page.url) if scope.next_page.present? output << tag(:link, :rel => "prev", :href => prev_page.url) if scope.prev_page.present? output.html_safe end
[ "def", "rel_next_prev_link_tags", "(", "scope", ",", "options", "=", "{", "}", ")", "next_page", "=", "Kaminari", "::", "Helpers", "::", "NextPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "prev_page", "=", "Kaminari", "::", "Helpers", "::", "PrevPage", ".", "new", "self", ",", "options", ".", "reverse_merge", "(", ":current_page", "=>", "scope", ".", "current_page", ")", "output", "=", "String", ".", "new", "output", "<<", "tag", "(", ":link", ",", ":rel", "=>", "\"next\"", ",", ":href", "=>", "next_page", ".", "url", ")", "if", "scope", ".", "next_page", ".", "present?", "output", "<<", "tag", "(", ":link", ",", ":rel", "=>", "\"prev\"", ",", ":href", "=>", "prev_page", ".", "url", ")", "if", "scope", ".", "prev_page", ".", "present?", "output", ".", "html_safe", "end" ]
Renders rel="next" and rel="prev" links to be used in the head. ==== Examples Basic usage: In head: <head> <title>My Website</title> <%= yield :head %> </head> Somewhere in body: <% content_for :head do %> <%= rel_next_prev_link_tags @items %> <% end %> #-> <link rel="next" href="/items/page/3" /><link rel="prev" href="/items/page/1" />
[ "Renders", "rel", "=", "next", "and", "rel", "=", "prev", "links", "to", "be", "used", "in", "the", "head", "." ]
70f955e56a777272b033c1ee623ed7269e12d03b
https://github.com/cbeer/kaminari_route_prefix/blob/70f955e56a777272b033c1ee623ed7269e12d03b/lib/kaminari_route_prefix/actionview/action_view_extension.rb#L122-L130
3,226
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.ratio
def ratio(rgb1, rgb2) raise InvalidColorError, rgb1 unless valid_rgb?(rgb1) raise InvalidColorError, rgb2 unless valid_rgb?(rgb2) srgb1 = rgb_to_srgba(rgb1) srgb2 = rgb_to_srgba(rgb2) l1 = srgb_lightness(srgb1) l2 = srgb_lightness(srgb2) l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05) end
ruby
def ratio(rgb1, rgb2) raise InvalidColorError, rgb1 unless valid_rgb?(rgb1) raise InvalidColorError, rgb2 unless valid_rgb?(rgb2) srgb1 = rgb_to_srgba(rgb1) srgb2 = rgb_to_srgba(rgb2) l1 = srgb_lightness(srgb1) l2 = srgb_lightness(srgb2) l1 > l2 ? (l1 + 0.05) / (l2 + 0.05) : (l2 + 0.05) / (l1 + 0.05) end
[ "def", "ratio", "(", "rgb1", ",", "rgb2", ")", "raise", "InvalidColorError", ",", "rgb1", "unless", "valid_rgb?", "(", "rgb1", ")", "raise", "InvalidColorError", ",", "rgb2", "unless", "valid_rgb?", "(", "rgb2", ")", "srgb1", "=", "rgb_to_srgba", "(", "rgb1", ")", "srgb2", "=", "rgb_to_srgba", "(", "rgb2", ")", "l1", "=", "srgb_lightness", "(", "srgb1", ")", "l2", "=", "srgb_lightness", "(", "srgb2", ")", "l1", ">", "l2", "?", "(", "l1", "+", "0.05", ")", "/", "(", "l2", "+", "0.05", ")", ":", "(", "l2", "+", "0.05", ")", "/", "(", "l1", "+", "0.05", ")", "end" ]
Calculate contast ratio beetween RGB1 and RGB2.
[ "Calculate", "contast", "ratio", "beetween", "RGB1", "and", "RGB2", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L17-L28
3,227
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.relative_luminance
def relative_luminance(rgb) raise InvalidColorError, rgb unless valid_rgb?(rgb) srgb = rgb_to_srgba(rgb) srgb_lightness(srgb) end
ruby
def relative_luminance(rgb) raise InvalidColorError, rgb unless valid_rgb?(rgb) srgb = rgb_to_srgba(rgb) srgb_lightness(srgb) end
[ "def", "relative_luminance", "(", "rgb", ")", "raise", "InvalidColorError", ",", "rgb", "unless", "valid_rgb?", "(", "rgb", ")", "srgb", "=", "rgb_to_srgba", "(", "rgb", ")", "srgb_lightness", "(", "srgb", ")", "end" ]
Calculate the relative luminance for an rgb color
[ "Calculate", "the", "relative", "luminance", "for", "an", "rgb", "color" ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L31-L36
3,228
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.rgb_to_srgba
def rgb_to_srgba(rgb) rgb << rgb if rgb.size == 3 [ rgb.slice(0,2).to_i(16) / 255.0, rgb.slice(2,2).to_i(16) / 255.0, rgb.slice(4,2).to_i(16) / 255.0 ] end
ruby
def rgb_to_srgba(rgb) rgb << rgb if rgb.size == 3 [ rgb.slice(0,2).to_i(16) / 255.0, rgb.slice(2,2).to_i(16) / 255.0, rgb.slice(4,2).to_i(16) / 255.0 ] end
[ "def", "rgb_to_srgba", "(", "rgb", ")", "rgb", "<<", "rgb", "if", "rgb", ".", "size", "==", "3", "[", "rgb", ".", "slice", "(", "0", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", ",", "rgb", ".", "slice", "(", "2", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", ",", "rgb", ".", "slice", "(", "4", ",", "2", ")", ".", "to_i", "(", "16", ")", "/", "255.0", "]", "end" ]
Convert RGB color to sRGB.
[ "Convert", "RGB", "color", "to", "sRGB", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L41-L48
3,229
mkdynamic/wcag_color_contrast
lib/wcag_color_contrast.rb
WCAGColorContrast.Ratio.srgb_lightness
def srgb_lightness(srgb) r, g, b = srgb 0.2126 * (r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4) + 0.7152 * (g <= 0.03928 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4) + 0.0722 * (b <= 0.03928 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4) end
ruby
def srgb_lightness(srgb) r, g, b = srgb 0.2126 * (r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4) + 0.7152 * (g <= 0.03928 ? g / 12.92 : ((g + 0.055) / 1.055) ** 2.4) + 0.0722 * (b <= 0.03928 ? b / 12.92 : ((b + 0.055) / 1.055) ** 2.4) end
[ "def", "srgb_lightness", "(", "srgb", ")", "r", ",", "g", ",", "b", "=", "srgb", "0.2126", "*", "(", "r", "<=", "0.03928", "?", "r", "/", "12.92", ":", "(", "(", "r", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "+", "0.7152", "*", "(", "g", "<=", "0.03928", "?", "g", "/", "12.92", ":", "(", "(", "g", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "+", "0.0722", "*", "(", "b", "<=", "0.03928", "?", "b", "/", "12.92", ":", "(", "(", "b", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", ")", "end" ]
Calculate lightness for sRGB color.
[ "Calculate", "lightness", "for", "sRGB", "color", "." ]
f6e05ef0887edcbfab4b04ff7729b51213df8aa9
https://github.com/mkdynamic/wcag_color_contrast/blob/f6e05ef0887edcbfab4b04ff7729b51213df8aa9/lib/wcag_color_contrast.rb#L51-L56
3,230
mpalmer/frankenstein
lib/frankenstein/server.rb
Frankenstein.Server.run
def run @op_mutex.synchronize do return AlreadyRunningError if @server @server_thread = Thread.new do @op_mutex.synchronize do begin wrapped_logger = Frankenstein::Server::WEBrickLogger.new(logger: @logger, progname: "Frankenstein::Server") @server = WEBrick::HTTPServer.new(Logger: wrapped_logger, BindAddress: nil, Port: @port, AccessLog: [[wrapped_logger, WEBrick::AccessLog::COMMON_LOG_FORMAT]]) @server.mount "/", Rack::Handler::WEBrick, app rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: ensure @op_cv.signal end end begin @server.start if @server rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: end end end @op_mutex.synchronize { @op_cv.wait(@op_mutex) until @server } end
ruby
def run @op_mutex.synchronize do return AlreadyRunningError if @server @server_thread = Thread.new do @op_mutex.synchronize do begin wrapped_logger = Frankenstein::Server::WEBrickLogger.new(logger: @logger, progname: "Frankenstein::Server") @server = WEBrick::HTTPServer.new(Logger: wrapped_logger, BindAddress: nil, Port: @port, AccessLog: [[wrapped_logger, WEBrick::AccessLog::COMMON_LOG_FORMAT]]) @server.mount "/", Rack::Handler::WEBrick, app rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: ensure @op_cv.signal end end begin @server.start if @server rescue => ex #:nocov: @logger.fatal("Frankenstein::Server#run") { (["Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})"] + ex.backtrace).join("\n ") } #:nocov: end end end @op_mutex.synchronize { @op_cv.wait(@op_mutex) until @server } end
[ "def", "run", "@op_mutex", ".", "synchronize", "do", "return", "AlreadyRunningError", "if", "@server", "@server_thread", "=", "Thread", ".", "new", "do", "@op_mutex", ".", "synchronize", "do", "begin", "wrapped_logger", "=", "Frankenstein", "::", "Server", "::", "WEBrickLogger", ".", "new", "(", "logger", ":", "@logger", ",", "progname", ":", "\"Frankenstein::Server\"", ")", "@server", "=", "WEBrick", "::", "HTTPServer", ".", "new", "(", "Logger", ":", "wrapped_logger", ",", "BindAddress", ":", "nil", ",", "Port", ":", "@port", ",", "AccessLog", ":", "[", "[", "wrapped_logger", ",", "WEBrick", "::", "AccessLog", "::", "COMMON_LOG_FORMAT", "]", "]", ")", "@server", ".", "mount", "\"/\"", ",", "Rack", "::", "Handler", "::", "WEBrick", ",", "app", "rescue", "=>", "ex", "#:nocov:", "@logger", ".", "fatal", "(", "\"Frankenstein::Server#run\"", ")", "{", "(", "[", "\"Exception while trying to create WEBrick::HTTPServer: #{ex.message} (#{ex.class})\"", "]", "+", "ex", ".", "backtrace", ")", ".", "join", "(", "\"\\n \"", ")", "}", "#:nocov:", "ensure", "@op_cv", ".", "signal", "end", "end", "begin", "@server", ".", "start", "if", "@server", "rescue", "=>", "ex", "#:nocov:", "@logger", ".", "fatal", "(", "\"Frankenstein::Server#run\"", ")", "{", "(", "[", "\"Exception while running WEBrick::HTTPServer: #{ex.message} (#{ex.class})\"", "]", "+", "ex", ".", "backtrace", ")", ".", "join", "(", "\"\\n \"", ")", "}", "#:nocov:", "end", "end", "end", "@op_mutex", ".", "synchronize", "{", "@op_cv", ".", "wait", "(", "@op_mutex", ")", "until", "@server", "}", "end" ]
Create a new server instance. @param port [Integer] the TCP to listen on. @param logger [Logger] send log messages from WEBrick to this logger. If not specified, all log messages will be silently eaten. @param metrics_prefix [#to_s] The prefix to apply to the metrics exposed instrumenting the metrics server itself. @param registry [Prometheus::Client::Registry] if you want to use an existing metrics registry for this server, pass it in here. Otherwise, a new one will be created for you, and be made available via #registry. Start the server instance running in a separate thread. This method returns once the server is just about ready to start serving requests.
[ "Create", "a", "new", "server", "instance", "." ]
1bbd9835233d0672af020da405ea1b29d55d105e
https://github.com/mpalmer/frankenstein/blob/1bbd9835233d0672af020da405ea1b29d55d105e/lib/frankenstein/server.rb#L74-L104
3,231
localmed/outbox
lib/outbox/message_types.rb
Outbox.MessageTypes.assign_message_type_values
def assign_message_type_values(values) values.each do |key, value| public_send(key, value) if respond_to?(key) end end
ruby
def assign_message_type_values(values) values.each do |key, value| public_send(key, value) if respond_to?(key) end end
[ "def", "assign_message_type_values", "(", "values", ")", "values", ".", "each", "do", "|", "key", ",", "value", "|", "public_send", "(", "key", ",", "value", ")", "if", "respond_to?", "(", "key", ")", "end", "end" ]
Assign the given hash where each key is a message type and the value is a hash of options for that message type.
[ "Assign", "the", "given", "hash", "where", "each", "key", "is", "a", "message", "type", "and", "the", "value", "is", "a", "hash", "of", "options", "for", "that", "message", "type", "." ]
4c7bd2129df7d2bbb49e464699afed9eb8396a5f
https://github.com/localmed/outbox/blob/4c7bd2129df7d2bbb49e464699afed9eb8396a5f/lib/outbox/message_types.rb#L101-L105
3,232
mbj/esearch
lib/esearch/request.rb
Esearch.Request.run
def run(connection) connection.public_send(verb, path) do |request| request.params = params request.headers[:content_type] = Command::JSON_CONTENT_TYPE request.body = MultiJson.dump(body) end end
ruby
def run(connection) connection.public_send(verb, path) do |request| request.params = params request.headers[:content_type] = Command::JSON_CONTENT_TYPE request.body = MultiJson.dump(body) end end
[ "def", "run", "(", "connection", ")", "connection", ".", "public_send", "(", "verb", ",", "path", ")", "do", "|", "request", "|", "request", ".", "params", "=", "params", "request", ".", "headers", "[", ":content_type", "]", "=", "Command", "::", "JSON_CONTENT_TYPE", "request", ".", "body", "=", "MultiJson", ".", "dump", "(", "body", ")", "end", "end" ]
Run request on connection @param [Faraday::Connection] @return [Faraday::Response] @api private
[ "Run", "request", "on", "connection" ]
45a1dcb495d650e450085c2240a280fc8082cc34
https://github.com/mbj/esearch/blob/45a1dcb495d650e450085c2240a280fc8082cc34/lib/esearch/request.rb#L77-L83
3,233
G5/modelish
lib/modelish/validations.rb
Modelish.Validations.validate
def validate errors = {} call_validators do |name, message| errors[name] ||= [] errors[name] << to_error(message) end errors end
ruby
def validate errors = {} call_validators do |name, message| errors[name] ||= [] errors[name] << to_error(message) end errors end
[ "def", "validate", "errors", "=", "{", "}", "call_validators", "do", "|", "name", ",", "message", "|", "errors", "[", "name", "]", "||=", "[", "]", "errors", "[", "name", "]", "<<", "to_error", "(", "message", ")", "end", "errors", "end" ]
Validates all properties based on configured validators. @return [Hash<Symbol,Array>] map of errors where key is the property name and value is the list of errors @see ClassMethods#add_validator
[ "Validates", "all", "properties", "based", "on", "configured", "validators", "." ]
42cb6e07dafd794e0180b858a36fb7b5a8e424b6
https://github.com/G5/modelish/blob/42cb6e07dafd794e0180b858a36fb7b5a8e424b6/lib/modelish/validations.rb#L17-L26
3,234
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.load_capabilities
def load_capabilities(caps) device = @server.device_data unless device.nil? caps[:caps][:udid] = device.fetch('udid', nil) caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion]) caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName]) caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil) caps[:caps][:avd] = device.fetch('avd', nil) end caps[:appium_lib][:server_url] = ENV['SERVER_URL'] caps end
ruby
def load_capabilities(caps) device = @server.device_data unless device.nil? caps[:caps][:udid] = device.fetch('udid', nil) caps[:caps][:platformVersion] = device.fetch('os', caps[:caps][:platformVersion]) caps[:caps][:deviceName] = device.fetch('name', caps[:caps][:deviceName]) caps[:caps][:wdaLocalPort] = device.fetch('wdaPort', nil) caps[:caps][:avd] = device.fetch('avd', nil) end caps[:appium_lib][:server_url] = ENV['SERVER_URL'] caps end
[ "def", "load_capabilities", "(", "caps", ")", "device", "=", "@server", ".", "device_data", "unless", "device", ".", "nil?", "caps", "[", ":caps", "]", "[", ":udid", "]", "=", "device", ".", "fetch", "(", "'udid'", ",", "nil", ")", "caps", "[", ":caps", "]", "[", ":platformVersion", "]", "=", "device", ".", "fetch", "(", "'os'", ",", "caps", "[", ":caps", "]", "[", ":platformVersion", "]", ")", "caps", "[", ":caps", "]", "[", ":deviceName", "]", "=", "device", ".", "fetch", "(", "'name'", ",", "caps", "[", ":caps", "]", "[", ":deviceName", "]", ")", "caps", "[", ":caps", "]", "[", ":wdaLocalPort", "]", "=", "device", ".", "fetch", "(", "'wdaPort'", ",", "nil", ")", "caps", "[", ":caps", "]", "[", ":avd", "]", "=", "device", ".", "fetch", "(", "'avd'", ",", "nil", ")", "end", "caps", "[", ":appium_lib", "]", "[", ":server_url", "]", "=", "ENV", "[", "'SERVER_URL'", "]", "caps", "end" ]
Load capabilities based on current device data
[ "Load", "capabilities", "based", "on", "current", "device", "data" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L26-L38
3,235
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.initialize_appium
def initialize_appium(**args) platform = args[:platform] caps = args[:caps] platform = ENV['platform'] if platform.nil? if platform.nil? puts 'Platform not found in environment variable' exit end caps = Appium.load_appium_txt file: File.new("#{Dir.pwd}/appium-#{platform}.txt") if caps.nil? if caps.nil? puts 'No capabilities specified' exit end puts 'Preparing to load capabilities' capabilities = load_capabilities(caps) puts 'Loaded capabilities' @driver = Appium::Driver.new(capabilities, true) puts 'Created driver' Appium.promote_appium_methods Object Appium.promote_appium_methods RSpec::Core::ExampleGroup @driver end
ruby
def initialize_appium(**args) platform = args[:platform] caps = args[:caps] platform = ENV['platform'] if platform.nil? if platform.nil? puts 'Platform not found in environment variable' exit end caps = Appium.load_appium_txt file: File.new("#{Dir.pwd}/appium-#{platform}.txt") if caps.nil? if caps.nil? puts 'No capabilities specified' exit end puts 'Preparing to load capabilities' capabilities = load_capabilities(caps) puts 'Loaded capabilities' @driver = Appium::Driver.new(capabilities, true) puts 'Created driver' Appium.promote_appium_methods Object Appium.promote_appium_methods RSpec::Core::ExampleGroup @driver end
[ "def", "initialize_appium", "(", "**", "args", ")", "platform", "=", "args", "[", ":platform", "]", "caps", "=", "args", "[", ":caps", "]", "platform", "=", "ENV", "[", "'platform'", "]", "if", "platform", ".", "nil?", "if", "platform", ".", "nil?", "puts", "'Platform not found in environment variable'", "exit", "end", "caps", "=", "Appium", ".", "load_appium_txt", "file", ":", "File", ".", "new", "(", "\"#{Dir.pwd}/appium-#{platform}.txt\"", ")", "if", "caps", ".", "nil?", "if", "caps", ".", "nil?", "puts", "'No capabilities specified'", "exit", "end", "puts", "'Preparing to load capabilities'", "capabilities", "=", "load_capabilities", "(", "caps", ")", "puts", "'Loaded capabilities'", "@driver", "=", "Appium", "::", "Driver", ".", "new", "(", "capabilities", ",", "true", ")", "puts", "'Created driver'", "Appium", ".", "promote_appium_methods", "Object", "Appium", ".", "promote_appium_methods", "RSpec", "::", "Core", "::", "ExampleGroup", "@driver", "end" ]
Load appium text file if available and attempt to start the driver platform is either android or ios, otherwise read from ENV caps is mapping of appium capabilities
[ "Load", "appium", "text", "file", "if", "available", "and", "attempt", "to", "start", "the", "driver", "platform", "is", "either", "android", "or", "ios", "otherwise", "read", "from", "ENV", "caps", "is", "mapping", "of", "appium", "capabilities" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L43-L68
3,236
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.setup_signal_handler
def setup_signal_handler(ios_pid = nil, android_pid = nil) Signal.trap('INT') do Process.kill('INT', ios_pid) unless ios_pid.nil? Process.kill('INT', android_pid) unless android_pid.nil? # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' # Terminate ourself exit 1 end end
ruby
def setup_signal_handler(ios_pid = nil, android_pid = nil) Signal.trap('INT') do Process.kill('INT', ios_pid) unless ios_pid.nil? Process.kill('INT', android_pid) unless android_pid.nil? # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' # Terminate ourself exit 1 end end
[ "def", "setup_signal_handler", "(", "ios_pid", "=", "nil", ",", "android_pid", "=", "nil", ")", "Signal", ".", "trap", "(", "'INT'", ")", "do", "Process", ".", "kill", "(", "'INT'", ",", "ios_pid", ")", "unless", "ios_pid", ".", "nil?", "Process", ".", "kill", "(", "'INT'", ",", "android_pid", ")", "unless", "android_pid", ".", "nil?", "# Kill any existing Appium and Selenium processes", "kill_process", "'appium'", "kill_process", "'selenium'", "# Terminate ourself", "exit", "1", "end", "end" ]
Define a signal handler for SIGINT
[ "Define", "a", "signal", "handler", "for", "SIGINT" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L71-L83
3,237
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.execute_specs
def execute_specs(platform, threads, spec_path, parallel = false) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
ruby
def execute_specs(platform, threads, spec_path, parallel = false) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
[ "def", "execute_specs", "(", "platform", ",", "threads", ",", "spec_path", ",", "parallel", "=", "false", ")", "command", "=", "if", "parallel", "\"platform=#{platform} parallel_rspec -n #{threads} #{spec_path}\"", "else", "\"platform=#{platform} rspec #{spec_path} --tag #{platform}\"", "end", "puts", "\"Executing #{command}\"", "exec", "command", "end" ]
Decide whether to execute specs in parallel or not @param [String] platform @param [int] threads @param [String] spec_path @param [boolean] parallel
[ "Decide", "whether", "to", "execute", "specs", "in", "parallel", "or", "not" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L90-L99
3,238
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.setup
def setup(platform, file_path, threads, parallel) spec_path = 'spec/' spec_path = file_path.to_s unless file_path.nil? puts "SPEC PATH:#{spec_path}" unless %w[ios android].include? platform puts "Invalid platform #{platform}" exit end execute_specs platform, threads, spec_path, parallel end
ruby
def setup(platform, file_path, threads, parallel) spec_path = 'spec/' spec_path = file_path.to_s unless file_path.nil? puts "SPEC PATH:#{spec_path}" unless %w[ios android].include? platform puts "Invalid platform #{platform}" exit end execute_specs platform, threads, spec_path, parallel end
[ "def", "setup", "(", "platform", ",", "file_path", ",", "threads", ",", "parallel", ")", "spec_path", "=", "'spec/'", "spec_path", "=", "file_path", ".", "to_s", "unless", "file_path", ".", "nil?", "puts", "\"SPEC PATH:#{spec_path}\"", "unless", "%w[", "ios", "android", "]", ".", "include?", "platform", "puts", "\"Invalid platform #{platform}\"", "exit", "end", "execute_specs", "platform", ",", "threads", ",", "spec_path", ",", "parallel", "end" ]
Define Spec path, validate platform and execute specs
[ "Define", "Spec", "path", "validate", "platform", "and", "execute", "specs" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L102-L113
3,239
JavonDavis/parallel_appium
lib/parallel_appium.rb
ParallelAppium.ParallelAppium.start
def start(**args) platform = args[:platform] file_path = args[:file_path] # Validate environment variable if ENV['platform'].nil? if platform.nil? puts 'No platform detected in environment and none passed to start...' exit end ENV['platform'] = platform end sleep 3 # Appium ports ios_port = 4725 android_port = 4727 default_port = 4725 platform = ENV['platform'] # Platform is required check_platform platform platform = platform.downcase ENV['BASE_DIR'] = Dir.pwd # Check if multithreaded for distributing tests across devices threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i parallel = threads != 1 if platform != 'all' pid = fork do if !parallel ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub" @server.start_single_appium platform, default_port else ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' @server.launch_hub_and_nodes platform end setup(platform, file_path, threads, parallel) end puts "PID: #{pid}" setup_signal_handler(pid) Process.waitpid(pid) else # Spin off 2 sub-processes, one for Android connections and another for iOS, # each with redefining environment variables for the server url, number of threads and platform ios_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start iOS' @server.launch_hub_and_nodes 'ios' else ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub" puts 'Start iOS' @server.start_single_appium 'ios', ios_port end setup('ios', file_path, threads, parallel) end android_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start Android' @server.launch_hub_and_nodes 'android' else ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub" puts 'Start Android' @server.start_single_appium 'android', android_port end setup('android', file_path, threads, parallel) end puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}" setup_signal_handler(ios_pid, android_pid) [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) } end # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' end
ruby
def start(**args) platform = args[:platform] file_path = args[:file_path] # Validate environment variable if ENV['platform'].nil? if platform.nil? puts 'No platform detected in environment and none passed to start...' exit end ENV['platform'] = platform end sleep 3 # Appium ports ios_port = 4725 android_port = 4727 default_port = 4725 platform = ENV['platform'] # Platform is required check_platform platform platform = platform.downcase ENV['BASE_DIR'] = Dir.pwd # Check if multithreaded for distributing tests across devices threads = ENV['THREADS'].nil? ? 1 : ENV['THREADS'].to_i parallel = threads != 1 if platform != 'all' pid = fork do if !parallel ENV['SERVER_URL'] = "http://0.0.0.0:#{default_port}/wd/hub" @server.start_single_appium platform, default_port else ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' @server.launch_hub_and_nodes platform end setup(platform, file_path, threads, parallel) end puts "PID: #{pid}" setup_signal_handler(pid) Process.waitpid(pid) else # Spin off 2 sub-processes, one for Android connections and another for iOS, # each with redefining environment variables for the server url, number of threads and platform ios_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start iOS' @server.launch_hub_and_nodes 'ios' else ENV['SERVER_URL'] = "http://0.0.0.0:#{ios_port}/wd/hub" puts 'Start iOS' @server.start_single_appium 'ios', ios_port end setup('ios', file_path, threads, parallel) end android_pid = fork do ENV['THREADS'] = threads.to_s if parallel ENV['SERVER_URL'] = 'http://localhost:4444/wd/hub' puts 'Start Android' @server.launch_hub_and_nodes 'android' else ENV['SERVER_URL'] = "http://0.0.0.0:#{android_port}/wd/hub" puts 'Start Android' @server.start_single_appium 'android', android_port end setup('android', file_path, threads, parallel) end puts "iOS PID: #{ios_pid}\nAndroid PID: #{android_pid}" setup_signal_handler(ios_pid, android_pid) [ios_pid, android_pid].each { |process_pid| Process.waitpid(process_pid) } end # Kill any existing Appium and Selenium processes kill_process 'appium' kill_process 'selenium' end
[ "def", "start", "(", "**", "args", ")", "platform", "=", "args", "[", ":platform", "]", "file_path", "=", "args", "[", ":file_path", "]", "# Validate environment variable", "if", "ENV", "[", "'platform'", "]", ".", "nil?", "if", "platform", ".", "nil?", "puts", "'No platform detected in environment and none passed to start...'", "exit", "end", "ENV", "[", "'platform'", "]", "=", "platform", "end", "sleep", "3", "# Appium ports", "ios_port", "=", "4725", "android_port", "=", "4727", "default_port", "=", "4725", "platform", "=", "ENV", "[", "'platform'", "]", "# Platform is required", "check_platform", "platform", "platform", "=", "platform", ".", "downcase", "ENV", "[", "'BASE_DIR'", "]", "=", "Dir", ".", "pwd", "# Check if multithreaded for distributing tests across devices", "threads", "=", "ENV", "[", "'THREADS'", "]", ".", "nil?", "?", "1", ":", "ENV", "[", "'THREADS'", "]", ".", "to_i", "parallel", "=", "threads", "!=", "1", "if", "platform", "!=", "'all'", "pid", "=", "fork", "do", "if", "!", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{default_port}/wd/hub\"", "@server", ".", "start_single_appium", "platform", ",", "default_port", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "@server", ".", "launch_hub_and_nodes", "platform", "end", "setup", "(", "platform", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "puts", "\"PID: #{pid}\"", "setup_signal_handler", "(", "pid", ")", "Process", ".", "waitpid", "(", "pid", ")", "else", "# Spin off 2 sub-processes, one for Android connections and another for iOS,", "# each with redefining environment variables for the server url, number of threads and platform", "ios_pid", "=", "fork", "do", "ENV", "[", "'THREADS'", "]", "=", "threads", ".", "to_s", "if", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "puts", "'Start iOS'", "@server", ".", "launch_hub_and_nodes", "'ios'", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{ios_port}/wd/hub\"", "puts", "'Start iOS'", "@server", ".", "start_single_appium", "'ios'", ",", "ios_port", "end", "setup", "(", "'ios'", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "android_pid", "=", "fork", "do", "ENV", "[", "'THREADS'", "]", "=", "threads", ".", "to_s", "if", "parallel", "ENV", "[", "'SERVER_URL'", "]", "=", "'http://localhost:4444/wd/hub'", "puts", "'Start Android'", "@server", ".", "launch_hub_and_nodes", "'android'", "else", "ENV", "[", "'SERVER_URL'", "]", "=", "\"http://0.0.0.0:#{android_port}/wd/hub\"", "puts", "'Start Android'", "@server", ".", "start_single_appium", "'android'", ",", "android_port", "end", "setup", "(", "'android'", ",", "file_path", ",", "threads", ",", "parallel", ")", "end", "puts", "\"iOS PID: #{ios_pid}\\nAndroid PID: #{android_pid}\"", "setup_signal_handler", "(", "ios_pid", ",", "android_pid", ")", "[", "ios_pid", ",", "android_pid", "]", ".", "each", "{", "|", "process_pid", "|", "Process", ".", "waitpid", "(", "process_pid", ")", "}", "end", "# Kill any existing Appium and Selenium processes", "kill_process", "'appium'", "kill_process", "'selenium'", "end" ]
Fire necessary appium server instances and Selenium grid server if needed.
[ "Fire", "necessary", "appium", "server", "instances", "and", "Selenium", "grid", "server", "if", "needed", "." ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium.rb#L128-L214
3,240
weenhanceit/gaapi
lib/gaapi/query.rb
GAAPI.Query.execute
def execute uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true # https.set_debug_output($stdout) request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{access_token}") request.body = query.to_json Response.new(https.request(request)) end
ruby
def execute uri = URI.parse("https://analyticsreporting.googleapis.com/v4/reports:batchGet") https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true # https.set_debug_output($stdout) request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{access_token}") request.body = query.to_json Response.new(https.request(request)) end
[ "def", "execute", "uri", "=", "URI", ".", "parse", "(", "\"https://analyticsreporting.googleapis.com/v4/reports:batchGet\"", ")", "https", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "https", ".", "use_ssl", "=", "true", "# https.set_debug_output($stdout)", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "request_uri", ",", "\"Content-Type\"", "=>", "\"application/json\"", ",", "\"Authorization\"", "=>", "\"Bearer #{access_token}\"", ")", "request", ".", "body", "=", "query", ".", "to_json", "Response", ".", "new", "(", "https", ".", "request", "(", "request", ")", ")", "end" ]
Create a Query object. @param access_token [String] A valid access token with which to make a request to the specified View ID. @param end_date [Date, String] The end date for the report. @param query_string [String, Hash, JSON] The query in JSON format. @param start_date [Date, String] The start date for the report. @param view_id [String] The view ID of the property for which to submit the query. Send the requested query to Google Analytics and return the response. @return [GAAPI::Response] The response from the request.
[ "Create", "a", "Query", "object", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/query.rb#L34-L44
3,241
weenhanceit/gaapi
lib/gaapi/query.rb
GAAPI.Query.stringify_keys
def stringify_keys(object) case object when Hash object.each_with_object({}) do |(key, value), result| result[key.to_s] = stringify_keys(value) end when Array object.map { |e| stringify_keys(e) } else object end end
ruby
def stringify_keys(object) case object when Hash object.each_with_object({}) do |(key, value), result| result[key.to_s] = stringify_keys(value) end when Array object.map { |e| stringify_keys(e) } else object end end
[ "def", "stringify_keys", "(", "object", ")", "case", "object", "when", "Hash", "object", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "result", "|", "result", "[", "key", ".", "to_s", "]", "=", "stringify_keys", "(", "value", ")", "end", "when", "Array", "object", ".", "map", "{", "|", "e", "|", "stringify_keys", "(", "e", ")", "}", "else", "object", "end", "end" ]
The keys have to be strings to get converted to a GA query. Adapted from Rails.
[ "The", "keys", "have", "to", "be", "strings", "to", "get", "converted", "to", "a", "GA", "query", ".", "Adapted", "from", "Rails", "." ]
20d25bd06b2e0cccc86ca1ea1baaac6be045355a
https://github.com/weenhanceit/gaapi/blob/20d25bd06b2e0cccc86ca1ea1baaac6be045355a/lib/gaapi/query.rb#L52-L63
3,242
mbj/esearch
lib/esearch/command.rb
Esearch.Command.raise_status_error
def raise_status_error message = format( 'expected response stati: %s but got: %s, remote message: %s', expected_response_stati, response.status, remote_message.inspect ) fail ProtocolError, message end
ruby
def raise_status_error message = format( 'expected response stati: %s but got: %s, remote message: %s', expected_response_stati, response.status, remote_message.inspect ) fail ProtocolError, message end
[ "def", "raise_status_error", "message", "=", "format", "(", "'expected response stati: %s but got: %s, remote message: %s'", ",", "expected_response_stati", ",", "response", ".", "status", ",", "remote_message", ".", "inspect", ")", "fail", "ProtocolError", ",", "message", "end" ]
Raise remote status error @return [undefined] @api private
[ "Raise", "remote", "status", "error" ]
45a1dcb495d650e450085c2240a280fc8082cc34
https://github.com/mbj/esearch/blob/45a1dcb495d650e450085c2240a280fc8082cc34/lib/esearch/command.rb#L116-L124
3,243
henkm/shake-the-counter
lib/shake_the_counter/performance.rb
ShakeTheCounter.Performance.sections
def sections return @sections if @sections @sections = [] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event.client.call(path, http_method: :get) for section in result @sections << ShakeTheCounter::Section.new(section, performance: self) end return @sections end
ruby
def sections return @sections if @sections @sections = [] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event.client.call(path, http_method: :get) for section in result @sections << ShakeTheCounter::Section.new(section, performance: self) end return @sections end
[ "def", "sections", "return", "@sections", "if", "@sections", "@sections", "=", "[", "]", "path", "=", "\"event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}\"", "result", "=", "event", ".", "client", ".", "call", "(", "path", ",", "http_method", ":", ":get", ")", "for", "section", "in", "result", "@sections", "<<", "ShakeTheCounter", "::", "Section", ".", "new", "(", "section", ",", "performance", ":", "self", ")", "end", "return", "@sections", "end" ]
Sets up a new event GET /api/v1/event/{eventKey}/performance/{performanceKey}/sections/{languageCode} Get available sections, pricetypes and prices of the selected performance @return Array of sections
[ "Sets", "up", "a", "new", "event" ]
094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e
https://github.com/henkm/shake-the-counter/blob/094d3fe7b0bd0cd2dd1c0bdb1d0ccc5fa147851e/lib/shake_the_counter/performance.rb#L29-L38
3,244
rtjoseph11/modernizer
lib/modernizer/version_parser.rb
Modernize.VersionParsingContext.method_missing
def method_missing(method, *args, &block) raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 raise NoMethodError.new("Undefined translation method #{method}") unless MapMethods.respond_to?(method) @maps << {name: method, field: args[0], block: block} end
ruby
def method_missing(method, *args, &block) raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1 raise NoMethodError.new("Undefined translation method #{method}") unless MapMethods.respond_to?(method) @maps << {name: method, field: args[0], block: block} end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "raise", "ArgumentError", ".", "new", "(", "\"wrong number of arguments (#{args.size} for 1)\"", ")", "if", "args", ".", "size", "!=", "1", "raise", "NoMethodError", ".", "new", "(", "\"Undefined translation method #{method}\"", ")", "unless", "MapMethods", ".", "respond_to?", "(", "method", ")", "@maps", "<<", "{", "name", ":", "method", ",", "field", ":", "args", "[", "0", "]", ",", "block", ":", "block", "}", "end" ]
Figures out which translations are done for each version.
[ "Figures", "out", "which", "translations", "are", "done", "for", "each", "version", "." ]
5700b61815731f41146248d7e3fe8eca0e647ef3
https://github.com/rtjoseph11/modernizer/blob/5700b61815731f41146248d7e3fe8eca0e647ef3/lib/modernizer/version_parser.rb#L21-L25
3,245
fiatinsight/fiat_publication
app/models/fiat_publication/comment.rb
FiatPublication.Comment.mention_users
def mention_users mentions ||= begin regex = /@([\w]+)/ self.body.scan(regex).flatten end mentioned_users ||= User.where(username: mentions) if mentioned_users.any? mentioned_users.each do |i| FiatNotifications::Notification::CreateNotificationJob.set(wait: 5.seconds).perform_later( self, self.authorable, i, action: "mentioned", notified_type: "User", notified_ids: [i.id], email_template_id: FiatNotifications.email_template_id, email_subject: "You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}", email_body: "#{self.body}", reply_to_address: FiatNotifications.reply_to_email_address ) end end end
ruby
def mention_users mentions ||= begin regex = /@([\w]+)/ self.body.scan(regex).flatten end mentioned_users ||= User.where(username: mentions) if mentioned_users.any? mentioned_users.each do |i| FiatNotifications::Notification::CreateNotificationJob.set(wait: 5.seconds).perform_later( self, self.authorable, i, action: "mentioned", notified_type: "User", notified_ids: [i.id], email_template_id: FiatNotifications.email_template_id, email_subject: "You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}", email_body: "#{self.body}", reply_to_address: FiatNotifications.reply_to_email_address ) end end end
[ "def", "mention_users", "mentions", "||=", "begin", "regex", "=", "/", "\\w", "/", "self", ".", "body", ".", "scan", "(", "regex", ")", ".", "flatten", "end", "mentioned_users", "||=", "User", ".", "where", "(", "username", ":", "mentions", ")", "if", "mentioned_users", ".", "any?", "mentioned_users", ".", "each", "do", "|", "i", "|", "FiatNotifications", "::", "Notification", "::", "CreateNotificationJob", ".", "set", "(", "wait", ":", "5", ".", "seconds", ")", ".", "perform_later", "(", "self", ",", "self", ".", "authorable", ",", "i", ",", "action", ":", "\"mentioned\"", ",", "notified_type", ":", "\"User\"", ",", "notified_ids", ":", "[", "i", ".", "id", "]", ",", "email_template_id", ":", "FiatNotifications", ".", "email_template_id", ",", "email_subject", ":", "\"You were mentioned: '#{self.commentable.subject}' on #{l self.created_at, format: :complete}\"", ",", "email_body", ":", "\"#{self.body}\"", ",", "reply_to_address", ":", "FiatNotifications", ".", "reply_to_email_address", ")", "end", "end", "end" ]
Ideally, this would be polymorphic-enabled
[ "Ideally", "this", "would", "be", "polymorphic", "-", "enabled" ]
f4c7209cd7c5e7a51bb70b90171d6e769792c6cf
https://github.com/fiatinsight/fiat_publication/blob/f4c7209cd7c5e7a51bb70b90171d6e769792c6cf/app/models/fiat_publication/comment.rb#L28-L51
3,246
code0100fun/assignment
lib/assignment/attributes.rb
Assignment.Attributes.assign_attributes
def assign_attributes(new_attributes) if !new_attributes.respond_to?(:stringify_keys) raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." end return if new_attributes.nil? || new_attributes.empty? attributes = new_attributes.stringify_keys _assign_attributes(attributes) end
ruby
def assign_attributes(new_attributes) if !new_attributes.respond_to?(:stringify_keys) raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." end return if new_attributes.nil? || new_attributes.empty? attributes = new_attributes.stringify_keys _assign_attributes(attributes) end
[ "def", "assign_attributes", "(", "new_attributes", ")", "if", "!", "new_attributes", ".", "respond_to?", "(", ":stringify_keys", ")", "raise", "ArgumentError", ",", "\"When assigning attributes, you must pass a hash as an argument.\"", "end", "return", "if", "new_attributes", ".", "nil?", "||", "new_attributes", ".", "empty?", "attributes", "=", "new_attributes", ".", "stringify_keys", "_assign_attributes", "(", "attributes", ")", "end" ]
Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names. class Cat include Assignment::Attributes attr_accessor :name, :status end cat = Cat.new cat.assign_attributes(name: "Gorby", status: "yawning") cat.name # => 'Gorby' cat.status => 'yawning' cat.assign_attributes(status: "sleeping") cat.name # => 'Gorby' cat.status => 'sleeping'
[ "Allows", "you", "to", "set", "all", "the", "attributes", "by", "passing", "in", "a", "hash", "of", "attributes", "with", "keys", "matching", "the", "attribute", "names", "." ]
40134e362dbbe60c6217cf147675ef7df136114d
https://github.com/code0100fun/assignment/blob/40134e362dbbe60c6217cf147675ef7df136114d/lib/assignment/attributes.rb#L21-L29
3,247
stvvan/hoiio-ruby
lib/hoiio-ruby/util/response_util.rb
Hoiio.ResponseUtil.create_hash
def create_hash(response) begin JSON.parse response rescue JSON::ParserError response rescue StandardError response end end
ruby
def create_hash(response) begin JSON.parse response rescue JSON::ParserError response rescue StandardError response end end
[ "def", "create_hash", "(", "response", ")", "begin", "JSON", ".", "parse", "response", "rescue", "JSON", "::", "ParserError", "response", "rescue", "StandardError", "response", "end", "end" ]
Create a Hash from a JSON response @param response response of Hoiio API @return response parsed as a Hash
[ "Create", "a", "Hash", "from", "a", "JSON", "response" ]
7f6840b94c5f61c221619ca069bc008d502dd339
https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/util/response_util.rb#L48-L56
3,248
metanorma/gb-agencies
lib/gb_agencies/gb_agencies.rb
GbAgencies.Agencies.standard_agency1
def standard_agency1(scope, prefix, mandate) case scope when "national" ret = NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil ret = ret.join(" ") if ret && ret.is_a?(Array) ret when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" LOCAL&.dig(@lang, prefix.to_sym) || nil when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
ruby
def standard_agency1(scope, prefix, mandate) case scope when "national" ret = NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil ret = ret.join(" ") if ret && ret.is_a?(Array) ret when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" LOCAL&.dig(@lang, prefix.to_sym) || nil when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
[ "def", "standard_agency1", "(", "scope", ",", "prefix", ",", "mandate", ")", "case", "scope", "when", "\"national\"", "ret", "=", "NATIONAL", "&.", "dig", "(", "@lang", ",", "gb_mandate_suffix", "(", "prefix", ",", "mandate", ")", ".", "to_sym", ",", ":admin", ")", "||", "nil", "ret", "=", "ret", ".", "join", "(", "\" \"", ")", "if", "ret", "&&", "ret", ".", "is_a?", "(", "Array", ")", "ret", "when", "\"sector\"", "SECTOR", "&.", "dig", "(", "@lang", ",", "prefix", ".", "to_sym", ",", ":admin", ")", "||", "nil", "when", "\"local\"", "LOCAL", "&.", "dig", "(", "@lang", ",", "prefix", ".", "to_sym", ")", "||", "nil", "when", "\"enterprise\"", ",", "\"social-group\"", "@issuer", "||", "nil", "when", "\"professional\"", "then", "\"PROFESSIONAL STANDARD\"", "# TODO", "end", "end" ]
return agency name as single string
[ "return", "agency", "name", "as", "single", "string" ]
3840dcdcb8dd4b88f40542a3b3ee8931e065fac0
https://github.com/metanorma/gb-agencies/blob/3840dcdcb8dd4b88f40542a3b3ee8931e065fac0/lib/gb_agencies/gb_agencies.rb#L287-L302
3,249
metanorma/gb-agencies
lib/gb_agencies/gb_agencies.rb
GbAgencies.Agencies.standard_agency
def standard_agency(scope, prefix, mandate) case scope when "national" NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" "#{LOCAL&.dig(@lang, prefix.to_sym) || 'XXXX'}#{@labels["local_issuer"]}" when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
ruby
def standard_agency(scope, prefix, mandate) case scope when "national" NATIONAL&.dig(@lang, gb_mandate_suffix(prefix, mandate).to_sym, :admin) || nil when "sector" SECTOR&.dig(@lang, prefix.to_sym, :admin) || nil when "local" "#{LOCAL&.dig(@lang, prefix.to_sym) || 'XXXX'}#{@labels["local_issuer"]}" when "enterprise", "social-group" @issuer || nil when "professional" then "PROFESSIONAL STANDARD" # TODO end end
[ "def", "standard_agency", "(", "scope", ",", "prefix", ",", "mandate", ")", "case", "scope", "when", "\"national\"", "NATIONAL", "&.", "dig", "(", "@lang", ",", "gb_mandate_suffix", "(", "prefix", ",", "mandate", ")", ".", "to_sym", ",", ":admin", ")", "||", "nil", "when", "\"sector\"", "SECTOR", "&.", "dig", "(", "@lang", ",", "prefix", ".", "to_sym", ",", ":admin", ")", "||", "nil", "when", "\"local\"", "\"#{LOCAL&.dig(@lang, prefix.to_sym) || 'XXXX'}#{@labels[\"local_issuer\"]}\"", "when", "\"enterprise\"", ",", "\"social-group\"", "@issuer", "||", "nil", "when", "\"professional\"", "then", "\"PROFESSIONAL STANDARD\"", "# TODO", "end", "end" ]
return agency name, allowing arrays in output
[ "return", "agency", "name", "allowing", "arrays", "in", "output" ]
3840dcdcb8dd4b88f40542a3b3ee8931e065fac0
https://github.com/metanorma/gb-agencies/blob/3840dcdcb8dd4b88f40542a3b3ee8931e065fac0/lib/gb_agencies/gb_agencies.rb#L305-L318
3,250
Pluvie/rails-scheduler
lib/scheduler/main_process.rb
Scheduler.MainProcess.start_loop
def start_loop loop do begin # Loads up a job queue. queue = [] # Counts jobs to schedule. running_jobs = @job_class.running.entries schedulable_jobs = @job_class.queued.order_by(scheduled_at: :asc).entries jobs_to_schedule = @max_concurrent_jobs - running_jobs.count jobs_to_schedule = 0 if jobs_to_schedule < 0 # Finds out scheduled jobs waiting to be performed. scheduled_jobs = [] schedulable_jobs.first(jobs_to_schedule).each do |job| job_pid = Process.fork do begin job.perform_now rescue StandardError => e @logger.error "[Scheduler:#{@pid}] Error #{e.class}: #{e.message} "\ "(#{e.backtrace.select { |l| l.include?('app') }.first}).".red end end Process.detach(job_pid) job.update_attribute(:pid, job_pid) scheduled_jobs << job queue << job.id.to_s end # Logs launched jobs if scheduled_jobs.any? @logger.info "[Scheduler:#{@pid}] Launched #{scheduled_jobs.count} "\ "jobs: #{scheduled_jobs.map(&:id).map(&:to_s).join(', ')}.".cyan else if schedulable_jobs.count == 0 @logger.info "[Scheduler:#{@pid}] No jobs in queue.".cyan else @logger.warn "[Scheduler:#{@pid}] No jobs launched, reached maximum "\ "number of concurrent jobs. Jobs in queue: #{schedulable_jobs.count}.".yellow end end # Checks for completed jobs: clears up queue and kills any zombie pid queue.delete_if do |job_id| job = @job_class.find(job_id) if job.present? and job.status.in? [ :completed, :error ] begin @logger.info "[Scheduler:#{@pid}] Rimosso processo #{job.pid} per lavoro completato".cyan Process.kill :QUIT, job.pid rescue Errno::ENOENT, Errno::ESRCH end true else false end end # Waits the specified amount of time before next iteration sleep @polling_interval rescue StandardError => error @logger.error "[Scheduler:#{@pid}] Error #{error.message}".red @logger.error error.backtrace.select { |line| line.include?('app') }.join("\n").red rescue SignalException => signal if signal.message.in? [ 'SIGINT', 'SIGTERM', 'SIGQUIT' ] @logger.warn "[Scheduler:#{@pid}] Received interrupt, terminating scheduler..".yellow reschedule_running_jobs break end end end end
ruby
def start_loop loop do begin # Loads up a job queue. queue = [] # Counts jobs to schedule. running_jobs = @job_class.running.entries schedulable_jobs = @job_class.queued.order_by(scheduled_at: :asc).entries jobs_to_schedule = @max_concurrent_jobs - running_jobs.count jobs_to_schedule = 0 if jobs_to_schedule < 0 # Finds out scheduled jobs waiting to be performed. scheduled_jobs = [] schedulable_jobs.first(jobs_to_schedule).each do |job| job_pid = Process.fork do begin job.perform_now rescue StandardError => e @logger.error "[Scheduler:#{@pid}] Error #{e.class}: #{e.message} "\ "(#{e.backtrace.select { |l| l.include?('app') }.first}).".red end end Process.detach(job_pid) job.update_attribute(:pid, job_pid) scheduled_jobs << job queue << job.id.to_s end # Logs launched jobs if scheduled_jobs.any? @logger.info "[Scheduler:#{@pid}] Launched #{scheduled_jobs.count} "\ "jobs: #{scheduled_jobs.map(&:id).map(&:to_s).join(', ')}.".cyan else if schedulable_jobs.count == 0 @logger.info "[Scheduler:#{@pid}] No jobs in queue.".cyan else @logger.warn "[Scheduler:#{@pid}] No jobs launched, reached maximum "\ "number of concurrent jobs. Jobs in queue: #{schedulable_jobs.count}.".yellow end end # Checks for completed jobs: clears up queue and kills any zombie pid queue.delete_if do |job_id| job = @job_class.find(job_id) if job.present? and job.status.in? [ :completed, :error ] begin @logger.info "[Scheduler:#{@pid}] Rimosso processo #{job.pid} per lavoro completato".cyan Process.kill :QUIT, job.pid rescue Errno::ENOENT, Errno::ESRCH end true else false end end # Waits the specified amount of time before next iteration sleep @polling_interval rescue StandardError => error @logger.error "[Scheduler:#{@pid}] Error #{error.message}".red @logger.error error.backtrace.select { |line| line.include?('app') }.join("\n").red rescue SignalException => signal if signal.message.in? [ 'SIGINT', 'SIGTERM', 'SIGQUIT' ] @logger.warn "[Scheduler:#{@pid}] Received interrupt, terminating scheduler..".yellow reschedule_running_jobs break end end end end
[ "def", "start_loop", "loop", "do", "begin", "# Loads up a job queue.", "queue", "=", "[", "]", "# Counts jobs to schedule.", "running_jobs", "=", "@job_class", ".", "running", ".", "entries", "schedulable_jobs", "=", "@job_class", ".", "queued", ".", "order_by", "(", "scheduled_at", ":", ":asc", ")", ".", "entries", "jobs_to_schedule", "=", "@max_concurrent_jobs", "-", "running_jobs", ".", "count", "jobs_to_schedule", "=", "0", "if", "jobs_to_schedule", "<", "0", "# Finds out scheduled jobs waiting to be performed.", "scheduled_jobs", "=", "[", "]", "schedulable_jobs", ".", "first", "(", "jobs_to_schedule", ")", ".", "each", "do", "|", "job", "|", "job_pid", "=", "Process", ".", "fork", "do", "begin", "job", ".", "perform_now", "rescue", "StandardError", "=>", "e", "@logger", ".", "error", "\"[Scheduler:#{@pid}] Error #{e.class}: #{e.message} \"", "\"(#{e.backtrace.select { |l| l.include?('app') }.first}).\"", ".", "red", "end", "end", "Process", ".", "detach", "(", "job_pid", ")", "job", ".", "update_attribute", "(", ":pid", ",", "job_pid", ")", "scheduled_jobs", "<<", "job", "queue", "<<", "job", ".", "id", ".", "to_s", "end", "# Logs launched jobs", "if", "scheduled_jobs", ".", "any?", "@logger", ".", "info", "\"[Scheduler:#{@pid}] Launched #{scheduled_jobs.count} \"", "\"jobs: #{scheduled_jobs.map(&:id).map(&:to_s).join(', ')}.\"", ".", "cyan", "else", "if", "schedulable_jobs", ".", "count", "==", "0", "@logger", ".", "info", "\"[Scheduler:#{@pid}] No jobs in queue.\"", ".", "cyan", "else", "@logger", ".", "warn", "\"[Scheduler:#{@pid}] No jobs launched, reached maximum \"", "\"number of concurrent jobs. Jobs in queue: #{schedulable_jobs.count}.\"", ".", "yellow", "end", "end", "# Checks for completed jobs: clears up queue and kills any zombie pid", "queue", ".", "delete_if", "do", "|", "job_id", "|", "job", "=", "@job_class", ".", "find", "(", "job_id", ")", "if", "job", ".", "present?", "and", "job", ".", "status", ".", "in?", "[", ":completed", ",", ":error", "]", "begin", "@logger", ".", "info", "\"[Scheduler:#{@pid}] Rimosso processo #{job.pid} per lavoro completato\"", ".", "cyan", "Process", ".", "kill", ":QUIT", ",", "job", ".", "pid", "rescue", "Errno", "::", "ENOENT", ",", "Errno", "::", "ESRCH", "end", "true", "else", "false", "end", "end", "# Waits the specified amount of time before next iteration", "sleep", "@polling_interval", "rescue", "StandardError", "=>", "error", "@logger", ".", "error", "\"[Scheduler:#{@pid}] Error #{error.message}\"", ".", "red", "@logger", ".", "error", "error", ".", "backtrace", ".", "select", "{", "|", "line", "|", "line", ".", "include?", "(", "'app'", ")", "}", ".", "join", "(", "\"\\n\"", ")", ".", "red", "rescue", "SignalException", "=>", "signal", "if", "signal", ".", "message", ".", "in?", "[", "'SIGINT'", ",", "'SIGTERM'", ",", "'SIGQUIT'", "]", "@logger", ".", "warn", "\"[Scheduler:#{@pid}] Received interrupt, terminating scheduler..\"", ".", "yellow", "reschedule_running_jobs", "break", "end", "end", "end", "end" ]
Creates a MainProcess which keeps running and continuously checks if new jobs are queued. @return [Scheduler::MainProcess] the created MainProcess. Main loop. @return [nil]
[ "Creates", "a", "MainProcess", "which", "keeps", "running", "and", "continuously", "checks", "if", "new", "jobs", "are", "queued", "." ]
9421c6f1465ae93780e5177b20ac613a6bbd5b9c
https://github.com/Pluvie/rails-scheduler/blob/9421c6f1465ae93780e5177b20ac613a6bbd5b9c/lib/scheduler/main_process.rb#L50-L118
3,251
Pluvie/rails-scheduler
lib/scheduler/main_process.rb
Scheduler.MainProcess.reschedule_running_jobs
def reschedule_running_jobs @job_class.running.each do |job| begin Process.kill :QUIT, job.pid if job.pid.present? rescue Errno::ESRCH, Errno::EPERM ensure job.schedule end end end
ruby
def reschedule_running_jobs @job_class.running.each do |job| begin Process.kill :QUIT, job.pid if job.pid.present? rescue Errno::ESRCH, Errno::EPERM ensure job.schedule end end end
[ "def", "reschedule_running_jobs", "@job_class", ".", "running", ".", "each", "do", "|", "job", "|", "begin", "Process", ".", "kill", ":QUIT", ",", "job", ".", "pid", "if", "job", ".", "pid", ".", "present?", "rescue", "Errno", "::", "ESRCH", ",", "Errno", "::", "EPERM", "ensure", "job", ".", "schedule", "end", "end", "end" ]
Reschedules currently running jobs. @return [nil]
[ "Reschedules", "currently", "running", "jobs", "." ]
9421c6f1465ae93780e5177b20ac613a6bbd5b9c
https://github.com/Pluvie/rails-scheduler/blob/9421c6f1465ae93780e5177b20ac613a6bbd5b9c/lib/scheduler/main_process.rb#L124-L133
3,252
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.device_data
def device_data JSON.parse(ENV['DEVICES']).find { |t| t['thread'].eql? thread } unless ENV['DEVICES'].nil? end
ruby
def device_data JSON.parse(ENV['DEVICES']).find { |t| t['thread'].eql? thread } unless ENV['DEVICES'].nil? end
[ "def", "device_data", "JSON", ".", "parse", "(", "ENV", "[", "'DEVICES'", "]", ")", ".", "find", "{", "|", "t", "|", "t", "[", "'thread'", "]", ".", "eql?", "thread", "}", "unless", "ENV", "[", "'DEVICES'", "]", ".", "nil?", "end" ]
Get the device data from the DEVICES environment variable
[ "Get", "the", "device", "data", "from", "the", "DEVICES", "environment", "variable" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L10-L12
3,253
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.save_device_data
def save_device_data(dev_array) dev_array.each do |device| device_hash = {} device.each do |key, value| device_hash[key] = value end # Delete and create output folder `rm -rf output` `mkdir output` device.each do |k, v| open("output/specs-#{device_hash[:udid]}.log", 'a') do |file| file << "#{k}: #{v}\n" end end end end
ruby
def save_device_data(dev_array) dev_array.each do |device| device_hash = {} device.each do |key, value| device_hash[key] = value end # Delete and create output folder `rm -rf output` `mkdir output` device.each do |k, v| open("output/specs-#{device_hash[:udid]}.log", 'a') do |file| file << "#{k}: #{v}\n" end end end end
[ "def", "save_device_data", "(", "dev_array", ")", "dev_array", ".", "each", "do", "|", "device", "|", "device_hash", "=", "{", "}", "device", ".", "each", "do", "|", "key", ",", "value", "|", "device_hash", "[", "key", "]", "=", "value", "end", "# Delete and create output folder", "`", "`", "`", "`", "device", ".", "each", "do", "|", "k", ",", "v", "|", "open", "(", "\"output/specs-#{device_hash[:udid]}.log\"", ",", "'a'", ")", "do", "|", "file", "|", "file", "<<", "\"#{k}: #{v}\\n\"", "end", "end", "end", "end" ]
Save device specifications to output directory
[ "Save", "device", "specifications", "to", "output", "directory" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L15-L32
3,254
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.get_devices
def get_devices(platform) ENV['THREADS'] = '1' if ENV['THREADS'].nil? if platform == 'android' Android.new.devices elsif platform == 'ios' IOS.new.devices end end
ruby
def get_devices(platform) ENV['THREADS'] = '1' if ENV['THREADS'].nil? if platform == 'android' Android.new.devices elsif platform == 'ios' IOS.new.devices end end
[ "def", "get_devices", "(", "platform", ")", "ENV", "[", "'THREADS'", "]", "=", "'1'", "if", "ENV", "[", "'THREADS'", "]", ".", "nil?", "if", "platform", "==", "'android'", "Android", ".", "new", ".", "devices", "elsif", "platform", "==", "'ios'", "IOS", ".", "new", ".", "devices", "end", "end" ]
Get the device information for the respective platform
[ "Get", "the", "device", "information", "for", "the", "respective", "platform" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L41-L48
3,255
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.appium_server_start
def appium_server_start(**options) command = +'appium' command << " --nodeconfig #{options[:config]}" if options.key?(:config) command << " -p #{options[:port]}" if options.key?(:port) command << " -bp #{options[:bp]}" if options.key?(:bp) command << " --log #{Dir.pwd}/output/#{options[:log]}" if options.key?(:log) command << " --tmp #{ENV['BASE_DIR']}/tmp/#{options[:tmp]}" if options.key?(:tmp) Dir.chdir('.') do puts(command) pid = spawn(command, out: '/dev/null') puts 'Waiting for Appium to start up...' sleep 10 puts "Appium PID: #{pid}" puts 'Appium server did not start' if pid.nil? end end
ruby
def appium_server_start(**options) command = +'appium' command << " --nodeconfig #{options[:config]}" if options.key?(:config) command << " -p #{options[:port]}" if options.key?(:port) command << " -bp #{options[:bp]}" if options.key?(:bp) command << " --log #{Dir.pwd}/output/#{options[:log]}" if options.key?(:log) command << " --tmp #{ENV['BASE_DIR']}/tmp/#{options[:tmp]}" if options.key?(:tmp) Dir.chdir('.') do puts(command) pid = spawn(command, out: '/dev/null') puts 'Waiting for Appium to start up...' sleep 10 puts "Appium PID: #{pid}" puts 'Appium server did not start' if pid.nil? end end
[ "def", "appium_server_start", "(", "**", "options", ")", "command", "=", "+", "'appium'", "command", "<<", "\" --nodeconfig #{options[:config]}\"", "if", "options", ".", "key?", "(", ":config", ")", "command", "<<", "\" -p #{options[:port]}\"", "if", "options", ".", "key?", "(", ":port", ")", "command", "<<", "\" -bp #{options[:bp]}\"", "if", "options", ".", "key?", "(", ":bp", ")", "command", "<<", "\" --log #{Dir.pwd}/output/#{options[:log]}\"", "if", "options", ".", "key?", "(", ":log", ")", "command", "<<", "\" --tmp #{ENV['BASE_DIR']}/tmp/#{options[:tmp]}\"", "if", "options", ".", "key?", "(", ":tmp", ")", "Dir", ".", "chdir", "(", "'.'", ")", "do", "puts", "(", "command", ")", "pid", "=", "spawn", "(", "command", ",", "out", ":", "'/dev/null'", ")", "puts", "'Waiting for Appium to start up...'", "sleep", "10", "puts", "\"Appium PID: #{pid}\"", "puts", "'Appium server did not start'", "if", "pid", ".", "nil?", "end", "end" ]
Start the appium server with the specified options
[ "Start", "the", "appium", "server", "with", "the", "specified", "options" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L51-L66
3,256
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.generate_node_config
def generate_node_config(file_name, appium_port, device) system 'mkdir node_configs >> /dev/null 2>&1' f = File.new("#{Dir.pwd}/node_configs/#{file_name}", 'w') f.write(JSON.generate( capabilities: [{ browserName: device[:udid], maxInstances: 5, platform: device[:platform] }], configuration: { cleanUpCycle: 2000, timeout: 1_800_000, registerCycle: 5000, proxy: 'org.openqa.grid.selenium.proxy.DefaultRemoteProxy', url: "http://127.0.0.1:#{appium_port}/wd/hub", host: '127.0.0.1', port: appium_port, maxSession: 5, register: true, hubPort: 4444, hubHost: 'localhost' } )) f.close end
ruby
def generate_node_config(file_name, appium_port, device) system 'mkdir node_configs >> /dev/null 2>&1' f = File.new("#{Dir.pwd}/node_configs/#{file_name}", 'w') f.write(JSON.generate( capabilities: [{ browserName: device[:udid], maxInstances: 5, platform: device[:platform] }], configuration: { cleanUpCycle: 2000, timeout: 1_800_000, registerCycle: 5000, proxy: 'org.openqa.grid.selenium.proxy.DefaultRemoteProxy', url: "http://127.0.0.1:#{appium_port}/wd/hub", host: '127.0.0.1', port: appium_port, maxSession: 5, register: true, hubPort: 4444, hubHost: 'localhost' } )) f.close end
[ "def", "generate_node_config", "(", "file_name", ",", "appium_port", ",", "device", ")", "system", "'mkdir node_configs >> /dev/null 2>&1'", "f", "=", "File", ".", "new", "(", "\"#{Dir.pwd}/node_configs/#{file_name}\"", ",", "'w'", ")", "f", ".", "write", "(", "JSON", ".", "generate", "(", "capabilities", ":", "[", "{", "browserName", ":", "device", "[", ":udid", "]", ",", "maxInstances", ":", "5", ",", "platform", ":", "device", "[", ":platform", "]", "}", "]", ",", "configuration", ":", "{", "cleanUpCycle", ":", "2000", ",", "timeout", ":", "1_800_000", ",", "registerCycle", ":", "5000", ",", "proxy", ":", "'org.openqa.grid.selenium.proxy.DefaultRemoteProxy'", ",", "url", ":", "\"http://127.0.0.1:#{appium_port}/wd/hub\"", ",", "host", ":", "'127.0.0.1'", ",", "port", ":", "appium_port", ",", "maxSession", ":", "5", ",", "register", ":", "true", ",", "hubPort", ":", "4444", ",", "hubHost", ":", "'localhost'", "}", ")", ")", "f", ".", "close", "end" ]
Generate node config for sellenium grid
[ "Generate", "node", "config", "for", "sellenium", "grid" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L69-L87
3,257
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.start_single_appium
def start_single_appium(platform, port) puts 'Getting Device data' devices = get_devices(platform)[0] if devices.nil? puts "No devices for #{platform}, Exiting..." exit else udid = devices[:udid] save_device_data [devices] end ENV['UDID'] = udid appium_server_start udid: udid, log: "appium-#{udid}.log", port: port end
ruby
def start_single_appium(platform, port) puts 'Getting Device data' devices = get_devices(platform)[0] if devices.nil? puts "No devices for #{platform}, Exiting..." exit else udid = devices[:udid] save_device_data [devices] end ENV['UDID'] = udid appium_server_start udid: udid, log: "appium-#{udid}.log", port: port end
[ "def", "start_single_appium", "(", "platform", ",", "port", ")", "puts", "'Getting Device data'", "devices", "=", "get_devices", "(", "platform", ")", "[", "0", "]", "if", "devices", ".", "nil?", "puts", "\"No devices for #{platform}, Exiting...\"", "exit", "else", "udid", "=", "devices", "[", ":udid", "]", "save_device_data", "[", "devices", "]", "end", "ENV", "[", "'UDID'", "]", "=", "udid", "appium_server_start", "udid", ":", "udid", ",", "log", ":", "\"appium-#{udid}.log\"", ",", "port", ":", "port", "end" ]
Start an appium server or the platform on the specified port
[ "Start", "an", "appium", "server", "or", "the", "platform", "on", "the", "specified", "port" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L97-L109
3,258
JavonDavis/parallel_appium
lib/parallel_appium/server.rb
ParallelAppium.Server.launch_hub_and_nodes
def launch_hub_and_nodes(platform) start_hub unless port_open?('localhost', 4444) devices = get_devices(platform) if devices.nil? puts "No devices for #{platform}, Exiting...." exit else save_device_data [devices] end threads = ENV['THREADS'].to_i if devices.size < threads puts "Not enough available devices, reducing to #{devices.size} threads" ENV['THREADS'] = devices.size.to_s else puts "Using #{threads} of the available #{devices.size} devices" devices = devices[0, threads] end Parallel.map_with_index(devices, in_processes: devices.size) do |device, index| offset = platform == 'android' ? 0 : threads port = 4000 + index + offset bp = 2250 + index + offset config_name = "#{device[:udid]}.json" generate_node_config config_name, port, device node_config = "#{Dir.pwd}/node_configs/#{config_name}" puts port appium_server_start config: node_config, port: port, bp: bp, udid: device[:udid], log: "appium-#{device[:udid]}.log", tmp: device[:udid] end end
ruby
def launch_hub_and_nodes(platform) start_hub unless port_open?('localhost', 4444) devices = get_devices(platform) if devices.nil? puts "No devices for #{platform}, Exiting...." exit else save_device_data [devices] end threads = ENV['THREADS'].to_i if devices.size < threads puts "Not enough available devices, reducing to #{devices.size} threads" ENV['THREADS'] = devices.size.to_s else puts "Using #{threads} of the available #{devices.size} devices" devices = devices[0, threads] end Parallel.map_with_index(devices, in_processes: devices.size) do |device, index| offset = platform == 'android' ? 0 : threads port = 4000 + index + offset bp = 2250 + index + offset config_name = "#{device[:udid]}.json" generate_node_config config_name, port, device node_config = "#{Dir.pwd}/node_configs/#{config_name}" puts port appium_server_start config: node_config, port: port, bp: bp, udid: device[:udid], log: "appium-#{device[:udid]}.log", tmp: device[:udid] end end
[ "def", "launch_hub_and_nodes", "(", "platform", ")", "start_hub", "unless", "port_open?", "(", "'localhost'", ",", "4444", ")", "devices", "=", "get_devices", "(", "platform", ")", "if", "devices", ".", "nil?", "puts", "\"No devices for #{platform}, Exiting....\"", "exit", "else", "save_device_data", "[", "devices", "]", "end", "threads", "=", "ENV", "[", "'THREADS'", "]", ".", "to_i", "if", "devices", ".", "size", "<", "threads", "puts", "\"Not enough available devices, reducing to #{devices.size} threads\"", "ENV", "[", "'THREADS'", "]", "=", "devices", ".", "size", ".", "to_s", "else", "puts", "\"Using #{threads} of the available #{devices.size} devices\"", "devices", "=", "devices", "[", "0", ",", "threads", "]", "end", "Parallel", ".", "map_with_index", "(", "devices", ",", "in_processes", ":", "devices", ".", "size", ")", "do", "|", "device", ",", "index", "|", "offset", "=", "platform", "==", "'android'", "?", "0", ":", "threads", "port", "=", "4000", "+", "index", "+", "offset", "bp", "=", "2250", "+", "index", "+", "offset", "config_name", "=", "\"#{device[:udid]}.json\"", "generate_node_config", "config_name", ",", "port", ",", "device", "node_config", "=", "\"#{Dir.pwd}/node_configs/#{config_name}\"", "puts", "port", "appium_server_start", "config", ":", "node_config", ",", "port", ":", "port", ",", "bp", ":", "bp", ",", "udid", ":", "device", "[", ":udid", "]", ",", "log", ":", "\"appium-#{device[:udid]}.log\"", ",", "tmp", ":", "device", "[", ":udid", "]", "end", "end" ]
Launch the Selenium grid hub and required appium instances
[ "Launch", "the", "Selenium", "grid", "hub", "and", "required", "appium", "instances" ]
2e92bf6f4cf6142909080f471dda196ee12c41ea
https://github.com/JavonDavis/parallel_appium/blob/2e92bf6f4cf6142909080f471dda196ee12c41ea/lib/parallel_appium/server.rb#L130-L162
3,259
trisrael/mindbody
lib/mindbody/service.rb
Mb.Service.build_request
def build_request(options = {}) src_creds_name = SRC_CREDS options = options.dup #Don't clobber the original hash #NOTE: Could extend this to read WSDL document or using Savon client to tell which nodes are allowed in the request #performing the same type of test against passed in variables on each and replacing with the appropriate value final_opts = options.dup options.keys.each do |key| orig_key = key new_key = orig_key.to_s.gsub("_", "").downcase if (new_key == src_creds_name.downcase) final_opts[src_creds_name] = final_opts[key] #Set "SourceCredentials" to hash referenced by similarly named final_opts.delete(orig_key) end end opts = {}; final_opts.each do |key, value| new_val = value if value.kind_of?(Array) tranformed = {} if item[0].kind_of? Integer transformed[:int] = value elsif item[0].kind_of? String transformed[:string] = value else break #Don't know how to deal with it, return regular end new_val = transformed end opts[key] = new_val end request_body = { "PageSize" => 10, "CurrentPageIndex" => 0 } request_body["XMLDetail"] = "Bare" unless opts["Fields"] request_body[src_creds_name] = @src_creds.to_hash if @src_creds request_body["UserCredentials"] = @usr_creds.to_hash if @usr_creds return request_body.merge!(opts) end
ruby
def build_request(options = {}) src_creds_name = SRC_CREDS options = options.dup #Don't clobber the original hash #NOTE: Could extend this to read WSDL document or using Savon client to tell which nodes are allowed in the request #performing the same type of test against passed in variables on each and replacing with the appropriate value final_opts = options.dup options.keys.each do |key| orig_key = key new_key = orig_key.to_s.gsub("_", "").downcase if (new_key == src_creds_name.downcase) final_opts[src_creds_name] = final_opts[key] #Set "SourceCredentials" to hash referenced by similarly named final_opts.delete(orig_key) end end opts = {}; final_opts.each do |key, value| new_val = value if value.kind_of?(Array) tranformed = {} if item[0].kind_of? Integer transformed[:int] = value elsif item[0].kind_of? String transformed[:string] = value else break #Don't know how to deal with it, return regular end new_val = transformed end opts[key] = new_val end request_body = { "PageSize" => 10, "CurrentPageIndex" => 0 } request_body["XMLDetail"] = "Bare" unless opts["Fields"] request_body[src_creds_name] = @src_creds.to_hash if @src_creds request_body["UserCredentials"] = @usr_creds.to_hash if @usr_creds return request_body.merge!(opts) end
[ "def", "build_request", "(", "options", "=", "{", "}", ")", "src_creds_name", "=", "SRC_CREDS", "options", "=", "options", ".", "dup", "#Don't clobber the original hash", "#NOTE: Could extend this to read WSDL document or using Savon client to tell which nodes are allowed in the request", "#performing the same type of test against passed in variables on each and replacing with the appropriate value", "final_opts", "=", "options", ".", "dup", "options", ".", "keys", ".", "each", "do", "|", "key", "|", "orig_key", "=", "key", "new_key", "=", "orig_key", ".", "to_s", ".", "gsub", "(", "\"_\"", ",", "\"\"", ")", ".", "downcase", "if", "(", "new_key", "==", "src_creds_name", ".", "downcase", ")", "final_opts", "[", "src_creds_name", "]", "=", "final_opts", "[", "key", "]", "#Set \"SourceCredentials\" to hash referenced by similarly named", "final_opts", ".", "delete", "(", "orig_key", ")", "end", "end", "opts", "=", "{", "}", ";", "final_opts", ".", "each", "do", "|", "key", ",", "value", "|", "new_val", "=", "value", "if", "value", ".", "kind_of?", "(", "Array", ")", "tranformed", "=", "{", "}", "if", "item", "[", "0", "]", ".", "kind_of?", "Integer", "transformed", "[", ":int", "]", "=", "value", "elsif", "item", "[", "0", "]", ".", "kind_of?", "String", "transformed", "[", ":string", "]", "=", "value", "else", "break", "#Don't know how to deal with it, return regular", "end", "new_val", "=", "transformed", "end", "opts", "[", "key", "]", "=", "new_val", "end", "request_body", "=", "{", "\"PageSize\"", "=>", "10", ",", "\"CurrentPageIndex\"", "=>", "0", "}", "request_body", "[", "\"XMLDetail\"", "]", "=", "\"Bare\"", "unless", "opts", "[", "\"Fields\"", "]", "request_body", "[", "src_creds_name", "]", "=", "@src_creds", ".", "to_hash", "if", "@src_creds", "request_body", "[", "\"UserCredentials\"", "]", "=", "@usr_creds", ".", "to_hash", "if", "@usr_creds", "return", "request_body", ".", "merge!", "(", "opts", ")", "end" ]
Builds the inner XML of the Mindbody SOAP call
[ "Builds", "the", "inner", "XML", "of", "the", "Mindbody", "SOAP", "call" ]
3adc8dd4ab09bf74ffc9155f036629edbbbe1dad
https://github.com/trisrael/mindbody/blob/3adc8dd4ab09bf74ffc9155f036629edbbbe1dad/lib/mindbody/service.rb#L58-L107
3,260
trisrael/mindbody
lib/mindbody/service.rb
Mb.Service.get_service
def get_service(service_symbol, options, unwrap_bool) raise "No SOAP client instantiated" unless @client request_options = build_request(options) raise "No SourceCredentials supplied" if !@src_creds || !request_options[SRC_CREDS] #Just checking for :source_credentials does not #check all possiblities as "SourceCredentials", response = @client.request Mb::Meta::NS, service_symbol do soap.body = { "Request" => request_options } end if unwrap_bool #Unwrap response to hash array underneath) plural = service_symbol.to_s.gsub("get_", "") singular =plural[0..-2] #Remove last r = response.to_hash basify = lambda {|enda| (service_symbol.to_s + "_" + enda).to_sym } r = r[basify.call('response')][basify.call('result')] return [] if r[:result_count] == "0" r = r[plural.to_sym][singular.to_sym] return r end response end
ruby
def get_service(service_symbol, options, unwrap_bool) raise "No SOAP client instantiated" unless @client request_options = build_request(options) raise "No SourceCredentials supplied" if !@src_creds || !request_options[SRC_CREDS] #Just checking for :source_credentials does not #check all possiblities as "SourceCredentials", response = @client.request Mb::Meta::NS, service_symbol do soap.body = { "Request" => request_options } end if unwrap_bool #Unwrap response to hash array underneath) plural = service_symbol.to_s.gsub("get_", "") singular =plural[0..-2] #Remove last r = response.to_hash basify = lambda {|enda| (service_symbol.to_s + "_" + enda).to_sym } r = r[basify.call('response')][basify.call('result')] return [] if r[:result_count] == "0" r = r[plural.to_sym][singular.to_sym] return r end response end
[ "def", "get_service", "(", "service_symbol", ",", "options", ",", "unwrap_bool", ")", "raise", "\"No SOAP client instantiated\"", "unless", "@client", "request_options", "=", "build_request", "(", "options", ")", "raise", "\"No SourceCredentials supplied\"", "if", "!", "@src_creds", "||", "!", "request_options", "[", "SRC_CREDS", "]", "#Just checking for :source_credentials does not ", "#check all possiblities as \"SourceCredentials\", ", "response", "=", "@client", ".", "request", "Mb", "::", "Meta", "::", "NS", ",", "service_symbol", "do", "soap", ".", "body", "=", "{", "\"Request\"", "=>", "request_options", "}", "end", "if", "unwrap_bool", "#Unwrap response to hash array underneath)", "plural", "=", "service_symbol", ".", "to_s", ".", "gsub", "(", "\"get_\"", ",", "\"\"", ")", "singular", "=", "plural", "[", "0", "..", "-", "2", "]", "#Remove last", "r", "=", "response", ".", "to_hash", "basify", "=", "lambda", "{", "|", "enda", "|", "(", "service_symbol", ".", "to_s", "+", "\"_\"", "+", "enda", ")", ".", "to_sym", "}", "r", "=", "r", "[", "basify", ".", "call", "(", "'response'", ")", "]", "[", "basify", ".", "call", "(", "'result'", ")", "]", "return", "[", "]", "if", "r", "[", ":result_count", "]", "==", "\"0\"", "r", "=", "r", "[", "plural", ".", "to_sym", "]", "[", "singular", ".", "to_sym", "]", "return", "r", "end", "response", "end" ]
Build a Mindbody SOAP request for the given service
[ "Build", "a", "Mindbody", "SOAP", "request", "for", "the", "given", "service" ]
3adc8dd4ab09bf74ffc9155f036629edbbbe1dad
https://github.com/trisrael/mindbody/blob/3adc8dd4ab09bf74ffc9155f036629edbbbe1dad/lib/mindbody/service.rb#L110-L137
3,261
Bweeb/malcolm
lib/malcolm/response/soap_parser.rb
Malcolm.SOAPParser.on_complete
def on_complete(env) env[:body] = Nori.new( strip_namespaces: true, convert_tags_to: ->(tag) { tag.snakecase.to_sym } ).parse(env[:body]) raise SOAPError, "Invalid SOAP response" if env[:body].empty? env[:body] = env[:body][:envelope][:body] env[:body] = find_key_in_hash(env[:body], @key) end
ruby
def on_complete(env) env[:body] = Nori.new( strip_namespaces: true, convert_tags_to: ->(tag) { tag.snakecase.to_sym } ).parse(env[:body]) raise SOAPError, "Invalid SOAP response" if env[:body].empty? env[:body] = env[:body][:envelope][:body] env[:body] = find_key_in_hash(env[:body], @key) end
[ "def", "on_complete", "(", "env", ")", "env", "[", ":body", "]", "=", "Nori", ".", "new", "(", "strip_namespaces", ":", "true", ",", "convert_tags_to", ":", "->", "(", "tag", ")", "{", "tag", ".", "snakecase", ".", "to_sym", "}", ")", ".", "parse", "(", "env", "[", ":body", "]", ")", "raise", "SOAPError", ",", "\"Invalid SOAP response\"", "if", "env", "[", ":body", "]", ".", "empty?", "env", "[", ":body", "]", "=", "env", "[", ":body", "]", "[", ":envelope", "]", "[", ":body", "]", "env", "[", ":body", "]", "=", "find_key_in_hash", "(", "env", "[", ":body", "]", ",", "@key", ")", "end" ]
Expects response XML to already be parsed
[ "Expects", "response", "XML", "to", "already", "be", "parsed" ]
8a6253ec72a6c15a25fb765d4fceb4d0ede165e7
https://github.com/Bweeb/malcolm/blob/8a6253ec72a6c15a25fb765d4fceb4d0ede165e7/lib/malcolm/response/soap_parser.rb#L10-L20
3,262
Bweeb/malcolm
lib/malcolm/response/soap_parser.rb
Malcolm.SOAPParser.find_key_in_hash
def find_key_in_hash(hash, index) hash.each do |key, val| if val.respond_to? :has_key? if val.has_key? index return val[index] else return find_key_in_hash val, index end else val end end end
ruby
def find_key_in_hash(hash, index) hash.each do |key, val| if val.respond_to? :has_key? if val.has_key? index return val[index] else return find_key_in_hash val, index end else val end end end
[ "def", "find_key_in_hash", "(", "hash", ",", "index", ")", "hash", ".", "each", "do", "|", "key", ",", "val", "|", "if", "val", ".", "respond_to?", ":has_key?", "if", "val", ".", "has_key?", "index", "return", "val", "[", "index", "]", "else", "return", "find_key_in_hash", "val", ",", "index", "end", "else", "val", "end", "end", "end" ]
Finds +index+ in +hash+ by searching recursively @param [Hash] hash The hash to search @param index The hash key to look for
[ "Finds", "+", "index", "+", "in", "+", "hash", "+", "by", "searching", "recursively" ]
8a6253ec72a6c15a25fb765d4fceb4d0ede165e7
https://github.com/Bweeb/malcolm/blob/8a6253ec72a6c15a25fb765d4fceb4d0ede165e7/lib/malcolm/response/soap_parser.rb#L31-L43
3,263
jaymcgavren/zyps
lib/zyps.rb
Zyps.GameObject.<<
def <<(item) if item.kind_of? Zyps::Location self.location = item elsif item.kind_of? Zyps::Color self.color = item elsif item.kind_of? Zyps::Vector self.vector = item else raise "Invalid item: #{item.class}" end self end
ruby
def <<(item) if item.kind_of? Zyps::Location self.location = item elsif item.kind_of? Zyps::Color self.color = item elsif item.kind_of? Zyps::Vector self.vector = item else raise "Invalid item: #{item.class}" end self end
[ "def", "<<", "(", "item", ")", "if", "item", ".", "kind_of?", "Zyps", "::", "Location", "self", ".", "location", "=", "item", "elsif", "item", ".", "kind_of?", "Zyps", "::", "Color", "self", ".", "color", "=", "item", "elsif", "item", ".", "kind_of?", "Zyps", "::", "Vector", "self", ".", "vector", "=", "item", "else", "raise", "\"Invalid item: #{item.class}\"", "end", "self", "end" ]
Overloads the << operator to put the new item into the correct list or assign it to the correct attribute. Assignment is done based on item's class or a parent class of item.
[ "Overloads", "the", "<<", "operator", "to", "put", "the", "new", "item", "into", "the", "correct", "list", "or", "assign", "it", "to", "the", "correct", "attribute", ".", "Assignment", "is", "done", "based", "on", "item", "s", "class", "or", "a", "parent", "class", "of", "item", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps.rb#L270-L281
3,264
jaymcgavren/zyps
lib/zyps.rb
Zyps.Behavior.<<
def <<(item) if item.kind_of? Condition add_condition(item) elsif item.kind_of? Action add_action(item) else raise "Invalid item: #{item.class}" end self end
ruby
def <<(item) if item.kind_of? Condition add_condition(item) elsif item.kind_of? Action add_action(item) else raise "Invalid item: #{item.class}" end self end
[ "def", "<<", "(", "item", ")", "if", "item", ".", "kind_of?", "Condition", "add_condition", "(", "item", ")", "elsif", "item", ".", "kind_of?", "Action", "add_action", "(", "item", ")", "else", "raise", "\"Invalid item: #{item.class}\"", "end", "self", "end" ]
True if all attributes, actions and conditions are the same. Overloads the << operator to put the new item into the correct list or assign it to the correct attribute. Assignment is done based on item's class or a parent class of item.
[ "True", "if", "all", "attributes", "actions", "and", "conditions", "are", "the", "same", ".", "Overloads", "the", "<<", "operator", "to", "put", "the", "new", "item", "into", "the", "correct", "list", "or", "assign", "it", "to", "the", "correct", "attribute", ".", "Assignment", "is", "done", "based", "on", "item", "s", "class", "or", "a", "parent", "class", "of", "item", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps.rb#L599-L608
3,265
jaymcgavren/zyps
lib/zyps.rb
Zyps.Vector.+
def +(vector2) #Get the x and y components of the new vector. new_x = (self.x + vector2.x) new_y = (self.y + vector2.y) new_length_squared = new_x ** 2 + new_y ** 2 new_length = (new_length_squared == 0 ? 0 : Math.sqrt(new_length_squared)) new_angle = (new_x == 0 ? 0 : Utility.to_degrees(Math.atan2(new_y, new_x))) #Calculate speed and angle of new vector with components. Vector.new(new_length, new_angle) end
ruby
def +(vector2) #Get the x and y components of the new vector. new_x = (self.x + vector2.x) new_y = (self.y + vector2.y) new_length_squared = new_x ** 2 + new_y ** 2 new_length = (new_length_squared == 0 ? 0 : Math.sqrt(new_length_squared)) new_angle = (new_x == 0 ? 0 : Utility.to_degrees(Math.atan2(new_y, new_x))) #Calculate speed and angle of new vector with components. Vector.new(new_length, new_angle) end
[ "def", "+", "(", "vector2", ")", "#Get the x and y components of the new vector.", "new_x", "=", "(", "self", ".", "x", "+", "vector2", ".", "x", ")", "new_y", "=", "(", "self", ".", "y", "+", "vector2", ".", "y", ")", "new_length_squared", "=", "new_x", "**", "2", "+", "new_y", "**", "2", "new_length", "=", "(", "new_length_squared", "==", "0", "?", "0", ":", "Math", ".", "sqrt", "(", "new_length_squared", ")", ")", "new_angle", "=", "(", "new_x", "==", "0", "?", "0", ":", "Utility", ".", "to_degrees", "(", "Math", ".", "atan2", "(", "new_y", ",", "new_x", ")", ")", ")", "#Calculate speed and angle of new vector with components.", "Vector", ".", "new", "(", "new_length", ",", "new_angle", ")", "end" ]
Add this Vector to vector2, returning a new Vector. This operation is useful when calculating the effect of wind or thrust on an object's current heading.
[ "Add", "this", "Vector", "to", "vector2", "returning", "a", "new", "Vector", ".", "This", "operation", "is", "useful", "when", "calculating", "the", "effect", "of", "wind", "or", "thrust", "on", "an", "object", "s", "current", "heading", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps.rb#L765-L774
3,266
faradayio/charisma
lib/charisma/measurement.rb
Charisma.Measurement.method_missing
def method_missing(*args) if Conversions.conversions[units.to_sym][args.first] to_f.send(units.to_sym).to(args.first) else super end end
ruby
def method_missing(*args) if Conversions.conversions[units.to_sym][args.first] to_f.send(units.to_sym).to(args.first) else super end end
[ "def", "method_missing", "(", "*", "args", ")", "if", "Conversions", ".", "conversions", "[", "units", ".", "to_sym", "]", "[", "args", ".", "first", "]", "to_f", ".", "send", "(", "units", ".", "to_sym", ")", ".", "to", "(", "args", ".", "first", ")", "else", "super", "end", "end" ]
Handle conversion methods
[ "Handle", "conversion", "methods" ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/measurement.rb#L44-L50
3,267
spudtrooper/rdiorb
lib/rdio/types.rb
Rdio.Artist.albums
def albums(featuring=nil,extras=nil,start=nil,count=nil) api.getAlbumsForArtist self,featuring,extras,start,count end
ruby
def albums(featuring=nil,extras=nil,start=nil,count=nil) api.getAlbumsForArtist self,featuring,extras,start,count end
[ "def", "albums", "(", "featuring", "=", "nil", ",", "extras", "=", "nil", ",", "start", "=", "nil", ",", "count", "=", "nil", ")", "api", ".", "getAlbumsForArtist", "self", ",", "featuring", ",", "extras", ",", "start", ",", "count", "end" ]
Get all the albums by this artist
[ "Get", "all", "the", "albums", "by", "this", "artist" ]
e137fd016bfba42d9e50f421b009b2ad3c41baaf
https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/types.rb#L45-L47
3,268
spudtrooper/rdiorb
lib/rdio/types.rb
Rdio.Playlist.tracks
def tracks ids = track_keys return [] if not ids return ids.map {|id| Track.get id} end
ruby
def tracks ids = track_keys return [] if not ids return ids.map {|id| Track.get id} end
[ "def", "tracks", "ids", "=", "track_keys", "return", "[", "]", "if", "not", "ids", "return", "ids", ".", "map", "{", "|", "id", "|", "Track", ".", "get", "id", "}", "end" ]
Returns an array of tracks
[ "Returns", "an", "array", "of", "tracks" ]
e137fd016bfba42d9e50f421b009b2ad3c41baaf
https://github.com/spudtrooper/rdiorb/blob/e137fd016bfba42d9e50f421b009b2ad3c41baaf/lib/rdio/types.rb#L342-L346
3,269
drish/hyperb
lib/hyperb/funcs/funcs.rb
Hyperb.Funcs.create_func
def create_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/create' body = {} body.merge!(prepare_json(params)) Hyperb::Request.new(self, path, {}, 'post', body).perform end
ruby
def create_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/create' body = {} body.merge!(prepare_json(params)) Hyperb::Request.new(self, path, {}, 'post', body).perform end
[ "def", "create_func", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid arguments.'", "unless", "check_arguments", "(", "params", ",", "'name'", ")", "path", "=", "'/funcs/create'", "body", "=", "{", "}", "body", ".", "merge!", "(", "prepare_json", "(", "params", ")", ")", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "{", "}", ",", "'post'", ",", "body", ")", ".", "perform", "end" ]
create a func @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Func/create.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::Conflict] raised when func already exist @raise [Hyperb::Error::BadRequest] raised when a bad parameter is sent @raise [Hyperb::Error::InternalServerError] server error on hyper side. @raise [ArgumentError] when required arguments are not provided. @param params [Hash] A customizable set of params. @param params :name [String] the function name. @param params :container_size [String] the size of containers to run the function (e.g. s1,s2, s3, s4, m1, m2, m3, l1, l2, l3) @param params :timeout [String] default is 300 seconds, maximum is 86400 seconds. @param params :uuid [String] The uuid of function. @param params :config [Hash] func configurations @param params config :tty [Boolean] attach streams to a tty @param params config :exposed_ports [Hash] an object mapping ports to an empty object in the form of: "ExposedPorts": { "<port>/<tcp|udp>: {}" } @param params config :env [Array] list of env vars, "VAR=VALUE" @param params config :cmd [Array|String] list of env vars, "VAR=VALUE" @param params config :image [String] image to run @param params config :entrypoint [String] entrypoint @param params config :working_dir [String] working directory @param params config :labels [Hash] labels @param params :host_config [Hash] func host configurations @param params host_config :links [Array] list of links @param params host_config :port_bindings [Hash] @param params host_config :publish_all_ports [Boolean] @param params host_config :volumes_from [Array] @param params host_config :network_mode [String]
[ "create", "a", "func" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/funcs/funcs.rb#L80-L88
3,270
drish/hyperb
lib/hyperb/funcs/funcs.rb
Hyperb.Funcs.remove_func
def remove_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/' + params[:name] Hyperb::Request.new(self, path, {}, 'delete').perform end
ruby
def remove_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name') path = '/funcs/' + params[:name] Hyperb::Request.new(self, path, {}, 'delete').perform end
[ "def", "remove_func", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid arguments.'", "unless", "check_arguments", "(", "params", ",", "'name'", ")", "path", "=", "'/funcs/'", "+", "params", "[", ":name", "]", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "{", "}", ",", "'delete'", ")", ".", "perform", "end" ]
remove a func @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Func/remove.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::Conflict] raised when func with that name is running @raise [Hyperb::Error::BadRequest] raised when a bad parameter is sent @raise [Hyperb::Error::InternalServerError] server error on hyper side. @raise [ArgumentError] when required arguments are not provided. @param params [Hash] A customizable set of params. @param params :name [String] the function name.
[ "remove", "a", "func" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/funcs/funcs.rb#L103-L107
3,271
drish/hyperb
lib/hyperb/funcs/funcs.rb
Hyperb.Funcs.call_func
def call_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name', 'uuid') path = "call/#{params[:name]}/#{params[:uuid]}" path.concat('/sync') if params.key?(:sync) && params[:sync] Hyperb::FuncCallRequest.new(self, path, {}, 'post').perform end
ruby
def call_func(params = {}) raise ArgumentError, 'Invalid arguments.' unless check_arguments(params, 'name', 'uuid') path = "call/#{params[:name]}/#{params[:uuid]}" path.concat('/sync') if params.key?(:sync) && params[:sync] Hyperb::FuncCallRequest.new(self, path, {}, 'post').perform end
[ "def", "call_func", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid arguments.'", "unless", "check_arguments", "(", "params", ",", "'name'", ",", "'uuid'", ")", "path", "=", "\"call/#{params[:name]}/#{params[:uuid]}\"", "path", ".", "concat", "(", "'/sync'", ")", "if", "params", ".", "key?", "(", ":sync", ")", "&&", "params", "[", ":sync", "]", "Hyperb", "::", "FuncCallRequest", ".", "new", "(", "self", ",", "path", ",", "{", "}", ",", "'post'", ")", ".", "perform", "end" ]
call a func @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Func/call.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::NotFound] no such func @raise [ArgumentError] when required arguments are not provided. @param params [Hash] A customizable set of params. @param params :name [String] the function name. @param params :uuid [String] function uuid. @param params :sync [Boolean] block until function reply
[ "call", "a", "func" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/funcs/funcs.rb#L122-L127
3,272
zires/open_qq
lib/open_qq/gateway.rb
OpenQq.Gateway.wrap
def wrap(http_method, url, params) params = params.merge(:appid => @appid) params[:sig] = Gateway.signature( "#{@appkey}&", Gateway.make_source(http_method.to_s.upcase, url, params) ) params end
ruby
def wrap(http_method, url, params) params = params.merge(:appid => @appid) params[:sig] = Gateway.signature( "#{@appkey}&", Gateway.make_source(http_method.to_s.upcase, url, params) ) params end
[ "def", "wrap", "(", "http_method", ",", "url", ",", "params", ")", "params", "=", "params", ".", "merge", "(", ":appid", "=>", "@appid", ")", "params", "[", ":sig", "]", "=", "Gateway", ".", "signature", "(", "\"#{@appkey}&\"", ",", "Gateway", ".", "make_source", "(", "http_method", ".", "to_s", ".", "upcase", ",", "url", ",", "params", ")", ")", "params", "end" ]
wrap `http_method`, `url`, `params` together
[ "wrap", "http_method", "url", "params", "together" ]
14bb3dba0aff3152307bd82d69b602e1a7a4ac9e
https://github.com/zires/open_qq/blob/14bb3dba0aff3152307bd82d69b602e1a7a4ac9e/lib/open_qq/gateway.rb#L75-L79
3,273
picatz/Willow-Run
lib/willow_run/sniffer.rb
WillowRun.Sniffer.default_ip
def default_ip begin orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect rand_routable_daddr.to_s, rand_port s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end
ruby
def default_ip begin orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect rand_routable_daddr.to_s, rand_port s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end
[ "def", "default_ip", "begin", "orig", ",", "Socket", ".", "do_not_reverse_lookup", "=", "Socket", ".", "do_not_reverse_lookup", ",", "true", "# turn off reverse DNS resolution temporarily", "UDPSocket", ".", "open", "do", "|", "s", "|", "s", ".", "connect", "rand_routable_daddr", ".", "to_s", ",", "rand_port", "s", ".", "addr", ".", "last", "end", "ensure", "Socket", ".", "do_not_reverse_lookup", "=", "orig", "end", "end" ]
Determine the default ip address, taken from packetfu's utils.rb
[ "Determine", "the", "default", "ip", "address", "taken", "from", "packetfu", "s", "utils", ".", "rb" ]
0953e31fc0e1aac1664f9c06208839c3b4de7359
https://github.com/picatz/Willow-Run/blob/0953e31fc0e1aac1664f9c06208839c3b4de7359/lib/willow_run/sniffer.rb#L81-L91
3,274
picatz/Willow-Run
lib/willow_run/sniffer.rb
WillowRun.Sniffer.default_interface
def default_interface ip = default_ip Socket.getifaddrs.each do |ifaddr| next unless ifaddr.addr.ip? return ifaddr.name if ifaddr.addr.ip_address == ip end # Fall back to libpcap as last resort return Pcap.lookupdev end
ruby
def default_interface ip = default_ip Socket.getifaddrs.each do |ifaddr| next unless ifaddr.addr.ip? return ifaddr.name if ifaddr.addr.ip_address == ip end # Fall back to libpcap as last resort return Pcap.lookupdev end
[ "def", "default_interface", "ip", "=", "default_ip", "Socket", ".", "getifaddrs", ".", "each", "do", "|", "ifaddr", "|", "next", "unless", "ifaddr", ".", "addr", ".", "ip?", "return", "ifaddr", ".", "name", "if", "ifaddr", ".", "addr", ".", "ip_address", "==", "ip", "end", "# Fall back to libpcap as last resort", "return", "Pcap", ".", "lookupdev", "end" ]
Determine the default routeable interface, taken from packetfu's utils.rb
[ "Determine", "the", "default", "routeable", "interface", "taken", "from", "packetfu", "s", "utils", ".", "rb" ]
0953e31fc0e1aac1664f9c06208839c3b4de7359
https://github.com/picatz/Willow-Run/blob/0953e31fc0e1aac1664f9c06208839c3b4de7359/lib/willow_run/sniffer.rb#L94-L102
3,275
Katello/trebuchet
lib/trebuchet/runner.rb
Trebuchet.Runner.run
def run(config, operation_name=nil) config = config.with_indifferent_access config.merge!(load_config(config[:config])) if config[:config] operation_run = false gather_operations.each do |operation| if operation_name.nil? || operation_name == operation.name op = operation.new(config) op.debrief = Trebuchet::Debrief.new({ :operation => op.class.name, :name => config['name'] }) op.run op.save_debrief operation_run = true end end raise "No Operation Run!" unless operation_run end
ruby
def run(config, operation_name=nil) config = config.with_indifferent_access config.merge!(load_config(config[:config])) if config[:config] operation_run = false gather_operations.each do |operation| if operation_name.nil? || operation_name == operation.name op = operation.new(config) op.debrief = Trebuchet::Debrief.new({ :operation => op.class.name, :name => config['name'] }) op.run op.save_debrief operation_run = true end end raise "No Operation Run!" unless operation_run end
[ "def", "run", "(", "config", ",", "operation_name", "=", "nil", ")", "config", "=", "config", ".", "with_indifferent_access", "config", ".", "merge!", "(", "load_config", "(", "config", "[", ":config", "]", ")", ")", "if", "config", "[", ":config", "]", "operation_run", "=", "false", "gather_operations", ".", "each", "do", "|", "operation", "|", "if", "operation_name", ".", "nil?", "||", "operation_name", "==", "operation", ".", "name", "op", "=", "operation", ".", "new", "(", "config", ")", "op", ".", "debrief", "=", "Trebuchet", "::", "Debrief", ".", "new", "(", "{", ":operation", "=>", "op", ".", "class", ".", "name", ",", ":name", "=>", "config", "[", "'name'", "]", "}", ")", "op", ".", "run", "op", ".", "save_debrief", "operation_run", "=", "true", "end", "end", "raise", "\"No Operation Run!\"", "unless", "operation_run", "end" ]
Run all operations, or a specific operation @param [Hash] config config hash to pass to operations (currently :host, :user, :password) @param [String] operation_name the single operation to run, otherwise all
[ "Run", "all", "operations", "or", "a", "specific", "operation" ]
83a34c6cadf8dcf5632b1cb4b2af5bc43dbe1fa5
https://github.com/Katello/trebuchet/blob/83a34c6cadf8dcf5632b1cb4b2af5bc43dbe1fa5/lib/trebuchet/runner.rb#L44-L60
3,276
ic-factory/ecic
lib/ecic/source_file_info.rb
Ecic.SourceFileInfo.find_sources_file_dir
def find_sources_file_dir(dir = @relative_path_from_project.dirname) return nil if is_outside_project? file = File.join(@project.root, dir, "sources.rb") if dir.root? or dir.to_s == "." return nil elsif File.exists?(file) return dir else return find_sources_file_dir(dir.parent) end end
ruby
def find_sources_file_dir(dir = @relative_path_from_project.dirname) return nil if is_outside_project? file = File.join(@project.root, dir, "sources.rb") if dir.root? or dir.to_s == "." return nil elsif File.exists?(file) return dir else return find_sources_file_dir(dir.parent) end end
[ "def", "find_sources_file_dir", "(", "dir", "=", "@relative_path_from_project", ".", "dirname", ")", "return", "nil", "if", "is_outside_project?", "file", "=", "File", ".", "join", "(", "@project", ".", "root", ",", "dir", ",", "\"sources.rb\"", ")", "if", "dir", ".", "root?", "or", "dir", ".", "to_s", "==", "\".\"", "return", "nil", "elsif", "File", ".", "exists?", "(", "file", ")", "return", "dir", "else", "return", "find_sources_file_dir", "(", "dir", ".", "parent", ")", "end", "end" ]
def within_expected_folder? rel_design_path_list = @relative_path_from_project.to_s.split('/') return nil if rel_design_path_list.length < 3 str = [rel_design_path_list.first(2)].join('/') STANDARD_LIBRARY_FOLDERS_LIST.include? str end Function that looks for a sources.rb file within the project
[ "def", "within_expected_folder?", "rel_design_path_list", "=" ]
b1b13440046779a603526f43473cb94c4dbe7fb7
https://github.com/ic-factory/ecic/blob/b1b13440046779a603526f43473cb94c4dbe7fb7/lib/ecic/source_file_info.rb#L56-L66
3,277
jaymcgavren/zyps
lib/zyps/conditions.rb
Zyps.ProximityCondition.select
def select(actor, targets) targets.find_all {|target| Utility.find_distance(actor.location, target.location) <= @distance} end
ruby
def select(actor, targets) targets.find_all {|target| Utility.find_distance(actor.location, target.location) <= @distance} end
[ "def", "select", "(", "actor", ",", "targets", ")", "targets", ".", "find_all", "{", "|", "target", "|", "Utility", ".", "find_distance", "(", "actor", ".", "location", ",", "target", ".", "location", ")", "<=", "@distance", "}", "end" ]
Returns an array of targets that are at the given distance or closer.
[ "Returns", "an", "array", "of", "targets", "that", "are", "at", "the", "given", "distance", "or", "closer", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/conditions.rb#L69-L71
3,278
jaymcgavren/zyps
lib/zyps/conditions.rb
Zyps.CollisionCondition.select
def select(actor, targets) return [] unless targets.length > 0 #The size of the largest other object max_size = targets.map{|t| t.size}.max #The maximum distance on a straight line the largest object and self could be and still be touching. max_diff = Math.sqrt(actor.size / Math::PI) + Math.sqrt(max_size / Math::PI) x_range = (actor.location.x - max_diff .. actor.location.x + max_diff) y_range = (actor.location.y - max_diff .. actor.location.y + max_diff) targets.select do | target | x_range.include?(target.location.x) and y_range.include?(target.location.y) and Utility.collided?(actor, target) end end
ruby
def select(actor, targets) return [] unless targets.length > 0 #The size of the largest other object max_size = targets.map{|t| t.size}.max #The maximum distance on a straight line the largest object and self could be and still be touching. max_diff = Math.sqrt(actor.size / Math::PI) + Math.sqrt(max_size / Math::PI) x_range = (actor.location.x - max_diff .. actor.location.x + max_diff) y_range = (actor.location.y - max_diff .. actor.location.y + max_diff) targets.select do | target | x_range.include?(target.location.x) and y_range.include?(target.location.y) and Utility.collided?(actor, target) end end
[ "def", "select", "(", "actor", ",", "targets", ")", "return", "[", "]", "unless", "targets", ".", "length", ">", "0", "#The size of the largest other object", "max_size", "=", "targets", ".", "map", "{", "|", "t", "|", "t", ".", "size", "}", ".", "max", "#The maximum distance on a straight line the largest object and self could be and still be touching.", "max_diff", "=", "Math", ".", "sqrt", "(", "actor", ".", "size", "/", "Math", "::", "PI", ")", "+", "Math", ".", "sqrt", "(", "max_size", "/", "Math", "::", "PI", ")", "x_range", "=", "(", "actor", ".", "location", ".", "x", "-", "max_diff", "..", "actor", ".", "location", ".", "x", "+", "max_diff", ")", "y_range", "=", "(", "actor", ".", "location", ".", "y", "-", "max_diff", "..", "actor", ".", "location", ".", "y", "+", "max_diff", ")", "targets", ".", "select", "do", "|", "target", "|", "x_range", ".", "include?", "(", "target", ".", "location", ".", "x", ")", "and", "y_range", ".", "include?", "(", "target", ".", "location", ".", "y", ")", "and", "Utility", ".", "collided?", "(", "actor", ",", "target", ")", "end", "end" ]
Returns an array of targets that have collided with the actor.
[ "Returns", "an", "array", "of", "targets", "that", "have", "collided", "with", "the", "actor", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/conditions.rb#L86-L97
3,279
jaymcgavren/zyps
lib/zyps/conditions.rb
Zyps.StrengthCondition.select
def select(actor, targets) targets.find_all {|target| actor.size >= target.size} end
ruby
def select(actor, targets) targets.find_all {|target| actor.size >= target.size} end
[ "def", "select", "(", "actor", ",", "targets", ")", "targets", ".", "find_all", "{", "|", "target", "|", "actor", ".", "size", ">=", "target", ".", "size", "}", "end" ]
Returns an array of targets that are weaker than the actor. For now, strength is based merely on size.
[ "Returns", "an", "array", "of", "targets", "that", "are", "weaker", "than", "the", "actor", ".", "For", "now", "strength", "is", "based", "merely", "on", "size", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/conditions.rb#L105-L107
3,280
raygao/asf-soap-adapter
lib/salesforce/sf_base.rb
Salesforce.SfBase.logout
def logout(session_ids=Hash.new) result = SfBase.connection.binding.invalidateSessions(session_ids) if"invalidateSessionsResponse" == result.to_s return true else return false end #result this.connection.binding.logout(Hash.new) end
ruby
def logout(session_ids=Hash.new) result = SfBase.connection.binding.invalidateSessions(session_ids) if"invalidateSessionsResponse" == result.to_s return true else return false end #result this.connection.binding.logout(Hash.new) end
[ "def", "logout", "(", "session_ids", "=", "Hash", ".", "new", ")", "result", "=", "SfBase", ".", "connection", ".", "binding", ".", "invalidateSessions", "(", "session_ids", ")", "if", "\"invalidateSessionsResponse\"", "==", "result", ".", "to_s", "return", "true", "else", "return", "false", "end", "#result this.connection.binding.logout(Hash.new)", "end" ]
Logs out of the Salesforce session
[ "Logs", "out", "of", "the", "Salesforce", "session" ]
ab96dc48d60a6410d620cafe68ae7add012dc9d4
https://github.com/raygao/asf-soap-adapter/blob/ab96dc48d60a6410d620cafe68ae7add012dc9d4/lib/salesforce/sf_base.rb#L51-L59
3,281
caruby/uom
lib/uom/measurement.rb
UOM.Measurement.as
def as(unit) unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit return self if @unit == unit Measurement.new(unit, @unit.as(quantity, unit)) end
ruby
def as(unit) unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit return self if @unit == unit Measurement.new(unit, @unit.as(quantity, unit)) end
[ "def", "as", "(", "unit", ")", "unit", "=", "UOM", "::", "Unit", ".", "for", "(", "unit", ".", "to_sym", ")", "if", "String", "===", "unit", "or", "Symbol", "===", "unit", "return", "self", "if", "@unit", "==", "unit", "Measurement", ".", "new", "(", "unit", ",", "@unit", ".", "as", "(", "quantity", ",", "unit", ")", ")", "end" ]
Returns a new Measurement which expresses this measurement as the given unit.
[ "Returns", "a", "new", "Measurement", "which", "expresses", "this", "measurement", "as", "the", "given", "unit", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/measurement.rb#L52-L56
3,282
caruby/uom
lib/uom/measurement.rb
UOM.Measurement.apply_to_quantity
def apply_to_quantity(method, other) other = other.as(unit).quantity if Measurement === other new_quantity = block_given? ? yield(to_f, other) : to_f.send(method, other) Measurement.new(unit, new_quantity) end
ruby
def apply_to_quantity(method, other) other = other.as(unit).quantity if Measurement === other new_quantity = block_given? ? yield(to_f, other) : to_f.send(method, other) Measurement.new(unit, new_quantity) end
[ "def", "apply_to_quantity", "(", "method", ",", "other", ")", "other", "=", "other", ".", "as", "(", "unit", ")", ".", "quantity", "if", "Measurement", "===", "other", "new_quantity", "=", "block_given?", "?", "yield", "(", "to_f", ",", "other", ")", ":", "to_f", ".", "send", "(", "method", ",", "other", ")", "Measurement", ".", "new", "(", "unit", ",", "new_quantity", ")", "end" ]
Returns a new Measurement whose unit is this Measurement's unit and quantity is the result of applying the given method to this Measurement's quantity and the other quantity. If other is a Measurement, then the operation argument is the other Measurement quantity, e.g.: Measurement.new(:g, 3).apply(Measurement.new(:mg, 2000), :div) #=> 1 gram
[ "Returns", "a", "new", "Measurement", "whose", "unit", "is", "this", "Measurement", "s", "unit", "and", "quantity", "is", "the", "result", "of", "applying", "the", "given", "method", "to", "this", "Measurement", "s", "quantity", "and", "the", "other", "quantity", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/measurement.rb#L72-L76
3,283
caruby/uom
lib/uom/measurement.rb
UOM.Measurement.compose
def compose(method, other) return apply_to_quantity(method, other) unless Measurement === other other = other.as(unit) if other.unit.axis == unit.axis new_quantity = quantity.zero? ? 0.0 : quantity.to_f.send(method, other.quantity) Measurement.new(unit.send(method, other.unit), new_quantity) end
ruby
def compose(method, other) return apply_to_quantity(method, other) unless Measurement === other other = other.as(unit) if other.unit.axis == unit.axis new_quantity = quantity.zero? ? 0.0 : quantity.to_f.send(method, other.quantity) Measurement.new(unit.send(method, other.unit), new_quantity) end
[ "def", "compose", "(", "method", ",", "other", ")", "return", "apply_to_quantity", "(", "method", ",", "other", ")", "unless", "Measurement", "===", "other", "other", "=", "other", ".", "as", "(", "unit", ")", "if", "other", ".", "unit", ".", "axis", "==", "unit", ".", "axis", "new_quantity", "=", "quantity", ".", "zero?", "?", "0.0", ":", "quantity", ".", "to_f", ".", "send", "(", "method", ",", "other", ".", "quantity", ")", "Measurement", ".", "new", "(", "unit", ".", "send", "(", "method", ",", "other", ".", "unit", ")", ",", "new_quantity", ")", "end" ]
Returns the application of method to this measurement and the other measurement or Numeric. If other is a Measurement, then the returned Measurement Unit is the composition of this Measurement's unit and the other Measurement's unit.
[ "Returns", "the", "application", "of", "method", "to", "this", "measurement", "and", "the", "other", "measurement", "or", "Numeric", ".", "If", "other", "is", "a", "Measurement", "then", "the", "returned", "Measurement", "Unit", "is", "the", "composition", "of", "this", "Measurement", "s", "unit", "and", "the", "other", "Measurement", "s", "unit", "." ]
04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1
https://github.com/caruby/uom/blob/04597e0fe44f1f58d5c08303ab90f8c68bb8ebc1/lib/uom/measurement.rb#L81-L86
3,284
barcoo/rworkflow
lib/rworkflow/sidekiq_flow.rb
Rworkflow.SidekiqFlow.continue
def continue return if self.finished? || !self.valid? || !self.paused? if @flow_data.decr(:paused) == 0 workers = Hash[self.counters.select { |name, _| !self.class.terminal?(name) && name != :processing }] # enqueue jobs workers.each { |worker, num_objects| create_jobs(worker, num_objects) } end rescue StandardError => e Rails.logger.error("Error continuing flow #{self.id}: #{e.message}") end
ruby
def continue return if self.finished? || !self.valid? || !self.paused? if @flow_data.decr(:paused) == 0 workers = Hash[self.counters.select { |name, _| !self.class.terminal?(name) && name != :processing }] # enqueue jobs workers.each { |worker, num_objects| create_jobs(worker, num_objects) } end rescue StandardError => e Rails.logger.error("Error continuing flow #{self.id}: #{e.message}") end
[ "def", "continue", "return", "if", "self", ".", "finished?", "||", "!", "self", ".", "valid?", "||", "!", "self", ".", "paused?", "if", "@flow_data", ".", "decr", "(", ":paused", ")", "==", "0", "workers", "=", "Hash", "[", "self", ".", "counters", ".", "select", "{", "|", "name", ",", "_", "|", "!", "self", ".", "class", ".", "terminal?", "(", "name", ")", "&&", "name", "!=", ":processing", "}", "]", "# enqueue jobs", "workers", ".", "each", "{", "|", "worker", ",", "num_objects", "|", "create_jobs", "(", "worker", ",", "num_objects", ")", "}", "end", "rescue", "StandardError", "=>", "e", "Rails", ".", "logger", ".", "error", "(", "\"Error continuing flow #{self.id}: #{e.message}\"", ")", "end" ]
for now assumes
[ "for", "now", "assumes" ]
1dccaabd47144c846e3d87e65c11ee056ae597a1
https://github.com/barcoo/rworkflow/blob/1dccaabd47144c846e3d87e65c11ee056ae597a1/lib/rworkflow/sidekiq_flow.rb#L44-L54
3,285
egonbraun/logmsg
lib/logmsg/logfile.rb
Logmsg.LogFile.init_formatter
def init_formatter @formatter = proc do |s, d, p, m| "#{@format}\n" % { severity: s, datetime: d, progname: p, msg: m } end end
ruby
def init_formatter @formatter = proc do |s, d, p, m| "#{@format}\n" % { severity: s, datetime: d, progname: p, msg: m } end end
[ "def", "init_formatter", "@formatter", "=", "proc", "do", "|", "s", ",", "d", ",", "p", ",", "m", "|", "\"#{@format}\\n\"", "%", "{", "severity", ":", "s", ",", "datetime", ":", "d", ",", "progname", ":", "p", ",", "msg", ":", "m", "}", "end", "end" ]
Initializes the logger's formatter proc based on the value of format instance variable. This method should only be called inside the register method @private
[ "Initializes", "the", "logger", "s", "formatter", "proc", "based", "on", "the", "value", "of", "format", "instance", "variable", ".", "This", "method", "should", "only", "be", "called", "inside", "the", "register", "method" ]
7ca139edb856ada08cb7465acd68bd60bc2837fa
https://github.com/egonbraun/logmsg/blob/7ca139edb856ada08cb7465acd68bd60bc2837fa/lib/logmsg/logfile.rb#L155-L159
3,286
egonbraun/logmsg
lib/logmsg/logfile.rb
Logmsg.LogFile.init_logger
def init_logger @logger = case @path when STDOUT_STREAM then Logger.new(STDOUT) when STDERR_STREAM then Logger.new(STDERR) else Logger.new(File.open(@path, 'a')) end @logger.datetime_format = @datetime_format @logger.sev_threshold = @threshold unless @severities.any? @logger.formatter = @formatter unless @formatter.nil? end
ruby
def init_logger @logger = case @path when STDOUT_STREAM then Logger.new(STDOUT) when STDERR_STREAM then Logger.new(STDERR) else Logger.new(File.open(@path, 'a')) end @logger.datetime_format = @datetime_format @logger.sev_threshold = @threshold unless @severities.any? @logger.formatter = @formatter unless @formatter.nil? end
[ "def", "init_logger", "@logger", "=", "case", "@path", "when", "STDOUT_STREAM", "then", "Logger", ".", "new", "(", "STDOUT", ")", "when", "STDERR_STREAM", "then", "Logger", ".", "new", "(", "STDERR", ")", "else", "Logger", ".", "new", "(", "File", ".", "open", "(", "@path", ",", "'a'", ")", ")", "end", "@logger", ".", "datetime_format", "=", "@datetime_format", "@logger", ".", "sev_threshold", "=", "@threshold", "unless", "@severities", ".", "any?", "@logger", ".", "formatter", "=", "@formatter", "unless", "@formatter", ".", "nil?", "end" ]
Initializes the logger object from the standard library. This method should only be called inside the register method @private
[ "Initializes", "the", "logger", "object", "from", "the", "standard", "library", ".", "This", "method", "should", "only", "be", "called", "inside", "the", "register", "method" ]
7ca139edb856ada08cb7465acd68bd60bc2837fa
https://github.com/egonbraun/logmsg/blob/7ca139edb856ada08cb7465acd68bd60bc2837fa/lib/logmsg/logfile.rb#L164-L173
3,287
egonbraun/logmsg
lib/logmsg/logfile.rb
Logmsg.LogFile.log
def log(message, severity = DEFAULT_SEVERITY) fail 'Logfile not registered' unless @registered return if message.nil? @logger.add(severity, message, @name) if should_log?(severity) end
ruby
def log(message, severity = DEFAULT_SEVERITY) fail 'Logfile not registered' unless @registered return if message.nil? @logger.add(severity, message, @name) if should_log?(severity) end
[ "def", "log", "(", "message", ",", "severity", "=", "DEFAULT_SEVERITY", ")", "fail", "'Logfile not registered'", "unless", "@registered", "return", "if", "message", ".", "nil?", "@logger", ".", "add", "(", "severity", ",", "message", ",", "@name", ")", "if", "should_log?", "(", "severity", ")", "end" ]
Log a message to the configured logger using the severity and program name as specified @param [String] message message to be logged @param [Number] severity message's severity @see http://ruby-doc.org/stdlib-2.2.4/libdoc/logger/rdoc/Logger.html @private
[ "Log", "a", "message", "to", "the", "configured", "logger", "using", "the", "severity", "and", "program", "name", "as", "specified" ]
7ca139edb856ada08cb7465acd68bd60bc2837fa
https://github.com/egonbraun/logmsg/blob/7ca139edb856ada08cb7465acd68bd60bc2837fa/lib/logmsg/logfile.rb#L183-L187
3,288
stvvan/hoiio-ruby
lib/hoiio-ruby/api/ivr.rb
Hoiio.IVR.set_up
def set_up @start = Hoiio::IVRBlock::Start.new @client @middle = Hoiio::IVRBlock::Middle.new @client @end = Hoiio::IVRBlock::End.new @client end
ruby
def set_up @start = Hoiio::IVRBlock::Start.new @client @middle = Hoiio::IVRBlock::Middle.new @client @end = Hoiio::IVRBlock::End.new @client end
[ "def", "set_up", "@start", "=", "Hoiio", "::", "IVRBlock", "::", "Start", ".", "new", "@client", "@middle", "=", "Hoiio", "::", "IVRBlock", "::", "Middle", ".", "new", "@client", "@end", "=", "Hoiio", "::", "IVRBlock", "::", "End", ".", "new", "@client", "end" ]
Set up the sub resources using shared @client object
[ "Set", "up", "the", "sub", "resources", "using", "shared" ]
7f6840b94c5f61c221619ca069bc008d502dd339
https://github.com/stvvan/hoiio-ruby/blob/7f6840b94c5f61c221619ca069bc008d502dd339/lib/hoiio-ruby/api/ivr.rb#L45-L49
3,289
drish/hyperb
lib/hyperb/network/fips.rb
Hyperb.Network.fips_ls
def fips_ls(params = {}) path = '/fips' query = {} query[:filters] = params[:filters] if params.key?(:filters) downcase_symbolize(JSON.parse(Hyperb::Request.new(self, path, query, 'get').perform)) end
ruby
def fips_ls(params = {}) path = '/fips' query = {} query[:filters] = params[:filters] if params.key?(:filters) downcase_symbolize(JSON.parse(Hyperb::Request.new(self, path, query, 'get').perform)) end
[ "def", "fips_ls", "(", "params", "=", "{", "}", ")", "path", "=", "'/fips'", "query", "=", "{", "}", "query", "[", ":filters", "]", "=", "params", "[", ":filters", "]", "if", "params", ".", "key?", "(", ":filters", ")", "downcase_symbolize", "(", "JSON", ".", "parse", "(", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "query", ",", "'get'", ")", ".", "perform", ")", ")", "end" ]
list floating ips @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Network/fip_ls.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::NotFound] raised when ips are not found. @returns [Array] array of downcased symbolized has @param params [Hash] A customizable set of params. @option params [String] :filters
[ "list", "floating", "ips" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/network/fips.rb#L60-L65
3,290
drish/hyperb
lib/hyperb/network/fips.rb
Hyperb.Network.fip_release
def fip_release(params = {}) path = '/fips/release' query = {} query[:ip] = params[:ip] if params.key?(:ip) Hyperb::Request.new(self, path, query, 'post').perform end
ruby
def fip_release(params = {}) path = '/fips/release' query = {} query[:ip] = params[:ip] if params.key?(:ip) Hyperb::Request.new(self, path, query, 'post').perform end
[ "def", "fip_release", "(", "params", "=", "{", "}", ")", "path", "=", "'/fips/release'", "query", "=", "{", "}", "query", "[", ":ip", "]", "=", "params", "[", ":ip", "]", "if", "params", ".", "key?", "(", ":ip", ")", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "query", ",", "'post'", ")", ".", "perform", "end" ]
release a floating ip @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Network/fip_release.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @raise [Hyperb::Error::NotFound] raised when ips are not found. @param params [Hash] A customizable set of params. @option params [String] :ip the number of free fips to allocate
[ "release", "a", "floating", "ip" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/network/fips.rb#L76-L81
3,291
drish/hyperb
lib/hyperb/network/fips.rb
Hyperb.Network.fip_allocate
def fip_allocate(params = {}) raise ArgumentError, 'Invalid Arguments' unless check_arguments(params, 'count') path = '/fips/allocate' query = {} query[:count] = params[:count] if params.key?(:count) fips = JSON.parse(Hyperb::Request.new(self, path, query, 'post').perform) fips end
ruby
def fip_allocate(params = {}) raise ArgumentError, 'Invalid Arguments' unless check_arguments(params, 'count') path = '/fips/allocate' query = {} query[:count] = params[:count] if params.key?(:count) fips = JSON.parse(Hyperb::Request.new(self, path, query, 'post').perform) fips end
[ "def", "fip_allocate", "(", "params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Invalid Arguments'", "unless", "check_arguments", "(", "params", ",", "'count'", ")", "path", "=", "'/fips/allocate'", "query", "=", "{", "}", "query", "[", ":count", "]", "=", "params", "[", ":count", "]", "if", "params", ".", "key?", "(", ":count", ")", "fips", "=", "JSON", ".", "parse", "(", "Hyperb", "::", "Request", ".", "new", "(", "self", ",", "path", ",", "query", ",", "'post'", ")", ".", "perform", ")", "fips", "end" ]
allocate a new floating ip @see https://docs.hyper.sh/Reference/API/2016-04-04%20[Ver.%201.23]/Network/fip_allocate.html @raise [Hyperb::Error::Unauthorized] raised when credentials are not valid. @return [Array] Array of ips (string). @param params [Hash] A customizable set of params. @option params [String] :count the number of free fips to allocate
[ "allocate", "a", "new", "floating", "ip" ]
637de68dc304d8d07470a771f499e33f227955f4
https://github.com/drish/hyperb/blob/637de68dc304d8d07470a771f499e33f227955f4/lib/hyperb/network/fips.rb#L93-L100
3,292
jaymcgavren/zyps
lib/zyps/environmental_factors.rb
Zyps.SpeedLimit.act
def act(environment) environment.objects.each do |object| object.vector.speed = Utility.constrain_value(object.vector.speed, @maximum) end end
ruby
def act(environment) environment.objects.each do |object| object.vector.speed = Utility.constrain_value(object.vector.speed, @maximum) end end
[ "def", "act", "(", "environment", ")", "environment", ".", "objects", ".", "each", "do", "|", "object", "|", "object", ".", "vector", ".", "speed", "=", "Utility", ".", "constrain_value", "(", "object", ".", "vector", ".", "speed", ",", "@maximum", ")", "end", "end" ]
If object is over the speed, reduce its speed.
[ "If", "object", "is", "over", "the", "speed", "reduce", "its", "speed", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/environmental_factors.rb#L132-L136
3,293
jaymcgavren/zyps
lib/zyps/environmental_factors.rb
Zyps.Accelerator.act
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Push on object. object.vector += Vector.new(@vector.speed * elapsed_time, @vector.pitch) end end
ruby
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Push on object. object.vector += Vector.new(@vector.speed * elapsed_time, @vector.pitch) end end
[ "def", "act", "(", "environment", ")", "elapsed_time", "=", "@clock", ".", "elapsed_time", "environment", ".", "objects", ".", "each", "do", "|", "object", "|", "#Push on object.", "object", ".", "vector", "+=", "Vector", ".", "new", "(", "@vector", ".", "speed", "*", "elapsed_time", ",", "@vector", ".", "pitch", ")", "end", "end" ]
Add the given vector to each object, but limited by elapsed time.
[ "Add", "the", "given", "vector", "to", "each", "object", "but", "limited", "by", "elapsed", "time", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/environmental_factors.rb#L169-L175
3,294
jaymcgavren/zyps
lib/zyps/environmental_factors.rb
Zyps.Friction.act
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Slow object. acceleration = @force * elapsed_time speed = object.vector.speed if speed > 0 speed -= acceleration speed = 0 if speed < 0 elsif speed < 0 speed += acceleration speed = 0 if speed > 0 end object.vector.speed = speed end end
ruby
def act(environment) elapsed_time = @clock.elapsed_time environment.objects.each do |object| #Slow object. acceleration = @force * elapsed_time speed = object.vector.speed if speed > 0 speed -= acceleration speed = 0 if speed < 0 elsif speed < 0 speed += acceleration speed = 0 if speed > 0 end object.vector.speed = speed end end
[ "def", "act", "(", "environment", ")", "elapsed_time", "=", "@clock", ".", "elapsed_time", "environment", ".", "objects", ".", "each", "do", "|", "object", "|", "#Slow object.", "acceleration", "=", "@force", "*", "elapsed_time", "speed", "=", "object", ".", "vector", ".", "speed", "if", "speed", ">", "0", "speed", "-=", "acceleration", "speed", "=", "0", "if", "speed", "<", "0", "elsif", "speed", "<", "0", "speed", "+=", "acceleration", "speed", "=", "0", "if", "speed", ">", "0", "end", "object", ".", "vector", ".", "speed", "=", "speed", "end", "end" ]
Reduce each object's speed at the given rate.
[ "Reduce", "each", "object", "s", "speed", "at", "the", "given", "rate", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/environmental_factors.rb#L227-L242
3,295
jaymcgavren/zyps
lib/zyps/environmental_factors.rb
Zyps.PopulationLimit.act
def act(environment) excess = environment.object_count - @count if excess > 0 objects_for_removal = [] environment.objects.each do |object| objects_for_removal << object break if objects_for_removal.length >= excess end objects_for_removal.each {|object| environment.remove_object(object.identifier)} end end
ruby
def act(environment) excess = environment.object_count - @count if excess > 0 objects_for_removal = [] environment.objects.each do |object| objects_for_removal << object break if objects_for_removal.length >= excess end objects_for_removal.each {|object| environment.remove_object(object.identifier)} end end
[ "def", "act", "(", "environment", ")", "excess", "=", "environment", ".", "object_count", "-", "@count", "if", "excess", ">", "0", "objects_for_removal", "=", "[", "]", "environment", ".", "objects", ".", "each", "do", "|", "object", "|", "objects_for_removal", "<<", "object", "break", "if", "objects_for_removal", ".", "length", ">=", "excess", "end", "objects_for_removal", ".", "each", "{", "|", "object", "|", "environment", ".", "remove_object", "(", "object", ".", "identifier", ")", "}", "end", "end" ]
Remove objects if there are too many objects in environment.
[ "Remove", "objects", "if", "there", "are", "too", "many", "objects", "in", "environment", "." ]
7fa9dc497abc30fe2d1a2a17e129628ffb0456fb
https://github.com/jaymcgavren/zyps/blob/7fa9dc497abc30fe2d1a2a17e129628ffb0456fb/lib/zyps/environmental_factors.rb#L263-L273
3,296
faradayio/charisma
lib/charisma/characterization.rb
Charisma.Characterization.has
def has(name, options = {}, &blk) name = name.to_sym self[name] = Characteristic.new(name, options, &blk) end
ruby
def has(name, options = {}, &blk) name = name.to_sym self[name] = Characteristic.new(name, options, &blk) end
[ "def", "has", "(", "name", ",", "options", "=", "{", "}", ",", "&", "blk", ")", "name", "=", "name", ".", "to_sym", "self", "[", "name", "]", "=", "Characteristic", ".", "new", "(", "name", ",", "options", ",", "blk", ")", "end" ]
Define a characteristic. This is used within <tt>Charisma::Base::ClassMethods#characterize</tt> blocks to curate attributes on a class. Internally, a <tt>Charisma::Characteristic</tt> is created to store the definition. @param [Symbol] @param [Symbol] name The name of the characteristic. The method with this name will be called on the characterized object to retrieve its raw value. @param [Hash] options The options hash. @option [Symbol] display_with A symbol that gets sent as a method on the characteristic to retrieve its display value. @option [Class, Symbol] measures Specifies a measurement for the characteristic. Either provide a class constant that conforms to the Charisma::Measurement API, or use a symbol to specify a built-in Charisma measurement. @option [Proc] blk A proc that defines how the characteristic should be displayed. @see Charisma::Base::ClassMethods#characterize @see Charisma::Characteristic @see Charisma::Measurement
[ "Define", "a", "characteristic", "." ]
87d26ff48c9611f99ebfd01cee9cd15b5d79cabe
https://github.com/faradayio/charisma/blob/87d26ff48c9611f99ebfd01cee9cd15b5d79cabe/lib/charisma/characterization.rb#L18-L21
3,297
blythedunham/static_record_cache
lib/acts_as_static_record.rb
ActsAsStaticRecord.ClassMethods.define_static_cache_key_finder
def define_static_cache_key_finder#:nodoc: return unless acts_as_static_record_options[:find_by_attribute_support] #define the key column if it is not a hash column if ((key_column = acts_as_static_record_options[:key]) && (!column_methods_hash.include?(key_column.to_sym))) class_eval %{ def self.find_by_#{key_column}(arg) self.static_record_cache[:key][arg.to_s] end }, __FILE__, __LINE__ end end
ruby
def define_static_cache_key_finder#:nodoc: return unless acts_as_static_record_options[:find_by_attribute_support] #define the key column if it is not a hash column if ((key_column = acts_as_static_record_options[:key]) && (!column_methods_hash.include?(key_column.to_sym))) class_eval %{ def self.find_by_#{key_column}(arg) self.static_record_cache[:key][arg.to_s] end }, __FILE__, __LINE__ end end
[ "def", "define_static_cache_key_finder", "#:nodoc:", "return", "unless", "acts_as_static_record_options", "[", ":find_by_attribute_support", "]", "#define the key column if it is not a hash column", "if", "(", "(", "key_column", "=", "acts_as_static_record_options", "[", ":key", "]", ")", "&&", "(", "!", "column_methods_hash", ".", "include?", "(", "key_column", ".", "to_sym", ")", ")", ")", "class_eval", "%{\n def self.find_by_#{key_column}(arg)\n self.static_record_cache[:key][arg.to_s]\n end\n }", ",", "__FILE__", ",", "__LINE__", "end", "end" ]
Define a method find_by_KEY if the specified cache key is not an active record column
[ "Define", "a", "method", "find_by_KEY", "if", "the", "specified", "cache", "key", "is", "not", "an", "active", "record", "column" ]
3c8226886a99128a776b5a81f27c7aab8f4ce529
https://github.com/blythedunham/static_record_cache/blob/3c8226886a99128a776b5a81f27c7aab8f4ce529/lib/acts_as_static_record.rb#L242-L253
3,298
blythedunham/static_record_cache
lib/acts_as_static_record.rb
ActsAsStaticRecord.SingletonMethods.static_record_lookup_key
def static_record_lookup_key(value)#:nodoc: if value.is_a? self static_record_lookup_key( value.send( acts_as_static_record_options[:lookup_key] || acts_as_static_record_options[:key] || primary_key ) ) else value.to_s.gsub(' ', '_').gsub(/\W/, "").underscore end end
ruby
def static_record_lookup_key(value)#:nodoc: if value.is_a? self static_record_lookup_key( value.send( acts_as_static_record_options[:lookup_key] || acts_as_static_record_options[:key] || primary_key ) ) else value.to_s.gsub(' ', '_').gsub(/\W/, "").underscore end end
[ "def", "static_record_lookup_key", "(", "value", ")", "#:nodoc:", "if", "value", ".", "is_a?", "self", "static_record_lookup_key", "(", "value", ".", "send", "(", "acts_as_static_record_options", "[", ":lookup_key", "]", "||", "acts_as_static_record_options", "[", ":key", "]", "||", "primary_key", ")", ")", "else", "value", ".", "to_s", ".", "gsub", "(", "' '", ",", "'_'", ")", ".", "gsub", "(", "/", "\\W", "/", ",", "\"\"", ")", ".", "underscore", "end", "end" ]
Parse the lookup key
[ "Parse", "the", "lookup", "key" ]
3c8226886a99128a776b5a81f27c7aab8f4ce529
https://github.com/blythedunham/static_record_cache/blob/3c8226886a99128a776b5a81f27c7aab8f4ce529/lib/acts_as_static_record.rb#L311-L323
3,299
blythedunham/static_record_cache
lib/acts_as_static_record.rb
ActsAsStaticRecord.SingletonMethods.find_in_static_record_cache
def find_in_static_record_cache(finder, attributes)#:nodoc: list = static_record_cache[:primary_key].values.inject([]) do |list, record| unless attributes.select{|k,v| record.send(k).to_s != v.to_s}.any? return record if finder == :first list << record end list end finder == :all ? list : list.last end
ruby
def find_in_static_record_cache(finder, attributes)#:nodoc: list = static_record_cache[:primary_key].values.inject([]) do |list, record| unless attributes.select{|k,v| record.send(k).to_s != v.to_s}.any? return record if finder == :first list << record end list end finder == :all ? list : list.last end
[ "def", "find_in_static_record_cache", "(", "finder", ",", "attributes", ")", "#:nodoc:", "list", "=", "static_record_cache", "[", ":primary_key", "]", ".", "values", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "record", "|", "unless", "attributes", ".", "select", "{", "|", "k", ",", "v", "|", "record", ".", "send", "(", "k", ")", ".", "to_s", "!=", "v", ".", "to_s", "}", ".", "any?", "return", "record", "if", "finder", "==", ":first", "list", "<<", "record", "end", "list", "end", "finder", "==", ":all", "?", "list", ":", "list", ".", "last", "end" ]
Search the cache for records with the specified attributes * +finder+ - Same as with +find+ specify <tt>:all</tt>, <tt>:last</tt> or <tt>:first</tt> <tt>:all</all> returns an array of active records, <tt>:last</tt> or <tt>:first</tt> returns a single instance * +attributes+ - a hash map of fields (or methods) => values User.find_in_static_cache(:first, {:password => 'fun', :user_name => 'giraffe'})
[ "Search", "the", "cache", "for", "records", "with", "the", "specified", "attributes" ]
3c8226886a99128a776b5a81f27c7aab8f4ce529
https://github.com/blythedunham/static_record_cache/blob/3c8226886a99128a776b5a81f27c7aab8f4ce529/lib/acts_as_static_record.rb#L332-L341