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
5,800
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.delete_branch
def delete_branch(branch, path = Dir.pwd, opts = { :force => false }) g = MiniGit.new(path) error "'#{branch}' is not a valid existing branch" unless list_branch(path).include?( branch ) g.branch ((opts[:force]) ? :D : :d) => branch.to_s end
ruby
def delete_branch(branch, path = Dir.pwd, opts = { :force => false }) g = MiniGit.new(path) error "'#{branch}' is not a valid existing branch" unless list_branch(path).include?( branch ) g.branch ((opts[:force]) ? :D : :d) => branch.to_s end
[ "def", "delete_branch", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "opts", "=", "{", ":force", "=>", "false", "}", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "error", "\"'#{branch}' is not a valid existing branch\"", "unless", "list_branch", "(", "path", ")", ".", "include?", "(", "branch", ")", "g", ".", "branch", "(", "(", "opts", "[", ":force", "]", ")", "?", ":D", ":", ":d", ")", "=>", "branch", ".", "to_s", "end" ]
Delete a branch.
[ "Delete", "a", "branch", "." ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L140-L144
5,801
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.grab
def grab(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) if branches.include? "remotes/#{remote}/#{branch}" info "Grab the branch '#{remote}/#{branch}'" exit_status = execute_in_dir(FalkorLib::Git.rootdir( path ), "git branch --track #{branch} #{remote}/#{branch}") else warning "the remote branch '#{remote}/#{branch}' cannot be found" end exit_status end
ruby
def grab(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) if branches.include? "remotes/#{remote}/#{branch}" info "Grab the branch '#{remote}/#{branch}'" exit_status = execute_in_dir(FalkorLib::Git.rootdir( path ), "git branch --track #{branch} #{remote}/#{branch}") else warning "the remote branch '#{remote}/#{branch}' cannot be found" end exit_status end
[ "def", "grab", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "remote", "=", "'origin'", ")", "exit_status", "=", "1", "error", "\"no branch provided\"", "if", "branch", ".", "nil?", "#remotes = FalkorLib::Git.remotes(path)", "branches", "=", "FalkorLib", "::", "Git", ".", "list_branch", "(", "path", ")", "if", "branches", ".", "include?", "\"remotes/#{remote}/#{branch}\"", "info", "\"Grab the branch '#{remote}/#{branch}'\"", "exit_status", "=", "execute_in_dir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ",", "\"git branch --track #{branch} #{remote}/#{branch}\"", ")", "else", "warning", "\"the remote branch '#{remote}/#{branch}' cannot be found\"", "end", "exit_status", "end" ]
Grab a remote branch
[ "Grab", "a", "remote", "branch" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L199-L211
5,802
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.publish
def publish(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) Dir.chdir(FalkorLib::Git.rootdir( path ) ) do if branches.include? "remotes/#{remote}/#{branch}" warning "the remote branch '#{remote}/#{branch}' already exists" else info "Publish the branch '#{branch}' on the remote '#{remote}'" exit_status = run %( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} ) end end exit_status end
ruby
def publish(branch, path = Dir.pwd, remote = 'origin') exit_status = 1 error "no branch provided" if branch.nil? #remotes = FalkorLib::Git.remotes(path) branches = FalkorLib::Git.list_branch(path) Dir.chdir(FalkorLib::Git.rootdir( path ) ) do if branches.include? "remotes/#{remote}/#{branch}" warning "the remote branch '#{remote}/#{branch}' already exists" else info "Publish the branch '#{branch}' on the remote '#{remote}'" exit_status = run %( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} ) end end exit_status end
[ "def", "publish", "(", "branch", ",", "path", "=", "Dir", ".", "pwd", ",", "remote", "=", "'origin'", ")", "exit_status", "=", "1", "error", "\"no branch provided\"", "if", "branch", ".", "nil?", "#remotes = FalkorLib::Git.remotes(path)", "branches", "=", "FalkorLib", "::", "Git", ".", "list_branch", "(", "path", ")", "Dir", ".", "chdir", "(", "FalkorLib", "::", "Git", ".", "rootdir", "(", "path", ")", ")", "do", "if", "branches", ".", "include?", "\"remotes/#{remote}/#{branch}\"", "warning", "\"the remote branch '#{remote}/#{branch}' already exists\"", "else", "info", "\"Publish the branch '#{branch}' on the remote '#{remote}'\"", "exit_status", "=", "run", "%(\n git push #{remote} #{branch}:refs/heads/#{branch}\n git fetch #{remote}\n git branch -u #{remote}/#{branch} #{branch}\n )", "end", "end", "exit_status", "end" ]
Publish a branch on the remote
[ "Publish", "a", "branch", "on", "the", "remote" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L214-L232
5,803
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.list_files
def list_files(path = Dir.pwd) g = MiniGit.new(path) g.capturing.ls_files.split end
ruby
def list_files(path = Dir.pwd) g = MiniGit.new(path) g.capturing.ls_files.split end
[ "def", "list_files", "(", "path", "=", "Dir", ".", "pwd", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "g", ".", "capturing", ".", "ls_files", ".", "split", "end" ]
List the files currently under version
[ "List", "the", "files", "currently", "under", "version" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L235-L238
5,804
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.last_tag_commit
def last_tag_commit(path = Dir.pwd) res = "" g = MiniGit.new(path) unless (g.capturing.tag :list => true).empty? # git rev-list --tags --max-count=1 res = (g.capturing.rev_list :tags => true, :max_count => 1).chomp end res end
ruby
def last_tag_commit(path = Dir.pwd) res = "" g = MiniGit.new(path) unless (g.capturing.tag :list => true).empty? # git rev-list --tags --max-count=1 res = (g.capturing.rev_list :tags => true, :max_count => 1).chomp end res end
[ "def", "last_tag_commit", "(", "path", "=", "Dir", ".", "pwd", ")", "res", "=", "\"\"", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "unless", "(", "g", ".", "capturing", ".", "tag", ":list", "=>", "true", ")", ".", "empty?", "# git rev-list --tags --max-count=1", "res", "=", "(", "g", ".", "capturing", ".", "rev_list", ":tags", "=>", "true", ",", ":max_count", "=>", "1", ")", ".", "chomp", "end", "res", "end" ]
list_tag Get the last tag commit, or nil if no tag can be found
[ "list_tag", "Get", "the", "last", "tag", "commit", "or", "nil", "if", "no", "tag", "can", "be", "found" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L282-L290
5,805
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.remotes
def remotes(path = Dir.pwd) g = MiniGit.new(path) g.capturing.remote.split end
ruby
def remotes(path = Dir.pwd) g = MiniGit.new(path) g.capturing.remote.split end
[ "def", "remotes", "(", "path", "=", "Dir", ".", "pwd", ")", "g", "=", "MiniGit", ".", "new", "(", "path", ")", "g", ".", "capturing", ".", "remote", ".", "split", "end" ]
tag List of Git remotes
[ "tag", "List", "of", "Git", "remotes" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L303-L306
5,806
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.subtree_init?
def subtree_init?(path = Dir.pwd) res = true FalkorLib.config.git[:subtrees].keys.each do |dir| res &&= File.directory?(File.join(path, dir)) end res end
ruby
def subtree_init?(path = Dir.pwd) res = true FalkorLib.config.git[:subtrees].keys.each do |dir| res &&= File.directory?(File.join(path, dir)) end res end
[ "def", "subtree_init?", "(", "path", "=", "Dir", ".", "pwd", ")", "res", "=", "true", "FalkorLib", ".", "config", ".", "git", "[", ":subtrees", "]", ".", "keys", ".", "each", "do", "|", "dir", "|", "res", "&&=", "File", ".", "directory?", "(", "File", ".", "join", "(", "path", ",", "dir", ")", ")", "end", "res", "end" ]
Check if the subtrees have been initialized. Actually based on a naive check of sub-directory existence
[ "Check", "if", "the", "subtrees", "have", "been", "initialized", ".", "Actually", "based", "on", "a", "naive", "check", "of", "sub", "-", "directory", "existence" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L414-L420
5,807
Falkor/falkorlib
lib/falkorlib/git/base.rb
FalkorLib.Git.subtree_up
def subtree_up(path = Dir.pwd) error "Unable to pull subtree(s): Dirty Git repository" if FalkorLib::Git.dirty?( path ) exit_status = 0 git_root_dir = rootdir(path) Dir.chdir(git_root_dir) do FalkorLib.config.git[:subtrees].each do |dir, conf| next if conf[:url].nil? #url = conf[:url] remote = dir.gsub(/\//, '-') branch = (conf[:branch].nil?) ? 'master' : conf[:branch] remotes = FalkorLib::Git.remotes info "Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'" raise IOError, "The git remote '#{remote}' is not configured" unless remotes.include?( remote ) info "\t\\__ fetching remote '#{remotes.join(',')}'" FalkorLib::Git.fetch( git_root_dir ) raise IOError, "The git subtree directory '#{dir}' does not exists" unless File.directory?( File.join(git_root_dir, dir) ) info "\t\\__ pulling changes" exit_status = execute "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" #exit_status = puts "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" end end exit_status end
ruby
def subtree_up(path = Dir.pwd) error "Unable to pull subtree(s): Dirty Git repository" if FalkorLib::Git.dirty?( path ) exit_status = 0 git_root_dir = rootdir(path) Dir.chdir(git_root_dir) do FalkorLib.config.git[:subtrees].each do |dir, conf| next if conf[:url].nil? #url = conf[:url] remote = dir.gsub(/\//, '-') branch = (conf[:branch].nil?) ? 'master' : conf[:branch] remotes = FalkorLib::Git.remotes info "Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'" raise IOError, "The git remote '#{remote}' is not configured" unless remotes.include?( remote ) info "\t\\__ fetching remote '#{remotes.join(',')}'" FalkorLib::Git.fetch( git_root_dir ) raise IOError, "The git subtree directory '#{dir}' does not exists" unless File.directory?( File.join(git_root_dir, dir) ) info "\t\\__ pulling changes" exit_status = execute "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" #exit_status = puts "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" end end exit_status end
[ "def", "subtree_up", "(", "path", "=", "Dir", ".", "pwd", ")", "error", "\"Unable to pull subtree(s): Dirty Git repository\"", "if", "FalkorLib", "::", "Git", ".", "dirty?", "(", "path", ")", "exit_status", "=", "0", "git_root_dir", "=", "rootdir", "(", "path", ")", "Dir", ".", "chdir", "(", "git_root_dir", ")", "do", "FalkorLib", ".", "config", ".", "git", "[", ":subtrees", "]", ".", "each", "do", "|", "dir", ",", "conf", "|", "next", "if", "conf", "[", ":url", "]", ".", "nil?", "#url = conf[:url]", "remote", "=", "dir", ".", "gsub", "(", "/", "\\/", "/", ",", "'-'", ")", "branch", "=", "(", "conf", "[", ":branch", "]", ".", "nil?", ")", "?", "'master'", ":", "conf", "[", ":branch", "]", "remotes", "=", "FalkorLib", "::", "Git", ".", "remotes", "info", "\"Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'\"", "raise", "IOError", ",", "\"The git remote '#{remote}' is not configured\"", "unless", "remotes", ".", "include?", "(", "remote", ")", "info", "\"\\t\\\\__ fetching remote '#{remotes.join(',')}'\"", "FalkorLib", "::", "Git", ".", "fetch", "(", "git_root_dir", ")", "raise", "IOError", ",", "\"The git subtree directory '#{dir}' does not exists\"", "unless", "File", ".", "directory?", "(", "File", ".", "join", "(", "git_root_dir", ",", "dir", ")", ")", "info", "\"\\t\\\\__ pulling changes\"", "exit_status", "=", "execute", "\"git subtree pull --prefix #{dir} --squash #{remote} #{branch}\"", "#exit_status = puts \"git subtree pull --prefix #{dir} --squash #{remote} #{branch}\"", "end", "end", "exit_status", "end" ]
Pull the latest changes, assuming the git repository is not dirty
[ "Pull", "the", "latest", "changes", "assuming", "the", "git", "repository", "is", "not", "dirty" ]
1a6d732e8fd5550efb7c98a87ee97fcd2e051858
https://github.com/Falkor/falkorlib/blob/1a6d732e8fd5550efb7c98a87ee97fcd2e051858/lib/falkorlib/git/base.rb#L449-L471
5,808
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.local_init
def local_init(bucket_count, bucket_width, start_priority) @width = bucket_width old = @buckets @buckets = if @cached_buckets == nil Array.new(bucket_count) { [] } else n = @cached_buckets.size if bucket_count < n # shrink the array @cached_buckets.slice!(bucket_count, n) else # expand the array @cached_buckets.fill(n, bucket_count - n) { [] } end @cached_buckets end @cached_buckets = old @last_priority = start_priority i = start_priority / bucket_width # virtual bucket @last_bucket = (i % bucket_count).to_i @bucket_top = (i+1) * bucket_width + 0.5 * bucket_width # set up queue size change thresholds @shrink_threshold = bucket_count / 2 - 2 @expand_threshold = 2 * bucket_count end
ruby
def local_init(bucket_count, bucket_width, start_priority) @width = bucket_width old = @buckets @buckets = if @cached_buckets == nil Array.new(bucket_count) { [] } else n = @cached_buckets.size if bucket_count < n # shrink the array @cached_buckets.slice!(bucket_count, n) else # expand the array @cached_buckets.fill(n, bucket_count - n) { [] } end @cached_buckets end @cached_buckets = old @last_priority = start_priority i = start_priority / bucket_width # virtual bucket @last_bucket = (i % bucket_count).to_i @bucket_top = (i+1) * bucket_width + 0.5 * bucket_width # set up queue size change thresholds @shrink_threshold = bucket_count / 2 - 2 @expand_threshold = 2 * bucket_count end
[ "def", "local_init", "(", "bucket_count", ",", "bucket_width", ",", "start_priority", ")", "@width", "=", "bucket_width", "old", "=", "@buckets", "@buckets", "=", "if", "@cached_buckets", "==", "nil", "Array", ".", "new", "(", "bucket_count", ")", "{", "[", "]", "}", "else", "n", "=", "@cached_buckets", ".", "size", "if", "bucket_count", "<", "n", "# shrink the array", "@cached_buckets", ".", "slice!", "(", "bucket_count", ",", "n", ")", "else", "# expand the array", "@cached_buckets", ".", "fill", "(", "n", ",", "bucket_count", "-", "n", ")", "{", "[", "]", "}", "end", "@cached_buckets", "end", "@cached_buckets", "=", "old", "@last_priority", "=", "start_priority", "i", "=", "start_priority", "/", "bucket_width", "# virtual bucket", "@last_bucket", "=", "(", "i", "%", "bucket_count", ")", ".", "to_i", "@bucket_top", "=", "(", "i", "+", "1", ")", "*", "bucket_width", "+", "0.5", "*", "bucket_width", "# set up queue size change thresholds", "@shrink_threshold", "=", "bucket_count", "/", "2", "-", "2", "@expand_threshold", "=", "2", "*", "bucket_count", "end" ]
Initializes a bucket array within
[ "Initializes", "a", "bucket", "array", "within" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L231-L257
5,809
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.resize
def resize(new_size) return unless @resize_enabled bucket_width = new_width # find new bucket width local_init(new_size, bucket_width, @last_priority) i = 0 while i < @cached_buckets.size bucket = @cached_buckets[i] @size -= bucket.size while obj = bucket.pop self << obj end i += 1 end end
ruby
def resize(new_size) return unless @resize_enabled bucket_width = new_width # find new bucket width local_init(new_size, bucket_width, @last_priority) i = 0 while i < @cached_buckets.size bucket = @cached_buckets[i] @size -= bucket.size while obj = bucket.pop self << obj end i += 1 end end
[ "def", "resize", "(", "new_size", ")", "return", "unless", "@resize_enabled", "bucket_width", "=", "new_width", "# find new bucket width", "local_init", "(", "new_size", ",", "bucket_width", ",", "@last_priority", ")", "i", "=", "0", "while", "i", "<", "@cached_buckets", ".", "size", "bucket", "=", "@cached_buckets", "[", "i", "]", "@size", "-=", "bucket", ".", "size", "while", "obj", "=", "bucket", ".", "pop", "self", "<<", "obj", "end", "i", "+=", "1", "end", "end" ]
Resize buckets to new_size.
[ "Resize", "buckets", "to", "new_size", "." ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L260-L275
5,810
devs-ruby/devs
lib/devs/schedulers/calendar_queue.rb
DEVS.CalendarQueue.new_width
def new_width # decides how many queue elements to sample return 1.0 if @size < 2 n = if @size <= 5 @size else 5 + (@size / 10).to_i end n = 25 if n > 25 # record variables tmp_last_bucket = @last_bucket tmp_last_priority = @last_priority tmp_bucket_top = @bucket_top # dequeue n events from the queue and record their priorities with # resize_enabled set to false. @resize_enabled = false tmp = Array.new(n) average = 0.0 i = 0 while i < n # dequeue events to get a test sample tmp[i] = self.pop # and sum up the differences in time average += tmp[i].time_next - tmp[i-1].time_next if i > 0 i += 1 end # calculate average separation of sampled events average = average / (n-1).to_f # put the first sample back onto the queue self << tmp[0] # recalculate average using only separations smaller than twice the # original average new_average = 0.0 j = 0 i = 1 while i < n sub = tmp[i].time_next - tmp[i-1].time_next if sub < average * 2.0 new_average += sub j += 1 end # put the remaining samples back onto the queue self << tmp[i] i += 1 end new_average = new_average / j.to_f # restore variables @resize_enabled = true @last_bucket = tmp_last_bucket @last_priority = tmp_last_priority @bucket_top = tmp_bucket_top # this is the new width if new_average > 0.0 new_average * 3.0 elsif average > 0.0 average * 2.0 else 1.0 end end
ruby
def new_width # decides how many queue elements to sample return 1.0 if @size < 2 n = if @size <= 5 @size else 5 + (@size / 10).to_i end n = 25 if n > 25 # record variables tmp_last_bucket = @last_bucket tmp_last_priority = @last_priority tmp_bucket_top = @bucket_top # dequeue n events from the queue and record their priorities with # resize_enabled set to false. @resize_enabled = false tmp = Array.new(n) average = 0.0 i = 0 while i < n # dequeue events to get a test sample tmp[i] = self.pop # and sum up the differences in time average += tmp[i].time_next - tmp[i-1].time_next if i > 0 i += 1 end # calculate average separation of sampled events average = average / (n-1).to_f # put the first sample back onto the queue self << tmp[0] # recalculate average using only separations smaller than twice the # original average new_average = 0.0 j = 0 i = 1 while i < n sub = tmp[i].time_next - tmp[i-1].time_next if sub < average * 2.0 new_average += sub j += 1 end # put the remaining samples back onto the queue self << tmp[i] i += 1 end new_average = new_average / j.to_f # restore variables @resize_enabled = true @last_bucket = tmp_last_bucket @last_priority = tmp_last_priority @bucket_top = tmp_bucket_top # this is the new width if new_average > 0.0 new_average * 3.0 elsif average > 0.0 average * 2.0 else 1.0 end end
[ "def", "new_width", "# decides how many queue elements to sample", "return", "1.0", "if", "@size", "<", "2", "n", "=", "if", "@size", "<=", "5", "@size", "else", "5", "+", "(", "@size", "/", "10", ")", ".", "to_i", "end", "n", "=", "25", "if", "n", ">", "25", "# record variables", "tmp_last_bucket", "=", "@last_bucket", "tmp_last_priority", "=", "@last_priority", "tmp_bucket_top", "=", "@bucket_top", "# dequeue n events from the queue and record their priorities with", "# resize_enabled set to false.", "@resize_enabled", "=", "false", "tmp", "=", "Array", ".", "new", "(", "n", ")", "average", "=", "0.0", "i", "=", "0", "while", "i", "<", "n", "# dequeue events to get a test sample", "tmp", "[", "i", "]", "=", "self", ".", "pop", "# and sum up the differences in time", "average", "+=", "tmp", "[", "i", "]", ".", "time_next", "-", "tmp", "[", "i", "-", "1", "]", ".", "time_next", "if", "i", ">", "0", "i", "+=", "1", "end", "# calculate average separation of sampled events", "average", "=", "average", "/", "(", "n", "-", "1", ")", ".", "to_f", "# put the first sample back onto the queue", "self", "<<", "tmp", "[", "0", "]", "# recalculate average using only separations smaller than twice the", "# original average", "new_average", "=", "0.0", "j", "=", "0", "i", "=", "1", "while", "i", "<", "n", "sub", "=", "tmp", "[", "i", "]", ".", "time_next", "-", "tmp", "[", "i", "-", "1", "]", ".", "time_next", "if", "sub", "<", "average", "*", "2.0", "new_average", "+=", "sub", "j", "+=", "1", "end", "# put the remaining samples back onto the queue", "self", "<<", "tmp", "[", "i", "]", "i", "+=", "1", "end", "new_average", "=", "new_average", "/", "j", ".", "to_f", "# restore variables", "@resize_enabled", "=", "true", "@last_bucket", "=", "tmp_last_bucket", "@last_priority", "=", "tmp_last_priority", "@bucket_top", "=", "tmp_bucket_top", "# this is the new width", "if", "new_average", ">", "0.0", "new_average", "*", "3.0", "elsif", "average", ">", "0.0", "average", "*", "2.0", "else", "1.0", "end", "end" ]
Calculates the width to use for buckets
[ "Calculates", "the", "width", "to", "use", "for", "buckets" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/schedulers/calendar_queue.rb#L278-L344
5,811
devs-ruby/devs
lib/devs/simulation.rb
DEVS.Simulation.transition_stats
def transition_stats if done? @transition_stats ||= ( stats = {} hierarchy = @processor.children.dup i = 0 while i < hierarchy.size child = hierarchy[i] if child.model.coupled? hierarchy.concat(child.children) else stats[child.model.name] = child.transition_stats end i+=1 end total = Hash.new(0) stats.values.each { |h| h.each { |k, v| total[k] += v }} stats[:TOTAL] = total stats ) end end
ruby
def transition_stats if done? @transition_stats ||= ( stats = {} hierarchy = @processor.children.dup i = 0 while i < hierarchy.size child = hierarchy[i] if child.model.coupled? hierarchy.concat(child.children) else stats[child.model.name] = child.transition_stats end i+=1 end total = Hash.new(0) stats.values.each { |h| h.each { |k, v| total[k] += v }} stats[:TOTAL] = total stats ) end end
[ "def", "transition_stats", "if", "done?", "@transition_stats", "||=", "(", "stats", "=", "{", "}", "hierarchy", "=", "@processor", ".", "children", ".", "dup", "i", "=", "0", "while", "i", "<", "hierarchy", ".", "size", "child", "=", "hierarchy", "[", "i", "]", "if", "child", ".", "model", ".", "coupled?", "hierarchy", ".", "concat", "(", "child", ".", "children", ")", "else", "stats", "[", "child", ".", "model", ".", "name", "]", "=", "child", ".", "transition_stats", "end", "i", "+=", "1", "end", "total", "=", "Hash", ".", "new", "(", "0", ")", "stats", ".", "values", ".", "each", "{", "|", "h", "|", "h", ".", "each", "{", "|", "k", ",", "v", "|", "total", "[", "k", "]", "+=", "v", "}", "}", "stats", "[", ":TOTAL", "]", "=", "total", "stats", ")", "end", "end" ]
Returns the number of transitions per model along with the total @return [Hash<Symbol, Fixnum>]
[ "Returns", "the", "number", "of", "transitions", "per", "model", "along", "with", "the", "total" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/simulation.rb#L163-L184
5,812
robertwahler/repo_manager
lib/repo_manager/views/base_view.rb
RepoManager.BaseView.partial
def partial(filename) filename = partial_path(filename) raise "unable to find partial file: #{filename}" unless File.exists?(filename) contents = File.open(filename, "rb") {|f| f.read} # TODO: detect template EOL and match it to the partial's EOL # force unix eol contents.gsub!(/\r\n/, "\n") if contents.match("\r\n") contents end
ruby
def partial(filename) filename = partial_path(filename) raise "unable to find partial file: #{filename}" unless File.exists?(filename) contents = File.open(filename, "rb") {|f| f.read} # TODO: detect template EOL and match it to the partial's EOL # force unix eol contents.gsub!(/\r\n/, "\n") if contents.match("\r\n") contents end
[ "def", "partial", "(", "filename", ")", "filename", "=", "partial_path", "(", "filename", ")", "raise", "\"unable to find partial file: #{filename}\"", "unless", "File", ".", "exists?", "(", "filename", ")", "contents", "=", "File", ".", "open", "(", "filename", ",", "\"rb\"", ")", "{", "|", "f", "|", "f", ".", "read", "}", "# TODO: detect template EOL and match it to the partial's EOL", "# force unix eol", "contents", ".", "gsub!", "(", "/", "\\r", "\\n", "/", ",", "\"\\n\"", ")", "if", "contents", ".", "match", "(", "\"\\r\\n\"", ")", "contents", "end" ]
render a partial filename: unless absolute, it will be relative to the main template @example slim escapes HTML, use '==' head == render 'mystyle.css' @return [String] of non-escaped textual content
[ "render", "a", "partial" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L86-L94
5,813
robertwahler/repo_manager
lib/repo_manager/views/base_view.rb
RepoManager.BaseView.partial_path
def partial_path(filename) return filename if filename.nil? || Pathname.new(filename).absolute? # try relative to template if template base_folder = File.dirname(template) filename = File.expand_path(File.join(base_folder, filename)) return filename if File.exists?(filename) end # try relative to PWD filename = File.expand_path(File.join(FileUtils.pwd, filename)) return filename if File.exists?(filename) # try built in template folder filename = File.expand_path(File.join('../templates', filename), __FILE__) end
ruby
def partial_path(filename) return filename if filename.nil? || Pathname.new(filename).absolute? # try relative to template if template base_folder = File.dirname(template) filename = File.expand_path(File.join(base_folder, filename)) return filename if File.exists?(filename) end # try relative to PWD filename = File.expand_path(File.join(FileUtils.pwd, filename)) return filename if File.exists?(filename) # try built in template folder filename = File.expand_path(File.join('../templates', filename), __FILE__) end
[ "def", "partial_path", "(", "filename", ")", "return", "filename", "if", "filename", ".", "nil?", "||", "Pathname", ".", "new", "(", "filename", ")", ".", "absolute?", "# try relative to template", "if", "template", "base_folder", "=", "File", ".", "dirname", "(", "template", ")", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "base_folder", ",", "filename", ")", ")", "return", "filename", "if", "File", ".", "exists?", "(", "filename", ")", "end", "# try relative to PWD", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "FileUtils", ".", "pwd", ",", "filename", ")", ")", "return", "filename", "if", "File", ".", "exists?", "(", "filename", ")", "# try built in template folder", "filename", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "'../templates'", ",", "filename", ")", ",", "__FILE__", ")", "end" ]
full expanded path to the given partial
[ "full", "expanded", "path", "to", "the", "given", "partial" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/views/base_view.rb#L118-L134
5,814
abarrak/network-client
lib/network/client.rb
Network.Client.set_logger
def set_logger @logger = if block_given? yield elsif defined?(Rails) Rails.logger else logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger end end
ruby
def set_logger @logger = if block_given? yield elsif defined?(Rails) Rails.logger else logger = Logger.new(STDOUT) logger.level = Logger::DEBUG logger end end
[ "def", "set_logger", "@logger", "=", "if", "block_given?", "yield", "elsif", "defined?", "(", "Rails", ")", "Rails", ".", "logger", "else", "logger", "=", "Logger", ".", "new", "(", "STDOUT", ")", "logger", ".", "level", "=", "Logger", "::", "DEBUG", "logger", "end", "end" ]
Sets the client logger object. Execution is yielded to passed +block+ to set, customize, and returning a logger instance. == Returns: +logger+ instance variable.
[ "Sets", "the", "client", "logger", "object", ".", "Execution", "is", "yielded", "to", "passed", "+", "block", "+", "to", "set", "customize", "and", "returning", "a", "logger", "instance", "." ]
4cf898be318bb4df056f82d405ba9ce09d3f59ac
https://github.com/abarrak/network-client/blob/4cf898be318bb4df056f82d405ba9ce09d3f59ac/lib/network/client.rb#L168-L178
5,815
pwnieexpress/snapi
lib/snapi/validator.rb
Snapi.Validator.valid_input?
def valid_input?(key,string) raise InvalidFormatError unless valid_regex_format?(key) boolarray = validation_regex[key].map do |regxp| (string =~ regxp) == 0 ? true : false end return true if boolarray.include?(true) false end
ruby
def valid_input?(key,string) raise InvalidFormatError unless valid_regex_format?(key) boolarray = validation_regex[key].map do |regxp| (string =~ regxp) == 0 ? true : false end return true if boolarray.include?(true) false end
[ "def", "valid_input?", "(", "key", ",", "string", ")", "raise", "InvalidFormatError", "unless", "valid_regex_format?", "(", "key", ")", "boolarray", "=", "validation_regex", "[", "key", "]", ".", "map", "do", "|", "regxp", "|", "(", "string", "=~", "regxp", ")", "==", "0", "?", "true", ":", "false", "end", "return", "true", "if", "boolarray", ".", "include?", "(", "true", ")", "false", "end" ]
Core method of the module which attempts to check if a provided string matches any of the regex's as identified by the key @params key, Symbol key which maps to one of the keys in the validation_regex method below @params string, String to check @returns Boolean, true if string checks out
[ "Core", "method", "of", "the", "module", "which", "attempts", "to", "check", "if", "a", "provided", "string", "matches", "any", "of", "the", "regex", "s", "as", "identified", "by", "the", "key" ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/validator.rb#L14-L23
5,816
pwnieexpress/snapi
lib/snapi/validator.rb
Snapi.Validator.validation_regex
def validation_regex { :address => [HOSTNAME_REGEX, DOMAIN_REGEX, IP_V4_REGEX, IP_V6_REGEX], :anything => [/.*/], :bool => [TRUEFALSE_REGEX], :command => [SIMPLE_COMMAND_REGEX], :gsm_adapter => [ADAPTER_REGEX], :hostname => [HOSTNAME_REGEX], :interface => [INTERFACE_REGEX], :ip => [IP_V4_REGEX, IP_V6_REGEX], :ipv6 => [IP_V6_REGEX], :ipv4 => [IP_V4_REGEX], :json => [JsonValidator], :mac => [MAC_REGEX], :snapi_function_name => [SNAPI_FUNCTION_NAME], :on_off => [ON_OFF_REGEX], :port => [PORT_REGEX], :uri => [URI_REGEX], } end
ruby
def validation_regex { :address => [HOSTNAME_REGEX, DOMAIN_REGEX, IP_V4_REGEX, IP_V6_REGEX], :anything => [/.*/], :bool => [TRUEFALSE_REGEX], :command => [SIMPLE_COMMAND_REGEX], :gsm_adapter => [ADAPTER_REGEX], :hostname => [HOSTNAME_REGEX], :interface => [INTERFACE_REGEX], :ip => [IP_V4_REGEX, IP_V6_REGEX], :ipv6 => [IP_V6_REGEX], :ipv4 => [IP_V4_REGEX], :json => [JsonValidator], :mac => [MAC_REGEX], :snapi_function_name => [SNAPI_FUNCTION_NAME], :on_off => [ON_OFF_REGEX], :port => [PORT_REGEX], :uri => [URI_REGEX], } end
[ "def", "validation_regex", "{", ":address", "=>", "[", "HOSTNAME_REGEX", ",", "DOMAIN_REGEX", ",", "IP_V4_REGEX", ",", "IP_V6_REGEX", "]", ",", ":anything", "=>", "[", "/", "/", "]", ",", ":bool", "=>", "[", "TRUEFALSE_REGEX", "]", ",", ":command", "=>", "[", "SIMPLE_COMMAND_REGEX", "]", ",", ":gsm_adapter", "=>", "[", "ADAPTER_REGEX", "]", ",", ":hostname", "=>", "[", "HOSTNAME_REGEX", "]", ",", ":interface", "=>", "[", "INTERFACE_REGEX", "]", ",", ":ip", "=>", "[", "IP_V4_REGEX", ",", "IP_V6_REGEX", "]", ",", ":ipv6", "=>", "[", "IP_V6_REGEX", "]", ",", ":ipv4", "=>", "[", "IP_V4_REGEX", "]", ",", ":json", "=>", "[", "JsonValidator", "]", ",", ":mac", "=>", "[", "MAC_REGEX", "]", ",", ":snapi_function_name", "=>", "[", "SNAPI_FUNCTION_NAME", "]", ",", ":on_off", "=>", "[", "ON_OFF_REGEX", "]", ",", ":port", "=>", "[", "PORT_REGEX", "]", ",", ":uri", "=>", "[", "URI_REGEX", "]", ",", "}", "end" ]
A helper dictionary which returns and array of valid Regexp patterns in exchange for a valid key @returns Hash, dictionary of symbols and Regexp arrays
[ "A", "helper", "dictionary", "which", "returns", "and", "array", "of", "valid", "Regexp", "patterns", "in", "exchange", "for", "a", "valid", "key" ]
3c2a6fe454721945e4e58b8b496d3c20ada55df7
https://github.com/pwnieexpress/snapi/blob/3c2a6fe454721945e4e58b8b496d3c20ada55df7/lib/snapi/validator.rb#L45-L64
5,817
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.load_tasks
def load_tasks return if @loaded # By convention, the '*_helper.rb' files are helpers and need to be loaded first. Load # them into the Thor::Sandbox namespace Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| if task.match(/_helper\.rb$/) #logger.debug "load_thorfile helper: #{task}" ::Thor::Util.load_thorfile task end end # Now load the thor files Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| unless task.match(/_helper\.rb$/) #logger.debug "load_thorfile: #{task}" ::Thor::Util.load_thorfile task end end # load user tasks if user_tasks_folder Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task if task.match(/_helper\.rb$/) } Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task unless task.match(/_helper\.rb$/) } end @loaded = true end
ruby
def load_tasks return if @loaded # By convention, the '*_helper.rb' files are helpers and need to be loaded first. Load # them into the Thor::Sandbox namespace Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| if task.match(/_helper\.rb$/) #logger.debug "load_thorfile helper: #{task}" ::Thor::Util.load_thorfile task end end # Now load the thor files Dir.glob( File.join(File.dirname(__FILE__), '**', '*.rb') ).each do |task| unless task.match(/_helper\.rb$/) #logger.debug "load_thorfile: #{task}" ::Thor::Util.load_thorfile task end end # load user tasks if user_tasks_folder Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task if task.match(/_helper\.rb$/) } Dir.glob( File.join([user_tasks_folder, '**', '*.{rb,thor}']) ).each { |task| ::Thor::Util.load_thorfile task unless task.match(/_helper\.rb$/) } end @loaded = true end
[ "def", "load_tasks", "return", "if", "@loaded", "# By convention, the '*_helper.rb' files are helpers and need to be loaded first. Load", "# them into the Thor::Sandbox namespace", "Dir", ".", "glob", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'**'", ",", "'*.rb'", ")", ")", ".", "each", "do", "|", "task", "|", "if", "task", ".", "match", "(", "/", "\\.", "/", ")", "#logger.debug \"load_thorfile helper: #{task}\"", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "end", "end", "# Now load the thor files", "Dir", ".", "glob", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'**'", ",", "'*.rb'", ")", ")", ".", "each", "do", "|", "task", "|", "unless", "task", ".", "match", "(", "/", "\\.", "/", ")", "#logger.debug \"load_thorfile: #{task}\"", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "end", "end", "# load user tasks", "if", "user_tasks_folder", "Dir", ".", "glob", "(", "File", ".", "join", "(", "[", "user_tasks_folder", ",", "'**'", ",", "'*.{rb,thor}'", "]", ")", ")", ".", "each", "{", "|", "task", "|", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "if", "task", ".", "match", "(", "/", "\\.", "/", ")", "}", "Dir", ".", "glob", "(", "File", ".", "join", "(", "[", "user_tasks_folder", ",", "'**'", ",", "'*.{rb,thor}'", "]", ")", ")", ".", "each", "{", "|", "task", "|", "::", "Thor", "::", "Util", ".", "load_thorfile", "task", "unless", "task", ".", "match", "(", "/", "\\.", "/", ")", "}", "end", "@loaded", "=", "true", "end" ]
load all the tasks in this gem plus the user's own repo_manager task folder NOTE: doesn't load any default tasks or non-RepoManager tasks
[ "load", "all", "the", "tasks", "in", "this", "gem", "plus", "the", "user", "s", "own", "repo_manager", "task", "folder" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L72-L99
5,818
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.task_help
def task_help(name) load_tasks klass, task = find_by_namespace(name) # set '$thor_runner' to true to display full namespace $thor_runner = true klass.task_help(shell , task) end
ruby
def task_help(name) load_tasks klass, task = find_by_namespace(name) # set '$thor_runner' to true to display full namespace $thor_runner = true klass.task_help(shell , task) end
[ "def", "task_help", "(", "name", ")", "load_tasks", "klass", ",", "task", "=", "find_by_namespace", "(", "name", ")", "# set '$thor_runner' to true to display full namespace", "$thor_runner", "=", "true", "klass", ".", "task_help", "(", "shell", ",", "task", ")", "end" ]
display help for the given task
[ "display", "help", "for", "the", "given", "task" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L135-L144
5,819
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.list_tasks
def list_tasks load_tasks # set '$thor_runner' to true to display full namespace $thor_runner = true list = [] #Thor.printable_tasks(all = true, subcommand = true) Thor::Base.subclasses.each do |klass| list += klass.printable_tasks(false) unless klass == Thor end list.sort!{ |a,b| a[0] <=> b[0] } title = "repo_manager tasks" shell.say shell.set_color(title, :blue, bold=true) shell.say "-" * title.size shell.print_table(list, :ident => 2, :truncate => true) end
ruby
def list_tasks load_tasks # set '$thor_runner' to true to display full namespace $thor_runner = true list = [] #Thor.printable_tasks(all = true, subcommand = true) Thor::Base.subclasses.each do |klass| list += klass.printable_tasks(false) unless klass == Thor end list.sort!{ |a,b| a[0] <=> b[0] } title = "repo_manager tasks" shell.say shell.set_color(title, :blue, bold=true) shell.say "-" * title.size shell.print_table(list, :ident => 2, :truncate => true) end
[ "def", "list_tasks", "load_tasks", "# set '$thor_runner' to true to display full namespace", "$thor_runner", "=", "true", "list", "=", "[", "]", "#Thor.printable_tasks(all = true, subcommand = true)", "Thor", "::", "Base", ".", "subclasses", ".", "each", "do", "|", "klass", "|", "list", "+=", "klass", ".", "printable_tasks", "(", "false", ")", "unless", "klass", "==", "Thor", "end", "list", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", "[", "0", "]", "<=>", "b", "[", "0", "]", "}", "title", "=", "\"repo_manager tasks\"", "shell", ".", "say", "shell", ".", "set_color", "(", "title", ",", ":blue", ",", "bold", "=", "true", ")", "shell", ".", "say", "\"-\"", "*", "title", ".", "size", "shell", ".", "print_table", "(", "list", ",", ":ident", "=>", "2", ",", ":truncate", "=>", "true", ")", "end" ]
display a list of tasks for user display
[ "display", "a", "list", "of", "tasks", "for", "user", "display" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L147-L163
5,820
robertwahler/repo_manager
lib/repo_manager/tasks/task_manager.rb
RepoManager.TaskManager.list_bare_tasks
def list_bare_tasks load_tasks Thor::Base.subclasses.each do |klass| unless klass == Thor klass.tasks.each do |t| puts "#{klass.namespace}:#{t[0]}" end end end end
ruby
def list_bare_tasks load_tasks Thor::Base.subclasses.each do |klass| unless klass == Thor klass.tasks.each do |t| puts "#{klass.namespace}:#{t[0]}" end end end end
[ "def", "list_bare_tasks", "load_tasks", "Thor", "::", "Base", ".", "subclasses", ".", "each", "do", "|", "klass", "|", "unless", "klass", "==", "Thor", "klass", ".", "tasks", ".", "each", "do", "|", "t", "|", "puts", "\"#{klass.namespace}:#{t[0]}\"", "end", "end", "end", "end" ]
display a list of tasks for CLI completion
[ "display", "a", "list", "of", "tasks", "for", "CLI", "completion" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/task_manager.rb#L166-L176
5,821
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.search_for_by_provider
def search_for_by_provider(name, provider) url = build_query(name) url += '/fuzzy/' + provider + "/web" data = @client.query(url) data["results"] end
ruby
def search_for_by_provider(name, provider) url = build_query(name) url += '/fuzzy/' + provider + "/web" data = @client.query(url) data["results"] end
[ "def", "search_for_by_provider", "(", "name", ",", "provider", ")", "url", "=", "build_query", "(", "name", ")", "url", "+=", "'/fuzzy/'", "+", "provider", "+", "\"/web\"", "data", "=", "@client", ".", "query", "(", "url", ")", "data", "[", "\"results\"", "]", "end" ]
Search by provider
[ "Search", "by", "provider" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L17-L22
5,822
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.search_by_db_id
def search_by_db_id(id, type) url = @base_url url += "/search/id/" case type when "tvdb" url += "tvdb/" url += id.to_s when "themoviedb" url += "themoviedb/" url += id.to_s when "imdb" url += "imdb/" url += id else puts "That id type does not exist" return end @client.query(url) end
ruby
def search_by_db_id(id, type) url = @base_url url += "/search/id/" case type when "tvdb" url += "tvdb/" url += id.to_s when "themoviedb" url += "themoviedb/" url += id.to_s when "imdb" url += "imdb/" url += id else puts "That id type does not exist" return end @client.query(url) end
[ "def", "search_by_db_id", "(", "id", ",", "type", ")", "url", "=", "@base_url", "url", "+=", "\"/search/id/\"", "case", "type", "when", "\"tvdb\"", "url", "+=", "\"tvdb/\"", "url", "+=", "id", ".", "to_s", "when", "\"themoviedb\"", "url", "+=", "\"themoviedb/\"", "url", "+=", "id", ".", "to_s", "when", "\"imdb\"", "url", "+=", "\"imdb/\"", "url", "+=", "id", "else", "puts", "\"That id type does not exist\"", "return", "end", "@client", ".", "query", "(", "url", ")", "end" ]
Search for show by external db id
[ "Search", "for", "show", "by", "external", "db", "id" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L25-L43
5,823
tmobaird/GuideboxWrapper
lib/GuideboxWrapper/guidebox_tv.rb
GuideboxWrapper.GuideboxTv.show_information
def show_information(name) id = self.search_for(name).first["id"] url = @base_url url += "/show/" + id.to_s @client.query(url) end
ruby
def show_information(name) id = self.search_for(name).first["id"] url = @base_url url += "/show/" + id.to_s @client.query(url) end
[ "def", "show_information", "(", "name", ")", "id", "=", "self", ".", "search_for", "(", "name", ")", ".", "first", "[", "\"id\"", "]", "url", "=", "@base_url", "url", "+=", "\"/show/\"", "+", "id", ".", "to_s", "@client", ".", "query", "(", "url", ")", "end" ]
Get all tv show info
[ "Get", "all", "tv", "show", "info" ]
431d541141c21620b640dcffee6cf23b3d5ca616
https://github.com/tmobaird/GuideboxWrapper/blob/431d541141c21620b640dcffee6cf23b3d5ca616/lib/GuideboxWrapper/guidebox_tv.rb#L66-L71
5,824
devs-ruby/devs
lib/devs/coordinator.rb
DEVS.Coordinator.min_time_next
def min_time_next tn = DEVS::INFINITY if (obj = @scheduler.peek) tn = obj.time_next end tn end
ruby
def min_time_next tn = DEVS::INFINITY if (obj = @scheduler.peek) tn = obj.time_next end tn end
[ "def", "min_time_next", "tn", "=", "DEVS", "::", "INFINITY", "if", "(", "obj", "=", "@scheduler", ".", "peek", ")", "tn", "=", "obj", ".", "time_next", "end", "tn", "end" ]
Returns the minimum time next in all children @return [Numeric] the min time next
[ "Returns", "the", "minimum", "time", "next", "in", "all", "children" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/coordinator.rb#L53-L59
5,825
devs-ruby/devs
lib/devs/coordinator.rb
DEVS.Coordinator.max_time_last
def max_time_last max = 0 i = 0 while i < @children.size tl = @children[i].time_last max = tl if tl > max i += 1 end max end
ruby
def max_time_last max = 0 i = 0 while i < @children.size tl = @children[i].time_last max = tl if tl > max i += 1 end max end
[ "def", "max_time_last", "max", "=", "0", "i", "=", "0", "while", "i", "<", "@children", ".", "size", "tl", "=", "@children", "[", "i", "]", ".", "time_last", "max", "=", "tl", "if", "tl", ">", "max", "i", "+=", "1", "end", "max", "end" ]
Returns the maximum time last in all children @return [Numeric] the max time last
[ "Returns", "the", "maximum", "time", "last", "in", "all", "children" ]
767212b3825068a82ada4ddaabe0a4e3a8144817
https://github.com/devs-ruby/devs/blob/767212b3825068a82ada4ddaabe0a4e3a8144817/lib/devs/coordinator.rb#L64-L73
5,826
mynyml/rack-accept-media-types
lib/rack/accept_media_types.rb
Rack.AcceptMediaTypes.order
def order(types) #:nodoc: types.map {|type| AcceptMediaType.new(type) }.reverse.sort.reverse.select {|type| type.valid? }.map {|type| type.range } end
ruby
def order(types) #:nodoc: types.map {|type| AcceptMediaType.new(type) }.reverse.sort.reverse.select {|type| type.valid? }.map {|type| type.range } end
[ "def", "order", "(", "types", ")", "#:nodoc:", "types", ".", "map", "{", "|", "type", "|", "AcceptMediaType", ".", "new", "(", "type", ")", "}", ".", "reverse", ".", "sort", ".", "reverse", ".", "select", "{", "|", "type", "|", "type", ".", "valid?", "}", ".", "map", "{", "|", "type", "|", "type", ".", "range", "}", "end" ]
Order media types by quality values, remove invalid types, and return media ranges.
[ "Order", "media", "types", "by", "quality", "values", "remove", "invalid", "types", "and", "return", "media", "ranges", "." ]
3d0f38882a466cc72043fd6f6e735b7f255e4b0d
https://github.com/mynyml/rack-accept-media-types/blob/3d0f38882a466cc72043fd6f6e735b7f255e4b0d/lib/rack/accept_media_types.rb#L80-L82
5,827
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.set
def set(key, value) types[key.to_sym] = (value == [] ? [] : (value.is_a?(Symbol) ? value : nil)) messages[key.to_sym] = value end
ruby
def set(key, value) types[key.to_sym] = (value == [] ? [] : (value.is_a?(Symbol) ? value : nil)) messages[key.to_sym] = value end
[ "def", "set", "(", "key", ",", "value", ")", "types", "[", "key", ".", "to_sym", "]", "=", "(", "value", "==", "[", "]", "?", "[", "]", ":", "(", "value", ".", "is_a?", "(", "Symbol", ")", "?", "value", ":", "nil", ")", ")", "messages", "[", "key", ".", "to_sym", "]", "=", "value", "end" ]
Set messages for +key+ to +value+
[ "Set", "messages", "for", "+", "key", "+", "to", "+", "value", "+" ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L122-L125
5,828
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.delete
def delete(key) key = key.to_sym types.delete(key) messages.delete(key) end
ruby
def delete(key) key = key.to_sym types.delete(key) messages.delete(key) end
[ "def", "delete", "(", "key", ")", "key", "=", "key", ".", "to_sym", "types", ".", "delete", "(", "key", ")", "messages", ".", "delete", "(", "key", ")", "end" ]
Delete messages for +key+
[ "Delete", "messages", "for", "+", "key", "+" ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L128-L132
5,829
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.empty?
def empty? all? { |k, v| v && v.empty? && !v.is_a?(String) } end
ruby
def empty? all? { |k, v| v && v.empty? && !v.is_a?(String) } end
[ "def", "empty?", "all?", "{", "|", "k", ",", "v", "|", "v", "&&", "v", ".", "empty?", "&&", "!", "v", ".", "is_a?", "(", "String", ")", "}", "end" ]
Returns true if no errors are found, false otherwise. If the error message is a string it can be empty.
[ "Returns", "true", "if", "no", "errors", "are", "found", "false", "otherwise", ".", "If", "the", "error", "message", "is", "a", "string", "it", "can", "be", "empty", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L219-L221
5,830
lml/lev
lib/lev/better_active_model_errors.rb
Lev.BetterActiveModelErrors.add_on_empty
def add_on_empty(attributes, options = {}) [attributes].flatten.each do |attribute| value = @base.send(:read_attribute_for_validation, attribute) is_empty = value.respond_to?(:empty?) ? value.empty? : false add(attribute, :empty, options) if value.nil? || is_empty end end
ruby
def add_on_empty(attributes, options = {}) [attributes].flatten.each do |attribute| value = @base.send(:read_attribute_for_validation, attribute) is_empty = value.respond_to?(:empty?) ? value.empty? : false add(attribute, :empty, options) if value.nil? || is_empty end end
[ "def", "add_on_empty", "(", "attributes", ",", "options", "=", "{", "}", ")", "[", "attributes", "]", ".", "flatten", ".", "each", "do", "|", "attribute", "|", "value", "=", "@base", ".", "send", "(", ":read_attribute_for_validation", ",", "attribute", ")", "is_empty", "=", "value", ".", "respond_to?", "(", ":empty?", ")", "?", "value", ".", "empty?", ":", "false", "add", "(", "attribute", ",", ":empty", ",", "options", ")", "if", "value", ".", "nil?", "||", "is_empty", "end", "end" ]
Will add an error message to each of the attributes in +attributes+ that is empty.
[ "Will", "add", "an", "error", "message", "to", "each", "of", "the", "attributes", "in", "+", "attributes", "+", "that", "is", "empty", "." ]
ce39ac122796974dafb24ee61428540dacf34371
https://github.com/lml/lev/blob/ce39ac122796974dafb24ee61428540dacf34371/lib/lev/better_active_model_errors.rb#L269-L275
5,831
chills42/guard-inch
lib/guard/inch.rb
Guard.Inch.start
def start message = 'Guard::Inch is running' message << ' in pedantic mode' if options[:pedantic] message << ' and inspecting private fields' if options[:private] ::Guard::UI.info message run_all if options[:all_on_start] end
ruby
def start message = 'Guard::Inch is running' message << ' in pedantic mode' if options[:pedantic] message << ' and inspecting private fields' if options[:private] ::Guard::UI.info message run_all if options[:all_on_start] end
[ "def", "start", "message", "=", "'Guard::Inch is running'", "message", "<<", "' in pedantic mode'", "if", "options", "[", ":pedantic", "]", "message", "<<", "' and inspecting private fields'", "if", "options", "[", ":private", "]", "::", "Guard", "::", "UI", ".", "info", "message", "run_all", "if", "options", "[", ":all_on_start", "]", "end" ]
configure a new instance of the plugin @param [Hash] options the guard plugin options On start, display a message and optionally run the documentation lint
[ "configure", "a", "new", "instance", "of", "the", "plugin" ]
5f8427996797e5c2100b7a1abb36fedf696b725c
https://github.com/chills42/guard-inch/blob/5f8427996797e5c2100b7a1abb36fedf696b725c/lib/guard/inch.rb#L19-L25
5,832
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.update_fields_values
def update_fields_values(params) params || return fields.each {|f| f.find_or_create_type_object(self).tap {|t| t || next params[f.code_name.to_sym].tap {|v| v && t.value = v} t.save }} end
ruby
def update_fields_values(params) params || return fields.each {|f| f.find_or_create_type_object(self).tap {|t| t || next params[f.code_name.to_sym].tap {|v| v && t.value = v} t.save }} end
[ "def", "update_fields_values", "(", "params", ")", "params", "||", "return", "fields", ".", "each", "{", "|", "f", "|", "f", ".", "find_or_create_type_object", "(", "self", ")", ".", "tap", "{", "|", "t", "|", "t", "||", "next", "params", "[", "f", ".", "code_name", ".", "to_sym", "]", ".", "tap", "{", "|", "v", "|", "v", "&&", "t", ".", "value", "=", "v", "}", "t", ".", "save", "}", "}", "end" ]
Update all fields values with given params. @param params should looks like <tt>{price: 500, content: 'Hello'}</tt>
[ "Update", "all", "fields", "values", "with", "given", "params", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L133-L139
5,833
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.find_page_in_branch
def find_page_in_branch(cname) Template.find_by(code_name: cname.singularize).tap {|t| t || return (descendants.where(template_id: t.id) if cname == cname.pluralize).tap {|r| r ||= [] return r.empty? ? ancestors.find_by(template_id: t.id) : r}} end
ruby
def find_page_in_branch(cname) Template.find_by(code_name: cname.singularize).tap {|t| t || return (descendants.where(template_id: t.id) if cname == cname.pluralize).tap {|r| r ||= [] return r.empty? ? ancestors.find_by(template_id: t.id) : r}} end
[ "def", "find_page_in_branch", "(", "cname", ")", "Template", ".", "find_by", "(", "code_name", ":", "cname", ".", "singularize", ")", ".", "tap", "{", "|", "t", "|", "t", "||", "return", "(", "descendants", ".", "where", "(", "template_id", ":", "t", ".", "id", ")", "if", "cname", "==", "cname", ".", "pluralize", ")", ".", "tap", "{", "|", "r", "|", "r", "||=", "[", "]", "return", "r", ".", "empty?", "?", "ancestors", ".", "find_by", "(", "template_id", ":", "t", ".", "id", ")", ":", "r", "}", "}", "end" ]
Search page by template code_name in same branch of pages and templates. It allows to call page.category.brand.series.model etc. Return one page if founded in ancestors, and return array of pages if founded in descendants It determines if code_name is singular or nor @param cname template code name
[ "Search", "page", "by", "template", "code_name", "in", "same", "branch", "of", "pages", "and", "templates", ".", "It", "allows", "to", "call", "page", ".", "category", ".", "brand", ".", "series", ".", "model", "etc", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L155-L159
5,834
ivanzotov/constructor
pages/app/models/constructor_pages/page.rb
ConstructorPages.Page.as_json
def as_json(options = {}) {name: self.name, title: self.title}.merge(options).tap do |options| fields.each {|f| options.merge!({f.code_name.to_sym => f.get_value_for(self)})} end end
ruby
def as_json(options = {}) {name: self.name, title: self.title}.merge(options).tap do |options| fields.each {|f| options.merge!({f.code_name.to_sym => f.get_value_for(self)})} end end
[ "def", "as_json", "(", "options", "=", "{", "}", ")", "{", "name", ":", "self", ".", "name", ",", "title", ":", "self", ".", "title", "}", ".", "merge", "(", "options", ")", ".", "tap", "do", "|", "options", "|", "fields", ".", "each", "{", "|", "f", "|", "options", ".", "merge!", "(", "{", "f", ".", "code_name", ".", "to_sym", "=>", "f", ".", "get_value_for", "(", "self", ")", "}", ")", "}", "end", "end" ]
Returns page hash attributes with fields. Default attributes are name and title. Options param allows to add more. @param options default merge name and title page attributes
[ "Returns", "page", "hash", "attributes", "with", "fields", "." ]
1d52fb5b642200a6993f5a630e6934bccbcbf4e8
https://github.com/ivanzotov/constructor/blob/1d52fb5b642200a6993f5a630e6934bccbcbf4e8/pages/app/models/constructor_pages/page.rb#L177-L181
5,835
stve/tophat
lib/tophat/meta.rb
TopHat.MetaHelper.meta_tag
def meta_tag(options, open=false, escape=true) tag(:meta, options, open, escape) end
ruby
def meta_tag(options, open=false, escape=true) tag(:meta, options, open, escape) end
[ "def", "meta_tag", "(", "options", ",", "open", "=", "false", ",", "escape", "=", "true", ")", "tag", "(", ":meta", ",", "options", ",", "open", ",", "escape", ")", "end" ]
Meta Tag helper
[ "Meta", "Tag", "helper" ]
c49a7ec029604f0fa2b64af29a72fb07f317f242
https://github.com/stve/tophat/blob/c49a7ec029604f0fa2b64af29a72fb07f317f242/lib/tophat/meta.rb#L5-L7
5,836
postmodern/ffi-bit_masks
lib/ffi/bit_masks.rb
FFI.BitMasks.bit_mask
def bit_mask(name,flags,type=:uint) bit_mask = BitMask.new(flags,type) typedef(bit_mask,name) return bit_mask end
ruby
def bit_mask(name,flags,type=:uint) bit_mask = BitMask.new(flags,type) typedef(bit_mask,name) return bit_mask end
[ "def", "bit_mask", "(", "name", ",", "flags", ",", "type", "=", ":uint", ")", "bit_mask", "=", "BitMask", ".", "new", "(", "flags", ",", "type", ")", "typedef", "(", "bit_mask", ",", "name", ")", "return", "bit_mask", "end" ]
Defines a new bitmask. @param [Symbol] name The name of the bitmask. @param [Hash{Symbol => Integer}] flags The flags and their masks. @param [Symbol] type The underlying type. @return [BitMask] The new bitmask.
[ "Defines", "a", "new", "bitmask", "." ]
dc34c2f99f9cc9a5629de8ccee87a97a182e0fa8
https://github.com/postmodern/ffi-bit_masks/blob/dc34c2f99f9cc9a5629de8ccee87a97a182e0fa8/lib/ffi/bit_masks.rb#L24-L29
5,837
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.build_up_commands
def build_up_commands local_versions.select{ |v| v > current_version && v <= target_version } .map{ |v| ApplyCommand.new(v) } end
ruby
def build_up_commands local_versions.select{ |v| v > current_version && v <= target_version } .map{ |v| ApplyCommand.new(v) } end
[ "def", "build_up_commands", "local_versions", ".", "select", "{", "|", "v", "|", "v", ">", "current_version", "&&", "v", "<=", "target_version", "}", ".", "map", "{", "|", "v", "|", "ApplyCommand", ".", "new", "(", "v", ")", "}", "end" ]
install all local versions since current a (current) | b | c | d (target) | e
[ "install", "all", "local", "versions", "since", "current" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L73-L76
5,838
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.build_down_commands
def build_down_commands rollbacks = rollback_versions.map{ |v| RollbackCommand.new(v) } missing = missing_versions_before(rollbacks.last.version).map{ |v| ApplyCommand.new(v) } rollbacks + missing end
ruby
def build_down_commands rollbacks = rollback_versions.map{ |v| RollbackCommand.new(v) } missing = missing_versions_before(rollbacks.last.version).map{ |v| ApplyCommand.new(v) } rollbacks + missing end
[ "def", "build_down_commands", "rollbacks", "=", "rollback_versions", ".", "map", "{", "|", "v", "|", "RollbackCommand", ".", "new", "(", "v", ")", "}", "missing", "=", "missing_versions_before", "(", "rollbacks", ".", "last", ".", "version", ")", ".", "map", "{", "|", "v", "|", "ApplyCommand", ".", "new", "(", "v", ")", "}", "rollbacks", "+", "missing", "end" ]
rollback all versions applied past the target and apply missing versions to get to target 0 | a (target) (not applied) | b | c | d (current) | e
[ "rollback", "all", "versions", "applied", "past", "the", "target", "and", "apply", "missing", "versions", "to", "get", "to", "target" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L82-L86
5,839
eprothro/cassie
lib/cassie/schema/migrator.rb
Cassie::Schema.Migrator.missing_versions_before
def missing_versions_before(last_rollback) return [] unless last_rollback rollback_index = applied_versions.index(last_rollback) stop = if rollback_index == applied_versions.length - 1 # rolled back to oldest version, a rollback # would put us in a versionless state. # Any versions up to target should be applied Version.new('0') else applied_versions[rollback_index + 1] end return [] if stop == target_version local_versions.select{ |v| v > stop && v <= target_version } end
ruby
def missing_versions_before(last_rollback) return [] unless last_rollback rollback_index = applied_versions.index(last_rollback) stop = if rollback_index == applied_versions.length - 1 # rolled back to oldest version, a rollback # would put us in a versionless state. # Any versions up to target should be applied Version.new('0') else applied_versions[rollback_index + 1] end return [] if stop == target_version local_versions.select{ |v| v > stop && v <= target_version } end
[ "def", "missing_versions_before", "(", "last_rollback", ")", "return", "[", "]", "unless", "last_rollback", "rollback_index", "=", "applied_versions", ".", "index", "(", "last_rollback", ")", "stop", "=", "if", "rollback_index", "==", "applied_versions", ".", "length", "-", "1", "# rolled back to oldest version, a rollback", "# would put us in a versionless state.", "# Any versions up to target should be applied", "Version", ".", "new", "(", "'0'", ")", "else", "applied_versions", "[", "rollback_index", "+", "1", "]", "end", "return", "[", "]", "if", "stop", "==", "target_version", "local_versions", ".", "select", "{", "|", "v", "|", "v", ">", "stop", "&&", "v", "<=", "target_version", "}", "end" ]
versions that are not applied yet but need to get applied to get up the target version | 0 (stop) | a (target) | b | c
[ "versions", "that", "are", "not", "applied", "yet", "but", "need", "to", "get", "applied", "to", "get", "up", "the", "target", "version" ]
63e71d12d3549882147e715e427a16fd8e0aa210
https://github.com/eprothro/cassie/blob/63e71d12d3549882147e715e427a16fd8e0aa210/lib/cassie/schema/migrator.rb#L99-L116
5,840
nulldef/ciesta
lib/ciesta/class_methods.rb
Ciesta.ClassMethods.field
def field(name, **options) name = name.to_sym definitions[name] = options proxy.instance_eval do define_method(name) { fields[name] } define_method("#{name}=") { |value| fields[name] = value } end end
ruby
def field(name, **options) name = name.to_sym definitions[name] = options proxy.instance_eval do define_method(name) { fields[name] } define_method("#{name}=") { |value| fields[name] = value } end end
[ "def", "field", "(", "name", ",", "**", "options", ")", "name", "=", "name", ".", "to_sym", "definitions", "[", "name", "]", "=", "options", "proxy", ".", "instance_eval", "do", "define_method", "(", "name", ")", "{", "fields", "[", "name", "]", "}", "define_method", "(", "\"#{name}=\"", ")", "{", "|", "value", "|", "fields", "[", "name", "]", "=", "value", "}", "end", "end" ]
Declare new form field @param [Symbol] name Field name @param [Hash] options Options @option (see Ciesta::Field)
[ "Declare", "new", "form", "field" ]
07352988e687c0778fce8cae001fc2876480da32
https://github.com/nulldef/ciesta/blob/07352988e687c0778fce8cae001fc2876480da32/lib/ciesta/class_methods.rb#L10-L17
5,841
CDLUC3/resync
lib/resync/shared/base_change_list.rb
Resync.BaseChangeList.changes
def changes(of_type: nil, in_range: nil) resources.select do |r| is_of_type = of_type ? r.change == of_type : true is_in_range = in_range ? in_range.cover?(r.modified_time) : true is_of_type && is_in_range end end
ruby
def changes(of_type: nil, in_range: nil) resources.select do |r| is_of_type = of_type ? r.change == of_type : true is_in_range = in_range ? in_range.cover?(r.modified_time) : true is_of_type && is_in_range end end
[ "def", "changes", "(", "of_type", ":", "nil", ",", "in_range", ":", "nil", ")", "resources", ".", "select", "do", "|", "r", "|", "is_of_type", "=", "of_type", "?", "r", ".", "change", "==", "of_type", ":", "true", "is_in_range", "=", "in_range", "?", "in_range", ".", "cover?", "(", "r", ".", "modified_time", ")", ":", "true", "is_of_type", "&&", "is_in_range", "end", "end" ]
Filters the list of changes by change type, modification time, or both. @param of_type [Types::Change] the change type @param in_range [Range<Time>] the range of modification times @return [Array<Resource>] the matching changes, or all changes if neither +of_type+ nor +in_range+ is specified.
[ "Filters", "the", "list", "of", "changes", "by", "change", "type", "modification", "time", "or", "both", "." ]
f59a1f77f3c378180ee9ebcc42b325372f1e7a31
https://github.com/CDLUC3/resync/blob/f59a1f77f3c378180ee9ebcc42b325372f1e7a31/lib/resync/shared/base_change_list.rb#L11-L17
5,842
ohler55/opee
lib/opee/actor.rb
Opee.Actor.on_idle
def on_idle(op, *args) @idle_mutex.synchronize { @idle.insert(0, Act.new(op, args)) } @loop.wakeup() if RUNNING == @state end
ruby
def on_idle(op, *args) @idle_mutex.synchronize { @idle.insert(0, Act.new(op, args)) } @loop.wakeup() if RUNNING == @state end
[ "def", "on_idle", "(", "op", ",", "*", "args", ")", "@idle_mutex", ".", "synchronize", "{", "@idle", ".", "insert", "(", "0", ",", "Act", ".", "new", "(", "op", ",", "args", ")", ")", "}", "@loop", ".", "wakeup", "(", ")", "if", "RUNNING", "==", "@state", "end" ]
Queues an operation and arguments to be called when the Actor is has no other requests to process. @param [Symbol] op method to queue for the Actor @param [Array] args arguments to the op method
[ "Queues", "an", "operation", "and", "arguments", "to", "be", "called", "when", "the", "Actor", "is", "has", "no", "other", "requests", "to", "process", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/actor.rb#L153-L158
5,843
ohler55/opee
lib/opee/actor.rb
Opee.Actor.method_missing
def method_missing(m, *args, &blk) raise NoMethodError.new("undefined method '#{m}' for #{self.class}", m, args) unless respond_to?(m, true) ask(m, *args) end
ruby
def method_missing(m, *args, &blk) raise NoMethodError.new("undefined method '#{m}' for #{self.class}", m, args) unless respond_to?(m, true) ask(m, *args) end
[ "def", "method_missing", "(", "m", ",", "*", "args", ",", "&", "blk", ")", "raise", "NoMethodError", ".", "new", "(", "\"undefined method '#{m}' for #{self.class}\"", ",", "m", ",", "args", ")", "unless", "respond_to?", "(", "m", ",", "true", ")", "ask", "(", "m", ",", "args", ")", "end" ]
When an attempt is made to call a private method of the Actor it is places on the processing queue. Other methods cause a NoMethodError to be raised as it normally would. @param [Symbol] m method to queue for the Actor @param [Array] args arguments to the op method @param [Proc] blk ignored
[ "When", "an", "attempt", "is", "made", "to", "call", "a", "private", "method", "of", "the", "Actor", "it", "is", "places", "on", "the", "processing", "queue", ".", "Other", "methods", "cause", "a", "NoMethodError", "to", "be", "raised", "as", "it", "normally", "would", "." ]
09d947affeddc0501f61b928050fbde1838ed57a
https://github.com/ohler55/opee/blob/09d947affeddc0501f61b928050fbde1838ed57a/lib/opee/actor.rb#L177-L180
5,844
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.findings=
def findings=(findings) raise TypeException unless findings.is_a?(Array) findings.each { |item| raise TypeException unless item.is_a?(StatModule::Finding) raise DuplicateElementException if @findings.include?(item) @findings.push(item) } end
ruby
def findings=(findings) raise TypeException unless findings.is_a?(Array) findings.each { |item| raise TypeException unless item.is_a?(StatModule::Finding) raise DuplicateElementException if @findings.include?(item) @findings.push(item) } end
[ "def", "findings", "=", "(", "findings", ")", "raise", "TypeException", "unless", "findings", ".", "is_a?", "(", "Array", ")", "findings", ".", "each", "{", "|", "item", "|", "raise", "TypeException", "unless", "item", ".", "is_a?", "(", "StatModule", "::", "Finding", ")", "raise", "DuplicateElementException", "if", "@findings", ".", "include?", "(", "item", ")", "@findings", ".", "push", "(", "item", ")", "}", "end" ]
Initialize new Stat object Params: +process+:: StatModule::Process, required +hash+:: Hash, can be null Set array of findings Params: +findings+:: Array of StatModule::Finding
[ "Initialize", "new", "Stat", "object" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L43-L50
5,845
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.print_header
def print_header @finding_print_index = 0 hash = {} hash['statVersion'] = @statVersion hash['process'] = @process hash['findings'] = [] result = hash.to_json result = result[0..result.length - 3] puts(result) puts $stdout.flush end
ruby
def print_header @finding_print_index = 0 hash = {} hash['statVersion'] = @statVersion hash['process'] = @process hash['findings'] = [] result = hash.to_json result = result[0..result.length - 3] puts(result) puts $stdout.flush end
[ "def", "print_header", "@finding_print_index", "=", "0", "hash", "=", "{", "}", "hash", "[", "'statVersion'", "]", "=", "@statVersion", "hash", "[", "'process'", "]", "=", "@process", "hash", "[", "'findings'", "]", "=", "[", "]", "result", "=", "hash", ".", "to_json", "result", "=", "result", "[", "0", "..", "result", ".", "length", "-", "3", "]", "puts", "(", "result", ")", "puts", "$stdout", ".", "flush", "end" ]
Prints header of STAT object in json format Header contains statVersion, process and optional array of findings
[ "Prints", "header", "of", "STAT", "object", "in", "json", "format", "Header", "contains", "statVersion", "process", "and", "optional", "array", "of", "findings" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L77-L88
5,846
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.print_finding
def print_finding if @finding_print_index < @findings.length result = @findings[@finding_print_index].to_json result += ',' unless @finding_print_index >= @findings.length - 1 puts result puts $stdout.flush @finding_print_index += 1 else raise IndexOutOfBoundException end end
ruby
def print_finding if @finding_print_index < @findings.length result = @findings[@finding_print_index].to_json result += ',' unless @finding_print_index >= @findings.length - 1 puts result puts $stdout.flush @finding_print_index += 1 else raise IndexOutOfBoundException end end
[ "def", "print_finding", "if", "@finding_print_index", "<", "@findings", ".", "length", "result", "=", "@findings", "[", "@finding_print_index", "]", ".", "to_json", "result", "+=", "','", "unless", "@finding_print_index", ">=", "@findings", ".", "length", "-", "1", "puts", "result", "puts", "$stdout", ".", "flush", "@finding_print_index", "+=", "1", "else", "raise", "IndexOutOfBoundException", "end", "end" ]
Prints one finding in json format.
[ "Prints", "one", "finding", "in", "json", "format", "." ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L92-L103
5,847
fulldecent/structured-acceptance-test
implementations/ruby/lib/stat.rb
StatModule.Stat.summary_print
def summary_print(formatted = false) errors = 0 warnings = 0 findings.each { |finding| if finding.failure errors += 1 else warnings += 1 end } if errors == 0 && warnings == 0 result = "#{FORMATTING_CHECKMARK} PASSED with no warning".colorize(:green) elsif errors == 0 result = "#{FORMATTING_WARNING} PASSED with #{warnings} warning".colorize(:yellow) elsif warnings == 0 result = "#{FORMATTING_BALL} FAILED with #{errors} error".colorize(:red) else result = "#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning".colorize(:red) end if formatted result else result[result.index(' ') + 1..result.length] end end
ruby
def summary_print(formatted = false) errors = 0 warnings = 0 findings.each { |finding| if finding.failure errors += 1 else warnings += 1 end } if errors == 0 && warnings == 0 result = "#{FORMATTING_CHECKMARK} PASSED with no warning".colorize(:green) elsif errors == 0 result = "#{FORMATTING_WARNING} PASSED with #{warnings} warning".colorize(:yellow) elsif warnings == 0 result = "#{FORMATTING_BALL} FAILED with #{errors} error".colorize(:red) else result = "#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning".colorize(:red) end if formatted result else result[result.index(' ') + 1..result.length] end end
[ "def", "summary_print", "(", "formatted", "=", "false", ")", "errors", "=", "0", "warnings", "=", "0", "findings", ".", "each", "{", "|", "finding", "|", "if", "finding", ".", "failure", "errors", "+=", "1", "else", "warnings", "+=", "1", "end", "}", "if", "errors", "==", "0", "&&", "warnings", "==", "0", "result", "=", "\"#{FORMATTING_CHECKMARK} PASSED with no warning\"", ".", "colorize", "(", ":green", ")", "elsif", "errors", "==", "0", "result", "=", "\"#{FORMATTING_WARNING} PASSED with #{warnings} warning\"", ".", "colorize", "(", ":yellow", ")", "elsif", "warnings", "==", "0", "result", "=", "\"#{FORMATTING_BALL} FAILED with #{errors} error\"", ".", "colorize", "(", ":red", ")", "else", "result", "=", "\"#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning\"", ".", "colorize", "(", ":red", ")", "end", "if", "formatted", "result", "else", "result", "[", "result", ".", "index", "(", "' '", ")", "+", "1", "..", "result", ".", "length", "]", "end", "end" ]
Get statistic information about findings Params: +formatted+:: indicate weather print boring or pretty colorful statistic
[ "Get", "statistic", "information", "about", "findings" ]
9766f4863a8bcfdf6ac50a7aa36cce0314481118
https://github.com/fulldecent/structured-acceptance-test/blob/9766f4863a8bcfdf6ac50a7aa36cce0314481118/implementations/ruby/lib/stat.rb#L126-L150
5,848
dennmart/wanikani-gem
lib/wanikani/user.rb
Wanikani.User.gravatar_url
def gravatar_url(options = {}) raise ArgumentError, "The size parameter must be an integer" if options[:size] && !options[:size].is_a?(Integer) response = api_response("user-information") hash = response["user_information"]["gravatar"] return nil if hash.nil? return build_gravatar_url(hash, options) end
ruby
def gravatar_url(options = {}) raise ArgumentError, "The size parameter must be an integer" if options[:size] && !options[:size].is_a?(Integer) response = api_response("user-information") hash = response["user_information"]["gravatar"] return nil if hash.nil? return build_gravatar_url(hash, options) end
[ "def", "gravatar_url", "(", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "\"The size parameter must be an integer\"", "if", "options", "[", ":size", "]", "&&", "!", "options", "[", ":size", "]", ".", "is_a?", "(", "Integer", ")", "response", "=", "api_response", "(", "\"user-information\"", ")", "hash", "=", "response", "[", "\"user_information\"", "]", "[", "\"gravatar\"", "]", "return", "nil", "if", "hash", ".", "nil?", "return", "build_gravatar_url", "(", "hash", ",", "options", ")", "end" ]
Returns the Gravatar image URL using the Gravatar hash from the user's information. @param options [Hash] optional settings for the gravatar URL. @return [String, nil] the Gravatar URL, with the optional size parameter, nil if the user information contains no Gravatar hash.
[ "Returns", "the", "Gravatar", "image", "URL", "using", "the", "Gravatar", "hash", "from", "the", "user", "s", "information", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/user.rb#L27-L34
5,849
addagger/html_slicer
lib/html_slicer/helpers/action_view_extension.rb
HtmlSlicer.ActionViewExtension.slice
def slice(object, options = {}, &block) slicer = HtmlSlicer::Helpers::Slicer.new self, object.options.reverse_merge(options).reverse_merge(:current_slice => object.current_slice, :slice_number => object.slice_number, :remote => false) slicer.to_s end
ruby
def slice(object, options = {}, &block) slicer = HtmlSlicer::Helpers::Slicer.new self, object.options.reverse_merge(options).reverse_merge(:current_slice => object.current_slice, :slice_number => object.slice_number, :remote => false) slicer.to_s end
[ "def", "slice", "(", "object", ",", "options", "=", "{", "}", ",", "&", "block", ")", "slicer", "=", "HtmlSlicer", "::", "Helpers", "::", "Slicer", ".", "new", "self", ",", "object", ".", "options", ".", "reverse_merge", "(", "options", ")", ".", "reverse_merge", "(", ":current_slice", "=>", "object", ".", "current_slice", ",", ":slice_number", "=>", "object", ".", "slice_number", ",", ":remote", "=>", "false", ")", "slicer", ".", "to_s", "end" ]
A helper that renders the pagination links. <%= slicer @article.paged %> ==== Options * <tt>:window</tt> - The "inner window" size (4 by default). * <tt>:outer_window</tt> - The "outer window" size (0 by default). * <tt>:left</tt> - The "left outer window" size (0 by default). * <tt>:right</tt> - The "right outer window" size (0 by default). * <tt>:params</tt> - url_for parameters for the links (:controller, :action, etc.) * <tt>:param_name</tt> - parameter name for slice number in the links. Accepts +symbol+, +string+, +array+. * <tt>:remote</tt> - Ajax? (false by default) * <tt>:ANY_OTHER_VALUES</tt> - Any other hash key & values would be directly passed into each tag as :locals value.
[ "A", "helper", "that", "renders", "the", "pagination", "links", "." ]
bbe6ab55a0d0335621079c304af534959b518d8b
https://github.com/addagger/html_slicer/blob/bbe6ab55a0d0335621079c304af534959b518d8b/lib/html_slicer/helpers/action_view_extension.rb#L33-L36
5,850
holyshared/yaml-translator
lib/yaml-translator/locale.rb
YamlTranslator.Locale.save
def save(dir = Dir.pwd, options = {}) prefix = options[:prefix] if options.key?(:prefix) write_file(File.join(dir, "#{prefix}#{lang}.yml"), options) end
ruby
def save(dir = Dir.pwd, options = {}) prefix = options[:prefix] if options.key?(:prefix) write_file(File.join(dir, "#{prefix}#{lang}.yml"), options) end
[ "def", "save", "(", "dir", "=", "Dir", ".", "pwd", ",", "options", "=", "{", "}", ")", "prefix", "=", "options", "[", ":prefix", "]", "if", "options", ".", "key?", "(", ":prefix", ")", "write_file", "(", "File", ".", "join", "(", "dir", ",", "\"#{prefix}#{lang}.yml\"", ")", ",", "options", ")", "end" ]
Save the file @param dir [String] Directory path to save the file @param options [Hash] Options for saving @return int
[ "Save", "the", "file" ]
f6e4497e1695a353534828b005638a6d5c625c07
https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L73-L76
5,851
holyshared/yaml-translator
lib/yaml-translator/locale.rb
YamlTranslator.Locale.compact_of
def compact_of(values = {}, path = KeyPath.new) result = {} values.each_with_index do |(i, v)| path.move_to(i) if v.is_a?(Hash) result.merge!(compact_of(v, path)) else result[path.to_s] = v end path.leave end result end
ruby
def compact_of(values = {}, path = KeyPath.new) result = {} values.each_with_index do |(i, v)| path.move_to(i) if v.is_a?(Hash) result.merge!(compact_of(v, path)) else result[path.to_s] = v end path.leave end result end
[ "def", "compact_of", "(", "values", "=", "{", "}", ",", "path", "=", "KeyPath", ".", "new", ")", "result", "=", "{", "}", "values", ".", "each_with_index", "do", "|", "(", "i", ",", "v", ")", "|", "path", ".", "move_to", "(", "i", ")", "if", "v", ".", "is_a?", "(", "Hash", ")", "result", ".", "merge!", "(", "compact_of", "(", "v", ",", "path", ")", ")", "else", "result", "[", "path", ".", "to_s", "]", "=", "v", "end", "path", ".", "leave", "end", "result", "end" ]
Covert to a flatten hash
[ "Covert", "to", "a", "flatten", "hash" ]
f6e4497e1695a353534828b005638a6d5c625c07
https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L98-L110
5,852
holyshared/yaml-translator
lib/yaml-translator/locale.rb
YamlTranslator.Locale.tree_of
def tree_of(values) result = {} current = result values.each do |k, v| keys = k.to_s.split('.') last_key = keys.pop keys.each do |ks| current = if current.key?(ks) current[ks] else current[ks] = {} current[ks] end end current[last_key] = v current = result end result end
ruby
def tree_of(values) result = {} current = result values.each do |k, v| keys = k.to_s.split('.') last_key = keys.pop keys.each do |ks| current = if current.key?(ks) current[ks] else current[ks] = {} current[ks] end end current[last_key] = v current = result end result end
[ "def", "tree_of", "(", "values", ")", "result", "=", "{", "}", "current", "=", "result", "values", ".", "each", "do", "|", "k", ",", "v", "|", "keys", "=", "k", ".", "to_s", ".", "split", "(", "'.'", ")", "last_key", "=", "keys", ".", "pop", "keys", ".", "each", "do", "|", "ks", "|", "current", "=", "if", "current", ".", "key?", "(", "ks", ")", "current", "[", "ks", "]", "else", "current", "[", "ks", "]", "=", "{", "}", "current", "[", "ks", "]", "end", "end", "current", "[", "last_key", "]", "=", "v", "current", "=", "result", "end", "result", "end" ]
Returning the flattened structure to the tree structure @param [Hash] values flatten Hash @return [Hash] translated hash
[ "Returning", "the", "flattened", "structure", "to", "the", "tree", "structure" ]
f6e4497e1695a353534828b005638a6d5c625c07
https://github.com/holyshared/yaml-translator/blob/f6e4497e1695a353534828b005638a6d5c625c07/lib/yaml-translator/locale.rb#L116-L134
5,853
bterkuile/cmtool
app/helpers/cmtool/application_helper.rb
Cmtool.ApplicationHelper.collapsible_content
def collapsible_content(options = {}, &blk) options = {title: options} if options.is_a?(String) # Single argument is title content = capture(&blk) if blk.present? content ||= options[:content] options[:collapsed] = true unless options.has_key?(:collapsed) classes = Array.wrap(options[:class]) | ["collapsible-container", options[:collapsed] ? 'collapsed' : nil] title_tag = content_tag(:div, "<span></span>#{options[:title]}".html_safe, class: 'collapsible-title') content_tag(:div, title_tag + content_tag(:div, content, class: 'collapsible-content'), class: classes) end
ruby
def collapsible_content(options = {}, &blk) options = {title: options} if options.is_a?(String) # Single argument is title content = capture(&blk) if blk.present? content ||= options[:content] options[:collapsed] = true unless options.has_key?(:collapsed) classes = Array.wrap(options[:class]) | ["collapsible-container", options[:collapsed] ? 'collapsed' : nil] title_tag = content_tag(:div, "<span></span>#{options[:title]}".html_safe, class: 'collapsible-title') content_tag(:div, title_tag + content_tag(:div, content, class: 'collapsible-content'), class: classes) end
[ "def", "collapsible_content", "(", "options", "=", "{", "}", ",", "&", "blk", ")", "options", "=", "{", "title", ":", "options", "}", "if", "options", ".", "is_a?", "(", "String", ")", "# Single argument is title", "content", "=", "capture", "(", "blk", ")", "if", "blk", ".", "present?", "content", "||=", "options", "[", ":content", "]", "options", "[", ":collapsed", "]", "=", "true", "unless", "options", ".", "has_key?", "(", ":collapsed", ")", "classes", "=", "Array", ".", "wrap", "(", "options", "[", ":class", "]", ")", "|", "[", "\"collapsible-container\"", ",", "options", "[", ":collapsed", "]", "?", "'collapsed'", ":", "nil", "]", "title_tag", "=", "content_tag", "(", ":div", ",", "\"<span></span>#{options[:title]}\"", ".", "html_safe", ",", "class", ":", "'collapsible-title'", ")", "content_tag", "(", ":div", ",", "title_tag", "+", "content_tag", "(", ":div", ",", "content", ",", "class", ":", "'collapsible-content'", ")", ",", "class", ":", "classes", ")", "end" ]
This is a wrapper to create collapsible content.
[ "This", "is", "a", "wrapper", "to", "create", "collapsible", "content", "." ]
3caf808e223233f19b29acde35429be75acd44e2
https://github.com/bterkuile/cmtool/blob/3caf808e223233f19b29acde35429be75acd44e2/app/helpers/cmtool/application_helper.rb#L107-L115
5,854
praxis/praxis-blueprints
lib/praxis-blueprints/view.rb
Praxis.View.attribute
def attribute(name, **opts, &block) raise AttributorException, "Attribute names must be symbols, got: #{name.inspect}" unless name.is_a? ::Symbol attribute = schema.attributes.fetch(name) do raise "Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype" end if block_given? type = attribute.type @contents[name] = if type < Attributor::Collection CollectionView.new(name, type.member_attribute.type, &block) else View.new(name, attribute, &block) end else type = attribute.type if type < Attributor::Collection is_collection = true type = type.member_attribute.type end if type < Praxis::Blueprint view_name = opts[:view] || :default view = type.views.fetch(view_name) do raise "view with name '#{view_name.inspect}' is not defined in #{type}" end @contents[name] = if is_collection Praxis::CollectionView.new(view_name, type, view) else view end else @contents[name] = attribute # , opts] end end end
ruby
def attribute(name, **opts, &block) raise AttributorException, "Attribute names must be symbols, got: #{name.inspect}" unless name.is_a? ::Symbol attribute = schema.attributes.fetch(name) do raise "Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype" end if block_given? type = attribute.type @contents[name] = if type < Attributor::Collection CollectionView.new(name, type.member_attribute.type, &block) else View.new(name, attribute, &block) end else type = attribute.type if type < Attributor::Collection is_collection = true type = type.member_attribute.type end if type < Praxis::Blueprint view_name = opts[:view] || :default view = type.views.fetch(view_name) do raise "view with name '#{view_name.inspect}' is not defined in #{type}" end @contents[name] = if is_collection Praxis::CollectionView.new(view_name, type, view) else view end else @contents[name] = attribute # , opts] end end end
[ "def", "attribute", "(", "name", ",", "**", "opts", ",", "&", "block", ")", "raise", "AttributorException", ",", "\"Attribute names must be symbols, got: #{name.inspect}\"", "unless", "name", ".", "is_a?", "::", "Symbol", "attribute", "=", "schema", ".", "attributes", ".", "fetch", "(", "name", ")", "do", "raise", "\"Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype\"", "end", "if", "block_given?", "type", "=", "attribute", ".", "type", "@contents", "[", "name", "]", "=", "if", "type", "<", "Attributor", "::", "Collection", "CollectionView", ".", "new", "(", "name", ",", "type", ".", "member_attribute", ".", "type", ",", "block", ")", "else", "View", ".", "new", "(", "name", ",", "attribute", ",", "block", ")", "end", "else", "type", "=", "attribute", ".", "type", "if", "type", "<", "Attributor", "::", "Collection", "is_collection", "=", "true", "type", "=", "type", ".", "member_attribute", ".", "type", "end", "if", "type", "<", "Praxis", "::", "Blueprint", "view_name", "=", "opts", "[", ":view", "]", "||", ":default", "view", "=", "type", ".", "views", ".", "fetch", "(", "view_name", ")", "do", "raise", "\"view with name '#{view_name.inspect}' is not defined in #{type}\"", "end", "@contents", "[", "name", "]", "=", "if", "is_collection", "Praxis", "::", "CollectionView", ".", "new", "(", "view_name", ",", "type", ",", "view", ")", "else", "view", "end", "else", "@contents", "[", "name", "]", "=", "attribute", "# , opts]", "end", "end", "end" ]
Why did we need this again?
[ "Why", "did", "we", "need", "this", "again?" ]
57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c
https://github.com/praxis/praxis-blueprints/blob/57b9f9d81d313a7c7bf3e9eebb4b8153c3b48f1c/lib/praxis-blueprints/view.rb#L40-L75
5,855
robertwahler/repo_manager
lib/repo_manager/assets/asset_configuration.rb
RepoManager.AssetConfiguration.save
def save(attrs=nil) raise "a Hash of attributes to save must be specified" unless attrs && attrs.is_a?(Hash) raise "folder must be set prior to saving attributes" unless folder # merge attributes to asset that contains parent attributes @asset.attributes.merge!(attrs) # load contents of the user folder and merge in attributes passed to save # so that we don't save parent attributes contents = {} if File.exists?(folder) contents = load_contents(folder) raise "expected contents to be a hash" unless contents.is_a?(Hash) end contents = contents.merge!(attrs) write_contents(folder, contents) end
ruby
def save(attrs=nil) raise "a Hash of attributes to save must be specified" unless attrs && attrs.is_a?(Hash) raise "folder must be set prior to saving attributes" unless folder # merge attributes to asset that contains parent attributes @asset.attributes.merge!(attrs) # load contents of the user folder and merge in attributes passed to save # so that we don't save parent attributes contents = {} if File.exists?(folder) contents = load_contents(folder) raise "expected contents to be a hash" unless contents.is_a?(Hash) end contents = contents.merge!(attrs) write_contents(folder, contents) end
[ "def", "save", "(", "attrs", "=", "nil", ")", "raise", "\"a Hash of attributes to save must be specified\"", "unless", "attrs", "&&", "attrs", ".", "is_a?", "(", "Hash", ")", "raise", "\"folder must be set prior to saving attributes\"", "unless", "folder", "# merge attributes to asset that contains parent attributes", "@asset", ".", "attributes", ".", "merge!", "(", "attrs", ")", "# load contents of the user folder and merge in attributes passed to save", "# so that we don't save parent attributes", "contents", "=", "{", "}", "if", "File", ".", "exists?", "(", "folder", ")", "contents", "=", "load_contents", "(", "folder", ")", "raise", "\"expected contents to be a hash\"", "unless", "contents", ".", "is_a?", "(", "Hash", ")", "end", "contents", "=", "contents", ".", "merge!", "(", "attrs", ")", "write_contents", "(", "folder", ",", "contents", ")", "end" ]
Save specific attributes to an asset configuration file. Only the param 'attrs' and the current contents of the config file are saved. Parent asset configurations are not saved.
[ "Save", "specific", "attributes", "to", "an", "asset", "configuration", "file", ".", "Only", "the", "param", "attrs", "and", "the", "current", "contents", "of", "the", "config", "file", "are", "saved", ".", "Parent", "asset", "configurations", "are", "not", "saved", "." ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L45-L62
5,856
robertwahler/repo_manager
lib/repo_manager/assets/asset_configuration.rb
RepoManager.AssetConfiguration.load
def load(ds=nil) @folder ||= ds contents = load_contents(folder) # if a global parent folder is defined, load it first parent = contents.delete(:parent) || parent if parent parent_folder = File.join(parent) unless Pathname.new(parent_folder).absolute? base_folder = File.dirname(folder) parent_folder = File.join(base_folder, parent_folder) end logger.debug "AssetConfiguration loading parent: #{parent_folder}" parent_configuration = RepoManager::AssetConfiguration.new(asset) begin parent_configuration.load(parent_folder) rescue Exception => e logger.warn "AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'" end end # Load all attributes as hash 'attributes' so that merging # and adding new attributes doesn't require code changes. Note # that the 'parent' setting is not merged to attributes @asset.attributes.merge!(contents) @asset.create_accessors(@asset.attributes[:user_attributes]) @asset end
ruby
def load(ds=nil) @folder ||= ds contents = load_contents(folder) # if a global parent folder is defined, load it first parent = contents.delete(:parent) || parent if parent parent_folder = File.join(parent) unless Pathname.new(parent_folder).absolute? base_folder = File.dirname(folder) parent_folder = File.join(base_folder, parent_folder) end logger.debug "AssetConfiguration loading parent: #{parent_folder}" parent_configuration = RepoManager::AssetConfiguration.new(asset) begin parent_configuration.load(parent_folder) rescue Exception => e logger.warn "AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'" end end # Load all attributes as hash 'attributes' so that merging # and adding new attributes doesn't require code changes. Note # that the 'parent' setting is not merged to attributes @asset.attributes.merge!(contents) @asset.create_accessors(@asset.attributes[:user_attributes]) @asset end
[ "def", "load", "(", "ds", "=", "nil", ")", "@folder", "||=", "ds", "contents", "=", "load_contents", "(", "folder", ")", "# if a global parent folder is defined, load it first", "parent", "=", "contents", ".", "delete", "(", ":parent", ")", "||", "parent", "if", "parent", "parent_folder", "=", "File", ".", "join", "(", "parent", ")", "unless", "Pathname", ".", "new", "(", "parent_folder", ")", ".", "absolute?", "base_folder", "=", "File", ".", "dirname", "(", "folder", ")", "parent_folder", "=", "File", ".", "join", "(", "base_folder", ",", "parent_folder", ")", "end", "logger", ".", "debug", "\"AssetConfiguration loading parent: #{parent_folder}\"", "parent_configuration", "=", "RepoManager", "::", "AssetConfiguration", ".", "new", "(", "asset", ")", "begin", "parent_configuration", ".", "load", "(", "parent_folder", ")", "rescue", "Exception", "=>", "e", "logger", ".", "warn", "\"AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'\"", "end", "end", "# Load all attributes as hash 'attributes' so that merging", "# and adding new attributes doesn't require code changes. Note", "# that the 'parent' setting is not merged to attributes", "@asset", ".", "attributes", ".", "merge!", "(", "contents", ")", "@asset", ".", "create_accessors", "(", "@asset", ".", "attributes", "[", ":user_attributes", "]", ")", "@asset", "end" ]
load an asset from a configuration folder
[ "load", "an", "asset", "from", "a", "configuration", "folder" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L65-L95
5,857
robertwahler/repo_manager
lib/repo_manager/assets/asset_configuration.rb
RepoManager.AssetConfiguration.load_contents
def load_contents(asset_folder) file = File.join(asset_folder, 'asset.conf') if File.exists?(file) contents = YAML.load(ERB.new(File.open(file, "rb").read).result(@asset.get_binding)) if contents && contents.is_a?(Hash) contents.recursively_symbolize_keys! else {} end else {} end end
ruby
def load_contents(asset_folder) file = File.join(asset_folder, 'asset.conf') if File.exists?(file) contents = YAML.load(ERB.new(File.open(file, "rb").read).result(@asset.get_binding)) if contents && contents.is_a?(Hash) contents.recursively_symbolize_keys! else {} end else {} end end
[ "def", "load_contents", "(", "asset_folder", ")", "file", "=", "File", ".", "join", "(", "asset_folder", ",", "'asset.conf'", ")", "if", "File", ".", "exists?", "(", "file", ")", "contents", "=", "YAML", ".", "load", "(", "ERB", ".", "new", "(", "File", ".", "open", "(", "file", ",", "\"rb\"", ")", ".", "read", ")", ".", "result", "(", "@asset", ".", "get_binding", ")", ")", "if", "contents", "&&", "contents", ".", "is_a?", "(", "Hash", ")", "contents", ".", "recursively_symbolize_keys!", "else", "{", "}", "end", "else", "{", "}", "end", "end" ]
load the raw contents from an asset_folder, ignore parents @return [Hash] of the raw text contents
[ "load", "the", "raw", "contents", "from", "an", "asset_folder", "ignore", "parents" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L109-L121
5,858
robertwahler/repo_manager
lib/repo_manager/assets/asset_configuration.rb
RepoManager.AssetConfiguration.write_contents
def write_contents(asset_folder, contents) contents.recursively_stringify_keys! FileUtils.mkdir(asset_folder) unless File.exists?(asset_folder) filename = File.join(asset_folder, 'asset.conf') #TODO, use "wb" and write CRLF on Windows File.open(filename, "w") do |f| f.write(contents.to_conf) end end
ruby
def write_contents(asset_folder, contents) contents.recursively_stringify_keys! FileUtils.mkdir(asset_folder) unless File.exists?(asset_folder) filename = File.join(asset_folder, 'asset.conf') #TODO, use "wb" and write CRLF on Windows File.open(filename, "w") do |f| f.write(contents.to_conf) end end
[ "def", "write_contents", "(", "asset_folder", ",", "contents", ")", "contents", ".", "recursively_stringify_keys!", "FileUtils", ".", "mkdir", "(", "asset_folder", ")", "unless", "File", ".", "exists?", "(", "asset_folder", ")", "filename", "=", "File", ".", "join", "(", "asset_folder", ",", "'asset.conf'", ")", "#TODO, use \"wb\" and write CRLF on Windows", "File", ".", "open", "(", "filename", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "contents", ".", "to_conf", ")", "end", "end" ]
write raw contents to an asset_folder
[ "write", "raw", "contents", "to", "an", "asset_folder" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/assets/asset_configuration.rb#L124-L134
5,859
SebastianSzturo/inaho
lib/inaho/entry.rb
Inaho.Entry.to_xml
def to_xml return nil if title.nil? || body.nil? xml = "" xml << "<d:entry id=\"#{self.id}\" d:title=\"#{self.title}\">\n" @index.each do |i| xml << "\t<d:index d:value=\"#{i}\" d:title=\"#{title}\" " xml << "d:yomi=\"#{yomi}\"" if !self.yomi.nil? xml << "/>\n" end xml << "\t<div>\n" xml << "\t\t#{@body}\n" xml << "\t</div>\n" xml << "</d:entry>\n" return xml end
ruby
def to_xml return nil if title.nil? || body.nil? xml = "" xml << "<d:entry id=\"#{self.id}\" d:title=\"#{self.title}\">\n" @index.each do |i| xml << "\t<d:index d:value=\"#{i}\" d:title=\"#{title}\" " xml << "d:yomi=\"#{yomi}\"" if !self.yomi.nil? xml << "/>\n" end xml << "\t<div>\n" xml << "\t\t#{@body}\n" xml << "\t</div>\n" xml << "</d:entry>\n" return xml end
[ "def", "to_xml", "return", "nil", "if", "title", ".", "nil?", "||", "body", ".", "nil?", "xml", "=", "\"\"", "xml", "<<", "\"<d:entry id=\\\"#{self.id}\\\" d:title=\\\"#{self.title}\\\">\\n\"", "@index", ".", "each", "do", "|", "i", "|", "xml", "<<", "\"\\t<d:index d:value=\\\"#{i}\\\" d:title=\\\"#{title}\\\" \"", "xml", "<<", "\"d:yomi=\\\"#{yomi}\\\"\"", "if", "!", "self", ".", "yomi", ".", "nil?", "xml", "<<", "\"/>\\n\"", "end", "xml", "<<", "\"\\t<div>\\n\"", "xml", "<<", "\"\\t\\t#{@body}\\n\"", "xml", "<<", "\"\\t</div>\\n\"", "xml", "<<", "\"</d:entry>\\n\"", "return", "xml", "end" ]
Generates xml for the Entry object. Returns String.
[ "Generates", "xml", "for", "the", "Entry", "object", "." ]
e3664bc59aa90197258d715a9032c18f82b84ebd
https://github.com/SebastianSzturo/inaho/blob/e3664bc59aa90197258d715a9032c18f82b84ebd/lib/inaho/entry.rb#L32-L48
5,860
hendricius/instagram_public_api
lib/instagram_public_api/client.rb
InstagramPublicApi.Client.location_media
def location_media(location_id, request_parameters: {limit: 1000}, limit: 10) location = extract_location_media(location_id, request_parameters: request_parameters) # check if we should get more data paging_info = location.paging_info # poll more data while location.total_media_count < limit && paging_info[:has_next_page] do request_opts = {}.merge(request_parameters) if paging_info && paging_info[:end_cursor] request_opts[:max_id] = paging_info[:end_cursor] end next_page_location = extract_location_media(location_id, request_parameters: request_opts) location.add_media(next_page_location.media) paging_info = next_page_location.paging_info location end location end
ruby
def location_media(location_id, request_parameters: {limit: 1000}, limit: 10) location = extract_location_media(location_id, request_parameters: request_parameters) # check if we should get more data paging_info = location.paging_info # poll more data while location.total_media_count < limit && paging_info[:has_next_page] do request_opts = {}.merge(request_parameters) if paging_info && paging_info[:end_cursor] request_opts[:max_id] = paging_info[:end_cursor] end next_page_location = extract_location_media(location_id, request_parameters: request_opts) location.add_media(next_page_location.media) paging_info = next_page_location.paging_info location end location end
[ "def", "location_media", "(", "location_id", ",", "request_parameters", ":", "{", "limit", ":", "1000", "}", ",", "limit", ":", "10", ")", "location", "=", "extract_location_media", "(", "location_id", ",", "request_parameters", ":", "request_parameters", ")", "# check if we should get more data", "paging_info", "=", "location", ".", "paging_info", "# poll more data", "while", "location", ".", "total_media_count", "<", "limit", "&&", "paging_info", "[", ":has_next_page", "]", "do", "request_opts", "=", "{", "}", ".", "merge", "(", "request_parameters", ")", "if", "paging_info", "&&", "paging_info", "[", ":end_cursor", "]", "request_opts", "[", ":max_id", "]", "=", "paging_info", "[", ":end_cursor", "]", "end", "next_page_location", "=", "extract_location_media", "(", "location_id", ",", "request_parameters", ":", "request_opts", ")", "location", ".", "add_media", "(", "next_page_location", ".", "media", ")", "paging_info", "=", "next_page_location", ".", "paging_info", "location", "end", "location", "end" ]
returns a location with media attached for the given location id limit: the amount of media that should be fetched. request_parameters: optional parameters that will be passed to the request
[ "returns", "a", "location", "with", "media", "attached", "for", "the", "given", "location", "id" ]
ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6
https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L15-L31
5,861
hendricius/instagram_public_api
lib/instagram_public_api/client.rb
InstagramPublicApi.Client.extract_location_media
def extract_location_media(location_id, request_parameters: {}) uri = "explore/locations/#{location_id}/" data = request(uri: uri, parameters: request_parameters) body = data.body[:location] location = Entities::Location.new attrs = %i[name lat lng id] attrs.each do |attribute| location.send("#{attribute}=", body[attribute]) end media = {} body[:media].fetch(:nodes, []).each do |medium| media[medium[:id]] = Entities::MediumNode.new(medium) end location.media = media.values location.top_posts = body[:top_posts].fetch(:nodes, []).map {|d| Entities::MediumNode.new(d)} location.paging_info = body[:media].fetch(:page_info, {}) location end
ruby
def extract_location_media(location_id, request_parameters: {}) uri = "explore/locations/#{location_id}/" data = request(uri: uri, parameters: request_parameters) body = data.body[:location] location = Entities::Location.new attrs = %i[name lat lng id] attrs.each do |attribute| location.send("#{attribute}=", body[attribute]) end media = {} body[:media].fetch(:nodes, []).each do |medium| media[medium[:id]] = Entities::MediumNode.new(medium) end location.media = media.values location.top_posts = body[:top_posts].fetch(:nodes, []).map {|d| Entities::MediumNode.new(d)} location.paging_info = body[:media].fetch(:page_info, {}) location end
[ "def", "extract_location_media", "(", "location_id", ",", "request_parameters", ":", "{", "}", ")", "uri", "=", "\"explore/locations/#{location_id}/\"", "data", "=", "request", "(", "uri", ":", "uri", ",", "parameters", ":", "request_parameters", ")", "body", "=", "data", ".", "body", "[", ":location", "]", "location", "=", "Entities", "::", "Location", ".", "new", "attrs", "=", "%i[", "name", "lat", "lng", "id", "]", "attrs", ".", "each", "do", "|", "attribute", "|", "location", ".", "send", "(", "\"#{attribute}=\"", ",", "body", "[", "attribute", "]", ")", "end", "media", "=", "{", "}", "body", "[", ":media", "]", ".", "fetch", "(", ":nodes", ",", "[", "]", ")", ".", "each", "do", "|", "medium", "|", "media", "[", "medium", "[", ":id", "]", "]", "=", "Entities", "::", "MediumNode", ".", "new", "(", "medium", ")", "end", "location", ".", "media", "=", "media", ".", "values", "location", ".", "top_posts", "=", "body", "[", ":top_posts", "]", ".", "fetch", "(", ":nodes", ",", "[", "]", ")", ".", "map", "{", "|", "d", "|", "Entities", "::", "MediumNode", ".", "new", "(", "d", ")", "}", "location", ".", "paging_info", "=", "body", "[", ":media", "]", ".", "fetch", "(", ":page_info", ",", "{", "}", ")", "location", "end" ]
performs the actual request to the API. returns a Location object.
[ "performs", "the", "actual", "request", "to", "the", "API", "." ]
ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6
https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L46-L63
5,862
hendricius/instagram_public_api
lib/instagram_public_api/client.rb
InstagramPublicApi.Client.request
def request(uri:, request_options: {}, parameters: {}) opts = { uri: uri, request_options: request_options, parameters: @default_parameters.merge(parameters) } parse_response(http_service.perform_request(opts)) end
ruby
def request(uri:, request_options: {}, parameters: {}) opts = { uri: uri, request_options: request_options, parameters: @default_parameters.merge(parameters) } parse_response(http_service.perform_request(opts)) end
[ "def", "request", "(", "uri", ":", ",", "request_options", ":", "{", "}", ",", "parameters", ":", "{", "}", ")", "opts", "=", "{", "uri", ":", "uri", ",", "request_options", ":", "request_options", ",", "parameters", ":", "@default_parameters", ".", "merge", "(", "parameters", ")", "}", "parse_response", "(", "http_service", ".", "perform_request", "(", "opts", ")", ")", "end" ]
perform the actual request. receives a URI as argument. Optional parameters and request parameter options can be passed. returns the raw http response
[ "perform", "the", "actual", "request", ".", "receives", "a", "URI", "as", "argument", ".", "Optional", "parameters", "and", "request", "parameter", "options", "can", "be", "passed", "." ]
ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6
https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L69-L76
5,863
hendricius/instagram_public_api
lib/instagram_public_api/client.rb
InstagramPublicApi.Client.parse_response
def parse_response(response) OpenStruct.new( raw_response: response, body: JSON.parse(response.body, symbolize_names: true) ) end
ruby
def parse_response(response) OpenStruct.new( raw_response: response, body: JSON.parse(response.body, symbolize_names: true) ) end
[ "def", "parse_response", "(", "response", ")", "OpenStruct", ".", "new", "(", "raw_response", ":", "response", ",", "body", ":", "JSON", ".", "parse", "(", "response", ".", "body", ",", "symbolize_names", ":", "true", ")", ")", "end" ]
parses the raw response by the remote. returns an object with a raw_response as method and the parsed body associated.
[ "parses", "the", "raw", "response", "by", "the", "remote", ".", "returns", "an", "object", "with", "a", "raw_response", "as", "method", "and", "the", "parsed", "body", "associated", "." ]
ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6
https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/client.rb#L87-L92
5,864
mLewisLogic/saddle
lib/saddle/options.rb
Saddle.Options.default_options
def default_options { :host => host, :port => port, :path_prefix => path_prefix, :use_ssl => use_ssl, :request_style => request_style, :num_retries => num_retries, :timeout => timeout, :extra_env => extra_env, :http_adapter => http_adapter, :stubs => stubs, :return_full_response => return_full_response, :additional_middlewares => self.additional_middlewares } end
ruby
def default_options { :host => host, :port => port, :path_prefix => path_prefix, :use_ssl => use_ssl, :request_style => request_style, :num_retries => num_retries, :timeout => timeout, :extra_env => extra_env, :http_adapter => http_adapter, :stubs => stubs, :return_full_response => return_full_response, :additional_middlewares => self.additional_middlewares } end
[ "def", "default_options", "{", ":host", "=>", "host", ",", ":port", "=>", "port", ",", ":path_prefix", "=>", "path_prefix", ",", ":use_ssl", "=>", "use_ssl", ",", ":request_style", "=>", "request_style", ",", ":num_retries", "=>", "num_retries", ",", ":timeout", "=>", "timeout", ",", ":extra_env", "=>", "extra_env", ",", ":http_adapter", "=>", "http_adapter", ",", ":stubs", "=>", "stubs", ",", ":return_full_response", "=>", "return_full_response", ",", ":additional_middlewares", "=>", "self", ".", "additional_middlewares", "}", "end" ]
Construct our default options, based upon the class methods
[ "Construct", "our", "default", "options", "based", "upon", "the", "class", "methods" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/options.rb#L8-L23
5,865
ccocchi/heimdall
lib/heimdall_apm/probe.rb
HeimdallApm.Probe.instrument
def instrument(type, name, opts = {}) txn = ::HeimdallApm::TransactionManager.current segment = ::HeimdallApm::Segment.new(type, name) txn.start_segment(segment) # TODO: maybe yield the segment here to have the block pass additional # informations yield ensure txn.stop_segment end
ruby
def instrument(type, name, opts = {}) txn = ::HeimdallApm::TransactionManager.current segment = ::HeimdallApm::Segment.new(type, name) txn.start_segment(segment) # TODO: maybe yield the segment here to have the block pass additional # informations yield ensure txn.stop_segment end
[ "def", "instrument", "(", "type", ",", "name", ",", "opts", "=", "{", "}", ")", "txn", "=", "::", "HeimdallApm", "::", "TransactionManager", ".", "current", "segment", "=", "::", "HeimdallApm", "::", "Segment", ".", "new", "(", "type", ",", "name", ")", "txn", ".", "start_segment", "(", "segment", ")", "# TODO: maybe yield the segment here to have the block pass additional", "# informations", "yield", "ensure", "txn", ".", "stop_segment", "end" ]
Insruments block passed to the method into the current transaction. @param type Segment type (i.e 'ActiveRecord' or similar) @param name Specific name for the segment
[ "Insruments", "block", "passed", "to", "the", "method", "into", "the", "current", "transaction", "." ]
138e415e9a6ba9d3aceed3dd963f297464de923b
https://github.com/ccocchi/heimdall/blob/138e415e9a6ba9d3aceed3dd963f297464de923b/lib/heimdall_apm/probe.rb#L13-L23
5,866
drnic/rubigen
lib/rubigen/lookup.rb
RubiGen.Source.names
def names(filter = nil) inject([]) do |mem, spec| case filter when :visible mem << spec.name if spec.visible? end mem end.sort end
ruby
def names(filter = nil) inject([]) do |mem, spec| case filter when :visible mem << spec.name if spec.visible? end mem end.sort end
[ "def", "names", "(", "filter", "=", "nil", ")", "inject", "(", "[", "]", ")", "do", "|", "mem", ",", "spec", "|", "case", "filter", "when", ":visible", "mem", "<<", "spec", ".", "name", "if", "spec", ".", "visible?", "end", "mem", "end", ".", "sort", "end" ]
Return a convenient sorted list of all generator names.
[ "Return", "a", "convenient", "sorted", "list", "of", "all", "generator", "names", "." ]
5288e0014011d6f7519c4231f65c8e5d78f48afb
https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L200-L208
5,867
drnic/rubigen
lib/rubigen/lookup.rb
RubiGen.PathSource.each
def each Dir["#{path}/[a-z]*"].each do |dir| if File.directory?(dir) yield Spec.new(File.basename(dir), dir, label) end end end
ruby
def each Dir["#{path}/[a-z]*"].each do |dir| if File.directory?(dir) yield Spec.new(File.basename(dir), dir, label) end end end
[ "def", "each", "Dir", "[", "\"#{path}/[a-z]*\"", "]", ".", "each", "do", "|", "dir", "|", "if", "File", ".", "directory?", "(", "dir", ")", "yield", "Spec", ".", "new", "(", "File", ".", "basename", "(", "dir", ")", ",", "dir", ",", "label", ")", "end", "end", "end" ]
Yield each eligible subdirectory.
[ "Yield", "each", "eligible", "subdirectory", "." ]
5288e0014011d6f7519c4231f65c8e5d78f48afb
https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L222-L228
5,868
drnic/rubigen
lib/rubigen/lookup.rb
RubiGen.GemPathSource.each
def each generator_full_paths.each do |generator| yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label) end end
ruby
def each generator_full_paths.each do |generator| yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label) end end
[ "def", "each", "generator_full_paths", ".", "each", "do", "|", "generator", "|", "yield", "Spec", ".", "new", "(", "File", ".", "basename", "(", "generator", ")", ".", "sub", "(", "/", "/", ",", "''", ")", ",", "File", ".", "dirname", "(", "generator", ")", ",", "label", ")", "end", "end" ]
Yield each generator within rails_generator subdirectories.
[ "Yield", "each", "generator", "within", "rails_generator", "subdirectories", "." ]
5288e0014011d6f7519c4231f65c8e5d78f48afb
https://github.com/drnic/rubigen/blob/5288e0014011d6f7519c4231f65c8e5d78f48afb/lib/rubigen/lookup.rb#L271-L275
5,869
wwidea/minimalist_authentication
lib/minimalist_authentication/verifiable_token.rb
MinimalistAuthentication.VerifiableToken.secure_match?
def secure_match?(token) ActiveSupport::SecurityUtils.secure_compare( ::Digest::SHA256.hexdigest(token), ::Digest::SHA256.hexdigest(verification_token) ) end
ruby
def secure_match?(token) ActiveSupport::SecurityUtils.secure_compare( ::Digest::SHA256.hexdigest(token), ::Digest::SHA256.hexdigest(verification_token) ) end
[ "def", "secure_match?", "(", "token", ")", "ActiveSupport", "::", "SecurityUtils", ".", "secure_compare", "(", "::", "Digest", "::", "SHA256", ".", "hexdigest", "(", "token", ")", ",", "::", "Digest", "::", "SHA256", ".", "hexdigest", "(", "verification_token", ")", ")", "end" ]
Compare the tokens in a time-constant manner, to mitigate timing attacks.
[ "Compare", "the", "tokens", "in", "a", "time", "-", "constant", "manner", "to", "mitigate", "timing", "attacks", "." ]
29372225a8ee7132bf3b989b824b36cf306cc656
https://github.com/wwidea/minimalist_authentication/blob/29372225a8ee7132bf3b989b824b36cf306cc656/lib/minimalist_authentication/verifiable_token.rb#L44-L49
5,870
linsen/mxit-rails
lib/mxit_rails/page.rb
MxitRails.Page.render
def render *arguments if @_mxit_emulator output = render_to_string *arguments output = MxitRails::Styles.add_emoticons output super :inline => output else super *arguments end end
ruby
def render *arguments if @_mxit_emulator output = render_to_string *arguments output = MxitRails::Styles.add_emoticons output super :inline => output else super *arguments end end
[ "def", "render", "*", "arguments", "if", "@_mxit_emulator", "output", "=", "render_to_string", "arguments", "output", "=", "MxitRails", "::", "Styles", ".", "add_emoticons", "output", "super", ":inline", "=>", "output", "else", "super", "arguments", "end", "end" ]
Override render method so as to inject emoticons, etc
[ "Override", "render", "method", "so", "as", "to", "inject", "emoticons", "etc" ]
0a076efccd5042f6b05336785818905b103796ab
https://github.com/linsen/mxit-rails/blob/0a076efccd5042f6b05336785818905b103796ab/lib/mxit_rails/page.rb#L165-L173
5,871
linsen/mxit-rails
lib/mxit_api/client.rb
MxitApi.Client.user_code_request_uri
def user_code_request_uri(redirect_uri, state, scopes) if scopes.empty? raise MxitApi::Exception.new("No scopes were provided.") end # build parameters parameters = { :response_type => "code", :client_id => @client_id, :redirect_uri => redirect_uri, :state => state, :scope => scopes.join(' ') } path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}" end
ruby
def user_code_request_uri(redirect_uri, state, scopes) if scopes.empty? raise MxitApi::Exception.new("No scopes were provided.") end # build parameters parameters = { :response_type => "code", :client_id => @client_id, :redirect_uri => redirect_uri, :state => state, :scope => scopes.join(' ') } path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}" end
[ "def", "user_code_request_uri", "(", "redirect_uri", ",", "state", ",", "scopes", ")", "if", "scopes", ".", "empty?", "raise", "MxitApi", "::", "Exception", ".", "new", "(", "\"No scopes were provided.\"", ")", "end", "# build parameters", "parameters", "=", "{", ":response_type", "=>", "\"code\"", ",", ":client_id", "=>", "@client_id", ",", ":redirect_uri", "=>", "redirect_uri", ",", ":state", "=>", "state", ",", ":scope", "=>", "scopes", ".", "join", "(", "' '", ")", "}", "path", "=", "MXIT_AUTH_CODE_URI", "+", "\"?#{URI.encode_www_form(parameters)}\"", "end" ]
The user's response to the authorisation code request will be redirected to `redirect_uri`. If the request was successful there will be a `code` request parameter; otherwise `error`. redirect_uri - absolute URI to which the user will be redirected after authorisation state - passed back to `redirect_uri` as a request parameter scopes - list of scopes to which access is required
[ "The", "user", "s", "response", "to", "the", "authorisation", "code", "request", "will", "be", "redirected", "to", "redirect_uri", ".", "If", "the", "request", "was", "successful", "there", "will", "be", "a", "code", "request", "parameter", ";", "otherwise", "error", "." ]
0a076efccd5042f6b05336785818905b103796ab
https://github.com/linsen/mxit-rails/blob/0a076efccd5042f6b05336785818905b103796ab/lib/mxit_api/client.rb#L46-L61
5,872
cyberarm/rewrite-gameoverseer
lib/gameoverseer/messages/message_manager.rb
GameOverseer.MessageManager.message
def message(client_id, string, reliable = false, channel = ChannelManager::CHAT) GameOverseer::ENetServer.instance.transmit(client_id, string, reliable, channel) end
ruby
def message(client_id, string, reliable = false, channel = ChannelManager::CHAT) GameOverseer::ENetServer.instance.transmit(client_id, string, reliable, channel) end
[ "def", "message", "(", "client_id", ",", "string", ",", "reliable", "=", "false", ",", "channel", "=", "ChannelManager", "::", "CHAT", ")", "GameOverseer", "::", "ENetServer", ".", "instance", ".", "transmit", "(", "client_id", ",", "string", ",", "reliable", ",", "channel", ")", "end" ]
Send a message to a specific client @param client_id [Integer] ID of client @param string [String] message to send @param reliable [Boolean] whether or not packet delivery is reliable @param channel [Integer] What channel to send on
[ "Send", "a", "message", "to", "a", "specific", "client" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/messages/message_manager.rb#L17-L19
5,873
cyberarm/rewrite-gameoverseer
lib/gameoverseer/messages/message_manager.rb
GameOverseer.MessageManager.broadcast
def broadcast(string, reliable = false, channel = ChannelManager::CHAT) GameOverseer::ENetServer.instance.broadcast(string, reliable, channel) end
ruby
def broadcast(string, reliable = false, channel = ChannelManager::CHAT) GameOverseer::ENetServer.instance.broadcast(string, reliable, channel) end
[ "def", "broadcast", "(", "string", ",", "reliable", "=", "false", ",", "channel", "=", "ChannelManager", "::", "CHAT", ")", "GameOverseer", "::", "ENetServer", ".", "instance", ".", "broadcast", "(", "string", ",", "reliable", ",", "channel", ")", "end" ]
Send a message to all connected clients @param string [String] message to send @param reliable [Boolean] whether or not packet delivery is reliable @param channel [Integer] What channel to send on
[ "Send", "a", "message", "to", "all", "connected", "clients" ]
279ba63868ad11aa2c937fc6c2544049f05d4bca
https://github.com/cyberarm/rewrite-gameoverseer/blob/279ba63868ad11aa2c937fc6c2544049f05d4bca/lib/gameoverseer/messages/message_manager.rb#L26-L28
5,874
edraut/clark-kent
app/models/clark_kent/report.rb
ClarkKent.Report.row_class
def row_class report_columns = viable_report_columns @row_class ||= Class.new do report_columns.each do |report_column| attr_accessor report_column.column_name.to_sym end def initialize params = {} params.each { |key, value| send "#{key}=", value } end def [](key) self.send key end end end
ruby
def row_class report_columns = viable_report_columns @row_class ||= Class.new do report_columns.each do |report_column| attr_accessor report_column.column_name.to_sym end def initialize params = {} params.each { |key, value| send "#{key}=", value } end def [](key) self.send key end end end
[ "def", "row_class", "report_columns", "=", "viable_report_columns", "@row_class", "||=", "Class", ".", "new", "do", "report_columns", ".", "each", "do", "|", "report_column", "|", "attr_accessor", "report_column", ".", "column_name", ".", "to_sym", "end", "def", "initialize", "params", "=", "{", "}", "params", ".", "each", "{", "|", "key", ",", "value", "|", "send", "\"#{key}=\"", ",", "value", "}", "end", "def", "[]", "(", "key", ")", "self", ".", "send", "key", "end", "end", "end" ]
This ephemeral class allows us to create a row object that has the same attributes as the AR response to the query, including all the custom columns defined in the resource class report config. currently only used for the summary row, since we can't get that in the same AR query and have to add it to the collection after the query returns.
[ "This", "ephemeral", "class", "allows", "us", "to", "create", "a", "row", "object", "that", "has", "the", "same", "attributes", "as", "the", "AR", "response", "to", "the", "query", "including", "all", "the", "custom", "columns", "defined", "in", "the", "resource", "class", "report", "config", ".", "currently", "only", "used", "for", "the", "summary", "row", "since", "we", "can", "t", "get", "that", "in", "the", "same", "AR", "query", "and", "have", "to", "add", "it", "to", "the", "collection", "after", "the", "query", "returns", "." ]
93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91
https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L106-L121
5,875
edraut/clark-kent
app/models/clark_kent/report.rb
ClarkKent.Report.report_filter_params
def report_filter_params Hash[*viable_report_filters.map{|filter| filter.filter_match_params}.flatten]. merge(order: self.sorter) end
ruby
def report_filter_params Hash[*viable_report_filters.map{|filter| filter.filter_match_params}.flatten]. merge(order: self.sorter) end
[ "def", "report_filter_params", "Hash", "[", "viable_report_filters", ".", "map", "{", "|", "filter", "|", "filter", ".", "filter_match_params", "}", ".", "flatten", "]", ".", "merge", "(", "order", ":", "self", ".", "sorter", ")", "end" ]
These are the built-in filter params that define this report. They are merged at a later step with the runtime params entered by the user for a specific report run. nb. the sorter column here may be overridden by a runtime sort if requested by the user.
[ "These", "are", "the", "built", "-", "in", "filter", "params", "that", "define", "this", "report", ".", "They", "are", "merged", "at", "a", "later", "step", "with", "the", "runtime", "params", "entered", "by", "the", "user", "for", "a", "specific", "report", "run", ".", "nb", ".", "the", "sorter", "column", "here", "may", "be", "overridden", "by", "a", "runtime", "sort", "if", "requested", "by", "the", "user", "." ]
93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91
https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L173-L176
5,876
edraut/clark-kent
app/models/clark_kent/report.rb
ClarkKent.Report.custom_filters
def custom_filters self.resource_class.report_filter_options.select{|filter| viable_report_filters.map(&:filter_name).exclude? filter.param} end
ruby
def custom_filters self.resource_class.report_filter_options.select{|filter| viable_report_filters.map(&:filter_name).exclude? filter.param} end
[ "def", "custom_filters", "self", ".", "resource_class", ".", "report_filter_options", ".", "select", "{", "|", "filter", "|", "viable_report_filters", ".", "map", "(", ":filter_name", ")", ".", "exclude?", "filter", ".", "param", "}", "end" ]
These are the filters available at runtime, ie. not including the ones set to define this report. If updating the report, this is the set available to add as new report definition filters.
[ "These", "are", "the", "filters", "available", "at", "runtime", "ie", ".", "not", "including", "the", "ones", "set", "to", "define", "this", "report", ".", "If", "updating", "the", "report", "this", "is", "the", "set", "available", "to", "add", "as", "new", "report", "definition", "filters", "." ]
93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91
https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L240-L242
5,877
edraut/clark-kent
app/models/clark_kent/report.rb
ClarkKent.Report.available_columns
def available_columns column_options.reject{|column| viable_report_columns.map(&:column_name).include? column.name.to_s} end
ruby
def available_columns column_options.reject{|column| viable_report_columns.map(&:column_name).include? column.name.to_s} end
[ "def", "available_columns", "column_options", ".", "reject", "{", "|", "column", "|", "viable_report_columns", ".", "map", "(", ":column_name", ")", ".", "include?", "column", ".", "name", ".", "to_s", "}", "end" ]
This is the set of columns not chosed to use in the report. These are the ones available to add when updating a report.
[ "This", "is", "the", "set", "of", "columns", "not", "chosed", "to", "use", "in", "the", "report", ".", "These", "are", "the", "ones", "available", "to", "add", "when", "updating", "a", "report", "." ]
93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91
https://github.com/edraut/clark-kent/blob/93d2f2dd0f7d6ee939180ba58ca4c69c3d8c1a91/app/models/clark_kent/report.rb#L246-L248
5,878
jkr2255/prop_logic
lib/prop_logic/term.rb
PropLogic.Term.each_sat
def each_sat return to_enum(:each_sat) unless block_given? sat_loop(self) do |sat, solver| yield sat negated_vars = sat.terms.map do |t| t.is_a?(NotTerm) ? t.terms[0] : ~t end solver << PropLogic.all_or(*negated_vars) end end
ruby
def each_sat return to_enum(:each_sat) unless block_given? sat_loop(self) do |sat, solver| yield sat negated_vars = sat.terms.map do |t| t.is_a?(NotTerm) ? t.terms[0] : ~t end solver << PropLogic.all_or(*negated_vars) end end
[ "def", "each_sat", "return", "to_enum", "(", ":each_sat", ")", "unless", "block_given?", "sat_loop", "(", "self", ")", "do", "|", "sat", ",", "solver", "|", "yield", "sat", "negated_vars", "=", "sat", ".", "terms", ".", "map", "do", "|", "t", "|", "t", ".", "is_a?", "(", "NotTerm", ")", "?", "t", ".", "terms", "[", "0", "]", ":", "~", "t", "end", "solver", "<<", "PropLogic", ".", "all_or", "(", "negated_vars", ")", "end", "end" ]
loop with each satisfied terms. @return [Enumerator] if block is not given. @return [nil] if block is given.
[ "loop", "with", "each", "satisfied", "terms", "." ]
285654d49874195e234f575cdc54f77829a19eae
https://github.com/jkr2255/prop_logic/blob/285654d49874195e234f575cdc54f77829a19eae/lib/prop_logic/term.rb#L173-L182
5,879
suculent/apprepo
lib/apprepo/analyser.rb
AppRepo.Analyser.fetch_app_version
def fetch_app_version(options) metadata = AppRepo::Uploader.new(options).download_manifest_only FastlaneCore::UI.command_output('TODO: Parse version out from metadata') puts JSON.pretty_generate(metadata) unless metadata.nil? FastlaneCore::UI.important('TODO: parse out the bundle-version') metadata['bundle-version'] end
ruby
def fetch_app_version(options) metadata = AppRepo::Uploader.new(options).download_manifest_only FastlaneCore::UI.command_output('TODO: Parse version out from metadata') puts JSON.pretty_generate(metadata) unless metadata.nil? FastlaneCore::UI.important('TODO: parse out the bundle-version') metadata['bundle-version'] end
[ "def", "fetch_app_version", "(", "options", ")", "metadata", "=", "AppRepo", "::", "Uploader", ".", "new", "(", "options", ")", ".", "download_manifest_only", "FastlaneCore", "::", "UI", ".", "command_output", "(", "'TODO: Parse version out from metadata'", ")", "puts", "JSON", ".", "pretty_generate", "(", "metadata", ")", "unless", "metadata", ".", "nil?", "FastlaneCore", "::", "UI", ".", "important", "(", "'TODO: parse out the bundle-version'", ")", "metadata", "[", "'bundle-version'", "]", "end" ]
Fetches remote app version from metadata
[ "Fetches", "remote", "app", "version", "from", "metadata" ]
91583c7e8eb45490c088155174f9dfc2cac7812d
https://github.com/suculent/apprepo/blob/91583c7e8eb45490c088155174f9dfc2cac7812d/lib/apprepo/analyser.rb#L18-L24
5,880
knut2/todonotes
lib/todonotes/log4r.rb
Todonotes.FixmeFormatter.format
def format(event) #@@basicformat "%*s %s" #~ buff = sprintf("%-*s %-5s", Log4r::MaxLevelLength, Log4r::LNAMES[event.level], #~ event.data.is_a?(Array) ? event.data.first : event.name) buff = "%5s" % (event.data.is_a?(Array) ? event.data.first : event.name) #~ buff += (event.tracer.nil? ? "" : "(#{event.tracer[2]})") + ": " buff << ": " buff << format_object(event.data.is_a?(Array) ? event.data.last : event.data) buff << (event.tracer.nil? ? "" : " (#{event.tracer.join('/')})") buff << "\n" buff end
ruby
def format(event) #@@basicformat "%*s %s" #~ buff = sprintf("%-*s %-5s", Log4r::MaxLevelLength, Log4r::LNAMES[event.level], #~ event.data.is_a?(Array) ? event.data.first : event.name) buff = "%5s" % (event.data.is_a?(Array) ? event.data.first : event.name) #~ buff += (event.tracer.nil? ? "" : "(#{event.tracer[2]})") + ": " buff << ": " buff << format_object(event.data.is_a?(Array) ? event.data.last : event.data) buff << (event.tracer.nil? ? "" : " (#{event.tracer.join('/')})") buff << "\n" buff end
[ "def", "format", "(", "event", ")", "#@@basicformat \"%*s %s\"", "#~ buff = sprintf(\"%-*s %-5s\", Log4r::MaxLevelLength, Log4r::LNAMES[event.level],", "#~ event.data.is_a?(Array) ? event.data.first : event.name)", "buff", "=", "\"%5s\"", "%", "(", "event", ".", "data", ".", "is_a?", "(", "Array", ")", "?", "event", ".", "data", ".", "first", ":", "event", ".", "name", ")", "#~ buff += (event.tracer.nil? ? \"\" : \"(#{event.tracer[2]})\") + \": \"", "buff", "<<", "\": \"", "buff", "<<", "format_object", "(", "event", ".", "data", ".", "is_a?", "(", "Array", ")", "?", "event", ".", "data", ".", "last", ":", "event", ".", "data", ")", "buff", "<<", "(", "event", ".", "tracer", ".", "nil?", "?", "\"\"", ":", "\" (#{event.tracer.join('/')})\"", ")", "buff", "<<", "\"\\n\"", "buff", "end" ]
=begin rdoc If event is an Array, the output is adapted. This outputter is only for internal use via Todonotes. =end
[ "=", "begin", "rdoc", "If", "event", "is", "an", "Array", "the", "output", "is", "adapted", "." ]
67e6e9402d2e67fb0cda320669dd33d737351fa4
https://github.com/knut2/todonotes/blob/67e6e9402d2e67fb0cda320669dd33d737351fa4/lib/todonotes/log4r.rb#L11-L22
5,881
dennmart/wanikani-gem
lib/wanikani/client.rb
Wanikani.Client.valid_api_key?
def valid_api_key?(api_key = nil) api_key ||= @api_key return false if api_key.empty? res = client.get("/api/#{@api_version}/user/#{api_key}/user-information") return false if !res.success? || res.body.has_key?("error") return true end
ruby
def valid_api_key?(api_key = nil) api_key ||= @api_key return false if api_key.empty? res = client.get("/api/#{@api_version}/user/#{api_key}/user-information") return false if !res.success? || res.body.has_key?("error") return true end
[ "def", "valid_api_key?", "(", "api_key", "=", "nil", ")", "api_key", "||=", "@api_key", "return", "false", "if", "api_key", ".", "empty?", "res", "=", "client", ".", "get", "(", "\"/api/#{@api_version}/user/#{api_key}/user-information\"", ")", "return", "false", "if", "!", "res", ".", "success?", "||", "res", ".", "body", ".", "has_key?", "(", "\"error\"", ")", "return", "true", "end" ]
Initialize a client which will be used to communicate with WaniKani. @param options [Hash] the API key (required) and API version (optional) used to communicate with the WaniKani API. @return [Wanikani::Client] an instance of Wanikani::Client. Verifies if the client's API key is valid by checking WaniKani's API. @param api_key [String] the API key to validate in WaniKani. @return [Boolean] whether the API key is valid.
[ "Initialize", "a", "client", "which", "will", "be", "used", "to", "communicate", "with", "WaniKani", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L40-L48
5,882
dennmart/wanikani-gem
lib/wanikani/client.rb
Wanikani.Client.client
def client Faraday.new(url: Wanikani::API_ENDPOINT) do |conn| conn.response :json, :content_type => /\bjson$/ conn.adapter Faraday.default_adapter end end
ruby
def client Faraday.new(url: Wanikani::API_ENDPOINT) do |conn| conn.response :json, :content_type => /\bjson$/ conn.adapter Faraday.default_adapter end end
[ "def", "client", "Faraday", ".", "new", "(", "url", ":", "Wanikani", "::", "API_ENDPOINT", ")", "do", "|", "conn", "|", "conn", ".", "response", ":json", ",", ":content_type", "=>", "/", "\\b", "/", "conn", ".", "adapter", "Faraday", ".", "default_adapter", "end", "end" ]
Sets up the HTTP client for communicating with the WaniKani API. @return [Faraday::Connection] the HTTP client to communicate with the WaniKani API.
[ "Sets", "up", "the", "HTTP", "client", "for", "communicating", "with", "the", "WaniKani", "API", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L67-L72
5,883
dennmart/wanikani-gem
lib/wanikani/client.rb
Wanikani.Client.api_response
def api_response(resource, optional_arg = nil) raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty? begin res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}") if !res.success? || res.body.has_key?("error") raise_exception(res) else return res.body end rescue => error raise Exception, "There was an error: #{error.message}" end end
ruby
def api_response(resource, optional_arg = nil) raise ArgumentError, "You must define a resource to query WaniKani" if resource.nil? || resource.empty? begin res = client.get("/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}") if !res.success? || res.body.has_key?("error") raise_exception(res) else return res.body end rescue => error raise Exception, "There was an error: #{error.message}" end end
[ "def", "api_response", "(", "resource", ",", "optional_arg", "=", "nil", ")", "raise", "ArgumentError", ",", "\"You must define a resource to query WaniKani\"", "if", "resource", ".", "nil?", "||", "resource", ".", "empty?", "begin", "res", "=", "client", ".", "get", "(", "\"/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}\"", ")", "if", "!", "res", ".", "success?", "||", "res", ".", "body", ".", "has_key?", "(", "\"error\"", ")", "raise_exception", "(", "res", ")", "else", "return", "res", ".", "body", "end", "rescue", "=>", "error", "raise", "Exception", ",", "\"There was an error: #{error.message}\"", "end", "end" ]
Contacts the WaniKani API and returns the data specified. @param resource [String] the resource to access. @param optional_arg [String] optional arguments for the specified resource. @return [Hash] the parsed API response.
[ "Contacts", "the", "WaniKani", "API", "and", "returns", "the", "data", "specified", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L79-L93
5,884
dennmart/wanikani-gem
lib/wanikani/client.rb
Wanikani.Client.raise_exception
def raise_exception(response) raise Wanikani::InvalidKey, "The API key used for this request is invalid." and return if response.status == 401 message = if response.body.is_a?(Hash) and response.body.has_key?("error") response.body["error"]["message"] else "Status code: #{response.status}" end raise Wanikani::Exception, "There was an error fetching the data from WaniKani (#{message})" end
ruby
def raise_exception(response) raise Wanikani::InvalidKey, "The API key used for this request is invalid." and return if response.status == 401 message = if response.body.is_a?(Hash) and response.body.has_key?("error") response.body["error"]["message"] else "Status code: #{response.status}" end raise Wanikani::Exception, "There was an error fetching the data from WaniKani (#{message})" end
[ "def", "raise_exception", "(", "response", ")", "raise", "Wanikani", "::", "InvalidKey", ",", "\"The API key used for this request is invalid.\"", "and", "return", "if", "response", ".", "status", "==", "401", "message", "=", "if", "response", ".", "body", ".", "is_a?", "(", "Hash", ")", "and", "response", ".", "body", ".", "has_key?", "(", "\"error\"", ")", "response", ".", "body", "[", "\"error\"", "]", "[", "\"message\"", "]", "else", "\"Status code: #{response.status}\"", "end", "raise", "Wanikani", "::", "Exception", ",", "\"There was an error fetching the data from WaniKani (#{message})\"", "end" ]
Handles exceptions according to the API response. @param response [Hash] the parsed API response from WaniKani's API.
[ "Handles", "exceptions", "according", "to", "the", "API", "response", "." ]
70f9e4289f758c9663c0ee4d1172acb711487df9
https://github.com/dennmart/wanikani-gem/blob/70f9e4289f758c9663c0ee4d1172acb711487df9/lib/wanikani/client.rb#L98-L107
5,885
conspire-org/lazy-json
lib/lazy-json.rb
LazyJson.Object.[]
def [](key) if ! @fields.has_key?(key) && ! @fseq.empty? while true @fseq = @fseq.skip_whitespace if @fseq.first == 125 # '}'.ord @fseq = @fseq.skip_byte(125).skip_whitespace # '}'.ord break end new_key, new_value = read_field_and_consume @fields[new_key] = new_value break if new_key == key end end @fields[key] end
ruby
def [](key) if ! @fields.has_key?(key) && ! @fseq.empty? while true @fseq = @fseq.skip_whitespace if @fseq.first == 125 # '}'.ord @fseq = @fseq.skip_byte(125).skip_whitespace # '}'.ord break end new_key, new_value = read_field_and_consume @fields[new_key] = new_value break if new_key == key end end @fields[key] end
[ "def", "[]", "(", "key", ")", "if", "!", "@fields", ".", "has_key?", "(", "key", ")", "&&", "!", "@fseq", ".", "empty?", "while", "true", "@fseq", "=", "@fseq", ".", "skip_whitespace", "if", "@fseq", ".", "first", "==", "125", "# '}'.ord", "@fseq", "=", "@fseq", ".", "skip_byte", "(", "125", ")", ".", "skip_whitespace", "# '}'.ord", "break", "end", "new_key", ",", "new_value", "=", "read_field_and_consume", "@fields", "[", "new_key", "]", "=", "new_value", "break", "if", "new_key", "==", "key", "end", "end", "@fields", "[", "key", "]", "end" ]
Access a field, lazily parsing if not yet parsed
[ "Access", "a", "field", "lazily", "parsing", "if", "not", "yet", "parsed" ]
f655f7de0b06b9c5e61655e0f4e54f90edaf263d
https://github.com/conspire-org/lazy-json/blob/f655f7de0b06b9c5e61655e0f4e54f90edaf263d/lib/lazy-json.rb#L206-L220
5,886
conspire-org/lazy-json
lib/lazy-json.rb
LazyJson.Array.[]
def [](i) if @elements.size <= i && ! @eseq.empty? while true @eseq = @eseq.skip_whitespace if @eseq.first == 93 # ']'.ord @eseq = @eseq.skip_byte(93).skip_whitespace # ']'.ord break end new_value = read_value_and_consume @elements << new_value break if @elements.size > i end end @elements[i] end
ruby
def [](i) if @elements.size <= i && ! @eseq.empty? while true @eseq = @eseq.skip_whitespace if @eseq.first == 93 # ']'.ord @eseq = @eseq.skip_byte(93).skip_whitespace # ']'.ord break end new_value = read_value_and_consume @elements << new_value break if @elements.size > i end end @elements[i] end
[ "def", "[]", "(", "i", ")", "if", "@elements", ".", "size", "<=", "i", "&&", "!", "@eseq", ".", "empty?", "while", "true", "@eseq", "=", "@eseq", ".", "skip_whitespace", "if", "@eseq", ".", "first", "==", "93", "# ']'.ord", "@eseq", "=", "@eseq", ".", "skip_byte", "(", "93", ")", ".", "skip_whitespace", "# ']'.ord", "break", "end", "new_value", "=", "read_value_and_consume", "@elements", "<<", "new_value", "break", "if", "@elements", ".", "size", ">", "i", "end", "end", "@elements", "[", "i", "]", "end" ]
Access an element, lazily parsing if not yet parsed
[ "Access", "an", "element", "lazily", "parsing", "if", "not", "yet", "parsed" ]
f655f7de0b06b9c5e61655e0f4e54f90edaf263d
https://github.com/conspire-org/lazy-json/blob/f655f7de0b06b9c5e61655e0f4e54f90edaf263d/lib/lazy-json.rb#L248-L262
5,887
robertwahler/repo_manager
lib/repo_manager/tasks/thor_helper.rb
RepoManager.ThorHelper.configuration
def configuration(configuration_file=nil) return @configuration if @configuration logger.debug "getting repo_manager configuration" app_options = {} app_options[:config] = configuration_file || options[:config] @configuration = ::RepoManager::Settings.new(nil, app_options) end
ruby
def configuration(configuration_file=nil) return @configuration if @configuration logger.debug "getting repo_manager configuration" app_options = {} app_options[:config] = configuration_file || options[:config] @configuration = ::RepoManager::Settings.new(nil, app_options) end
[ "def", "configuration", "(", "configuration_file", "=", "nil", ")", "return", "@configuration", "if", "@configuration", "logger", ".", "debug", "\"getting repo_manager configuration\"", "app_options", "=", "{", "}", "app_options", "[", ":config", "]", "=", "configuration_file", "||", "options", "[", ":config", "]", "@configuration", "=", "::", "RepoManager", "::", "Settings", ".", "new", "(", "nil", ",", "app_options", ")", "end" ]
main repo_manager configuration setttings file
[ "main", "repo_manager", "configuration", "setttings", "file" ]
d945f1cb6ac48b5689b633fcc029fd77c6a02d09
https://github.com/robertwahler/repo_manager/blob/d945f1cb6ac48b5689b633fcc029fd77c6a02d09/lib/repo_manager/tasks/thor_helper.rb#L11-L17
5,888
mLewisLogic/saddle
lib/saddle/endpoint.rb
Saddle.BaseEndpoint.request
def request(method, action, params={}, options={}) # Augment in interesting options options[:call_chain] = _path_array options[:action] = action @requester.send(method, _path(action), params, options) end
ruby
def request(method, action, params={}, options={}) # Augment in interesting options options[:call_chain] = _path_array options[:action] = action @requester.send(method, _path(action), params, options) end
[ "def", "request", "(", "method", ",", "action", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "# Augment in interesting options", "options", "[", ":call_chain", "]", "=", "_path_array", "options", "[", ":action", "]", "=", "action", "@requester", ".", "send", "(", "method", ",", "_path", "(", "action", ")", ",", "params", ",", "options", ")", "end" ]
Each endpoint needs to have a requester in order to ... make ... uh ... requests. Generic request wrapper
[ "Each", "endpoint", "needs", "to", "have", "a", "requester", "in", "order", "to", "...", "make", "...", "uh", "...", "requests", ".", "Generic", "request", "wrapper" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L25-L30
5,889
mLewisLogic/saddle
lib/saddle/endpoint.rb
Saddle.BaseEndpoint._build_and_attach_node
def _build_and_attach_node(endpoint_class, method_name=nil) # Create the new endpoint endpoint_instance = endpoint_class.new(@requester, method_name, self) # Attach the endpoint as an instance variable and method method_name ||= endpoint_class.name.demodulize.underscore self.instance_variable_set("@#{method_name}", endpoint_instance) self.define_singleton_method(method_name.to_s) { endpoint_instance } endpoint_instance end
ruby
def _build_and_attach_node(endpoint_class, method_name=nil) # Create the new endpoint endpoint_instance = endpoint_class.new(@requester, method_name, self) # Attach the endpoint as an instance variable and method method_name ||= endpoint_class.name.demodulize.underscore self.instance_variable_set("@#{method_name}", endpoint_instance) self.define_singleton_method(method_name.to_s) { endpoint_instance } endpoint_instance end
[ "def", "_build_and_attach_node", "(", "endpoint_class", ",", "method_name", "=", "nil", ")", "# Create the new endpoint", "endpoint_instance", "=", "endpoint_class", ".", "new", "(", "@requester", ",", "method_name", ",", "self", ")", "# Attach the endpoint as an instance variable and method", "method_name", "||=", "endpoint_class", ".", "name", ".", "demodulize", ".", "underscore", "self", ".", "instance_variable_set", "(", "\"@#{method_name}\"", ",", "endpoint_instance", ")", "self", ".", "define_singleton_method", "(", "method_name", ".", "to_s", ")", "{", "endpoint_instance", "}", "endpoint_instance", "end" ]
Create an endpoint instance and foist it upon this node Not private, but not part of the public interface for an endpoint
[ "Create", "an", "endpoint", "instance", "and", "foist", "it", "upon", "this", "node", "Not", "private", "but", "not", "part", "of", "the", "public", "interface", "for", "an", "endpoint" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L62-L70
5,890
mLewisLogic/saddle
lib/saddle/endpoint.rb
Saddle.BaseEndpoint._endpoint_chain
def _endpoint_chain chain = [] node = self while node.is_a?(BaseEndpoint) chain << node node = node.parent end chain.reverse end
ruby
def _endpoint_chain chain = [] node = self while node.is_a?(BaseEndpoint) chain << node node = node.parent end chain.reverse end
[ "def", "_endpoint_chain", "chain", "=", "[", "]", "node", "=", "self", "while", "node", ".", "is_a?", "(", "BaseEndpoint", ")", "chain", "<<", "node", "node", "=", "node", ".", "parent", "end", "chain", ".", "reverse", "end" ]
Get the parent chain that led to this endpoint
[ "Get", "the", "parent", "chain", "that", "led", "to", "this", "endpoint" ]
9f470a948039dbedb75655d883e714a29b273961
https://github.com/mLewisLogic/saddle/blob/9f470a948039dbedb75655d883e714a29b273961/lib/saddle/endpoint.rb#L101-L109
5,891
hendricius/instagram_public_api
lib/instagram_public_api/http_service.rb
InstagramPublicApi.HTTPService.perform_request
def perform_request(request_options: {}, parameters: {}, uri:) args = parameters request_options = request_options.merge(faraday_options) # figure out our options for this request # set up our Faraday connection connection = Faraday.new(faraday_options) do |faraday| faraday.adapter Faraday.default_adapter end connection.get(uri, args) end
ruby
def perform_request(request_options: {}, parameters: {}, uri:) args = parameters request_options = request_options.merge(faraday_options) # figure out our options for this request # set up our Faraday connection connection = Faraday.new(faraday_options) do |faraday| faraday.adapter Faraday.default_adapter end connection.get(uri, args) end
[ "def", "perform_request", "(", "request_options", ":", "{", "}", ",", "parameters", ":", "{", "}", ",", "uri", ":", ")", "args", "=", "parameters", "request_options", "=", "request_options", ".", "merge", "(", "faraday_options", ")", "# figure out our options for this request", "# set up our Faraday connection", "connection", "=", "Faraday", ".", "new", "(", "faraday_options", ")", "do", "|", "faraday", "|", "faraday", ".", "adapter", "Faraday", ".", "default_adapter", "end", "connection", ".", "get", "(", "uri", ",", "args", ")", "end" ]
performs the actual http request
[ "performs", "the", "actual", "http", "request" ]
ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6
https://github.com/hendricius/instagram_public_api/blob/ec7c729109135297f3e8f5dc2c8d43cc97e1d3a6/lib/instagram_public_api/http_service.rb#L38-L47
5,892
Deradon/d3_mpq
lib/d3_mpq/analyzer.rb
D3MPQ.Analyzer.write_game_balance
def write_game_balance write_single_file("analyze") dir = File.join("analyze", parser_name) dir = File.join(dir, @field.to_s) if @field write_analyzed(dir) end
ruby
def write_game_balance write_single_file("analyze") dir = File.join("analyze", parser_name) dir = File.join(dir, @field.to_s) if @field write_analyzed(dir) end
[ "def", "write_game_balance", "write_single_file", "(", "\"analyze\"", ")", "dir", "=", "File", ".", "join", "(", "\"analyze\"", ",", "parser_name", ")", "dir", "=", "File", ".", "join", "(", "dir", ",", "@field", ".", "to_s", ")", "if", "@field", "write_analyzed", "(", "dir", ")", "end" ]
Writing if GameBalance
[ "Writing", "if", "GameBalance" ]
370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78
https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L49-L55
5,893
Deradon/d3_mpq
lib/d3_mpq/analyzer.rb
D3MPQ.Analyzer.write_analyzed
def write_analyzed(dir) FileUtils.mkdir_p(dir) attributes.each do |a, v| path = File.join(dir, a.to_s) s = "Count|Value\n" + v.map { |e| "#{e[:count]}|#{e[:value]}" }.join("\n") File.open("#{path}.csv", 'w') { |f| f.write(s) } end end
ruby
def write_analyzed(dir) FileUtils.mkdir_p(dir) attributes.each do |a, v| path = File.join(dir, a.to_s) s = "Count|Value\n" + v.map { |e| "#{e[:count]}|#{e[:value]}" }.join("\n") File.open("#{path}.csv", 'w') { |f| f.write(s) } end end
[ "def", "write_analyzed", "(", "dir", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "attributes", ".", "each", "do", "|", "a", ",", "v", "|", "path", "=", "File", ".", "join", "(", "dir", ",", "a", ".", "to_s", ")", "s", "=", "\"Count|Value\\n\"", "+", "v", ".", "map", "{", "|", "e", "|", "\"#{e[:count]}|#{e[:value]}\"", "}", ".", "join", "(", "\"\\n\"", ")", "File", ".", "open", "(", "\"#{path}.csv\"", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "s", ")", "}", "end", "end" ]
Writing multiple files to given dir.
[ "Writing", "multiple", "files", "to", "given", "dir", "." ]
370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78
https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L98-L106
5,894
Deradon/d3_mpq
lib/d3_mpq/analyzer.rb
D3MPQ.Analyzer.attributes
def attributes return @attributes if @attributes unsorted = Hash.new { |h,k| h[k] = Hash.new(0) } snapshots.each do |attributes| attributes = attributes[@field] if @field attributes.each do |h| h.each { |attribute, value| unsorted[attribute][value] += 1 } end end @attributes = Hash.new { |h,k| h[k] = [] } unsorted.each do |name, h| h.each do |value, count| @attributes[name] << { :value => value, :count => count } end @attributes[name].sort! { |x,y| y[:count] <=> x[:count] } end return @attributes end
ruby
def attributes return @attributes if @attributes unsorted = Hash.new { |h,k| h[k] = Hash.new(0) } snapshots.each do |attributes| attributes = attributes[@field] if @field attributes.each do |h| h.each { |attribute, value| unsorted[attribute][value] += 1 } end end @attributes = Hash.new { |h,k| h[k] = [] } unsorted.each do |name, h| h.each do |value, count| @attributes[name] << { :value => value, :count => count } end @attributes[name].sort! { |x,y| y[:count] <=> x[:count] } end return @attributes end
[ "def", "attributes", "return", "@attributes", "if", "@attributes", "unsorted", "=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "Hash", ".", "new", "(", "0", ")", "}", "snapshots", ".", "each", "do", "|", "attributes", "|", "attributes", "=", "attributes", "[", "@field", "]", "if", "@field", "attributes", ".", "each", "do", "|", "h", "|", "h", ".", "each", "{", "|", "attribute", ",", "value", "|", "unsorted", "[", "attribute", "]", "[", "value", "]", "+=", "1", "}", "end", "end", "@attributes", "=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "[", "]", "}", "unsorted", ".", "each", "do", "|", "name", ",", "h", "|", "h", ".", "each", "do", "|", "value", ",", "count", "|", "@attributes", "[", "name", "]", "<<", "{", ":value", "=>", "value", ",", ":count", "=>", "count", "}", "end", "@attributes", "[", "name", "]", ".", "sort!", "{", "|", "x", ",", "y", "|", "y", "[", ":count", "]", "<=>", "x", "[", ":count", "]", "}", "end", "return", "@attributes", "end" ]
Return analyzed attributes
[ "Return", "analyzed", "attributes" ]
370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78
https://github.com/Deradon/d3_mpq/blob/370af6dbe3c2ae5141b6d2faf1ba8fdd3ff2ca78/lib/d3_mpq/analyzer.rb#L109-L130
5,895
astro/remcached
lib/remcached/packet.rb
Memcached.Packet.to_s
def to_s extras_s = extras_to_s key_s = self[:key].to_s value_s = self[:value].to_s self[:extras_length] = extras_s.length self[:key_length] = key_s.length self[:total_body_length] = extras_s.length + key_s.length + value_s.length header_to_s + extras_s + key_s + value_s end
ruby
def to_s extras_s = extras_to_s key_s = self[:key].to_s value_s = self[:value].to_s self[:extras_length] = extras_s.length self[:key_length] = key_s.length self[:total_body_length] = extras_s.length + key_s.length + value_s.length header_to_s + extras_s + key_s + value_s end
[ "def", "to_s", "extras_s", "=", "extras_to_s", "key_s", "=", "self", "[", ":key", "]", ".", "to_s", "value_s", "=", "self", "[", ":value", "]", ".", "to_s", "self", "[", ":extras_length", "]", "=", "extras_s", ".", "length", "self", "[", ":key_length", "]", "=", "key_s", ".", "length", "self", "[", ":total_body_length", "]", "=", "extras_s", ".", "length", "+", "key_s", ".", "length", "+", "value_s", ".", "length", "header_to_s", "+", "extras_s", "+", "key_s", "+", "value_s", "end" ]
Serialize for wire
[ "Serialize", "for", "wire" ]
cd687e219c228ee718ec0e9a93e12eb01ca6a38b
https://github.com/astro/remcached/blob/cd687e219c228ee718ec0e9a93e12eb01ca6a38b/lib/remcached/packet.rb#L106-L114
5,896
mediatainment/mongoid_cart
lib/mongoid_cart/view_helpers.rb
MongoidCart.ViewHelpers.remove_from_cart_link
def remove_from_cart_link(item) link_to(mongoid_cart.remove_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do (tag :i, class: 'fa fa-cart-plus').concat('Remove from cart') end end
ruby
def remove_from_cart_link(item) link_to(mongoid_cart.remove_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do (tag :i, class: 'fa fa-cart-plus').concat('Remove from cart') end end
[ "def", "remove_from_cart_link", "(", "item", ")", "link_to", "(", "mongoid_cart", ".", "remove_item_path", "(", "item", ":", "{", "type", ":", "item", ".", "class", ".", "to_s", ",", "id", ":", "item", ".", "_id", "}", ")", ",", "{", "class", ":", "\"btn btn-default\"", "}", ")", "do", "(", "tag", ":i", ",", "class", ":", "'fa fa-cart-plus'", ")", ".", "concat", "(", "'Remove from cart'", ")", "end", "end" ]
link_to mongoid_cart.remove_item_path
[ "link_to", "mongoid_cart", ".", "remove_item_path" ]
49f9d01a6b627570122d464ef134638e03535c5f
https://github.com/mediatainment/mongoid_cart/blob/49f9d01a6b627570122d464ef134638e03535c5f/lib/mongoid_cart/view_helpers.rb#L5-L9
5,897
mediatainment/mongoid_cart
lib/mongoid_cart/view_helpers.rb
MongoidCart.ViewHelpers.add_to_cart_link
def add_to_cart_link(item) link_to(mongoid_cart.add_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do (tag :i, class: 'fa fa-cart-plus').concat('Add to cart') end end
ruby
def add_to_cart_link(item) link_to(mongoid_cart.add_item_path(item: {type: item.class.to_s, id: item._id}), {class: "btn btn-default"}) do (tag :i, class: 'fa fa-cart-plus').concat('Add to cart') end end
[ "def", "add_to_cart_link", "(", "item", ")", "link_to", "(", "mongoid_cart", ".", "add_item_path", "(", "item", ":", "{", "type", ":", "item", ".", "class", ".", "to_s", ",", "id", ":", "item", ".", "_id", "}", ")", ",", "{", "class", ":", "\"btn btn-default\"", "}", ")", "do", "(", "tag", ":i", ",", "class", ":", "'fa fa-cart-plus'", ")", ".", "concat", "(", "'Add to cart'", ")", "end", "end" ]
link_to mongoid_cart.add_item_path
[ "link_to", "mongoid_cart", ".", "add_item_path" ]
49f9d01a6b627570122d464ef134638e03535c5f
https://github.com/mediatainment/mongoid_cart/blob/49f9d01a6b627570122d464ef134638e03535c5f/lib/mongoid_cart/view_helpers.rb#L12-L16
5,898
astro/remcached
lib/remcached/client.rb
Memcached.Client.stats
def stats(contents={}, &callback) send_request Request::Stats.new(contents) do |result| callback.call result if result[:status] == Errors::NO_ERROR && result[:key] != '' :proceed end end end
ruby
def stats(contents={}, &callback) send_request Request::Stats.new(contents) do |result| callback.call result if result[:status] == Errors::NO_ERROR && result[:key] != '' :proceed end end end
[ "def", "stats", "(", "contents", "=", "{", "}", ",", "&", "callback", ")", "send_request", "Request", "::", "Stats", ".", "new", "(", "contents", ")", "do", "|", "result", "|", "callback", ".", "call", "result", "if", "result", "[", ":status", "]", "==", "Errors", "::", "NO_ERROR", "&&", "result", "[", ":key", "]", "!=", "''", ":proceed", "end", "end", "end" ]
Callback will be called multiple times
[ "Callback", "will", "be", "called", "multiple", "times" ]
cd687e219c228ee718ec0e9a93e12eb01ca6a38b
https://github.com/astro/remcached/blob/cd687e219c228ee718ec0e9a93e12eb01ca6a38b/lib/remcached/client.rb#L155-L163
5,899
jgoizueta/numerals
lib/numerals/numeral.rb
Numerals.Numeral.to_base
def to_base(other_base) if other_base == @radix dup else normalization = exact? ? :exact : :approximate Numeral.from_quotient to_quotient, base: other_base, normalize: normalization end end
ruby
def to_base(other_base) if other_base == @radix dup else normalization = exact? ? :exact : :approximate Numeral.from_quotient to_quotient, base: other_base, normalize: normalization end end
[ "def", "to_base", "(", "other_base", ")", "if", "other_base", "==", "@radix", "dup", "else", "normalization", "=", "exact?", "?", ":exact", ":", ":approximate", "Numeral", ".", "from_quotient", "to_quotient", ",", "base", ":", "other_base", ",", "normalize", ":", "normalization", "end", "end" ]
Convert a Numeral to a different base
[ "Convert", "a", "Numeral", "to", "a", "different", "base" ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/numeral.rb#L541-L548