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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,500
tclaus/keytechkit.gem
lib/keytechKit/elements/element_files/element_file_handler.rb
KeytechKit.ElementFileHandler.load
def load(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files", parameter) parse_files(response['FileInfos']) if response.success? end
ruby
def load(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files", parameter) parse_files(response['FileInfos']) if response.success? end
[ "def", "load", "(", "element_key", ")", "parameter", "=", "{", "basic_auth", ":", "@auth", "}", "response", "=", "self", ".", "class", ".", "get", "(", "\"/elements/#{element_key}/files\"", ",", "parameter", ")", "parse_files", "(", "response", "[", "'FileInfos'", "]", ")", "if", "response", ".", "success?", "end" ]
Loads the filelist Returns a full list of file data
[ "Loads", "the", "filelist", "Returns", "a", "full", "list", "of", "file", "data" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L55-L59
6,501
tclaus/keytechkit.gem
lib/keytechKit/elements/element_files/element_file_handler.rb
KeytechKit.ElementFileHandler.load_masterfile
def load_masterfile(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files/masterfile", parameter) return response if response.success? end
ruby
def load_masterfile(element_key) parameter = { basic_auth: @auth } response = self.class.get("/elements/#{element_key}/files/masterfile", parameter) return response if response.success? end
[ "def", "load_masterfile", "(", "element_key", ")", "parameter", "=", "{", "basic_auth", ":", "@auth", "}", "response", "=", "self", ".", "class", ".", "get", "(", "\"/elements/#{element_key}/files/masterfile\"", ",", "parameter", ")", "return", "response", "if", "response", ".", "success?", "end" ]
Loads the masterfile directly
[ "Loads", "the", "masterfile", "directly" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L62-L66
6,502
tclaus/keytechkit.gem
lib/keytechKit/elements/element_files/element_file_handler.rb
KeytechKit.ElementFileHandler.upload_masterfile
def upload_masterfile(element_key, file, original_filename) # file, elementkey , name?? content_length = file.size content_type = 'application/octet-stream; charset=utf-8' parameter = { basic_auth: @auth, headers: { 'Content-Type' => content_type, 'Content-Length' => content_length.to_s, 'storageType' => 'MASTER', 'filename' => original_filename.to_s }, body: file.read } upload_file element_key, parameter end
ruby
def upload_masterfile(element_key, file, original_filename) # file, elementkey , name?? content_length = file.size content_type = 'application/octet-stream; charset=utf-8' parameter = { basic_auth: @auth, headers: { 'Content-Type' => content_type, 'Content-Length' => content_length.to_s, 'storageType' => 'MASTER', 'filename' => original_filename.to_s }, body: file.read } upload_file element_key, parameter end
[ "def", "upload_masterfile", "(", "element_key", ",", "file", ",", "original_filename", ")", "# file, elementkey , name??", "content_length", "=", "file", ".", "size", "content_type", "=", "'application/octet-stream; charset=utf-8'", "parameter", "=", "{", "basic_auth", ":", "@auth", ",", "headers", ":", "{", "'Content-Type'", "=>", "content_type", ",", "'Content-Length'", "=>", "content_length", ".", "to_s", ",", "'storageType'", "=>", "'MASTER'", ",", "'filename'", "=>", "original_filename", ".", "to_s", "}", ",", "body", ":", "file", ".", "read", "}", "upload_file", "element_key", ",", "parameter", "end" ]
Masterfile is the main file attached to a document
[ "Masterfile", "is", "the", "main", "file", "attached", "to", "a", "document" ]
caa7a6bee32b75ec18a4004179ae10cb69d148c2
https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L70-L81
6,503
barkerest/shells
lib/shells/shell_base/options.rb
Shells.ShellBase.change_quit
def change_quit(quit_command) raise Shells::NotRunning unless running? self.options = options.dup.merge( quit: quit_command ).freeze self end
ruby
def change_quit(quit_command) raise Shells::NotRunning unless running? self.options = options.dup.merge( quit: quit_command ).freeze self end
[ "def", "change_quit", "(", "quit_command", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "self", ".", "options", "=", "options", ".", "dup", ".", "merge", "(", "quit", ":", "quit_command", ")", ".", "freeze", "self", "end" ]
Initializes the shell with the supplied options. These options are common to all shells. +prompt+:: Defaults to "~~#". Most special characters will be stripped. +retrieve_exit_code+:: Defaults to false. Can also be true. +on_non_zero_exit_code+:: Defaults to :ignore. Can also be :raise. +silence_timeout+:: Defaults to 0. If greater than zero, will raise an error after waiting this many seconds for a prompt. +command_timeout+:: Defaults to 0. If greater than zero, will raise an error after a command runs for this long without finishing. +unbuffered_input+:: Defaults to false. If non-false, then input is sent one character at a time, otherwise input is sent in whole strings. If set to :echo, then input is sent one character at a time and the character must be echoed back from the shell before the next character will be sent. Please check the documentation for each shell class for specific shell options. Allows you to change the :quit option inside of a session. This is useful if you need to change the quit command for some reason. e.g. - Changing the command to "reboot". Returns the shell instance.
[ "Initializes", "the", "shell", "with", "the", "supplied", "options", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/options.rb#L103-L107
6,504
BUEZE/taaze
lib/taaze/comments.rb
Taaze.TaazeComments.url_get_html
def url_get_html(url_str) url = URI.parse(URI.encode(url_str)) # first get total size req = Net::HTTP::Get.new(url.to_s) res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) } res.body end
ruby
def url_get_html(url_str) url = URI.parse(URI.encode(url_str)) # first get total size req = Net::HTTP::Get.new(url.to_s) res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) } res.body end
[ "def", "url_get_html", "(", "url_str", ")", "url", "=", "URI", ".", "parse", "(", "URI", ".", "encode", "(", "url_str", ")", ")", "# first get total size", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "url", ".", "to_s", ")", "res", "=", "Net", "::", "HTTP", ".", "start", "(", "url", ".", "host", ",", "url", ".", "port", ")", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "res", ".", "body", "end" ]
Send url to get response
[ "Send", "url", "to", "get", "response" ]
ef95e1ad71140a7eaf9e2c65830d900f651bc184
https://github.com/BUEZE/taaze/blob/ef95e1ad71140a7eaf9e2c65830d900f651bc184/lib/taaze/comments.rb#L74-L79
6,505
BUEZE/taaze
lib/taaze/comments.rb
Taaze.TaazeComments.extract_comments
def extract_comments(content, user_id) # Json format~ # "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....", # "title":"", # "status":"C", # "stars":"5", # "prodId":"11100597685", # "titleMain":"行銷之神原一平全集(精裝版)", # "orgProdId":"11100597685", # "pkNo":"1000243977", # "mdf_time":"2015/10/15", # "crt_time":"2015/10/15" # # orgProdId -> bookID -> 11100597685 # title -> book title # content -> comment # comment_url # pkNo -> comment ID ->13313301 # # http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3 # co->comment ci->user data_arr = [] if content content.each do |cmtItem| data_hash_sub = Hash.new {} data_hash_sub['title'] = cmtItem['titleMain'] data_hash_sub['comment'] = cmtItem['content'] data_hash_sub['book_url'] = BOOK_URL + cmtItem['orgProdId'] url = MAIN_URL + 'co=' + cmtItem['pkNo'] + '&ci=' + user_id + '&cp=3' data_hash_sub['comment_url'] = url data_hash_sub['crt_time'] = cmtItem['crt_time'] data_arr.push(data_hash_sub) end else data_arr = [] end @comments_found ||= data_arr end
ruby
def extract_comments(content, user_id) # Json format~ # "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....", # "title":"", # "status":"C", # "stars":"5", # "prodId":"11100597685", # "titleMain":"行銷之神原一平全集(精裝版)", # "orgProdId":"11100597685", # "pkNo":"1000243977", # "mdf_time":"2015/10/15", # "crt_time":"2015/10/15" # # orgProdId -> bookID -> 11100597685 # title -> book title # content -> comment # comment_url # pkNo -> comment ID ->13313301 # # http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3 # co->comment ci->user data_arr = [] if content content.each do |cmtItem| data_hash_sub = Hash.new {} data_hash_sub['title'] = cmtItem['titleMain'] data_hash_sub['comment'] = cmtItem['content'] data_hash_sub['book_url'] = BOOK_URL + cmtItem['orgProdId'] url = MAIN_URL + 'co=' + cmtItem['pkNo'] + '&ci=' + user_id + '&cp=3' data_hash_sub['comment_url'] = url data_hash_sub['crt_time'] = cmtItem['crt_time'] data_arr.push(data_hash_sub) end else data_arr = [] end @comments_found ||= data_arr end
[ "def", "extract_comments", "(", "content", ",", "user_id", ")", "# Json format~", "# \"content\":\"勇氣就是熱誠,來自於我們對自己工作的自信心;.....\",", "# \"title\":\"\",", "# \"status\":\"C\",", "# \"stars\":\"5\",", "# \"prodId\":\"11100597685\",", "# \"titleMain\":\"行銷之神原一平全集(精裝版)\",", "# \"orgProdId\":\"11100597685\",", "# \"pkNo\":\"1000243977\",", "# \"mdf_time\":\"2015/10/15\",", "# \"crt_time\":\"2015/10/15\"", "#", "# orgProdId -> bookID -> 11100597685", "# title -> book title", "# content -> comment", "# comment_url", "# pkNo -> comment ID ->13313301", "#", "# http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3", "# co->comment ci->user", "data_arr", "=", "[", "]", "if", "content", "content", ".", "each", "do", "|", "cmtItem", "|", "data_hash_sub", "=", "Hash", ".", "new", "{", "}", "data_hash_sub", "[", "'title'", "]", "=", "cmtItem", "[", "'titleMain'", "]", "data_hash_sub", "[", "'comment'", "]", "=", "cmtItem", "[", "'content'", "]", "data_hash_sub", "[", "'book_url'", "]", "=", "BOOK_URL", "+", "cmtItem", "[", "'orgProdId'", "]", "url", "=", "MAIN_URL", "+", "'co='", "+", "cmtItem", "[", "'pkNo'", "]", "+", "'&ci='", "+", "user_id", "+", "'&cp=3'", "data_hash_sub", "[", "'comment_url'", "]", "=", "url", "data_hash_sub", "[", "'crt_time'", "]", "=", "cmtItem", "[", "'crt_time'", "]", "data_arr", ".", "push", "(", "data_hash_sub", ")", "end", "else", "data_arr", "=", "[", "]", "end", "@comments_found", "||=", "data_arr", "end" ]
Return the comments in the format specified in spec.
[ "Return", "the", "comments", "in", "the", "format", "specified", "in", "spec", "." ]
ef95e1ad71140a7eaf9e2c65830d900f651bc184
https://github.com/BUEZE/taaze/blob/ef95e1ad71140a7eaf9e2c65830d900f651bc184/lib/taaze/comments.rb#L82-L119
6,506
kukushkin/aerogel-core
lib/aerogel/core/db/model.rb
Model.ClassMethods.find!
def find!( *args ) raise_not_found_error_was = Mongoid.raise_not_found_error begin Mongoid.raise_not_found_error = true self.find( *args ) ensure Mongoid.raise_not_found_error = raise_not_found_error_was end end
ruby
def find!( *args ) raise_not_found_error_was = Mongoid.raise_not_found_error begin Mongoid.raise_not_found_error = true self.find( *args ) ensure Mongoid.raise_not_found_error = raise_not_found_error_was end end
[ "def", "find!", "(", "*", "args", ")", "raise_not_found_error_was", "=", "Mongoid", ".", "raise_not_found_error", "begin", "Mongoid", ".", "raise_not_found_error", "=", "true", "self", ".", "find", "(", "args", ")", "ensure", "Mongoid", ".", "raise_not_found_error", "=", "raise_not_found_error_was", "end", "end" ]
Finds document by id. Raises error if document is not found.
[ "Finds", "document", "by", "id", ".", "Raises", "error", "if", "document", "is", "not", "found", "." ]
e156af6b237c410c1ee75e5cdf1b10075e7fbb8b
https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/db/model.rb#L19-L27
6,507
NU-CBITS/think_feel_do_dashboard
app/helpers/think_feel_do_dashboard/application_helper.rb
ThinkFeelDoDashboard.ApplicationHelper.breadcrumbs
def breadcrumbs return unless show_breadcrumbs? content_for( :breadcrumbs, content_tag(:ol, class: "breadcrumb") do concat(content_tag(:li, link_to("Home", root_path))) if can_view_resource_index? concat( content_tag( :li, controller_link ) ) end end ) end
ruby
def breadcrumbs return unless show_breadcrumbs? content_for( :breadcrumbs, content_tag(:ol, class: "breadcrumb") do concat(content_tag(:li, link_to("Home", root_path))) if can_view_resource_index? concat( content_tag( :li, controller_link ) ) end end ) end
[ "def", "breadcrumbs", "return", "unless", "show_breadcrumbs?", "content_for", "(", ":breadcrumbs", ",", "content_tag", "(", ":ol", ",", "class", ":", "\"breadcrumb\"", ")", "do", "concat", "(", "content_tag", "(", ":li", ",", "link_to", "(", "\"Home\"", ",", "root_path", ")", ")", ")", "if", "can_view_resource_index?", "concat", "(", "content_tag", "(", ":li", ",", "controller_link", ")", ")", "end", "end", ")", "end" ]
Render navigational information in the form of breadcrumbs
[ "Render", "navigational", "information", "in", "the", "form", "of", "breadcrumbs" ]
ff88b539d18a41b71fb93187607d74039f87215a
https://github.com/NU-CBITS/think_feel_do_dashboard/blob/ff88b539d18a41b71fb93187607d74039f87215a/app/helpers/think_feel_do_dashboard/application_helper.rb#L8-L25
6,508
grandcloud/sndacs-ruby
lib/sndacs/bucket.rb
Sndacs.Bucket.put_bucket_policy
def put_bucket_policy(bucket_policy) if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != '' bucket_request(:put,:body => bucket_policy,:subresource=>"policy") true else false end end
ruby
def put_bucket_policy(bucket_policy) if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != '' bucket_request(:put,:body => bucket_policy,:subresource=>"policy") true else false end end
[ "def", "put_bucket_policy", "(", "bucket_policy", ")", "if", "bucket_policy", "&&", "bucket_policy", ".", "is_a?", "(", "String", ")", "&&", "bucket_policy", ".", "strip", "!=", "''", "bucket_request", "(", ":put", ",", ":body", "=>", "bucket_policy", ",", ":subresource", "=>", "\"policy\"", ")", "true", "else", "false", "end", "end" ]
Set bucket policy for the given bucket
[ "Set", "bucket", "policy", "for", "the", "given", "bucket" ]
4565e926473e3af9df2ae17f728c423662ca750a
https://github.com/grandcloud/sndacs-ruby/blob/4565e926473e3af9df2ae17f728c423662ca750a/lib/sndacs/bucket.rb#L66-L73
6,509
codescrum/bebox
lib/bebox/wizards/profile_wizard.rb
Bebox.ProfileWizard.create_new_profile
def create_new_profile(project_root, profile_name, profile_base_path) # Clean the profile_path to make it a valid path profile_base_path = Bebox::Profile.cleanpath(profile_base_path) # Check if the profile name is valid return unless name_valid?(profile_name, profile_base_path) # Check if the profile exist profile_path = profile_base_path.empty? ? profile_name : profile_complete_path(profile_base_path, profile_name) return error(_('wizard.profile.name_exist')%{profile: profile_path}) if profile_exists?(project_root, profile_path) # Profile creation profile = Bebox::Profile.new(profile_name, project_root, profile_base_path) output = profile.create ok _('wizard.profile.creation_success')%{profile: profile_path} return output end
ruby
def create_new_profile(project_root, profile_name, profile_base_path) # Clean the profile_path to make it a valid path profile_base_path = Bebox::Profile.cleanpath(profile_base_path) # Check if the profile name is valid return unless name_valid?(profile_name, profile_base_path) # Check if the profile exist profile_path = profile_base_path.empty? ? profile_name : profile_complete_path(profile_base_path, profile_name) return error(_('wizard.profile.name_exist')%{profile: profile_path}) if profile_exists?(project_root, profile_path) # Profile creation profile = Bebox::Profile.new(profile_name, project_root, profile_base_path) output = profile.create ok _('wizard.profile.creation_success')%{profile: profile_path} return output end
[ "def", "create_new_profile", "(", "project_root", ",", "profile_name", ",", "profile_base_path", ")", "# Clean the profile_path to make it a valid path", "profile_base_path", "=", "Bebox", "::", "Profile", ".", "cleanpath", "(", "profile_base_path", ")", "# Check if the profile name is valid", "return", "unless", "name_valid?", "(", "profile_name", ",", "profile_base_path", ")", "# Check if the profile exist", "profile_path", "=", "profile_base_path", ".", "empty?", "?", "profile_name", ":", "profile_complete_path", "(", "profile_base_path", ",", "profile_name", ")", "return", "error", "(", "_", "(", "'wizard.profile.name_exist'", ")", "%", "{", "profile", ":", "profile_path", "}", ")", "if", "profile_exists?", "(", "project_root", ",", "profile_path", ")", "# Profile creation", "profile", "=", "Bebox", "::", "Profile", ".", "new", "(", "profile_name", ",", "project_root", ",", "profile_base_path", ")", "output", "=", "profile", ".", "create", "ok", "_", "(", "'wizard.profile.creation_success'", ")", "%", "{", "profile", ":", "profile_path", "}", "return", "output", "end" ]
Create a new profile
[ "Create", "a", "new", "profile" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L8-L21
6,510
codescrum/bebox
lib/bebox/wizards/profile_wizard.rb
Bebox.ProfileWizard.name_valid?
def name_valid?(profile_name, profile_base_path) unless valid_puppet_class_name?(profile_name) error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} return false end return true if profile_base_path.empty? # Check if the path name is valid unless Bebox::Profile.valid_pathname?(profile_base_path) error _('wizard.profile.invalid_path')%{words: Bebox::RESERVED_WORDS.join(', ')} return false end true end
ruby
def name_valid?(profile_name, profile_base_path) unless valid_puppet_class_name?(profile_name) error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} return false end return true if profile_base_path.empty? # Check if the path name is valid unless Bebox::Profile.valid_pathname?(profile_base_path) error _('wizard.profile.invalid_path')%{words: Bebox::RESERVED_WORDS.join(', ')} return false end true end
[ "def", "name_valid?", "(", "profile_name", ",", "profile_base_path", ")", "unless", "valid_puppet_class_name?", "(", "profile_name", ")", "error", "_", "(", "'wizard.profile.invalid_name'", ")", "%", "{", "words", ":", "Bebox", "::", "RESERVED_WORDS", ".", "join", "(", "', '", ")", "}", "return", "false", "end", "return", "true", "if", "profile_base_path", ".", "empty?", "# Check if the path name is valid", "unless", "Bebox", "::", "Profile", ".", "valid_pathname?", "(", "profile_base_path", ")", "error", "_", "(", "'wizard.profile.invalid_path'", ")", "%", "{", "words", ":", "Bebox", "::", "RESERVED_WORDS", ".", "join", "(", "', '", ")", "}", "return", "false", "end", "true", "end" ]
Check if the profile name is valid
[ "Check", "if", "the", "profile", "name", "is", "valid" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L24-L36
6,511
codescrum/bebox
lib/bebox/wizards/profile_wizard.rb
Bebox.ProfileWizard.remove_profile
def remove_profile(project_root) # Choose a profile from the availables profiles = Bebox::Profile.list(project_root) # Get a profile if exist if profiles.count > 0 profile = choose_option(profiles, _('wizard.choose_remove_profile')) else return error _('wizard.profile.no_deletion_profiles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion')) # Profile deletion profile_name = profile.split('/').last profile_base_path = profile.split('/')[0...-1].join('/') profile = Bebox::Profile.new(profile_name, project_root, profile_base_path) output = profile.remove ok _('wizard.profile.deletion_success') return output end
ruby
def remove_profile(project_root) # Choose a profile from the availables profiles = Bebox::Profile.list(project_root) # Get a profile if exist if profiles.count > 0 profile = choose_option(profiles, _('wizard.choose_remove_profile')) else return error _('wizard.profile.no_deletion_profiles') end # Ask for deletion confirmation return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion')) # Profile deletion profile_name = profile.split('/').last profile_base_path = profile.split('/')[0...-1].join('/') profile = Bebox::Profile.new(profile_name, project_root, profile_base_path) output = profile.remove ok _('wizard.profile.deletion_success') return output end
[ "def", "remove_profile", "(", "project_root", ")", "# Choose a profile from the availables", "profiles", "=", "Bebox", "::", "Profile", ".", "list", "(", "project_root", ")", "# Get a profile if exist", "if", "profiles", ".", "count", ">", "0", "profile", "=", "choose_option", "(", "profiles", ",", "_", "(", "'wizard.choose_remove_profile'", ")", ")", "else", "return", "error", "_", "(", "'wizard.profile.no_deletion_profiles'", ")", "end", "# Ask for deletion confirmation", "return", "warn", "(", "_", "(", "'wizard.no_changes'", ")", ")", "unless", "confirm_action?", "(", "_", "(", "'wizard.profile.confirm_deletion'", ")", ")", "# Profile deletion", "profile_name", "=", "profile", ".", "split", "(", "'/'", ")", ".", "last", "profile_base_path", "=", "profile", ".", "split", "(", "'/'", ")", "[", "0", "...", "-", "1", "]", ".", "join", "(", "'/'", ")", "profile", "=", "Bebox", "::", "Profile", ".", "new", "(", "profile_name", ",", "project_root", ",", "profile_base_path", ")", "output", "=", "profile", ".", "remove", "ok", "_", "(", "'wizard.profile.deletion_success'", ")", "return", "output", "end" ]
Removes an existing profile
[ "Removes", "an", "existing", "profile" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L39-L57
6,512
inside-track/remi
lib/remi/data_subject.rb
Remi.DataSubject.field_symbolizer
def field_symbolizer(arg = nil) return @field_symbolizer unless arg @field_symbolizer = if arg.is_a? Symbol Remi::FieldSymbolizers[arg] else arg end end
ruby
def field_symbolizer(arg = nil) return @field_symbolizer unless arg @field_symbolizer = if arg.is_a? Symbol Remi::FieldSymbolizers[arg] else arg end end
[ "def", "field_symbolizer", "(", "arg", "=", "nil", ")", "return", "@field_symbolizer", "unless", "arg", "@field_symbolizer", "=", "if", "arg", ".", "is_a?", "Symbol", "Remi", "::", "FieldSymbolizers", "[", "arg", "]", "else", "arg", "end", "end" ]
Field symbolizer used to convert field names into symbols. This method sets the symbolizer for the data subject and also sets the symbolizers for any associated parser and encoders. @return [Proc] the method for symbolizing field names
[ "Field", "symbolizer", "used", "to", "convert", "field", "names", "into", "symbols", ".", "This", "method", "sets", "the", "symbolizer", "for", "the", "data", "subject", "and", "also", "sets", "the", "symbolizers", "for", "any", "associated", "parser", "and", "encoders", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subject.rb#L56-L63
6,513
inside-track/remi
lib/remi/data_subject.rb
Remi.DataSubject.df=
def df=(new_dataframe) dsl_eval if new_dataframe.respond_to? :df_type @dataframe = new_dataframe else @dataframe = Remi::DataFrame.create(df_type, new_dataframe) end end
ruby
def df=(new_dataframe) dsl_eval if new_dataframe.respond_to? :df_type @dataframe = new_dataframe else @dataframe = Remi::DataFrame.create(df_type, new_dataframe) end end
[ "def", "df", "=", "(", "new_dataframe", ")", "dsl_eval", "if", "new_dataframe", ".", "respond_to?", ":df_type", "@dataframe", "=", "new_dataframe", "else", "@dataframe", "=", "Remi", "::", "DataFrame", ".", "create", "(", "df_type", ",", "new_dataframe", ")", "end", "end" ]
Reassigns the dataframe associated with this DataSubject. @param new_dataframe [Object] The new dataframe object to be associated. @return [Remi::DataFrame] the associated dataframe
[ "Reassigns", "the", "dataframe", "associated", "with", "this", "DataSubject", "." ]
f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7
https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subject.rb#L74-L81
6,514
jinx/core
lib/jinx/helpers/multi_enumerator.rb
Jinx.MultiEnumerator.method_missing
def method_missing(symbol, *args) self.class.new(@components.map { |enum|enum.send(symbol, *args) }) end
ruby
def method_missing(symbol, *args) self.class.new(@components.map { |enum|enum.send(symbol, *args) }) end
[ "def", "method_missing", "(", "symbol", ",", "*", "args", ")", "self", ".", "class", ".", "new", "(", "@components", ".", "map", "{", "|", "enum", "|", "enum", ".", "send", "(", "symbol", ",", "args", ")", "}", ")", "end" ]
Returns the union of the results of calling the given method symbol on each component.
[ "Returns", "the", "union", "of", "the", "results", "of", "calling", "the", "given", "method", "symbol", "on", "each", "component", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/multi_enumerator.rb#L43-L45
6,515
itisnotdone/gogetit
lib/providers/lxd.rb
Gogetit.GogetLXD.generate_user_data
def generate_user_data(lxd_params, options) logger.info("Calling <#{__method__.to_s}>") lxd_params[:config] = {} if options[:'no-maas'] lxd_params[:config][:"user.user-data"] = {} else sshkeys = maas.get_sshkeys pkg_repos = maas.get_package_repos lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] } sshkeys.each do |key| lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key']) end pkg_repos.each do |repo| if repo['name'] == 'main_archive' lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url'] end end lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias] lxd_params[:config][:"user.user-data"]['maas'] = true end if options[:'maas-on-lxc'] lxd_params[:config][:"security.privileged"] = "true" end if options[:'lxd-in-lxd'] lxd_params[:config][:"security.privileged"] = "true" lxd_params[:config][:"security.nesting"] = "true" end if options[:'kvm-in-lxd'] lxd_params[:config][:"security.nesting"] = "true" lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock" end lxd_params[:config][:"user.user-data"]['gogetit'] = true # To disable to update apt database on first boot # so chef client can keep doing its job. lxd_params[:config][:'user.user-data']['package_update'] = false lxd_params[:config][:'user.user-data']['package_upgrade'] = false lxd_params[:config][:'user.user-data'] = generate_cloud_init_config( options, config, lxd_params[:config][:'user.user-data'] ) lxd_params[:config][:"user.user-data"] = \ "#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1] return lxd_params end
ruby
def generate_user_data(lxd_params, options) logger.info("Calling <#{__method__.to_s}>") lxd_params[:config] = {} if options[:'no-maas'] lxd_params[:config][:"user.user-data"] = {} else sshkeys = maas.get_sshkeys pkg_repos = maas.get_package_repos lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] } sshkeys.each do |key| lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key']) end pkg_repos.each do |repo| if repo['name'] == 'main_archive' lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url'] end end lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias] lxd_params[:config][:"user.user-data"]['maas'] = true end if options[:'maas-on-lxc'] lxd_params[:config][:"security.privileged"] = "true" end if options[:'lxd-in-lxd'] lxd_params[:config][:"security.privileged"] = "true" lxd_params[:config][:"security.nesting"] = "true" end if options[:'kvm-in-lxd'] lxd_params[:config][:"security.nesting"] = "true" lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock" end lxd_params[:config][:"user.user-data"]['gogetit'] = true # To disable to update apt database on first boot # so chef client can keep doing its job. lxd_params[:config][:'user.user-data']['package_update'] = false lxd_params[:config][:'user.user-data']['package_upgrade'] = false lxd_params[:config][:'user.user-data'] = generate_cloud_init_config( options, config, lxd_params[:config][:'user.user-data'] ) lxd_params[:config][:"user.user-data"] = \ "#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1] return lxd_params end
[ "def", "generate_user_data", "(", "lxd_params", ",", "options", ")", "logger", ".", "info", "(", "\"Calling <#{__method__.to_s}>\"", ")", "lxd_params", "[", ":config", "]", "=", "{", "}", "if", "options", "[", ":'", "'", "]", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "{", "}", "else", "sshkeys", "=", "maas", ".", "get_sshkeys", "pkg_repos", "=", "maas", ".", "get_package_repos", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "=", "{", "'ssh_authorized_keys'", "=>", "[", "]", "}", "sshkeys", ".", "each", "do", "|", "key", "|", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "[", "'ssh_authorized_keys'", "]", ".", "push", "(", "key", "[", "'key'", "]", ")", "end", "pkg_repos", ".", "each", "do", "|", "repo", "|", "if", "repo", "[", "'name'", "]", "==", "'main_archive'", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "[", "'apt_mirror'", "]", "=", "repo", "[", "'url'", "]", "end", "end", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "[", "'source_image_alias'", "]", "=", "lxd_params", "[", ":alias", "]", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "[", "'maas'", "]", "=", "true", "end", "if", "options", "[", ":'", "'", "]", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"true\"", "end", "if", "options", "[", ":'", "'", "]", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"true\"", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"true\"", "end", "if", "options", "[", ":'", "'", "]", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"true\"", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock\"", "end", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "[", "'gogetit'", "]", "=", "true", "# To disable to update apt database on first boot", "# so chef client can keep doing its job.", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "[", "'package_update'", "]", "=", "false", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "[", "'package_upgrade'", "]", "=", "false", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", "=", "generate_cloud_init_config", "(", "options", ",", "config", ",", "lxd_params", "[", ":config", "]", "[", ":'", "'", "]", ")", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", "=", "\"#cloud-config\\n\"", "+", "YAML", ".", "dump", "(", "lxd_params", "[", ":config", "]", "[", ":\"", "\"", "]", ")", "[", "4", "..", "-", "1", "]", "return", "lxd_params", "end" ]
to generate 'user.user-data'
[ "to", "generate", "user", ".", "user", "-", "data" ]
62628c04c0310567178c4738aa5b64645ed5c4bd
https://github.com/itisnotdone/gogetit/blob/62628c04c0310567178c4738aa5b64645ed5c4bd/lib/providers/lxd.rb#L49-L107
6,516
mintdigital/pyrite
lib/pyrite/dsl.rb
Pyrite.Dsl.fill_in
def fill_in(element, value) if element.match /date/ # Try to guess at date selects select_date(element, value) else browser.type("jquery=#{element}", value) end end
ruby
def fill_in(element, value) if element.match /date/ # Try to guess at date selects select_date(element, value) else browser.type("jquery=#{element}", value) end end
[ "def", "fill_in", "(", "element", ",", "value", ")", "if", "element", ".", "match", "/", "/", "# Try to guess at date selects", "select_date", "(", "element", ",", "value", ")", "else", "browser", ".", "type", "(", "\"jquery=#{element}\"", ",", "value", ")", "end", "end" ]
Fill in a form field
[ "Fill", "in", "a", "form", "field" ]
acba5d6b460e4262b29be522a0bde0c29ef14cb1
https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L5-L11
6,517
mintdigital/pyrite
lib/pyrite/dsl.rb
Pyrite.Dsl.select_date
def select_date(element, value) suffixes = { :year => '1i', :month => '2i', :day => '3i', :hour => '4i', :minute => '5i' } date = value.respond_to?(:year) ? value : Date.parse(value) browser.select "jquery=#{element}_#{suffixes[:year]}", date.year browser.select "jquery=#{element}_#{suffixes[:month]}", date.strftime('%B') browser.select "jquery=#{element}_#{suffixes[:day]}", date.day end
ruby
def select_date(element, value) suffixes = { :year => '1i', :month => '2i', :day => '3i', :hour => '4i', :minute => '5i' } date = value.respond_to?(:year) ? value : Date.parse(value) browser.select "jquery=#{element}_#{suffixes[:year]}", date.year browser.select "jquery=#{element}_#{suffixes[:month]}", date.strftime('%B') browser.select "jquery=#{element}_#{suffixes[:day]}", date.day end
[ "def", "select_date", "(", "element", ",", "value", ")", "suffixes", "=", "{", ":year", "=>", "'1i'", ",", ":month", "=>", "'2i'", ",", ":day", "=>", "'3i'", ",", ":hour", "=>", "'4i'", ",", ":minute", "=>", "'5i'", "}", "date", "=", "value", ".", "respond_to?", "(", ":year", ")", "?", "value", ":", "Date", ".", "parse", "(", "value", ")", "browser", ".", "select", "\"jquery=#{element}_#{suffixes[:year]}\"", ",", "date", ".", "year", "browser", ".", "select", "\"jquery=#{element}_#{suffixes[:month]}\"", ",", "date", ".", "strftime", "(", "'%B'", ")", "browser", ".", "select", "\"jquery=#{element}_#{suffixes[:day]}\"", ",", "date", ".", "day", "end" ]
Fill in a Rails-ish set of date_select fields
[ "Fill", "in", "a", "Rails", "-", "ish", "set", "of", "date_select", "fields" ]
acba5d6b460e4262b29be522a0bde0c29ef14cb1
https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L14-L26
6,518
mintdigital/pyrite
lib/pyrite/dsl.rb
Pyrite.Dsl.wait_for
def wait_for(element) case element when :page_load browser.wait_for(:wait_for => :page) when :ajax browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework) else browser.wait_for(:element => "jquery=#{element}") end end
ruby
def wait_for(element) case element when :page_load browser.wait_for(:wait_for => :page) when :ajax browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework) else browser.wait_for(:element => "jquery=#{element}") end end
[ "def", "wait_for", "(", "element", ")", "case", "element", "when", ":page_load", "browser", ".", "wait_for", "(", ":wait_for", "=>", ":page", ")", "when", ":ajax", "browser", ".", "wait_for", "(", ":wait_for", "=>", ":ajax", ",", ":javascript_framework", "=>", "Pyrite", ".", "js_framework", ")", "else", "browser", ".", "wait_for", "(", ":element", "=>", "\"jquery=#{element}\"", ")", "end", "end" ]
Wait for a specific element, the page to load or an AJAX request to return
[ "Wait", "for", "a", "specific", "element", "the", "page", "to", "load", "or", "an", "AJAX", "request", "to", "return" ]
acba5d6b460e4262b29be522a0bde0c29ef14cb1
https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L61-L70
6,519
Bottega8/maguro
lib/maguro/features.rb
Maguro.Features.create_database_files
def create_database_files username = builder.options['database-username'] password = builder.options['database-password'] builder.remove_file "config/database.yml" create_database_yml_file("config/database.sample.yml", "username", "pass") create_database_yml_file("config/database.yml", username, password) end
ruby
def create_database_files username = builder.options['database-username'] password = builder.options['database-password'] builder.remove_file "config/database.yml" create_database_yml_file("config/database.sample.yml", "username", "pass") create_database_yml_file("config/database.yml", username, password) end
[ "def", "create_database_files", "username", "=", "builder", ".", "options", "[", "'database-username'", "]", "password", "=", "builder", ".", "options", "[", "'database-password'", "]", "builder", ".", "remove_file", "\"config/database.yml\"", "create_database_yml_file", "(", "\"config/database.sample.yml\"", ",", "\"username\"", ",", "\"pass\"", ")", "create_database_yml_file", "(", "\"config/database.yml\"", ",", "username", ",", "password", ")", "end" ]
create a new database.yml that works with PG.
[ "create", "a", "new", "database", ".", "yml", "that", "works", "with", "PG", "." ]
9bfff4e3a9e823d57d55f86394dcb9353fd8205e
https://github.com/Bottega8/maguro/blob/9bfff4e3a9e823d57d55f86394dcb9353fd8205e/lib/maguro/features.rb#L165-L172
6,520
SwagDevOps/kamaze-project
lib/kamaze/project/concern/observable.rb
Kamaze::Project::Concern::Observable.ClassMethods.add_observer
def add_observer(observer_class, func = :handle_event) func = func.to_sym unless observer_class.instance_methods.include?(func) m = "#<#{observer_class}> does not respond to `#{func}'" raise NoMethodError, m end observer_peers[observer_class] = func self end
ruby
def add_observer(observer_class, func = :handle_event) func = func.to_sym unless observer_class.instance_methods.include?(func) m = "#<#{observer_class}> does not respond to `#{func}'" raise NoMethodError, m end observer_peers[observer_class] = func self end
[ "def", "add_observer", "(", "observer_class", ",", "func", "=", ":handle_event", ")", "func", "=", "func", ".", "to_sym", "unless", "observer_class", ".", "instance_methods", ".", "include?", "(", "func", ")", "m", "=", "\"#<#{observer_class}> does not respond to `#{func}'\"", "raise", "NoMethodError", ",", "m", "end", "observer_peers", "[", "observer_class", "]", "=", "func", "self", "end" ]
Add observer. @param [Class] observer_class @return [self]
[ "Add", "observer", "." ]
a0451ff204ed3072c1d6ae980811a32b3eb50345
https://github.com/SwagDevOps/kamaze-project/blob/a0451ff204ed3072c1d6ae980811a32b3eb50345/lib/kamaze/project/concern/observable.rb#L58-L69
6,521
tatemae/muck-engine
lib/muck-engine/controllers/ssl_requirement.rb
MuckEngine.SslRequirement.ssl_required?
def ssl_required? return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL'] return false if local_request? return false if RAILS_ENV == 'test' ((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Rails.env == 'staging') end
ruby
def ssl_required? return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL'] return false if local_request? return false if RAILS_ENV == 'test' ((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Rails.env == 'staging') end
[ "def", "ssl_required?", "return", "ENV", "[", "'SSL'", "]", "==", "'on'", "?", "true", ":", "false", "if", "defined?", "ENV", "[", "'SSL'", "]", "return", "false", "if", "local_request?", "return", "false", "if", "RAILS_ENV", "==", "'test'", "(", "(", "self", ".", "class", ".", "read_inheritable_attribute", "(", ":ssl_required_actions", ")", "||", "[", "]", ")", ".", "include?", "(", "action_name", ".", "to_sym", ")", ")", "&&", "(", "::", "Rails", ".", "env", "==", "'production'", "||", "::", "Rails", ".", "env", "==", "'staging'", ")", "end" ]
Only require ssl if we are in production
[ "Only", "require", "ssl", "if", "we", "are", "in", "production" ]
41fc072dce3a365b3ce4a73d4f60a4ff24026d51
https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/controllers/ssl_requirement.rb#L24-L29
6,522
seblindberg/ruby-rooted_tree
lib/rooted_tree/node.rb
RootedTree.Node.ancestors
def ancestors return to_enum(__callee__) unless block_given? node = self loop do node = node.parent yield node end end
ruby
def ancestors return to_enum(__callee__) unless block_given? node = self loop do node = node.parent yield node end end
[ "def", "ancestors", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "node", "=", "self", "loop", "do", "node", "=", "node", ".", "parent", "yield", "node", "end", "end" ]
Iterates over the nodes above this in the tree hierarchy and yields them to a block. If no block is given an enumerator is returned. @yield [Node] each parent node. @return [Enumerator] if no block is given.
[ "Iterates", "over", "the", "nodes", "above", "this", "in", "the", "tree", "hierarchy", "and", "yields", "them", "to", "a", "block", ".", "If", "no", "block", "is", "given", "an", "enumerator", "is", "returned", "." ]
59013fc0fd59f137b5e40d86c49afe08ea678941
https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L109-L116
6,523
seblindberg/ruby-rooted_tree
lib/rooted_tree/node.rb
RootedTree.Node.child
def child(index = nil) unless index raise ArgumentError, 'No index for node with degree != 1' if degree != 1 return first end rtl, index = wrap_index index raise RangeError, 'Child index out of range' if index >= degree children(rtl: rtl).each do |c| break c if index.zero? index -= 1 end end
ruby
def child(index = nil) unless index raise ArgumentError, 'No index for node with degree != 1' if degree != 1 return first end rtl, index = wrap_index index raise RangeError, 'Child index out of range' if index >= degree children(rtl: rtl).each do |c| break c if index.zero? index -= 1 end end
[ "def", "child", "(", "index", "=", "nil", ")", "unless", "index", "raise", "ArgumentError", ",", "'No index for node with degree != 1'", "if", "degree", "!=", "1", "return", "first", "end", "rtl", ",", "index", "=", "wrap_index", "index", "raise", "RangeError", ",", "'Child index out of range'", "if", "index", ">=", "degree", "children", "(", "rtl", ":", "rtl", ")", ".", "each", "do", "|", "c", "|", "break", "c", "if", "index", ".", "zero?", "index", "-=", "1", "end", "end" ]
Accessor method for any of the n children under this node. If called without an argument and the node has anything but exactly one child an exception will be raised. @param index [Integer] the n:th child to be returned. If the index is negative the indexing will be reversed and the children counted from the last to the first. @return [Node] the child at the n:th index.
[ "Accessor", "method", "for", "any", "of", "the", "n", "children", "under", "this", "node", ".", "If", "called", "without", "an", "argument", "and", "the", "node", "has", "anything", "but", "exactly", "one", "child", "an", "exception", "will", "be", "raised", "." ]
59013fc0fd59f137b5e40d86c49afe08ea678941
https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L139-L153
6,524
seblindberg/ruby-rooted_tree
lib/rooted_tree/node.rb
RootedTree.Node.edges
def edges(&block) return to_enum(__callee__) unless block_given? children do |v| yield self, v v.edges(&block) end end
ruby
def edges(&block) return to_enum(__callee__) unless block_given? children do |v| yield self, v v.edges(&block) end end
[ "def", "edges", "(", "&", "block", ")", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "children", "do", "|", "v", "|", "yield", "self", ",", "v", "v", ".", "edges", "(", "block", ")", "end", "end" ]
Iterates over each edge in the tree. @yield [Array<Node>] each connected node pair. @return [Enumerator] if no block is given.
[ "Iterates", "over", "each", "edge", "in", "the", "tree", "." ]
59013fc0fd59f137b5e40d86c49afe08ea678941
https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L200-L207
6,525
seblindberg/ruby-rooted_tree
lib/rooted_tree/node.rb
RootedTree.Node.+
def +(other) unless root? && other.root? raise StructureException, 'Only roots can be added' end a = frozen? ? dup : self b = other.frozen? ? other.dup : other ab = self.class.new ab << a << b end
ruby
def +(other) unless root? && other.root? raise StructureException, 'Only roots can be added' end a = frozen? ? dup : self b = other.frozen? ? other.dup : other ab = self.class.new ab << a << b end
[ "def", "+", "(", "other", ")", "unless", "root?", "&&", "other", ".", "root?", "raise", "StructureException", ",", "'Only roots can be added'", "end", "a", "=", "frozen?", "?", "dup", ":", "self", "b", "=", "other", ".", "frozen?", "?", "other", ".", "dup", ":", "other", "ab", "=", "self", ".", "class", ".", "new", "ab", "<<", "a", "<<", "b", "end" ]
Add two roots together to create a larger tree. A new common root will be created and returned. Note that if the any of the root nodes are not frozen they will be modified, and as a result seize to be roots. @param other [Node] a Node-like object that responds true to #root? @return [Node] a new root with the two nodes as children.
[ "Add", "two", "roots", "together", "to", "create", "a", "larger", "tree", ".", "A", "new", "common", "root", "will", "be", "created", "and", "returned", ".", "Note", "that", "if", "the", "any", "of", "the", "root", "nodes", "are", "not", "frozen", "they", "will", "be", "modified", "and", "as", "a", "result", "seize", "to", "be", "roots", "." ]
59013fc0fd59f137b5e40d86c49afe08ea678941
https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L215-L225
6,526
Dev-Crea/swagger-docs-generator
lib/swagger_docs_generator/methods.rb
SwaggerDocsGenerator.Methods.swagger_doc
def swagger_doc(action, &block) parse = ParserAction.new(action, &block) parse.adding_path end
ruby
def swagger_doc(action, &block) parse = ParserAction.new(action, &block) parse.adding_path end
[ "def", "swagger_doc", "(", "action", ",", "&", "block", ")", "parse", "=", "ParserAction", ".", "new", "(", "action", ",", "block", ")", "parse", ".", "adding_path", "end" ]
Complete json file with datas to method and controller. Each action to controller is writing in temporary file.
[ "Complete", "json", "file", "with", "datas", "to", "method", "and", "controller", ".", "Each", "action", "to", "controller", "is", "writing", "in", "temporary", "file", "." ]
5d3de176aa1119cb38100b451bee028d66c0809d
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/methods.rb#L18-L21
6,527
Dev-Crea/swagger-docs-generator
lib/swagger_docs_generator/methods.rb
SwaggerDocsGenerator.Methods.swagger_definition
def swagger_definition(name, &block) parse = ParserDefinition.new(name, &block) parse.adding_definition end
ruby
def swagger_definition(name, &block) parse = ParserDefinition.new(name, &block) parse.adding_definition end
[ "def", "swagger_definition", "(", "name", ",", "&", "block", ")", "parse", "=", "ParserDefinition", ".", "new", "(", "name", ",", "block", ")", "parse", ".", "adding_definition", "end" ]
Complete definitions objects for each controller.
[ "Complete", "definitions", "objects", "for", "each", "controller", "." ]
5d3de176aa1119cb38100b451bee028d66c0809d
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/methods.rb#L24-L27
6,528
avdgaag/whenner
lib/whenner/conversions.rb
Whenner.Conversions.Promise
def Promise(obj) return obj.to_promise if obj.respond_to?(:to_promise) Deferred.new.fulfill(obj) end
ruby
def Promise(obj) return obj.to_promise if obj.respond_to?(:to_promise) Deferred.new.fulfill(obj) end
[ "def", "Promise", "(", "obj", ")", "return", "obj", ".", "to_promise", "if", "obj", ".", "respond_to?", "(", ":to_promise", ")", "Deferred", ".", "new", ".", "fulfill", "(", "obj", ")", "end" ]
Convert any object to a promise. When the object in question responds to `to_promise`, the result of that method will be returned. If not, a new deferred object is created and immediately fulfilled with the given object. @param [Object] obj @return [Promise]
[ "Convert", "any", "object", "to", "a", "promise", ".", "When", "the", "object", "in", "question", "responds", "to", "to_promise", "the", "result", "of", "that", "method", "will", "be", "returned", ".", "If", "not", "a", "new", "deferred", "object", "is", "created", "and", "immediately", "fulfilled", "with", "the", "given", "object", "." ]
f27331435402648d02377bef9fce9ff8ae84845a
https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/conversions.rb#L12-L15
6,529
DigitPaint/roger_eslint
lib/roger_eslint/lint.rb
RogerEslint.Lint.normalize_path
def normalize_path(test, path) Pathname.new(path).relative_path_from(test.project.path.realpath).to_s end
ruby
def normalize_path(test, path) Pathname.new(path).relative_path_from(test.project.path.realpath).to_s end
[ "def", "normalize_path", "(", "test", ",", "path", ")", "Pathname", ".", "new", "(", "path", ")", ".", "relative_path_from", "(", "test", ".", "project", ".", "path", ".", "realpath", ")", ".", "to_s", "end" ]
Will make path relative to project dir @return [String] relative path
[ "Will", "make", "path", "relative", "to", "project", "dir" ]
8d14a44b12fba27c6df9fc5f71920fc6cdecbf3d
https://github.com/DigitPaint/roger_eslint/blob/8d14a44b12fba27c6df9fc5f71920fc6cdecbf3d/lib/roger_eslint/lint.rb#L156-L158
6,530
syborg/mme_tools
lib/mme_tools/args_proc.rb
MMETools.ArgsProc.assert_valid_keys
def assert_valid_keys(options, valid_options) unknown_keys = options.keys - valid_options.keys raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end
ruby
def assert_valid_keys(options, valid_options) unknown_keys = options.keys - valid_options.keys raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end
[ "def", "assert_valid_keys", "(", "options", ",", "valid_options", ")", "unknown_keys", "=", "options", ".", "keys", "-", "valid_options", ".", "keys", "raise", "(", "ArgumentError", ",", "\"Unknown options(s): #{unknown_keys.join(\", \")}\"", ")", "unless", "unknown_keys", ".", "empty?", "end" ]
Tests if +options+ includes only valid keys. Raises an error if any key is not included within +valid_options+. +valid_options+ is a Hash that must include all accepted keys. values aren't taken into account.
[ "Tests", "if", "+", "options", "+", "includes", "only", "valid", "keys", ".", "Raises", "an", "error", "if", "any", "key", "is", "not", "included", "within", "+", "valid_options", "+", ".", "+", "valid_options", "+", "is", "a", "Hash", "that", "must", "include", "all", "accepted", "keys", ".", "values", "aren", "t", "taken", "into", "account", "." ]
e93919f7fcfb408b941d6144290991a7feabaa7d
https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/args_proc.rb#L18-L21
6,531
mrackwitz/CLIntegracon
lib/CLIntegracon/formatter.rb
CLIntegracon.Formatter.describe_file_diff
def describe_file_diff(diff, max_width=80) description = [] description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:" description << "--- DIFF ".ljust(max_width, '-') description += diff.map do |line| case line when /^\+/ then line.green when /^-/ then line.red else line end.gsub("\n",'').gsub("\r", '\r') end description << "--- END ".ljust(max_width, '-') description << '' description * "\n" end
ruby
def describe_file_diff(diff, max_width=80) description = [] description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:" description << "--- DIFF ".ljust(max_width, '-') description += diff.map do |line| case line when /^\+/ then line.green when /^-/ then line.red else line end.gsub("\n",'').gsub("\r", '\r') end description << "--- END ".ljust(max_width, '-') description << '' description * "\n" end
[ "def", "describe_file_diff", "(", "diff", ",", "max_width", "=", "80", ")", "description", "=", "[", "]", "description", "<<", "\"File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:\"", "description", "<<", "\"--- DIFF \"", ".", "ljust", "(", "max_width", ",", "'-'", ")", "description", "+=", "diff", ".", "map", "do", "|", "line", "|", "case", "line", "when", "/", "\\+", "/", "then", "line", ".", "green", "when", "/", "/", "then", "line", ".", "red", "else", "line", "end", ".", "gsub", "(", "\"\\n\"", ",", "''", ")", ".", "gsub", "(", "\"\\r\"", ",", "'\\r'", ")", "end", "description", "<<", "\"--- END \"", ".", "ljust", "(", "max_width", ",", "'-'", ")", "description", "<<", "''", "description", "*", "\"\\n\"", "end" ]
Return a description text for an expectation that two files were expected to be the same, but are not. @param [Diff] diff the diff which holds the difference @param [Integer] max_width the max width of the terminal to print matching separators @return [String]
[ "Return", "a", "description", "text", "for", "an", "expectation", "that", "two", "files", "were", "expected", "to", "be", "the", "same", "but", "are", "not", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/formatter.rb#L145-L159
6,532
mohan/gitkite
app/controllers/gitkite/gitkit_controller.rb
Gitkite.GitkitController.sign_in_success
def sign_in_success g_user = signed_in? if g_user user = { :email => g_user.email, :user_id => g_user.user_id, :name => g_user.name, :photo_url => g_user.photo_url, :provider_id => g_user.provider_id } @user = User.find_by(user_id: user[:user_id]) if @user.nil? @user = User.create user else @user.update user end session[:user] = @user.id if session[:previous_url] previous_url = session[:previous_url] session.delete :previous_url redirect_to previous_url else redirect_to main_app.root_url end else @user = false session.delete :user flash.alert = "Sign in failed. Please try again." redirect_to gitkit_sign_in_url end end
ruby
def sign_in_success g_user = signed_in? if g_user user = { :email => g_user.email, :user_id => g_user.user_id, :name => g_user.name, :photo_url => g_user.photo_url, :provider_id => g_user.provider_id } @user = User.find_by(user_id: user[:user_id]) if @user.nil? @user = User.create user else @user.update user end session[:user] = @user.id if session[:previous_url] previous_url = session[:previous_url] session.delete :previous_url redirect_to previous_url else redirect_to main_app.root_url end else @user = false session.delete :user flash.alert = "Sign in failed. Please try again." redirect_to gitkit_sign_in_url end end
[ "def", "sign_in_success", "g_user", "=", "signed_in?", "if", "g_user", "user", "=", "{", ":email", "=>", "g_user", ".", "email", ",", ":user_id", "=>", "g_user", ".", "user_id", ",", ":name", "=>", "g_user", ".", "name", ",", ":photo_url", "=>", "g_user", ".", "photo_url", ",", ":provider_id", "=>", "g_user", ".", "provider_id", "}", "@user", "=", "User", ".", "find_by", "(", "user_id", ":", "user", "[", ":user_id", "]", ")", "if", "@user", ".", "nil?", "@user", "=", "User", ".", "create", "user", "else", "@user", ".", "update", "user", "end", "session", "[", ":user", "]", "=", "@user", ".", "id", "if", "session", "[", ":previous_url", "]", "previous_url", "=", "session", "[", ":previous_url", "]", "session", ".", "delete", ":previous_url", "redirect_to", "previous_url", "else", "redirect_to", "main_app", ".", "root_url", "end", "else", "@user", "=", "false", "session", ".", "delete", ":user", "flash", ".", "alert", "=", "\"Sign in failed. Please try again.\"", "redirect_to", "gitkit_sign_in_url", "end", "end" ]
This will be called after successfull signin
[ "This", "will", "be", "called", "after", "successfull", "signin" ]
c6ebefecdd44d1dfd30a41190e7661da877c091d
https://github.com/mohan/gitkite/blob/c6ebefecdd44d1dfd30a41190e7661da877c091d/app/controllers/gitkite/gitkit_controller.rb#L18-L54
6,533
codescrum/bebox
lib/bebox/files_helper.rb
Bebox.FilesHelper.render_erb_template
def render_erb_template(template_path, options) require 'tilt' Tilt::ERBTemplate.new(template_path).render(nil, options) end
ruby
def render_erb_template(template_path, options) require 'tilt' Tilt::ERBTemplate.new(template_path).render(nil, options) end
[ "def", "render_erb_template", "(", "template_path", ",", "options", ")", "require", "'tilt'", "Tilt", "::", "ERBTemplate", ".", "new", "(", "template_path", ")", ".", "render", "(", "nil", ",", "options", ")", "end" ]
Render a template for file content
[ "Render", "a", "template", "for", "file", "content" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/files_helper.rb#L15-L18
6,534
codescrum/bebox
lib/bebox/files_helper.rb
Bebox.FilesHelper.write_content_to_file
def write_content_to_file(file_path, content) File.open(file_path, 'w') do |f| f.write content end end
ruby
def write_content_to_file(file_path, content) File.open(file_path, 'w') do |f| f.write content end end
[ "def", "write_content_to_file", "(", "file_path", ",", "content", ")", "File", ".", "open", "(", "file_path", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "content", "end", "end" ]
Write content to a file
[ "Write", "content", "to", "a", "file" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/files_helper.rb#L21-L25
6,535
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/resources_api.rb
TriglavClient.ResourcesApi.create_resource
def create_resource(resource, opts = {}) data, _status_code, _headers = create_resource_with_http_info(resource, opts) return data end
ruby
def create_resource(resource, opts = {}) data, _status_code, _headers = create_resource_with_http_info(resource, opts) return data end
[ "def", "create_resource", "(", "resource", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_resource_with_http_info", "(", "resource", ",", "opts", ")", "return", "data", "end" ]
Creates a new resource @param resource Resource to add @param [Hash] opts the optional parameters @return [ResourceResponse]
[ "Creates", "a", "new", "resource" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L39-L42
6,536
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/resources_api.rb
TriglavClient.ResourcesApi.get_resource
def get_resource(id_or_uri, opts = {}) data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts) return data end
ruby
def get_resource(id_or_uri, opts = {}) data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts) return data end
[ "def", "get_resource", "(", "id_or_uri", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_resource_with_http_info", "(", "id_or_uri", ",", "opts", ")", "return", "data", "end" ]
Returns a single resource @param id_or_uri ID or URI of resource to fetch @param [Hash] opts the optional parameters @return [ResourceResponse]
[ "Returns", "a", "single", "resource" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L152-L155
6,537
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/resources_api.rb
TriglavClient.ResourcesApi.list_aggregated_resources
def list_aggregated_resources(uri_prefix, opts = {}) data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts) return data end
ruby
def list_aggregated_resources(uri_prefix, opts = {}) data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts) return data end
[ "def", "list_aggregated_resources", "(", "uri_prefix", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "list_aggregated_resources_with_http_info", "(", "uri_prefix", ",", "opts", ")", "return", "data", "end" ]
Returns aggregated resources to be monitored @param uri_prefix Prefix of Resource URI @param [Hash] opts the optional parameters @return [Array<AggregatedResourceEachResponse>]
[ "Returns", "aggregated", "resources", "to", "be", "monitored" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L209-L212
6,538
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/resources_api.rb
TriglavClient.ResourcesApi.update_resource
def update_resource(id_or_uri, resource, opts = {}) data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts) return data end
ruby
def update_resource(id_or_uri, resource, opts = {}) data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts) return data end
[ "def", "update_resource", "(", "id_or_uri", ",", "resource", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_resource_with_http_info", "(", "id_or_uri", ",", "resource", ",", "opts", ")", "return", "data", "end" ]
Updates a single resource @param id_or_uri ID or URI of resource to fetch @param resource Resource parameters to update @param [Hash] opts the optional parameters @return [ResourceResponse]
[ "Updates", "a", "single", "resource" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L324-L327
6,539
tnorthb/coinstack
lib/coinstack/list.rb
Coinstack.UserPair.add_list_data
def add_list_data(data) raise symbol.to_s if data.nil? self.exchange_rate = data['price_usd'].to_f self.perchant_change_week = data['percent_change_7d'].to_f self.perchant_change_day = data['percent_change_24h'].to_f end
ruby
def add_list_data(data) raise symbol.to_s if data.nil? self.exchange_rate = data['price_usd'].to_f self.perchant_change_week = data['percent_change_7d'].to_f self.perchant_change_day = data['percent_change_24h'].to_f end
[ "def", "add_list_data", "(", "data", ")", "raise", "symbol", ".", "to_s", "if", "data", ".", "nil?", "self", ".", "exchange_rate", "=", "data", "[", "'price_usd'", "]", ".", "to_f", "self", ".", "perchant_change_week", "=", "data", "[", "'percent_change_7d'", "]", ".", "to_f", "self", ".", "perchant_change_day", "=", "data", "[", "'percent_change_24h'", "]", ".", "to_f", "end" ]
Builds a UserPair given the related CMC data
[ "Builds", "a", "UserPair", "given", "the", "related", "CMC", "data" ]
1316fd069f502fa04fe15bc6ab7e63302aa29fd8
https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/list.rb#L87-L92
6,540
arvicco/poster
lib/poster/forum.rb
Poster.Forum.new_topic
def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation" board = board.instance_of?(Symbol) ? @opts[:boards][board] : board # Check board posting page first (to get sequence numbers) get "/index.php?action=post;board=#{board}.0" raise "Not logged, cannot post!" unless logged? p msg # Create new post seqnum, sc = find_fields 'seqnum', 'sc' subj = xml_encode(subj_encode(subj)) msg = xml_encode(msg) # p subj, msg # exit post "/index.php?action=post2;start=0;board=#{board}", content_type: 'multipart/form-data; charset=ISO-8859-1', body: { topic: 0, subject: subj, icon: icon, message: msg, notify: 0, do_watch: 0, selfmod: 0, lock: 0, goback: 1, ns: "NS", post: "Post", additional_options: 0, sc: sc, seqnum: seqnum }, options: {timeout: 5} # open/read timeout in seconds # Make sure the message was posted, return topic page new_topic = @response.headers['location'] # p @response.body raise "No redirect to posted topic!" unless new_topic && @response.status == 302 get new_topic end
ruby
def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation" board = board.instance_of?(Symbol) ? @opts[:boards][board] : board # Check board posting page first (to get sequence numbers) get "/index.php?action=post;board=#{board}.0" raise "Not logged, cannot post!" unless logged? p msg # Create new post seqnum, sc = find_fields 'seqnum', 'sc' subj = xml_encode(subj_encode(subj)) msg = xml_encode(msg) # p subj, msg # exit post "/index.php?action=post2;start=0;board=#{board}", content_type: 'multipart/form-data; charset=ISO-8859-1', body: { topic: 0, subject: subj, icon: icon, message: msg, notify: 0, do_watch: 0, selfmod: 0, lock: 0, goback: 1, ns: "NS", post: "Post", additional_options: 0, sc: sc, seqnum: seqnum }, options: {timeout: 5} # open/read timeout in seconds # Make sure the message was posted, return topic page new_topic = @response.headers['location'] # p @response.body raise "No redirect to posted topic!" unless new_topic && @response.status == 302 get new_topic end
[ "def", "new_topic", "board", ":", "92", ",", "subj", ":", "'test'", ",", "msg", ":", "'msg'", ",", "icon", ":", "\"exclamation\"", "board", "=", "board", ".", "instance_of?", "(", "Symbol", ")", "?", "@opts", "[", ":boards", "]", "[", "board", "]", ":", "board", "# Check board posting page first (to get sequence numbers)", "get", "\"/index.php?action=post;board=#{board}.0\"", "raise", "\"Not logged, cannot post!\"", "unless", "logged?", "p", "msg", "# Create new post", "seqnum", ",", "sc", "=", "find_fields", "'seqnum'", ",", "'sc'", "subj", "=", "xml_encode", "(", "subj_encode", "(", "subj", ")", ")", "msg", "=", "xml_encode", "(", "msg", ")", "# p subj, msg", "# exit", "post", "\"/index.php?action=post2;start=0;board=#{board}\"", ",", "content_type", ":", "'multipart/form-data; charset=ISO-8859-1'", ",", "body", ":", "{", "topic", ":", "0", ",", "subject", ":", "subj", ",", "icon", ":", "icon", ",", "message", ":", "msg", ",", "notify", ":", "0", ",", "do_watch", ":", "0", ",", "selfmod", ":", "0", ",", "lock", ":", "0", ",", "goback", ":", "1", ",", "ns", ":", "\"NS\"", ",", "post", ":", "\"Post\"", ",", "additional_options", ":", "0", ",", "sc", ":", "sc", ",", "seqnum", ":", "seqnum", "}", ",", "options", ":", "{", "timeout", ":", "5", "}", "# open/read timeout in seconds", "# Make sure the message was posted, return topic page", "new_topic", "=", "@response", ".", "headers", "[", "'location'", "]", "# p @response.body", "raise", "\"No redirect to posted topic!\"", "unless", "new_topic", "&&", "@response", ".", "status", "==", "302", "get", "new_topic", "end" ]
Post new topic
[ "Post", "new", "topic" ]
a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63
https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/forum.rb#L21-L46
6,541
notCalle/ruby-tangle
lib/tangle/base_graph_private.rb
Tangle.BaseGraphPrivate.each_vertex_breadth_first
def each_vertex_breadth_first(start_vertex, walk_method) remaining = [start_vertex] remaining.each_with_object([]) do |vertex, history| history << vertex yield vertex send(walk_method, vertex).each do |other| remaining << other unless history.include?(other) end end end
ruby
def each_vertex_breadth_first(start_vertex, walk_method) remaining = [start_vertex] remaining.each_with_object([]) do |vertex, history| history << vertex yield vertex send(walk_method, vertex).each do |other| remaining << other unless history.include?(other) end end end
[ "def", "each_vertex_breadth_first", "(", "start_vertex", ",", "walk_method", ")", "remaining", "=", "[", "start_vertex", "]", "remaining", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "vertex", ",", "history", "|", "history", "<<", "vertex", "yield", "vertex", "send", "(", "walk_method", ",", "vertex", ")", ".", "each", "do", "|", "other", "|", "remaining", "<<", "other", "unless", "history", ".", "include?", "(", "other", ")", "end", "end", "end" ]
Yield each reachable vertex to a block, breadth first
[ "Yield", "each", "reachable", "vertex", "to", "a", "block", "breadth", "first" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph_private.rb#L25-L34
6,542
LifebookerInc/requires_approval
lib/requires_approval.rb
RequiresApproval.ClassMethods.create_versions_class
def create_versions_class versions_table_name = self.versions_table_name self.const_set self.versions_class_name, Class.new(ActiveRecord::Base) self.versions_class.class_eval do self.table_name = versions_table_name # Whitelist public attributes # Everything since this class is for internal use only public_attributes = self.column_names.reject{|attr| self.protected_attributes.deny?(attr)} self.attr_accessible(*public_attributes) end end
ruby
def create_versions_class versions_table_name = self.versions_table_name self.const_set self.versions_class_name, Class.new(ActiveRecord::Base) self.versions_class.class_eval do self.table_name = versions_table_name # Whitelist public attributes # Everything since this class is for internal use only public_attributes = self.column_names.reject{|attr| self.protected_attributes.deny?(attr)} self.attr_accessible(*public_attributes) end end
[ "def", "create_versions_class", "versions_table_name", "=", "self", ".", "versions_table_name", "self", ".", "const_set", "self", ".", "versions_class_name", ",", "Class", ".", "new", "(", "ActiveRecord", "::", "Base", ")", "self", ".", "versions_class", ".", "class_eval", "do", "self", ".", "table_name", "=", "versions_table_name", "# Whitelist public attributes", "# Everything since this class is for internal use only", "public_attributes", "=", "self", ".", "column_names", ".", "reject", "{", "|", "attr", "|", "self", ".", "protected_attributes", ".", "deny?", "(", "attr", ")", "}", "self", ".", "attr_accessible", "(", "public_attributes", ")", "end", "end" ]
create a class
[ "create", "a", "class" ]
83b18b4693143777108b5e066b252ebff9263cbc
https://github.com/LifebookerInc/requires_approval/blob/83b18b4693143777108b5e066b252ebff9263cbc/lib/requires_approval.rb#L294-L307
6,543
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.make_bonds
def make_bonds(bond_length = 3.0) # initialize an empty array @bonds = Array.new # Make bonds between all atoms # stack = atoms.dup atoms_extended = atoms.dup if periodic? v1 = lattice_vectors[0] v2 = lattice_vectors[1] atoms.each{|a| [-1, 0, 1].each{|n1| [-1, 0, 1].each{|n2| atoms_extended << a.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]) } } } end tree = KDTree.new(atoms_extended, 3) atoms.each{|a| r = 4 neighbors = tree.find([a.x-r, a.x+r], [a.y-r, a.y+r], [a.z-r, a.z+r]) neighbors.each{|n| b = Bond.new(a, n) @bonds << b if b.length < bond_length } } # atom1 = stack.pop # while (not stack.empty?) # stack.each{|atom2| # b = Bond.new(atom1, atom2) # @bonds << b if b.length < bond_length # if periodic? # v1 = lattice_vectors[0] # v2 = lattice_vectors[1] # [-1, 0, 1].each{|n1| # [-1, 0, 1].each{|n2| # b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2])) # @bonds << b if b.length < bond_length # } # } # end # } # atom1 = stack.pop # end end
ruby
def make_bonds(bond_length = 3.0) # initialize an empty array @bonds = Array.new # Make bonds between all atoms # stack = atoms.dup atoms_extended = atoms.dup if periodic? v1 = lattice_vectors[0] v2 = lattice_vectors[1] atoms.each{|a| [-1, 0, 1].each{|n1| [-1, 0, 1].each{|n2| atoms_extended << a.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]) } } } end tree = KDTree.new(atoms_extended, 3) atoms.each{|a| r = 4 neighbors = tree.find([a.x-r, a.x+r], [a.y-r, a.y+r], [a.z-r, a.z+r]) neighbors.each{|n| b = Bond.new(a, n) @bonds << b if b.length < bond_length } } # atom1 = stack.pop # while (not stack.empty?) # stack.each{|atom2| # b = Bond.new(atom1, atom2) # @bonds << b if b.length < bond_length # if periodic? # v1 = lattice_vectors[0] # v2 = lattice_vectors[1] # [-1, 0, 1].each{|n1| # [-1, 0, 1].each{|n2| # b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2])) # @bonds << b if b.length < bond_length # } # } # end # } # atom1 = stack.pop # end end
[ "def", "make_bonds", "(", "bond_length", "=", "3.0", ")", "# initialize an empty array", "@bonds", "=", "Array", ".", "new", "# Make bonds between all atoms", "# stack = atoms.dup", "atoms_extended", "=", "atoms", ".", "dup", "if", "periodic?", "v1", "=", "lattice_vectors", "[", "0", "]", "v2", "=", "lattice_vectors", "[", "1", "]", "atoms", ".", "each", "{", "|", "a", "|", "[", "-", "1", ",", "0", ",", "1", "]", ".", "each", "{", "|", "n1", "|", "[", "-", "1", ",", "0", ",", "1", "]", ".", "each", "{", "|", "n2", "|", "atoms_extended", "<<", "a", ".", "displace", "(", "n1", "v1", "[", "0", "]", "+", "n2", "v2", "[", "0", "]", ",", "n1", "v1", "[", "1", "]", "+", "n2", "v2", "[", "1", "]", ",", "n1", "v1", "[", "2", "]", "+", "n2", "v2", "[", "2", "]", ")", "}", "}", "}", "end", "tree", "=", "KDTree", ".", "new", "(", "atoms_extended", ",", "3", ")", "atoms", ".", "each", "{", "|", "a", "|", "r", "=", "4", "neighbors", "=", "tree", ".", "find", "(", "[", "a", ".", "x", "-", "r", ",", "a", ".", "x", "+", "r", "]", ",", "[", "a", ".", "y", "-", "r", ",", "a", ".", "y", "+", "r", "]", ",", "[", "a", ".", "z", "-", "r", ",", "a", ".", "z", "+", "r", "]", ")", "neighbors", ".", "each", "{", "|", "n", "|", "b", "=", "Bond", ".", "new", "(", "a", ",", "n", ")", "@bonds", "<<", "b", "if", "b", ".", "length", "<", "bond_length", "}", "}", "# atom1 = stack.pop", "# while (not stack.empty?)", "# stack.each{|atom2|", "# b = Bond.new(atom1, atom2)", "# @bonds << b if b.length < bond_length", "# if periodic?", "# v1 = lattice_vectors[0]", "# v2 = lattice_vectors[1]", "# [-1, 0, 1].each{|n1|", "# [-1, 0, 1].each{|n2| ", "# b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]))", "# @bonds << b if b.length < bond_length", "# }", "# }", "# end", "# }", "# atom1 = stack.pop", "# end", "end" ]
Generate and cache bonds for this geometry. A bond will be generated for every pair of atoms closer than +bond_length+
[ "Generate", "and", "cache", "bonds", "for", "this", "geometry", ".", "A", "bond", "will", "be", "generated", "for", "every", "pair", "of", "atoms", "closer", "than", "+", "bond_length", "+" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L128-L175
6,544
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.recache_visible_atoms
def recache_visible_atoms(makeBonds = false) plane_count = (@clip_planes ? @clip_planes.length : 0) return if plane_count == 0 if @visibleAtoms @visibleAtoms.clear else @visibleAtoms = [] end @atoms.each{|a| i = plane_count @clip_planes.each{|p| i = i-1 if 0 >= p.distance_to_point(a.x, a.y, a.z) } @visibleAtoms << a if i == 0 } if @visibleBonds @visibleBonds.clear else @visibleBonds = [] end make_bonds if (makeBonds or @bonds.nil?) @bonds.each{|b| a0 = b[0] a1 = b[1] i0 = plane_count i1 = plane_count @clip_planes.each{|p| i0 = i0-1 if 0 >= p.distance_to_point(a0.x, a0.y, a0.z) i1 = i1-1 if 0 >= p.distance_to_point(a1.x, a1.y, a1.z) } @visibleBonds << b if (i0 + i1) < 2 } end
ruby
def recache_visible_atoms(makeBonds = false) plane_count = (@clip_planes ? @clip_planes.length : 0) return if plane_count == 0 if @visibleAtoms @visibleAtoms.clear else @visibleAtoms = [] end @atoms.each{|a| i = plane_count @clip_planes.each{|p| i = i-1 if 0 >= p.distance_to_point(a.x, a.y, a.z) } @visibleAtoms << a if i == 0 } if @visibleBonds @visibleBonds.clear else @visibleBonds = [] end make_bonds if (makeBonds or @bonds.nil?) @bonds.each{|b| a0 = b[0] a1 = b[1] i0 = plane_count i1 = plane_count @clip_planes.each{|p| i0 = i0-1 if 0 >= p.distance_to_point(a0.x, a0.y, a0.z) i1 = i1-1 if 0 >= p.distance_to_point(a1.x, a1.y, a1.z) } @visibleBonds << b if (i0 + i1) < 2 } end
[ "def", "recache_visible_atoms", "(", "makeBonds", "=", "false", ")", "plane_count", "=", "(", "@clip_planes", "?", "@clip_planes", ".", "length", ":", "0", ")", "return", "if", "plane_count", "==", "0", "if", "@visibleAtoms", "@visibleAtoms", ".", "clear", "else", "@visibleAtoms", "=", "[", "]", "end", "@atoms", ".", "each", "{", "|", "a", "|", "i", "=", "plane_count", "@clip_planes", ".", "each", "{", "|", "p", "|", "i", "=", "i", "-", "1", "if", "0", ">=", "p", ".", "distance_to_point", "(", "a", ".", "x", ",", "a", ".", "y", ",", "a", ".", "z", ")", "}", "@visibleAtoms", "<<", "a", "if", "i", "==", "0", "}", "if", "@visibleBonds", "@visibleBonds", ".", "clear", "else", "@visibleBonds", "=", "[", "]", "end", "make_bonds", "if", "(", "makeBonds", "or", "@bonds", ".", "nil?", ")", "@bonds", ".", "each", "{", "|", "b", "|", "a0", "=", "b", "[", "0", "]", "a1", "=", "b", "[", "1", "]", "i0", "=", "plane_count", "i1", "=", "plane_count", "@clip_planes", ".", "each", "{", "|", "p", "|", "i0", "=", "i0", "-", "1", "if", "0", ">=", "p", ".", "distance_to_point", "(", "a0", ".", "x", ",", "a0", ".", "y", ",", "a0", ".", "z", ")", "i1", "=", "i1", "-", "1", "if", "0", ">=", "p", ".", "distance_to_point", "(", "a1", ".", "x", ",", "a1", ".", "y", ",", "a1", ".", "z", ")", "}", "@visibleBonds", "<<", "b", "if", "(", "i0", "+", "i1", ")", "<", "2", "}", "end" ]
Recompute the atoms that are behind all the clip planes Atoms that are in front of any clip-plane are considered invisible.
[ "Recompute", "the", "atoms", "that", "are", "behind", "all", "the", "clip", "planes", "Atoms", "that", "are", "in", "front", "of", "any", "clip", "-", "plane", "are", "considered", "invisible", "." ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L299-L337
6,545
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.center
def center(visible_only = true) if atoms.empty? return Atom.new(0,0,0) else bounds = bounding_box(visible_only) x = (bounds[0].x + bounds[1].x)/2.0 y = (bounds[0].y + bounds[1].y)/2.0 z = (bounds[0].z + bounds[1].z)/2.0 return Atom.new(x,y,z) end end
ruby
def center(visible_only = true) if atoms.empty? return Atom.new(0,0,0) else bounds = bounding_box(visible_only) x = (bounds[0].x + bounds[1].x)/2.0 y = (bounds[0].y + bounds[1].y)/2.0 z = (bounds[0].z + bounds[1].z)/2.0 return Atom.new(x,y,z) end end
[ "def", "center", "(", "visible_only", "=", "true", ")", "if", "atoms", ".", "empty?", "return", "Atom", ".", "new", "(", "0", ",", "0", ",", "0", ")", "else", "bounds", "=", "bounding_box", "(", "visible_only", ")", "x", "=", "(", "bounds", "[", "0", "]", ".", "x", "+", "bounds", "[", "1", "]", ".", "x", ")", "/", "2.0", "y", "=", "(", "bounds", "[", "0", "]", ".", "y", "+", "bounds", "[", "1", "]", ".", "y", ")", "/", "2.0", "z", "=", "(", "bounds", "[", "0", "]", ".", "z", "+", "bounds", "[", "1", "]", ".", "z", ")", "/", "2.0", "return", "Atom", ".", "new", "(", "x", ",", "y", ",", "z", ")", "end", "end" ]
Return an Atom whose coordinates are the center of the unit-cell.
[ "Return", "an", "Atom", "whose", "coordinates", "are", "the", "center", "of", "the", "unit", "-", "cell", "." ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L429-L439
6,546
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.displace
def displace(x,y,z) Geometry.new(atoms(:all).collect{|a| a.displace(x,y,z) }, self.lattice_vectors) #TODO copy miller indices end
ruby
def displace(x,y,z) Geometry.new(atoms(:all).collect{|a| a.displace(x,y,z) }, self.lattice_vectors) #TODO copy miller indices end
[ "def", "displace", "(", "x", ",", "y", ",", "z", ")", "Geometry", ".", "new", "(", "atoms", "(", ":all", ")", ".", "collect", "{", "|", "a", "|", "a", ".", "displace", "(", "x", ",", "y", ",", "z", ")", "}", ",", "self", ".", "lattice_vectors", ")", "#TODO copy miller indices", "end" ]
Return a new unit cell with all the atoms displaced by the amount x,y,z
[ "Return", "a", "new", "unit", "cell", "with", "all", "the", "atoms", "displaced", "by", "the", "amount", "x", "y", "z" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L463-L468
6,547
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.repeat
def repeat(nx=1, ny=1, nz=1) raise "Not a periodic system." if self.lattice_vectors.nil? u = self.copy v1 = self.lattice_vectors[0] v2 = self.lattice_vectors[1] v3 = self.lattice_vectors[2] nx_sign = (0 < nx) ? 1 : -1 ny_sign = (0 < ny) ? 1 : -1 nz_sign = (0 < nz) ? 1 : -1 new_atoms = [] nx.to_i.abs.times do |i| ny.to_i.abs.times do |j| nz.to_i.abs.times do |k| new_atoms << self.displace(nx_sign*i*v1[0] + ny_sign*j*v2[0] + nz_sign*k*v3[0], nx_sign*i*v1[1] + ny_sign*j*v2[1] + nz_sign*k*v3[1], nx_sign*i*v1[2] + ny_sign*j*v2[2] + nz_sign*k*v3[2]).atoms end end end u.atoms = new_atoms.flatten u.lattice_vectors = [Vector[nx.abs*v1[0], nx.abs*v1[1], nx.abs*v1[2]], Vector[ny.abs*v2[0], ny.abs*v2[1], ny.abs*v2[2]], Vector[nz.abs*v3[0], nz.abs*v3[1], nz.abs*v3[2]]] # u.make_bonds return u end
ruby
def repeat(nx=1, ny=1, nz=1) raise "Not a periodic system." if self.lattice_vectors.nil? u = self.copy v1 = self.lattice_vectors[0] v2 = self.lattice_vectors[1] v3 = self.lattice_vectors[2] nx_sign = (0 < nx) ? 1 : -1 ny_sign = (0 < ny) ? 1 : -1 nz_sign = (0 < nz) ? 1 : -1 new_atoms = [] nx.to_i.abs.times do |i| ny.to_i.abs.times do |j| nz.to_i.abs.times do |k| new_atoms << self.displace(nx_sign*i*v1[0] + ny_sign*j*v2[0] + nz_sign*k*v3[0], nx_sign*i*v1[1] + ny_sign*j*v2[1] + nz_sign*k*v3[1], nx_sign*i*v1[2] + ny_sign*j*v2[2] + nz_sign*k*v3[2]).atoms end end end u.atoms = new_atoms.flatten u.lattice_vectors = [Vector[nx.abs*v1[0], nx.abs*v1[1], nx.abs*v1[2]], Vector[ny.abs*v2[0], ny.abs*v2[1], ny.abs*v2[2]], Vector[nz.abs*v3[0], nz.abs*v3[1], nz.abs*v3[2]]] # u.make_bonds return u end
[ "def", "repeat", "(", "nx", "=", "1", ",", "ny", "=", "1", ",", "nz", "=", "1", ")", "raise", "\"Not a periodic system.\"", "if", "self", ".", "lattice_vectors", ".", "nil?", "u", "=", "self", ".", "copy", "v1", "=", "self", ".", "lattice_vectors", "[", "0", "]", "v2", "=", "self", ".", "lattice_vectors", "[", "1", "]", "v3", "=", "self", ".", "lattice_vectors", "[", "2", "]", "nx_sign", "=", "(", "0", "<", "nx", ")", "?", "1", ":", "-", "1", "ny_sign", "=", "(", "0", "<", "ny", ")", "?", "1", ":", "-", "1", "nz_sign", "=", "(", "0", "<", "nz", ")", "?", "1", ":", "-", "1", "new_atoms", "=", "[", "]", "nx", ".", "to_i", ".", "abs", ".", "times", "do", "|", "i", "|", "ny", ".", "to_i", ".", "abs", ".", "times", "do", "|", "j", "|", "nz", ".", "to_i", ".", "abs", ".", "times", "do", "|", "k", "|", "new_atoms", "<<", "self", ".", "displace", "(", "nx_sign", "i", "v1", "[", "0", "]", "+", "ny_sign", "j", "v2", "[", "0", "]", "+", "nz_sign", "k", "v3", "[", "0", "]", ",", "nx_sign", "i", "v1", "[", "1", "]", "+", "ny_sign", "j", "v2", "[", "1", "]", "+", "nz_sign", "k", "v3", "[", "1", "]", ",", "nx_sign", "i", "v1", "[", "2", "]", "+", "ny_sign", "j", "v2", "[", "2", "]", "+", "nz_sign", "k", "v3", "[", "2", "]", ")", ".", "atoms", "end", "end", "end", "u", ".", "atoms", "=", "new_atoms", ".", "flatten", "u", ".", "lattice_vectors", "=", "[", "Vector", "[", "nx", ".", "abs", "v1", "[", "0", "]", ",", "nx", ".", "abs", "v1", "[", "1", "]", ",", "nx", ".", "abs", "v1", "[", "2", "]", "]", ",", "Vector", "[", "ny", ".", "abs", "v2", "[", "0", "]", ",", "ny", ".", "abs", "v2", "[", "1", "]", ",", "ny", ".", "abs", "v2", "[", "2", "]", "]", ",", "Vector", "[", "nz", ".", "abs", "v3", "[", "0", "]", ",", "nz", ".", "abs", "v3", "[", "1", "]", ",", "nz", ".", "abs", "v3", "[", "2", "]", "]", "]", "# u.make_bonds ", "return", "u", "end" ]
Repeat a unit cell nx,ny,nz times in the directions of the lattice vectors. Negative values of nx,ny or nz results in displacement in the negative direction of the lattice vectors
[ "Repeat", "a", "unit", "cell", "nx", "ny", "nz", "times", "in", "the", "directions", "of", "the", "lattice", "vectors", ".", "Negative", "values", "of", "nx", "ny", "or", "nz", "results", "in", "displacement", "in", "the", "negative", "direction", "of", "the", "lattice", "vectors" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L474-L504
6,548
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.format_geometry_in
def format_geometry_in output = "" if self.lattice_vectors output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n") output << "\n" end output << self.atoms.collect{|a| a.format_geometry_in}.join("\n") output end
ruby
def format_geometry_in output = "" if self.lattice_vectors output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n") output << "\n" end output << self.atoms.collect{|a| a.format_geometry_in}.join("\n") output end
[ "def", "format_geometry_in", "output", "=", "\"\"", "if", "self", ".", "lattice_vectors", "output", "<<", "self", ".", "lattice_vectors", ".", "collect", "{", "|", "v", "|", "\"lattice_vector #{v[0]} #{v[1]} #{v[2]}\"", "}", ".", "join", "(", "\"\\n\"", ")", "output", "<<", "\"\\n\"", "end", "output", "<<", "self", ".", "atoms", ".", "collect", "{", "|", "a", "|", "a", ".", "format_geometry_in", "}", ".", "join", "(", "\"\\n\"", ")", "output", "end" ]
Return a string formatted in the Aims geometry.in format.
[ "Return", "a", "string", "formatted", "in", "the", "Aims", "geometry", ".", "in", "format", "." ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L520-L529
6,549
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.format_xyz
def format_xyz(title = "Aims Geoemtry") output = self.atoms.size.to_s + "\n" output << "#{title} \n" self.atoms.each{ |a| output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n" } output end
ruby
def format_xyz(title = "Aims Geoemtry") output = self.atoms.size.to_s + "\n" output << "#{title} \n" self.atoms.each{ |a| output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n" } output end
[ "def", "format_xyz", "(", "title", "=", "\"Aims Geoemtry\"", ")", "output", "=", "self", ".", "atoms", ".", "size", ".", "to_s", "+", "\"\\n\"", "output", "<<", "\"#{title} \\n\"", "self", ".", "atoms", ".", "each", "{", "|", "a", "|", "output", "<<", "[", "a", ".", "species", ",", "a", ".", "x", ".", "to_s", ",", "a", ".", "y", ".", "to_s", ",", "a", ".", "z", ".", "to_s", "]", ".", "join", "(", "\"\\t\"", ")", "+", "\"\\n\"", "}", "output", "end" ]
return a string in xyz format
[ "return", "a", "string", "in", "xyz", "format" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L532-L539
6,550
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.delta
def delta(aCell) raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size pseudo_atoms = [] self.atoms.size.times {|i| a1 = self.atoms[i] a2 = aCell.atoms[i] raise "Species do not match" unless a1.species == a2.species a = Atom.new a.species = a1.species a.x = a1.x - a2.x a.y = a1.y - a2.y a.z = a1.z - a2.z pseudo_atoms << a } Geometry.new(pseudo_atoms) end
ruby
def delta(aCell) raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size pseudo_atoms = [] self.atoms.size.times {|i| a1 = self.atoms[i] a2 = aCell.atoms[i] raise "Species do not match" unless a1.species == a2.species a = Atom.new a.species = a1.species a.x = a1.x - a2.x a.y = a1.y - a2.y a.z = a1.z - a2.z pseudo_atoms << a } Geometry.new(pseudo_atoms) end
[ "def", "delta", "(", "aCell", ")", "raise", "\"Cells do not have the same number of atoms\"", "unless", "self", ".", "atoms", ".", "size", "==", "aCell", ".", "atoms", ".", "size", "pseudo_atoms", "=", "[", "]", "self", ".", "atoms", ".", "size", ".", "times", "{", "|", "i", "|", "a1", "=", "self", ".", "atoms", "[", "i", "]", "a2", "=", "aCell", ".", "atoms", "[", "i", "]", "raise", "\"Species do not match\"", "unless", "a1", ".", "species", "==", "a2", ".", "species", "a", "=", "Atom", ".", "new", "a", ".", "species", "=", "a1", ".", "species", "a", ".", "x", "=", "a1", ".", "x", "-", "a2", ".", "x", "a", ".", "y", "=", "a1", ".", "y", "-", "a2", ".", "y", "a", ".", "z", "=", "a1", ".", "z", "-", "a2", ".", "z", "pseudo_atoms", "<<", "a", "}", "Geometry", ".", "new", "(", "pseudo_atoms", ")", "end" ]
Find the difference between this cell and another cell Return a cell with Pseudo-Atoms whose positions are really the differences
[ "Find", "the", "difference", "between", "this", "cell", "and", "another", "cell", "Return", "a", "cell", "with", "Pseudo", "-", "Atoms", "whose", "positions", "are", "really", "the", "differences" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L543-L559
6,551
robertwahler/dynabix
lib/dynabix/metadata.rb
Dynabix.Metadata.has_metadata
def has_metadata(serializer=:metadata, *attributes) serialize(serializer, HashWithIndifferentAccess) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else # we can safely define additional accessors, Ruby 1.8 will only # be able to use the statically defined :metadata_accessor if serializer != :metadata # define the class accessor define_singleton_method "#{serializer}_accessor" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end # define the class read accessor define_singleton_method "#{serializer}_reader" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) end end # define the class write accessor define_singleton_method "#{serializer}_writer" do |*attrs| attrs.each do |attr| create_writer(serializer, attr) end end end end # Define each of the attributes for this serializer attributes.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end
ruby
def has_metadata(serializer=:metadata, *attributes) serialize(serializer, HashWithIndifferentAccess) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else # we can safely define additional accessors, Ruby 1.8 will only # be able to use the statically defined :metadata_accessor if serializer != :metadata # define the class accessor define_singleton_method "#{serializer}_accessor" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end # define the class read accessor define_singleton_method "#{serializer}_reader" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) end end # define the class write accessor define_singleton_method "#{serializer}_writer" do |*attrs| attrs.each do |attr| create_writer(serializer, attr) end end end end # Define each of the attributes for this serializer attributes.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end
[ "def", "has_metadata", "(", "serializer", "=", ":metadata", ",", "*", "attributes", ")", "serialize", "(", "serializer", ",", "HashWithIndifferentAccess", ")", "if", "RUBY_VERSION", "<", "'1.9'", "raise", "\"has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+\"", "unless", "serializer", "==", ":metadata", "else", "# we can safely define additional accessors, Ruby 1.8 will only", "# be able to use the statically defined :metadata_accessor", "if", "serializer", "!=", ":metadata", "# define the class accessor", "define_singleton_method", "\"#{serializer}_accessor\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end", "# define the class read accessor", "define_singleton_method", "\"#{serializer}_reader\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "end", "end", "# define the class write accessor", "define_singleton_method", "\"#{serializer}_writer\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end", "end", "end", "# Define each of the attributes for this serializer", "attributes", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end" ]
Set up the model for serialization to a HashWithIndifferentAccess. @example Using the default column name ":metadata", specify the attributes in a separate step class Thing < ActiveRecord::Base has_metadata # full accessors metadata_accessor :breakfast_food, :wheat_products, :needs_milk # read-only metadata_reader :friends_with_spoons end @example Specifying attributes for full attributes accessors in one step class Thing < ActiveRecord::Base has_metadata :metadata, :breakfast_food, :wheat_products, :needs_milk end @example Specifying multiple metadata serializers (Ruby 1.9 only) class Thing < ActiveRecord::Base has_metadata :cows has_metadata :chickens, :tasty, :feather_count # read-only cow_reader :likes_milk, :hates_eggs # write-only cow_writer :no_wheat_products # extra full accessors for chickens chicken_accessor :color, :likes_eggs end @param [Symbol] serializer, the symbolized name (:metadata) of the database text column used for serialization @param [Array<Symbol>] optional list of attribute names to add to the model as full accessors @return [void]
[ "Set", "up", "the", "model", "for", "serialization", "to", "a", "HashWithIndifferentAccess", "." ]
4a462c3d467433c76a1f7d308ba77ca9eedcbcb2
https://github.com/robertwahler/dynabix/blob/4a462c3d467433c76a1f7d308ba77ca9eedcbcb2/lib/dynabix/metadata.rb#L49-L89
6,552
barkerest/shells
lib/shells/shell_base/input.rb
Shells.ShellBase.queue_input
def queue_input(data) #:doc: sync do if options[:unbuffered_input] data = data.chars input_fifo.push *data else input_fifo.push data end end end
ruby
def queue_input(data) #:doc: sync do if options[:unbuffered_input] data = data.chars input_fifo.push *data else input_fifo.push data end end end
[ "def", "queue_input", "(", "data", ")", "#:doc:\r", "sync", "do", "if", "options", "[", ":unbuffered_input", "]", "data", "=", "data", ".", "chars", "input_fifo", ".", "push", "data", "else", "input_fifo", ".", "push", "data", "end", "end", "end" ]
Adds input to be sent to the shell.
[ "Adds", "input", "to", "be", "sent", "to", "the", "shell", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/input.rb#L31-L40
6,553
mrackwitz/CLIntegracon
lib/CLIntegracon/adapter/bacon.rb
CLIntegracon::Adapter::Bacon.Context.subject
def subject &block @subject ||= CLIntegracon::shared_config.subject.dup return @subject if block.nil? instance_exec(@subject, &block) end
ruby
def subject &block @subject ||= CLIntegracon::shared_config.subject.dup return @subject if block.nil? instance_exec(@subject, &block) end
[ "def", "subject", "&", "block", "@subject", "||=", "CLIntegracon", "::", "shared_config", ".", "subject", ".", "dup", "return", "@subject", "if", "block", ".", "nil?", "instance_exec", "(", "@subject", ",", "block", ")", "end" ]
Get or configure the current subject @note On first call this will create a new subject on base of the shared configuration and store it in the ivar `@subject`. @param [Block<(Subject) -> ()>] This block, if given, will be evaluated on the caller. It receives as first argument the subject itself. @return [Subject] the subject
[ "Get", "or", "configure", "the", "current", "subject" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/adapter/bacon.rb#L25-L29
6,554
mrackwitz/CLIntegracon
lib/CLIntegracon/adapter/bacon.rb
CLIntegracon::Adapter::Bacon.Context.file_tree_spec_context
def file_tree_spec_context &block @file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup return @file_tree_spec_context if block.nil? instance_exec(@file_tree_spec_context, &block) end
ruby
def file_tree_spec_context &block @file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup return @file_tree_spec_context if block.nil? instance_exec(@file_tree_spec_context, &block) end
[ "def", "file_tree_spec_context", "&", "block", "@file_tree_spec_context", "||=", "CLIntegracon", ".", "shared_config", ".", "file_tree_spec_context", ".", "dup", "return", "@file_tree_spec_context", "if", "block", ".", "nil?", "instance_exec", "(", "@file_tree_spec_context", ",", "block", ")", "end" ]
Get or configure the current context for FileTreeSpecs @note On first call this will create a new context on base of the shared configuration and store it in the ivar `@file_tree_spec_context`. @param [Block<(FileTreeSpecContext) -> ()>] This block, if given, will be evaluated on the caller. It receives as first argument the context itself. @return [FileTreeSpecContext] the spec context, will be lazily created if not already present.
[ "Get", "or", "configure", "the", "current", "context", "for", "FileTreeSpecs" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/adapter/bacon.rb#L43-L47
6,555
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.acquire_read_lock
def acquire_read_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many reader threads' if max_readers?(c) if waiting_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if waiting_writer? end while(true) c = @counter.value if running_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if running_writer? end else return if @counter.compare_and_swap(c,c+1) end end else break if @counter.compare_and_swap(c,c+1) end end true end
ruby
def acquire_read_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many reader threads' if max_readers?(c) if waiting_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if waiting_writer? end while(true) c = @counter.value if running_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if running_writer? end else return if @counter.compare_and_swap(c,c+1) end end else break if @counter.compare_and_swap(c,c+1) end end true end
[ "def", "acquire_read_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "raise", "ResourceLimitError", ",", "'Too many reader threads'", "if", "max_readers?", "(", "c", ")", "if", "waiting_writer?", "(", "c", ")", "@reader_mutex", ".", "synchronize", "do", "@reader_q", ".", "wait", "(", "@reader_mutex", ")", "if", "waiting_writer?", "end", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "running_writer?", "(", "c", ")", "@reader_mutex", ".", "synchronize", "do", "@reader_q", ".", "wait", "(", "@reader_mutex", ")", "if", "running_writer?", "end", "else", "return", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "1", ")", "end", "end", "else", "break", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "1", ")", "end", "end", "true", "end" ]
Acquire a read lock. If a write lock has been acquired will block until it is released. Will not block if other read locks have been acquired. @return [Boolean] True if the lock is successfully acquired. @raise [Garcon::ResourceLimitError] If the maximum number of readers is exceeded.
[ "Acquire", "a", "read", "lock", ".", "If", "a", "write", "lock", "has", "been", "acquired", "will", "block", "until", "it", "is", "released", ".", "Will", "not", "block", "if", "other", "read", "locks", "have", "been", "acquired", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L134-L159
6,556
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.release_read_lock
def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if waiting_writer?(c) && running_readers(c) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
ruby
def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if waiting_writer?(c) && running_readers(c) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
[ "def", "release_read_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "-", "1", ")", "if", "waiting_writer?", "(", "c", ")", "&&", "running_readers", "(", "c", ")", "==", "1", "@writer_mutex", ".", "synchronize", "{", "@writer_q", ".", "signal", "}", "end", "break", "end", "end", "true", "end" ]
Release a previously acquired read lock. @return [Boolean] True if the lock is successfully released.
[ "Release", "a", "previously", "acquired", "read", "lock", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L166-L177
6,557
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.acquire_write_lock
def acquire_write_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many writer threads' if max_writers?(c) if c == 0 break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) @writer_mutex.synchronize do c = @counter.value if running_writer?(c) || running_readers?(c) @writer_q.wait(@writer_mutex) end end c = @counter.value break if !running_writer?(c) && !running_readers?(c) && @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER) end break end end true end
ruby
def acquire_write_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many writer threads' if max_writers?(c) if c == 0 break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) @writer_mutex.synchronize do c = @counter.value if running_writer?(c) || running_readers?(c) @writer_q.wait(@writer_mutex) end end c = @counter.value break if !running_writer?(c) && !running_readers?(c) && @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER) end break end end true end
[ "def", "acquire_write_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "raise", "ResourceLimitError", ",", "'Too many writer threads'", "if", "max_writers?", "(", "c", ")", "if", "c", "==", "0", "break", "if", "@counter", ".", "compare_and_swap", "(", "0", ",", "RUNNING_WRITER", ")", "elsif", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "WAITING_WRITER", ")", "while", "(", "true", ")", "@writer_mutex", ".", "synchronize", "do", "c", "=", "@counter", ".", "value", "if", "running_writer?", "(", "c", ")", "||", "running_readers?", "(", "c", ")", "@writer_q", ".", "wait", "(", "@writer_mutex", ")", "end", "end", "c", "=", "@counter", ".", "value", "break", "if", "!", "running_writer?", "(", "c", ")", "&&", "!", "running_readers?", "(", "c", ")", "&&", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "RUNNING_WRITER", "-", "WAITING_WRITER", ")", "end", "break", "end", "end", "true", "end" ]
Acquire a write lock. Will block and wait for all active readers and writers. @return [Boolean] True if the lock is successfully acquired. @raise [Garcon::ResourceLimitError] If the maximum number of writers is exceeded.
[ "Acquire", "a", "write", "lock", ".", "Will", "block", "and", "wait", "for", "all", "active", "readers", "and", "writers", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L188-L212
6,558
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.release_write_lock
def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) @reader_mutex.synchronize { @reader_q.broadcast } if waiting_writers(c) > 0 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
ruby
def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) @reader_mutex.synchronize { @reader_q.broadcast } if waiting_writers(c) > 0 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
[ "def", "release_write_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "-", "RUNNING_WRITER", ")", "@reader_mutex", ".", "synchronize", "{", "@reader_q", ".", "broadcast", "}", "if", "waiting_writers", "(", "c", ")", ">", "0", "@writer_mutex", ".", "synchronize", "{", "@writer_q", ".", "signal", "}", "end", "break", "end", "end", "true", "end" ]
Release a previously acquired write lock. @return [Boolean] True if the lock is successfully released.
[ "Release", "a", "previously", "acquired", "write", "lock", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L219-L231
6,559
jackc/command_model
lib/command_model/model.rb
CommandModel.Model.parameters
def parameters self.class.parameters.each_with_object({}) do |parameter, hash| hash[parameter.name] = send(parameter.name) end end
ruby
def parameters self.class.parameters.each_with_object({}) do |parameter, hash| hash[parameter.name] = send(parameter.name) end end
[ "def", "parameters", "self", ".", "class", ".", "parameters", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "parameter", ",", "hash", "|", "hash", "[", "parameter", ".", "name", "]", "=", "send", "(", "parameter", ".", "name", ")", "end", "end" ]
Returns hash of all parameter names and values
[ "Returns", "hash", "of", "all", "parameter", "names", "and", "values" ]
9c97ce7c9a51801c28b1b923396bad81505bf5dc
https://github.com/jackc/command_model/blob/9c97ce7c9a51801c28b1b923396bad81505bf5dc/lib/command_model/model.rb#L171-L175
6,560
neuron-digital/models_auditor
lib/models_auditor/controller.rb
ModelsAuditor.Controller.user_for_models_auditor
def user_for_models_auditor user = case when defined?(current_user) current_user when defined?(current_employee) current_employee else return end ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id) rescue NoMethodError user end
ruby
def user_for_models_auditor user = case when defined?(current_user) current_user when defined?(current_employee) current_employee else return end ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id) rescue NoMethodError user end
[ "def", "user_for_models_auditor", "user", "=", "case", "when", "defined?", "(", "current_user", ")", "current_user", "when", "defined?", "(", "current_employee", ")", "current_employee", "else", "return", "end", "ActiveSupport", "::", "VERSION", "::", "MAJOR", ">=", "4", "?", "user", ".", "try!", "(", ":id", ")", ":", "user", ".", "try", "(", ":id", ")", "rescue", "NoMethodError", "user", "end" ]
Returns the user who is responsible for any changes that occur. By default this calls `current_user` or `current_employee` and returns the result. Override this method in your controller to call a different method, e.g. `current_person`, or anything you like.
[ "Returns", "the", "user", "who", "is", "responsible", "for", "any", "changes", "that", "occur", ".", "By", "default", "this", "calls", "current_user", "or", "current_employee", "and", "returns", "the", "result", "." ]
f5cf07416a7a7f7473fcc4dabc86f2300b76de7b
https://github.com/neuron-digital/models_auditor/blob/f5cf07416a7a7f7473fcc4dabc86f2300b76de7b/lib/models_auditor/controller.rb#L37-L50
6,561
neuron-digital/models_auditor
lib/models_auditor/controller.rb
ModelsAuditor.Controller.info_for_models_auditor
def info_for_models_auditor { ip: request.remote_ip, user_agent: request.user_agent, controller: self.class.name, action: action_name, path: request.path_info } end
ruby
def info_for_models_auditor { ip: request.remote_ip, user_agent: request.user_agent, controller: self.class.name, action: action_name, path: request.path_info } end
[ "def", "info_for_models_auditor", "{", "ip", ":", "request", ".", "remote_ip", ",", "user_agent", ":", "request", ".", "user_agent", ",", "controller", ":", "self", ".", "class", ".", "name", ",", "action", ":", "action_name", ",", "path", ":", "request", ".", "path_info", "}", "end" ]
Returns any information about the controller or request that you want ModelsAuditor to store alongside any changes that occur. By default this returns an empty hash. Override this method in your controller to return a hash of any information you need. The hash's keys must correspond to columns in your `auditor_requests` table, so don't forget to add any new columns you need. For example: {:ip => request.remote_ip, :user_agent => request.user_agent} The columns `ip` and `user_agent` must exist in your `versions` # table. Use the `:meta` option to `PaperTrail::Model::ClassMethods.has_paper_trail` to store any extra model-level data you need.
[ "Returns", "any", "information", "about", "the", "controller", "or", "request", "that", "you", "want", "ModelsAuditor", "to", "store", "alongside", "any", "changes", "that", "occur", ".", "By", "default", "this", "returns", "an", "empty", "hash", "." ]
f5cf07416a7a7f7473fcc4dabc86f2300b76de7b
https://github.com/neuron-digital/models_auditor/blob/f5cf07416a7a7f7473fcc4dabc86f2300b76de7b/lib/models_auditor/controller.rb#L69-L77
6,562
authrocket/authrocket-ruby
lib/authrocket/credential.rb
AuthRocket.Credential.verify
def verify(code, attribs={}) params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds parsed, _ = request(:post, url+'/verify', params) load(parsed) errors.empty? ? self : false end
ruby
def verify(code, attribs={}) params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds parsed, _ = request(:post, url+'/verify', params) load(parsed) errors.empty? ? self : false end
[ "def", "verify", "(", "code", ",", "attribs", "=", "{", "}", ")", "params", "=", "parse_request_params", "(", "attribs", ".", "merge", "(", "code", ":", "code", ")", ",", "json_root", ":", "json_root", ")", ".", "merge", "credentials", ":", "api_creds", "parsed", ",", "_", "=", "request", "(", ":post", ",", "url", "+", "'/verify'", ",", "params", ")", "load", "(", "parsed", ")", "errors", ".", "empty?", "?", "self", ":", "false", "end" ]
code - required
[ "code", "-", "required" ]
6a0496035b219e6d0acbee24b1b483051c57b1ef
https://github.com/authrocket/authrocket-ruby/blob/6a0496035b219e6d0acbee24b1b483051c57b1ef/lib/authrocket/credential.rb#L16-L21
6,563
kindlinglabs/bullring
lib/bullring/workers/rhino_server.rb
Bullring.RhinoServer.fetch_library
def fetch_library(name) library_script = @server_registry['library', name] logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found."} raise NameError, "Server cannot find a script named #{name}" if library_script.nil? library_script end
ruby
def fetch_library(name) library_script = @server_registry['library', name] logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found."} raise NameError, "Server cannot find a script named #{name}" if library_script.nil? library_script end
[ "def", "fetch_library", "(", "name", ")", "library_script", "=", "@server_registry", "[", "'library'", ",", "name", "]", "logger", ".", "debug", "{", "\"#{logname}: Tried to fetch script '#{name}' from the registry and it \"", "+", "\"was #{'not ' if library_script.nil?}found.\"", "}", "raise", "NameError", ",", "\"Server cannot find a script named #{name}\"", "if", "library_script", ".", "nil?", "library_script", "end" ]
Grab the library from the registry server
[ "Grab", "the", "library", "from", "the", "registry", "server" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/workers/rhino_server.rb#L147-L156
6,564
jakewendt/rails_extension
lib/rails_extension/action_controller_extension/accessible_via_user.rb
RailsExtension::ActionControllerExtension::AccessibleViaUser.ClassMethods.assert_access_without_login
def assert_access_without_login(*actions) user_options = actions.extract_options! options = {} if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') ) options.merge!(self::ASSERT_ACCESS_OPTIONS) end options.merge!(user_options) actions += options[:actions]||[] m_key = options[:model].try(:underscore).try(:to_sym) test "#{brand}AWoL should get new without login" do get :new assert_response :success assert_template 'new' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:new) || options.keys.include?(:new) test "#{brand}AWoL should post create without login" do args = if options[:create] options[:create] elsif options[:attributes_for_create] {m_key => send(options[:attributes_for_create])} else {} end assert_difference("#{options[:model]}.count",1) do send(:post,:create,args) end assert_response :redirect assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:create) || options.keys.include?(:create) # test "should NOT get edit without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # send(:get,:edit, *args) # assert_redirected_to_login # end if actions.include?(:edit) || options.keys.include?(:edit) # # test "should NOT put update without login" do # args={} # if options[:factory] # obj = Factory(options[:factory]) # args[:id] = obj.id # args[options[:factory]] = Factory.attributes_for(options[:factory]) # end # send(:put,:update, args) # assert_redirected_to_login # end if actions.include?(:update) || options.keys.include?(:update) test "#{brand}AWoL should get show without login" do args={} if options[:method_for_create] obj = send(options[:method_for_create]) args[:id] = obj.id end send(:get,:show, args) assert_response :success assert_template 'show' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:show) || options.keys.include?(:show) # test "should NOT delete destroy without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # assert_no_difference("#{options[:model]}.count") do # send(:delete,:destroy,*args) # end # assert_redirected_to_login # end if actions.include?(:destroy) || options.keys.include?(:destroy) # # test "should NOT get index without login" do # get :index # assert_redirected_to_login # end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login" do get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login and items" do send(options[:before]) if !options[:before].blank? 3.times{ send(options[:method_for_create]) } if !options[:method_for_create].blank? get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) end
ruby
def assert_access_without_login(*actions) user_options = actions.extract_options! options = {} if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') ) options.merge!(self::ASSERT_ACCESS_OPTIONS) end options.merge!(user_options) actions += options[:actions]||[] m_key = options[:model].try(:underscore).try(:to_sym) test "#{brand}AWoL should get new without login" do get :new assert_response :success assert_template 'new' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:new) || options.keys.include?(:new) test "#{brand}AWoL should post create without login" do args = if options[:create] options[:create] elsif options[:attributes_for_create] {m_key => send(options[:attributes_for_create])} else {} end assert_difference("#{options[:model]}.count",1) do send(:post,:create,args) end assert_response :redirect assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:create) || options.keys.include?(:create) # test "should NOT get edit without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # send(:get,:edit, *args) # assert_redirected_to_login # end if actions.include?(:edit) || options.keys.include?(:edit) # # test "should NOT put update without login" do # args={} # if options[:factory] # obj = Factory(options[:factory]) # args[:id] = obj.id # args[options[:factory]] = Factory.attributes_for(options[:factory]) # end # send(:put,:update, args) # assert_redirected_to_login # end if actions.include?(:update) || options.keys.include?(:update) test "#{brand}AWoL should get show without login" do args={} if options[:method_for_create] obj = send(options[:method_for_create]) args[:id] = obj.id end send(:get,:show, args) assert_response :success assert_template 'show' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:show) || options.keys.include?(:show) # test "should NOT delete destroy without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # assert_no_difference("#{options[:model]}.count") do # send(:delete,:destroy,*args) # end # assert_redirected_to_login # end if actions.include?(:destroy) || options.keys.include?(:destroy) # # test "should NOT get index without login" do # get :index # assert_redirected_to_login # end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login" do get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login and items" do send(options[:before]) if !options[:before].blank? 3.times{ send(options[:method_for_create]) } if !options[:method_for_create].blank? get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) end
[ "def", "assert_access_without_login", "(", "*", "actions", ")", "user_options", "=", "actions", ".", "extract_options!", "options", "=", "{", "}", "if", "(", "self", ".", "constants", ".", "include?", "(", "'ASSERT_ACCESS_OPTIONS'", ")", ")", "options", ".", "merge!", "(", "self", "::", "ASSERT_ACCESS_OPTIONS", ")", "end", "options", ".", "merge!", "(", "user_options", ")", "actions", "+=", "options", "[", ":actions", "]", "||", "[", "]", "m_key", "=", "options", "[", ":model", "]", ".", "try", "(", ":underscore", ")", ".", "try", "(", ":to_sym", ")", "test", "\"#{brand}AWoL should get new without login\"", "do", "get", ":new", "assert_response", ":success", "assert_template", "'new'", "assert", "assigns", "(", "m_key", ")", ",", "\"#{m_key} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":new", ")", "||", "options", ".", "keys", ".", "include?", "(", ":new", ")", "test", "\"#{brand}AWoL should post create without login\"", "do", "args", "=", "if", "options", "[", ":create", "]", "options", "[", ":create", "]", "elsif", "options", "[", ":attributes_for_create", "]", "{", "m_key", "=>", "send", "(", "options", "[", ":attributes_for_create", "]", ")", "}", "else", "{", "}", "end", "assert_difference", "(", "\"#{options[:model]}.count\"", ",", "1", ")", "do", "send", "(", ":post", ",", ":create", ",", "args", ")", "end", "assert_response", ":redirect", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":create", ")", "||", "options", ".", "keys", ".", "include?", "(", ":create", ")", "#\t\t\ttest \"should NOT get edit without login\" do", "#\t\t\t\targs=[]", "#\t\t\t\tif options[:factory]", "#\t\t\t\t\tobj = Factory(options[:factory])", "#\t\t\t\t\targs.push(:id => obj.id)", "#\t\t\t\tend", "#\t\t\t\tsend(:get,:edit, *args)", "#\t\t\t\tassert_redirected_to_login", "#\t\t\tend if actions.include?(:edit) || options.keys.include?(:edit)", "#", "#\t\t\ttest \"should NOT put update without login\" do", "#\t\t\t\targs={}", "#\t\t\t\tif options[:factory]", "#\t\t\t\t\tobj = Factory(options[:factory])", "#\t\t\t\t\targs[:id] = obj.id", "#\t\t\t\t\targs[options[:factory]] = Factory.attributes_for(options[:factory])", "#\t\t\t\tend", "#\t\t\t\tsend(:put,:update, args)", "#\t\t\t\tassert_redirected_to_login", "#\t\t\tend if actions.include?(:update) || options.keys.include?(:update)", "test", "\"#{brand}AWoL should get show without login\"", "do", "args", "=", "{", "}", "if", "options", "[", ":method_for_create", "]", "obj", "=", "send", "(", "options", "[", ":method_for_create", "]", ")", "args", "[", ":id", "]", "=", "obj", ".", "id", "end", "send", "(", ":get", ",", ":show", ",", "args", ")", "assert_response", ":success", "assert_template", "'show'", "assert", "assigns", "(", "m_key", ")", ",", "\"#{m_key} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":show", ")", "||", "options", ".", "keys", ".", "include?", "(", ":show", ")", "#\t\t\ttest \"should NOT delete destroy without login\" do", "#\t\t\t\targs=[]", "#\t\t\t\tif options[:factory]", "#\t\t\t\t\tobj = Factory(options[:factory])", "#\t\t\t\t\targs.push(:id => obj.id)", "#\t\t\t\tend", "#\t\t\t\tassert_no_difference(\"#{options[:model]}.count\") do", "#\t\t\t\t\tsend(:delete,:destroy,*args)", "#\t\t\t\tend", "#\t\t\t\tassert_redirected_to_login", "#\t\t\tend if actions.include?(:destroy) || options.keys.include?(:destroy)", "#", "#\t\t\ttest \"should NOT get index without login\" do", "#\t\t\t\tget :index", "#\t\t\t\tassert_redirected_to_login", "#\t\t\tend if actions.include?(:index) || options.keys.include?(:index)", "test", "\"#{brand}should get index without login\"", "do", "get", ":index", "assert_response", ":success", "assert_template", "'index'", "assert", "assigns", "(", "m_key", ".", "try", "(", ":to_s", ")", ".", "try", "(", ":pluralize", ")", ".", "try", "(", ":to_sym", ")", ")", ",", "\"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":index", ")", "||", "options", ".", "keys", ".", "include?", "(", ":index", ")", "test", "\"#{brand}should get index without login and items\"", "do", "send", "(", "options", "[", ":before", "]", ")", "if", "!", "options", "[", ":before", "]", ".", "blank?", "3", ".", "times", "{", "send", "(", "options", "[", ":method_for_create", "]", ")", "}", "if", "!", "options", "[", ":method_for_create", "]", ".", "blank?", "get", ":index", "assert_response", ":success", "assert_template", "'index'", "assert", "assigns", "(", "m_key", ".", "try", "(", ":to_s", ")", ".", "try", "(", ":pluralize", ")", ".", "try", "(", ":to_sym", ")", ")", ",", "\"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":index", ")", "||", "options", ".", "keys", ".", "include?", "(", ":index", ")", "end" ]
I can't imagine a whole lot of use for this one.
[ "I", "can", "t", "imagine", "a", "whole", "lot", "of", "use", "for", "this", "one", "." ]
310774fea4a07821aee8f87b9f30d2b4b0bbe548
https://github.com/jakewendt/rails_extension/blob/310774fea4a07821aee8f87b9f30d2b4b0bbe548/lib/rails_extension/action_controller_extension/accessible_via_user.rb#L279-L385
6,565
jinx/json
lib/jinx/json/collection.rb
Jinx.Collection.to_json
def to_json(state=nil) # Make a new State from the options if this is a top-level call. state = JSON::State.for(state) unless JSON::State === state to_a.to_json(state) end
ruby
def to_json(state=nil) # Make a new State from the options if this is a top-level call. state = JSON::State.for(state) unless JSON::State === state to_a.to_json(state) end
[ "def", "to_json", "(", "state", "=", "nil", ")", "# Make a new State from the options if this is a top-level call.", "state", "=", "JSON", "::", "State", ".", "for", "(", "state", ")", "unless", "JSON", "::", "State", "===", "state", "to_a", ".", "to_json", "(", "state", ")", "end" ]
Adds JSON serialization to collections. @param [State, Hash, nil] state the JSON state or serialization options @return [String] the JSON representation of this {Jinx::Resource}
[ "Adds", "JSON", "serialization", "to", "collections", "." ]
b9d596e3d1d56076182003104a5e363216357873
https://github.com/jinx/json/blob/b9d596e3d1d56076182003104a5e363216357873/lib/jinx/json/collection.rb#L10-L14
6,566
Raybeam/myreplicator
app/models/myreplicator/export.rb
Myreplicator.Export.export
def export Log.run(:job_type => "export", :name => schedule_name, :file => filename, :export_id => id) do |log| exporter = MysqlExporter.new exporter.export_table self # pass current object to exporter end end
ruby
def export Log.run(:job_type => "export", :name => schedule_name, :file => filename, :export_id => id) do |log| exporter = MysqlExporter.new exporter.export_table self # pass current object to exporter end end
[ "def", "export", "Log", ".", "run", "(", ":job_type", "=>", "\"export\"", ",", ":name", "=>", "schedule_name", ",", ":file", "=>", "filename", ",", ":export_id", "=>", "id", ")", "do", "|", "log", "|", "exporter", "=", "MysqlExporter", ".", "new", "exporter", ".", "export_table", "self", "# pass current object to exporter", "end", "end" ]
Runs the export process using the required Exporter library
[ "Runs", "the", "export", "process", "using", "the", "required", "Exporter", "library" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/export.rb#L69-L75
6,567
Raybeam/myreplicator
app/models/myreplicator/export.rb
Myreplicator.Export.is_running?
def is_running? return false if state != "exporting" begin Process.getpgid(exporter_pid) raise Exceptions::ExportIgnored.new("Ignored") rescue Errno::ESRCH return false end end
ruby
def is_running? return false if state != "exporting" begin Process.getpgid(exporter_pid) raise Exceptions::ExportIgnored.new("Ignored") rescue Errno::ESRCH return false end end
[ "def", "is_running?", "return", "false", "if", "state", "!=", "\"exporting\"", "begin", "Process", ".", "getpgid", "(", "exporter_pid", ")", "raise", "Exceptions", "::", "ExportIgnored", ".", "new", "(", "\"Ignored\"", ")", "rescue", "Errno", "::", "ESRCH", "return", "false", "end", "end" ]
Throws ExportIgnored if the job is still running Checks the state of the job using PID and state
[ "Throws", "ExportIgnored", "if", "the", "job", "is", "still", "running", "Checks", "the", "state", "of", "the", "job", "using", "PID", "and", "state" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/export.rb#L280-L288
6,568
chef-workflow/furnish-ssh
lib/furnish/ssh.rb
Furnish.SSH.run
def run(cmd) ret = { :exit_status => 0, :stdout => "", :stderr => "" } port = ssh_args[:port] Net::SSH.start(host, username, ssh_args) do |ssh| ssh.open_channel do |ch| if stdin ch.send_data(stdin) ch.eof! end if require_pty ch.request_pty do |ch, success| unless success raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one." end end end ch.on_open_failed do |ch, code, desc| raise "Connection Error to #{username}@#{host}: #{desc}" end ch.exec(cmd) do |ch, success| unless success raise "Could not execute command '#{cmd}' on #{username}@#{host}" end if merge_output ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| if type == 1 log(host, port, data) ret[:stdout] << data end end else ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| ret[:stderr] << data if type == 1 end end ch.on_request("exit-status") do |ch, data| ret[:exit_status] = data.read_long end end end ssh.loop end return ret end
ruby
def run(cmd) ret = { :exit_status => 0, :stdout => "", :stderr => "" } port = ssh_args[:port] Net::SSH.start(host, username, ssh_args) do |ssh| ssh.open_channel do |ch| if stdin ch.send_data(stdin) ch.eof! end if require_pty ch.request_pty do |ch, success| unless success raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one." end end end ch.on_open_failed do |ch, code, desc| raise "Connection Error to #{username}@#{host}: #{desc}" end ch.exec(cmd) do |ch, success| unless success raise "Could not execute command '#{cmd}' on #{username}@#{host}" end if merge_output ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| if type == 1 log(host, port, data) ret[:stdout] << data end end else ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| ret[:stderr] << data if type == 1 end end ch.on_request("exit-status") do |ch, data| ret[:exit_status] = data.read_long end end end ssh.loop end return ret end
[ "def", "run", "(", "cmd", ")", "ret", "=", "{", ":exit_status", "=>", "0", ",", ":stdout", "=>", "\"\"", ",", ":stderr", "=>", "\"\"", "}", "port", "=", "ssh_args", "[", ":port", "]", "Net", "::", "SSH", ".", "start", "(", "host", ",", "username", ",", "ssh_args", ")", "do", "|", "ssh", "|", "ssh", ".", "open_channel", "do", "|", "ch", "|", "if", "stdin", "ch", ".", "send_data", "(", "stdin", ")", "ch", ".", "eof!", "end", "if", "require_pty", "ch", ".", "request_pty", "do", "|", "ch", ",", "success", "|", "unless", "success", "raise", "\"The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one.\"", "end", "end", "end", "ch", ".", "on_open_failed", "do", "|", "ch", ",", "code", ",", "desc", "|", "raise", "\"Connection Error to #{username}@#{host}: #{desc}\"", "end", "ch", ".", "exec", "(", "cmd", ")", "do", "|", "ch", ",", "success", "|", "unless", "success", "raise", "\"Could not execute command '#{cmd}' on #{username}@#{host}\"", "end", "if", "merge_output", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "ch", ".", "on_extended_data", "do", "|", "ch", ",", "type", ",", "data", "|", "if", "type", "==", "1", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "end", "else", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "ch", ".", "on_extended_data", "do", "|", "ch", ",", "type", ",", "data", "|", "ret", "[", ":stderr", "]", "<<", "data", "if", "type", "==", "1", "end", "end", "ch", ".", "on_request", "(", "\"exit-status\"", ")", "do", "|", "ch", ",", "data", "|", "ret", "[", ":exit_status", "]", "=", "data", ".", "read_long", "end", "end", "end", "ssh", ".", "loop", "end", "return", "ret", "end" ]
Run the command on the remote host. Return value is a hash of symbol -> value, where symbol might be: * :stdout -- the standard output of the run. if #merge_output is supplied, this will be all the output. Will be an empty string by default. * :stderr -- standard error. Will be an empty string by default. * :exit_status -- the exit status. Will be zero by default.
[ "Run", "the", "command", "on", "the", "remote", "host", "." ]
1e2e2f720456f522a4d738134280701c6932f3a1
https://github.com/chef-workflow/furnish-ssh/blob/1e2e2f720456f522a4d738134280701c6932f3a1/lib/furnish/ssh.rb#L112-L178
6,569
jeremiahishere/trackable_tasks
app/models/trackable_tasks/task_run.rb
TrackableTasks.TaskRun.run_time_or_time_elapsed
def run_time_or_time_elapsed if self.end_time return Time.at(self.end_time - self.start_time) else return Time.at(Time.now - self.start_time) end end
ruby
def run_time_or_time_elapsed if self.end_time return Time.at(self.end_time - self.start_time) else return Time.at(Time.now - self.start_time) end end
[ "def", "run_time_or_time_elapsed", "if", "self", ".", "end_time", "return", "Time", ".", "at", "(", "self", ".", "end_time", "-", "self", ".", "start_time", ")", "else", "return", "Time", ".", "at", "(", "Time", ".", "now", "-", "self", ".", "start_time", ")", "end", "end" ]
Creates run time based on start and end time If there is no end_time, returns time between start and now @return [Time] The run time object
[ "Creates", "run", "time", "based", "on", "start", "and", "end", "time", "If", "there", "is", "no", "end_time", "returns", "time", "between", "start", "and", "now" ]
8702672a7b38efa936fd285a0025e04e4b025908
https://github.com/jeremiahishere/trackable_tasks/blob/8702672a7b38efa936fd285a0025e04e4b025908/app/models/trackable_tasks/task_run.rb#L90-L96
6,570
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_label
def extra_label(index) return nil if index < 1 || index > 5 txt = send("extra_#{index}_label") txt = extra_name(index).to_s.humanize.capitalize if txt.blank? txt end
ruby
def extra_label(index) return nil if index < 1 || index > 5 txt = send("extra_#{index}_label") txt = extra_name(index).to_s.humanize.capitalize if txt.blank? txt end
[ "def", "extra_label", "(", "index", ")", "return", "nil", "if", "index", "<", "1", "||", "index", ">", "5", "txt", "=", "send", "(", "\"extra_#{index}_label\"", ")", "txt", "=", "extra_name", "(", "index", ")", ".", "to_s", ".", "humanize", ".", "capitalize", "if", "txt", ".", "blank?", "txt", "end" ]
Gets the label for an extra value.
[ "Gets", "the", "label", "for", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L98-L103
6,571
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_field_type
def extra_field_type(index) t = extra_type(index).to_s case t when 'password' 'password' when 'integer', 'float' 'number' when 'boolean' 'checkbox' else if t.downcase.index('in:') 'select' else 'text' end end end
ruby
def extra_field_type(index) t = extra_type(index).to_s case t when 'password' 'password' when 'integer', 'float' 'number' when 'boolean' 'checkbox' else if t.downcase.index('in:') 'select' else 'text' end end end
[ "def", "extra_field_type", "(", "index", ")", "t", "=", "extra_type", "(", "index", ")", ".", "to_s", "case", "t", "when", "'password'", "'password'", "when", "'integer'", ",", "'float'", "'number'", "when", "'boolean'", "'checkbox'", "else", "if", "t", ".", "downcase", ".", "index", "(", "'in:'", ")", "'select'", "else", "'text'", "end", "end", "end" ]
Gets the field type for an extra value.
[ "Gets", "the", "field", "type", "for", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L114-L130
6,572
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_value
def extra_value(index, convert = false) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type(index) when 'boolean' BarkestCore::BooleanParser.parse_for_boolean_column(val) when 'integer' BarkestCore::NumberParser.parse_for_int_column(val) when 'float' BarkestCore::NumberParser.parse_for_float_column(val) else val.to_s end end end
ruby
def extra_value(index, convert = false) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type(index) when 'boolean' BarkestCore::BooleanParser.parse_for_boolean_column(val) when 'integer' BarkestCore::NumberParser.parse_for_int_column(val) when 'float' BarkestCore::NumberParser.parse_for_float_column(val) else val.to_s end end end
[ "def", "extra_value", "(", "index", ",", "convert", "=", "false", ")", "return", "nil", "if", "index", "<", "1", "||", "index", ">", "5", "val", "=", "send", "\"extra_#{index}_value\"", "if", "convert", "case", "extra_type", "(", "index", ")", "when", "'boolean'", "BarkestCore", "::", "BooleanParser", ".", "parse_for_boolean_column", "(", "val", ")", "when", "'integer'", "BarkestCore", "::", "NumberParser", ".", "parse_for_int_column", "(", "val", ")", "when", "'float'", "BarkestCore", "::", "NumberParser", ".", "parse_for_float_column", "(", "val", ")", "else", "val", ".", "to_s", "end", "end", "end" ]
Gets an extra value.
[ "Gets", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L144-L159
6,573
codez/mail_relay
lib/mail_relay/base.rb
MailRelay.Base.resend_to
def resend_to(destinations) if destinations.size > 0 message.smtp_envelope_to = destinations # Set envelope from and sender to local server to satisfy SPF: # http://www.openspf.org/Best_Practices/Webgenerated message.sender = envelope_sender message.smtp_envelope_from = envelope_sender # set list headers message.header['Precedence'] = 'list' message.header['List-Id'] = list_id deliver(message) end end
ruby
def resend_to(destinations) if destinations.size > 0 message.smtp_envelope_to = destinations # Set envelope from and sender to local server to satisfy SPF: # http://www.openspf.org/Best_Practices/Webgenerated message.sender = envelope_sender message.smtp_envelope_from = envelope_sender # set list headers message.header['Precedence'] = 'list' message.header['List-Id'] = list_id deliver(message) end end
[ "def", "resend_to", "(", "destinations", ")", "if", "destinations", ".", "size", ">", "0", "message", ".", "smtp_envelope_to", "=", "destinations", "# Set envelope from and sender to local server to satisfy SPF:", "# http://www.openspf.org/Best_Practices/Webgenerated", "message", ".", "sender", "=", "envelope_sender", "message", ".", "smtp_envelope_from", "=", "envelope_sender", "# set list headers", "message", ".", "header", "[", "'Precedence'", "]", "=", "'list'", "message", ".", "header", "[", "'List-Id'", "]", "=", "list_id", "deliver", "(", "message", ")", "end", "end" ]
Send the same mail as is to all receivers, if any.
[ "Send", "the", "same", "mail", "as", "is", "to", "all", "receivers", "if", "any", "." ]
0ee7e5e7affea62b2338ad11d3bbe3e44448e968
https://github.com/codez/mail_relay/blob/0ee7e5e7affea62b2338ad11d3bbe3e44448e968/lib/mail_relay/base.rb#L64-L79
6,574
codez/mail_relay
lib/mail_relay/base.rb
MailRelay.Base.receiver_from_received_header
def receiver_from_received_header if received = message.received received = received.first if received.respond_to?(:first) received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1] end end
ruby
def receiver_from_received_header if received = message.received received = received.first if received.respond_to?(:first) received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1] end end
[ "def", "receiver_from_received_header", "if", "received", "=", "message", ".", "received", "received", "=", "received", ".", "first", "if", "received", ".", "respond_to?", "(", ":first", ")", "received", ".", "info", "[", "/", "\\s", "\\s", "/", ",", "1", "]", "end", "end" ]
Heuristic method to find actual receiver of the message. May return nil if could not determine.
[ "Heuristic", "method", "to", "find", "actual", "receiver", "of", "the", "message", ".", "May", "return", "nil", "if", "could", "not", "determine", "." ]
0ee7e5e7affea62b2338ad11d3bbe3e44448e968
https://github.com/codez/mail_relay/blob/0ee7e5e7affea62b2338ad11d3bbe3e44448e968/lib/mail_relay/base.rb#L110-L115
6,575
rogerleite/http_monkey
lib/http_monkey/client/environment.rb
HttpMonkey.Client::Environment.uri=
def uri=(uri) self['SERVER_NAME'] = uri.host self['SERVER_PORT'] = uri.port.to_s self['QUERY_STRING'] = (uri.query || "") self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path self['rack.url_scheme'] = uri.scheme self['HTTPS'] = (uri.scheme == "https" ? "on" : "off") self['REQUEST_URI'] = uri.request_uri self['HTTP_HOST'] = uri.host end
ruby
def uri=(uri) self['SERVER_NAME'] = uri.host self['SERVER_PORT'] = uri.port.to_s self['QUERY_STRING'] = (uri.query || "") self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path self['rack.url_scheme'] = uri.scheme self['HTTPS'] = (uri.scheme == "https" ? "on" : "off") self['REQUEST_URI'] = uri.request_uri self['HTTP_HOST'] = uri.host end
[ "def", "uri", "=", "(", "uri", ")", "self", "[", "'SERVER_NAME'", "]", "=", "uri", ".", "host", "self", "[", "'SERVER_PORT'", "]", "=", "uri", ".", "port", ".", "to_s", "self", "[", "'QUERY_STRING'", "]", "=", "(", "uri", ".", "query", "||", "\"\"", ")", "self", "[", "'PATH_INFO'", "]", "=", "(", "!", "uri", ".", "path", "||", "uri", ".", "path", ".", "empty?", ")", "?", "\"/\"", ":", "uri", ".", "path", "self", "[", "'rack.url_scheme'", "]", "=", "uri", ".", "scheme", "self", "[", "'HTTPS'", "]", "=", "(", "uri", ".", "scheme", "==", "\"https\"", "?", "\"on\"", ":", "\"off\"", ")", "self", "[", "'REQUEST_URI'", "]", "=", "uri", ".", "request_uri", "self", "[", "'HTTP_HOST'", "]", "=", "uri", ".", "host", "end" ]
Sets uri as Rack wants.
[ "Sets", "uri", "as", "Rack", "wants", "." ]
b57a972e97c60a017754200eef2094562ca546ef
https://github.com/rogerleite/http_monkey/blob/b57a972e97c60a017754200eef2094562ca546ef/lib/http_monkey/client/environment.rb#L62-L71
6,576
rogerleite/http_monkey
lib/http_monkey/client/environment.rb
HttpMonkey.Client::Environment.uri
def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI.parse(uri) rescue StandardError => e raise ArgumentError, "Invalid #{uri}", e.backtrace end end
ruby
def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI.parse(uri) rescue StandardError => e raise ArgumentError, "Invalid #{uri}", e.backtrace end end
[ "def", "uri", "uri", "=", "%Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}}", "begin", "URI", ".", "parse", "(", "uri", ")", "rescue", "StandardError", "=>", "e", "raise", "ArgumentError", ",", "\"Invalid #{uri}\"", ",", "e", ".", "backtrace", "end", "end" ]
Returns uri from Rack environment. Throws ArgumentError for invalid uri.
[ "Returns", "uri", "from", "Rack", "environment", ".", "Throws", "ArgumentError", "for", "invalid", "uri", "." ]
b57a972e97c60a017754200eef2094562ca546ef
https://github.com/rogerleite/http_monkey/blob/b57a972e97c60a017754200eef2094562ca546ef/lib/http_monkey/client/environment.rb#L75-L82
6,577
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/menus_controller.rb
Roroacms.Admin::MenusController.edit
def edit @menu = Menu.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name) set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name)) end
ruby
def edit @menu = Menu.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name) set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name)) end
[ "def", "edit", "@menu", "=", "Menu", ".", "find", "(", "params", "[", ":id", "]", ")", "# add breadcrumb and set title", "add_breadcrumb", "I18n", ".", "t", "(", "\"controllers.admin.menus.edit.breadcrumb\"", ",", "menu_name", ":", "@menu", ".", "name", ")", "set_title", "(", "I18n", ".", "t", "(", "\"controllers.admin.menus.edit.title\"", ",", "menu_name", ":", "@menu", ".", "name", ")", ")", "end" ]
get menu object and display it for editing
[ "get", "menu", "object", "and", "display", "it", "for", "editing" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/menus_controller.rb#L43-L49
6,578
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/menus_controller.rb
Roroacms.Admin::MenusController.destroy
def destroy @menu = Menu.find(params[:id]) @menu.destroy respond_to do |format| format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") } end end
ruby
def destroy @menu = Menu.find(params[:id]) @menu.destroy respond_to do |format| format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") } end end
[ "def", "destroy", "@menu", "=", "Menu", ".", "find", "(", "params", "[", ":id", "]", ")", "@menu", ".", "destroy", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_menus_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.menus.destroy.flash.success\"", ")", "}", "end", "end" ]
deletes the whole menu. Although there is a delete button on each menu option this just removes it from the list which is then interpreted when you save the menu as a whole.
[ "deletes", "the", "whole", "menu", ".", "Although", "there", "is", "a", "delete", "button", "on", "each", "menu", "option", "this", "just", "removes", "it", "from", "the", "list", "which", "is", "then", "interpreted", "when", "you", "save", "the", "menu", "as", "a", "whole", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/menus_controller.rb#L55-L62
6,579
tongueroo/chap
lib/chap/hook.rb
Chap.Hook.symlink_configs
def symlink_configs paths = Dir.glob("#{shared_path}/config/**/*"). select {|p| File.file?(p) } paths.each do |src| relative_path = src.gsub(%r{.*config/},'config/') dest = "#{release_path}/#{relative_path}" # make sure the directory exist for symlink creation dirname = File.dirname(dest) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) FileUtils.rm_rf(dest) if File.exist?(dest) FileUtils.ln_s(src,dest) end end
ruby
def symlink_configs paths = Dir.glob("#{shared_path}/config/**/*"). select {|p| File.file?(p) } paths.each do |src| relative_path = src.gsub(%r{.*config/},'config/') dest = "#{release_path}/#{relative_path}" # make sure the directory exist for symlink creation dirname = File.dirname(dest) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) FileUtils.rm_rf(dest) if File.exist?(dest) FileUtils.ln_s(src,dest) end end
[ "def", "symlink_configs", "paths", "=", "Dir", ".", "glob", "(", "\"#{shared_path}/config/**/*\"", ")", ".", "select", "{", "|", "p", "|", "File", ".", "file?", "(", "p", ")", "}", "paths", ".", "each", "do", "|", "src", "|", "relative_path", "=", "src", ".", "gsub", "(", "%r{", "}", ",", "'config/'", ")", "dest", "=", "\"#{release_path}/#{relative_path}\"", "# make sure the directory exist for symlink creation", "dirname", "=", "File", ".", "dirname", "(", "dest", ")", "FileUtils", ".", "mkdir_p", "(", "dirname", ")", "unless", "File", ".", "exist?", "(", "dirname", ")", "FileUtils", ".", "rm_rf", "(", "dest", ")", "if", "File", ".", "exist?", "(", "dest", ")", "FileUtils", ".", "ln_s", "(", "src", ",", "dest", ")", "end", "end" ]
hook helper methods
[ "hook", "helper", "methods" ]
317cebeace6cbae793ecd0e4a3d357c671ac1106
https://github.com/tongueroo/chap/blob/317cebeace6cbae793ecd0e4a3d357c671ac1106/lib/chap/hook.rb#L18-L30
6,580
skellock/motion-mastr
lib/motion-mastr/mastr_builder.rb
MotionMastr.MastrBuilder.apply_attributes
def apply_attributes(attributed_string, start, length, styles) return unless attributed_string && start && length && styles # sanity return unless start >= 0 && length > 0 && styles.length > 0 # minimums return unless start + length <= attributed_string.length # maximums range = [start, length] ATTRIBUTES.each_pair do |method_name, attribute_name| value = send method_name, styles attributed_string.addAttribute(attribute_name, value: value, range: range) if value end end
ruby
def apply_attributes(attributed_string, start, length, styles) return unless attributed_string && start && length && styles # sanity return unless start >= 0 && length > 0 && styles.length > 0 # minimums return unless start + length <= attributed_string.length # maximums range = [start, length] ATTRIBUTES.each_pair do |method_name, attribute_name| value = send method_name, styles attributed_string.addAttribute(attribute_name, value: value, range: range) if value end end
[ "def", "apply_attributes", "(", "attributed_string", ",", "start", ",", "length", ",", "styles", ")", "return", "unless", "attributed_string", "&&", "start", "&&", "length", "&&", "styles", "# sanity", "return", "unless", "start", ">=", "0", "&&", "length", ">", "0", "&&", "styles", ".", "length", ">", "0", "# minimums", "return", "unless", "start", "+", "length", "<=", "attributed_string", ".", "length", "# maximums", "range", "=", "[", "start", ",", "length", "]", "ATTRIBUTES", ".", "each_pair", "do", "|", "method_name", ",", "attribute_name", "|", "value", "=", "send", "method_name", ",", "styles", "attributed_string", ".", "addAttribute", "(", "attribute_name", ",", "value", ":", "value", ",", "range", ":", "range", ")", "if", "value", "end", "end" ]
applies styles in a range to the attributed string
[ "applies", "styles", "in", "a", "range", "to", "the", "attributed", "string" ]
db95803be3a7865f967ad7499dff4e2d0aee8570
https://github.com/skellock/motion-mastr/blob/db95803be3a7865f967ad7499dff4e2d0aee8570/lib/motion-mastr/mastr_builder.rb#L72-L83
6,581
rsanders/transaction_reliability
lib/transaction_reliability.rb
TransactionReliability.Helpers.with_transaction_retry
def with_transaction_retry(options = {}) retry_count = options.fetch(:retry_count, 4) backoff = options.fetch(:backoff, 0.25) exit_on_fail = options.fetch(:exit_on_fail, false) exit_on_disconnect = options.fetch(:exit_on_disconnect, true) count = 0 # list of exceptions we may catch exceptions = ['ActiveRecord::StatementInvalid', 'PG::Error', 'Mysql2::Error']. map {|name| name.safe_constantize}. compact # # There are times when, for example, # a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid # # Also, connector-specific classes like PG::Error may not be defined # begin connection_lost = false yield rescue *exceptions => e translated = TransactionReliability.rewrap_exception(e) case translated when ConnectionLost (options[:connection] || ActiveRecord::Base.connection).reconnect! connection_lost = true when DeadlockDetected, SerializationFailure else raise translated end # Retry up to retry_count times if count < retry_count sleep backoff count += 1 backoff *= 2 retry else if (connection_lost && exit_on_disconnect) || exit_on_fail exit else raise(translated) end end end end
ruby
def with_transaction_retry(options = {}) retry_count = options.fetch(:retry_count, 4) backoff = options.fetch(:backoff, 0.25) exit_on_fail = options.fetch(:exit_on_fail, false) exit_on_disconnect = options.fetch(:exit_on_disconnect, true) count = 0 # list of exceptions we may catch exceptions = ['ActiveRecord::StatementInvalid', 'PG::Error', 'Mysql2::Error']. map {|name| name.safe_constantize}. compact # # There are times when, for example, # a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid # # Also, connector-specific classes like PG::Error may not be defined # begin connection_lost = false yield rescue *exceptions => e translated = TransactionReliability.rewrap_exception(e) case translated when ConnectionLost (options[:connection] || ActiveRecord::Base.connection).reconnect! connection_lost = true when DeadlockDetected, SerializationFailure else raise translated end # Retry up to retry_count times if count < retry_count sleep backoff count += 1 backoff *= 2 retry else if (connection_lost && exit_on_disconnect) || exit_on_fail exit else raise(translated) end end end end
[ "def", "with_transaction_retry", "(", "options", "=", "{", "}", ")", "retry_count", "=", "options", ".", "fetch", "(", ":retry_count", ",", "4", ")", "backoff", "=", "options", ".", "fetch", "(", ":backoff", ",", "0.25", ")", "exit_on_fail", "=", "options", ".", "fetch", "(", ":exit_on_fail", ",", "false", ")", "exit_on_disconnect", "=", "options", ".", "fetch", "(", ":exit_on_disconnect", ",", "true", ")", "count", "=", "0", "# list of exceptions we may catch", "exceptions", "=", "[", "'ActiveRecord::StatementInvalid'", ",", "'PG::Error'", ",", "'Mysql2::Error'", "]", ".", "map", "{", "|", "name", "|", "name", ".", "safe_constantize", "}", ".", "compact", "#", "# There are times when, for example, ", "# a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid", "#", "# Also, connector-specific classes like PG::Error may not be defined", "#", "begin", "connection_lost", "=", "false", "yield", "rescue", "exceptions", "=>", "e", "translated", "=", "TransactionReliability", ".", "rewrap_exception", "(", "e", ")", "case", "translated", "when", "ConnectionLost", "(", "options", "[", ":connection", "]", "||", "ActiveRecord", "::", "Base", ".", "connection", ")", ".", "reconnect!", "connection_lost", "=", "true", "when", "DeadlockDetected", ",", "SerializationFailure", "else", "raise", "translated", "end", "# Retry up to retry_count times", "if", "count", "<", "retry_count", "sleep", "backoff", "count", "+=", "1", "backoff", "*=", "2", "retry", "else", "if", "(", "connection_lost", "&&", "exit_on_disconnect", ")", "||", "exit_on_fail", "exit", "else", "raise", "(", "translated", ")", "end", "end", "end", "end" ]
Intended to be included in an ActiveRecord model class. Retries a block (which usually contains a transaction) under certain failure conditions, up to a configurable number of times with an exponential backoff delay between each attempt. Conditions for retrying: 1. Database connection lost 2. Query or txn failed due to detected deadlock (Mysql/InnoDB and Postgres can both signal this for just about any transaction) 3. Query or txn failed due to serialization failure (Postgres will signal this for transactions in isolation level SERIALIZABLE) options: retry_count - how many retries to make; default 4 backoff - time period before 1st retry, in fractional seconds. will double at every retry. default 0.25 seconds. exit_on_disconnect - whether to call exit if no retry succeeds and the cause is a failed connection exit_on_fail - whether to call exit if no retry succeeds defaults:
[ "Intended", "to", "be", "included", "in", "an", "ActiveRecord", "model", "class", "." ]
9a314f7c3284452b5e3fb1bd17c6ff89784b5764
https://github.com/rsanders/transaction_reliability/blob/9a314f7c3284452b5e3fb1bd17c6ff89784b5764/lib/transaction_reliability.rb#L76-L124
6,582
rsanders/transaction_reliability
lib/transaction_reliability.rb
TransactionReliability.Helpers.transaction_with_retry
def transaction_with_retry(txn_options = {}, retry_options = {}) base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base with_transaction_retry(retry_options) do base_obj.transaction(txn_options) do yield end end end
ruby
def transaction_with_retry(txn_options = {}, retry_options = {}) base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base with_transaction_retry(retry_options) do base_obj.transaction(txn_options) do yield end end end
[ "def", "transaction_with_retry", "(", "txn_options", "=", "{", "}", ",", "retry_options", "=", "{", "}", ")", "base_obj", "=", "self", ".", "respond_to?", "(", ":transaction", ")", "?", "self", ":", "ActiveRecord", "::", "Base", "with_transaction_retry", "(", "retry_options", ")", "do", "base_obj", ".", "transaction", "(", "txn_options", ")", "do", "yield", "end", "end", "end" ]
Execute some code in a DB transaction, with retry
[ "Execute", "some", "code", "in", "a", "DB", "transaction", "with", "retry" ]
9a314f7c3284452b5e3fb1bd17c6ff89784b5764
https://github.com/rsanders/transaction_reliability/blob/9a314f7c3284452b5e3fb1bd17c6ff89784b5764/lib/transaction_reliability.rb#L129-L137
6,583
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.connect_to_unit
def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket.new @host, @port @ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context @ssl_client.connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end
ruby
def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket.new @host, @port @ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context @ssl_client.connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end
[ "def", "connect_to_unit", "puts", "\"Connecting to '#{@host}...\"", "begin", "tcp_client", "=", "TCPSocket", ".", "new", "@host", ",", "@port", "@ssl_client", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "tcp_client", ",", "@context", "@ssl_client", ".", "connect", "rescue", "Exception", "=>", "e", "puts", "\"Could not connect to '#{@host}: #{e}\"", "end", "end" ]
Initializes the TV class. @param [Object] cert SSL certificate for this client @param [String] host hostname or IP address of the Google TV @param [Number] port port number of the Google TV @return an instance of TV Connect this object to a Google TV
[ "Initializes", "the", "TV", "class", "." ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L35-L44
6,584
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.fling_uri
def fling_uri(uri) send_request RequestMessage.new(fling_message: Fling.new(uri: uri)) end
ruby
def fling_uri(uri) send_request RequestMessage.new(fling_message: Fling.new(uri: uri)) end
[ "def", "fling_uri", "(", "uri", ")", "send_request", "RequestMessage", ".", "new", "(", "fling_message", ":", "Fling", ".", "new", "(", "uri", ":", "uri", ")", ")", "end" ]
Fling a URI to the Google TV connected to this object This is used send the Google Chrome browser to a web page
[ "Fling", "a", "URI", "to", "the", "Google", "TV", "connected", "to", "this", "object", "This", "is", "used", "send", "the", "Google", "Chrome", "browser", "to", "a", "web", "page" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L55-L57
6,585
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_keycode
def send_keycode(keycode) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN)) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP)) end
ruby
def send_keycode(keycode) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN)) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP)) end
[ "def", "send_keycode", "(", "keycode", ")", "send_request", "RequestMessage", ".", "new", "(", "key_event_message", ":", "KeyEvent", ".", "new", "(", "keycode", ":", "keycode", ",", "action", ":", "Action", "::", "DOWN", ")", ")", "send_request", "RequestMessage", ".", "new", "(", "key_event_message", ":", "KeyEvent", ".", "new", "(", "keycode", ":", "keycode", ",", "action", ":", "Action", "::", "UP", ")", ")", "end" ]
Send a keystroke to the Google TV This is used for things like hitting the ENTER key
[ "Send", "a", "keystroke", "to", "the", "Google", "TV", "This", "is", "used", "for", "things", "like", "hitting", "the", "ENTER", "key" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L62-L65
6,586
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_data
def send_data(msg) send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg)) end
ruby
def send_data(msg) send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg)) end
[ "def", "send_data", "(", "msg", ")", "send_request", "RequestMessage", ".", "new", "(", "data_message", ":", "Data1", ".", "new", "(", "type", ":", "\"com.google.tv.string\"", ",", "data", ":", "msg", ")", ")", "end" ]
Send a string to the Google TV. This is used for things like typing into text boxes.
[ "Send", "a", "string", "to", "the", "Google", "TV", ".", "This", "is", "used", "for", "things", "like", "typing", "into", "text", "boxes", "." ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L70-L72
6,587
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.move_mouse
def move_mouse(x_delta, y_delta) send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta)) end
ruby
def move_mouse(x_delta, y_delta) send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta)) end
[ "def", "move_mouse", "(", "x_delta", ",", "y_delta", ")", "send_request", "RequestMessage", ".", "new", "(", "mouse_event_message", ":", "MouseEvent", ".", "new", "(", "x_delta", ":", "x_delta", ",", "y_delta", ":", "y_delta", ")", ")", "end" ]
Move the mouse relative to its current position
[ "Move", "the", "mouse", "relative", "to", "its", "current", "position" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L76-L78
6,588
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.scroll_mouse
def scroll_mouse(x_amount, y_amount) send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount)) end
ruby
def scroll_mouse(x_amount, y_amount) send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount)) end
[ "def", "scroll_mouse", "(", "x_amount", ",", "y_amount", ")", "send_request", "RequestMessage", ".", "new", "(", "mouse_wheel_message", ":", "MouseWheel", ".", "new", "(", "x_scroll", ":", "x_amount", ",", "y_scroll", ":", "y_amount", ")", ")", "end" ]
Scroll the mouse wheel a certain amount
[ "Scroll", "the", "mouse", "wheel", "a", "certain", "amount" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L82-L84
6,589
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_request
def send_request(request) message = RemoteMessage.new(request_message: request).serialize_to_string message_size = [message.length].pack('N') @ssl_client.write(message_size + message) end
ruby
def send_request(request) message = RemoteMessage.new(request_message: request).serialize_to_string message_size = [message.length].pack('N') @ssl_client.write(message_size + message) end
[ "def", "send_request", "(", "request", ")", "message", "=", "RemoteMessage", ".", "new", "(", "request_message", ":", "request", ")", ".", "serialize_to_string", "message_size", "=", "[", "message", ".", "length", "]", ".", "pack", "(", "'N'", ")", "@ssl_client", ".", "write", "(", "message_size", "+", "message", ")", "end" ]
Send a request to the Google TV and don't wait for a response
[ "Send", "a", "request", "to", "the", "Google", "TV", "and", "don", "t", "wait", "for", "a", "response" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L90-L94
6,590
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_message
def send_message(msg) # Build the message and get it's size message = msg.serialize_to_string message_size = [message.length].pack('N') # Try to send the message try_again = true begin data = "" @ssl_client.write(message_size + message) @ssl_client.readpartial(1000,data) rescue # Sometimes our connection might drop or something, so # we'll reconnect to the unit and try to send the message again. if try_again try_again = false connect_to_unit retry else # Looks like we couldn't connect to the unit after all. puts "message not sent" end end return data end
ruby
def send_message(msg) # Build the message and get it's size message = msg.serialize_to_string message_size = [message.length].pack('N') # Try to send the message try_again = true begin data = "" @ssl_client.write(message_size + message) @ssl_client.readpartial(1000,data) rescue # Sometimes our connection might drop or something, so # we'll reconnect to the unit and try to send the message again. if try_again try_again = false connect_to_unit retry else # Looks like we couldn't connect to the unit after all. puts "message not sent" end end return data end
[ "def", "send_message", "(", "msg", ")", "# Build the message and get it's size", "message", "=", "msg", ".", "serialize_to_string", "message_size", "=", "[", "message", ".", "length", "]", ".", "pack", "(", "'N'", ")", "# Try to send the message", "try_again", "=", "true", "begin", "data", "=", "\"\"", "@ssl_client", ".", "write", "(", "message_size", "+", "message", ")", "@ssl_client", ".", "readpartial", "(", "1000", ",", "data", ")", "rescue", "# Sometimes our connection might drop or something, so", "# we'll reconnect to the unit and try to send the message again.", "if", "try_again", "try_again", "=", "false", "connect_to_unit", "retry", "else", "# Looks like we couldn't connect to the unit after all.", "puts", "\"message not sent\"", "end", "end", "return", "data", "end" ]
Send a message to the Google TV and return the response
[ "Send", "a", "message", "to", "the", "Google", "TV", "and", "return", "the", "response" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L98-L123
6,591
williambarry007/caboose-store
lib/caboose-store/caboose_store_helper.rb
CabooseStore.CabooseStoreHelper.init_routes
def init_routes puts "Adding the caboose store routes..." filename = File.join(@app_path,'config','routes.rb') return if !File.exists?(filename) return if !@force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" file = File.open(filename, 'rb') contents = file.read file.close if (contents.index(str).nil?) arr = contents.split('end', -1) str2 = arr[0] + "\n" + str + "\nend" + arr[1] File.open(filename, 'w') {|file| file.write(str2) } end end
ruby
def init_routes puts "Adding the caboose store routes..." filename = File.join(@app_path,'config','routes.rb') return if !File.exists?(filename) return if !@force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" file = File.open(filename, 'rb') contents = file.read file.close if (contents.index(str).nil?) arr = contents.split('end', -1) str2 = arr[0] + "\n" + str + "\nend" + arr[1] File.open(filename, 'w') {|file| file.write(str2) } end end
[ "def", "init_routes", "puts", "\"Adding the caboose store routes...\"", "filename", "=", "File", ".", "join", "(", "@app_path", ",", "'config'", ",", "'routes.rb'", ")", "return", "if", "!", "File", ".", "exists?", "(", "filename", ")", "return", "if", "!", "@force", "str", "=", "\"\"", "str", "<<", "\"\\t# Catch everything with caboose\\n\"", "str", "<<", "\"\\tmount CabooseStore::Engine => '/'\\n\"", "file", "=", "File", ".", "open", "(", "filename", ",", "'rb'", ")", "contents", "=", "file", ".", "read", "file", ".", "close", "if", "(", "contents", ".", "index", "(", "str", ")", ".", "nil?", ")", "arr", "=", "contents", ".", "split", "(", "'end'", ",", "-", "1", ")", "str2", "=", "arr", "[", "0", "]", "+", "\"\\n\"", "+", "str", "+", "\"\\nend\"", "+", "arr", "[", "1", "]", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "str2", ")", "}", "end", "end" ]
Adds the routes to the host app to point everything to caboose
[ "Adds", "the", "routes", "to", "the", "host", "app", "to", "point", "everything", "to", "caboose" ]
997970e1e332f6180a8674324da5331c192d7d54
https://github.com/williambarry007/caboose-store/blob/997970e1e332f6180a8674324da5331c192d7d54/lib/caboose-store/caboose_store_helper.rb#L13-L32
6,592
subimage/cashboard-rb
lib/cashboard/errors.rb
Cashboard.BadRequest.errors
def errors parsed_errors = XmlSimple.xml_in(response.response.body) error_hash = {} parsed_errors['error'].each do |e| error_hash[e['field']] = e['content'] end return error_hash end
ruby
def errors parsed_errors = XmlSimple.xml_in(response.response.body) error_hash = {} parsed_errors['error'].each do |e| error_hash[e['field']] = e['content'] end return error_hash end
[ "def", "errors", "parsed_errors", "=", "XmlSimple", ".", "xml_in", "(", "response", ".", "response", ".", "body", ")", "error_hash", "=", "{", "}", "parsed_errors", "[", "'error'", "]", ".", "each", "do", "|", "e", "|", "error_hash", "[", "e", "[", "'field'", "]", "]", "=", "e", "[", "'content'", "]", "end", "return", "error_hash", "end" ]
Returns a hash of errors keyed on field name. Return Example { :field_name_one => "Error message", :field_name_two => "Error message" }
[ "Returns", "a", "hash", "of", "errors", "keyed", "on", "field", "name", "." ]
320e311ea1549cdd0dada0f8a0a4f9942213b28f
https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/errors.rb#L39-L46
6,593
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.clients
def clients(options = {}) post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj } end
ruby
def clients(options = {}) post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj } end
[ "def", "clients", "(", "options", "=", "{", "}", ")", "post", "(", "\"/clients\"", ",", "options", ")", "[", "\"clients\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The clients method will return a list of all clients and can only be accessed by admins on the subscription. Optional paramaters: open => [true|false]
[ "The", "clients", "method", "will", "return", "a", "list", "of", "all", "clients", "and", "can", "only", "be", "accessed", "by", "admins", "on", "the", "subscription", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L23-L25
6,594
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.projects
def projects(options = {}) post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj } end
ruby
def projects(options = {}) post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj } end
[ "def", "projects", "(", "options", "=", "{", "}", ")", "post", "(", "\"/projects\"", ",", "options", ")", "[", "\"projects\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The projects method will return projects filtered by the parameters provided. Admin can see all projects on the subscription, while non-admins can only access the projects they are assigned. Optional parameters: project_id open [true|false] project_billable [true|false]
[ "The", "projects", "method", "will", "return", "projects", "filtered", "by", "the", "parameters", "provided", ".", "Admin", "can", "see", "all", "projects", "on", "the", "subscription", "while", "non", "-", "admins", "can", "only", "access", "the", "projects", "they", "are", "assigned", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L36-L38
6,595
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.tasks
def tasks(options = {}) post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj } end
ruby
def tasks(options = {}) post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj } end
[ "def", "tasks", "(", "options", "=", "{", "}", ")", "post", "(", "\"/tasks\"", ",", "options", ")", "[", "\"tasks\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The tasks method will return a list of all the current tasks for a specified project and can only be accessed by admins on the subscription. Required parameters: project_id Optional Parameters: task_id open [true|false] task_billable [true|false]
[ "The", "tasks", "method", "will", "return", "a", "list", "of", "all", "the", "current", "tasks", "for", "a", "specified", "project", "and", "can", "only", "be", "accessed", "by", "admins", "on", "the", "subscription", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L51-L53
6,596
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.entries
def entries(options = {}) post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj } end
ruby
def entries(options = {}) post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj } end
[ "def", "entries", "(", "options", "=", "{", "}", ")", "post", "(", "\"/entries\"", ",", "options", ")", "[", "\"entries\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The entries method will return a list of all entries that meet the provided criteria. Either a start and end date have to be provided or an updated_at time. The entries will be in the start and end date range or they will be after the updated_at time depending on what criteria is provided. Each of the optional parameters will further filter the response. Required parameters: start_date end_date OR updated_at Optional Parameters: project_id task_id user_id user_email client_id entry_billable [true|false] billed [true|false]
[ "The", "entries", "method", "will", "return", "a", "list", "of", "all", "entries", "that", "meet", "the", "provided", "criteria", ".", "Either", "a", "start", "and", "end", "date", "have", "to", "be", "provided", "or", "an", "updated_at", "time", ".", "The", "entries", "will", "be", "in", "the", "start", "and", "end", "date", "range", "or", "they", "will", "be", "after", "the", "updated_at", "time", "depending", "on", "what", "criteria", "is", "provided", ".", "Each", "of", "the", "optional", "parameters", "will", "further", "filter", "the", "response", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L83-L85
6,597
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.users
def users(options = {}) post("/users", options)['users'].map {|obj| Hashie::Mash.new obj } end
ruby
def users(options = {}) post("/users", options)['users'].map {|obj| Hashie::Mash.new obj } end
[ "def", "users", "(", "options", "=", "{", "}", ")", "post", "(", "\"/users\"", ",", "options", ")", "[", "'users'", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The users method will return a list of users. Optional parameters: project_id
[ "The", "users", "method", "will", "return", "a", "list", "of", "users", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L99-L101
6,598
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.cache
def cache(key = nil) key ||= BasicCache.caller_name key = key.to_sym if include? key @store[key].value else value = yield @store[key] = TimeCacheItem.new Time.now, value value end end
ruby
def cache(key = nil) key ||= BasicCache.caller_name key = key.to_sym if include? key @store[key].value else value = yield @store[key] = TimeCacheItem.new Time.now, value value end end
[ "def", "cache", "(", "key", "=", "nil", ")", "key", "||=", "BasicCache", ".", "caller_name", "key", "=", "key", ".", "to_sym", "if", "include?", "key", "@store", "[", "key", "]", ".", "value", "else", "value", "=", "yield", "@store", "[", "key", "]", "=", "TimeCacheItem", ".", "new", "Time", ".", "now", ",", "value", "value", "end", "end" ]
Return a value from the cache, or calculate it and store it Recalculate if the cached value has expired
[ "Return", "a", "value", "from", "the", "cache", "or", "calculate", "it", "and", "store", "it", "Recalculate", "if", "the", "cached", "value", "has", "expired" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L34-L44
6,599
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.include?
def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end
ruby
def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end
[ "def", "include?", "(", "key", "=", "nil", ")", "key", "||=", "BasicCache", ".", "caller_name", "key", "=", "key", ".", "to_sym", "@store", ".", "include?", "(", "key", ")", "&&", "Time", ".", "now", "-", "@store", "[", "key", "]", ".", "stamp", "<", "@lifetime", "end" ]
Check if a value is cached and not expired
[ "Check", "if", "a", "value", "is", "cached", "and", "not", "expired" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L49-L53