repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/pages_controller.rb
Alchemy.Api::PagesController.nested
def nested @page = Page.find_by(id: params[:page_id]) || Language.current_root_page render json: PageTreeSerializer.new(@page, ability: current_ability, user: current_alchemy_user, elements: params[:elements], full: true) end
ruby
def nested @page = Page.find_by(id: params[:page_id]) || Language.current_root_page render json: PageTreeSerializer.new(@page, ability: current_ability, user: current_alchemy_user, elements: params[:elements], full: true) end
[ "def", "nested", "@page", "=", "Page", ".", "find_by", "(", "id", ":", "params", "[", ":page_id", "]", ")", "||", "Language", ".", "current_root_page", "render", "json", ":", "PageTreeSerializer", ".", "new", "(", "@page", ",", "ability", ":", "current_ability", ",", "user", ":", "current_alchemy_user", ",", "elements", ":", "params", "[", ":elements", "]", ",", "full", ":", "true", ")", "end" ]
Returns all pages as nested json object for tree views Pass a page_id param to only load tree for this page Pass elements=true param to include elements for pages
[ "Returns", "all", "pages", "as", "nested", "json", "object", "for", "tree", "views" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/pages_controller.rb#L28-L36
train
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/elements_controller.rb
Alchemy.Api::ElementsController.index
def index @elements = Element.not_nested # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:page_id].present? @elements = @elements.where(page_id: params[:page_id]) end if params[:named].present? @elements = @elements.named(params[:named]) end render json: @elements, adapter: :json, root: :elements end
ruby
def index @elements = Element.not_nested # Fix for cancancan not able to merge multiple AR scopes for logged in users if cannot? :manage, Alchemy::Element @elements = @elements.accessible_by(current_ability, :index) end if params[:page_id].present? @elements = @elements.where(page_id: params[:page_id]) end if params[:named].present? @elements = @elements.named(params[:named]) end render json: @elements, adapter: :json, root: :elements end
[ "def", "index", "@elements", "=", "Element", ".", "not_nested", "# Fix for cancancan not able to merge multiple AR scopes for logged in users", "if", "cannot?", ":manage", ",", "Alchemy", "::", "Element", "@elements", "=", "@elements", ".", "accessible_by", "(", "current_ability", ",", ":index", ")", "end", "if", "params", "[", ":page_id", "]", ".", "present?", "@elements", "=", "@elements", ".", "where", "(", "page_id", ":", "params", "[", ":page_id", "]", ")", "end", "if", "params", "[", ":named", "]", ".", "present?", "@elements", "=", "@elements", ".", "named", "(", "params", "[", ":named", "]", ")", "end", "render", "json", ":", "@elements", ",", "adapter", ":", ":json", ",", "root", ":", ":elements", "end" ]
Returns all elements as json object You can either load all or only these for :page_id param If you want to only load a specific type of element pass ?named=an_element_name
[ "Returns", "all", "elements", "as", "json", "object" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/elements_controller.rb#L11-L24
train
AlchemyCMS/alchemy_cms
lib/alchemy/configuration_methods.rb
Alchemy.ConfigurationMethods.prefix_locale?
def prefix_locale?(locale = Language.current.code) multi_language? && locale != ::I18n.default_locale.to_s end
ruby
def prefix_locale?(locale = Language.current.code) multi_language? && locale != ::I18n.default_locale.to_s end
[ "def", "prefix_locale?", "(", "locale", "=", "Language", ".", "current", ".", "code", ")", "multi_language?", "&&", "locale", "!=", "::", "I18n", ".", "default_locale", ".", "to_s", "end" ]
Decides if the locale should be prefixed to urls If the current language's locale (or the optionally passed in locale) matches the current I18n.locale then the prefix os omitted. Also, if only one published language exists.
[ "Decides", "if", "the", "locale", "should", "be", "prefixed", "to", "urls" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/configuration_methods.rb#L31-L33
train
AlchemyCMS/alchemy_cms
lib/alchemy/modules.rb
Alchemy.Modules.module_definition_for
def module_definition_for(name_or_params) case name_or_params when String alchemy_modules.detect { |m| m['name'] == name_or_params } when Hash name_or_params.stringify_keys! alchemy_modules.detect do |alchemy_module| module_navi = alchemy_module.fetch('navigation', {}) definition_from_mainnavi(module_navi, name_or_params) || definition_from_subnavi(module_navi, name_or_params) end else raise ArgumentError, "Could not find module definition for #{name_or_params}" end end
ruby
def module_definition_for(name_or_params) case name_or_params when String alchemy_modules.detect { |m| m['name'] == name_or_params } when Hash name_or_params.stringify_keys! alchemy_modules.detect do |alchemy_module| module_navi = alchemy_module.fetch('navigation', {}) definition_from_mainnavi(module_navi, name_or_params) || definition_from_subnavi(module_navi, name_or_params) end else raise ArgumentError, "Could not find module definition for #{name_or_params}" end end
[ "def", "module_definition_for", "(", "name_or_params", ")", "case", "name_or_params", "when", "String", "alchemy_modules", ".", "detect", "{", "|", "m", "|", "m", "[", "'name'", "]", "==", "name_or_params", "}", "when", "Hash", "name_or_params", ".", "stringify_keys!", "alchemy_modules", ".", "detect", "do", "|", "alchemy_module", "|", "module_navi", "=", "alchemy_module", ".", "fetch", "(", "'navigation'", ",", "{", "}", ")", "definition_from_mainnavi", "(", "module_navi", ",", "name_or_params", ")", "||", "definition_from_subnavi", "(", "module_navi", ",", "name_or_params", ")", "end", "else", "raise", "ArgumentError", ",", "\"Could not find module definition for #{name_or_params}\"", "end", "end" ]
Get the module definition for given module name You can also pass a hash of an module definition. It then tries to find the module defintion from controller name and action name
[ "Get", "the", "module", "definition", "for", "given", "module", "name" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/lib/alchemy/modules.rb#L66-L80
train
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/contents_controller.rb
Alchemy.Api::ContentsController.index
def index # Fix for cancancan not able to merge multiple AR scopes for logged in users if can? :manage, Alchemy::Content @contents = Content.all else @contents = Content.accessible_by(current_ability, :index) end if params[:element_id].present? @contents = @contents.where(element_id: params[:element_id]) end render json: @contents, adapter: :json, root: :contents end
ruby
def index # Fix for cancancan not able to merge multiple AR scopes for logged in users if can? :manage, Alchemy::Content @contents = Content.all else @contents = Content.accessible_by(current_ability, :index) end if params[:element_id].present? @contents = @contents.where(element_id: params[:element_id]) end render json: @contents, adapter: :json, root: :contents end
[ "def", "index", "# Fix for cancancan not able to merge multiple AR scopes for logged in users", "if", "can?", ":manage", ",", "Alchemy", "::", "Content", "@contents", "=", "Content", ".", "all", "else", "@contents", "=", "Content", ".", "accessible_by", "(", "current_ability", ",", ":index", ")", "end", "if", "params", "[", ":element_id", "]", ".", "present?", "@contents", "=", "@contents", ".", "where", "(", "element_id", ":", "params", "[", ":element_id", "]", ")", "end", "render", "json", ":", "@contents", ",", "adapter", ":", ":json", ",", "root", ":", ":contents", "end" ]
Returns all contents as json object You can either load all or only these for :element_id param
[ "Returns", "all", "contents", "as", "json", "object" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/contents_controller.rb#L9-L20
train
AlchemyCMS/alchemy_cms
app/controllers/alchemy/api/contents_controller.rb
Alchemy.Api::ContentsController.show
def show if params[:id] @content = Content.find(params[:id]) elsif params[:element_id] && params[:name] @content = Content.find_by!(element_id: params[:element_id], name: params[:name]) end authorize! :show, @content respond_with @content end
ruby
def show if params[:id] @content = Content.find(params[:id]) elsif params[:element_id] && params[:name] @content = Content.find_by!(element_id: params[:element_id], name: params[:name]) end authorize! :show, @content respond_with @content end
[ "def", "show", "if", "params", "[", ":id", "]", "@content", "=", "Content", ".", "find", "(", "params", "[", ":id", "]", ")", "elsif", "params", "[", ":element_id", "]", "&&", "params", "[", ":name", "]", "@content", "=", "Content", ".", "find_by!", "(", "element_id", ":", "params", "[", ":element_id", "]", ",", "name", ":", "params", "[", ":name", "]", ")", "end", "authorize!", ":show", ",", "@content", "respond_with", "@content", "end" ]
Returns a json object for content You can either load it from :id param or even more useful via passing the element id and the name of the content $ bin/rake routes for more infos on how the url looks like.
[ "Returns", "a", "json", "object", "for", "content" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/alchemy/api/contents_controller.rb#L31-L39
train
AlchemyCMS/alchemy_cms
app/models/alchemy/site.rb
Alchemy.Site.create_default_language!
def create_default_language! default_language = Alchemy::Config.get(:default_language) if default_language languages.build( name: default_language['name'], language_code: default_language['code'], locale: default_language['code'], frontpage_name: default_language['frontpage_name'], page_layout: default_language['page_layout'], public: true, default: true ) else raise DefaultLanguageNotFoundError end end
ruby
def create_default_language! default_language = Alchemy::Config.get(:default_language) if default_language languages.build( name: default_language['name'], language_code: default_language['code'], locale: default_language['code'], frontpage_name: default_language['frontpage_name'], page_layout: default_language['page_layout'], public: true, default: true ) else raise DefaultLanguageNotFoundError end end
[ "def", "create_default_language!", "default_language", "=", "Alchemy", "::", "Config", ".", "get", "(", ":default_language", ")", "if", "default_language", "languages", ".", "build", "(", "name", ":", "default_language", "[", "'name'", "]", ",", "language_code", ":", "default_language", "[", "'code'", "]", ",", "locale", ":", "default_language", "[", "'code'", "]", ",", "frontpage_name", ":", "default_language", "[", "'frontpage_name'", "]", ",", "page_layout", ":", "default_language", "[", "'page_layout'", "]", ",", "public", ":", "true", ",", "default", ":", "true", ")", "else", "raise", "DefaultLanguageNotFoundError", "end", "end" ]
If no languages are present, create a default language based on the host app's Alchemy configuration.
[ "If", "no", "languages", "are", "present", "create", "a", "default", "language", "based", "on", "the", "host", "app", "s", "Alchemy", "configuration", "." ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/models/alchemy/site.rb#L101-L116
train
AlchemyCMS/alchemy_cms
app/helpers/alchemy/url_helper.rb
Alchemy.UrlHelper.show_page_path_params
def show_page_path_params(page, optional_params = {}) raise ArgumentError, 'Page is nil' if page.nil? url_params = {urlname: page.urlname}.update(optional_params) prefix_locale? ? url_params.update(locale: page.language_code) : url_params end
ruby
def show_page_path_params(page, optional_params = {}) raise ArgumentError, 'Page is nil' if page.nil? url_params = {urlname: page.urlname}.update(optional_params) prefix_locale? ? url_params.update(locale: page.language_code) : url_params end
[ "def", "show_page_path_params", "(", "page", ",", "optional_params", "=", "{", "}", ")", "raise", "ArgumentError", ",", "'Page is nil'", "if", "page", ".", "nil?", "url_params", "=", "{", "urlname", ":", "page", ".", "urlname", "}", ".", "update", "(", "optional_params", ")", "prefix_locale?", "?", "url_params", ".", "update", "(", "locale", ":", "page", ".", "language_code", ")", ":", "url_params", "end" ]
Returns the correct params-hash for passing to show_page_path
[ "Returns", "the", "correct", "params", "-", "hash", "for", "passing", "to", "show_page_path" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/helpers/alchemy/url_helper.rb#L20-L24
train
AlchemyCMS/alchemy_cms
app/controllers/concerns/alchemy/page_redirects.rb
Alchemy.PageRedirects.page_redirect_url
def page_redirect_url(options = {}) options = { locale: prefix_locale? ? @page.language_code : nil, urlname: @page.urlname }.merge(options) alchemy.show_page_path additional_params.merge(options) end
ruby
def page_redirect_url(options = {}) options = { locale: prefix_locale? ? @page.language_code : nil, urlname: @page.urlname }.merge(options) alchemy.show_page_path additional_params.merge(options) end
[ "def", "page_redirect_url", "(", "options", "=", "{", "}", ")", "options", "=", "{", "locale", ":", "prefix_locale?", "?", "@page", ".", "language_code", ":", "nil", ",", "urlname", ":", "@page", ".", "urlname", "}", ".", "merge", "(", "options", ")", "alchemy", ".", "show_page_path", "additional_params", ".", "merge", "(", "options", ")", "end" ]
Page url with or without locale while keeping all additional params
[ "Page", "url", "with", "or", "without", "locale", "while", "keeping", "all", "additional", "params" ]
0e1c5665984ff67d387c8cb4255f805c296c2fb6
https://github.com/AlchemyCMS/alchemy_cms/blob/0e1c5665984ff67d387c8cb4255f805c296c2fb6/app/controllers/concerns/alchemy/page_redirects.rb#L58-L65
train
tandusrl/acts_as_bookable
lib/acts_as_bookable/bookable.rb
ActsAsBookable.Bookable.bookable
def bookable(options) if bookable? self.booking_opts = options else class_attribute :booking_opts self.booking_opts = options class_eval do serialize :schedule, IceCube::Schedule has_many :bookings, as: :bookable, dependent: :destroy, class_name: '::ActsAsBookable::Booking' validates_presence_of :schedule, if: :schedule_required? validates_presence_of :capacity, if: :capacity_required? validates_numericality_of :capacity, if: :capacity_required?, only_integer: true, greater_than_or_equal_to: 0 def self.bookable? true end def schedule_required? self.booking_opts && self.booking_opts && self.booking_opts[:time_type] != :none end def capacity_required? self.booking_opts && self.booking_opts[:capacity_type] != :none end end end include Core end
ruby
def bookable(options) if bookable? self.booking_opts = options else class_attribute :booking_opts self.booking_opts = options class_eval do serialize :schedule, IceCube::Schedule has_many :bookings, as: :bookable, dependent: :destroy, class_name: '::ActsAsBookable::Booking' validates_presence_of :schedule, if: :schedule_required? validates_presence_of :capacity, if: :capacity_required? validates_numericality_of :capacity, if: :capacity_required?, only_integer: true, greater_than_or_equal_to: 0 def self.bookable? true end def schedule_required? self.booking_opts && self.booking_opts && self.booking_opts[:time_type] != :none end def capacity_required? self.booking_opts && self.booking_opts[:capacity_type] != :none end end end include Core end
[ "def", "bookable", "(", "options", ")", "if", "bookable?", "self", ".", "booking_opts", "=", "options", "else", "class_attribute", ":booking_opts", "self", ".", "booking_opts", "=", "options", "class_eval", "do", "serialize", ":schedule", ",", "IceCube", "::", "Schedule", "has_many", ":bookings", ",", "as", ":", ":bookable", ",", "dependent", ":", ":destroy", ",", "class_name", ":", "'::ActsAsBookable::Booking'", "validates_presence_of", ":schedule", ",", "if", ":", ":schedule_required?", "validates_presence_of", ":capacity", ",", "if", ":", ":capacity_required?", "validates_numericality_of", ":capacity", ",", "if", ":", ":capacity_required?", ",", "only_integer", ":", "true", ",", "greater_than_or_equal_to", ":", "0", "def", "self", ".", "bookable?", "true", "end", "def", "schedule_required?", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "[", ":time_type", "]", "!=", ":none", "end", "def", "capacity_required?", "self", ".", "booking_opts", "&&", "self", ".", "booking_opts", "[", ":capacity_type", "]", "!=", ":none", "end", "end", "end", "include", "Core", "end" ]
Make a model bookable
[ "Make", "a", "model", "bookable" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/bookable.rb#L22-L54
train
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.bookable_must_be_bookable
def bookable_must_be_bookable if bookable.present? && !bookable.class.bookable? errors.add(:bookable, T.er('booking.bookable_must_be_bookable', model: bookable.class.to_s)) end end
ruby
def bookable_must_be_bookable if bookable.present? && !bookable.class.bookable? errors.add(:bookable, T.er('booking.bookable_must_be_bookable', model: bookable.class.to_s)) end end
[ "def", "bookable_must_be_bookable", "if", "bookable", ".", "present?", "&&", "!", "bookable", ".", "class", ".", "bookable?", "errors", ".", "add", "(", ":bookable", ",", "T", ".", "er", "(", "'booking.bookable_must_be_bookable'", ",", "model", ":", "bookable", ".", "class", ".", "to_s", ")", ")", "end", "end" ]
Validation method. Check if the bookable resource is actually bookable
[ "Validation", "method", ".", "Check", "if", "the", "bookable", "resource", "is", "actually", "bookable" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L39-L43
train
tandusrl/acts_as_bookable
lib/acts_as_bookable/booking.rb
ActsAsBookable.Booking.booker_must_be_booker
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
ruby
def booker_must_be_booker if booker.present? && !booker.class.booker? errors.add(:booker, T.er('booking.booker_must_be_booker', model: booker.class.to_s)) end end
[ "def", "booker_must_be_booker", "if", "booker", ".", "present?", "&&", "!", "booker", ".", "class", ".", "booker?", "errors", ".", "add", "(", ":booker", ",", "T", ".", "er", "(", "'booking.booker_must_be_booker'", ",", "model", ":", "booker", ".", "class", ".", "to_s", ")", ")", "end", "end" ]
Validation method. Check if the booker model is actually a booker
[ "Validation", "method", ".", "Check", "if", "the", "booker", "model", "is", "actually", "a", "booker" ]
45b78114e1a5dab96e59fc70933277a56f65b53b
https://github.com/tandusrl/acts_as_bookable/blob/45b78114e1a5dab96e59fc70933277a56f65b53b/lib/acts_as_bookable/booking.rb#L48-L52
train
strongqa/howitzer
lib/howitzer/capybara_helpers.rb
Howitzer.CapybaraHelpers.cloud_driver
def cloud_driver(app, caps, url) http_client = ::Selenium::WebDriver::Remote::Http::Default.new http_client.read_timeout = Howitzer.cloud_http_idle_timeout http_client.open_timeout = Howitzer.cloud_http_idle_timeout options = { url: url, desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.new(caps), http_client: http_client, browser: :remote } driver = Capybara::Selenium::Driver.new(app, options) driver.browser.file_detector = remote_file_detector driver end
ruby
def cloud_driver(app, caps, url) http_client = ::Selenium::WebDriver::Remote::Http::Default.new http_client.read_timeout = Howitzer.cloud_http_idle_timeout http_client.open_timeout = Howitzer.cloud_http_idle_timeout options = { url: url, desired_capabilities: ::Selenium::WebDriver::Remote::Capabilities.new(caps), http_client: http_client, browser: :remote } driver = Capybara::Selenium::Driver.new(app, options) driver.browser.file_detector = remote_file_detector driver end
[ "def", "cloud_driver", "(", "app", ",", "caps", ",", "url", ")", "http_client", "=", "::", "Selenium", "::", "WebDriver", "::", "Remote", "::", "Http", "::", "Default", ".", "new", "http_client", ".", "read_timeout", "=", "Howitzer", ".", "cloud_http_idle_timeout", "http_client", ".", "open_timeout", "=", "Howitzer", ".", "cloud_http_idle_timeout", "options", "=", "{", "url", ":", "url", ",", "desired_capabilities", ":", "::", "Selenium", "::", "WebDriver", "::", "Remote", "::", "Capabilities", ".", "new", "(", "caps", ")", ",", "http_client", ":", "http_client", ",", "browser", ":", ":remote", "}", "driver", "=", "Capybara", "::", "Selenium", "::", "Driver", ".", "new", "(", "app", ",", "options", ")", "driver", ".", "browser", ".", "file_detector", "=", "remote_file_detector", "driver", "end" ]
Buids selenium driver for a cloud service @param app [<Rack>] a rack application that this server will contain @param caps [Hash] remote capabilities @param url [String] a remote hub url @return [Capybara::Selenium::Driver]
[ "Buids", "selenium", "driver", "for", "a", "cloud", "service" ]
fb4d57932e1589cca5254fffc2ac2e57c6e74477
https://github.com/strongqa/howitzer/blob/fb4d57932e1589cca5254fffc2ac2e57c6e74477/lib/howitzer/capybara_helpers.rb#L118-L132
train
kontena/k8s-client
lib/k8s/logging.rb
K8s.Logging.logger!
def logger!(progname: self.class.name, target: LOG_TARGET, level: nil, debug: false) @logger = Logger.new(target).tap do |logger| level = Logger::DEBUG if debug logger.progname = "#{self.class.name}<#{progname}>" logger.level = level || self.class.log_level || K8s::Logging.log_level || LOG_LEVEL end end
ruby
def logger!(progname: self.class.name, target: LOG_TARGET, level: nil, debug: false) @logger = Logger.new(target).tap do |logger| level = Logger::DEBUG if debug logger.progname = "#{self.class.name}<#{progname}>" logger.level = level || self.class.log_level || K8s::Logging.log_level || LOG_LEVEL end end
[ "def", "logger!", "(", "progname", ":", "self", ".", "class", ".", "name", ",", "target", ":", "LOG_TARGET", ",", "level", ":", "nil", ",", "debug", ":", "false", ")", "@logger", "=", "Logger", ".", "new", "(", "target", ")", ".", "tap", "do", "|", "logger", "|", "level", "=", "Logger", "::", "DEBUG", "if", "debug", "logger", ".", "progname", "=", "\"#{self.class.name}<#{progname}>\"", "logger", ".", "level", "=", "level", "||", "self", ".", "class", ".", "log_level", "||", "K8s", "::", "Logging", ".", "log_level", "||", "LOG_LEVEL", "end", "end" ]
Use per-instance logger instead of the default per-class logger Sets the instance variable returned by #logger @return [Logger]
[ "Use", "per", "-", "instance", "logger", "instead", "of", "the", "default", "per", "-", "class", "logger" ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/logging.rb#L73-L80
train
kontena/k8s-client
lib/k8s/stack.rb
K8s.Stack.prune
def prune(client, keep_resources:, skip_forbidden: true) # using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either client.list_resources(labelSelector: { @label => name }, skip_forbidden: skip_forbidden).sort do |a, b| # Sort resources so that namespaced objects are deleted first if a.metadata.namespace == b.metadata.namespace 0 elsif a.metadata.namespace.nil? && !b.metadata.namespace.nil? 1 else -1 end end.each do |resource| next if PRUNE_IGNORE.include? "#{resource.apiVersion}:#{resource.kind}" resource_label = resource.metadata.labels ? resource.metadata.labels[@label] : nil resource_checksum = resource.metadata.annotations ? resource.metadata.annotations[@checksum_annotation] : nil logger.debug { "List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}" } if resource_label != name # apiserver did not respect labelSelector elsif keep_resources && keep_resource?(resource) # resource is up-to-date else logger.info "Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}" begin client.delete_resource(resource, propagationPolicy: 'Background') rescue K8s::Error::NotFound => e # assume aliased objects in multiple API groups, like for Deployments # alternatively, a custom resource whose definition was already deleted earlier logger.debug { "Ignoring #{e} : #{e.message}" } end end end end
ruby
def prune(client, keep_resources:, skip_forbidden: true) # using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either client.list_resources(labelSelector: { @label => name }, skip_forbidden: skip_forbidden).sort do |a, b| # Sort resources so that namespaced objects are deleted first if a.metadata.namespace == b.metadata.namespace 0 elsif a.metadata.namespace.nil? && !b.metadata.namespace.nil? 1 else -1 end end.each do |resource| next if PRUNE_IGNORE.include? "#{resource.apiVersion}:#{resource.kind}" resource_label = resource.metadata.labels ? resource.metadata.labels[@label] : nil resource_checksum = resource.metadata.annotations ? resource.metadata.annotations[@checksum_annotation] : nil logger.debug { "List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}" } if resource_label != name # apiserver did not respect labelSelector elsif keep_resources && keep_resource?(resource) # resource is up-to-date else logger.info "Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}" begin client.delete_resource(resource, propagationPolicy: 'Background') rescue K8s::Error::NotFound => e # assume aliased objects in multiple API groups, like for Deployments # alternatively, a custom resource whose definition was already deleted earlier logger.debug { "Ignoring #{e} : #{e.message}" } end end end end
[ "def", "prune", "(", "client", ",", "keep_resources", ":", ",", "skip_forbidden", ":", "true", ")", "# using skip_forbidden: assume we can't create resource types that we are forbidden to list, so we don't need to prune them either", "client", ".", "list_resources", "(", "labelSelector", ":", "{", "@label", "=>", "name", "}", ",", "skip_forbidden", ":", "skip_forbidden", ")", ".", "sort", "do", "|", "a", ",", "b", "|", "# Sort resources so that namespaced objects are deleted first", "if", "a", ".", "metadata", ".", "namespace", "==", "b", ".", "metadata", ".", "namespace", "0", "elsif", "a", ".", "metadata", ".", "namespace", ".", "nil?", "&&", "!", "b", ".", "metadata", ".", "namespace", ".", "nil?", "1", "else", "-", "1", "end", "end", ".", "each", "do", "|", "resource", "|", "next", "if", "PRUNE_IGNORE", ".", "include?", "\"#{resource.apiVersion}:#{resource.kind}\"", "resource_label", "=", "resource", ".", "metadata", ".", "labels", "?", "resource", ".", "metadata", ".", "labels", "[", "@label", "]", ":", "nil", "resource_checksum", "=", "resource", ".", "metadata", ".", "annotations", "?", "resource", ".", "metadata", ".", "annotations", "[", "@checksum_annotation", "]", ":", "nil", "logger", ".", "debug", "{", "\"List resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace} with checksum=#{resource_checksum}\"", "}", "if", "resource_label", "!=", "name", "# apiserver did not respect labelSelector", "elsif", "keep_resources", "&&", "keep_resource?", "(", "resource", ")", "# resource is up-to-date", "else", "logger", ".", "info", "\"Delete resource #{resource.apiVersion}:#{resource.kind}/#{resource.metadata.name} in namespace #{resource.metadata.namespace}\"", "begin", "client", ".", "delete_resource", "(", "resource", ",", "propagationPolicy", ":", "'Background'", ")", "rescue", "K8s", "::", "Error", "::", "NotFound", "=>", "e", "# assume aliased objects in multiple API groups, like for Deployments", "# alternatively, a custom resource whose definition was already deleted earlier", "logger", ".", "debug", "{", "\"Ignoring #{e} : #{e.message}\"", "}", "end", "end", "end", "end" ]
Delete all stack resources that were not applied @param client [K8s::Client] @param keep_resources [NilClass, Boolean] @param skip_forbidden [Boolean]
[ "Delete", "all", "stack", "resources", "that", "were", "not", "applied" ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/stack.rb#L139-L173
train
kontena/k8s-client
lib/k8s/client.rb
K8s.Client.get_resources
def get_resources(resources) # prefetch api resources, skip missing APIs resource_apis = apis(resources.map(&:apiVersion), prefetch_resources: true, skip_missing: true) # map each resource to excon request options, or nil if resource is not (yet) defined requests = resources.zip(resource_apis).map{ |resource, api_client| next nil unless api_client.api_resources? resource_client = api_client.client_for_resource(resource) { method: 'GET', path: resource_client.path(resource.metadata.name, namespace: resource.metadata.namespace), response_class: resource_client.resource_class } } # map non-nil requests to response objects, or nil for nil request options Util.compact_map(requests) { |reqs| @transport.requests(*reqs, skip_missing: true) } end
ruby
def get_resources(resources) # prefetch api resources, skip missing APIs resource_apis = apis(resources.map(&:apiVersion), prefetch_resources: true, skip_missing: true) # map each resource to excon request options, or nil if resource is not (yet) defined requests = resources.zip(resource_apis).map{ |resource, api_client| next nil unless api_client.api_resources? resource_client = api_client.client_for_resource(resource) { method: 'GET', path: resource_client.path(resource.metadata.name, namespace: resource.metadata.namespace), response_class: resource_client.resource_class } } # map non-nil requests to response objects, or nil for nil request options Util.compact_map(requests) { |reqs| @transport.requests(*reqs, skip_missing: true) } end
[ "def", "get_resources", "(", "resources", ")", "# prefetch api resources, skip missing APIs", "resource_apis", "=", "apis", "(", "resources", ".", "map", "(", ":apiVersion", ")", ",", "prefetch_resources", ":", "true", ",", "skip_missing", ":", "true", ")", "# map each resource to excon request options, or nil if resource is not (yet) defined", "requests", "=", "resources", ".", "zip", "(", "resource_apis", ")", ".", "map", "{", "|", "resource", ",", "api_client", "|", "next", "nil", "unless", "api_client", ".", "api_resources?", "resource_client", "=", "api_client", ".", "client_for_resource", "(", "resource", ")", "{", "method", ":", "'GET'", ",", "path", ":", "resource_client", ".", "path", "(", "resource", ".", "metadata", ".", "name", ",", "namespace", ":", "resource", ".", "metadata", ".", "namespace", ")", ",", "response_class", ":", "resource_client", ".", "resource_class", "}", "}", "# map non-nil requests to response objects, or nil for nil request options", "Util", ".", "compact_map", "(", "requests", ")", "{", "|", "reqs", "|", "@transport", ".", "requests", "(", "reqs", ",", "skip_missing", ":", "true", ")", "}", "end" ]
Returns nils for any resources that do not exist. This includes custom resources that were not yet defined. @param resources [Array<K8s::Resource>] @return [Array<K8s::Resource, nil>] matching resources array 1:1
[ "Returns", "nils", "for", "any", "resources", "that", "do", "not", "exist", ".", "This", "includes", "custom", "resources", "that", "were", "not", "yet", "defined", "." ]
efa19f43202a5d8840084a804afb936a57dc5bdd
https://github.com/kontena/k8s-client/blob/efa19f43202a5d8840084a804afb936a57dc5bdd/lib/k8s/client.rb#L232-L253
train
Shopify/active_shipping
lib/active_shipping/carriers/fedex.rb
ActiveShipping.FedEx.create_shipment
def create_shipment(origin, destination, packages, options = {}) options = @options.merge(options) packages = Array(packages) raise Error, "Multiple packages are not supported yet." if packages.length > 1 request = build_shipment_request(origin, destination, packages, options) logger.debug(request) if logger response = commit(save_request(request), (options[:test] || false)) parse_ship_response(response) end
ruby
def create_shipment(origin, destination, packages, options = {}) options = @options.merge(options) packages = Array(packages) raise Error, "Multiple packages are not supported yet." if packages.length > 1 request = build_shipment_request(origin, destination, packages, options) logger.debug(request) if logger response = commit(save_request(request), (options[:test] || false)) parse_ship_response(response) end
[ "def", "create_shipment", "(", "origin", ",", "destination", ",", "packages", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "packages", "=", "Array", "(", "packages", ")", "raise", "Error", ",", "\"Multiple packages are not supported yet.\"", "if", "packages", ".", "length", ">", "1", "request", "=", "build_shipment_request", "(", "origin", ",", "destination", ",", "packages", ",", "options", ")", "logger", ".", "debug", "(", "request", ")", "if", "logger", "response", "=", "commit", "(", "save_request", "(", "request", ")", ",", "(", "options", "[", ":test", "]", "||", "false", ")", ")", "parse_ship_response", "(", "response", ")", "end" ]
Get Shipping labels
[ "Get", "Shipping", "labels" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carriers/fedex.rb#L175-L185
train
Shopify/active_shipping
lib/active_shipping/carrier.rb
ActiveShipping.Carrier.timestamp_from_business_day
def timestamp_from_business_day(days) return unless days date = DateTime.now.utc days.times do date += 1.day date += 2.days if date.saturday? date += 1.day if date.sunday? end date.to_datetime end
ruby
def timestamp_from_business_day(days) return unless days date = DateTime.now.utc days.times do date += 1.day date += 2.days if date.saturday? date += 1.day if date.sunday? end date.to_datetime end
[ "def", "timestamp_from_business_day", "(", "days", ")", "return", "unless", "days", "date", "=", "DateTime", ".", "now", ".", "utc", "days", ".", "times", "do", "date", "+=", "1", ".", "day", "date", "+=", "2", ".", "days", "if", "date", ".", "saturday?", "date", "+=", "1", ".", "day", "if", "date", ".", "sunday?", "end", "date", ".", "to_datetime", "end" ]
Calculates a timestamp that corresponds a given number of business days in the future @param days [Integer] The number of business days from now. @return [DateTime] A timestamp, the provided number of business days in the future.
[ "Calculates", "a", "timestamp", "that", "corresponds", "a", "given", "number", "of", "business", "days", "in", "the", "future" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carrier.rb#L170-L182
train
Shopify/active_shipping
lib/active_shipping/rate_estimate.rb
ActiveShipping.RateEstimate.add
def add(package, rate = nil) cents = Package.cents_from(rate) raise ArgumentError.new("New packages must have valid rate information since this RateEstimate has no total_price set.") if cents.nil? and total_price.nil? @package_rates << {:package => package, :rate => cents} self end
ruby
def add(package, rate = nil) cents = Package.cents_from(rate) raise ArgumentError.new("New packages must have valid rate information since this RateEstimate has no total_price set.") if cents.nil? and total_price.nil? @package_rates << {:package => package, :rate => cents} self end
[ "def", "add", "(", "package", ",", "rate", "=", "nil", ")", "cents", "=", "Package", ".", "cents_from", "(", "rate", ")", "raise", "ArgumentError", ".", "new", "(", "\"New packages must have valid rate information since this RateEstimate has no total_price set.\"", ")", "if", "cents", ".", "nil?", "and", "total_price", ".", "nil?", "@package_rates", "<<", "{", ":package", "=>", "package", ",", ":rate", "=>", "cents", "}", "self", "end" ]
Adds a package to this rate estimate @param package [ActiveShipping::Package] The package to add. @param rate [#cents, Float, String, nil] The rate for this package. This is only required if there is no total price for this shipment @return [self]
[ "Adds", "a", "package", "to", "this", "rate", "estimate" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/rate_estimate.rb#L132-L137
train
Shopify/active_shipping
lib/active_shipping/carriers/canada_post_pws.rb
ActiveShipping.CanadaPostPWS.create_shipment
def create_shipment(origin, destination, package, line_items = [], options = {}) request_body = build_shipment_request(origin, destination, package, line_items, options) response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE)) parse_shipment_response(response) rescue ActiveUtils::ResponseError, ActiveShipping::ResponseError => e error_response(e.response.body, CPPWSShippingResponse) rescue MissingCustomerNumberError CPPWSShippingResponse.new(false, "Missing Customer Number", {}, :carrier => @@name) end
ruby
def create_shipment(origin, destination, package, line_items = [], options = {}) request_body = build_shipment_request(origin, destination, package, line_items, options) response = ssl_post(create_shipment_url(options), request_body, headers(options, SHIPMENT_MIMETYPE, SHIPMENT_MIMETYPE)) parse_shipment_response(response) rescue ActiveUtils::ResponseError, ActiveShipping::ResponseError => e error_response(e.response.body, CPPWSShippingResponse) rescue MissingCustomerNumberError CPPWSShippingResponse.new(false, "Missing Customer Number", {}, :carrier => @@name) end
[ "def", "create_shipment", "(", "origin", ",", "destination", ",", "package", ",", "line_items", "=", "[", "]", ",", "options", "=", "{", "}", ")", "request_body", "=", "build_shipment_request", "(", "origin", ",", "destination", ",", "package", ",", "line_items", ",", "options", ")", "response", "=", "ssl_post", "(", "create_shipment_url", "(", "options", ")", ",", "request_body", ",", "headers", "(", "options", ",", "SHIPMENT_MIMETYPE", ",", "SHIPMENT_MIMETYPE", ")", ")", "parse_shipment_response", "(", "response", ")", "rescue", "ActiveUtils", "::", "ResponseError", ",", "ActiveShipping", "::", "ResponseError", "=>", "e", "error_response", "(", "e", ".", "response", ".", "body", ",", "CPPWSShippingResponse", ")", "rescue", "MissingCustomerNumberError", "CPPWSShippingResponse", ".", "new", "(", "false", ",", "\"Missing Customer Number\"", ",", "{", "}", ",", ":carrier", "=>", "@@name", ")", "end" ]
line_items should be a list of PackageItem's
[ "line_items", "should", "be", "a", "list", "of", "PackageItem", "s" ]
590bc805e10a137251c122a1525940c34b164a44
https://github.com/Shopify/active_shipping/blob/590bc805e10a137251c122a1525940c34b164a44/lib/active_shipping/carriers/canada_post_pws.rb#L100-L108
train
activeadmin-plugins/active_admin_import
lib/active_admin_import/importer.rb
ActiveAdminImport.Importer.batch_slice_columns
def batch_slice_columns(slice_columns) use_indexes = [] headers.values.each_with_index do |val, index| use_indexes << index if val.in?(slice_columns) end return csv_lines if use_indexes.empty? # slice CSV headers @headers = headers.to_a.values_at(*use_indexes).to_h # slice CSV values csv_lines.map! do |line| line.values_at(*use_indexes) end end
ruby
def batch_slice_columns(slice_columns) use_indexes = [] headers.values.each_with_index do |val, index| use_indexes << index if val.in?(slice_columns) end return csv_lines if use_indexes.empty? # slice CSV headers @headers = headers.to_a.values_at(*use_indexes).to_h # slice CSV values csv_lines.map! do |line| line.values_at(*use_indexes) end end
[ "def", "batch_slice_columns", "(", "slice_columns", ")", "use_indexes", "=", "[", "]", "headers", ".", "values", ".", "each_with_index", "do", "|", "val", ",", "index", "|", "use_indexes", "<<", "index", "if", "val", ".", "in?", "(", "slice_columns", ")", "end", "return", "csv_lines", "if", "use_indexes", ".", "empty?", "# slice CSV headers", "@headers", "=", "headers", ".", "to_a", ".", "values_at", "(", "use_indexes", ")", ".", "to_h", "# slice CSV values", "csv_lines", ".", "map!", "do", "|", "line", "|", "line", ".", "values_at", "(", "use_indexes", ")", "end", "end" ]
Use it when CSV file contain redundant columns Example: ActiveAdmin.register Post active_admin_import before_batch_import: lambda { |importer| importer.batch_slice_columns(['name', 'birthday']) } end
[ "Use", "it", "when", "CSV", "file", "contain", "redundant", "columns" ]
7e17eb6f33cdb0329ac98730ab063cd0f31339c9
https://github.com/activeadmin-plugins/active_admin_import/blob/7e17eb6f33cdb0329ac98730ab063cd0f31339c9/lib/active_admin_import/importer.rb#L83-L95
train
chriskite/anemone
lib/anemone/page_store.rb
Anemone.PageStore.has_page?
def has_page?(url) schemes = %w(http https) if schemes.include? url.scheme u = url.dup return schemes.any? { |s| u.scheme = s; has_key?(u) } end has_key? url end
ruby
def has_page?(url) schemes = %w(http https) if schemes.include? url.scheme u = url.dup return schemes.any? { |s| u.scheme = s; has_key?(u) } end has_key? url end
[ "def", "has_page?", "(", "url", ")", "schemes", "=", "%w(", "http", "https", ")", "if", "schemes", ".", "include?", "url", ".", "scheme", "u", "=", "url", ".", "dup", "return", "schemes", ".", "any?", "{", "|", "s", "|", "u", ".", "scheme", "=", "s", ";", "has_key?", "(", "u", ")", "}", "end", "has_key?", "url", "end" ]
Does this PageStore contain the specified URL? HTTP and HTTPS versions of a URL are considered to be the same page.
[ "Does", "this", "PageStore", "contain", "the", "specified", "URL?", "HTTP", "and", "HTTPS", "versions", "of", "a", "URL", "are", "considered", "to", "be", "the", "same", "page", "." ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/page_store.rb#L51-L59
train
chriskite/anemone
lib/anemone/core.rb
Anemone.Core.run
def run process_options @urls.delete_if { |url| !visit_link?(url) } return if @urls.empty? link_queue = Queue.new page_queue = Queue.new @opts[:threads].times do @tentacles << Thread.new { Tentacle.new(link_queue, page_queue, @opts).run } end @urls.each{ |url| link_queue.enq(url) } loop do page = page_queue.deq @pages.touch_key page.url puts "#{page.url} Queue: #{link_queue.size}" if @opts[:verbose] do_page_blocks page page.discard_doc! if @opts[:discard_page_bodies] links = links_to_follow page links.each do |link| link_queue << [link, page.url.dup, page.depth + 1] end @pages.touch_keys links @pages[page.url] = page # if we are done with the crawl, tell the threads to end if link_queue.empty? and page_queue.empty? until link_queue.num_waiting == @tentacles.size Thread.pass end if page_queue.empty? @tentacles.size.times { link_queue << :END } break end end end @tentacles.each { |thread| thread.join } do_after_crawl_blocks self end
ruby
def run process_options @urls.delete_if { |url| !visit_link?(url) } return if @urls.empty? link_queue = Queue.new page_queue = Queue.new @opts[:threads].times do @tentacles << Thread.new { Tentacle.new(link_queue, page_queue, @opts).run } end @urls.each{ |url| link_queue.enq(url) } loop do page = page_queue.deq @pages.touch_key page.url puts "#{page.url} Queue: #{link_queue.size}" if @opts[:verbose] do_page_blocks page page.discard_doc! if @opts[:discard_page_bodies] links = links_to_follow page links.each do |link| link_queue << [link, page.url.dup, page.depth + 1] end @pages.touch_keys links @pages[page.url] = page # if we are done with the crawl, tell the threads to end if link_queue.empty? and page_queue.empty? until link_queue.num_waiting == @tentacles.size Thread.pass end if page_queue.empty? @tentacles.size.times { link_queue << :END } break end end end @tentacles.each { |thread| thread.join } do_after_crawl_blocks self end
[ "def", "run", "process_options", "@urls", ".", "delete_if", "{", "|", "url", "|", "!", "visit_link?", "(", "url", ")", "}", "return", "if", "@urls", ".", "empty?", "link_queue", "=", "Queue", ".", "new", "page_queue", "=", "Queue", ".", "new", "@opts", "[", ":threads", "]", ".", "times", "do", "@tentacles", "<<", "Thread", ".", "new", "{", "Tentacle", ".", "new", "(", "link_queue", ",", "page_queue", ",", "@opts", ")", ".", "run", "}", "end", "@urls", ".", "each", "{", "|", "url", "|", "link_queue", ".", "enq", "(", "url", ")", "}", "loop", "do", "page", "=", "page_queue", ".", "deq", "@pages", ".", "touch_key", "page", ".", "url", "puts", "\"#{page.url} Queue: #{link_queue.size}\"", "if", "@opts", "[", ":verbose", "]", "do_page_blocks", "page", "page", ".", "discard_doc!", "if", "@opts", "[", ":discard_page_bodies", "]", "links", "=", "links_to_follow", "page", "links", ".", "each", "do", "|", "link", "|", "link_queue", "<<", "[", "link", ",", "page", ".", "url", ".", "dup", ",", "page", ".", "depth", "+", "1", "]", "end", "@pages", ".", "touch_keys", "links", "@pages", "[", "page", ".", "url", "]", "=", "page", "# if we are done with the crawl, tell the threads to end", "if", "link_queue", ".", "empty?", "and", "page_queue", ".", "empty?", "until", "link_queue", ".", "num_waiting", "==", "@tentacles", ".", "size", "Thread", ".", "pass", "end", "if", "page_queue", ".", "empty?", "@tentacles", ".", "size", ".", "times", "{", "link_queue", "<<", ":END", "}", "break", "end", "end", "end", "@tentacles", ".", "each", "{", "|", "thread", "|", "thread", ".", "join", "}", "do_after_crawl_blocks", "self", "end" ]
Perform the crawl
[ "Perform", "the", "crawl" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/core.rb#L148-L193
train
chriskite/anemone
lib/anemone/core.rb
Anemone.Core.freeze_options
def freeze_options @opts.freeze @opts.each_key { |key| @opts[key].freeze } @opts[:cookies].each_key { |key| @opts[:cookies][key].freeze } rescue nil end
ruby
def freeze_options @opts.freeze @opts.each_key { |key| @opts[key].freeze } @opts[:cookies].each_key { |key| @opts[:cookies][key].freeze } rescue nil end
[ "def", "freeze_options", "@opts", ".", "freeze", "@opts", ".", "each_key", "{", "|", "key", "|", "@opts", "[", "key", "]", ".", "freeze", "}", "@opts", "[", ":cookies", "]", ".", "each_key", "{", "|", "key", "|", "@opts", "[", ":cookies", "]", "[", "key", "]", ".", "freeze", "}", "rescue", "nil", "end" ]
Freeze the opts Hash so that no options can be modified once the crawl begins
[ "Freeze", "the", "opts", "Hash", "so", "that", "no", "options", "can", "be", "modified", "once", "the", "crawl", "begins" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/core.rb#L211-L215
train
chriskite/anemone
lib/anemone/http.rb
Anemone.HTTP.allowed?
def allowed?(to_url, from_url) to_url.host.nil? || (to_url.host == from_url.host) end
ruby
def allowed?(to_url, from_url) to_url.host.nil? || (to_url.host == from_url.host) end
[ "def", "allowed?", "(", "to_url", ",", "from_url", ")", "to_url", ".", "host", ".", "nil?", "||", "(", "to_url", ".", "host", "==", "from_url", ".", "host", ")", "end" ]
Allowed to connect to the requested url?
[ "Allowed", "to", "connect", "to", "the", "requested", "url?" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/http.rb#L182-L184
train
chriskite/anemone
lib/anemone/tentacle.rb
Anemone.Tentacle.run
def run loop do link, referer, depth = @link_queue.deq break if link == :END @http.fetch_pages(link, referer, depth).each { |page| @page_queue << page } delay end end
ruby
def run loop do link, referer, depth = @link_queue.deq break if link == :END @http.fetch_pages(link, referer, depth).each { |page| @page_queue << page } delay end end
[ "def", "run", "loop", "do", "link", ",", "referer", ",", "depth", "=", "@link_queue", ".", "deq", "break", "if", "link", "==", ":END", "@http", ".", "fetch_pages", "(", "link", ",", "referer", ",", "depth", ")", ".", "each", "{", "|", "page", "|", "@page_queue", "<<", "page", "}", "delay", "end", "end" ]
Create a new Tentacle Gets links from @link_queue, and returns the fetched Page objects into @page_queue
[ "Create", "a", "new", "Tentacle" ]
72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa
https://github.com/chriskite/anemone/blob/72b699ee11f618bdeb5a8f198b0b9aa675b4e2fa/lib/anemone/tentacle.rb#L20-L30
train
tiagopog/jsonapi-utils
lib/jsonapi/utils/support/filter/default.rb
JSONAPI::Utils::Support::Filter.Default.apply_filter?
def apply_filter?(records, options = {}) params[:filter].present? && records.respond_to?(:where) && (options[:filter].nil? || options[:filter]) end
ruby
def apply_filter?(records, options = {}) params[:filter].present? && records.respond_to?(:where) && (options[:filter].nil? || options[:filter]) end
[ "def", "apply_filter?", "(", "records", ",", "options", "=", "{", "}", ")", "params", "[", ":filter", "]", ".", "present?", "&&", "records", ".", "respond_to?", "(", ":where", ")", "&&", "(", "options", "[", ":filter", "]", ".", "nil?", "||", "options", "[", ":filter", "]", ")", "end" ]
Check whether default filters should be applied. @param records [ActiveRecord::Relation, Array] collection of records e.g.: User.all or [{ id: 1, name: 'Tiago' }, { id: 2, name: 'Doug' }] @param options [Hash] JU's options e.g.: { filter: false, paginate: false } @return [Boolean] @api public
[ "Check", "whether", "default", "filters", "should", "be", "applied", "." ]
a2c2b0e3843376718929723d9f609611f68b665e
https://github.com/tiagopog/jsonapi-utils/blob/a2c2b0e3843376718929723d9f609611f68b665e/lib/jsonapi/utils/support/filter/default.rb#L34-L37
train
tiagopog/jsonapi-utils
lib/jsonapi/utils/support/filter/default.rb
JSONAPI::Utils::Support::Filter.Default.filter_params
def filter_params @_filter_params ||= case params[:filter] when Hash, ActionController::Parameters default_filters.each_with_object({}) do |field, hash| unformatted_field = @request.unformat_key(field) hash[unformatted_field] = params[:filter][field] end end end
ruby
def filter_params @_filter_params ||= case params[:filter] when Hash, ActionController::Parameters default_filters.each_with_object({}) do |field, hash| unformatted_field = @request.unformat_key(field) hash[unformatted_field] = params[:filter][field] end end end
[ "def", "filter_params", "@_filter_params", "||=", "case", "params", "[", ":filter", "]", "when", "Hash", ",", "ActionController", "::", "Parameters", "default_filters", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "field", ",", "hash", "|", "unformatted_field", "=", "@request", ".", "unformat_key", "(", "field", ")", "hash", "[", "unformatted_field", "]", "=", "params", "[", ":filter", "]", "[", "field", "]", "end", "end", "end" ]
Build a Hash with the default filters. @return [Hash, NilClass] @api public
[ "Build", "a", "Hash", "with", "the", "default", "filters", "." ]
a2c2b0e3843376718929723d9f609611f68b665e
https://github.com/tiagopog/jsonapi-utils/blob/a2c2b0e3843376718929723d9f609611f68b665e/lib/jsonapi/utils/support/filter/default.rb#L44-L53
train
tiagopog/jsonapi-utils
lib/jsonapi/utils/support/sort.rb
JSONAPI::Utils::Support.Sort.sort_params
def sort_params @_sort_params ||= if params[:sort].present? params[:sort].split(',').each_with_object({}) do |field, hash| unformatted_field = @request.unformat_key(field) desc, field = unformatted_field.to_s.match(/^([-_])?(\w+)$/i)[1..2] hash[field.to_sym] = desc.present? ? :desc : :asc end end end
ruby
def sort_params @_sort_params ||= if params[:sort].present? params[:sort].split(',').each_with_object({}) do |field, hash| unformatted_field = @request.unformat_key(field) desc, field = unformatted_field.to_s.match(/^([-_])?(\w+)$/i)[1..2] hash[field.to_sym] = desc.present? ? :desc : :asc end end end
[ "def", "sort_params", "@_sort_params", "||=", "if", "params", "[", ":sort", "]", ".", "present?", "params", "[", ":sort", "]", ".", "split", "(", "','", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "field", ",", "hash", "|", "unformatted_field", "=", "@request", ".", "unformat_key", "(", "field", ")", "desc", ",", "field", "=", "unformatted_field", ".", "to_s", ".", "match", "(", "/", "\\w", "/i", ")", "[", "1", "..", "2", "]", "hash", "[", "field", ".", "to_sym", "]", "=", "desc", ".", "present?", "?", ":desc", ":", ":asc", "end", "end", "end" ]
Build a Hash with the sort criteria. @return [Hash, NilClass] @api public
[ "Build", "a", "Hash", "with", "the", "sort", "criteria", "." ]
a2c2b0e3843376718929723d9f609611f68b665e
https://github.com/tiagopog/jsonapi-utils/blob/a2c2b0e3843376718929723d9f609611f68b665e/lib/jsonapi/utils/support/sort.rb#L42-L51
train
tiagopog/jsonapi-utils
lib/jsonapi/utils/request.rb
JSONAPI::Utils.Request.setup_request
def setup_request @request ||= JSONAPI::RequestParser.new( params, context: context, key_formatter: key_formatter, server_error_callbacks: (self.class.server_error_callbacks || []) ) end
ruby
def setup_request @request ||= JSONAPI::RequestParser.new( params, context: context, key_formatter: key_formatter, server_error_callbacks: (self.class.server_error_callbacks || []) ) end
[ "def", "setup_request", "@request", "||=", "JSONAPI", "::", "RequestParser", ".", "new", "(", "params", ",", "context", ":", "context", ",", "key_formatter", ":", "key_formatter", ",", "server_error_callbacks", ":", "(", "self", ".", "class", ".", "server_error_callbacks", "||", "[", "]", ")", ")", "end" ]
Instantiate the request object. @return [JSONAPI::RequestParser] @api public
[ "Instantiate", "the", "request", "object", "." ]
a2c2b0e3843376718929723d9f609611f68b665e
https://github.com/tiagopog/jsonapi-utils/blob/a2c2b0e3843376718929723d9f609611f68b665e/lib/jsonapi/utils/request.rb#L16-L23
train
tiagopog/jsonapi-utils
lib/jsonapi/utils/request.rb
JSONAPI::Utils.Request.build_params_for
def build_params_for(param_type) return {} if @request.operations.empty? keys = %i(attributes to_one to_many) operation = @request.operations.find { |e| e.options[:data].keys & keys == keys } if operation.nil? {} elsif param_type == :relationship operation.options[:data].values_at(:to_one, :to_many).compact.reduce(&:merge) else operation.options[:data][:attributes] end end
ruby
def build_params_for(param_type) return {} if @request.operations.empty? keys = %i(attributes to_one to_many) operation = @request.operations.find { |e| e.options[:data].keys & keys == keys } if operation.nil? {} elsif param_type == :relationship operation.options[:data].values_at(:to_one, :to_many).compact.reduce(&:merge) else operation.options[:data][:attributes] end end
[ "def", "build_params_for", "(", "param_type", ")", "return", "{", "}", "if", "@request", ".", "operations", ".", "empty?", "keys", "=", "%i(", "attributes", "to_one", "to_many", ")", "operation", "=", "@request", ".", "operations", ".", "find", "{", "|", "e", "|", "e", ".", "options", "[", ":data", "]", ".", "keys", "&", "keys", "==", "keys", "}", "if", "operation", ".", "nil?", "{", "}", "elsif", "param_type", "==", ":relationship", "operation", ".", "options", "[", ":data", "]", ".", "values_at", "(", ":to_one", ",", ":to_many", ")", ".", "compact", ".", "reduce", "(", ":merge", ")", "else", "operation", ".", "options", "[", ":data", "]", "[", ":attributes", "]", "end", "end" ]
Extract params from request and build a Hash with params for either the main resource or relationships. @return [Hash] @api private
[ "Extract", "params", "from", "request", "and", "build", "a", "Hash", "with", "params", "for", "either", "the", "main", "resource", "or", "relationships", "." ]
a2c2b0e3843376718929723d9f609611f68b665e
https://github.com/tiagopog/jsonapi-utils/blob/a2c2b0e3843376718929723d9f609611f68b665e/lib/jsonapi/utils/request.rb#L77-L90
train
jenseng/hair_trigger
lib/hair_trigger/builder.rb
HairTrigger.Builder.initialize_copy
def initialize_copy(other) @trigger_group = other @triggers = nil @chained_calls = [] @errors = [] @warnings = [] @options = @options.dup @options.delete(:name) # this will be inferred (or set further down the line) @options.each do |key, value| @options[key] = value.dup rescue value end end
ruby
def initialize_copy(other) @trigger_group = other @triggers = nil @chained_calls = [] @errors = [] @warnings = [] @options = @options.dup @options.delete(:name) # this will be inferred (or set further down the line) @options.each do |key, value| @options[key] = value.dup rescue value end end
[ "def", "initialize_copy", "(", "other", ")", "@trigger_group", "=", "other", "@triggers", "=", "nil", "@chained_calls", "=", "[", "]", "@errors", "=", "[", "]", "@warnings", "=", "[", "]", "@options", "=", "@options", ".", "dup", "@options", ".", "delete", "(", ":name", ")", "# this will be inferred (or set further down the line)", "@options", ".", "each", "do", "|", "key", ",", "value", "|", "@options", "[", "key", "]", "=", "value", ".", "dup", "rescue", "value", "end", "end" ]
after delayed interpolation
[ "after", "delayed", "interpolation" ]
567ace98e896f0107ca1ea50c448d32409453811
https://github.com/jenseng/hair_trigger/blob/567ace98e896f0107ca1ea50c448d32409453811/lib/hair_trigger/builder.rb#L29-L40
train
cgriego/active_attr
lib/active_attr/typecasting.rb
ActiveAttr.Typecasting.typecast_attribute
def typecast_attribute(typecaster, value) raise ArgumentError, "a typecaster must be given" unless typecaster.respond_to?(:call) return value if value.nil? typecaster.call(value) end
ruby
def typecast_attribute(typecaster, value) raise ArgumentError, "a typecaster must be given" unless typecaster.respond_to?(:call) return value if value.nil? typecaster.call(value) end
[ "def", "typecast_attribute", "(", "typecaster", ",", "value", ")", "raise", "ArgumentError", ",", "\"a typecaster must be given\"", "unless", "typecaster", ".", "respond_to?", "(", ":call", ")", "return", "value", "if", "value", ".", "nil?", "typecaster", ".", "call", "(", "value", ")", "end" ]
Typecasts a value using a Class @param [#call] typecaster The typecaster to use for typecasting @param [Object] value The value to be typecasted @return [Object, nil] The typecasted value or nil if it cannot be typecasted @since 0.5.0
[ "Typecasts", "a", "value", "using", "a", "Class" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/typecasting.rb#L48-L52
train
cgriego/active_attr
lib/active_attr/attributes.rb
ActiveAttr.Attributes.inspect
def inspect attribute_descriptions = attributes.sort.map { |key, value| "#{key}: #{value.inspect}" }.join(", ") separator = " " unless attribute_descriptions.empty? "#<#{self.class.name}#{separator}#{attribute_descriptions}>" end
ruby
def inspect attribute_descriptions = attributes.sort.map { |key, value| "#{key}: #{value.inspect}" }.join(", ") separator = " " unless attribute_descriptions.empty? "#<#{self.class.name}#{separator}#{attribute_descriptions}>" end
[ "def", "inspect", "attribute_descriptions", "=", "attributes", ".", "sort", ".", "map", "{", "|", "key", ",", "value", "|", "\"#{key}: #{value.inspect}\"", "}", ".", "join", "(", "\", \"", ")", "separator", "=", "\" \"", "unless", "attribute_descriptions", ".", "empty?", "\"#<#{self.class.name}#{separator}#{attribute_descriptions}>\"", "end" ]
Returns the class name plus its attributes @example Inspect the model. person.inspect @return [String] Human-readable presentation of the attribute definitions @since 0.2.0
[ "Returns", "the", "class", "name", "plus", "its", "attributes" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/attributes.rb#L72-L76
train
cgriego/active_attr
lib/active_attr/attribute_definition.rb
ActiveAttr.AttributeDefinition.inspect
def inspect options_description = options.map { |key, value| "#{key.inspect} => #{value.inspect}" }.sort.join(", ") inspected_options = ", #{options_description}" unless options_description.empty? "attribute :#{name}#{inspected_options}" end
ruby
def inspect options_description = options.map { |key, value| "#{key.inspect} => #{value.inspect}" }.sort.join(", ") inspected_options = ", #{options_description}" unless options_description.empty? "attribute :#{name}#{inspected_options}" end
[ "def", "inspect", "options_description", "=", "options", ".", "map", "{", "|", "key", ",", "value", "|", "\"#{key.inspect} => #{value.inspect}\"", "}", ".", "sort", ".", "join", "(", "\", \"", ")", "inspected_options", "=", "\", #{options_description}\"", "unless", "options_description", ".", "empty?", "\"attribute :#{name}#{inspected_options}\"", "end" ]
Creates a new AttributeDefinition @example Create an attribute defintion AttributeDefinition.new(:amount) @param [Symbol, String, #to_sym] name attribute name @param [Hash{Symbol => Object}] options attribute options @return [ActiveAttr::AttributeDefinition] @since 0.2.0 Returns the code that would generate the attribute definition @example Inspect the attribute definition attribute.inspect @return [String] Human-readable presentation of the attribute definition @since 0.6.0
[ "Creates", "a", "new", "AttributeDefinition" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/attribute_definition.rb#L70-L74
train
cgriego/active_attr
lib/active_attr/attribute_defaults.rb
ActiveAttr.AttributeDefaults.apply_defaults
def apply_defaults(defaults=attribute_defaults) @attributes ||= {} defaults.each do |name, value| # instance variable is used here to avoid any dirty tracking in attribute setter methods @attributes[name] = value unless @attributes.has_key? name end end
ruby
def apply_defaults(defaults=attribute_defaults) @attributes ||= {} defaults.each do |name, value| # instance variable is used here to avoid any dirty tracking in attribute setter methods @attributes[name] = value unless @attributes.has_key? name end end
[ "def", "apply_defaults", "(", "defaults", "=", "attribute_defaults", ")", "@attributes", "||=", "{", "}", "defaults", ".", "each", "do", "|", "name", ",", "value", "|", "# instance variable is used here to avoid any dirty tracking in attribute setter methods", "@attributes", "[", "name", "]", "=", "value", "unless", "@attributes", ".", "has_key?", "name", "end", "end" ]
Applies the attribute defaults Applies all the default values to any attributes not yet set, avoiding any attribute setter logic, such as dirty tracking. @example Usage class Person include ActiveAttr::AttributeDefaults attribute :first_name, :default => "John" def reset! @attributes = {} apply_defaults end end person = Person.new(:first_name => "Chris") person.reset! person.first_name #=> "John" @param [Hash{String => Object}, #each] defaults The defaults to apply @since 0.5.0
[ "Applies", "the", "attribute", "defaults" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/attribute_defaults.rb#L70-L76
train
cgriego/active_attr
lib/active_attr/attribute_defaults.rb
ActiveAttr.AttributeDefaults._attribute_default
def _attribute_default(attribute_name) default = self.class.attributes[attribute_name][:default] case when default.respond_to?(:call) then instance_exec(&default) when default.duplicable? then default.dup else default end end
ruby
def _attribute_default(attribute_name) default = self.class.attributes[attribute_name][:default] case when default.respond_to?(:call) then instance_exec(&default) when default.duplicable? then default.dup else default end end
[ "def", "_attribute_default", "(", "attribute_name", ")", "default", "=", "self", ".", "class", ".", "attributes", "[", "attribute_name", "]", "[", ":default", "]", "case", "when", "default", ".", "respond_to?", "(", ":call", ")", "then", "instance_exec", "(", "default", ")", "when", "default", ".", "duplicable?", "then", "default", ".", "dup", "else", "default", "end", "end" ]
Calculates an attribute default @private @since 0.5.0
[ "Calculates", "an", "attribute", "default" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/attribute_defaults.rb#L110-L118
train
cgriego/active_attr
lib/active_attr/mass_assignment.rb
ActiveAttr.MassAssignment.sanitize_for_mass_assignment_with_or_without_role
def sanitize_for_mass_assignment_with_or_without_role(new_attributes, options) if method(:sanitize_for_mass_assignment).arity.abs > 1 sanitize_for_mass_assignment new_attributes, options[:as] || :default else sanitize_for_mass_assignment new_attributes end end
ruby
def sanitize_for_mass_assignment_with_or_without_role(new_attributes, options) if method(:sanitize_for_mass_assignment).arity.abs > 1 sanitize_for_mass_assignment new_attributes, options[:as] || :default else sanitize_for_mass_assignment new_attributes end end
[ "def", "sanitize_for_mass_assignment_with_or_without_role", "(", "new_attributes", ",", "options", ")", "if", "method", "(", ":sanitize_for_mass_assignment", ")", ".", "arity", ".", "abs", ">", "1", "sanitize_for_mass_assignment", "new_attributes", ",", "options", "[", ":as", "]", "||", ":default", "else", "sanitize_for_mass_assignment", "new_attributes", "end", "end" ]
Rails 3.0 and 4.0 do not take a role argument for the sanitizer @since 0.7.0
[ "Rails", "3", ".", "0", "and", "4", ".", "0", "do", "not", "take", "a", "role", "argument", "for", "the", "sanitizer" ]
1f3a49309561491fe436e3253de7d2faa92012ec
https://github.com/cgriego/active_attr/blob/1f3a49309561491fe436e3253de7d2faa92012ec/lib/active_attr/mass_assignment.rb#L87-L93
train
jmfederico/draftsman
lib/draftsman/frameworks/sinatra.rb
Draftsman.Sinatra.user_for_draftsman
def user_for_draftsman return unless defined?(current_user) ActiveSupport::VERSION::MAJOR >= 4 ? current_user.try!(:id) : current_user.try(:id) rescue NoMethodError current_user end
ruby
def user_for_draftsman return unless defined?(current_user) ActiveSupport::VERSION::MAJOR >= 4 ? current_user.try!(:id) : current_user.try(:id) rescue NoMethodError current_user end
[ "def", "user_for_draftsman", "return", "unless", "defined?", "(", "current_user", ")", "ActiveSupport", "::", "VERSION", "::", "MAJOR", ">=", "4", "?", "current_user", ".", "try!", "(", ":id", ")", ":", "current_user", ".", "try", "(", ":id", ")", "rescue", "NoMethodError", "current_user", "end" ]
Returns the user who is responsible for any changes that occur. By default this calls `current_user` 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", "and", "returns", "the", "result", "." ]
fe7d29d37f12d126e502647c68ab9468747f5719
https://github.com/jmfederico/draftsman/blob/fe7d29d37f12d126e502647c68ab9468747f5719/lib/draftsman/frameworks/sinatra.rb#L19-L24
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.set_exception
def set_exception(worker_name, exc_or_message) if exc_or_message.is_a?(Exception) self.exception = JobException.from_exception(exc_or_message) exception.worker_name = worker_name else build_exception( class_name: 'RocketJob::DirmonEntryException', message: exc_or_message, backtrace: [], worker_name: worker_name ) end end
ruby
def set_exception(worker_name, exc_or_message) if exc_or_message.is_a?(Exception) self.exception = JobException.from_exception(exc_or_message) exception.worker_name = worker_name else build_exception( class_name: 'RocketJob::DirmonEntryException', message: exc_or_message, backtrace: [], worker_name: worker_name ) end end
[ "def", "set_exception", "(", "worker_name", ",", "exc_or_message", ")", "if", "exc_or_message", ".", "is_a?", "(", "Exception", ")", "self", ".", "exception", "=", "JobException", ".", "from_exception", "(", "exc_or_message", ")", "exception", ".", "worker_name", "=", "worker_name", "else", "build_exception", "(", "class_name", ":", "'RocketJob::DirmonEntryException'", ",", "message", ":", "exc_or_message", ",", "backtrace", ":", "[", "]", ",", "worker_name", ":", "worker_name", ")", "end", "end" ]
Set exception information for this DirmonEntry and fail it
[ "Set", "exception", "information", "for", "this", "DirmonEntry", "and", "fail", "it" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L220-L232
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.later
def later(pathname) job_id = BSON::ObjectId.new archived_file_name = archive_file(job_id, pathname) job = RocketJob::Jobs::UploadFileJob.create!( job_class_name: job_class_name, properties: properties, description: "#{name}: #{pathname.basename}", upload_file_name: archived_file_name.to_s, original_file_name: pathname.to_s, job_id: job_id ) logger.info( message: 'Created RocketJob::Jobs::UploadFileJob', payload: { dirmon_entry_name: name, upload_file_name: archived_file_name.to_s, original_file_name: pathname.to_s, job_class_name: job_class_name, job_id: job_id.to_s, upload_job_id: job.id.to_s } ) job end
ruby
def later(pathname) job_id = BSON::ObjectId.new archived_file_name = archive_file(job_id, pathname) job = RocketJob::Jobs::UploadFileJob.create!( job_class_name: job_class_name, properties: properties, description: "#{name}: #{pathname.basename}", upload_file_name: archived_file_name.to_s, original_file_name: pathname.to_s, job_id: job_id ) logger.info( message: 'Created RocketJob::Jobs::UploadFileJob', payload: { dirmon_entry_name: name, upload_file_name: archived_file_name.to_s, original_file_name: pathname.to_s, job_class_name: job_class_name, job_id: job_id.to_s, upload_job_id: job.id.to_s } ) job end
[ "def", "later", "(", "pathname", ")", "job_id", "=", "BSON", "::", "ObjectId", ".", "new", "archived_file_name", "=", "archive_file", "(", "job_id", ",", "pathname", ")", "job", "=", "RocketJob", "::", "Jobs", "::", "UploadFileJob", ".", "create!", "(", "job_class_name", ":", "job_class_name", ",", "properties", ":", "properties", ",", "description", ":", "\"#{name}: #{pathname.basename}\"", ",", "upload_file_name", ":", "archived_file_name", ".", "to_s", ",", "original_file_name", ":", "pathname", ".", "to_s", ",", "job_id", ":", "job_id", ")", "logger", ".", "info", "(", "message", ":", "'Created RocketJob::Jobs::UploadFileJob'", ",", "payload", ":", "{", "dirmon_entry_name", ":", "name", ",", "upload_file_name", ":", "archived_file_name", ".", "to_s", ",", "original_file_name", ":", "pathname", ".", "to_s", ",", "job_class_name", ":", "job_class_name", ",", "job_id", ":", "job_id", ".", "to_s", ",", "upload_job_id", ":", "job", ".", "id", ".", "to_s", "}", ")", "job", "end" ]
Archives the file and kicks off a proxy job to upload the file.
[ "Archives", "the", "file", "and", "kicks", "off", "a", "proxy", "job", "to", "upload", "the", "file", "." ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L243-L268
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.strip_whitespace
def strip_whitespace self.pattern = pattern.strip unless pattern.nil? self.archive_directory = archive_directory.strip unless archive_directory.nil? end
ruby
def strip_whitespace self.pattern = pattern.strip unless pattern.nil? self.archive_directory = archive_directory.strip unless archive_directory.nil? end
[ "def", "strip_whitespace", "self", ".", "pattern", "=", "pattern", ".", "strip", "unless", "pattern", ".", "nil?", "self", ".", "archive_directory", "=", "archive_directory", ".", "strip", "unless", "archive_directory", ".", "nil?", "end" ]
strip whitespaces from all variables that reference paths or patterns
[ "strip", "whitespaces", "from", "all", "variables", "that", "reference", "paths", "or", "patterns" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L273-L276
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.archive_file
def archive_file(job_id, pathname) target_path = archive_pathname(pathname) target_path.mkpath target_file_name = target_path.join("#{job_id}_#{pathname.basename}") # In case the file is being moved across partitions FileUtils.move(pathname.to_s, target_file_name.to_s) target_file_name.to_s end
ruby
def archive_file(job_id, pathname) target_path = archive_pathname(pathname) target_path.mkpath target_file_name = target_path.join("#{job_id}_#{pathname.basename}") # In case the file is being moved across partitions FileUtils.move(pathname.to_s, target_file_name.to_s) target_file_name.to_s end
[ "def", "archive_file", "(", "job_id", ",", "pathname", ")", "target_path", "=", "archive_pathname", "(", "pathname", ")", "target_path", ".", "mkpath", "target_file_name", "=", "target_path", ".", "join", "(", "\"#{job_id}_#{pathname.basename}\"", ")", "# In case the file is being moved across partitions", "FileUtils", ".", "move", "(", "pathname", ".", "to_s", ",", "target_file_name", ".", "to_s", ")", "target_file_name", ".", "to_s", "end" ]
Move the file to the archive directory The archived file name is prefixed with the job id Returns [String] the fully qualified archived file name Note: - Works across partitions when the file and the archive are on different partitions
[ "Move", "the", "file", "to", "the", "archive", "directory" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L289-L296
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.job_is_a_rocket_job
def job_is_a_rocket_job klass = job_class return if job_class_name.nil? || klass&.ancestors&.include?(RocketJob::Job) errors.add(:job_class_name, "Job #{job_class_name} must be defined and inherit from RocketJob::Job") end
ruby
def job_is_a_rocket_job klass = job_class return if job_class_name.nil? || klass&.ancestors&.include?(RocketJob::Job) errors.add(:job_class_name, "Job #{job_class_name} must be defined and inherit from RocketJob::Job") end
[ "def", "job_is_a_rocket_job", "klass", "=", "job_class", "return", "if", "job_class_name", ".", "nil?", "||", "klass", "&.", "ancestors", "&.", "include?", "(", "RocketJob", "::", "Job", ")", "errors", ".", "add", "(", ":job_class_name", ",", "\"Job #{job_class_name} must be defined and inherit from RocketJob::Job\"", ")", "end" ]
Validates job_class is a Rocket Job
[ "Validates", "job_class", "is", "a", "Rocket", "Job" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L315-L319
train
rocketjob/rocketjob
lib/rocket_job/dirmon_entry.rb
RocketJob.DirmonEntry.job_has_properties
def job_has_properties klass = job_class return unless klass properties.each_pair do |k, _v| next if klass.public_method_defined?("#{k}=".to_sym) errors.add(:properties, "Unknown Property: Attempted to set a value for #{k.inspect} which is not allowed on the job #{job_class_name}") end end
ruby
def job_has_properties klass = job_class return unless klass properties.each_pair do |k, _v| next if klass.public_method_defined?("#{k}=".to_sym) errors.add(:properties, "Unknown Property: Attempted to set a value for #{k.inspect} which is not allowed on the job #{job_class_name}") end end
[ "def", "job_has_properties", "klass", "=", "job_class", "return", "unless", "klass", "properties", ".", "each_pair", "do", "|", "k", ",", "_v", "|", "next", "if", "klass", ".", "public_method_defined?", "(", "\"#{k}=\"", ".", "to_sym", ")", "errors", ".", "add", "(", ":properties", ",", "\"Unknown Property: Attempted to set a value for #{k.inspect} which is not allowed on the job #{job_class_name}\"", ")", "end", "end" ]
Does the job have all the supplied properties
[ "Does", "the", "job", "have", "all", "the", "supplied", "properties" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/dirmon_entry.rb#L322-L330
train
rocketjob/rocketjob
lib/rocket_job/cli.rb
RocketJob.CLI.boot_standalone
def boot_standalone # Try to load bundler if present begin require 'bundler/setup' Bundler.require(environment) rescue LoadError nil end require 'rocketjob' begin require 'rocketjob_enterprise' rescue LoadError nil end # Log to file except when booting rails, when it will add the log file path path = log_file ? Pathname.new(log_file) : Pathname.pwd.join("log/#{environment}.log") path.dirname.mkpath SemanticLogger.add_appender(file_name: path.to_s, formatter: :color) logger.info "Rails not detected. Running standalone: #{environment}" RocketJob::Config.load!(environment, mongo_config, symmetric_encryption_config) self.class.eager_load_jobs(File.expand_path('jobs', File.dirname(__FILE__))) self.class.eager_load_jobs end
ruby
def boot_standalone # Try to load bundler if present begin require 'bundler/setup' Bundler.require(environment) rescue LoadError nil end require 'rocketjob' begin require 'rocketjob_enterprise' rescue LoadError nil end # Log to file except when booting rails, when it will add the log file path path = log_file ? Pathname.new(log_file) : Pathname.pwd.join("log/#{environment}.log") path.dirname.mkpath SemanticLogger.add_appender(file_name: path.to_s, formatter: :color) logger.info "Rails not detected. Running standalone: #{environment}" RocketJob::Config.load!(environment, mongo_config, symmetric_encryption_config) self.class.eager_load_jobs(File.expand_path('jobs', File.dirname(__FILE__))) self.class.eager_load_jobs end
[ "def", "boot_standalone", "# Try to load bundler if present", "begin", "require", "'bundler/setup'", "Bundler", ".", "require", "(", "environment", ")", "rescue", "LoadError", "nil", "end", "require", "'rocketjob'", "begin", "require", "'rocketjob_enterprise'", "rescue", "LoadError", "nil", "end", "# Log to file except when booting rails, when it will add the log file path", "path", "=", "log_file", "?", "Pathname", ".", "new", "(", "log_file", ")", ":", "Pathname", ".", "pwd", ".", "join", "(", "\"log/#{environment}.log\"", ")", "path", ".", "dirname", ".", "mkpath", "SemanticLogger", ".", "add_appender", "(", "file_name", ":", "path", ".", "to_s", ",", "formatter", ":", ":color", ")", "logger", ".", "info", "\"Rails not detected. Running standalone: #{environment}\"", "RocketJob", "::", "Config", ".", "load!", "(", "environment", ",", "mongo_config", ",", "symmetric_encryption_config", ")", "self", ".", "class", ".", "eager_load_jobs", "(", "File", ".", "expand_path", "(", "'jobs'", ",", "File", ".", "dirname", "(", "__FILE__", ")", ")", ")", "self", ".", "class", ".", "eager_load_jobs", "end" ]
In a standalone environment, explicitly load config files
[ "In", "a", "standalone", "environment", "explicitly", "load", "config", "files" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/cli.rb#L88-L113
train
rocketjob/rocketjob
lib/rocket_job/cli.rb
RocketJob.CLI.write_pidfile
def write_pidfile return unless pidfile pid = $PID File.open(pidfile, 'w') { |f| f.puts(pid) } # Remove pidfile on exit at_exit do File.delete(pidfile) if pid == $PID end end
ruby
def write_pidfile return unless pidfile pid = $PID File.open(pidfile, 'w') { |f| f.puts(pid) } # Remove pidfile on exit at_exit do File.delete(pidfile) if pid == $PID end end
[ "def", "write_pidfile", "return", "unless", "pidfile", "pid", "=", "$PID", "File", ".", "open", "(", "pidfile", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "(", "pid", ")", "}", "# Remove pidfile on exit", "at_exit", "do", "File", ".", "delete", "(", "pidfile", ")", "if", "pid", "==", "$PID", "end", "end" ]
Create a PID file if requested
[ "Create", "a", "PID", "file", "if", "requested" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/cli.rb#L116-L125
train
rocketjob/rocketjob
lib/rocket_job/cli.rb
RocketJob.CLI.parse
def parse(argv) parser = OptionParser.new do |o| o.on('-n', '--name NAME', 'Unique Name of this server (Default: host_name:PID)') do |arg| @name = arg end o.on('-w', '--workers COUNT', 'Number of workers (threads) to start') do |arg| @workers = arg.to_i end o.on('-t', '--threads COUNT', 'DEPRECATED') do |arg| warn '-t and --threads are deprecated, use -w or --workers' @workers = arg.to_i end o.on('-F', '--filter REGEXP', 'Limit this server to only those job classes that match this regular expression (case-insensitive). Example: "DirmonJob|WeeklyReportJob"') do |arg| @include_filter = Regexp.new(arg, true) end o.on('-E', '--exclude REGEXP', 'Prevent this server from working on any job classes that match this regular expression (case-insensitive). Example: "DirmonJob|WeeklyReportJob"') do |arg| @exclude_filter = Regexp.new(arg, true) end o.on('-W', '--where JSON', "Limit this server instance to the supplied mongo query filter. Supply as a string in JSON format. Example: '{\"priority\":{\"$lte\":25}}'") do |arg| @where_filter = JSON.parse(arg) end o.on('-q', '--quiet', 'Do not write to stdout, only to logfile. Necessary when running as a daemon') do @quiet = true end o.on('-d', '--dir DIR', 'Directory containing Rails app, if not current directory') do |arg| @directory = arg end o.on('-e', '--environment ENVIRONMENT', 'The environment to run the app on (Default: RAILS_ENV || RACK_ENV || development)') do |arg| @environment = arg end o.on('-l', '--log_level trace|debug|info|warn|error|fatal', 'The log level to use') do |arg| @log_level = arg end o.on('-f', '--log_file FILE_NAME', 'The log file to write to. Default: log/<environment>.log') do |arg| @log_file = arg end o.on('--pidfile PATH', 'Use PATH as a pidfile') do |arg| @pidfile = arg end o.on('-m', '--mongo MONGO_CONFIG_FILE_NAME', 'Path and filename of config file. Default: config/mongoid.yml') do |arg| @mongo_config = arg end o.on('-s', '--symmetric-encryption SYMMETRIC_ENCRYPTION_CONFIG_FILE_NAME', 'Path and filename of Symmetric Encryption config file. Default: config/symmetric-encryption.yml') do |arg| @symmetric_encryption_config = arg end o.on('-v', '--version', 'Print the version information') do puts "Rocket Job v#{RocketJob::VERSION}" exit 1 end end parser.banner = 'rocketjob <options>' parser.on_tail '-h', '--help', 'Show help' do puts parser exit 1 end parser.parse! argv end
ruby
def parse(argv) parser = OptionParser.new do |o| o.on('-n', '--name NAME', 'Unique Name of this server (Default: host_name:PID)') do |arg| @name = arg end o.on('-w', '--workers COUNT', 'Number of workers (threads) to start') do |arg| @workers = arg.to_i end o.on('-t', '--threads COUNT', 'DEPRECATED') do |arg| warn '-t and --threads are deprecated, use -w or --workers' @workers = arg.to_i end o.on('-F', '--filter REGEXP', 'Limit this server to only those job classes that match this regular expression (case-insensitive). Example: "DirmonJob|WeeklyReportJob"') do |arg| @include_filter = Regexp.new(arg, true) end o.on('-E', '--exclude REGEXP', 'Prevent this server from working on any job classes that match this regular expression (case-insensitive). Example: "DirmonJob|WeeklyReportJob"') do |arg| @exclude_filter = Regexp.new(arg, true) end o.on('-W', '--where JSON', "Limit this server instance to the supplied mongo query filter. Supply as a string in JSON format. Example: '{\"priority\":{\"$lte\":25}}'") do |arg| @where_filter = JSON.parse(arg) end o.on('-q', '--quiet', 'Do not write to stdout, only to logfile. Necessary when running as a daemon') do @quiet = true end o.on('-d', '--dir DIR', 'Directory containing Rails app, if not current directory') do |arg| @directory = arg end o.on('-e', '--environment ENVIRONMENT', 'The environment to run the app on (Default: RAILS_ENV || RACK_ENV || development)') do |arg| @environment = arg end o.on('-l', '--log_level trace|debug|info|warn|error|fatal', 'The log level to use') do |arg| @log_level = arg end o.on('-f', '--log_file FILE_NAME', 'The log file to write to. Default: log/<environment>.log') do |arg| @log_file = arg end o.on('--pidfile PATH', 'Use PATH as a pidfile') do |arg| @pidfile = arg end o.on('-m', '--mongo MONGO_CONFIG_FILE_NAME', 'Path and filename of config file. Default: config/mongoid.yml') do |arg| @mongo_config = arg end o.on('-s', '--symmetric-encryption SYMMETRIC_ENCRYPTION_CONFIG_FILE_NAME', 'Path and filename of Symmetric Encryption config file. Default: config/symmetric-encryption.yml') do |arg| @symmetric_encryption_config = arg end o.on('-v', '--version', 'Print the version information') do puts "Rocket Job v#{RocketJob::VERSION}" exit 1 end end parser.banner = 'rocketjob <options>' parser.on_tail '-h', '--help', 'Show help' do puts parser exit 1 end parser.parse! argv end
[ "def", "parse", "(", "argv", ")", "parser", "=", "OptionParser", ".", "new", "do", "|", "o", "|", "o", ".", "on", "(", "'-n'", ",", "'--name NAME'", ",", "'Unique Name of this server (Default: host_name:PID)'", ")", "do", "|", "arg", "|", "@name", "=", "arg", "end", "o", ".", "on", "(", "'-w'", ",", "'--workers COUNT'", ",", "'Number of workers (threads) to start'", ")", "do", "|", "arg", "|", "@workers", "=", "arg", ".", "to_i", "end", "o", ".", "on", "(", "'-t'", ",", "'--threads COUNT'", ",", "'DEPRECATED'", ")", "do", "|", "arg", "|", "warn", "'-t and --threads are deprecated, use -w or --workers'", "@workers", "=", "arg", ".", "to_i", "end", "o", ".", "on", "(", "'-F'", ",", "'--filter REGEXP'", ",", "'Limit this server to only those job classes that match this regular expression (case-insensitive). Example: \"DirmonJob|WeeklyReportJob\"'", ")", "do", "|", "arg", "|", "@include_filter", "=", "Regexp", ".", "new", "(", "arg", ",", "true", ")", "end", "o", ".", "on", "(", "'-E'", ",", "'--exclude REGEXP'", ",", "'Prevent this server from working on any job classes that match this regular expression (case-insensitive). Example: \"DirmonJob|WeeklyReportJob\"'", ")", "do", "|", "arg", "|", "@exclude_filter", "=", "Regexp", ".", "new", "(", "arg", ",", "true", ")", "end", "o", ".", "on", "(", "'-W'", ",", "'--where JSON'", ",", "\"Limit this server instance to the supplied mongo query filter. Supply as a string in JSON format. Example: '{\\\"priority\\\":{\\\"$lte\\\":25}}'\"", ")", "do", "|", "arg", "|", "@where_filter", "=", "JSON", ".", "parse", "(", "arg", ")", "end", "o", ".", "on", "(", "'-q'", ",", "'--quiet'", ",", "'Do not write to stdout, only to logfile. Necessary when running as a daemon'", ")", "do", "@quiet", "=", "true", "end", "o", ".", "on", "(", "'-d'", ",", "'--dir DIR'", ",", "'Directory containing Rails app, if not current directory'", ")", "do", "|", "arg", "|", "@directory", "=", "arg", "end", "o", ".", "on", "(", "'-e'", ",", "'--environment ENVIRONMENT'", ",", "'The environment to run the app on (Default: RAILS_ENV || RACK_ENV || development)'", ")", "do", "|", "arg", "|", "@environment", "=", "arg", "end", "o", ".", "on", "(", "'-l'", ",", "'--log_level trace|debug|info|warn|error|fatal'", ",", "'The log level to use'", ")", "do", "|", "arg", "|", "@log_level", "=", "arg", "end", "o", ".", "on", "(", "'-f'", ",", "'--log_file FILE_NAME'", ",", "'The log file to write to. Default: log/<environment>.log'", ")", "do", "|", "arg", "|", "@log_file", "=", "arg", "end", "o", ".", "on", "(", "'--pidfile PATH'", ",", "'Use PATH as a pidfile'", ")", "do", "|", "arg", "|", "@pidfile", "=", "arg", "end", "o", ".", "on", "(", "'-m'", ",", "'--mongo MONGO_CONFIG_FILE_NAME'", ",", "'Path and filename of config file. Default: config/mongoid.yml'", ")", "do", "|", "arg", "|", "@mongo_config", "=", "arg", "end", "o", ".", "on", "(", "'-s'", ",", "'--symmetric-encryption SYMMETRIC_ENCRYPTION_CONFIG_FILE_NAME'", ",", "'Path and filename of Symmetric Encryption config file. Default: config/symmetric-encryption.yml'", ")", "do", "|", "arg", "|", "@symmetric_encryption_config", "=", "arg", "end", "o", ".", "on", "(", "'-v'", ",", "'--version'", ",", "'Print the version information'", ")", "do", "puts", "\"Rocket Job v#{RocketJob::VERSION}\"", "exit", "1", "end", "end", "parser", ".", "banner", "=", "'rocketjob <options>'", "parser", ".", "on_tail", "'-h'", ",", "'--help'", ",", "'Show help'", "do", "puts", "parser", "exit", "1", "end", "parser", ".", "parse!", "argv", "end" ]
Parse command line options placing results in the corresponding instance variables
[ "Parse", "command", "line", "options", "placing", "results", "in", "the", "corresponding", "instance", "variables" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/cli.rb#L168-L224
train
rocketjob/rocketjob
lib/rocket_job/worker.rb
RocketJob.Worker.run
def run Thread.current.name = format('rocketjob %03i', id) logger.info 'Started' until shutdown? wait = RocketJob::Config.instance.max_poll_seconds if process_available_jobs # Keeps workers staggered across the poll interval so that # all workers don't poll at the same time wait = rand(wait * 1000) / 1000 end break if wait_for_shutdown?(wait) end logger.info 'Stopping' rescue Exception => exc logger.fatal('Unhandled exception in job processing thread', exc) ensure ActiveRecord::Base.clear_active_connections! if defined?(ActiveRecord::Base) end
ruby
def run Thread.current.name = format('rocketjob %03i', id) logger.info 'Started' until shutdown? wait = RocketJob::Config.instance.max_poll_seconds if process_available_jobs # Keeps workers staggered across the poll interval so that # all workers don't poll at the same time wait = rand(wait * 1000) / 1000 end break if wait_for_shutdown?(wait) end logger.info 'Stopping' rescue Exception => exc logger.fatal('Unhandled exception in job processing thread', exc) ensure ActiveRecord::Base.clear_active_connections! if defined?(ActiveRecord::Base) end
[ "def", "run", "Thread", ".", "current", ".", "name", "=", "format", "(", "'rocketjob %03i'", ",", "id", ")", "logger", ".", "info", "'Started'", "until", "shutdown?", "wait", "=", "RocketJob", "::", "Config", ".", "instance", ".", "max_poll_seconds", "if", "process_available_jobs", "# Keeps workers staggered across the poll interval so that", "# all workers don't poll at the same time", "wait", "=", "rand", "(", "wait", "*", "1000", ")", "/", "1000", "end", "break", "if", "wait_for_shutdown?", "(", "wait", ")", "end", "logger", ".", "info", "'Stopping'", "rescue", "Exception", "=>", "exc", "logger", ".", "fatal", "(", "'Unhandled exception in job processing thread'", ",", "exc", ")", "ensure", "ActiveRecord", "::", "Base", ".", "clear_active_connections!", "if", "defined?", "(", "ActiveRecord", "::", "Base", ")", "end" ]
Process jobs until it shuts down Params worker_id [Integer] The number of this worker for logging purposes
[ "Process", "jobs", "until", "it", "shuts", "down" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/worker.rb#L92-L109
train
rocketjob/rocketjob
lib/rocket_job/worker.rb
RocketJob.Worker.reset_filter_if_expired
def reset_filter_if_expired # Only clear out the current_filter after every `re_check_seconds` time = Time.now return unless (time - @re_check_start) > re_check_seconds @re_check_start = time self.current_filter = filter.dup if current_filter != filter end
ruby
def reset_filter_if_expired # Only clear out the current_filter after every `re_check_seconds` time = Time.now return unless (time - @re_check_start) > re_check_seconds @re_check_start = time self.current_filter = filter.dup if current_filter != filter end
[ "def", "reset_filter_if_expired", "# Only clear out the current_filter after every `re_check_seconds`", "time", "=", "Time", ".", "now", "return", "unless", "(", "time", "-", "@re_check_start", ")", ">", "re_check_seconds", "@re_check_start", "=", "time", "self", ".", "current_filter", "=", "filter", ".", "dup", "if", "current_filter", "!=", "filter", "end" ]
Resets the current job filter if the relevant time interval has passed
[ "Resets", "the", "current", "job", "filter", "if", "the", "relevant", "time", "interval", "has", "passed" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/worker.rb#L128-L135
train
rocketjob/rocketjob
lib/rocket_job/plugins/rufus/cron_line.rb
RocketJob::Plugins::Rufus.CronLine.previous_time
def previous_time(from=ZoTime.now) pt = nil zt = ZoTime.new(from.to_i - 1, @timezone) miny = from.year - NEXT_TIME_MAX_YEARS loop do pt = zt.dup fail RangeError.new( "failed to reach occurrence within " + "#{NEXT_TIME_MAX_YEARS} years for '#{original}'" ) if pt.year < miny unless date_match?(pt) zt.substract(pt.hour * 3600 + pt.min * 60 + pt.sec + 1) next end unless sub_match?(pt, :hour, @hours) zt.substract(pt.min * 60 + pt.sec + 1) next end unless sub_match?(pt, :min, @minutes) zt.substract(pt.sec + 1) next end unless sub_match?(pt, :sec, @seconds) zt.substract(prev_second(pt)) next end break end pt end
ruby
def previous_time(from=ZoTime.now) pt = nil zt = ZoTime.new(from.to_i - 1, @timezone) miny = from.year - NEXT_TIME_MAX_YEARS loop do pt = zt.dup fail RangeError.new( "failed to reach occurrence within " + "#{NEXT_TIME_MAX_YEARS} years for '#{original}'" ) if pt.year < miny unless date_match?(pt) zt.substract(pt.hour * 3600 + pt.min * 60 + pt.sec + 1) next end unless sub_match?(pt, :hour, @hours) zt.substract(pt.min * 60 + pt.sec + 1) next end unless sub_match?(pt, :min, @minutes) zt.substract(pt.sec + 1) next end unless sub_match?(pt, :sec, @seconds) zt.substract(prev_second(pt)) next end break end pt end
[ "def", "previous_time", "(", "from", "=", "ZoTime", ".", "now", ")", "pt", "=", "nil", "zt", "=", "ZoTime", ".", "new", "(", "from", ".", "to_i", "-", "1", ",", "@timezone", ")", "miny", "=", "from", ".", "year", "-", "NEXT_TIME_MAX_YEARS", "loop", "do", "pt", "=", "zt", ".", "dup", "fail", "RangeError", ".", "new", "(", "\"failed to reach occurrence within \"", "+", "\"#{NEXT_TIME_MAX_YEARS} years for '#{original}'\"", ")", "if", "pt", ".", "year", "<", "miny", "unless", "date_match?", "(", "pt", ")", "zt", ".", "substract", "(", "pt", ".", "hour", "*", "3600", "+", "pt", ".", "min", "*", "60", "+", "pt", ".", "sec", "+", "1", ")", "next", "end", "unless", "sub_match?", "(", "pt", ",", ":hour", ",", "@hours", ")", "zt", ".", "substract", "(", "pt", ".", "min", "*", "60", "+", "pt", ".", "sec", "+", "1", ")", "next", "end", "unless", "sub_match?", "(", "pt", ",", ":min", ",", "@minutes", ")", "zt", ".", "substract", "(", "pt", ".", "sec", "+", "1", ")", "next", "end", "unless", "sub_match?", "(", "pt", ",", ":sec", ",", "@seconds", ")", "zt", ".", "substract", "(", "prev_second", "(", "pt", ")", ")", "next", "end", "break", "end", "pt", "end" ]
Returns the previous time the cronline matched. It's like next_time, but for the past.
[ "Returns", "the", "previous", "time", "the", "cronline", "matched", ".", "It", "s", "like", "next_time", "but", "for", "the", "past", "." ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/plugins/rufus/cron_line.rb#L182-L218
train
rocketjob/rocketjob
lib/rocket_job/worker_pool.rb
RocketJob.WorkerPool.rebalance
def rebalance(max_workers, stagger_start = false) count = max_workers.to_i - living_count return 0 unless count > 0 logger.info("#{'Stagger ' if stagger_start}Starting #{count} workers") add_one count -= 1 delay = Config.instance.max_poll_seconds.to_f / max_workers count.times.each do sleep(delay) if stagger_start return -1 if Supervisor.shutdown? add_one end end
ruby
def rebalance(max_workers, stagger_start = false) count = max_workers.to_i - living_count return 0 unless count > 0 logger.info("#{'Stagger ' if stagger_start}Starting #{count} workers") add_one count -= 1 delay = Config.instance.max_poll_seconds.to_f / max_workers count.times.each do sleep(delay) if stagger_start return -1 if Supervisor.shutdown? add_one end end
[ "def", "rebalance", "(", "max_workers", ",", "stagger_start", "=", "false", ")", "count", "=", "max_workers", ".", "to_i", "-", "living_count", "return", "0", "unless", "count", ">", "0", "logger", ".", "info", "(", "\"#{'Stagger ' if stagger_start}Starting #{count} workers\"", ")", "add_one", "count", "-=", "1", "delay", "=", "Config", ".", "instance", ".", "max_poll_seconds", ".", "to_f", "/", "max_workers", "count", ".", "times", ".", "each", "do", "sleep", "(", "delay", ")", "if", "stagger_start", "return", "-", "1", "if", "Supervisor", ".", "shutdown?", "add_one", "end", "end" ]
Add new workers to get back to the `max_workers` if not already at `max_workers` Parameters stagger_start Whether to stagger when the workers poll for work the first time. It spreads out the queue polling over the max_poll_seconds so that not all workers poll at the same time. The worker also responds faster than max_poll_seconds when a new job is created.
[ "Add", "new", "workers", "to", "get", "back", "to", "the", "max_workers", "if", "not", "already", "at", "max_workers", "Parameters", "stagger_start", "Whether", "to", "stagger", "when", "the", "workers", "poll", "for", "work", "the", "first", "time", ".", "It", "spreads", "out", "the", "queue", "polling", "over", "the", "max_poll_seconds", "so", "that", "not", "all", "workers", "poll", "at", "the", "same", "time", ".", "The", "worker", "also", "responds", "faster", "than", "max_poll_seconds", "when", "a", "new", "job", "is", "created", "." ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/worker_pool.rb#L29-L44
train
rocketjob/rocketjob
lib/rocket_job/performance.rb
RocketJob.Performance.export_results
def export_results(results) CSV.open("job_results_#{ruby}_#{servers}s_#{workers}w_v#{version}.csv", 'wb') do |csv| csv << results.first.keys results.each { |result| csv << result.values } end end
ruby
def export_results(results) CSV.open("job_results_#{ruby}_#{servers}s_#{workers}w_v#{version}.csv", 'wb') do |csv| csv << results.first.keys results.each { |result| csv << result.values } end end
[ "def", "export_results", "(", "results", ")", "CSV", ".", "open", "(", "\"job_results_#{ruby}_#{servers}s_#{workers}w_v#{version}.csv\"", ",", "'wb'", ")", "do", "|", "csv", "|", "csv", "<<", "results", ".", "first", ".", "keys", "results", ".", "each", "{", "|", "result", "|", "csv", "<<", "result", ".", "values", "}", "end", "end" ]
Export the Results hash to a CSV file
[ "Export", "the", "Results", "hash", "to", "a", "CSV", "file" ]
6492dd68bf8b906fcca6d374cca65e0238ce07b7
https://github.com/rocketjob/rocketjob/blob/6492dd68bf8b906fcca6d374cca65e0238ce07b7/lib/rocket_job/performance.rb#L60-L65
train
envato/event_sourcery
lib/event_sourcery/event.rb
EventSourcery.Event.with
def with(event_class: self.class, **attributes) if self.class != Event && !attributes[:type].nil? && attributes[:type] != type raise Error, 'When using typed events change the type by changing the event class.' end event_class.new(**to_h.merge!(attributes)) end
ruby
def with(event_class: self.class, **attributes) if self.class != Event && !attributes[:type].nil? && attributes[:type] != type raise Error, 'When using typed events change the type by changing the event class.' end event_class.new(**to_h.merge!(attributes)) end
[ "def", "with", "(", "event_class", ":", "self", ".", "class", ",", "**", "attributes", ")", "if", "self", ".", "class", "!=", "Event", "&&", "!", "attributes", "[", ":type", "]", ".", "nil?", "&&", "attributes", "[", ":type", "]", "!=", "type", "raise", "Error", ",", "'When using typed events change the type by changing the event class.'", "end", "event_class", ".", "new", "(", "**", "to_h", ".", "merge!", "(", "attributes", ")", ")", "end" ]
create a new event identical to the old event except for the provided changes @param attributes [Hash] @return Event @example old_event = EventSourcery::Event.new(type: "item_added", causation_id: nil) new_event = old_event.with(causation_id: "05781bd6-796a-4a58-8573-b109f683fd99") new_event.type # => "item_added" new_event.causation_id # => "05781bd6-796a-4a58-8573-b109f683fd99" old_event.type # => "item_added" old_event.causation_id # => nil # Of course, with can accept any number of event attributes: new_event = old_event.with(id: 42, version: 77, body: { 'attr' => 'value' }) # When using typed events you can also override the event class: new_event = old_event.with(event_class: ItemRemoved) new_event.type # => "item_removed" new_event.class # => ItemRemoved
[ "create", "a", "new", "event", "identical", "to", "the", "old", "event", "except", "for", "the", "provided", "changes" ]
f844921b0368af2ee6342a988ee0a2635c7c821c
https://github.com/envato/event_sourcery/blob/f844921b0368af2ee6342a988ee0a2635c7c821c/lib/event_sourcery/event.rb#L138-L144
train
envato/event_sourcery
lib/event_sourcery/event.rb
EventSourcery.Event.to_h
def to_h { id: id, uuid: uuid, aggregate_id: aggregate_id, type: type, body: body, version: version, created_at: created_at, correlation_id: correlation_id, causation_id: causation_id, } end
ruby
def to_h { id: id, uuid: uuid, aggregate_id: aggregate_id, type: type, body: body, version: version, created_at: created_at, correlation_id: correlation_id, causation_id: causation_id, } end
[ "def", "to_h", "{", "id", ":", "id", ",", "uuid", ":", "uuid", ",", "aggregate_id", ":", "aggregate_id", ",", "type", ":", "type", ",", "body", ":", "body", ",", "version", ":", "version", ",", "created_at", ":", "created_at", ",", "correlation_id", ":", "correlation_id", ",", "causation_id", ":", "causation_id", ",", "}", "end" ]
returns a hash of the event attributes @return Hash
[ "returns", "a", "hash", "of", "the", "event", "attributes" ]
f844921b0368af2ee6342a988ee0a2635c7c821c
https://github.com/envato/event_sourcery/blob/f844921b0368af2ee6342a988ee0a2635c7c821c/lib/event_sourcery/event.rb#L149-L161
train
senchalabs/jsduck
lib/jsduck/parser.rb
JsDuck.Parser.parse
def parse(contents, filename="", options={}) @doc_processor.filename = @filename = filename parse_js_or_scss(contents, filename, options).map do |docset| expand(docset) end.flatten.map do |docset| merge(docset) end end
ruby
def parse(contents, filename="", options={}) @doc_processor.filename = @filename = filename parse_js_or_scss(contents, filename, options).map do |docset| expand(docset) end.flatten.map do |docset| merge(docset) end end
[ "def", "parse", "(", "contents", ",", "filename", "=", "\"\"", ",", "options", "=", "{", "}", ")", "@doc_processor", ".", "filename", "=", "@filename", "=", "filename", "parse_js_or_scss", "(", "contents", ",", "filename", ",", "options", ")", ".", "map", "do", "|", "docset", "|", "expand", "(", "docset", ")", "end", ".", "flatten", ".", "map", "do", "|", "docset", "|", "merge", "(", "docset", ")", "end", "end" ]
Parses file into final docset that can be fed into Aggregator
[ "Parses", "file", "into", "final", "docset", "that", "can", "be", "fed", "into", "Aggregator" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/parser.rb#L27-L35
train
senchalabs/jsduck
lib/jsduck/parser.rb
JsDuck.Parser.parse_js_or_scss
def parse_js_or_scss(contents, filename, options) if filename =~ /\.scss$/ docs = Css::Parser.new(contents, options).parse else docs = Js::Parser.new(contents, options).parse docs = Js::Ast.new(docs).detect_all! end end
ruby
def parse_js_or_scss(contents, filename, options) if filename =~ /\.scss$/ docs = Css::Parser.new(contents, options).parse else docs = Js::Parser.new(contents, options).parse docs = Js::Ast.new(docs).detect_all! end end
[ "def", "parse_js_or_scss", "(", "contents", ",", "filename", ",", "options", ")", "if", "filename", "=~", "/", "\\.", "/", "docs", "=", "Css", "::", "Parser", ".", "new", "(", "contents", ",", "options", ")", ".", "parse", "else", "docs", "=", "Js", "::", "Parser", ".", "new", "(", "contents", ",", "options", ")", ".", "parse", "docs", "=", "Js", "::", "Ast", ".", "new", "(", "docs", ")", ".", "detect_all!", "end", "end" ]
Parses the file depending on filename as JS or SCSS
[ "Parses", "the", "file", "depending", "on", "filename", "as", "JS", "or", "SCSS" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/parser.rb#L40-L47
train
senchalabs/jsduck
lib/jsduck/parser.rb
JsDuck.Parser.expand
def expand(docset) docset[:comment] = @doc_parser.parse(docset[:comment], @filename, docset[:linenr]) docset[:doc_map] = Doc::Map.build(docset[:comment]) docset[:tagname] = BaseType.detect(docset[:doc_map], docset[:code]) if docset[:tagname] == :class # expand class into several docsets, and rebuild doc-maps for all of them. @class_doc_expander.expand(docset).map do |ds| ds[:doc_map] = Doc::Map.build(ds[:comment]) ds end else docset end end
ruby
def expand(docset) docset[:comment] = @doc_parser.parse(docset[:comment], @filename, docset[:linenr]) docset[:doc_map] = Doc::Map.build(docset[:comment]) docset[:tagname] = BaseType.detect(docset[:doc_map], docset[:code]) if docset[:tagname] == :class # expand class into several docsets, and rebuild doc-maps for all of them. @class_doc_expander.expand(docset).map do |ds| ds[:doc_map] = Doc::Map.build(ds[:comment]) ds end else docset end end
[ "def", "expand", "(", "docset", ")", "docset", "[", ":comment", "]", "=", "@doc_parser", ".", "parse", "(", "docset", "[", ":comment", "]", ",", "@filename", ",", "docset", "[", ":linenr", "]", ")", "docset", "[", ":doc_map", "]", "=", "Doc", "::", "Map", ".", "build", "(", "docset", "[", ":comment", "]", ")", "docset", "[", ":tagname", "]", "=", "BaseType", ".", "detect", "(", "docset", "[", ":doc_map", "]", ",", "docset", "[", ":code", "]", ")", "if", "docset", "[", ":tagname", "]", "==", ":class", "# expand class into several docsets, and rebuild doc-maps for all of them.", "@class_doc_expander", ".", "expand", "(", "docset", ")", ".", "map", "do", "|", "ds", "|", "ds", "[", ":doc_map", "]", "=", "Doc", "::", "Map", ".", "build", "(", "ds", "[", ":comment", "]", ")", "ds", "end", "else", "docset", "end", "end" ]
Parses the docs, detects tagname and expands class docset
[ "Parses", "the", "docs", "detects", "tagname", "and", "expands", "class", "docset" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/parser.rb#L50-L64
train
senchalabs/jsduck
lib/jsduck/parser.rb
JsDuck.Parser.merge
def merge(docset) @doc_processor.linenr = docset[:linenr] docset[:comment] = @doc_processor.process(docset[:tagname], docset[:doc_map]) docset.delete(:doc_map) @merger.merge(docset, @filename, docset[:linenr]) end
ruby
def merge(docset) @doc_processor.linenr = docset[:linenr] docset[:comment] = @doc_processor.process(docset[:tagname], docset[:doc_map]) docset.delete(:doc_map) @merger.merge(docset, @filename, docset[:linenr]) end
[ "def", "merge", "(", "docset", ")", "@doc_processor", ".", "linenr", "=", "docset", "[", ":linenr", "]", "docset", "[", ":comment", "]", "=", "@doc_processor", ".", "process", "(", "docset", "[", ":tagname", "]", ",", "docset", "[", ":doc_map", "]", ")", "docset", ".", "delete", "(", ":doc_map", ")", "@merger", ".", "merge", "(", "docset", ",", "@filename", ",", "docset", "[", ":linenr", "]", ")", "end" ]
Merges comment and code parts of docset
[ "Merges", "comment", "and", "code", "parts", "of", "docset" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/parser.rb#L67-L73
train
senchalabs/jsduck
lib/jsduck/cache.rb
JsDuck.Cache.read
def read(file_name, file_contents) fname = cache_file_name(file_name, file_contents) if File.exists?(fname) @previous_entry = fname File.open(fname, "rb") {|file| Marshal::load(file) } else @previous_entry = nil nil end end
ruby
def read(file_name, file_contents) fname = cache_file_name(file_name, file_contents) if File.exists?(fname) @previous_entry = fname File.open(fname, "rb") {|file| Marshal::load(file) } else @previous_entry = nil nil end end
[ "def", "read", "(", "file_name", ",", "file_contents", ")", "fname", "=", "cache_file_name", "(", "file_name", ",", "file_contents", ")", "if", "File", ".", "exists?", "(", "fname", ")", "@previous_entry", "=", "fname", "File", ".", "open", "(", "fname", ",", "\"rb\"", ")", "{", "|", "file", "|", "Marshal", "::", "load", "(", "file", ")", "}", "else", "@previous_entry", "=", "nil", "nil", "end", "end" ]
Given the name and contents of a source file, reads the already parsed data structure from cache. Returns nil when not found.
[ "Given", "the", "name", "and", "contents", "of", "a", "source", "file", "reads", "the", "already", "parsed", "data", "structure", "from", "cache", ".", "Returns", "nil", "when", "not", "found", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/cache.rb#L76-L85
train
senchalabs/jsduck
lib/jsduck/cache.rb
JsDuck.Cache.write
def write(file_name, file_contents, data) fname = cache_file_name(file_name, file_contents) @previous_entry = fname File.open(fname, "wb") {|file| Marshal::dump(data, file) } end
ruby
def write(file_name, file_contents, data) fname = cache_file_name(file_name, file_contents) @previous_entry = fname File.open(fname, "wb") {|file| Marshal::dump(data, file) } end
[ "def", "write", "(", "file_name", ",", "file_contents", ",", "data", ")", "fname", "=", "cache_file_name", "(", "file_name", ",", "file_contents", ")", "@previous_entry", "=", "fname", "File", ".", "open", "(", "fname", ",", "\"wb\"", ")", "{", "|", "file", "|", "Marshal", "::", "dump", "(", "data", ",", "file", ")", "}", "end" ]
Writes parse data into cache under a name generated from the name and contents of a source file.
[ "Writes", "parse", "data", "into", "cache", "under", "a", "name", "generated", "from", "the", "name", "and", "contents", "of", "a", "source", "file", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/cache.rb#L89-L93
train
senchalabs/jsduck
lib/jsduck/guides.rb
JsDuck.Guides.write
def write(dir) FileUtils.mkdir(dir) unless File.exists?(dir) each_item {|guide| write_guide(guide, dir) } end
ruby
def write(dir) FileUtils.mkdir(dir) unless File.exists?(dir) each_item {|guide| write_guide(guide, dir) } end
[ "def", "write", "(", "dir", ")", "FileUtils", ".", "mkdir", "(", "dir", ")", "unless", "File", ".", "exists?", "(", "dir", ")", "each_item", "{", "|", "guide", "|", "write_guide", "(", "guide", ",", "dir", ")", "}", "end" ]
Parses guides config file Writes all guides to given dir in JsonP format
[ "Parses", "guides", "config", "file", "Writes", "all", "guides", "to", "given", "dir", "in", "JsonP", "format" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guides.rb#L36-L39
train
senchalabs/jsduck
lib/jsduck/guides.rb
JsDuck.Guides.fix_icon
def fix_icon(dir) if File.exists?(dir+"/icon.png") # All ok elsif File.exists?(dir+"/icon-lg.png") FileUtils.mv(dir+"/icon-lg.png", dir+"/icon.png") else FileUtils.cp(@opts.template+"/resources/images/default-guide.png", dir+"/icon.png") end end
ruby
def fix_icon(dir) if File.exists?(dir+"/icon.png") # All ok elsif File.exists?(dir+"/icon-lg.png") FileUtils.mv(dir+"/icon-lg.png", dir+"/icon.png") else FileUtils.cp(@opts.template+"/resources/images/default-guide.png", dir+"/icon.png") end end
[ "def", "fix_icon", "(", "dir", ")", "if", "File", ".", "exists?", "(", "dir", "+", "\"/icon.png\"", ")", "# All ok", "elsif", "File", ".", "exists?", "(", "dir", "+", "\"/icon-lg.png\"", ")", "FileUtils", ".", "mv", "(", "dir", "+", "\"/icon-lg.png\"", ",", "dir", "+", "\"/icon.png\"", ")", "else", "FileUtils", ".", "cp", "(", "@opts", ".", "template", "+", "\"/resources/images/default-guide.png\"", ",", "dir", "+", "\"/icon.png\"", ")", "end", "end" ]
Ensures the guide dir contains icon.png. When there isn't looks for icon-lg.png and renames it to icon.png. When neither exists, copies over default icon.
[ "Ensures", "the", "guide", "dir", "contains", "icon", ".", "png", ".", "When", "there", "isn", "t", "looks", "for", "icon", "-", "lg", ".", "png", "and", "renames", "it", "to", "icon", ".", "png", ".", "When", "neither", "exists", "copies", "over", "default", "icon", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guides.rb#L145-L153
train
senchalabs/jsduck
lib/jsduck/aggregator.rb
JsDuck.Aggregator.add_class
def add_class(cls) old_cls = @classes[cls[:name]] if !old_cls && @alt_names[cls[:name]] old_cls = @alt_names[cls[:name]] warn_alt_name(cls) end if old_cls merge_classes(old_cls, cls) @current_class = old_cls else @current_class = cls @classes[cls[:name]] = cls # Register all alternate names of class for lookup too cls[:alternateClassNames].each do |altname| if cls[:name] == altname # A buggy documentation, warn. warn_alt_name(cls) else @alt_names[altname] = cls # When an alternate name has been used as a class name before, # then this is one crappy documentation, but attempt to handle # it by merging the class with alt-name into this class. if @classes[altname] merge_classes(cls, @classes[altname]) @classes.delete(altname) warn_alt_name(cls) end end end insert_orphans(cls) end end
ruby
def add_class(cls) old_cls = @classes[cls[:name]] if !old_cls && @alt_names[cls[:name]] old_cls = @alt_names[cls[:name]] warn_alt_name(cls) end if old_cls merge_classes(old_cls, cls) @current_class = old_cls else @current_class = cls @classes[cls[:name]] = cls # Register all alternate names of class for lookup too cls[:alternateClassNames].each do |altname| if cls[:name] == altname # A buggy documentation, warn. warn_alt_name(cls) else @alt_names[altname] = cls # When an alternate name has been used as a class name before, # then this is one crappy documentation, but attempt to handle # it by merging the class with alt-name into this class. if @classes[altname] merge_classes(cls, @classes[altname]) @classes.delete(altname) warn_alt_name(cls) end end end insert_orphans(cls) end end
[ "def", "add_class", "(", "cls", ")", "old_cls", "=", "@classes", "[", "cls", "[", ":name", "]", "]", "if", "!", "old_cls", "&&", "@alt_names", "[", "cls", "[", ":name", "]", "]", "old_cls", "=", "@alt_names", "[", "cls", "[", ":name", "]", "]", "warn_alt_name", "(", "cls", ")", "end", "if", "old_cls", "merge_classes", "(", "old_cls", ",", "cls", ")", "@current_class", "=", "old_cls", "else", "@current_class", "=", "cls", "@classes", "[", "cls", "[", ":name", "]", "]", "=", "cls", "# Register all alternate names of class for lookup too", "cls", "[", ":alternateClassNames", "]", ".", "each", "do", "|", "altname", "|", "if", "cls", "[", ":name", "]", "==", "altname", "# A buggy documentation, warn.", "warn_alt_name", "(", "cls", ")", "else", "@alt_names", "[", "altname", "]", "=", "cls", "# When an alternate name has been used as a class name before,", "# then this is one crappy documentation, but attempt to handle", "# it by merging the class with alt-name into this class.", "if", "@classes", "[", "altname", "]", "merge_classes", "(", "cls", ",", "@classes", "[", "altname", "]", ")", "@classes", ".", "delete", "(", "altname", ")", "warn_alt_name", "(", "cls", ")", "end", "end", "end", "insert_orphans", "(", "cls", ")", "end", "end" ]
When class exists, merge it with class node. Otherwise add as new class.
[ "When", "class", "exists", "merge", "it", "with", "class", "node", ".", "Otherwise", "add", "as", "new", "class", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/aggregator.rb#L53-L87
train
senchalabs/jsduck
lib/jsduck/aggregator.rb
JsDuck.Aggregator.merge_classes
def merge_classes(old, new) # Merge booleans [:extends, :singleton, :private].each do |tag| old[tag] = old[tag] || new[tag] end # Merge arrays [:mixins, :alternateClassNames, :requires, :uses, :files].each do |tag| old[tag] = (old[tag] || []) + (new[tag] || []) end # Merge hashes of arrays [:aliases].each do |tag| new[tag].each_pair do |key, contents| old[tag][key] = (old[tag][key] || []) + contents end end old[:doc] = old[:doc].length > 0 ? old[:doc] : new[:doc] # Additionally the doc-comment can contain configs and constructor old[:members] += new[:members] end
ruby
def merge_classes(old, new) # Merge booleans [:extends, :singleton, :private].each do |tag| old[tag] = old[tag] || new[tag] end # Merge arrays [:mixins, :alternateClassNames, :requires, :uses, :files].each do |tag| old[tag] = (old[tag] || []) + (new[tag] || []) end # Merge hashes of arrays [:aliases].each do |tag| new[tag].each_pair do |key, contents| old[tag][key] = (old[tag][key] || []) + contents end end old[:doc] = old[:doc].length > 0 ? old[:doc] : new[:doc] # Additionally the doc-comment can contain configs and constructor old[:members] += new[:members] end
[ "def", "merge_classes", "(", "old", ",", "new", ")", "# Merge booleans", "[", ":extends", ",", ":singleton", ",", ":private", "]", ".", "each", "do", "|", "tag", "|", "old", "[", "tag", "]", "=", "old", "[", "tag", "]", "||", "new", "[", "tag", "]", "end", "# Merge arrays", "[", ":mixins", ",", ":alternateClassNames", ",", ":requires", ",", ":uses", ",", ":files", "]", ".", "each", "do", "|", "tag", "|", "old", "[", "tag", "]", "=", "(", "old", "[", "tag", "]", "||", "[", "]", ")", "+", "(", "new", "[", "tag", "]", "||", "[", "]", ")", "end", "# Merge hashes of arrays", "[", ":aliases", "]", ".", "each", "do", "|", "tag", "|", "new", "[", "tag", "]", ".", "each_pair", "do", "|", "key", ",", "contents", "|", "old", "[", "tag", "]", "[", "key", "]", "=", "(", "old", "[", "tag", "]", "[", "key", "]", "||", "[", "]", ")", "+", "contents", "end", "end", "old", "[", ":doc", "]", "=", "old", "[", ":doc", "]", ".", "length", ">", "0", "?", "old", "[", ":doc", "]", ":", "new", "[", ":doc", "]", "# Additionally the doc-comment can contain configs and constructor", "old", "[", ":members", "]", "+=", "new", "[", ":members", "]", "end" ]
Merges new class-doc into old one.
[ "Merges", "new", "class", "-", "doc", "into", "old", "one", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/aggregator.rb#L94-L112
train
senchalabs/jsduck
lib/jsduck/aggregator.rb
JsDuck.Aggregator.add_member
def add_member(node) # Completely ignore member if @ignore used return if node[:ignore] if node[:owner] if @classes[node[:owner]] add_to_class(@classes[node[:owner]], node) else add_orphan(node) end elsif @current_class node[:owner] = @current_class[:name] add_to_class(@current_class, node) else add_orphan(node) end end
ruby
def add_member(node) # Completely ignore member if @ignore used return if node[:ignore] if node[:owner] if @classes[node[:owner]] add_to_class(@classes[node[:owner]], node) else add_orphan(node) end elsif @current_class node[:owner] = @current_class[:name] add_to_class(@current_class, node) else add_orphan(node) end end
[ "def", "add_member", "(", "node", ")", "# Completely ignore member if @ignore used", "return", "if", "node", "[", ":ignore", "]", "if", "node", "[", ":owner", "]", "if", "@classes", "[", "node", "[", ":owner", "]", "]", "add_to_class", "(", "@classes", "[", "node", "[", ":owner", "]", "]", ",", "node", ")", "else", "add_orphan", "(", "node", ")", "end", "elsif", "@current_class", "node", "[", ":owner", "]", "=", "@current_class", "[", ":name", "]", "add_to_class", "(", "@current_class", ",", "node", ")", "else", "add_orphan", "(", "node", ")", "end", "end" ]
Tries to place members into classes where they belong. @member explicitly defines the containing class, but we can meet item with @member=Foo before we actually meet class Foo - in that case we register them as orphans. (Later when we finally meet class Foo, orphans are inserted into it.) Items without @member belong by default to the preceding class. When no class precedes them - they too are orphaned.
[ "Tries", "to", "place", "members", "into", "classes", "where", "they", "belong", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/aggregator.rb#L123-L139
train
senchalabs/jsduck
lib/jsduck/aggregator.rb
JsDuck.Aggregator.insert_orphans
def insert_orphans(cls) members = @orphans.find_all {|node| node[:owner] == cls[:name] } members.each do |node| add_to_class(cls, node) @orphans.delete(node) end end
ruby
def insert_orphans(cls) members = @orphans.find_all {|node| node[:owner] == cls[:name] } members.each do |node| add_to_class(cls, node) @orphans.delete(node) end end
[ "def", "insert_orphans", "(", "cls", ")", "members", "=", "@orphans", ".", "find_all", "{", "|", "node", "|", "node", "[", ":owner", "]", "==", "cls", "[", ":name", "]", "}", "members", ".", "each", "do", "|", "node", "|", "add_to_class", "(", "cls", ",", "node", ")", "@orphans", ".", "delete", "(", "node", ")", "end", "end" ]
Inserts available orphans to class
[ "Inserts", "available", "orphans", "to", "class" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/aggregator.rb#L150-L156
train
senchalabs/jsduck
lib/jsduck/merger.rb
JsDuck.Merger.general_merge
def general_merge(h, docs, code) # Add all items in docs not already in result. docs.each_pair do |key, value| h[key] = value unless h[key] end # Add all items in code not already in result and mark them as # auto-detected. But only if the explicit and auto-detected # names don't conflict. if Merger.can_be_autodetected?(docs, code) code.each_pair do |key, value| unless h[key] h[key] = value mark_autodetected(h, key) end end end end
ruby
def general_merge(h, docs, code) # Add all items in docs not already in result. docs.each_pair do |key, value| h[key] = value unless h[key] end # Add all items in code not already in result and mark them as # auto-detected. But only if the explicit and auto-detected # names don't conflict. if Merger.can_be_autodetected?(docs, code) code.each_pair do |key, value| unless h[key] h[key] = value mark_autodetected(h, key) end end end end
[ "def", "general_merge", "(", "h", ",", "docs", ",", "code", ")", "# Add all items in docs not already in result.", "docs", ".", "each_pair", "do", "|", "key", ",", "value", "|", "h", "[", "key", "]", "=", "value", "unless", "h", "[", "key", "]", "end", "# Add all items in code not already in result and mark them as", "# auto-detected. But only if the explicit and auto-detected", "# names don't conflict.", "if", "Merger", ".", "can_be_autodetected?", "(", "docs", ",", "code", ")", "code", ".", "each_pair", "do", "|", "key", ",", "value", "|", "unless", "h", "[", "key", "]", "h", "[", "key", "]", "=", "value", "mark_autodetected", "(", "h", ",", "key", ")", "end", "end", "end", "end" ]
Applies default merge algorithm to the rest of the data.
[ "Applies", "default", "merge", "algorithm", "to", "the", "rest", "of", "the", "data", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/merger.rb#L49-L66
train
senchalabs/jsduck
lib/jsduck/members_index.rb
JsDuck.MembersIndex.merge!
def merge!(hash1, hash2) hash2.each_pair do |name, m| if m[:hide] if hash1[name] hash1.delete(name) else msg = "@hide used but #{m[:tagname]} #{m[:name]} not found in parent class" Logger.warn(:hide, msg, m[:files][0]) end else if hash1[name] store_overrides(hash1[name], m) end hash1[name] = m end end end
ruby
def merge!(hash1, hash2) hash2.each_pair do |name, m| if m[:hide] if hash1[name] hash1.delete(name) else msg = "@hide used but #{m[:tagname]} #{m[:name]} not found in parent class" Logger.warn(:hide, msg, m[:files][0]) end else if hash1[name] store_overrides(hash1[name], m) end hash1[name] = m end end end
[ "def", "merge!", "(", "hash1", ",", "hash2", ")", "hash2", ".", "each_pair", "do", "|", "name", ",", "m", "|", "if", "m", "[", ":hide", "]", "if", "hash1", "[", "name", "]", "hash1", ".", "delete", "(", "name", ")", "else", "msg", "=", "\"@hide used but #{m[:tagname]} #{m[:name]} not found in parent class\"", "Logger", ".", "warn", "(", ":hide", ",", "msg", ",", "m", "[", ":files", "]", "[", "0", "]", ")", "end", "else", "if", "hash1", "[", "name", "]", "store_overrides", "(", "hash1", "[", "name", "]", ",", "m", ")", "end", "hash1", "[", "name", "]", "=", "m", "end", "end", "end" ]
merges second members hash into first one
[ "merges", "second", "members", "hash", "into", "first", "one" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/members_index.rb#L93-L109
train
senchalabs/jsduck
lib/jsduck/members_index.rb
JsDuck.MembersIndex.store_overrides
def store_overrides(old, new) # Sometimes a class is included multiple times (like Ext.Base) # resulting in its members overriding themselves. Because of # this, ignore overriding itself. if new[:owner] != old[:owner] new[:overrides] = [] unless new[:overrides] unless new[:overrides].any? {|m| m[:owner] == old[:owner] } # Make a copy of the important properties for us. We can't # just push the actual `old` member itself, because there # can be circular overrides (notably with Ext.Base), which # will result in infinite loop when we try to convert our # class into JSON. new[:overrides] << { :name => old[:name], :owner => old[:owner], } end end end
ruby
def store_overrides(old, new) # Sometimes a class is included multiple times (like Ext.Base) # resulting in its members overriding themselves. Because of # this, ignore overriding itself. if new[:owner] != old[:owner] new[:overrides] = [] unless new[:overrides] unless new[:overrides].any? {|m| m[:owner] == old[:owner] } # Make a copy of the important properties for us. We can't # just push the actual `old` member itself, because there # can be circular overrides (notably with Ext.Base), which # will result in infinite loop when we try to convert our # class into JSON. new[:overrides] << { :name => old[:name], :owner => old[:owner], } end end end
[ "def", "store_overrides", "(", "old", ",", "new", ")", "# Sometimes a class is included multiple times (like Ext.Base)", "# resulting in its members overriding themselves. Because of", "# this, ignore overriding itself.", "if", "new", "[", ":owner", "]", "!=", "old", "[", ":owner", "]", "new", "[", ":overrides", "]", "=", "[", "]", "unless", "new", "[", ":overrides", "]", "unless", "new", "[", ":overrides", "]", ".", "any?", "{", "|", "m", "|", "m", "[", ":owner", "]", "==", "old", "[", ":owner", "]", "}", "# Make a copy of the important properties for us. We can't", "# just push the actual `old` member itself, because there", "# can be circular overrides (notably with Ext.Base), which", "# will result in infinite loop when we try to convert our", "# class into JSON.", "new", "[", ":overrides", "]", "<<", "{", ":name", "=>", "old", "[", ":name", "]", ",", ":owner", "=>", "old", "[", ":owner", "]", ",", "}", "end", "end", "end" ]
Invoked when merge! finds two members with the same name. New member always overrides the old, but inside new we keep a list of members it overrides. Normally one member will override one other member, but a member from mixin can override multiple members - although there's not a single such case in ExtJS, we have to handle it. Every overridden member is listed just once.
[ "Invoked", "when", "merge!", "finds", "two", "members", "with", "the", "same", "name", ".", "New", "member", "always", "overrides", "the", "old", "but", "inside", "new", "we", "keep", "a", "list", "of", "members", "it", "overrides", ".", "Normally", "one", "member", "will", "override", "one", "other", "member", "but", "a", "member", "from", "mixin", "can", "override", "multiple", "members", "-", "although", "there", "s", "not", "a", "single", "such", "case", "in", "ExtJS", "we", "have", "to", "handle", "it", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/members_index.rb#L119-L137
train
senchalabs/jsduck
lib/jsduck/news.rb
JsDuck.News.filter_new_members
def filter_new_members(cls) members = cls.all_local_members.find_all do |m| visible?(m) && (m[:new] || new_params?(m)) end members = discard_accessors(members) members.sort! {|a, b| a[:name] <=> b[:name] } end
ruby
def filter_new_members(cls) members = cls.all_local_members.find_all do |m| visible?(m) && (m[:new] || new_params?(m)) end members = discard_accessors(members) members.sort! {|a, b| a[:name] <=> b[:name] } end
[ "def", "filter_new_members", "(", "cls", ")", "members", "=", "cls", ".", "all_local_members", ".", "find_all", "do", "|", "m", "|", "visible?", "(", "m", ")", "&&", "(", "m", "[", ":new", "]", "||", "new_params?", "(", "m", ")", ")", "end", "members", "=", "discard_accessors", "(", "members", ")", "members", ".", "sort!", "{", "|", "a", ",", "b", "|", "a", "[", ":name", "]", "<=>", "b", "[", ":name", "]", "}", "end" ]
Returns all members of a class that have been marked as new, or have parameters marked as new.
[ "Returns", "all", "members", "of", "a", "class", "that", "have", "been", "marked", "as", "new", "or", "have", "parameters", "marked", "as", "new", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/news.rb#L68-L74
train
senchalabs/jsduck
lib/jsduck/guide_toc.rb
JsDuck.GuideToc.inject!
def inject! @html.each_line do |line| if line =~ /^\s*<h([1-6])>(.*?)<\/h[1-6]>$/ level = $1.to_i original_text = $2 text = Util::HTML.strip_tags(original_text) id = title_to_id(text) if include_to_toc?(level) @toc.add(level, id, text) end @new_html << "<h#{level} id='#{id}'>#{original_text}</h#{level}>\n" else @new_html << line end end inject_toc! @new_html.flatten.join end
ruby
def inject! @html.each_line do |line| if line =~ /^\s*<h([1-6])>(.*?)<\/h[1-6]>$/ level = $1.to_i original_text = $2 text = Util::HTML.strip_tags(original_text) id = title_to_id(text) if include_to_toc?(level) @toc.add(level, id, text) end @new_html << "<h#{level} id='#{id}'>#{original_text}</h#{level}>\n" else @new_html << line end end inject_toc! @new_html.flatten.join end
[ "def", "inject!", "@html", ".", "each_line", "do", "|", "line", "|", "if", "line", "=~", "/", "\\s", "\\/", "/", "level", "=", "$1", ".", "to_i", "original_text", "=", "$2", "text", "=", "Util", "::", "HTML", ".", "strip_tags", "(", "original_text", ")", "id", "=", "title_to_id", "(", "text", ")", "if", "include_to_toc?", "(", "level", ")", "@toc", ".", "add", "(", "level", ",", "id", ",", "text", ")", "end", "@new_html", "<<", "\"<h#{level} id='#{id}'>#{original_text}</h#{level}>\\n\"", "else", "@new_html", "<<", "line", "end", "end", "inject_toc!", "@new_html", ".", "flatten", ".", "join", "end" ]
Inserts table of contents at the top of guide HTML by looking for headings at or below the specified maximum level.
[ "Inserts", "table", "of", "contents", "at", "the", "top", "of", "guide", "HTML", "by", "looking", "for", "headings", "at", "or", "below", "the", "specified", "maximum", "level", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guide_toc.rb#L21-L42
train
senchalabs/jsduck
lib/jsduck/class.rb
JsDuck.Class.internal_doc=
def internal_doc=(doc) @doc.merge!(doc) do |key, oldval, newval| if key == :members oldval.zip(newval) do |ms| ms[0].merge!(ms[1]) end oldval else newval end end end
ruby
def internal_doc=(doc) @doc.merge!(doc) do |key, oldval, newval| if key == :members oldval.zip(newval) do |ms| ms[0].merge!(ms[1]) end oldval else newval end end end
[ "def", "internal_doc", "=", "(", "doc", ")", "@doc", ".", "merge!", "(", "doc", ")", "do", "|", "key", ",", "oldval", ",", "newval", "|", "if", "key", "==", ":members", "oldval", ".", "zip", "(", "newval", ")", "do", "|", "ms", "|", "ms", "[", "0", "]", ".", "merge!", "(", "ms", "[", "1", "]", ")", "end", "oldval", "else", "newval", "end", "end", "end" ]
Sets the internal doc object. The doc object is processed in parallel and then assigned back through this method. But because of parallel processing the assigned doc object will not be just a modified old @doc but a completely new. If we were to just assign to @doc the #find_members caches would still point to old @doc members resulting in mysterious errors further along...
[ "Sets", "the", "internal", "doc", "object", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class.rb#L46-L57
train
senchalabs/jsduck
lib/jsduck/class.rb
JsDuck.Class.lookup
def lookup(classname) if @relations[classname] @relations[classname] elsif @relations.ignore?(classname) || classname =~ /\*/ # Ignore explicitly ignored classes and classnames with # wildcards in them. We could expand the wildcard, but that # can result in a very long list of classes, like when # somebody requires 'Ext.form.*', so for now we do the # simplest thing and ignore it. Class.new({:name => classname}, false) else Logger.warn(:extend, "Class #{classname} not found", @doc[:files][0]) # Create placeholder class Class.new({:name => classname}, false) end end
ruby
def lookup(classname) if @relations[classname] @relations[classname] elsif @relations.ignore?(classname) || classname =~ /\*/ # Ignore explicitly ignored classes and classnames with # wildcards in them. We could expand the wildcard, but that # can result in a very long list of classes, like when # somebody requires 'Ext.form.*', so for now we do the # simplest thing and ignore it. Class.new({:name => classname}, false) else Logger.warn(:extend, "Class #{classname} not found", @doc[:files][0]) # Create placeholder class Class.new({:name => classname}, false) end end
[ "def", "lookup", "(", "classname", ")", "if", "@relations", "[", "classname", "]", "@relations", "[", "classname", "]", "elsif", "@relations", ".", "ignore?", "(", "classname", ")", "||", "classname", "=~", "/", "\\*", "/", "# Ignore explicitly ignored classes and classnames with", "# wildcards in them. We could expand the wildcard, but that", "# can result in a very long list of classes, like when", "# somebody requires 'Ext.form.*', so for now we do the", "# simplest thing and ignore it.", "Class", ".", "new", "(", "{", ":name", "=>", "classname", "}", ",", "false", ")", "else", "Logger", ".", "warn", "(", ":extend", ",", "\"Class #{classname} not found\"", ",", "@doc", "[", ":files", "]", "[", "0", "]", ")", "# Create placeholder class", "Class", ".", "new", "(", "{", ":name", "=>", "classname", "}", ",", "false", ")", "end", "end" ]
Looks up class object by name When not found, prints warning message.
[ "Looks", "up", "class", "object", "by", "name", "When", "not", "found", "prints", "warning", "message", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class.rb#L107-L122
train
senchalabs/jsduck
lib/jsduck/class.rb
JsDuck.Class.find_members
def find_members(query={}) if query[:name] ms = @members_index.global_by_name[query[:name]] || [] ms = ms.find_all {|m| m[:owner] == @doc[:name]} if query[:local] elsif query[:local] ms = @members_index.all_local else ms = @members_index.all_global end if query[:tagname] ms = ms.find_all {|m| m[:tagname] == query[:tagname] } end if query[:static] == true ms = ms.find_all {|m| m[:static] } elsif query[:static] == false ms = ms.reject {|m| m[:static] } end ms end
ruby
def find_members(query={}) if query[:name] ms = @members_index.global_by_name[query[:name]] || [] ms = ms.find_all {|m| m[:owner] == @doc[:name]} if query[:local] elsif query[:local] ms = @members_index.all_local else ms = @members_index.all_global end if query[:tagname] ms = ms.find_all {|m| m[:tagname] == query[:tagname] } end if query[:static] == true ms = ms.find_all {|m| m[:static] } elsif query[:static] == false ms = ms.reject {|m| m[:static] } end ms end
[ "def", "find_members", "(", "query", "=", "{", "}", ")", "if", "query", "[", ":name", "]", "ms", "=", "@members_index", ".", "global_by_name", "[", "query", "[", ":name", "]", "]", "||", "[", "]", "ms", "=", "ms", ".", "find_all", "{", "|", "m", "|", "m", "[", ":owner", "]", "==", "@doc", "[", ":name", "]", "}", "if", "query", "[", ":local", "]", "elsif", "query", "[", ":local", "]", "ms", "=", "@members_index", ".", "all_local", "else", "ms", "=", "@members_index", ".", "all_global", "end", "if", "query", "[", ":tagname", "]", "ms", "=", "ms", ".", "find_all", "{", "|", "m", "|", "m", "[", ":tagname", "]", "==", "query", "[", ":tagname", "]", "}", "end", "if", "query", "[", ":static", "]", "==", "true", "ms", "=", "ms", ".", "find_all", "{", "|", "m", "|", "m", "[", ":static", "]", "}", "elsif", "query", "[", ":static", "]", "==", "false", "ms", "=", "ms", ".", "reject", "{", "|", "m", "|", "m", "[", ":static", "]", "}", "end", "ms", "end" ]
Returns list of members filtered by a query. Searches both local and inherited members. The query hash can contain the following fields: - :name : String - the name of the member to find. - :tagname : Symbol - the member type to look for. - :static : Boolean - true to only return static members, false to only return instance members. When nil or unspecified, both static and instance members are returned. - :local : Boolean - true to only return non-inherited members. When called without arguments all members are returned. When nothing found, an empty array is returned.
[ "Returns", "list", "of", "members", "filtered", "by", "a", "query", ".", "Searches", "both", "local", "and", "inherited", "members", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class.rb#L149-L170
train
senchalabs/jsduck
lib/jsduck/tag/member_tag.rb
JsDuck::Tag.MemberTag.process_code
def process_code(code) return { :tagname => code[:tagname], # An auto-detected name might be "MyClass.prototype.myMethod" - # for member name we only want the last "myMethod" part. :name => code[:name] ? code[:name].split(/\./).last : nil, :autodetected => code[:autodetected], :inheritdoc => code[:inheritdoc], :static => code[:static], :private => code[:private], :inheritable => code[:inheritable], :linenr => code[:linenr], } end
ruby
def process_code(code) return { :tagname => code[:tagname], # An auto-detected name might be "MyClass.prototype.myMethod" - # for member name we only want the last "myMethod" part. :name => code[:name] ? code[:name].split(/\./).last : nil, :autodetected => code[:autodetected], :inheritdoc => code[:inheritdoc], :static => code[:static], :private => code[:private], :inheritable => code[:inheritable], :linenr => code[:linenr], } end
[ "def", "process_code", "(", "code", ")", "return", "{", ":tagname", "=>", "code", "[", ":tagname", "]", ",", "# An auto-detected name might be \"MyClass.prototype.myMethod\" -", "# for member name we only want the last \"myMethod\" part.", ":name", "=>", "code", "[", ":name", "]", "?", "code", "[", ":name", "]", ".", "split", "(", "/", "\\.", "/", ")", ".", "last", ":", "nil", ",", ":autodetected", "=>", "code", "[", ":autodetected", "]", ",", ":inheritdoc", "=>", "code", "[", ":inheritdoc", "]", ",", ":static", "=>", "code", "[", ":static", "]", ",", ":private", "=>", "code", "[", ":private", "]", ",", ":inheritable", "=>", "code", "[", ":inheritable", "]", ",", ":linenr", "=>", "code", "[", ":linenr", "]", ",", "}", "end" ]
Extracts the fields auto-detected from code that are relevant to the member type and returns a hash with them. The implementation here extracts fields applicable to all member types. When additional member-specific fields are to be extracted, override this method, but be sure to call the superclass method too. For example inside Method tag we might additionally want to extract :type and :default: def process_code(code) h = super(code) h[:type] = code[:type] h[:default] = code[:default] h end
[ "Extracts", "the", "fields", "auto", "-", "detected", "from", "code", "that", "are", "relevant", "to", "the", "member", "type", "and", "returns", "a", "hash", "with", "them", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag/member_tag.rb#L81-L95
train
senchalabs/jsduck
lib/jsduck/grouped_asset.rb
JsDuck.GroupedAsset.each_item
def each_item(group=nil, &block) group = group || @groups group.each do |item| if item["items"] each_item(item["items"], &block) else block.call(item) end end end
ruby
def each_item(group=nil, &block) group = group || @groups group.each do |item| if item["items"] each_item(item["items"], &block) else block.call(item) end end end
[ "def", "each_item", "(", "group", "=", "nil", ",", "&", "block", ")", "group", "=", "group", "||", "@groups", "group", ".", "each", "do", "|", "item", "|", "if", "item", "[", "\"items\"", "]", "each_item", "(", "item", "[", "\"items\"", "]", ",", "block", ")", "else", "block", ".", "call", "(", "item", ")", "end", "end", "end" ]
Iterates over all items in all groups
[ "Iterates", "over", "all", "items", "in", "all", "groups" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/grouped_asset.rb#L26-L36
train
senchalabs/jsduck
lib/jsduck/batch_processor.rb
JsDuck.BatchProcessor.aggregate
def aggregate(parsed_files) agr = Aggregator.new parsed_files.each do |file| Logger.log("Aggregating", file.filename) agr.aggregate(file) end agr.result end
ruby
def aggregate(parsed_files) agr = Aggregator.new parsed_files.each do |file| Logger.log("Aggregating", file.filename) agr.aggregate(file) end agr.result end
[ "def", "aggregate", "(", "parsed_files", ")", "agr", "=", "Aggregator", ".", "new", "parsed_files", ".", "each", "do", "|", "file", "|", "Logger", ".", "log", "(", "\"Aggregating\"", ",", "file", ".", "filename", ")", "agr", ".", "aggregate", "(", "file", ")", "end", "agr", ".", "result", "end" ]
Aggregates parsing results sequencially
[ "Aggregates", "parsing", "results", "sequencially" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/batch_processor.rb#L39-L46
train
senchalabs/jsduck
lib/jsduck/batch_processor.rb
JsDuck.BatchProcessor.pre_process
def pre_process(classes_hash, opts) Process::IgnoredClasses.new(classes_hash).process_all! Process::GlobalMembers.new(classes_hash, opts).process_all! Process::Accessors.new(classes_hash).process_all! Process::Ext4Events.new(classes_hash, opts).process_all! Process::Enums.new(classes_hash).process_all! Process::Overrides.new(classes_hash, opts).process_all! classes_hash.values end
ruby
def pre_process(classes_hash, opts) Process::IgnoredClasses.new(classes_hash).process_all! Process::GlobalMembers.new(classes_hash, opts).process_all! Process::Accessors.new(classes_hash).process_all! Process::Ext4Events.new(classes_hash, opts).process_all! Process::Enums.new(classes_hash).process_all! Process::Overrides.new(classes_hash, opts).process_all! classes_hash.values end
[ "def", "pre_process", "(", "classes_hash", ",", "opts", ")", "Process", "::", "IgnoredClasses", ".", "new", "(", "classes_hash", ")", ".", "process_all!", "Process", "::", "GlobalMembers", ".", "new", "(", "classes_hash", ",", "opts", ")", ".", "process_all!", "Process", "::", "Accessors", ".", "new", "(", "classes_hash", ")", ".", "process_all!", "Process", "::", "Ext4Events", ".", "new", "(", "classes_hash", ",", "opts", ")", ".", "process_all!", "Process", "::", "Enums", ".", "new", "(", "classes_hash", ")", ".", "process_all!", "Process", "::", "Overrides", ".", "new", "(", "classes_hash", ",", "opts", ")", ".", "process_all!", "classes_hash", ".", "values", "end" ]
Do all kinds of processing on the classes hash before turning it into Relations object.
[ "Do", "all", "kinds", "of", "processing", "on", "the", "classes", "hash", "before", "turning", "it", "into", "Relations", "object", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/batch_processor.rb#L50-L59
train
senchalabs/jsduck
lib/jsduck/batch_processor.rb
JsDuck.BatchProcessor.to_class_objects
def to_class_objects(docs, opts) classes = docs.map {|d| Class.new(d) } Relations.new(classes, opts.external) end
ruby
def to_class_objects(docs, opts) classes = docs.map {|d| Class.new(d) } Relations.new(classes, opts.external) end
[ "def", "to_class_objects", "(", "docs", ",", "opts", ")", "classes", "=", "docs", ".", "map", "{", "|", "d", "|", "Class", ".", "new", "(", "d", ")", "}", "Relations", ".", "new", "(", "classes", ",", "opts", ".", "external", ")", "end" ]
Turns all aggregated data into Class objects and places the classes inside Relations container.
[ "Turns", "all", "aggregated", "data", "into", "Class", "objects", "and", "places", "the", "classes", "inside", "Relations", "container", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/batch_processor.rb#L63-L66
train
senchalabs/jsduck
lib/jsduck/batch_processor.rb
JsDuck.BatchProcessor.post_process
def post_process(relations, opts) Process::CircularDeps.new(relations).process_all! Process::InheritDoc.new(relations).process_all! Process::Versions.new(relations, opts).process_all! Process::ReturnValues.new(relations).process_all! Process::Fires.new(relations).process_all! Process::Components.new(relations).process_all! Process::Lint.new(relations).process_all! Process::NoDoc.new(relations).process_all! relations end
ruby
def post_process(relations, opts) Process::CircularDeps.new(relations).process_all! Process::InheritDoc.new(relations).process_all! Process::Versions.new(relations, opts).process_all! Process::ReturnValues.new(relations).process_all! Process::Fires.new(relations).process_all! Process::Components.new(relations).process_all! Process::Lint.new(relations).process_all! Process::NoDoc.new(relations).process_all! relations end
[ "def", "post_process", "(", "relations", ",", "opts", ")", "Process", "::", "CircularDeps", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "InheritDoc", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "Versions", ".", "new", "(", "relations", ",", "opts", ")", ".", "process_all!", "Process", "::", "ReturnValues", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "Fires", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "Components", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "Lint", ".", "new", "(", "relations", ")", ".", "process_all!", "Process", "::", "NoDoc", ".", "new", "(", "relations", ")", ".", "process_all!", "relations", "end" ]
Do all kinds of post-processing on Relations object.
[ "Do", "all", "kinds", "of", "post", "-", "processing", "on", "Relations", "object", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/batch_processor.rb#L69-L79
train
senchalabs/jsduck
lib/jsduck/columns.rb
JsDuck.Columns.split
def split(items, n) if n == 1 [items] elsif items.length <= n Array.new(n) {|i| items[i] ? [items[i]] : [] } else min_max = nil min_arr = nil i = 0 while i <= items.length-n i += 1 # Try placing 1, 2, 3, ... items to first chunk. # Calculate the remaining chunks recursively. cols = [items[0,i]] + split(items[i, items.length], n-1) max = max_sum(cols) # Is this the optimal solution so far? Remember it. if !min_max || max < min_max min_max = max min_arr = cols end end min_arr end end
ruby
def split(items, n) if n == 1 [items] elsif items.length <= n Array.new(n) {|i| items[i] ? [items[i]] : [] } else min_max = nil min_arr = nil i = 0 while i <= items.length-n i += 1 # Try placing 1, 2, 3, ... items to first chunk. # Calculate the remaining chunks recursively. cols = [items[0,i]] + split(items[i, items.length], n-1) max = max_sum(cols) # Is this the optimal solution so far? Remember it. if !min_max || max < min_max min_max = max min_arr = cols end end min_arr end end
[ "def", "split", "(", "items", ",", "n", ")", "if", "n", "==", "1", "[", "items", "]", "elsif", "items", ".", "length", "<=", "n", "Array", ".", "new", "(", "n", ")", "{", "|", "i", "|", "items", "[", "i", "]", "?", "[", "items", "[", "i", "]", "]", ":", "[", "]", "}", "else", "min_max", "=", "nil", "min_arr", "=", "nil", "i", "=", "0", "while", "i", "<=", "items", ".", "length", "-", "n", "i", "+=", "1", "# Try placing 1, 2, 3, ... items to first chunk.", "# Calculate the remaining chunks recursively.", "cols", "=", "[", "items", "[", "0", ",", "i", "]", "]", "+", "split", "(", "items", "[", "i", ",", "items", ".", "length", "]", ",", "n", "-", "1", ")", "max", "=", "max_sum", "(", "cols", ")", "# Is this the optimal solution so far? Remember it.", "if", "!", "min_max", "||", "max", "<", "min_max", "min_max", "=", "max", "min_arr", "=", "cols", "end", "end", "min_arr", "end", "end" ]
Initialized with the name of subitems field. Splits the array of items into n chunks so that the sum of largest chunk is as small as possible. This is a brute-force implementation - we just try all the combinations and choose the best one.
[ "Initialized", "with", "the", "name", "of", "subitems", "field", ".", "Splits", "the", "array", "of", "items", "into", "n", "chunks", "so", "that", "the", "sum", "of", "largest", "chunk", "is", "as", "small", "as", "possible", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/columns.rb#L16-L39
train
senchalabs/jsduck
lib/jsduck/guide_toc_entry.rb
JsDuck.GuideTocEntry.add
def add(level, id, text) if level == @min_level @items << GuideTocEntry.new(self) @items.last.label = "#{prefix} <a href='#!/guide/#{id}'>#{text}</a>\n" else if @items.empty? @items << GuideTocEntry.new(self) end @items.last.add(level-1, id, text) end end
ruby
def add(level, id, text) if level == @min_level @items << GuideTocEntry.new(self) @items.last.label = "#{prefix} <a href='#!/guide/#{id}'>#{text}</a>\n" else if @items.empty? @items << GuideTocEntry.new(self) end @items.last.add(level-1, id, text) end end
[ "def", "add", "(", "level", ",", "id", ",", "text", ")", "if", "level", "==", "@min_level", "@items", "<<", "GuideTocEntry", ".", "new", "(", "self", ")", "@items", ".", "last", ".", "label", "=", "\"#{prefix} <a href='#!/guide/#{id}'>#{text}</a>\\n\"", "else", "if", "@items", ".", "empty?", "@items", "<<", "GuideTocEntry", ".", "new", "(", "self", ")", "end", "@items", ".", "last", ".", "add", "(", "level", "-", "1", ",", "id", ",", "text", ")", "end", "end" ]
Adds entry at the corresponding heading level.
[ "Adds", "entry", "at", "the", "corresponding", "heading", "level", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/guide_toc_entry.rb#L17-L27
train
senchalabs/jsduck
lib/jsduck/external_classes.rb
JsDuck.ExternalClasses.add
def add(name) if name =~ /\*/ @patterns << make_pattern(name) elsif name =~ /^@browser$/i WEB_APIS.each do |cls| @class_names[cls] = true end else @class_names[name] = true end end
ruby
def add(name) if name =~ /\*/ @patterns << make_pattern(name) elsif name =~ /^@browser$/i WEB_APIS.each do |cls| @class_names[cls] = true end else @class_names[name] = true end end
[ "def", "add", "(", "name", ")", "if", "name", "=~", "/", "\\*", "/", "@patterns", "<<", "make_pattern", "(", "name", ")", "elsif", "name", "=~", "/", "/i", "WEB_APIS", ".", "each", "do", "|", "cls", "|", "@class_names", "[", "cls", "]", "=", "true", "end", "else", "@class_names", "[", "name", "]", "=", "true", "end", "end" ]
Adds a classname or pattern to list of external classes.
[ "Adds", "a", "classname", "or", "pattern", "to", "list", "of", "external", "classes", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/external_classes.rb#L18-L28
train
senchalabs/jsduck
lib/jsduck/logger.rb
JsDuck.Logger.configure_defaults
def configure_defaults # Enable all warnings except some. set_warning(:all, true) set_warning(:link_auto, false) set_warning(:param_count, false) set_warning(:fires, false) set_warning(:nodoc, false) end
ruby
def configure_defaults # Enable all warnings except some. set_warning(:all, true) set_warning(:link_auto, false) set_warning(:param_count, false) set_warning(:fires, false) set_warning(:nodoc, false) end
[ "def", "configure_defaults", "# Enable all warnings except some.", "set_warning", "(", ":all", ",", "true", ")", "set_warning", "(", ":link_auto", ",", "false", ")", "set_warning", "(", ":param_count", ",", "false", ")", "set_warning", "(", ":fires", ",", "false", ")", "set_warning", "(", ":nodoc", ",", "false", ")", "end" ]
Configures warnings to default settings. NB! Needs to be called before retrieving the documentation with #doc_warnings (otherwise the +/- signs will be wrong).
[ "Configures", "warnings", "to", "default", "settings", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/logger.rb#L32-L39
train
senchalabs/jsduck
lib/jsduck/logger.rb
JsDuck.Logger.configure
def configure(opts) self.verbose = true if opts.verbose self.colors = opts.color unless opts.color.nil? begin opts.warnings.each do |w| set_warning(w[:type], w[:enabled], w[:path], w[:params]) end rescue Warning::WarnException => e warn(nil, e.message) end end
ruby
def configure(opts) self.verbose = true if opts.verbose self.colors = opts.color unless opts.color.nil? begin opts.warnings.each do |w| set_warning(w[:type], w[:enabled], w[:path], w[:params]) end rescue Warning::WarnException => e warn(nil, e.message) end end
[ "def", "configure", "(", "opts", ")", "self", ".", "verbose", "=", "true", "if", "opts", ".", "verbose", "self", ".", "colors", "=", "opts", ".", "color", "unless", "opts", ".", "color", ".", "nil?", "begin", "opts", ".", "warnings", ".", "each", "do", "|", "w", "|", "set_warning", "(", "w", "[", ":type", "]", ",", "w", "[", ":enabled", "]", ",", "w", "[", ":path", "]", ",", "w", "[", ":params", "]", ")", "end", "rescue", "Warning", "::", "WarnException", "=>", "e", "warn", "(", "nil", ",", "e", ".", "message", ")", "end", "end" ]
Configures the logger with command line options.
[ "Configures", "the", "logger", "with", "command", "line", "options", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/logger.rb#L42-L54
train
senchalabs/jsduck
lib/jsduck/logger.rb
JsDuck.Logger.warn
def warn(type, msg, file={}, args=[]) if warning_enabled?(type, file[:filename], args) print_warning(msg, file[:filename], file[:linenr]) end return false end
ruby
def warn(type, msg, file={}, args=[]) if warning_enabled?(type, file[:filename], args) print_warning(msg, file[:filename], file[:linenr]) end return false end
[ "def", "warn", "(", "type", ",", "msg", ",", "file", "=", "{", "}", ",", "args", "=", "[", "]", ")", "if", "warning_enabled?", "(", "type", ",", "file", "[", ":filename", "]", ",", "args", ")", "print_warning", "(", "msg", ",", "file", "[", ":filename", "]", ",", "file", "[", ":linenr", "]", ")", "end", "return", "false", "end" ]
Prints warning message. The type must be one of predefined warning types which can be toggled on/off with command-line options, or it can be nil, in which case the warning is always shown. Ignores duplicate warnings - only prints the first one. Works best when --processes=0, but it reduces the amount of warnings greatly also when run multiple processes. The `file` parameter must be a hash like: {:filename => "foo.js", :linenr => 17} When supplied, it the filename and line number will be appended to the message, to convey where the warning was triggered. The optional `args` parameter must be an array of arguments and only applies to some warning types like :nodoc.
[ "Prints", "warning", "message", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/logger.rb#L99-L105
train
senchalabs/jsduck
lib/jsduck/logger.rb
JsDuck.Logger.format
def format(filename=nil, line=nil) out = "" if filename out = Util::OS.windows? ? filename.gsub('/', '\\') : filename if line out += ":#{line}:" end end paint(:magenta, out) end
ruby
def format(filename=nil, line=nil) out = "" if filename out = Util::OS.windows? ? filename.gsub('/', '\\') : filename if line out += ":#{line}:" end end paint(:magenta, out) end
[ "def", "format", "(", "filename", "=", "nil", ",", "line", "=", "nil", ")", "out", "=", "\"\"", "if", "filename", "out", "=", "Util", "::", "OS", ".", "windows?", "?", "filename", ".", "gsub", "(", "'/'", ",", "'\\\\'", ")", ":", "filename", "if", "line", "out", "+=", "\":#{line}:\"", "end", "end", "paint", "(", ":magenta", ",", "out", ")", "end" ]
Formats filename and line number for output
[ "Formats", "filename", "and", "line", "number", "for", "output" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/logger.rb#L162-L171
train
senchalabs/jsduck
lib/jsduck/logger.rb
JsDuck.Logger.paint
def paint(color_name, msg) if @colors == false || @colors == nil && (Util::OS.windows? || !$stderr.tty?) msg else COLORS[color_name] + msg + CLEAR end end
ruby
def paint(color_name, msg) if @colors == false || @colors == nil && (Util::OS.windows? || !$stderr.tty?) msg else COLORS[color_name] + msg + CLEAR end end
[ "def", "paint", "(", "color_name", ",", "msg", ")", "if", "@colors", "==", "false", "||", "@colors", "==", "nil", "&&", "(", "Util", "::", "OS", ".", "windows?", "||", "!", "$stderr", ".", "tty?", ")", "msg", "else", "COLORS", "[", "color_name", "]", "+", "msg", "+", "CLEAR", "end", "end" ]
Helper for doing colored output in UNIX terminal Only does color output when STDERR is attached to TTY i.e. is not piped/redirected.
[ "Helper", "for", "doing", "colored", "output", "in", "UNIX", "terminal" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/logger.rb#L177-L183
train
senchalabs/jsduck
lib/jsduck/inline_examples.rb
JsDuck.InlineExamples.add_classes
def add_classes(relations) relations.each do |cls| extract(cls[:doc]).each_with_index do |ex, i| @examples << { :id => cls[:name] + "-" + i.to_s, :name => cls[:name] + " example #" + (i+1).to_s, :href => '#!/api/' + cls[:name], :code => ex[:code], :options => ex[:options], } end end self end
ruby
def add_classes(relations) relations.each do |cls| extract(cls[:doc]).each_with_index do |ex, i| @examples << { :id => cls[:name] + "-" + i.to_s, :name => cls[:name] + " example #" + (i+1).to_s, :href => '#!/api/' + cls[:name], :code => ex[:code], :options => ex[:options], } end end self end
[ "def", "add_classes", "(", "relations", ")", "relations", ".", "each", "do", "|", "cls", "|", "extract", "(", "cls", "[", ":doc", "]", ")", ".", "each_with_index", "do", "|", "ex", ",", "i", "|", "@examples", "<<", "{", ":id", "=>", "cls", "[", ":name", "]", "+", "\"-\"", "+", "i", ".", "to_s", ",", ":name", "=>", "cls", "[", ":name", "]", "+", "\" example #\"", "+", "(", "i", "+", "1", ")", ".", "to_s", ",", ":href", "=>", "'#!/api/'", "+", "cls", "[", ":name", "]", ",", ":code", "=>", "ex", "[", ":code", "]", ",", ":options", "=>", "ex", "[", ":options", "]", ",", "}", "end", "end", "self", "end" ]
Extracts inline examples from classes
[ "Extracts", "inline", "examples", "from", "classes" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/inline_examples.rb#L15-L29
train
senchalabs/jsduck
lib/jsduck/inline_examples.rb
JsDuck.InlineExamples.add_guides
def add_guides(guides) guides.each_item do |guide| extract(guide[:html]).each_with_index do |ex, i| @examples << { :id => guide["name"] + "-" + i.to_s, :name => guide["title"] + " example #" + (i+1).to_s, :href => '#!/guide/' + guide["name"], :code => ex[:code], :options => ex[:options], } end end self end
ruby
def add_guides(guides) guides.each_item do |guide| extract(guide[:html]).each_with_index do |ex, i| @examples << { :id => guide["name"] + "-" + i.to_s, :name => guide["title"] + " example #" + (i+1).to_s, :href => '#!/guide/' + guide["name"], :code => ex[:code], :options => ex[:options], } end end self end
[ "def", "add_guides", "(", "guides", ")", "guides", ".", "each_item", "do", "|", "guide", "|", "extract", "(", "guide", "[", ":html", "]", ")", ".", "each_with_index", "do", "|", "ex", ",", "i", "|", "@examples", "<<", "{", ":id", "=>", "guide", "[", "\"name\"", "]", "+", "\"-\"", "+", "i", ".", "to_s", ",", ":name", "=>", "guide", "[", "\"title\"", "]", "+", "\" example #\"", "+", "(", "i", "+", "1", ")", ".", "to_s", ",", ":href", "=>", "'#!/guide/'", "+", "guide", "[", "\"name\"", "]", ",", ":code", "=>", "ex", "[", ":code", "]", ",", ":options", "=>", "ex", "[", ":options", "]", ",", "}", "end", "end", "self", "end" ]
Extracts inline examples from guides
[ "Extracts", "inline", "examples", "from", "guides" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/inline_examples.rb#L32-L46
train
senchalabs/jsduck
lib/jsduck/inline_examples.rb
JsDuck.InlineExamples.extract
def extract(html) examples = [] s = StringScanner.new(html) while !s.eos? do if s.check(/</) if s.check(@begin_example_re) s.scan(@begin_example_re) =~ @begin_example_re options = build_options_hash($1) ex = s.scan_until(@end_example_re).sub(@end_example_re, '') examples << { :code => Util::HTML.unescape(Util::HTML.strip_tags(ex)), :options => options, } else s.skip(/</) end else s.skip(/[^<]+/) end end examples end
ruby
def extract(html) examples = [] s = StringScanner.new(html) while !s.eos? do if s.check(/</) if s.check(@begin_example_re) s.scan(@begin_example_re) =~ @begin_example_re options = build_options_hash($1) ex = s.scan_until(@end_example_re).sub(@end_example_re, '') examples << { :code => Util::HTML.unescape(Util::HTML.strip_tags(ex)), :options => options, } else s.skip(/</) end else s.skip(/[^<]+/) end end examples end
[ "def", "extract", "(", "html", ")", "examples", "=", "[", "]", "s", "=", "StringScanner", ".", "new", "(", "html", ")", "while", "!", "s", ".", "eos?", "do", "if", "s", ".", "check", "(", "/", "/", ")", "if", "s", ".", "check", "(", "@begin_example_re", ")", "s", ".", "scan", "(", "@begin_example_re", ")", "=~", "@begin_example_re", "options", "=", "build_options_hash", "(", "$1", ")", "ex", "=", "s", ".", "scan_until", "(", "@end_example_re", ")", ".", "sub", "(", "@end_example_re", ",", "''", ")", "examples", "<<", "{", ":code", "=>", "Util", "::", "HTML", ".", "unescape", "(", "Util", "::", "HTML", ".", "strip_tags", "(", "ex", ")", ")", ",", ":options", "=>", "options", ",", "}", "else", "s", ".", "skip", "(", "/", "/", ")", "end", "else", "s", ".", "skip", "(", "/", "/", ")", "end", "end", "examples", "end" ]
Extracts inline examples from HTML
[ "Extracts", "inline", "examples", "from", "HTML" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/inline_examples.rb#L54-L80
train
senchalabs/jsduck
lib/jsduck/class_doc_expander.rb
JsDuck.ClassDocExpander.expand_comment
def expand_comment(docset) groups = { :class => [], :cfg => [], :constructor => [], } # By default everything goes to :class group group_name = :class docset[:comment].each do |tag| tagname = tag[:tagname] if tagname == :cfg || tagname == :constructor group_name = tagname if tagname == :cfg && (tag[:name] !~ /\./ || groups[:cfg].length == 0) groups[:cfg] << [] end end if tagname == :aliases # For backwards compatibility allow @xtype after @constructor groups[:class] << tag elsif group_name == :cfg groups[:cfg].last << tag else groups[group_name] << tag end end groups_to_docsets(groups, docset) end
ruby
def expand_comment(docset) groups = { :class => [], :cfg => [], :constructor => [], } # By default everything goes to :class group group_name = :class docset[:comment].each do |tag| tagname = tag[:tagname] if tagname == :cfg || tagname == :constructor group_name = tagname if tagname == :cfg && (tag[:name] !~ /\./ || groups[:cfg].length == 0) groups[:cfg] << [] end end if tagname == :aliases # For backwards compatibility allow @xtype after @constructor groups[:class] << tag elsif group_name == :cfg groups[:cfg].last << tag else groups[group_name] << tag end end groups_to_docsets(groups, docset) end
[ "def", "expand_comment", "(", "docset", ")", "groups", "=", "{", ":class", "=>", "[", "]", ",", ":cfg", "=>", "[", "]", ",", ":constructor", "=>", "[", "]", ",", "}", "# By default everything goes to :class group", "group_name", "=", ":class", "docset", "[", ":comment", "]", ".", "each", "do", "|", "tag", "|", "tagname", "=", "tag", "[", ":tagname", "]", "if", "tagname", "==", ":cfg", "||", "tagname", "==", ":constructor", "group_name", "=", "tagname", "if", "tagname", "==", ":cfg", "&&", "(", "tag", "[", ":name", "]", "!~", "/", "\\.", "/", "||", "groups", "[", ":cfg", "]", ".", "length", "==", "0", ")", "groups", "[", ":cfg", "]", "<<", "[", "]", "end", "end", "if", "tagname", "==", ":aliases", "# For backwards compatibility allow @xtype after @constructor", "groups", "[", ":class", "]", "<<", "tag", "elsif", "group_name", "==", ":cfg", "groups", "[", ":cfg", "]", ".", "last", "<<", "tag", "else", "groups", "[", "group_name", "]", "<<", "tag", "end", "end", "groups_to_docsets", "(", "groups", ",", "docset", ")", "end" ]
Handles old syntax where configs and constructor are part of class doc-comment. Gathers all tags until first @cfg or @constructor into the first bare :class group. We have a special case for @xtype which in ExtJS comments often appears after @constructor - so we explicitly place it into :class group. Then gathers each @cfg and tags following it into :cfg group, so that it becomes array of arrays of tags. This is to allow some configs to be marked with @private or whatever else. Finally gathers tags after @constructor into its group.
[ "Handles", "old", "syntax", "where", "configs", "and", "constructor", "are", "part", "of", "class", "doc", "-", "comment", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class_doc_expander.rb#L38-L69
train
senchalabs/jsduck
lib/jsduck/class_doc_expander.rb
JsDuck.ClassDocExpander.groups_to_docsets
def groups_to_docsets(groups, docset) results = [] results << { :tagname => :class, :type => docset[:type], :comment => groups[:class], :code => docset[:code], :linenr => docset[:linenr], } groups[:cfg].each do |cfg| results << { :tagname => :cfg, :type => docset[:type], :comment => cfg, :code => {}, :linenr => docset[:linenr], } end if groups[:constructor].length > 0 # Remember that a constructor is already found and ignore if a # constructor is detected from code. @constructor_found = true results << { :tagname => :method, :type => docset[:type], :comment => groups[:constructor], :code => {}, :linenr => docset[:linenr], } end results end
ruby
def groups_to_docsets(groups, docset) results = [] results << { :tagname => :class, :type => docset[:type], :comment => groups[:class], :code => docset[:code], :linenr => docset[:linenr], } groups[:cfg].each do |cfg| results << { :tagname => :cfg, :type => docset[:type], :comment => cfg, :code => {}, :linenr => docset[:linenr], } end if groups[:constructor].length > 0 # Remember that a constructor is already found and ignore if a # constructor is detected from code. @constructor_found = true results << { :tagname => :method, :type => docset[:type], :comment => groups[:constructor], :code => {}, :linenr => docset[:linenr], } end results end
[ "def", "groups_to_docsets", "(", "groups", ",", "docset", ")", "results", "=", "[", "]", "results", "<<", "{", ":tagname", "=>", ":class", ",", ":type", "=>", "docset", "[", ":type", "]", ",", ":comment", "=>", "groups", "[", ":class", "]", ",", ":code", "=>", "docset", "[", ":code", "]", ",", ":linenr", "=>", "docset", "[", ":linenr", "]", ",", "}", "groups", "[", ":cfg", "]", ".", "each", "do", "|", "cfg", "|", "results", "<<", "{", ":tagname", "=>", ":cfg", ",", ":type", "=>", "docset", "[", ":type", "]", ",", ":comment", "=>", "cfg", ",", ":code", "=>", "{", "}", ",", ":linenr", "=>", "docset", "[", ":linenr", "]", ",", "}", "end", "if", "groups", "[", ":constructor", "]", ".", "length", ">", "0", "# Remember that a constructor is already found and ignore if a", "# constructor is detected from code.", "@constructor_found", "=", "true", "results", "<<", "{", ":tagname", "=>", ":method", ",", ":type", "=>", "docset", "[", ":type", "]", ",", ":comment", "=>", "groups", "[", ":constructor", "]", ",", ":code", "=>", "{", "}", ",", ":linenr", "=>", "docset", "[", ":linenr", "]", ",", "}", "end", "results", "end" ]
Turns groups hash into list of docsets
[ "Turns", "groups", "hash", "into", "list", "of", "docsets" ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class_doc_expander.rb#L72-L104
train
senchalabs/jsduck
lib/jsduck/class_doc_expander.rb
JsDuck.ClassDocExpander.expand_code
def expand_code(docset) results = [] if docset[:code] (docset[:code][:members] || []).each do |m| results << code_to_docset(m) unless @constructor_found && JsDuck::Class.constructor?(m) end end results end
ruby
def expand_code(docset) results = [] if docset[:code] (docset[:code][:members] || []).each do |m| results << code_to_docset(m) unless @constructor_found && JsDuck::Class.constructor?(m) end end results end
[ "def", "expand_code", "(", "docset", ")", "results", "=", "[", "]", "if", "docset", "[", ":code", "]", "(", "docset", "[", ":code", "]", "[", ":members", "]", "||", "[", "]", ")", ".", "each", "do", "|", "m", "|", "results", "<<", "code_to_docset", "(", "m", ")", "unless", "@constructor_found", "&&", "JsDuck", "::", "Class", ".", "constructor?", "(", "m", ")", "end", "end", "results", "end" ]
Turns auto-detected class members into docsets in their own right.
[ "Turns", "auto", "-", "detected", "class", "members", "into", "docsets", "in", "their", "own", "right", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/class_doc_expander.rb#L108-L118
train
senchalabs/jsduck
lib/jsduck/tag_loader.rb
JsDuck.TagLoader.load
def load(path) if File.directory?(path) Dir[path+"/**/*.rb"].each do |file| # Ruby 1.8 doesn't understand that "jsduck/tag/tag" and # "./lib/jsduck/tag/tag.rb" refer to the same file. So # explicitly avoid loading this file (as it's required on # top already) to prevent warnings of constants getting # defined multiple times. require(file) unless file =~ /jsduck\/tag\/tag\.rb$/ end else require(path) end end
ruby
def load(path) if File.directory?(path) Dir[path+"/**/*.rb"].each do |file| # Ruby 1.8 doesn't understand that "jsduck/tag/tag" and # "./lib/jsduck/tag/tag.rb" refer to the same file. So # explicitly avoid loading this file (as it's required on # top already) to prevent warnings of constants getting # defined multiple times. require(file) unless file =~ /jsduck\/tag\/tag\.rb$/ end else require(path) end end
[ "def", "load", "(", "path", ")", "if", "File", ".", "directory?", "(", "path", ")", "Dir", "[", "path", "+", "\"/**/*.rb\"", "]", ".", "each", "do", "|", "file", "|", "# Ruby 1.8 doesn't understand that \"jsduck/tag/tag\" and", "# \"./lib/jsduck/tag/tag.rb\" refer to the same file. So", "# explicitly avoid loading this file (as it's required on", "# top already) to prevent warnings of constants getting", "# defined multiple times.", "require", "(", "file", ")", "unless", "file", "=~", "/", "\\/", "\\/", "\\.", "/", "end", "else", "require", "(", "path", ")", "end", "end" ]
Loads tag classes from given dir or single file.
[ "Loads", "tag", "classes", "from", "given", "dir", "or", "single", "file", "." ]
febef5558ecd05da25f5c260365acc3afd0cafd8
https://github.com/senchalabs/jsduck/blob/febef5558ecd05da25f5c260365acc3afd0cafd8/lib/jsduck/tag_loader.rb#L25-L38
train
vmware/rbvmomi
lib/rbvmomi/optimist.rb
Optimist.Parser.rbvmomi_connection_opts
def rbvmomi_connection_opts opt :host, "host", :type => :string, :short => 'o', :default => ENV['RBVMOMI_HOST'] opt :port, "port", :type => :int, :short => :none, :default => (ENV.member?('RBVMOMI_PORT') ? ENV['RBVMOMI_PORT'].to_i : 443) opt :"no-ssl", "don't use ssl", :short => :none, :default => (ENV['RBVMOMI_SSL'] == '0') opt :insecure, "don't verify ssl certificate", :short => 'k', :default => (ENV['RBVMOMI_INSECURE'] == '1') opt :user, "username", :short => 'u', :default => (ENV['RBVMOMI_USER'] || 'root') opt :password, "password", :short => 'p', :default => (ENV['RBVMOMI_PASSWORD'] || '') opt :path, "SOAP endpoint path", :short => :none, :default => (ENV['RBVMOMI_PATH'] || '/sdk') opt :debug, "Log SOAP messages", :short => 'd', :default => (ENV['RBVMOMI_DEBUG'] || false) end
ruby
def rbvmomi_connection_opts opt :host, "host", :type => :string, :short => 'o', :default => ENV['RBVMOMI_HOST'] opt :port, "port", :type => :int, :short => :none, :default => (ENV.member?('RBVMOMI_PORT') ? ENV['RBVMOMI_PORT'].to_i : 443) opt :"no-ssl", "don't use ssl", :short => :none, :default => (ENV['RBVMOMI_SSL'] == '0') opt :insecure, "don't verify ssl certificate", :short => 'k', :default => (ENV['RBVMOMI_INSECURE'] == '1') opt :user, "username", :short => 'u', :default => (ENV['RBVMOMI_USER'] || 'root') opt :password, "password", :short => 'p', :default => (ENV['RBVMOMI_PASSWORD'] || '') opt :path, "SOAP endpoint path", :short => :none, :default => (ENV['RBVMOMI_PATH'] || '/sdk') opt :debug, "Log SOAP messages", :short => 'd', :default => (ENV['RBVMOMI_DEBUG'] || false) end
[ "def", "rbvmomi_connection_opts", "opt", ":host", ",", "\"host\"", ",", ":type", "=>", ":string", ",", ":short", "=>", "'o'", ",", ":default", "=>", "ENV", "[", "'RBVMOMI_HOST'", "]", "opt", ":port", ",", "\"port\"", ",", ":type", "=>", ":int", ",", ":short", "=>", ":none", ",", ":default", "=>", "(", "ENV", ".", "member?", "(", "'RBVMOMI_PORT'", ")", "?", "ENV", "[", "'RBVMOMI_PORT'", "]", ".", "to_i", ":", "443", ")", "opt", ":\"", "\"", ",", "\"don't use ssl\"", ",", ":short", "=>", ":none", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_SSL'", "]", "==", "'0'", ")", "opt", ":insecure", ",", "\"don't verify ssl certificate\"", ",", ":short", "=>", "'k'", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_INSECURE'", "]", "==", "'1'", ")", "opt", ":user", ",", "\"username\"", ",", ":short", "=>", "'u'", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_USER'", "]", "||", "'root'", ")", "opt", ":password", ",", "\"password\"", ",", ":short", "=>", "'p'", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_PASSWORD'", "]", "||", "''", ")", "opt", ":path", ",", "\"SOAP endpoint path\"", ",", ":short", "=>", ":none", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_PATH'", "]", "||", "'/sdk'", ")", "opt", ":debug", ",", "\"Log SOAP messages\"", ",", ":short", "=>", "'d'", ",", ":default", "=>", "(", "ENV", "[", "'RBVMOMI_DEBUG'", "]", "||", "false", ")", "end" ]
Options used by VIM.connect !!!plain host: -o --host RBVMOMI_HOST port: --port RBVMOMI_PORT (443) no-ssl: --no-ssl RBVMOMI_SSL (false) insecure: -k --insecure RBVMOMI_INSECURE (false) user: -u --user RBVMOMI_USER (root) password: -p --password RBVMOMI_PASSWORD () path: --path RBVMOMI_PATH (/sdk) debug: -d --debug RBVMOMI_DEBUG (false)
[ "Options", "used", "by", "VIM", ".", "connect" ]
0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81
https://github.com/vmware/rbvmomi/blob/0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81/lib/rbvmomi/optimist.rb#L29-L38
train
vmware/rbvmomi
lib/rbvmomi/type_loader.rb
RbVmomi.TypeLoader.reload_extensions_dir
def reload_extensions_dir path loaded = Set.new(typenames.select { |x| @namespace.const_defined? x }) Dir.open(path) do |dir| dir.each do |file| next unless file =~ /\.rb$/ next unless loaded.member? $` file_path = File.join(dir, file) load file_path end end end
ruby
def reload_extensions_dir path loaded = Set.new(typenames.select { |x| @namespace.const_defined? x }) Dir.open(path) do |dir| dir.each do |file| next unless file =~ /\.rb$/ next unless loaded.member? $` file_path = File.join(dir, file) load file_path end end end
[ "def", "reload_extensions_dir", "path", "loaded", "=", "Set", ".", "new", "(", "typenames", ".", "select", "{", "|", "x", "|", "@namespace", ".", "const_defined?", "x", "}", ")", "Dir", ".", "open", "(", "path", ")", "do", "|", "dir", "|", "dir", ".", "each", "do", "|", "file", "|", "next", "unless", "file", "=~", "/", "\\.", "/", "next", "unless", "loaded", ".", "member?", "$`", "file_path", "=", "File", ".", "join", "(", "dir", ",", "file", ")", "load", "file_path", "end", "end", "end" ]
Reload all extensions for loaded VMODL types from the given directory
[ "Reload", "all", "extensions", "for", "loaded", "VMODL", "types", "from", "the", "given", "directory" ]
0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81
https://github.com/vmware/rbvmomi/blob/0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81/lib/rbvmomi/type_loader.rb#L38-L48
train
vmware/rbvmomi
lib/rbvmomi/deserialization.rb
RbVmomi.NewDeserializer.leaf_keyvalue
def leaf_keyvalue node h = {} node.children.each do |child| next unless child.element? h[child.name] = child.content end [h['key'], h['value']] end
ruby
def leaf_keyvalue node h = {} node.children.each do |child| next unless child.element? h[child.name] = child.content end [h['key'], h['value']] end
[ "def", "leaf_keyvalue", "node", "h", "=", "{", "}", "node", ".", "children", ".", "each", "do", "|", "child", "|", "next", "unless", "child", ".", "element?", "h", "[", "child", ".", "name", "]", "=", "child", ".", "content", "end", "[", "h", "[", "'key'", "]", ",", "h", "[", "'value'", "]", "]", "end" ]
XXX does the value need to be deserialized?
[ "XXX", "does", "the", "value", "need", "to", "be", "deserialized?" ]
0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81
https://github.com/vmware/rbvmomi/blob/0cb564b2a2ca1d7b78ffbd63dc15763c5e36db81/lib/rbvmomi/deserialization.rb#L147-L154
train
andymeneely/squib
lib/squib/sample_helpers.rb
Squib.Deck.draw_graph_paper
def draw_graph_paper(width, height) background color: 'white' grid width: 50, height: 50, stroke_color: '#659ae9', stroke_width: 1.5 grid width: 200, height: 200, stroke_color: '#659ae9', stroke_width: 3, x: 50, y: 50 (50..height).step(200) do |y| text str: "y=#{y}", x: 3, y: y - 18, font: 'Open Sans, Sans 10' end end
ruby
def draw_graph_paper(width, height) background color: 'white' grid width: 50, height: 50, stroke_color: '#659ae9', stroke_width: 1.5 grid width: 200, height: 200, stroke_color: '#659ae9', stroke_width: 3, x: 50, y: 50 (50..height).step(200) do |y| text str: "y=#{y}", x: 3, y: y - 18, font: 'Open Sans, Sans 10' end end
[ "def", "draw_graph_paper", "(", "width", ",", "height", ")", "background", "color", ":", "'white'", "grid", "width", ":", "50", ",", "height", ":", "50", ",", "stroke_color", ":", "'#659ae9'", ",", "stroke_width", ":", "1.5", "grid", "width", ":", "200", ",", "height", ":", "200", ",", "stroke_color", ":", "'#659ae9'", ",", "stroke_width", ":", "3", ",", "x", ":", "50", ",", "y", ":", "50", "(", "50", "..", "height", ")", ".", "step", "(", "200", ")", "do", "|", "y", "|", "text", "str", ":", "\"y=#{y}\"", ",", "x", ":", "3", ",", "y", ":", "y", "-", "18", ",", "font", ":", "'Open Sans, Sans 10'", "end", "end" ]
Draw graph paper for samples
[ "Draw", "graph", "paper", "for", "samples" ]
1d307fe6e00306e7b21f35e6c51955724e4e0673
https://github.com/andymeneely/squib/blob/1d307fe6e00306e7b21f35e6c51955724e4e0673/lib/squib/sample_helpers.rb#L9-L16
train