id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
23,000
dradis/dradis-plugins
lib/dradis/plugins/content_service/issues.rb
Dradis::Plugins::ContentService.Issues.issue_cache
def issue_cache @issue_cache ||= begin issues_map = all_issues.map do |issue| cache_key = [ issue.fields['plugin'], issue.fields['plugin_id'] ].join('-') [cache_key, issue] end Hash[issues_map] end end
ruby
def issue_cache @issue_cache ||= begin issues_map = all_issues.map do |issue| cache_key = [ issue.fields['plugin'], issue.fields['plugin_id'] ].join('-') [cache_key, issue] end Hash[issues_map] end end
[ "def", "issue_cache", "@issue_cache", "||=", "begin", "issues_map", "=", "all_issues", ".", "map", "do", "|", "issue", "|", "cache_key", "=", "[", "issue", ".", "fields", "[", "'plugin'", "]", ",", "issue", ".", "fields", "[", "'plugin_id'", "]", "]", ".", "join", "(", "'-'", ")", "[", "cache_key", ",", "issue", "]", "end", "Hash", "[", "issues_map", "]", "end", "end" ]
Create a hash with all issues where the keys correspond to the field passed as an argument. This is use by the plugins to check whether a given issue is already in the project. def all_issues_by_field(field) # we don't memoize it because we want it to reflect recently added Issues klass = class_for(:issue) issues_map = klass.where(category_id: default_issue_category.id).map do |issue| [issue.fields[field], issue] end Hash[issues_map] end Accesing the library by primary sorting key. Raise an exception unless the issue library cache has been initialized.
[ "Create", "a", "hash", "with", "all", "issues", "where", "the", "keys", "correspond", "to", "the", "field", "passed", "as", "an", "argument", "." ]
570367ba16e42dae3f3065a6b72c544dd780ca36
https://github.com/dradis/dradis-plugins/blob/570367ba16e42dae3f3065a6b72c544dd780ca36/lib/dradis/plugins/content_service/issues.rb#L65-L77
23,001
bunto/bunto
lib/bunto/renderer.rb
Bunto.Renderer.render_liquid
def render_liquid(content, payload, info, path = nil) template = site.liquid_renderer.file(path).parse(content) template.warnings.each do |e| Bunto.logger.warn "Liquid Warning:", LiquidRenderer.format_error(e, path || document.relative_path) end template.render!(payload, info) # rubocop: disable RescueException rescue Exception => e Bunto.logger.error "Liquid Exception:", LiquidRenderer.format_error(e, path || document.relative_path) raise e end
ruby
def render_liquid(content, payload, info, path = nil) template = site.liquid_renderer.file(path).parse(content) template.warnings.each do |e| Bunto.logger.warn "Liquid Warning:", LiquidRenderer.format_error(e, path || document.relative_path) end template.render!(payload, info) # rubocop: disable RescueException rescue Exception => e Bunto.logger.error "Liquid Exception:", LiquidRenderer.format_error(e, path || document.relative_path) raise e end
[ "def", "render_liquid", "(", "content", ",", "payload", ",", "info", ",", "path", "=", "nil", ")", "template", "=", "site", ".", "liquid_renderer", ".", "file", "(", "path", ")", ".", "parse", "(", "content", ")", "template", ".", "warnings", ".", "each", "do", "|", "e", "|", "Bunto", ".", "logger", ".", "warn", "\"Liquid Warning:\"", ",", "LiquidRenderer", ".", "format_error", "(", "e", ",", "path", "||", "document", ".", "relative_path", ")", "end", "template", ".", "render!", "(", "payload", ",", "info", ")", "# rubocop: disable RescueException", "rescue", "Exception", "=>", "e", "Bunto", ".", "logger", ".", "error", "\"Liquid Exception:\"", ",", "LiquidRenderer", ".", "format_error", "(", "e", ",", "path", "||", "document", ".", "relative_path", ")", "raise", "e", "end" ]
Render the given content with the payload and info content - payload - info - path - (optional) the path to the file, for use in ex Returns the content, rendered by Liquid.
[ "Render", "the", "given", "content", "with", "the", "payload", "and", "info" ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/renderer.rb#L128-L140
23,002
bunto/bunto
lib/bunto/renderer.rb
Bunto.Renderer.place_in_layouts
def place_in_layouts(content, payload, info) output = content.dup layout = layouts[document.data["layout"]] Bunto.logger.warn( "Build Warning:", "Layout '#{document.data["layout"]}' requested in "\ "#{document.relative_path} does not exist." ) if invalid_layout? layout used = Set.new([layout]) # Reset the payload layout data to ensure it starts fresh for each page. payload["layout"] = nil while layout payload["content"] = output payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) output = render_liquid( layout.content, payload, info, layout.relative_path ) # Add layout to dependency tree site.regenerator.add_dependency( site.in_source_dir(document.path), site.in_source_dir(layout.path) ) if document.write? if (layout = layouts[layout.data["layout"]]) break if used.include?(layout) used << layout end end output end
ruby
def place_in_layouts(content, payload, info) output = content.dup layout = layouts[document.data["layout"]] Bunto.logger.warn( "Build Warning:", "Layout '#{document.data["layout"]}' requested in "\ "#{document.relative_path} does not exist." ) if invalid_layout? layout used = Set.new([layout]) # Reset the payload layout data to ensure it starts fresh for each page. payload["layout"] = nil while layout payload["content"] = output payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) output = render_liquid( layout.content, payload, info, layout.relative_path ) # Add layout to dependency tree site.regenerator.add_dependency( site.in_source_dir(document.path), site.in_source_dir(layout.path) ) if document.write? if (layout = layouts[layout.data["layout"]]) break if used.include?(layout) used << layout end end output end
[ "def", "place_in_layouts", "(", "content", ",", "payload", ",", "info", ")", "output", "=", "content", ".", "dup", "layout", "=", "layouts", "[", "document", ".", "data", "[", "\"layout\"", "]", "]", "Bunto", ".", "logger", ".", "warn", "(", "\"Build Warning:\"", ",", "\"Layout '#{document.data[\"layout\"]}' requested in \"", "\"#{document.relative_path} does not exist.\"", ")", "if", "invalid_layout?", "layout", "used", "=", "Set", ".", "new", "(", "[", "layout", "]", ")", "# Reset the payload layout data to ensure it starts fresh for each page.", "payload", "[", "\"layout\"", "]", "=", "nil", "while", "layout", "payload", "[", "\"content\"", "]", "=", "output", "payload", "[", "\"layout\"", "]", "=", "Utils", ".", "deep_merge_hashes", "(", "layout", ".", "data", ",", "payload", "[", "\"layout\"", "]", "||", "{", "}", ")", "output", "=", "render_liquid", "(", "layout", ".", "content", ",", "payload", ",", "info", ",", "layout", ".", "relative_path", ")", "# Add layout to dependency tree", "site", ".", "regenerator", ".", "add_dependency", "(", "site", ".", "in_source_dir", "(", "document", ".", "path", ")", ",", "site", ".", "in_source_dir", "(", "layout", ".", "path", ")", ")", "if", "document", ".", "write?", "if", "(", "layout", "=", "layouts", "[", "layout", ".", "data", "[", "\"layout\"", "]", "]", ")", "break", "if", "used", ".", "include?", "(", "layout", ")", "used", "<<", "layout", "end", "end", "output", "end" ]
Render layouts and place given content inside. content - the content to be placed in the layout Returns the content placed in the Liquid-rendered layouts
[ "Render", "layouts", "and", "place", "given", "content", "inside", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/renderer.rb#L158-L197
23,003
bunto/bunto
lib/bunto/site.rb
Bunto.Site.reset
def reset if config["time"] self.time = Utils.parse_date(config["time"].to_s, "Invalid time in _config.yml.") else self.time = Time.now end self.layouts = {} self.pages = [] self.static_files = [] self.data = {} @collections = nil @regenerator.clear_cache @liquid_renderer.reset if limit_posts < 0 raise ArgumentError, "limit_posts must be a non-negative number" end Bunto::Hooks.trigger :site, :after_reset, self end
ruby
def reset if config["time"] self.time = Utils.parse_date(config["time"].to_s, "Invalid time in _config.yml.") else self.time = Time.now end self.layouts = {} self.pages = [] self.static_files = [] self.data = {} @collections = nil @regenerator.clear_cache @liquid_renderer.reset if limit_posts < 0 raise ArgumentError, "limit_posts must be a non-negative number" end Bunto::Hooks.trigger :site, :after_reset, self end
[ "def", "reset", "if", "config", "[", "\"time\"", "]", "self", ".", "time", "=", "Utils", ".", "parse_date", "(", "config", "[", "\"time\"", "]", ".", "to_s", ",", "\"Invalid time in _config.yml.\"", ")", "else", "self", ".", "time", "=", "Time", ".", "now", "end", "self", ".", "layouts", "=", "{", "}", "self", ".", "pages", "=", "[", "]", "self", ".", "static_files", "=", "[", "]", "self", ".", "data", "=", "{", "}", "@collections", "=", "nil", "@regenerator", ".", "clear_cache", "@liquid_renderer", ".", "reset", "if", "limit_posts", "<", "0", "raise", "ArgumentError", ",", "\"limit_posts must be a non-negative number\"", "end", "Bunto", "::", "Hooks", ".", "trigger", ":site", ",", ":after_reset", ",", "self", "end" ]
Reset Site details. Returns nothing
[ "Reset", "Site", "details", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L84-L103
23,004
bunto/bunto
lib/bunto/site.rb
Bunto.Site.setup
def setup ensure_not_in_dest plugin_manager.conscientious_require self.converters = instantiate_subclasses(Bunto::Converter) self.generators = instantiate_subclasses(Bunto::Generator) end
ruby
def setup ensure_not_in_dest plugin_manager.conscientious_require self.converters = instantiate_subclasses(Bunto::Converter) self.generators = instantiate_subclasses(Bunto::Generator) end
[ "def", "setup", "ensure_not_in_dest", "plugin_manager", ".", "conscientious_require", "self", ".", "converters", "=", "instantiate_subclasses", "(", "Bunto", "::", "Converter", ")", "self", ".", "generators", "=", "instantiate_subclasses", "(", "Bunto", "::", "Generator", ")", "end" ]
Load necessary libraries, plugins, converters, and generators. Returns nothing.
[ "Load", "necessary", "libraries", "plugins", "converters", "and", "generators", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L108-L115
23,005
bunto/bunto
lib/bunto/site.rb
Bunto.Site.ensure_not_in_dest
def ensure_not_in_dest dest_pathname = Pathname.new(dest) Pathname.new(source).ascend do |path| if path == dest_pathname raise( Errors::FatalException, "Destination directory cannot be or contain the Source directory." ) end end end
ruby
def ensure_not_in_dest dest_pathname = Pathname.new(dest) Pathname.new(source).ascend do |path| if path == dest_pathname raise( Errors::FatalException, "Destination directory cannot be or contain the Source directory." ) end end end
[ "def", "ensure_not_in_dest", "dest_pathname", "=", "Pathname", ".", "new", "(", "dest", ")", "Pathname", ".", "new", "(", "source", ")", ".", "ascend", "do", "|", "path", "|", "if", "path", "==", "dest_pathname", "raise", "(", "Errors", "::", "FatalException", ",", "\"Destination directory cannot be or contain the Source directory.\"", ")", "end", "end", "end" ]
Check that the destination dir isn't the source dir or a directory parent to the source dir.
[ "Check", "that", "the", "destination", "dir", "isn", "t", "the", "source", "dir", "or", "a", "directory", "parent", "to", "the", "source", "dir", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L119-L129
23,006
bunto/bunto
lib/bunto/site.rb
Bunto.Site.generate
def generate generators.each do |generator| start = Time.now generator.generate(self) Bunto.logger.debug "Generating:", "#{generator.class} finished in #{Time.now - start} seconds." end end
ruby
def generate generators.each do |generator| start = Time.now generator.generate(self) Bunto.logger.debug "Generating:", "#{generator.class} finished in #{Time.now - start} seconds." end end
[ "def", "generate", "generators", ".", "each", "do", "|", "generator", "|", "start", "=", "Time", ".", "now", "generator", ".", "generate", "(", "self", ")", "Bunto", ".", "logger", ".", "debug", "\"Generating:\"", ",", "\"#{generator.class} finished in #{Time.now - start} seconds.\"", "end", "end" ]
Run each of the Generators. Returns nothing.
[ "Run", "each", "of", "the", "Generators", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L171-L178
23,007
bunto/bunto
lib/bunto/site.rb
Bunto.Site.render
def render relative_permalinks_are_deprecated payload = site_payload Bunto::Hooks.trigger :site, :pre_render, self, payload render_docs(payload) render_pages(payload) Bunto::Hooks.trigger :site, :post_render, self, payload end
ruby
def render relative_permalinks_are_deprecated payload = site_payload Bunto::Hooks.trigger :site, :pre_render, self, payload render_docs(payload) render_pages(payload) Bunto::Hooks.trigger :site, :post_render, self, payload end
[ "def", "render", "relative_permalinks_are_deprecated", "payload", "=", "site_payload", "Bunto", "::", "Hooks", ".", "trigger", ":site", ",", ":pre_render", ",", "self", ",", "payload", "render_docs", "(", "payload", ")", "render_pages", "(", "payload", ")", "Bunto", "::", "Hooks", ".", "trigger", ":site", ",", ":post_render", ",", "self", ",", "payload", "end" ]
Render the site to the destination. Returns nothing.
[ "Render", "the", "site", "to", "the", "destination", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/site.rb#L183-L194
23,008
bunto/bunto
lib/bunto/page.rb
Bunto.Page.dir
def dir if url.end_with?(FORWARD_SLASH) url else url_dir = File.dirname(url) url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/" end end
ruby
def dir if url.end_with?(FORWARD_SLASH) url else url_dir = File.dirname(url) url_dir.end_with?(FORWARD_SLASH) ? url_dir : "#{url_dir}/" end end
[ "def", "dir", "if", "url", ".", "end_with?", "(", "FORWARD_SLASH", ")", "url", "else", "url_dir", "=", "File", ".", "dirname", "(", "url", ")", "url_dir", ".", "end_with?", "(", "FORWARD_SLASH", ")", "?", "url_dir", ":", "\"#{url_dir}/\"", "end", "end" ]
Initialize a new Page. site - The Site object. base - The String path to the source. dir - The String path between the source and the file. name - The String filename of the file. The generated directory into which the page will be placed upon generation. This is derived from the permalink or, if permalink is absent, will be '/' Returns the String destination directory.
[ "Initialize", "a", "new", "Page", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/page.rb#L64-L71
23,009
bunto/bunto
lib/bunto/convertible.rb
Bunto.Convertible.read_yaml
def read_yaml(base, name, opts = {}) filename = File.join(base, name) begin self.content = File.read(@path || site.in_source_dir(base, name), Utils.merged_file_read_opts(site, opts)) if content =~ Document::YAML_FRONT_MATTER_REGEXP self.content = $POSTMATCH self.data = SafeYAML.load(Regexp.last_match(1)) end rescue SyntaxError => e Bunto.logger.warn "YAML Exception reading #{filename}: #{e.message}" rescue => e Bunto.logger.warn "Error reading file #{filename}: #{e.message}" end self.data ||= {} validate_data! filename validate_permalink! filename self.data end
ruby
def read_yaml(base, name, opts = {}) filename = File.join(base, name) begin self.content = File.read(@path || site.in_source_dir(base, name), Utils.merged_file_read_opts(site, opts)) if content =~ Document::YAML_FRONT_MATTER_REGEXP self.content = $POSTMATCH self.data = SafeYAML.load(Regexp.last_match(1)) end rescue SyntaxError => e Bunto.logger.warn "YAML Exception reading #{filename}: #{e.message}" rescue => e Bunto.logger.warn "Error reading file #{filename}: #{e.message}" end self.data ||= {} validate_data! filename validate_permalink! filename self.data end
[ "def", "read_yaml", "(", "base", ",", "name", ",", "opts", "=", "{", "}", ")", "filename", "=", "File", ".", "join", "(", "base", ",", "name", ")", "begin", "self", ".", "content", "=", "File", ".", "read", "(", "@path", "||", "site", ".", "in_source_dir", "(", "base", ",", "name", ")", ",", "Utils", ".", "merged_file_read_opts", "(", "site", ",", "opts", ")", ")", "if", "content", "=~", "Document", "::", "YAML_FRONT_MATTER_REGEXP", "self", ".", "content", "=", "$POSTMATCH", "self", ".", "data", "=", "SafeYAML", ".", "load", "(", "Regexp", ".", "last_match", "(", "1", ")", ")", "end", "rescue", "SyntaxError", "=>", "e", "Bunto", ".", "logger", ".", "warn", "\"YAML Exception reading #{filename}: #{e.message}\"", "rescue", "=>", "e", "Bunto", ".", "logger", ".", "warn", "\"Error reading file #{filename}: #{e.message}\"", "end", "self", ".", "data", "||=", "{", "}", "validate_data!", "filename", "validate_permalink!", "filename", "self", ".", "data", "end" ]
Read the YAML frontmatter. base - The String path to the dir containing the file. name - The String filename of the file. opts - optional parameter to File.read, default at site configs Returns nothing. rubocop:disable Metrics/AbcSize
[ "Read", "the", "YAML", "frontmatter", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/convertible.rb#L39-L61
23,010
bunto/bunto
lib/bunto/filters.rb
Bunto.Filters.sassify
def sassify(input) site = @context.registers[:site] converter = site.find_converter_instance(Bunto::Converters::Sass) converter.convert(input) end
ruby
def sassify(input) site = @context.registers[:site] converter = site.find_converter_instance(Bunto::Converters::Sass) converter.convert(input) end
[ "def", "sassify", "(", "input", ")", "site", "=", "@context", ".", "registers", "[", ":site", "]", "converter", "=", "site", ".", "find_converter_instance", "(", "Bunto", "::", "Converters", "::", "Sass", ")", "converter", ".", "convert", "(", "input", ")", "end" ]
Convert a Sass string into CSS output. input - The Sass String to convert. Returns the CSS formatted String.
[ "Convert", "a", "Sass", "string", "into", "CSS", "output", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/filters.rb#L40-L44
23,011
bunto/bunto
lib/bunto/filters.rb
Bunto.Filters.scssify
def scssify(input) site = @context.registers[:site] converter = site.find_converter_instance(Bunto::Converters::Scss) converter.convert(input) end
ruby
def scssify(input) site = @context.registers[:site] converter = site.find_converter_instance(Bunto::Converters::Scss) converter.convert(input) end
[ "def", "scssify", "(", "input", ")", "site", "=", "@context", ".", "registers", "[", ":site", "]", "converter", "=", "site", ".", "find_converter_instance", "(", "Bunto", "::", "Converters", "::", "Scss", ")", "converter", ".", "convert", "(", "input", ")", "end" ]
Convert a Scss string into CSS output. input - The Scss String to convert. Returns the CSS formatted String.
[ "Convert", "a", "Scss", "string", "into", "CSS", "output", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/filters.rb#L51-L55
23,012
spk/validate-website
lib/validate_website/crawl.rb
ValidateWebsite.Crawl.extract_imgs_from_page
def extract_imgs_from_page(page) return Set[] if page.is_redirect? page.doc.search('//img[@src]').reduce(Set[]) do |result, elem| u = elem.attributes['src'].content result << page.to_absolute(URI.parse(URI.encode(u))) end end
ruby
def extract_imgs_from_page(page) return Set[] if page.is_redirect? page.doc.search('//img[@src]').reduce(Set[]) do |result, elem| u = elem.attributes['src'].content result << page.to_absolute(URI.parse(URI.encode(u))) end end
[ "def", "extract_imgs_from_page", "(", "page", ")", "return", "Set", "[", "]", "if", "page", ".", "is_redirect?", "page", ".", "doc", ".", "search", "(", "'//img[@src]'", ")", ".", "reduce", "(", "Set", "[", "]", ")", "do", "|", "result", ",", "elem", "|", "u", "=", "elem", ".", "attributes", "[", "'src'", "]", ".", "content", "result", "<<", "page", ".", "to_absolute", "(", "URI", ".", "parse", "(", "URI", ".", "encode", "(", "u", ")", ")", ")", "end", "end" ]
Extract imgs urls from page @param [Spidr::Page] an Spidr::Page object @return [Array] Lists of urls
[ "Extract", "imgs", "urls", "from", "page" ]
f8e9a610592e340da6d71ff20116ff512ba7aab9
https://github.com/spk/validate-website/blob/f8e9a610592e340da6d71ff20116ff512ba7aab9/lib/validate_website/crawl.rb#L42-L48
23,013
dark-panda/ffi-geos
lib/ffi-geos/geometry_collection.rb
Geos.GeometryCollection.each
def each if block_given? num_geometries.times do |n| yield get_geometry_n(n) end self else num_geometries.times.collect { |n| get_geometry_n(n) }.to_enum end end
ruby
def each if block_given? num_geometries.times do |n| yield get_geometry_n(n) end self else num_geometries.times.collect { |n| get_geometry_n(n) }.to_enum end end
[ "def", "each", "if", "block_given?", "num_geometries", ".", "times", "do", "|", "n", "|", "yield", "get_geometry_n", "(", "n", ")", "end", "self", "else", "num_geometries", ".", "times", ".", "collect", "{", "|", "n", "|", "get_geometry_n", "(", "n", ")", "}", ".", "to_enum", "end", "end" ]
Yields each Geometry in the GeometryCollection.
[ "Yields", "each", "Geometry", "in", "the", "GeometryCollection", "." ]
ac58e52585741ce8e10b11ec4857e5e6534cc96b
https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry_collection.rb#L8-L19
23,014
bunto/bunto
lib/bunto/collection.rb
Bunto.Collection.read
def read filtered_entries.each do |file_path| full_path = collection_dir(file_path) next if File.directory?(full_path) if Utils.has_yaml_header? full_path read_document(full_path) else read_static_file(file_path, full_path) end end docs.sort! end
ruby
def read filtered_entries.each do |file_path| full_path = collection_dir(file_path) next if File.directory?(full_path) if Utils.has_yaml_header? full_path read_document(full_path) else read_static_file(file_path, full_path) end end docs.sort! end
[ "def", "read", "filtered_entries", ".", "each", "do", "|", "file_path", "|", "full_path", "=", "collection_dir", "(", "file_path", ")", "next", "if", "File", ".", "directory?", "(", "full_path", ")", "if", "Utils", ".", "has_yaml_header?", "full_path", "read_document", "(", "full_path", ")", "else", "read_static_file", "(", "file_path", ",", "full_path", ")", "end", "end", "docs", ".", "sort!", "end" ]
Read the allowed documents into the collection's array of docs. Returns the sorted array of docs.
[ "Read", "the", "allowed", "documents", "into", "the", "collection", "s", "array", "of", "docs", "." ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/collection.rb#L55-L66
23,015
bys-control/activeadmin-index_as_calendar
lib/index_as_calendar/dsl.rb
IndexAsCalendar.DSL.index_as_calendar
def index_as_calendar( options={}, &block ) default_options = { :ajax => true, # Use AJAX to fetch events. Set to false to send data during render. :model => nil, # Model to be used to fetch events. Defaults to ActiveAdmin resource model. :includes => [], # Eager loading of related models :start_date => :created_at, # Field to be used as start date for events :end_date => nil, # Field to be used as end date for events :block => block, # Block with the model<->event field mappings :fullCalendarOptions => nil, # fullCalendar options to be sent upon initialization :default => false # Set this index view as default } options = default_options.deep_merge(options) # Defines controller for event_mapping model items to events controller do def event_mapping( items, options ) events = items.map do |item| if !options[:block].blank? instance_exec(item, &options[:block]) else { :id => item.id, :title => item.to_s, :start => (options[:start_date].blank? or item.send(options[:start_date]).blank?) ? Date.today.to_s : item.send(options[:start_date]), :end => (options[:end_date].blank? or item.send(options[:end_date]).blank?) ? nil : item.send(options[:end_date]) } end end end end # Setup AJAX if options[:ajax] # Setup fullCalendar to use AJAX calls to retrieve event data index as: :calendar, default: options[:default] do |context| context[:fullCalendarOptions] = options[:fullCalendarOptions] events = { url: "#{collection_path()}/index_as_events.json", type: 'GET', data: params } end # Defines collection_action to get events data collection_action :index_as_events, :method => :get do items = options[:model] || end_of_association_chain items = items.send(params[:scope]) if params[:scope].present? items = items.includes(options[:includes]) unless options[:includes].blank? items = items.where(options[:start_date] => params[:start].to_date...params[:end].to_date).ransack(params[:q]).result events = event_mapping(items, options) respond_to do |format| format.json { render :json => events } end end # Return events to be used during partial render else index as: :calendar, default: options[:default] do |context| context[:fullCalendarOptions] = options[:fullCalendarOptions] events = self.controller.event_mapping(context[:collection], options) end end end
ruby
def index_as_calendar( options={}, &block ) default_options = { :ajax => true, # Use AJAX to fetch events. Set to false to send data during render. :model => nil, # Model to be used to fetch events. Defaults to ActiveAdmin resource model. :includes => [], # Eager loading of related models :start_date => :created_at, # Field to be used as start date for events :end_date => nil, # Field to be used as end date for events :block => block, # Block with the model<->event field mappings :fullCalendarOptions => nil, # fullCalendar options to be sent upon initialization :default => false # Set this index view as default } options = default_options.deep_merge(options) # Defines controller for event_mapping model items to events controller do def event_mapping( items, options ) events = items.map do |item| if !options[:block].blank? instance_exec(item, &options[:block]) else { :id => item.id, :title => item.to_s, :start => (options[:start_date].blank? or item.send(options[:start_date]).blank?) ? Date.today.to_s : item.send(options[:start_date]), :end => (options[:end_date].blank? or item.send(options[:end_date]).blank?) ? nil : item.send(options[:end_date]) } end end end end # Setup AJAX if options[:ajax] # Setup fullCalendar to use AJAX calls to retrieve event data index as: :calendar, default: options[:default] do |context| context[:fullCalendarOptions] = options[:fullCalendarOptions] events = { url: "#{collection_path()}/index_as_events.json", type: 'GET', data: params } end # Defines collection_action to get events data collection_action :index_as_events, :method => :get do items = options[:model] || end_of_association_chain items = items.send(params[:scope]) if params[:scope].present? items = items.includes(options[:includes]) unless options[:includes].blank? items = items.where(options[:start_date] => params[:start].to_date...params[:end].to_date).ransack(params[:q]).result events = event_mapping(items, options) respond_to do |format| format.json { render :json => events } end end # Return events to be used during partial render else index as: :calendar, default: options[:default] do |context| context[:fullCalendarOptions] = options[:fullCalendarOptions] events = self.controller.event_mapping(context[:collection], options) end end end
[ "def", "index_as_calendar", "(", "options", "=", "{", "}", ",", "&", "block", ")", "default_options", "=", "{", ":ajax", "=>", "true", ",", "# Use AJAX to fetch events. Set to false to send data during render.", ":model", "=>", "nil", ",", "# Model to be used to fetch events. Defaults to ActiveAdmin resource model.", ":includes", "=>", "[", "]", ",", "# Eager loading of related models", ":start_date", "=>", ":created_at", ",", "# Field to be used as start date for events", ":end_date", "=>", "nil", ",", "# Field to be used as end date for events", ":block", "=>", "block", ",", "# Block with the model<->event field mappings", ":fullCalendarOptions", "=>", "nil", ",", "# fullCalendar options to be sent upon initialization", ":default", "=>", "false", "# Set this index view as default", "}", "options", "=", "default_options", ".", "deep_merge", "(", "options", ")", "# Defines controller for event_mapping model items to events", "controller", "do", "def", "event_mapping", "(", "items", ",", "options", ")", "events", "=", "items", ".", "map", "do", "|", "item", "|", "if", "!", "options", "[", ":block", "]", ".", "blank?", "instance_exec", "(", "item", ",", "options", "[", ":block", "]", ")", "else", "{", ":id", "=>", "item", ".", "id", ",", ":title", "=>", "item", ".", "to_s", ",", ":start", "=>", "(", "options", "[", ":start_date", "]", ".", "blank?", "or", "item", ".", "send", "(", "options", "[", ":start_date", "]", ")", ".", "blank?", ")", "?", "Date", ".", "today", ".", "to_s", ":", "item", ".", "send", "(", "options", "[", ":start_date", "]", ")", ",", ":end", "=>", "(", "options", "[", ":end_date", "]", ".", "blank?", "or", "item", ".", "send", "(", "options", "[", ":end_date", "]", ")", ".", "blank?", ")", "?", "nil", ":", "item", ".", "send", "(", "options", "[", ":end_date", "]", ")", "}", "end", "end", "end", "end", "# Setup AJAX", "if", "options", "[", ":ajax", "]", "# Setup fullCalendar to use AJAX calls to retrieve event data", "index", "as", ":", ":calendar", ",", "default", ":", "options", "[", ":default", "]", "do", "|", "context", "|", "context", "[", ":fullCalendarOptions", "]", "=", "options", "[", ":fullCalendarOptions", "]", "events", "=", "{", "url", ":", "\"#{collection_path()}/index_as_events.json\"", ",", "type", ":", "'GET'", ",", "data", ":", "params", "}", "end", "# Defines collection_action to get events data", "collection_action", ":index_as_events", ",", ":method", "=>", ":get", "do", "items", "=", "options", "[", ":model", "]", "||", "end_of_association_chain", "items", "=", "items", ".", "send", "(", "params", "[", ":scope", "]", ")", "if", "params", "[", ":scope", "]", ".", "present?", "items", "=", "items", ".", "includes", "(", "options", "[", ":includes", "]", ")", "unless", "options", "[", ":includes", "]", ".", "blank?", "items", "=", "items", ".", "where", "(", "options", "[", ":start_date", "]", "=>", "params", "[", ":start", "]", ".", "to_date", "...", "params", "[", ":end", "]", ".", "to_date", ")", ".", "ransack", "(", "params", "[", ":q", "]", ")", ".", "result", "events", "=", "event_mapping", "(", "items", ",", "options", ")", "respond_to", "do", "|", "format", "|", "format", ".", "json", "{", "render", ":json", "=>", "events", "}", "end", "end", "# Return events to be used during partial render", "else", "index", "as", ":", ":calendar", ",", "default", ":", "options", "[", ":default", "]", "do", "|", "context", "|", "context", "[", ":fullCalendarOptions", "]", "=", "options", "[", ":fullCalendarOptions", "]", "events", "=", "self", ".", "controller", ".", "event_mapping", "(", "context", "[", ":collection", "]", ",", "options", ")", "end", "end", "end" ]
Initializes activeadmin index as calendar
[ "Initializes", "activeadmin", "index", "as", "calendar" ]
1e07d605b536f4f9a89c054f34910728f46d3871
https://github.com/bys-control/activeadmin-index_as_calendar/blob/1e07d605b536f4f9a89c054f34910728f46d3871/lib/index_as_calendar/dsl.rb#L7-L72
23,016
dark-panda/ffi-geos
lib/ffi-geos/geometry.rb
Geos.Geometry.union
def union(geom = nil) if geom check_geometry(geom) cast_geometry_ptr(FFIGeos.GEOSUnion_r(Geos.current_handle_pointer, ptr, geom.ptr), srid_copy: pick_srid_from_geoms(srid, geom.srid)) else if respond_to?(:unary_union) unary_union else union_cascaded end end end
ruby
def union(geom = nil) if geom check_geometry(geom) cast_geometry_ptr(FFIGeos.GEOSUnion_r(Geos.current_handle_pointer, ptr, geom.ptr), srid_copy: pick_srid_from_geoms(srid, geom.srid)) else if respond_to?(:unary_union) unary_union else union_cascaded end end end
[ "def", "union", "(", "geom", "=", "nil", ")", "if", "geom", "check_geometry", "(", "geom", ")", "cast_geometry_ptr", "(", "FFIGeos", ".", "GEOSUnion_r", "(", "Geos", ".", "current_handle_pointer", ",", "ptr", ",", "geom", ".", "ptr", ")", ",", "srid_copy", ":", "pick_srid_from_geoms", "(", "srid", ",", "geom", ".", "srid", ")", ")", "else", "if", "respond_to?", "(", ":unary_union", ")", "unary_union", "else", "union_cascaded", "end", "end", "end" ]
Calling without a geom argument is equivalent to calling unary_union when using GEOS 3.3+ and is equivalent to calling union_cascaded in older versions.
[ "Calling", "without", "a", "geom", "argument", "is", "equivalent", "to", "calling", "unary_union", "when", "using", "GEOS", "3", ".", "3", "+", "and", "is", "equivalent", "to", "calling", "union_cascaded", "in", "older", "versions", "." ]
ac58e52585741ce8e10b11ec4857e5e6534cc96b
https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry.rb#L162-L173
23,017
dark-panda/ffi-geos
lib/ffi-geos/geometry.rb
Geos.Geometry.relate_pattern
def relate_pattern(geom, pattern) check_geometry(geom) bool_result(FFIGeos.GEOSRelatePattern_r(Geos.current_handle_pointer, ptr, geom.ptr, pattern)) end
ruby
def relate_pattern(geom, pattern) check_geometry(geom) bool_result(FFIGeos.GEOSRelatePattern_r(Geos.current_handle_pointer, ptr, geom.ptr, pattern)) end
[ "def", "relate_pattern", "(", "geom", ",", "pattern", ")", "check_geometry", "(", "geom", ")", "bool_result", "(", "FFIGeos", ".", "GEOSRelatePattern_r", "(", "Geos", ".", "current_handle_pointer", ",", "ptr", ",", "geom", ".", "ptr", ",", "pattern", ")", ")", "end" ]
Checks the DE-9IM pattern against the geoms.
[ "Checks", "the", "DE", "-", "9IM", "pattern", "against", "the", "geoms", "." ]
ac58e52585741ce8e10b11ec4857e5e6534cc96b
https://github.com/dark-panda/ffi-geos/blob/ac58e52585741ce8e10b11ec4857e5e6534cc96b/lib/ffi-geos/geometry.rb#L223-L226
23,018
LaunchAcademy/roboto
lib/roboto/content_provider.rb
Roboto.ContentProvider.contents
def contents(custom_binding = nil) return @contents unless @contents.nil? @contents = File.read(path) if path.extname == '.erb' @contents = ERB.new(@contents, nil, '>').result(custom_binding ? custom_binding : binding) end @contents end
ruby
def contents(custom_binding = nil) return @contents unless @contents.nil? @contents = File.read(path) if path.extname == '.erb' @contents = ERB.new(@contents, nil, '>').result(custom_binding ? custom_binding : binding) end @contents end
[ "def", "contents", "(", "custom_binding", "=", "nil", ")", "return", "@contents", "unless", "@contents", ".", "nil?", "@contents", "=", "File", ".", "read", "(", "path", ")", "if", "path", ".", "extname", "==", "'.erb'", "@contents", "=", "ERB", ".", "new", "(", "@contents", ",", "nil", ",", "'>'", ")", ".", "result", "(", "custom_binding", "?", "custom_binding", ":", "binding", ")", "end", "@contents", "end" ]
Reads the contents of the effective robots.txt file @return [String] the contents of the effective robots.txt file
[ "Reads", "the", "contents", "of", "the", "effective", "robots", ".", "txt", "file" ]
c3b74aa9c7240fd557fe9317ba82c08e404bc265
https://github.com/LaunchAcademy/roboto/blob/c3b74aa9c7240fd557fe9317ba82c08e404bc265/lib/roboto/content_provider.rb#L8-L16
23,019
bunto/bunto
lib/bunto/regenerator.rb
Bunto.Regenerator.regenerate?
def regenerate?(document) case document when Page regenerate_page?(document) when Document regenerate_document?(document) else source_path = document.respond_to?(:path) ? document.path : nil dest_path = if document.respond_to?(:destination) document.destination(@site.dest) end source_modified_or_dest_missing?(source_path, dest_path) end end
ruby
def regenerate?(document) case document when Page regenerate_page?(document) when Document regenerate_document?(document) else source_path = document.respond_to?(:path) ? document.path : nil dest_path = if document.respond_to?(:destination) document.destination(@site.dest) end source_modified_or_dest_missing?(source_path, dest_path) end end
[ "def", "regenerate?", "(", "document", ")", "case", "document", "when", "Page", "regenerate_page?", "(", "document", ")", "when", "Document", "regenerate_document?", "(", "document", ")", "else", "source_path", "=", "document", ".", "respond_to?", "(", ":path", ")", "?", "document", ".", "path", ":", "nil", "dest_path", "=", "if", "document", ".", "respond_to?", "(", ":destination", ")", "document", ".", "destination", "(", "@site", ".", "dest", ")", "end", "source_modified_or_dest_missing?", "(", "source_path", ",", "dest_path", ")", "end", "end" ]
Checks if a renderable object needs to be regenerated Returns a boolean.
[ "Checks", "if", "a", "renderable", "object", "needs", "to", "be", "regenerated" ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/regenerator.rb#L20-L33
23,020
bunto/bunto
lib/bunto/regenerator.rb
Bunto.Regenerator.read_metadata
def read_metadata @metadata = if !disabled? && File.file?(metadata_file) content = File.binread(metadata_file) begin Marshal.load(content) rescue TypeError SafeYAML.load(content) rescue ArgumentError => e Bunto.logger.warn("Failed to load #{metadata_file}: #{e}") {} end else {} end end
ruby
def read_metadata @metadata = if !disabled? && File.file?(metadata_file) content = File.binread(metadata_file) begin Marshal.load(content) rescue TypeError SafeYAML.load(content) rescue ArgumentError => e Bunto.logger.warn("Failed to load #{metadata_file}: #{e}") {} end else {} end end
[ "def", "read_metadata", "@metadata", "=", "if", "!", "disabled?", "&&", "File", ".", "file?", "(", "metadata_file", ")", "content", "=", "File", ".", "binread", "(", "metadata_file", ")", "begin", "Marshal", ".", "load", "(", "content", ")", "rescue", "TypeError", "SafeYAML", ".", "load", "(", "content", ")", "rescue", "ArgumentError", "=>", "e", "Bunto", ".", "logger", ".", "warn", "(", "\"Failed to load #{metadata_file}: #{e}\"", ")", "{", "}", "end", "else", "{", "}", "end", "end" ]
Read metadata from the metadata file, if no file is found, initialize with an empty hash Returns the read metadata.
[ "Read", "metadata", "from", "the", "metadata", "file", "if", "no", "file", "is", "found", "initialize", "with", "an", "empty", "hash" ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/regenerator.rb#L146-L162
23,021
bunto/bunto
lib/bunto/frontmatter_defaults.rb
Bunto.FrontmatterDefaults.applies?
def applies?(scope, path, type) applies_path?(scope, path) && applies_type?(scope, type) end
ruby
def applies?(scope, path, type) applies_path?(scope, path) && applies_type?(scope, type) end
[ "def", "applies?", "(", "scope", ",", "path", ",", "type", ")", "applies_path?", "(", "scope", ",", "path", ")", "&&", "applies_type?", "(", "scope", ",", "type", ")", "end" ]
Checks if a given default setting scope matches the given path and type scope - the hash indicating the scope, as defined in _config.yml path - the path to check for type - the type (:post, :page or :draft) to check for Returns true if the scope applies to the given path and type
[ "Checks", "if", "a", "given", "default", "setting", "scope", "matches", "the", "given", "path", "and", "type" ]
45d993fb22329b12c277e15195af3415c9922a28
https://github.com/bunto/bunto/blob/45d993fb22329b12c277e15195af3415c9922a28/lib/bunto/frontmatter_defaults.rb#L94-L96
23,022
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/versions_controller.rb
Phcscriptcdn.Script::VersionsController.show
def show @script_versions = Script::Version.friendly.find(params[:id]) @versions = Phcscriptcdn::ScriptversionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Version') end
ruby
def show @script_versions = Script::Version.friendly.find(params[:id]) @versions = Phcscriptcdn::ScriptversionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Version') end
[ "def", "show", "@script_versions", "=", "Script", "::", "Version", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "@versions", "=", "Phcscriptcdn", "::", "ScriptversionVersions", ".", "where", "(", "item_id", ":", "params", "[", ":id", "]", ",", "item_type", ":", "'Phcscriptcdn::Script::Version'", ")", "end" ]
DETAILS - Script Versions
[ "DETAILS", "-", "Script", "Versions" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L18-L21
23,023
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/versions_controller.rb
Phcscriptcdn.Script::VersionsController.new
def new @script_version = Script::Version.new @script_version.user_id = current_user.id @script_version.org_id = current_user.org_id end
ruby
def new @script_version = Script::Version.new @script_version.user_id = current_user.id @script_version.org_id = current_user.org_id end
[ "def", "new", "@script_version", "=", "Script", "::", "Version", ".", "new", "@script_version", ".", "user_id", "=", "current_user", ".", "id", "@script_version", ".", "org_id", "=", "current_user", ".", "org_id", "end" ]
NEW - Script Versions
[ "NEW", "-", "Script", "Versions" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L24-L28
23,024
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/versions_controller.rb
Phcscriptcdn.Script::VersionsController.create
def create @script_version = Script::Version.new(script_version_params) @script_version.user_id = current_user.id @script_version.org_id = current_user.org_id if @script_version.save redirect_to script_versions_url, notice: 'Version was successfully created.' else render :new end end
ruby
def create @script_version = Script::Version.new(script_version_params) @script_version.user_id = current_user.id @script_version.org_id = current_user.org_id if @script_version.save redirect_to script_versions_url, notice: 'Version was successfully created.' else render :new end end
[ "def", "create", "@script_version", "=", "Script", "::", "Version", ".", "new", "(", "script_version_params", ")", "@script_version", ".", "user_id", "=", "current_user", ".", "id", "@script_version", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_version", ".", "save", "redirect_to", "script_versions_url", ",", "notice", ":", "'Version was successfully created.'", "else", "render", ":new", "end", "end" ]
POST - Script Versions
[ "POST", "-", "Script", "Versions" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/versions_controller.rb#L35-L44
23,025
teespring/nightwing
lib/nightwing/metric.rb
Nightwing.Metric.for
def for(queue:, worker: nil) worker_name = worker.to_s.underscore.tr("/", "_") if worker [namespace, queue, worker_name].compact.join(".") end
ruby
def for(queue:, worker: nil) worker_name = worker.to_s.underscore.tr("/", "_") if worker [namespace, queue, worker_name].compact.join(".") end
[ "def", "for", "(", "queue", ":", ",", "worker", ":", "nil", ")", "worker_name", "=", "worker", ".", "to_s", ".", "underscore", ".", "tr", "(", "\"/\"", ",", "\"_\"", ")", "if", "worker", "[", "namespace", ",", "queue", ",", "worker_name", "]", ".", "compact", ".", "join", "(", "\".\"", ")", "end" ]
Generates a metric name @param [String] queue @param [Class] worker returns a String object
[ "Generates", "a", "metric", "name" ]
619d0b3d2da29a8ca2dc82af0ce47595d435a391
https://github.com/teespring/nightwing/blob/619d0b3d2da29a8ca2dc82af0ce47595d435a391/lib/nightwing/metric.rb#L18-L21
23,026
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/urls_controller.rb
Phcscriptcdn.Script::UrlsController.show
def show script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.friendly.find(params[:id]) end
ruby
def show script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.friendly.find(params[:id]) end
[ "def", "show", "script_listing", "=", "Script", "::", "Listing", ".", "find", "(", "params", "[", ":listing_id", "]", ")", "@script_url", "=", "script_listing", ".", "urls", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "end" ]
DETAILED PROFILE - Script Authors
[ "DETAILED", "PROFILE", "-", "Script", "Authors" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L19-L22
23,027
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/urls_controller.rb
Phcscriptcdn.Script::UrlsController.new
def new script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.build @script_url.user_id = current_user.id @script_url.org_id = current_user.org_id end
ruby
def new script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.build @script_url.user_id = current_user.id @script_url.org_id = current_user.org_id end
[ "def", "new", "script_listing", "=", "Script", "::", "Listing", ".", "find", "(", "params", "[", ":listing_id", "]", ")", "@script_url", "=", "script_listing", ".", "urls", ".", "build", "@script_url", ".", "user_id", "=", "current_user", ".", "id", "@script_url", ".", "org_id", "=", "current_user", ".", "org_id", "end" ]
NEW - Script Athors
[ "NEW", "-", "Script", "Athors" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L25-L30
23,028
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/urls_controller.rb
Phcscriptcdn.Script::UrlsController.edit
def edit script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.find(params[:id]) end
ruby
def edit script_listing = Script::Listing.find(params[:listing_id]) @script_url = script_listing.urls.find(params[:id]) end
[ "def", "edit", "script_listing", "=", "Script", "::", "Listing", ".", "find", "(", "params", "[", ":listing_id", "]", ")", "@script_url", "=", "script_listing", ".", "urls", ".", "find", "(", "params", "[", ":id", "]", ")", "end" ]
EDIT - Script Athors
[ "EDIT", "-", "Script", "Athors" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L33-L36
23,029
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/urls_controller.rb
Phcscriptcdn.Script::UrlsController.create
def create @script_listing = Script::Listing.find(params[:listing_id]) @script_url = @script_listing.urls.create(script_url_params) @script_url.user_id = current_user.id @script_url.org_id = current_user.org_id if @script_url.save redirect_to script_listing_urls_path, notice: 'Author was successfully created.' else render :new end end
ruby
def create @script_listing = Script::Listing.find(params[:listing_id]) @script_url = @script_listing.urls.create(script_url_params) @script_url.user_id = current_user.id @script_url.org_id = current_user.org_id if @script_url.save redirect_to script_listing_urls_path, notice: 'Author was successfully created.' else render :new end end
[ "def", "create", "@script_listing", "=", "Script", "::", "Listing", ".", "find", "(", "params", "[", ":listing_id", "]", ")", "@script_url", "=", "@script_listing", ".", "urls", ".", "create", "(", "script_url_params", ")", "@script_url", ".", "user_id", "=", "current_user", ".", "id", "@script_url", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_url", ".", "save", "redirect_to", "script_listing_urls_path", ",", "notice", ":", "'Author was successfully created.'", "else", "render", ":new", "end", "end" ]
POST - Script Athors
[ "POST", "-", "Script", "Athors" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L39-L49
23,030
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/urls_controller.rb
Phcscriptcdn.Script::UrlsController.destroy
def destroy @script_listing = Script::Listing.find(params[:listing_id]) @script_url = @script_listing.urls.find(params[:id]) @script_url.destroy redirect_to script_listing_urls_path, notice: 'Author was successfully destroyed.' end
ruby
def destroy @script_listing = Script::Listing.find(params[:listing_id]) @script_url = @script_listing.urls.find(params[:id]) @script_url.destroy redirect_to script_listing_urls_path, notice: 'Author was successfully destroyed.' end
[ "def", "destroy", "@script_listing", "=", "Script", "::", "Listing", ".", "find", "(", "params", "[", ":listing_id", "]", ")", "@script_url", "=", "@script_listing", ".", "urls", ".", "find", "(", "params", "[", ":id", "]", ")", "@script_url", ".", "destroy", "redirect_to", "script_listing_urls_path", ",", "notice", ":", "'Author was successfully destroyed.'", "end" ]
DELETE - Script Athors
[ "DELETE", "-", "Script", "Athors" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/urls_controller.rb#L63-L68
23,031
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/listings_controller.rb
Phcscriptcdn.Script::ListingsController.show
def show @script_listings = Script::Listing.friendly.find(params[:id]) @versions = Phcscriptcdn::ListingVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Listing') end
ruby
def show @script_listings = Script::Listing.friendly.find(params[:id]) @versions = Phcscriptcdn::ListingVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Listing') end
[ "def", "show", "@script_listings", "=", "Script", "::", "Listing", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "@versions", "=", "Phcscriptcdn", "::", "ListingVersions", ".", "where", "(", "item_id", ":", "params", "[", ":id", "]", ",", "item_type", ":", "'Phcscriptcdn::Script::Listing'", ")", "end" ]
DETAILS - Script Listings
[ "DETAILS", "-", "Script", "Listings" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/listings_controller.rb#L18-L21
23,032
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/listings_controller.rb
Phcscriptcdn.Script::ListingsController.create
def create @script_listing = Script::Listing.new(script_listing_params) @script_listing.user_id = current_user.id @script_listing.org_id = current_user.org_id if @script_listing.save redirect_to script_listings_path, notice: 'Listing was successfully created.' else render :new end end
ruby
def create @script_listing = Script::Listing.new(script_listing_params) @script_listing.user_id = current_user.id @script_listing.org_id = current_user.org_id if @script_listing.save redirect_to script_listings_path, notice: 'Listing was successfully created.' else render :new end end
[ "def", "create", "@script_listing", "=", "Script", "::", "Listing", ".", "new", "(", "script_listing_params", ")", "@script_listing", ".", "user_id", "=", "current_user", ".", "id", "@script_listing", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_listing", ".", "save", "redirect_to", "script_listings_path", ",", "notice", ":", "'Listing was successfully created.'", "else", "render", ":new", "end", "end" ]
POST - Script Listings
[ "POST", "-", "Script", "Listings" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/listings_controller.rb#L33-L42
23,033
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.put_object
def put_object(obj_path, data, opts = {}) url = obj_url(obj_path) opts[:data] = data headers = gen_headers(opts) cors_headers = gen_cors_headers(opts) headers = headers.concat(cors_headers) durability_level = opts[:durability_level] if durability_level raise ArgumentError unless durability_level > 0 headers.push([ 'Durability-Level', durability_level ]) end content_type = opts[:content_type] if content_type raise ArgumentError unless content_type.is_a? String headers.push([ 'Content-Type', content_type ]) end attempt(opts[:attempts]) do result = @client.put(url, data, headers) raise unless result.is_a? HTTP::Message return true, result.headers if [204, 304].include? result.status raise_error(result) end end
ruby
def put_object(obj_path, data, opts = {}) url = obj_url(obj_path) opts[:data] = data headers = gen_headers(opts) cors_headers = gen_cors_headers(opts) headers = headers.concat(cors_headers) durability_level = opts[:durability_level] if durability_level raise ArgumentError unless durability_level > 0 headers.push([ 'Durability-Level', durability_level ]) end content_type = opts[:content_type] if content_type raise ArgumentError unless content_type.is_a? String headers.push([ 'Content-Type', content_type ]) end attempt(opts[:attempts]) do result = @client.put(url, data, headers) raise unless result.is_a? HTTP::Message return true, result.headers if [204, 304].include? result.status raise_error(result) end end
[ "def", "put_object", "(", "obj_path", ",", "data", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "obj_path", ")", "opts", "[", ":data", "]", "=", "data", "headers", "=", "gen_headers", "(", "opts", ")", "cors_headers", "=", "gen_cors_headers", "(", "opts", ")", "headers", "=", "headers", ".", "concat", "(", "cors_headers", ")", "durability_level", "=", "opts", "[", ":durability_level", "]", "if", "durability_level", "raise", "ArgumentError", "unless", "durability_level", ">", "0", "headers", ".", "push", "(", "[", "'Durability-Level'", ",", "durability_level", "]", ")", "end", "content_type", "=", "opts", "[", ":content_type", "]", "if", "content_type", "raise", "ArgumentError", "unless", "content_type", ".", "is_a?", "String", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "content_type", "]", ")", "end", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "put", "(", "url", ",", "data", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "[", "204", ",", "304", "]", ".", "include?", "result", ".", "status", "raise_error", "(", "result", ")", "end", "end" ]
Initialize a MantaClient instance. priv_key_data is data read directly from an SSH private key (i.e. RFC 4716 format). The method can also accept several optional args: :connect_timeout, :send_timeout, :receive_timeout, :disable_ssl_verification and :attempts. The timeouts are in seconds, and :attempts determines the default number of attempts each method will make upon receiving recoverable errors. Will throw an exception if given a key whose format it doesn't understand. Uploads object data to Manta to the given path, along with a computed MD5 hash. The path must start with /<user>/stor or /<user/public. Data can be any sequence of octets. The HTTP Content-Type stored on Manta can be set with an optional :content_type argument; the default is application/octet-stream. The number of distributed replicates of an object stored in Manta can be set with an optional :durability_level; the default is 2. Returns true along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Initialize", "a", "MantaClient", "instance", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L137-L165
23,034
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.get_object
def get_object(obj_path, opts = {}) url = obj_url(obj_path) headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 return true, result.headers if method == :head sent_md5 = result.headers['Content-MD5'] received_md5 = Digest::MD5.base64digest(result.body) raise CorruptResult if sent_md5 != received_md5 return result.body, result.headers elsif result.status == 304 return nil, result.headers end raise_error(result) end end
ruby
def get_object(obj_path, opts = {}) url = obj_url(obj_path) headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 return true, result.headers if method == :head sent_md5 = result.headers['Content-MD5'] received_md5 = Digest::MD5.base64digest(result.body) raise CorruptResult if sent_md5 != received_md5 return result.body, result.headers elsif result.status == 304 return nil, result.headers end raise_error(result) end end
[ "def", "get_object", "(", "obj_path", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "obj_path", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "method", "=", "opts", "[", ":head", "]", "?", ":head", ":", ":get", "result", "=", "@client", ".", "send", "(", "method", ",", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "return", "true", ",", "result", ".", "headers", "if", "method", "==", ":head", "sent_md5", "=", "result", ".", "headers", "[", "'Content-MD5'", "]", "received_md5", "=", "Digest", "::", "MD5", ".", "base64digest", "(", "result", ".", "body", ")", "raise", "CorruptResult", "if", "sent_md5", "!=", "received_md5", "return", "result", ".", "body", ",", "result", ".", "headers", "elsif", "result", ".", "status", "==", "304", "return", "nil", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Get an object from Manta at a given path, and checks it's uncorrupted. The path must start with /<user>/stor or /<user/public and point at an actual object, as well as output objects for jobs. :head => true can optionally be passed in to do a HEAD instead of a GET. Returns the retrieved data along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Get", "an", "object", "from", "Manta", "at", "a", "given", "path", "and", "checks", "it", "s", "uncorrupted", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L180-L203
23,035
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.delete_object
def delete_object(obj_path, opts = {}) url = obj_url(obj_path) headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.delete(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
ruby
def delete_object(obj_path, opts = {}) url = obj_url(obj_path) headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.delete(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
[ "def", "delete_object", "(", "obj_path", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "obj_path", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "delete", "(", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "204", "raise_error", "(", "result", ")", "end", "end" ]
Deletes an object off Manta at a given path. The path must start with /<user>/stor or /<user/public and point at an actual object. Returns true along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Deletes", "an", "object", "off", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L217-L228
23,036
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.put_directory
def put_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=directory' ]) cors_headers = gen_cors_headers(opts) headers = headers.concat(cors_headers) attempt(opts[:attempts]) do result = @client.put(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
ruby
def put_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=directory' ]) cors_headers = gen_cors_headers(opts) headers = headers.concat(cors_headers) attempt(opts[:attempts]) do result = @client.put(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
[ "def", "put_directory", "(", "dir_path", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "dir_path", ")", "headers", "=", "gen_headers", "(", "opts", ")", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "'application/json; type=directory'", "]", ")", "cors_headers", "=", "gen_cors_headers", "(", "opts", ")", "headers", "=", "headers", ".", "concat", "(", "cors_headers", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "put", "(", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "204", "raise_error", "(", "result", ")", "end", "end" ]
Creates a directory on Manta at a given path. The path must start with /<user>/stor or /<user/public. Returns true along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Creates", "a", "directory", "on", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L241-L256
23,037
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.list_directory
def list_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) query_parameters = {} limit = opts[:limit] || MAX_LIMIT raise ArgumentError unless 0 < limit && limit <= MAX_LIMIT query_parameters[:limit] = limit marker = opts[:marker] if marker raise ArgumentError unless marker.is_a? String query_parameters[:marker] = marker end attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, query_parameters, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=directory' return true, result.headers if method == :head json_chunks = result.body.split("\n") if json_chunks.size > limit raise CorruptResult end dir_entries = json_chunks.map { |i| JSON.parse(i) } return dir_entries, result.headers end raise_error(result) end end
ruby
def list_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) query_parameters = {} limit = opts[:limit] || MAX_LIMIT raise ArgumentError unless 0 < limit && limit <= MAX_LIMIT query_parameters[:limit] = limit marker = opts[:marker] if marker raise ArgumentError unless marker.is_a? String query_parameters[:marker] = marker end attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, query_parameters, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=directory' return true, result.headers if method == :head json_chunks = result.body.split("\n") if json_chunks.size > limit raise CorruptResult end dir_entries = json_chunks.map { |i| JSON.parse(i) } return dir_entries, result.headers end raise_error(result) end end
[ "def", "list_directory", "(", "dir_path", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "dir_path", ")", "headers", "=", "gen_headers", "(", "opts", ")", "query_parameters", "=", "{", "}", "limit", "=", "opts", "[", ":limit", "]", "||", "MAX_LIMIT", "raise", "ArgumentError", "unless", "0", "<", "limit", "&&", "limit", "<=", "MAX_LIMIT", "query_parameters", "[", ":limit", "]", "=", "limit", "marker", "=", "opts", "[", ":marker", "]", "if", "marker", "raise", "ArgumentError", "unless", "marker", ".", "is_a?", "String", "query_parameters", "[", ":marker", "]", "=", "marker", "end", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "method", "=", "opts", "[", ":head", "]", "?", ":head", ":", ":get", "result", "=", "@client", ".", "send", "(", "method", ",", "url", ",", "query_parameters", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "raise", "unless", "result", ".", "headers", "[", "'Content-Type'", "]", "==", "'application/x-json-stream; type=directory'", "return", "true", ",", "result", ".", "headers", "if", "method", "==", ":head", "json_chunks", "=", "result", ".", "body", ".", "split", "(", "\"\\n\"", ")", "if", "json_chunks", ".", "size", ">", "limit", "raise", "CorruptResult", "end", "dir_entries", "=", "json_chunks", ".", "map", "{", "|", "i", "|", "JSON", ".", "parse", "(", "i", ")", "}", "return", "dir_entries", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Gets a lexicographically sorted directory listing on Manta at a given path, The path must start with /<user>/stor or /<user/public and point at an actual directory. :limit optionally changes the maximum number of entries; the default is 1000. If given :marker, an object name in the directory, returned directory entries will begin from that point. :head => true can optionally be passed in to do a HEAD instead of a GET. Returns an array of hash objects, each object representing a directory entry. Also returns the received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Gets", "a", "lexicographically", "sorted", "directory", "listing", "on", "Manta", "at", "a", "given", "path" ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L274-L313
23,038
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.find
def find(dir_path, opts = {}) regex = opts.key?(:regex) ? opts[:regex] : nil # We should always be doing GET because switching between methods is used # within this function. opts.delete(:head) begin exists = list_directory(dir_path, head: true).first rescue exists = false end return [] unless exists response = list_directory(dir_path, opts) listing = response.first listing.inject([]) do |memo, obj| if obj['type'] == 'directory' sub_dir = "#{dir_path}/#{obj['name']}" sub_search = find(sub_dir, regex: regex) memo.push(*sub_search) end if obj['type'] == 'object' file = "#{dir_path}/#{obj['name']}" if !regex || obj['name'].match(regex) memo.push file end end memo end end
ruby
def find(dir_path, opts = {}) regex = opts.key?(:regex) ? opts[:regex] : nil # We should always be doing GET because switching between methods is used # within this function. opts.delete(:head) begin exists = list_directory(dir_path, head: true).first rescue exists = false end return [] unless exists response = list_directory(dir_path, opts) listing = response.first listing.inject([]) do |memo, obj| if obj['type'] == 'directory' sub_dir = "#{dir_path}/#{obj['name']}" sub_search = find(sub_dir, regex: regex) memo.push(*sub_search) end if obj['type'] == 'object' file = "#{dir_path}/#{obj['name']}" if !regex || obj['name'].match(regex) memo.push file end end memo end end
[ "def", "find", "(", "dir_path", ",", "opts", "=", "{", "}", ")", "regex", "=", "opts", ".", "key?", "(", ":regex", ")", "?", "opts", "[", ":regex", "]", ":", "nil", "# We should always be doing GET because switching between methods is used", "# within this function.", "opts", ".", "delete", "(", ":head", ")", "begin", "exists", "=", "list_directory", "(", "dir_path", ",", "head", ":", "true", ")", ".", "first", "rescue", "exists", "=", "false", "end", "return", "[", "]", "unless", "exists", "response", "=", "list_directory", "(", "dir_path", ",", "opts", ")", "listing", "=", "response", ".", "first", "listing", ".", "inject", "(", "[", "]", ")", "do", "|", "memo", ",", "obj", "|", "if", "obj", "[", "'type'", "]", "==", "'directory'", "sub_dir", "=", "\"#{dir_path}/#{obj['name']}\"", "sub_search", "=", "find", "(", "sub_dir", ",", "regex", ":", "regex", ")", "memo", ".", "push", "(", "sub_search", ")", "end", "if", "obj", "[", "'type'", "]", "==", "'object'", "file", "=", "\"#{dir_path}/#{obj['name']}\"", "if", "!", "regex", "||", "obj", "[", "'name'", "]", ".", "match", "(", "regex", ")", "memo", ".", "push", "file", "end", "end", "memo", "end", "end" ]
Finds all objects recursively under a given directory. Optionally, a regular expression can be specified and used to filter the results returned.
[ "Finds", "all", "objects", "recursively", "under", "a", "given", "directory", ".", "Optionally", "a", "regular", "expression", "can", "be", "specified", "and", "used", "to", "filter", "the", "results", "returned", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L318-L353
23,039
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.delete_directory
def delete_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.delete(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
ruby
def delete_directory(dir_path, opts = {}) url = obj_url(dir_path) headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.delete(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
[ "def", "delete_directory", "(", "dir_path", ",", "opts", "=", "{", "}", ")", "url", "=", "obj_url", "(", "dir_path", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "delete", "(", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "204", "raise_error", "(", "result", ")", "end", "end" ]
Removes a directory from Manta at a given path. The path must start with /<user>/stor or /<user/public and point at an actual object. Returns true along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Removes", "a", "directory", "from", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L367-L378
23,040
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.put_snaplink
def put_snaplink(orig_path, link_path, opts = {}) headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=link' ], [ 'Location', obj_url(orig_path) ]) attempt(opts[:attempts]) do result = @client.put(obj_url(link_path), nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
ruby
def put_snaplink(orig_path, link_path, opts = {}) headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=link' ], [ 'Location', obj_url(orig_path) ]) attempt(opts[:attempts]) do result = @client.put(obj_url(link_path), nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
[ "def", "put_snaplink", "(", "orig_path", ",", "link_path", ",", "opts", "=", "{", "}", ")", "headers", "=", "gen_headers", "(", "opts", ")", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "'application/json; type=link'", "]", ",", "[", "'Location'", ",", "obj_url", "(", "orig_path", ")", "]", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "put", "(", "obj_url", "(", "link_path", ")", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "204", "raise_error", "(", "result", ")", "end", "end" ]
Creates a snaplink from one object in Manta at a given path to a different path. Both paths should start with /<user>/stor or /<user/public. Returns true along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Creates", "a", "snaplink", "from", "one", "object", "in", "Manta", "at", "a", "given", "path", "to", "a", "different", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L392-L404
23,041
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.create_job
def create_job(job, opts = {}) raise ArgumentError unless job[:phases] || job['phases'] headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=job' ]) data = job.to_json attempt(opts[:attempts]) do result = @client.post(job_url(), data, headers) raise unless result.is_a? HTTP::Message if result.status == 201 location = result.headers['Location'] raise unless location return location, result.headers end raise_error(result) end end
ruby
def create_job(job, opts = {}) raise ArgumentError unless job[:phases] || job['phases'] headers = gen_headers(opts) headers.push([ 'Content-Type', 'application/json; type=job' ]) data = job.to_json attempt(opts[:attempts]) do result = @client.post(job_url(), data, headers) raise unless result.is_a? HTTP::Message if result.status == 201 location = result.headers['Location'] raise unless location return location, result.headers end raise_error(result) end end
[ "def", "create_job", "(", "job", ",", "opts", "=", "{", "}", ")", "raise", "ArgumentError", "unless", "job", "[", ":phases", "]", "||", "job", "[", "'phases'", "]", "headers", "=", "gen_headers", "(", "opts", ")", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "'application/json; type=job'", "]", ")", "data", "=", "job", ".", "to_json", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "post", "(", "job_url", "(", ")", ",", "data", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "201", "location", "=", "result", ".", "headers", "[", "'Location'", "]", "raise", "unless", "location", "return", "location", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Creates a job in Manta. The job must be a hash, containing at minimum a :phases key. See README.md or the Manta docs to see the format and options for setting up a job on Manta; this method effectively just converts the job hash to JSON and sends to the Manta service. Returns the path for the new job, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Creates", "a", "job", "in", "Manta", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L420-L440
23,042
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.get_job
def get_job(job_path, opts = {}) url = job_url(job_path, '/live/status') headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/json' return true, result.headers if method == :head job = JSON.parse(result.body) return job, result.headers end raise_error(result) end end
ruby
def get_job(job_path, opts = {}) url = job_url(job_path, '/live/status') headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/json' return true, result.headers if method == :head job = JSON.parse(result.body) return job, result.headers end raise_error(result) end end
[ "def", "get_job", "(", "job_path", ",", "opts", "=", "{", "}", ")", "url", "=", "job_url", "(", "job_path", ",", "'/live/status'", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "method", "=", "opts", "[", ":head", "]", "?", ":head", ":", ":get", "result", "=", "@client", ".", "send", "(", "method", ",", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "raise", "unless", "result", ".", "headers", "[", "'Content-Type'", "]", "==", "'application/json'", "return", "true", ",", "result", ".", "headers", "if", "method", "==", ":head", "job", "=", "JSON", ".", "parse", "(", "result", ".", "body", ")", "return", "job", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Gets various information about a job in Manta at a given path. The path must start with /<user>/jobs/<job UUID> and point at an actual job. :head => true can optionally be passed in to do a HEAD instead of a GET. Returns a hash with job information, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Gets", "various", "information", "about", "a", "job", "in", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L454-L474
23,043
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.get_job_errors
def get_job_errors(job_path, opts = {}) url = job_url(job_path, '/live/err') headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=job-error' return true, result.headers if method == :head json_chunks = result.body.split("\n") errors = json_chunks.map { |i| JSON.parse(i) } return errors, result.headers end raise_error(result) end end
ruby
def get_job_errors(job_path, opts = {}) url = job_url(job_path, '/live/err') headers = gen_headers(opts) attempt(opts[:attempts]) do method = opts[:head] ? :head : :get result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=job-error' return true, result.headers if method == :head json_chunks = result.body.split("\n") errors = json_chunks.map { |i| JSON.parse(i) } return errors, result.headers end raise_error(result) end end
[ "def", "get_job_errors", "(", "job_path", ",", "opts", "=", "{", "}", ")", "url", "=", "job_url", "(", "job_path", ",", "'/live/err'", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "method", "=", "opts", "[", ":head", "]", "?", ":head", ":", ":get", "result", "=", "@client", ".", "send", "(", "method", ",", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "raise", "unless", "result", ".", "headers", "[", "'Content-Type'", "]", "==", "'application/x-json-stream; type=job-error'", "return", "true", ",", "result", ".", "headers", "if", "method", "==", ":head", "json_chunks", "=", "result", ".", "body", ".", "split", "(", "\"\\n\"", ")", "errors", "=", "json_chunks", ".", "map", "{", "|", "i", "|", "JSON", ".", "parse", "(", "i", ")", "}", "return", "errors", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Gets errors that occured during the execution of a job in Manta at a given path. The path must start with /<user>/jobs/<job UUID> and point at an actual job. :head => true can optionally be passed in to do a HEAD instead of a GET. Returns an array of hashes, each hash containing information about an error; this information is best-effort by Manta, so it may not be complete. Also returns received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Gets", "errors", "that", "occured", "during", "the", "execution", "of", "a", "job", "in", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L491-L514
23,044
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.cancel_job
def cancel_job(job_path, opts = {}) url = job_url(job_path, 'live/cancel') body = '{}' opts[:data] = body headers = gen_headers(opts) headers << [ 'Accept', 'application/json' ] headers << [ 'Content-Type', 'application/json'] headers << [ 'Content-Length', body.bytesize ] args = { header: headers, body: body } attempt(opts[:attempts]) do result = @client.post(url, args) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 202 raise_error(result) end end
ruby
def cancel_job(job_path, opts = {}) url = job_url(job_path, 'live/cancel') body = '{}' opts[:data] = body headers = gen_headers(opts) headers << [ 'Accept', 'application/json' ] headers << [ 'Content-Type', 'application/json'] headers << [ 'Content-Length', body.bytesize ] args = { header: headers, body: body } attempt(opts[:attempts]) do result = @client.post(url, args) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 202 raise_error(result) end end
[ "def", "cancel_job", "(", "job_path", ",", "opts", "=", "{", "}", ")", "url", "=", "job_url", "(", "job_path", ",", "'live/cancel'", ")", "body", "=", "'{}'", "opts", "[", ":data", "]", "=", "body", "headers", "=", "gen_headers", "(", "opts", ")", "headers", "<<", "[", "'Accept'", ",", "'application/json'", "]", "headers", "<<", "[", "'Content-Type'", ",", "'application/json'", "]", "headers", "<<", "[", "'Content-Length'", ",", "body", ".", "bytesize", "]", "args", "=", "{", "header", ":", "headers", ",", "body", ":", "body", "}", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "post", "(", "url", ",", "args", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "202", "raise_error", "(", "result", ")", "end", "end" ]
Cancels a running job in Manta at a given path. The path must start with /<user>/jobs/<job UUID> and point at an actual job. Returns true, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Cancels", "a", "running", "job", "in", "Manta", "at", "a", "given", "path", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L527-L552
23,045
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.add_job_keys
def add_job_keys(job_path, obj_paths, opts = {}) url = job_url(job_path, '/live/in') headers = gen_headers(opts) headers.push([ 'Content-Type', 'text/plain' ]) data = obj_paths.join("\n") attempt(opts[:attempts]) do result = @client.post(url, data, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
ruby
def add_job_keys(job_path, obj_paths, opts = {}) url = job_url(job_path, '/live/in') headers = gen_headers(opts) headers.push([ 'Content-Type', 'text/plain' ]) data = obj_paths.join("\n") attempt(opts[:attempts]) do result = @client.post(url, data, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 204 raise_error(result) end end
[ "def", "add_job_keys", "(", "job_path", ",", "obj_paths", ",", "opts", "=", "{", "}", ")", "url", "=", "job_url", "(", "job_path", ",", "'/live/in'", ")", "headers", "=", "gen_headers", "(", "opts", ")", "headers", ".", "push", "(", "[", "'Content-Type'", ",", "'text/plain'", "]", ")", "data", "=", "obj_paths", ".", "join", "(", "\"\\n\"", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "post", "(", "url", ",", "data", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "204", "raise_error", "(", "result", ")", "end", "end" ]
Adds objects for a running job in Manta to process. The job_path must start with /<user>/jobs/<job UUID> and point at an actual running job. The obj_paths must be an array of paths, starting with /<user>/stor or /<user>/public, pointing at actual objects. Returns true, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Adds", "objects", "for", "a", "running", "job", "in", "Manta", "to", "process", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L567-L581
23,046
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.end_job_input
def end_job_input(job_path, opts = {}) url = job_url(job_path, '/live/in/end') headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.post(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 202 raise_error(result) end end
ruby
def end_job_input(job_path, opts = {}) url = job_url(job_path, '/live/in/end') headers = gen_headers(opts) attempt(opts[:attempts]) do result = @client.post(url, nil, headers) raise unless result.is_a? HTTP::Message return true, result.headers if result.status == 202 raise_error(result) end end
[ "def", "end_job_input", "(", "job_path", ",", "opts", "=", "{", "}", ")", "url", "=", "job_url", "(", "job_path", ",", "'/live/in/end'", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "result", "=", "@client", ".", "post", "(", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "return", "true", ",", "result", ".", "headers", "if", "result", ".", "status", "==", "202", "raise_error", "(", "result", ")", "end", "end" ]
Inform Manta that no more objects will be added for processing by a job, and that the job should finish all phases and terminate. The job_path must start with /<user>/jobs/<job UUID> and point at an actual running job. Returns true, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Inform", "Manta", "that", "no", "more", "objects", "will", "be", "added", "for", "processing", "by", "a", "job", "and", "that", "the", "job", "should", "finish", "all", "phases", "and", "terminate", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L596-L607
23,047
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.list_jobs
def list_jobs(state, opts = {}) raise ArgumentError unless [:all, :running, :done].include? state state = nil if state == :all headers = gen_headers(opts) attempt(opts[:attempts]) do # method = opts[:head] ? :head : :get method = :get # until added to Manta service result = @client.send(method, job_url(), { :state => state }, headers) raise unless result.is_a? HTTP::Message if result.status == 200 # return true, result.headers if method == :head return [], result.headers if result.body.size == 0 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=job' json_chunks = result.body.split("\n") job_entries = json_chunks.map { |i| JSON.parse(i) } return job_entries, result.headers end raise_error(result) end end
ruby
def list_jobs(state, opts = {}) raise ArgumentError unless [:all, :running, :done].include? state state = nil if state == :all headers = gen_headers(opts) attempt(opts[:attempts]) do # method = opts[:head] ? :head : :get method = :get # until added to Manta service result = @client.send(method, job_url(), { :state => state }, headers) raise unless result.is_a? HTTP::Message if result.status == 200 # return true, result.headers if method == :head return [], result.headers if result.body.size == 0 raise unless result.headers['Content-Type'] == 'application/x-json-stream; type=job' json_chunks = result.body.split("\n") job_entries = json_chunks.map { |i| JSON.parse(i) } return job_entries, result.headers end raise_error(result) end end
[ "def", "list_jobs", "(", "state", ",", "opts", "=", "{", "}", ")", "raise", "ArgumentError", "unless", "[", ":all", ",", ":running", ",", ":done", "]", ".", "include?", "state", "state", "=", "nil", "if", "state", "==", ":all", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "# method = opts[:head] ? :head : :get", "method", "=", ":get", "# until added to Manta service", "result", "=", "@client", ".", "send", "(", "method", ",", "job_url", "(", ")", ",", "{", ":state", "=>", "state", "}", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "# return true, result.headers if method == :head", "return", "[", "]", ",", "result", ".", "headers", "if", "result", ".", "body", ".", "size", "==", "0", "raise", "unless", "result", ".", "headers", "[", "'Content-Type'", "]", "==", "'application/x-json-stream; type=job'", "json_chunks", "=", "result", ".", "body", ".", "split", "(", "\"\\n\"", ")", "job_entries", "=", "json_chunks", ".", "map", "{", "|", "i", "|", "JSON", ".", "parse", "(", "i", ")", "}", "return", "job_entries", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Get lists of Manta jobs. The state indicates which kind of jobs to return. :running is for jobs that are currently processing, :done and :all should be obvious. Be careful of the latter two if you've run a lot of jobs -- the list could be quite long. Returns an array of hashes, each hash containing some information about a job. Also returns received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Get", "lists", "of", "Manta", "jobs", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L673-L700
23,048
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.gen_signed_url
def gen_signed_url(expires, method, path, args=[]) methods = method.is_a?(Array) ? method : [method] raise ArgumentError unless (methods - [:get, :put, :post, :delete, :options]).empty? raise ArgumentError unless path =~ OBJ_PATH_REGEX key_id = '/%s/keys/%s' % [user_path, @fingerprint] args.push([ 'expires', expires.to_i ]) args.push([ 'algorithm', @digest_name ]) args.push([ 'keyId', key_id ]) method = methods.map {|m| m.to_s.upcase }.sort.join(",") host = URI.encode(@host.split('/').last) path = URI.encode(path) args.push(['method', method]) if methods.count > 1 encoded_args = args.sort.map do |key, val| # to comply with RFC 3986 CGI.escape(key.to_s) + '=' + CGI.escape(val.to_s) end.join('&') plaintext = "#{method}\n#{host}\n#{path}\n#{encoded_args}" signature = @priv_key.sign(@digest, plaintext) encoded_signature = CGI.escape(Base64.strict_encode64(signature)) host + path + '?' + encoded_args + '&signature=' + encoded_signature end
ruby
def gen_signed_url(expires, method, path, args=[]) methods = method.is_a?(Array) ? method : [method] raise ArgumentError unless (methods - [:get, :put, :post, :delete, :options]).empty? raise ArgumentError unless path =~ OBJ_PATH_REGEX key_id = '/%s/keys/%s' % [user_path, @fingerprint] args.push([ 'expires', expires.to_i ]) args.push([ 'algorithm', @digest_name ]) args.push([ 'keyId', key_id ]) method = methods.map {|m| m.to_s.upcase }.sort.join(",") host = URI.encode(@host.split('/').last) path = URI.encode(path) args.push(['method', method]) if methods.count > 1 encoded_args = args.sort.map do |key, val| # to comply with RFC 3986 CGI.escape(key.to_s) + '=' + CGI.escape(val.to_s) end.join('&') plaintext = "#{method}\n#{host}\n#{path}\n#{encoded_args}" signature = @priv_key.sign(@digest, plaintext) encoded_signature = CGI.escape(Base64.strict_encode64(signature)) host + path + '?' + encoded_args + '&signature=' + encoded_signature end
[ "def", "gen_signed_url", "(", "expires", ",", "method", ",", "path", ",", "args", "=", "[", "]", ")", "methods", "=", "method", ".", "is_a?", "(", "Array", ")", "?", "method", ":", "[", "method", "]", "raise", "ArgumentError", "unless", "(", "methods", "-", "[", ":get", ",", ":put", ",", ":post", ",", ":delete", ",", ":options", "]", ")", ".", "empty?", "raise", "ArgumentError", "unless", "path", "=~", "OBJ_PATH_REGEX", "key_id", "=", "'/%s/keys/%s'", "%", "[", "user_path", ",", "@fingerprint", "]", "args", ".", "push", "(", "[", "'expires'", ",", "expires", ".", "to_i", "]", ")", "args", ".", "push", "(", "[", "'algorithm'", ",", "@digest_name", "]", ")", "args", ".", "push", "(", "[", "'keyId'", ",", "key_id", "]", ")", "method", "=", "methods", ".", "map", "{", "|", "m", "|", "m", ".", "to_s", ".", "upcase", "}", ".", "sort", ".", "join", "(", "\",\"", ")", "host", "=", "URI", ".", "encode", "(", "@host", ".", "split", "(", "'/'", ")", ".", "last", ")", "path", "=", "URI", ".", "encode", "(", "path", ")", "args", ".", "push", "(", "[", "'method'", ",", "method", "]", ")", "if", "methods", ".", "count", ">", "1", "encoded_args", "=", "args", ".", "sort", ".", "map", "do", "|", "key", ",", "val", "|", "# to comply with RFC 3986", "CGI", ".", "escape", "(", "key", ".", "to_s", ")", "+", "'='", "+", "CGI", ".", "escape", "(", "val", ".", "to_s", ")", "end", ".", "join", "(", "'&'", ")", "plaintext", "=", "\"#{method}\\n#{host}\\n#{path}\\n#{encoded_args}\"", "signature", "=", "@priv_key", ".", "sign", "(", "@digest", ",", "plaintext", ")", "encoded_signature", "=", "CGI", ".", "escape", "(", "Base64", ".", "strict_encode64", "(", "signature", ")", ")", "host", "+", "path", "+", "'?'", "+", "encoded_args", "+", "'&signature='", "+", "encoded_signature", "end" ]
Generates a signed URL which can be used by unauthenticated users to make a request to Manta at the given path. This is typically used to GET an object, or to make a CORS preflighted PUT request. expires is a Time object or integer representing time after epoch; this determines how long the signed URL will be valid for. The method is either a single HTTP method (:get, :put, :post, :delete, :options) or a list of such methods that the signed URL is allowed to be used for. The path must start with /<user>/stor. Lastly, the optional args is an array containing pairs of query args that will be appended at the end of the URL. The returned URL is signed, and can be used either over HTTP or HTTPS until it reaches the expiry date.
[ "Generates", "a", "signed", "URL", "which", "can", "be", "used", "by", "unauthenticated", "users", "to", "make", "a", "request", "to", "Manta", "at", "the", "given", "path", ".", "This", "is", "typically", "used", "to", "GET", "an", "object", "or", "to", "make", "a", "CORS", "preflighted", "PUT", "request", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L717-L744
23,049
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.get_job_state_streams
def get_job_state_streams(type, path, opts) raise ArgumentError unless [:in, :out, :fail].include? type url = job_url(path, '/live/' + type.to_s) headers = gen_headers(opts) attempt(opts[:attempts]) do #method = opts[:head] ? :head : :get method = :get # until added to Manta service result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'text/plain' return true, result.headers if method == :head paths = result.body.split("\n") return paths, result.headers end raise_error(result) end end
ruby
def get_job_state_streams(type, path, opts) raise ArgumentError unless [:in, :out, :fail].include? type url = job_url(path, '/live/' + type.to_s) headers = gen_headers(opts) attempt(opts[:attempts]) do #method = opts[:head] ? :head : :get method = :get # until added to Manta service result = @client.send(method, url, nil, headers) raise unless result.is_a? HTTP::Message if result.status == 200 raise unless result.headers['Content-Type'] == 'text/plain' return true, result.headers if method == :head paths = result.body.split("\n") return paths, result.headers end raise_error(result) end end
[ "def", "get_job_state_streams", "(", "type", ",", "path", ",", "opts", ")", "raise", "ArgumentError", "unless", "[", ":in", ",", ":out", ",", ":fail", "]", ".", "include?", "type", "url", "=", "job_url", "(", "path", ",", "'/live/'", "+", "type", ".", "to_s", ")", "headers", "=", "gen_headers", "(", "opts", ")", "attempt", "(", "opts", "[", ":attempts", "]", ")", "do", "#method = opts[:head] ? :head : :get", "method", "=", ":get", "# until added to Manta service", "result", "=", "@client", ".", "send", "(", "method", ",", "url", ",", "nil", ",", "headers", ")", "raise", "unless", "result", ".", "is_a?", "HTTP", "::", "Message", "if", "result", ".", "status", "==", "200", "raise", "unless", "result", ".", "headers", "[", "'Content-Type'", "]", "==", "'text/plain'", "return", "true", ",", "result", ".", "headers", "if", "method", "==", ":head", "paths", "=", "result", ".", "body", ".", "split", "(", "\"\\n\"", ")", "return", "paths", ",", "result", ".", "headers", "end", "raise_error", "(", "result", ")", "end", "end" ]
Fetch lists of objects that have a given status. type takes one of three values (:in, :out, fail), path must start with /<user>/jobs/<job UUID> and point at an actual job. Returns an array of object paths, along with received HTTP headers. If there was an unrecoverable error, throws an exception. On connection or corruption errors, more attempts will be made; the number of attempts can be altered by passing in :attempts.
[ "Fetch", "lists", "of", "objects", "that", "have", "a", "given", "status", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L779-L800
23,050
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.job_url
def job_url(*args) path = if args.size == 0 @job_base else raise ArgumentError unless args.first =~ JOB_PATH_REGEX args.join('/') end URI.encode(@host + path) end
ruby
def job_url(*args) path = if args.size == 0 @job_base else raise ArgumentError unless args.first =~ JOB_PATH_REGEX args.join('/') end URI.encode(@host + path) end
[ "def", "job_url", "(", "*", "args", ")", "path", "=", "if", "args", ".", "size", "==", "0", "@job_base", "else", "raise", "ArgumentError", "unless", "args", ".", "first", "=~", "JOB_PATH_REGEX", "args", ".", "join", "(", "'/'", ")", "end", "URI", ".", "encode", "(", "@host", "+", "path", ")", "end" ]
Returns a full URL for a given path to a job.
[ "Returns", "a", "full", "URL", "for", "a", "given", "path", "to", "a", "job", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L814-L823
23,051
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.gen_headers
def gen_headers(opts) now = Time.now.httpdate sig = gen_signature('date: ' + now) headers = [[ 'Date', now ], [ 'Authorization', sig ], [ 'User-Agent', HTTP_AGENT ], [ 'Accept-Version', '~1.0' ]] # headers for conditional requests (dates) for arg, conditional in [[:if_modified_since, 'If-Modified-Since' ], [:if_unmodified_since, 'If-Unmodified-Since']] date = opts[arg] next unless date date = Time.parse(date.to_s) unless date.kind_of? Time headers.push([conditional, date]) end # headers for conditional requests (etags) for arg, conditional in [[:if_match, 'If-Match' ], [:if_none_match, 'If-None-Match']] etag = opts[arg] next unless etag raise ArgumentError unless etag.kind_of? String headers.push([conditional, etag]) end origin = opts[:origin] if origin raise ArgumentError unless origin == 'null' || origin =~ CORS_ORIGIN_REGEX headers.push([ 'Origin', origin ]) end custom_headers = opts.keys.select { |key| key.to_s.start_with? 'm_' } unless custom_headers.empty? headers += custom_headers.map do |header_key| [ symbol_to_header(header_key), opts[header_key] ] end end # add md5 hash when sending data data = opts[:data] if data md5 = Digest::MD5.base64digest(data) headers.push([ 'Content-MD5', md5 ]) end return headers end
ruby
def gen_headers(opts) now = Time.now.httpdate sig = gen_signature('date: ' + now) headers = [[ 'Date', now ], [ 'Authorization', sig ], [ 'User-Agent', HTTP_AGENT ], [ 'Accept-Version', '~1.0' ]] # headers for conditional requests (dates) for arg, conditional in [[:if_modified_since, 'If-Modified-Since' ], [:if_unmodified_since, 'If-Unmodified-Since']] date = opts[arg] next unless date date = Time.parse(date.to_s) unless date.kind_of? Time headers.push([conditional, date]) end # headers for conditional requests (etags) for arg, conditional in [[:if_match, 'If-Match' ], [:if_none_match, 'If-None-Match']] etag = opts[arg] next unless etag raise ArgumentError unless etag.kind_of? String headers.push([conditional, etag]) end origin = opts[:origin] if origin raise ArgumentError unless origin == 'null' || origin =~ CORS_ORIGIN_REGEX headers.push([ 'Origin', origin ]) end custom_headers = opts.keys.select { |key| key.to_s.start_with? 'm_' } unless custom_headers.empty? headers += custom_headers.map do |header_key| [ symbol_to_header(header_key), opts[header_key] ] end end # add md5 hash when sending data data = opts[:data] if data md5 = Digest::MD5.base64digest(data) headers.push([ 'Content-MD5', md5 ]) end return headers end
[ "def", "gen_headers", "(", "opts", ")", "now", "=", "Time", ".", "now", ".", "httpdate", "sig", "=", "gen_signature", "(", "'date: '", "+", "now", ")", "headers", "=", "[", "[", "'Date'", ",", "now", "]", ",", "[", "'Authorization'", ",", "sig", "]", ",", "[", "'User-Agent'", ",", "HTTP_AGENT", "]", ",", "[", "'Accept-Version'", ",", "'~1.0'", "]", "]", "# headers for conditional requests (dates)", "for", "arg", ",", "conditional", "in", "[", "[", ":if_modified_since", ",", "'If-Modified-Since'", "]", ",", "[", ":if_unmodified_since", ",", "'If-Unmodified-Since'", "]", "]", "date", "=", "opts", "[", "arg", "]", "next", "unless", "date", "date", "=", "Time", ".", "parse", "(", "date", ".", "to_s", ")", "unless", "date", ".", "kind_of?", "Time", "headers", ".", "push", "(", "[", "conditional", ",", "date", "]", ")", "end", "# headers for conditional requests (etags)", "for", "arg", ",", "conditional", "in", "[", "[", ":if_match", ",", "'If-Match'", "]", ",", "[", ":if_none_match", ",", "'If-None-Match'", "]", "]", "etag", "=", "opts", "[", "arg", "]", "next", "unless", "etag", "raise", "ArgumentError", "unless", "etag", ".", "kind_of?", "String", "headers", ".", "push", "(", "[", "conditional", ",", "etag", "]", ")", "end", "origin", "=", "opts", "[", ":origin", "]", "if", "origin", "raise", "ArgumentError", "unless", "origin", "==", "'null'", "||", "origin", "=~", "CORS_ORIGIN_REGEX", "headers", ".", "push", "(", "[", "'Origin'", ",", "origin", "]", ")", "end", "custom_headers", "=", "opts", ".", "keys", ".", "select", "{", "|", "key", "|", "key", ".", "to_s", ".", "start_with?", "'m_'", "}", "unless", "custom_headers", ".", "empty?", "headers", "+=", "custom_headers", ".", "map", "do", "|", "header_key", "|", "[", "symbol_to_header", "(", "header_key", ")", ",", "opts", "[", "header_key", "]", "]", "end", "end", "# add md5 hash when sending data", "data", "=", "opts", "[", ":data", "]", "if", "data", "md5", "=", "Digest", "::", "MD5", ".", "base64digest", "(", "data", ")", "headers", ".", "push", "(", "[", "'Content-MD5'", ",", "md5", "]", ")", "end", "return", "headers", "end" ]
Creates headers to be given to the HTTP client and sent to the Manta service. The most important is the Authorization header, without which none of this class would work.
[ "Creates", "headers", "to", "be", "given", "to", "the", "HTTP", "client", "and", "sent", "to", "the", "Manta", "service", ".", "The", "most", "important", "is", "the", "Authorization", "header", "without", "which", "none", "of", "this", "class", "would", "work", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L863-L914
23,052
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.gen_cors_headers
def gen_cors_headers(opts) headers = [] allow_credentials = opts[:access_control_allow_credentials] if allow_credentials allow_credentials = allow_credentials.to_s raise ArgumentError unless allow_credentials == 'true' || allow_credentials == 'false' headers.push([ 'Access-Control-Allow-Credentials', allow_credentials ]) end allow_headers = opts[:access_control_allow_headers] if allow_headers raise ArgumentError unless allow_headers =~ CORS_HEADERS_REGEX allow_headers = allow_headers.split(', ').map(&:downcase).sort.join(', ') headers.push([ 'Access-Control-Allow-Headers', allow_headers ]) end allow_methods = opts[:access_control_allow_methods] if allow_methods raise ArgumentError unless allow_methods.kind_of? String unknown_methods = allow_methods.split(', ').reject do |str| CORS_METHODS.include? str end raise ArgumentError unless unknown_methods.size == 0 headers.push([ 'Access-Control-Allow-Methods', allow_methods ]) end allow_origin = opts[:access_control_allow_origin] if allow_origin raise ArgumentError unless allow_origin.kind_of? String raise ArgumentError unless allow_origin == '*' || allow_origin == 'null' || allow_origin =~ CORS_ORIGIN_REGEX headers.push([ 'Access-Control-Allow-Origin', allow_origin ]) end expose_headers = opts[:access_control_expose_headers] if expose_headers raise ArgumentError unless expose_headers =~ CORS_HEADERS_REGEX expose_headers = expose_headers.split(', ').map(&:downcase).sort.join(', ') headers.push([ 'Access-Control-Expose-Headers', expose_headers ]) end max_age = opts[:access_control_max_age] if max_age raise ArgumentError unless max_age.kind_of?(Integer) && max_age >= 0 headers.push([ 'Access-Control-Max-Age', max_age.to_s ]) end headers end
ruby
def gen_cors_headers(opts) headers = [] allow_credentials = opts[:access_control_allow_credentials] if allow_credentials allow_credentials = allow_credentials.to_s raise ArgumentError unless allow_credentials == 'true' || allow_credentials == 'false' headers.push([ 'Access-Control-Allow-Credentials', allow_credentials ]) end allow_headers = opts[:access_control_allow_headers] if allow_headers raise ArgumentError unless allow_headers =~ CORS_HEADERS_REGEX allow_headers = allow_headers.split(', ').map(&:downcase).sort.join(', ') headers.push([ 'Access-Control-Allow-Headers', allow_headers ]) end allow_methods = opts[:access_control_allow_methods] if allow_methods raise ArgumentError unless allow_methods.kind_of? String unknown_methods = allow_methods.split(', ').reject do |str| CORS_METHODS.include? str end raise ArgumentError unless unknown_methods.size == 0 headers.push([ 'Access-Control-Allow-Methods', allow_methods ]) end allow_origin = opts[:access_control_allow_origin] if allow_origin raise ArgumentError unless allow_origin.kind_of? String raise ArgumentError unless allow_origin == '*' || allow_origin == 'null' || allow_origin =~ CORS_ORIGIN_REGEX headers.push([ 'Access-Control-Allow-Origin', allow_origin ]) end expose_headers = opts[:access_control_expose_headers] if expose_headers raise ArgumentError unless expose_headers =~ CORS_HEADERS_REGEX expose_headers = expose_headers.split(', ').map(&:downcase).sort.join(', ') headers.push([ 'Access-Control-Expose-Headers', expose_headers ]) end max_age = opts[:access_control_max_age] if max_age raise ArgumentError unless max_age.kind_of?(Integer) && max_age >= 0 headers.push([ 'Access-Control-Max-Age', max_age.to_s ]) end headers end
[ "def", "gen_cors_headers", "(", "opts", ")", "headers", "=", "[", "]", "allow_credentials", "=", "opts", "[", ":access_control_allow_credentials", "]", "if", "allow_credentials", "allow_credentials", "=", "allow_credentials", ".", "to_s", "raise", "ArgumentError", "unless", "allow_credentials", "==", "'true'", "||", "allow_credentials", "==", "'false'", "headers", ".", "push", "(", "[", "'Access-Control-Allow-Credentials'", ",", "allow_credentials", "]", ")", "end", "allow_headers", "=", "opts", "[", ":access_control_allow_headers", "]", "if", "allow_headers", "raise", "ArgumentError", "unless", "allow_headers", "=~", "CORS_HEADERS_REGEX", "allow_headers", "=", "allow_headers", ".", "split", "(", "', '", ")", ".", "map", "(", ":downcase", ")", ".", "sort", ".", "join", "(", "', '", ")", "headers", ".", "push", "(", "[", "'Access-Control-Allow-Headers'", ",", "allow_headers", "]", ")", "end", "allow_methods", "=", "opts", "[", ":access_control_allow_methods", "]", "if", "allow_methods", "raise", "ArgumentError", "unless", "allow_methods", ".", "kind_of?", "String", "unknown_methods", "=", "allow_methods", ".", "split", "(", "', '", ")", ".", "reject", "do", "|", "str", "|", "CORS_METHODS", ".", "include?", "str", "end", "raise", "ArgumentError", "unless", "unknown_methods", ".", "size", "==", "0", "headers", ".", "push", "(", "[", "'Access-Control-Allow-Methods'", ",", "allow_methods", "]", ")", "end", "allow_origin", "=", "opts", "[", ":access_control_allow_origin", "]", "if", "allow_origin", "raise", "ArgumentError", "unless", "allow_origin", ".", "kind_of?", "String", "raise", "ArgumentError", "unless", "allow_origin", "==", "'*'", "||", "allow_origin", "==", "'null'", "||", "allow_origin", "=~", "CORS_ORIGIN_REGEX", "headers", ".", "push", "(", "[", "'Access-Control-Allow-Origin'", ",", "allow_origin", "]", ")", "end", "expose_headers", "=", "opts", "[", ":access_control_expose_headers", "]", "if", "expose_headers", "raise", "ArgumentError", "unless", "expose_headers", "=~", "CORS_HEADERS_REGEX", "expose_headers", "=", "expose_headers", ".", "split", "(", "', '", ")", ".", "map", "(", ":downcase", ")", ".", "sort", ".", "join", "(", "', '", ")", "headers", ".", "push", "(", "[", "'Access-Control-Expose-Headers'", ",", "expose_headers", "]", ")", "end", "max_age", "=", "opts", "[", ":access_control_max_age", "]", "if", "max_age", "raise", "ArgumentError", "unless", "max_age", ".", "kind_of?", "(", "Integer", ")", "&&", "max_age", ">=", "0", "headers", ".", "push", "(", "[", "'Access-Control-Max-Age'", ",", "max_age", ".", "to_s", "]", ")", "end", "headers", "end" ]
Do some sanity checks and create CORS-related headers For more details, see http://www.w3.org/TR/cors/ and https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Expose-Headers
[ "Do", "some", "sanity", "checks", "and", "create", "CORS", "-", "related", "headers" ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L922-L975
23,053
joyent/ruby-manta
lib/ruby-manta/manta_client.rb
RubyManta.MantaClient.gen_signature
def gen_signature(data) raise ArgumentError unless data sig = @priv_key.sign(@digest, data) base64sig = Base64.strict_encode64(sig) return HTTP_SIGNATURE % [user_path, @fingerprint, @digest_name, base64sig] end
ruby
def gen_signature(data) raise ArgumentError unless data sig = @priv_key.sign(@digest, data) base64sig = Base64.strict_encode64(sig) return HTTP_SIGNATURE % [user_path, @fingerprint, @digest_name, base64sig] end
[ "def", "gen_signature", "(", "data", ")", "raise", "ArgumentError", "unless", "data", "sig", "=", "@priv_key", ".", "sign", "(", "@digest", ",", "data", ")", "base64sig", "=", "Base64", ".", "strict_encode64", "(", "sig", ")", "return", "HTTP_SIGNATURE", "%", "[", "user_path", ",", "@fingerprint", ",", "@digest_name", ",", "base64sig", "]", "end" ]
Given a chunk of data, creates an HTTP signature which the Manta service understands and uses for authentication.
[ "Given", "a", "chunk", "of", "data", "creates", "an", "HTTP", "signature", "which", "the", "Manta", "service", "understands", "and", "uses", "for", "authentication", "." ]
56fc959a6c0143a17a379cc27404b59f996f1f2d
https://github.com/joyent/ruby-manta/blob/56fc959a6c0143a17a379cc27404b59f996f1f2d/lib/ruby-manta/manta_client.rb#L979-L986
23,054
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/authors_controller.rb
Phcscriptcdn.Script::AuthorsController.show
def show @script_authors = Script::Author.friendly.find(params[:id]) @versions = Phcscriptcdn::AuthorVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Author') end
ruby
def show @script_authors = Script::Author.friendly.find(params[:id]) @versions = Phcscriptcdn::AuthorVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Author') end
[ "def", "show", "@script_authors", "=", "Script", "::", "Author", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "@versions", "=", "Phcscriptcdn", "::", "AuthorVersions", ".", "where", "(", "item_id", ":", "params", "[", ":id", "]", ",", "item_type", ":", "'Phcscriptcdn::Script::Author'", ")", "end" ]
DETAILS - Script Author
[ "DETAILS", "-", "Script", "Author" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L18-L21
23,055
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/authors_controller.rb
Phcscriptcdn.Script::AuthorsController.new
def new @script_author = Script::Author.new @script_author.user_id = current_user.id @script_author.org_id = current_user.org_id end
ruby
def new @script_author = Script::Author.new @script_author.user_id = current_user.id @script_author.org_id = current_user.org_id end
[ "def", "new", "@script_author", "=", "Script", "::", "Author", ".", "new", "@script_author", ".", "user_id", "=", "current_user", ".", "id", "@script_author", ".", "org_id", "=", "current_user", ".", "org_id", "end" ]
NEW - Script Author
[ "NEW", "-", "Script", "Author" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L24-L28
23,056
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/authors_controller.rb
Phcscriptcdn.Script::AuthorsController.create
def create @script_author = Script::Author.new(script_author_params) @script_author.user_id = current_user.id @script_author.org_id = current_user.org_id if @script_author.save redirect_to script_authors_url, notice: 'Author was successfully created.' else render :new end end
ruby
def create @script_author = Script::Author.new(script_author_params) @script_author.user_id = current_user.id @script_author.org_id = current_user.org_id if @script_author.save redirect_to script_authors_url, notice: 'Author was successfully created.' else render :new end end
[ "def", "create", "@script_author", "=", "Script", "::", "Author", ".", "new", "(", "script_author_params", ")", "@script_author", ".", "user_id", "=", "current_user", ".", "id", "@script_author", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_author", ".", "save", "redirect_to", "script_authors_url", ",", "notice", ":", "'Author was successfully created.'", "else", "render", ":new", "end", "end" ]
CREATE - Script Author
[ "CREATE", "-", "Script", "Author" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/authors_controller.rb#L35-L44
23,057
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/extensions_controller.rb
Phcscriptcdn.Script::ExtensionsController.show
def show @script_extensions = Script::Extension.friendly.find(params[:id]) @versions = Phcscriptcdn::ExtensionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Extension') end
ruby
def show @script_extensions = Script::Extension.friendly.find(params[:id]) @versions = Phcscriptcdn::ExtensionVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Extension') end
[ "def", "show", "@script_extensions", "=", "Script", "::", "Extension", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "@versions", "=", "Phcscriptcdn", "::", "ExtensionVersions", ".", "where", "(", "item_id", ":", "params", "[", ":id", "]", ",", "item_type", ":", "'Phcscriptcdn::Script::Extension'", ")", "end" ]
DETAILS - Script Extension
[ "DETAILS", "-", "Script", "Extension" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L18-L21
23,058
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/extensions_controller.rb
Phcscriptcdn.Script::ExtensionsController.new
def new @script_extension = Script::Extension.new @script_extension.user_id = current_user.id @script_extension.org_id = current_user.org_id end
ruby
def new @script_extension = Script::Extension.new @script_extension.user_id = current_user.id @script_extension.org_id = current_user.org_id end
[ "def", "new", "@script_extension", "=", "Script", "::", "Extension", ".", "new", "@script_extension", ".", "user_id", "=", "current_user", ".", "id", "@script_extension", ".", "org_id", "=", "current_user", ".", "org_id", "end" ]
NEW - Script Extension
[ "NEW", "-", "Script", "Extension" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L24-L28
23,059
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/extensions_controller.rb
Phcscriptcdn.Script::ExtensionsController.create
def create @script_extension = Script::Extension.new(script_extension_params) @script_extension.user_id = current_user.id @script_extension.org_id = current_user.org_id if @script_extension.save redirect_to script_extensions_url, notice: 'Extension was successfully created.' else render :new end end
ruby
def create @script_extension = Script::Extension.new(script_extension_params) @script_extension.user_id = current_user.id @script_extension.org_id = current_user.org_id if @script_extension.save redirect_to script_extensions_url, notice: 'Extension was successfully created.' else render :new end end
[ "def", "create", "@script_extension", "=", "Script", "::", "Extension", ".", "new", "(", "script_extension_params", ")", "@script_extension", ".", "user_id", "=", "current_user", ".", "id", "@script_extension", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_extension", ".", "save", "redirect_to", "script_extensions_url", ",", "notice", ":", "'Extension was successfully created.'", "else", "render", ":new", "end", "end" ]
CREATE - Script Extension
[ "CREATE", "-", "Script", "Extension" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/extensions_controller.rb#L35-L44
23,060
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/licences_controller.rb
Phcscriptcdn.Script::LicencesController.show
def show @script_licences = Script::Licence.friendly.find(params[:id]) @versions = Phcscriptcdn::LicenceVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Licence') end
ruby
def show @script_licences = Script::Licence.friendly.find(params[:id]) @versions = Phcscriptcdn::LicenceVersions.where(item_id: params[:id], item_type: 'Phcscriptcdn::Script::Licence') end
[ "def", "show", "@script_licences", "=", "Script", "::", "Licence", ".", "friendly", ".", "find", "(", "params", "[", ":id", "]", ")", "@versions", "=", "Phcscriptcdn", "::", "LicenceVersions", ".", "where", "(", "item_id", ":", "params", "[", ":id", "]", ",", "item_type", ":", "'Phcscriptcdn::Script::Licence'", ")", "end" ]
DETAILS - Script Licences
[ "DETAILS", "-", "Script", "Licences" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L18-L21
23,061
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/licences_controller.rb
Phcscriptcdn.Script::LicencesController.new
def new @script_licence = Script::Licence.new @script_licence.user_id = current_user.id @script_licence.org_id = current_user.org_id end
ruby
def new @script_licence = Script::Licence.new @script_licence.user_id = current_user.id @script_licence.org_id = current_user.org_id end
[ "def", "new", "@script_licence", "=", "Script", "::", "Licence", ".", "new", "@script_licence", ".", "user_id", "=", "current_user", ".", "id", "@script_licence", ".", "org_id", "=", "current_user", ".", "org_id", "end" ]
NEW - Script Licences
[ "NEW", "-", "Script", "Licences" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L24-L28
23,062
phcdevworks/phc-scriptcdn
app/controllers/phcscriptcdn/script/licences_controller.rb
Phcscriptcdn.Script::LicencesController.create
def create @script_licence = Script::Licence.new(script_licence_params) @script_licence.user_id = current_user.id @script_licence.org_id = current_user.org_id if @script_licence.save redirect_to script_licences_url, notice: 'Licence was successfully created.' else render :new end end
ruby
def create @script_licence = Script::Licence.new(script_licence_params) @script_licence.user_id = current_user.id @script_licence.org_id = current_user.org_id if @script_licence.save redirect_to script_licences_url, notice: 'Licence was successfully created.' else render :new end end
[ "def", "create", "@script_licence", "=", "Script", "::", "Licence", ".", "new", "(", "script_licence_params", ")", "@script_licence", ".", "user_id", "=", "current_user", ".", "id", "@script_licence", ".", "org_id", "=", "current_user", ".", "org_id", "if", "@script_licence", ".", "save", "redirect_to", "script_licences_url", ",", "notice", ":", "'Licence was successfully created.'", "else", "render", ":new", "end", "end" ]
POST - Script Licences
[ "POST", "-", "Script", "Licences" ]
5679f9ae4da5e88d7173ddae0192a36d4b91d80f
https://github.com/phcdevworks/phc-scriptcdn/blob/5679f9ae4da5e88d7173ddae0192a36d4b91d80f/app/controllers/phcscriptcdn/script/licences_controller.rb#L35-L44
23,063
kostyantyn/hydra_attribute
lib/hydra_attribute/hydra_value.rb
HydraAttribute.HydraValue.save
def save raise EntityModelIsNotPersistedError unless entity.persisted? if persisted? return false unless changed? update else create end @previously_changed = changes @changed_attributes.clear true end
ruby
def save raise EntityModelIsNotPersistedError unless entity.persisted? if persisted? return false unless changed? update else create end @previously_changed = changes @changed_attributes.clear true end
[ "def", "save", "raise", "EntityModelIsNotPersistedError", "unless", "entity", ".", "persisted?", "if", "persisted?", "return", "false", "unless", "changed?", "update", "else", "create", "end", "@previously_changed", "=", "changes", "@changed_attributes", ".", "clear", "true", "end" ]
Saves model Performs +insert+ or +update+ sql query Method doesn't perform sql query if model isn't modified @return [TrueClass, FalseClass]
[ "Saves", "model", "Performs", "+", "insert", "+", "or", "+", "update", "+", "sql", "query", "Method", "doesn", "t", "perform", "sql", "query", "if", "model", "isn", "t", "modified" ]
64ba3ccb5c0d6cec6276a6a01734389b8f695572
https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L156-L170
23,064
kostyantyn/hydra_attribute
lib/hydra_attribute/hydra_value.rb
HydraAttribute.HydraValue.arel_insert
def arel_insert table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type] fields = {} fields[table[:entity_id]] = entity.id fields[table[:hydra_attribute_id]] = hydra_attribute.id fields[table[:value]] = value fields[table[:created_at]] = Time.now fields[table[:updated_at]] = Time.now table.compile_insert(fields) end
ruby
def arel_insert table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type] fields = {} fields[table[:entity_id]] = entity.id fields[table[:hydra_attribute_id]] = hydra_attribute.id fields[table[:value]] = value fields[table[:created_at]] = Time.now fields[table[:updated_at]] = Time.now table.compile_insert(fields) end
[ "def", "arel_insert", "table", "=", "self", ".", "class", ".", "arel_tables", "[", "entity", ".", "class", ".", "table_name", "]", "[", "hydra_attribute", ".", "backend_type", "]", "fields", "=", "{", "}", "fields", "[", "table", "[", ":entity_id", "]", "]", "=", "entity", ".", "id", "fields", "[", "table", "[", ":hydra_attribute_id", "]", "]", "=", "hydra_attribute", ".", "id", "fields", "[", "table", "[", ":value", "]", "]", "=", "value", "fields", "[", "table", "[", ":created_at", "]", "]", "=", "Time", ".", "now", "fields", "[", "table", "[", ":updated_at", "]", "]", "=", "Time", ".", "now", "table", ".", "compile_insert", "(", "fields", ")", "end" ]
Creates arel insert manager @return [Arel::InsertManager]
[ "Creates", "arel", "insert", "manager" ]
64ba3ccb5c0d6cec6276a6a01734389b8f695572
https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L176-L185
23,065
kostyantyn/hydra_attribute
lib/hydra_attribute/hydra_value.rb
HydraAttribute.HydraValue.arel_update
def arel_update table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type] arel = table.from(table) arel.where(table[:id].eq(id)).compile_update(table[:value] => value, table[:updated_at] => Time.now) end
ruby
def arel_update table = self.class.arel_tables[entity.class.table_name][hydra_attribute.backend_type] arel = table.from(table) arel.where(table[:id].eq(id)).compile_update(table[:value] => value, table[:updated_at] => Time.now) end
[ "def", "arel_update", "table", "=", "self", ".", "class", ".", "arel_tables", "[", "entity", ".", "class", ".", "table_name", "]", "[", "hydra_attribute", ".", "backend_type", "]", "arel", "=", "table", ".", "from", "(", "table", ")", "arel", ".", "where", "(", "table", "[", ":id", "]", ".", "eq", "(", "id", ")", ")", ".", "compile_update", "(", "table", "[", ":value", "]", "=>", "value", ",", "table", "[", ":updated_at", "]", "=>", "Time", ".", "now", ")", "end" ]
Creates arel update manager @return [Arel::UpdateManager]
[ "Creates", "arel", "update", "manager" ]
64ba3ccb5c0d6cec6276a6a01734389b8f695572
https://github.com/kostyantyn/hydra_attribute/blob/64ba3ccb5c0d6cec6276a6a01734389b8f695572/lib/hydra_attribute/hydra_value.rb#L190-L194
23,066
dougal/acts_as_indexed
lib/acts_as_indexed/search_index.rb
ActsAsIndexed.SearchIndex.add_records
def add_records(records) atoms = ActiveSupport::OrderedHash.new records_count = 0 records.each do |record| next unless allow_indexing?(record) records_count += 1 condensed_record = condense_record(record) atoms = add_occurences(condensed_record, record.id, atoms) end @storage.add(atoms, records_count) end
ruby
def add_records(records) atoms = ActiveSupport::OrderedHash.new records_count = 0 records.each do |record| next unless allow_indexing?(record) records_count += 1 condensed_record = condense_record(record) atoms = add_occurences(condensed_record, record.id, atoms) end @storage.add(atoms, records_count) end
[ "def", "add_records", "(", "records", ")", "atoms", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "records_count", "=", "0", "records", ".", "each", "do", "|", "record", "|", "next", "unless", "allow_indexing?", "(", "record", ")", "records_count", "+=", "1", "condensed_record", "=", "condense_record", "(", "record", ")", "atoms", "=", "add_occurences", "(", "condensed_record", ",", "record", ".", "id", ",", "atoms", ")", "end", "@storage", ".", "add", "(", "atoms", ",", "records_count", ")", "end" ]
Adds multiple records to the index. Accepts an array of +records+.
[ "Adds", "multiple", "records", "to", "the", "index", ".", "Accepts", "an", "array", "of", "+", "records", "+", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L27-L40
23,067
dougal/acts_as_indexed
lib/acts_as_indexed/search_index.rb
ActsAsIndexed.SearchIndex.remove_record
def remove_record(record) condensed_record = condense_record(record) atoms = add_occurences(condensed_record,record.id) @storage.remove(atoms) end
ruby
def remove_record(record) condensed_record = condense_record(record) atoms = add_occurences(condensed_record,record.id) @storage.remove(atoms) end
[ "def", "remove_record", "(", "record", ")", "condensed_record", "=", "condense_record", "(", "record", ")", "atoms", "=", "add_occurences", "(", "condensed_record", ",", "record", ".", "id", ")", "@storage", ".", "remove", "(", "atoms", ")", "end" ]
Removes +record+ from the index.
[ "Removes", "+", "record", "+", "from", "the", "index", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L43-L48
23,068
dougal/acts_as_indexed
lib/acts_as_indexed/search_index.rb
ActsAsIndexed.SearchIndex.search
def search(query) return [] if query.nil? @atoms = @storage.fetch(cleanup_atoms(query), query[/\^/]) queries = parse_query(query.dup) positive = run_queries(queries[:positive]) positive_quoted = run_quoted_queries(queries[:positive_quoted]) negative = run_queries(queries[:negative]) negative_quoted = run_quoted_queries(queries[:negative_quoted]) starts_with = run_queries(queries[:starts_with], true) start_quoted = run_quoted_queries(queries[:start_quoted], true) results = ActiveSupport::OrderedHash.new if queries[:start_quoted].any? results = merge_query_results(results, start_quoted) end if queries[:starts_with].any? results = merge_query_results(results, starts_with) end if queries[:positive_quoted].any? results = merge_query_results(results, positive_quoted) end if queries[:positive].any? results = merge_query_results(results, positive) end negative_results = (negative.keys + negative_quoted.keys) results.delete_if { |r_id, w| negative_results.include?(r_id) } results end
ruby
def search(query) return [] if query.nil? @atoms = @storage.fetch(cleanup_atoms(query), query[/\^/]) queries = parse_query(query.dup) positive = run_queries(queries[:positive]) positive_quoted = run_quoted_queries(queries[:positive_quoted]) negative = run_queries(queries[:negative]) negative_quoted = run_quoted_queries(queries[:negative_quoted]) starts_with = run_queries(queries[:starts_with], true) start_quoted = run_quoted_queries(queries[:start_quoted], true) results = ActiveSupport::OrderedHash.new if queries[:start_quoted].any? results = merge_query_results(results, start_quoted) end if queries[:starts_with].any? results = merge_query_results(results, starts_with) end if queries[:positive_quoted].any? results = merge_query_results(results, positive_quoted) end if queries[:positive].any? results = merge_query_results(results, positive) end negative_results = (negative.keys + negative_quoted.keys) results.delete_if { |r_id, w| negative_results.include?(r_id) } results end
[ "def", "search", "(", "query", ")", "return", "[", "]", "if", "query", ".", "nil?", "@atoms", "=", "@storage", ".", "fetch", "(", "cleanup_atoms", "(", "query", ")", ",", "query", "[", "/", "\\^", "/", "]", ")", "queries", "=", "parse_query", "(", "query", ".", "dup", ")", "positive", "=", "run_queries", "(", "queries", "[", ":positive", "]", ")", "positive_quoted", "=", "run_quoted_queries", "(", "queries", "[", ":positive_quoted", "]", ")", "negative", "=", "run_queries", "(", "queries", "[", ":negative", "]", ")", "negative_quoted", "=", "run_quoted_queries", "(", "queries", "[", ":negative_quoted", "]", ")", "starts_with", "=", "run_queries", "(", "queries", "[", ":starts_with", "]", ",", "true", ")", "start_quoted", "=", "run_quoted_queries", "(", "queries", "[", ":start_quoted", "]", ",", "true", ")", "results", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "if", "queries", "[", ":start_quoted", "]", ".", "any?", "results", "=", "merge_query_results", "(", "results", ",", "start_quoted", ")", "end", "if", "queries", "[", ":starts_with", "]", ".", "any?", "results", "=", "merge_query_results", "(", "results", ",", "starts_with", ")", "end", "if", "queries", "[", ":positive_quoted", "]", ".", "any?", "results", "=", "merge_query_results", "(", "results", ",", "positive_quoted", ")", "end", "if", "queries", "[", ":positive", "]", ".", "any?", "results", "=", "merge_query_results", "(", "results", ",", "positive", ")", "end", "negative_results", "=", "(", "negative", ".", "keys", "+", "negative_quoted", ".", "keys", ")", "results", ".", "delete_if", "{", "|", "r_id", ",", "w", "|", "negative_results", ".", "include?", "(", "r_id", ")", "}", "results", "end" ]
Returns an array of IDs for records matching +query+.
[ "Returns", "an", "array", "of", "IDs", "for", "records", "matching", "+", "query", "+", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L63-L96
23,069
dougal/acts_as_indexed
lib/acts_as_indexed/search_index.rb
ActsAsIndexed.SearchIndex.record_unchanged?
def record_unchanged?(record_new, record_old) # NOTE: Using the dirty state would be great here, but it doesn't keep track of # in-place changes. allow_indexing?(record_old) == allow_indexing?(record_new) && [email protected] { |field| record_old.send(field) == record_new.send(field) }.include?(false) end
ruby
def record_unchanged?(record_new, record_old) # NOTE: Using the dirty state would be great here, but it doesn't keep track of # in-place changes. allow_indexing?(record_old) == allow_indexing?(record_new) && [email protected] { |field| record_old.send(field) == record_new.send(field) }.include?(false) end
[ "def", "record_unchanged?", "(", "record_new", ",", "record_old", ")", "# NOTE: Using the dirty state would be great here, but it doesn't keep track of", "# in-place changes.", "allow_indexing?", "(", "record_old", ")", "==", "allow_indexing?", "(", "record_new", ")", "&&", "!", "@fields", ".", "map", "{", "|", "field", "|", "record_old", ".", "send", "(", "field", ")", "==", "record_new", ".", "send", "(", "field", ")", "}", ".", "include?", "(", "false", ")", "end" ]
The record is unchanged for our purposes if all the fields are the same and the if_proc returns the same result for both.
[ "The", "record", "is", "unchanged", "for", "our", "purposes", "if", "all", "the", "fields", "are", "the", "same", "and", "the", "if_proc", "returns", "the", "same", "result", "for", "both", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_index.rb#L102-L108
23,070
threez/ruby-vmstat
lib/vmstat/procfs.rb
Vmstat.ProcFS.memory
def memory @pagesize ||= Vmstat.pagesize has_available = false total = free = active = inactive = pageins = pageouts = available = 0 procfs_file("meminfo") do |file| content = file.read(2048) # the requested information is in the first bytes content.scan(/(\w+):\s+(\d+) kB/) do |name, kbytes| pages = (kbytes.to_i * 1024) / @pagesize case name when "MemTotal" then total = pages when "MemFree" then free = pages when "MemAvailable" available = pages has_available = true when "Active" then active = pages when "Inactive" then inactive = pages end end end procfs_file("vmstat") do |file| content = file.read if content =~ /pgpgin\s+(\d+)/ pageins = $1.to_i end if content =~ /pgpgout\s+(\d+)/ pageouts = $1.to_i end end mem_klass = has_available ? LinuxMemory : Memory mem_klass.new(@pagesize, total-free-active-inactive, active, inactive, free, pageins, pageouts).tap do |mem| mem.available = available if has_available end end
ruby
def memory @pagesize ||= Vmstat.pagesize has_available = false total = free = active = inactive = pageins = pageouts = available = 0 procfs_file("meminfo") do |file| content = file.read(2048) # the requested information is in the first bytes content.scan(/(\w+):\s+(\d+) kB/) do |name, kbytes| pages = (kbytes.to_i * 1024) / @pagesize case name when "MemTotal" then total = pages when "MemFree" then free = pages when "MemAvailable" available = pages has_available = true when "Active" then active = pages when "Inactive" then inactive = pages end end end procfs_file("vmstat") do |file| content = file.read if content =~ /pgpgin\s+(\d+)/ pageins = $1.to_i end if content =~ /pgpgout\s+(\d+)/ pageouts = $1.to_i end end mem_klass = has_available ? LinuxMemory : Memory mem_klass.new(@pagesize, total-free-active-inactive, active, inactive, free, pageins, pageouts).tap do |mem| mem.available = available if has_available end end
[ "def", "memory", "@pagesize", "||=", "Vmstat", ".", "pagesize", "has_available", "=", "false", "total", "=", "free", "=", "active", "=", "inactive", "=", "pageins", "=", "pageouts", "=", "available", "=", "0", "procfs_file", "(", "\"meminfo\"", ")", "do", "|", "file", "|", "content", "=", "file", ".", "read", "(", "2048", ")", "# the requested information is in the first bytes", "content", ".", "scan", "(", "/", "\\w", "\\s", "\\d", "/", ")", "do", "|", "name", ",", "kbytes", "|", "pages", "=", "(", "kbytes", ".", "to_i", "*", "1024", ")", "/", "@pagesize", "case", "name", "when", "\"MemTotal\"", "then", "total", "=", "pages", "when", "\"MemFree\"", "then", "free", "=", "pages", "when", "\"MemAvailable\"", "available", "=", "pages", "has_available", "=", "true", "when", "\"Active\"", "then", "active", "=", "pages", "when", "\"Inactive\"", "then", "inactive", "=", "pages", "end", "end", "end", "procfs_file", "(", "\"vmstat\"", ")", "do", "|", "file", "|", "content", "=", "file", ".", "read", "if", "content", "=~", "/", "\\s", "\\d", "/", "pageins", "=", "$1", ".", "to_i", "end", "if", "content", "=~", "/", "\\s", "\\d", "/", "pageouts", "=", "$1", ".", "to_i", "end", "end", "mem_klass", "=", "has_available", "?", "LinuxMemory", ":", "Memory", "mem_klass", ".", "new", "(", "@pagesize", ",", "total", "-", "free", "-", "active", "-", "inactive", ",", "active", ",", "inactive", ",", "free", ",", "pageins", ",", "pageouts", ")", ".", "tap", "do", "|", "mem", "|", "mem", ".", "available", "=", "available", "if", "has_available", "end", "end" ]
Fetches the memory usage information. @return [Vmstat::Memory] the memory data like free, used und total. @example Vmstat.memory # => #<struct Vmstat::Memory ...>
[ "Fetches", "the", "memory", "usage", "information", "." ]
f762a6a5c6627182d6c1bb33f6605da2d3d4ef45
https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L46-L86
23,071
threez/ruby-vmstat
lib/vmstat/procfs.rb
Vmstat.ProcFS.network_interfaces
def network_interfaces netifcs = [] procfs_file("net", "dev") do |file| file.read.scan(NET_DATA) do |columns| type = case columns[0] when /^eth/ then NetworkInterface::ETHERNET_TYPE when /^lo/ then NetworkInterface::LOOPBACK_TYPE end netifcs << NetworkInterface.new(columns[0].to_sym, columns[1].to_i, columns[3].to_i, columns[4].to_i, columns[9].to_i, columns[11].to_i, type) end end netifcs end
ruby
def network_interfaces netifcs = [] procfs_file("net", "dev") do |file| file.read.scan(NET_DATA) do |columns| type = case columns[0] when /^eth/ then NetworkInterface::ETHERNET_TYPE when /^lo/ then NetworkInterface::LOOPBACK_TYPE end netifcs << NetworkInterface.new(columns[0].to_sym, columns[1].to_i, columns[3].to_i, columns[4].to_i, columns[9].to_i, columns[11].to_i, type) end end netifcs end
[ "def", "network_interfaces", "netifcs", "=", "[", "]", "procfs_file", "(", "\"net\"", ",", "\"dev\"", ")", "do", "|", "file", "|", "file", ".", "read", ".", "scan", "(", "NET_DATA", ")", "do", "|", "columns", "|", "type", "=", "case", "columns", "[", "0", "]", "when", "/", "/", "then", "NetworkInterface", "::", "ETHERNET_TYPE", "when", "/", "/", "then", "NetworkInterface", "::", "LOOPBACK_TYPE", "end", "netifcs", "<<", "NetworkInterface", ".", "new", "(", "columns", "[", "0", "]", ".", "to_sym", ",", "columns", "[", "1", "]", ".", "to_i", ",", "columns", "[", "3", "]", ".", "to_i", ",", "columns", "[", "4", "]", ".", "to_i", ",", "columns", "[", "9", "]", ".", "to_i", ",", "columns", "[", "11", "]", ".", "to_i", ",", "type", ")", "end", "end", "netifcs", "end" ]
Fetches the information for all available network devices. @return [Array<Vmstat::NetworkInterface>] the network device information @example Vmstat.network_interfaces # => [#<struct Vmstat::NetworkInterface ...>, ...]
[ "Fetches", "the", "information", "for", "all", "available", "network", "devices", "." ]
f762a6a5c6627182d6c1bb33f6605da2d3d4ef45
https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L92-L108
23,072
threez/ruby-vmstat
lib/vmstat/procfs.rb
Vmstat.ProcFS.task
def task @pagesize ||= Vmstat.pagesize procfs_file("self", "stat") do |file| data = file.read.split(/ /) Task.new(data[22].to_i / @pagesize, data[23].to_i, data[13].to_i * 1000, data[14].to_i * 1000) end end
ruby
def task @pagesize ||= Vmstat.pagesize procfs_file("self", "stat") do |file| data = file.read.split(/ /) Task.new(data[22].to_i / @pagesize, data[23].to_i, data[13].to_i * 1000, data[14].to_i * 1000) end end
[ "def", "task", "@pagesize", "||=", "Vmstat", ".", "pagesize", "procfs_file", "(", "\"self\"", ",", "\"stat\"", ")", "do", "|", "file", "|", "data", "=", "file", ".", "read", ".", "split", "(", "/", "/", ")", "Task", ".", "new", "(", "data", "[", "22", "]", ".", "to_i", "/", "@pagesize", ",", "data", "[", "23", "]", ".", "to_i", ",", "data", "[", "13", "]", ".", "to_i", "*", "1000", ",", "data", "[", "14", "]", ".", "to_i", "*", "1000", ")", "end", "end" ]
Fetches the current process cpu and memory data. @return [Vmstat::Task] the task data for the current process
[ "Fetches", "the", "current", "process", "cpu", "and", "memory", "data", "." ]
f762a6a5c6627182d6c1bb33f6605da2d3d4ef45
https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L112-L120
23,073
threez/ruby-vmstat
lib/vmstat/procfs.rb
Vmstat.ProcFS.boot_time
def boot_time raw = procfs_file("uptime") { |file| file.read } Time.now - raw.split(/\s/).first.to_f end
ruby
def boot_time raw = procfs_file("uptime") { |file| file.read } Time.now - raw.split(/\s/).first.to_f end
[ "def", "boot_time", "raw", "=", "procfs_file", "(", "\"uptime\"", ")", "{", "|", "file", "|", "file", ".", "read", "}", "Time", ".", "now", "-", "raw", ".", "split", "(", "/", "\\s", "/", ")", ".", "first", ".", "to_f", "end" ]
Fetches the boot time of the system. @return [Time] the boot time as regular time object. @example Vmstat.boot_time # => 2012-10-09 18:42:37 +0200
[ "Fetches", "the", "boot", "time", "of", "the", "system", "." ]
f762a6a5c6627182d6c1bb33f6605da2d3d4ef45
https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L126-L129
23,074
threez/ruby-vmstat
lib/vmstat/procfs.rb
Vmstat.ProcFS.procfs_file
def procfs_file(*names, &block) path = File.join(procfs_path, *names) File.open(path, "r", &block) end
ruby
def procfs_file(*names, &block) path = File.join(procfs_path, *names) File.open(path, "r", &block) end
[ "def", "procfs_file", "(", "*", "names", ",", "&", "block", ")", "path", "=", "File", ".", "join", "(", "procfs_path", ",", "names", ")", "File", ".", "open", "(", "path", ",", "\"r\"", ",", "block", ")", "end" ]
Opens a proc file system file handle and returns the handle in the passed block. Closes the file handle. @see File#open @param [Array<String>] names parts of the path to the procfs file @example procfs_file("net", "dev") { |file| } procfs_file("stat") { |file| } @yieldparam [IO] file the file handle @api private
[ "Opens", "a", "proc", "file", "system", "file", "handle", "and", "returns", "the", "handle", "in", "the", "passed", "block", ".", "Closes", "the", "file", "handle", "." ]
f762a6a5c6627182d6c1bb33f6605da2d3d4ef45
https://github.com/threez/ruby-vmstat/blob/f762a6a5c6627182d6c1bb33f6605da2d3d4ef45/lib/vmstat/procfs.rb#L148-L151
23,075
dougal/acts_as_indexed
lib/acts_as_indexed/search_atom.rb
ActsAsIndexed.SearchAtom.+
def +(other) SearchAtom.new(@records.clone.merge!(other.records) { |key, _old, _new| _old + _new }) end
ruby
def +(other) SearchAtom.new(@records.clone.merge!(other.records) { |key, _old, _new| _old + _new }) end
[ "def", "+", "(", "other", ")", "SearchAtom", ".", "new", "(", "@records", ".", "clone", ".", "merge!", "(", "other", ".", "records", ")", "{", "|", "key", ",", "_old", ",", "_new", "|", "_old", "+", "_new", "}", ")", "end" ]
Creates a new SearchAtom with the combined records from self and other
[ "Creates", "a", "new", "SearchAtom", "with", "the", "combined", "records", "from", "self", "and", "other" ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L50-L54
23,076
dougal/acts_as_indexed
lib/acts_as_indexed/search_atom.rb
ActsAsIndexed.SearchAtom.-
def -(other) records = @records.clone.reject { |name, records| other.records.include?(name) } SearchAtom.new(records) end
ruby
def -(other) records = @records.clone.reject { |name, records| other.records.include?(name) } SearchAtom.new(records) end
[ "def", "-", "(", "other", ")", "records", "=", "@records", ".", "clone", ".", "reject", "{", "|", "name", ",", "records", "|", "other", ".", "records", ".", "include?", "(", "name", ")", "}", "SearchAtom", ".", "new", "(", "records", ")", "end" ]
Creates a new SearchAtom with records in other removed from self.
[ "Creates", "a", "new", "SearchAtom", "with", "records", "in", "other", "removed", "from", "self", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L57-L60
23,077
dougal/acts_as_indexed
lib/acts_as_indexed/search_atom.rb
ActsAsIndexed.SearchAtom.preceded_by
def preceded_by(former) matches = SearchAtom.new latter = ActiveSupport::OrderedHash.new former.record_ids.each do |rid| latter[rid] = @records[rid] if @records[rid] end # Iterate over each record in latter. latter.each do |record_id,pos| # Iterate over each position. pos.each do |p| # Check if previous position is in former. if former.include_position?(record_id,p-1) matches.add_record(record_id) unless matches.include_record?(record_id) matches.add_position(record_id,p) end end end matches end
ruby
def preceded_by(former) matches = SearchAtom.new latter = ActiveSupport::OrderedHash.new former.record_ids.each do |rid| latter[rid] = @records[rid] if @records[rid] end # Iterate over each record in latter. latter.each do |record_id,pos| # Iterate over each position. pos.each do |p| # Check if previous position is in former. if former.include_position?(record_id,p-1) matches.add_record(record_id) unless matches.include_record?(record_id) matches.add_position(record_id,p) end end end matches end
[ "def", "preceded_by", "(", "former", ")", "matches", "=", "SearchAtom", ".", "new", "latter", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "former", ".", "record_ids", ".", "each", "do", "|", "rid", "|", "latter", "[", "rid", "]", "=", "@records", "[", "rid", "]", "if", "@records", "[", "rid", "]", "end", "# Iterate over each record in latter.", "latter", ".", "each", "do", "|", "record_id", ",", "pos", "|", "# Iterate over each position.", "pos", ".", "each", "do", "|", "p", "|", "# Check if previous position is in former.", "if", "former", ".", "include_position?", "(", "record_id", ",", "p", "-", "1", ")", "matches", ".", "add_record", "(", "record_id", ")", "unless", "matches", ".", "include_record?", "(", "record_id", ")", "matches", ".", "add_position", "(", "record_id", ",", "p", ")", "end", "end", "end", "matches", "end" ]
Returns at atom containing the records and positions of +self+ preceded by +former+ "former latter" or "big dog" where "big" is the former and "dog" is the latter.
[ "Returns", "at", "atom", "containing", "the", "records", "and", "positions", "of", "+", "self", "+", "preceded", "by", "+", "former", "+", "former", "latter", "or", "big", "dog", "where", "big", "is", "the", "former", "and", "dog", "is", "the", "latter", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L64-L84
23,078
dougal/acts_as_indexed
lib/acts_as_indexed/search_atom.rb
ActsAsIndexed.SearchAtom.weightings
def weightings(records_size) out = ActiveSupport::OrderedHash.new ## phurni 2012-09-21 when records_size is exactly the @records.size (all records are matches), the Math.log would ## return 0 which means the frequency (pos.size) will have no effect. Cheat to make it like the matching ## record is one less, so that we still can weight on frequency. matching_records_size = (records_size == @records.size ? @records.size - 1 : @records.size) @records.each do |r_id, pos| # Fixes a bug when the records_size is zero. i.e. The only record # contaning the word has been deleted. if records_size < 1 out[r_id] = 0.0 next end # weighting = frequency * log (records.size / records_with_atom) ## parndt 2010/05/03 changed to records_size.to_f to avoid -Infinity Errno::ERANGE exceptions ## which would happen for example Math.log(1 / 20) == -Infinity but Math.log(1.0 / 20) == -2.99573227355399 out[r_id] = pos.size * Math.log(records_size.to_f / matching_records_size) end out end
ruby
def weightings(records_size) out = ActiveSupport::OrderedHash.new ## phurni 2012-09-21 when records_size is exactly the @records.size (all records are matches), the Math.log would ## return 0 which means the frequency (pos.size) will have no effect. Cheat to make it like the matching ## record is one less, so that we still can weight on frequency. matching_records_size = (records_size == @records.size ? @records.size - 1 : @records.size) @records.each do |r_id, pos| # Fixes a bug when the records_size is zero. i.e. The only record # contaning the word has been deleted. if records_size < 1 out[r_id] = 0.0 next end # weighting = frequency * log (records.size / records_with_atom) ## parndt 2010/05/03 changed to records_size.to_f to avoid -Infinity Errno::ERANGE exceptions ## which would happen for example Math.log(1 / 20) == -Infinity but Math.log(1.0 / 20) == -2.99573227355399 out[r_id] = pos.size * Math.log(records_size.to_f / matching_records_size) end out end
[ "def", "weightings", "(", "records_size", ")", "out", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "## phurni 2012-09-21 when records_size is exactly the @records.size (all records are matches), the Math.log would", "## return 0 which means the frequency (pos.size) will have no effect. Cheat to make it like the matching", "## record is one less, so that we still can weight on frequency.", "matching_records_size", "=", "(", "records_size", "==", "@records", ".", "size", "?", "@records", ".", "size", "-", "1", ":", "@records", ".", "size", ")", "@records", ".", "each", "do", "|", "r_id", ",", "pos", "|", "# Fixes a bug when the records_size is zero. i.e. The only record", "# contaning the word has been deleted.", "if", "records_size", "<", "1", "out", "[", "r_id", "]", "=", "0.0", "next", "end", "# weighting = frequency * log (records.size / records_with_atom)", "## parndt 2010/05/03 changed to records_size.to_f to avoid -Infinity Errno::ERANGE exceptions", "## which would happen for example Math.log(1 / 20) == -Infinity but Math.log(1.0 / 20) == -2.99573227355399", "out", "[", "r_id", "]", "=", "pos", ".", "size", "*", "Math", ".", "log", "(", "records_size", ".", "to_f", "/", "matching_records_size", ")", "end", "out", "end" ]
Returns a hash of record_ids and weightings for each record in the atom.
[ "Returns", "a", "hash", "of", "record_ids", "and", "weightings", "for", "each", "record", "in", "the", "atom", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/search_atom.rb#L88-L112
23,079
tsrivishnu/alexa-rails
lib/alexa/response.rb
Alexa.Response.elicit_slot!
def elicit_slot!(slot_to_elicit, skip_render: false) directives << { type: "Dialog.ElicitSlot", slotToElicit: slot_to_elicit } if skip_render @slots_to_not_render_elicitation << slot_to_elicit end end
ruby
def elicit_slot!(slot_to_elicit, skip_render: false) directives << { type: "Dialog.ElicitSlot", slotToElicit: slot_to_elicit } if skip_render @slots_to_not_render_elicitation << slot_to_elicit end end
[ "def", "elicit_slot!", "(", "slot_to_elicit", ",", "skip_render", ":", "false", ")", "directives", "<<", "{", "type", ":", "\"Dialog.ElicitSlot\"", ",", "slotToElicit", ":", "slot_to_elicit", "}", "if", "skip_render", "@slots_to_not_render_elicitation", "<<", "slot_to_elicit", "end", "end" ]
Marks a slot for elicitation. Options: - skip_render: Lets you skip the rendering of the elicited slot's view. Helpful when you have the elication text already in the response and don't wanna override it.
[ "Marks", "a", "slot", "for", "elicitation", "." ]
bc9fda6610c8e563116bc53d64af7c41a13f1014
https://github.com/tsrivishnu/alexa-rails/blob/bc9fda6610c8e563116bc53d64af7c41a13f1014/lib/alexa/response.rb#L23-L32
23,080
dougal/acts_as_indexed
lib/acts_as_indexed/storage.rb
ActsAsIndexed.Storage.fetch
def fetch(atom_names, start=false) atoms = ActiveSupport::OrderedHash.new atom_names.uniq.collect{|a| encoded_prefix(a) }.uniq.each do |prefix| pattern = @path.join(prefix.to_s).to_s pattern += '*' if start pattern += INDEX_FILE_EXTENSION Pathname.glob(pattern).each do |atom_file| atom_file.open do |f| atoms.merge!(Marshal.load(f)) end end # Pathname.glob end # atom_names.uniq atoms end
ruby
def fetch(atom_names, start=false) atoms = ActiveSupport::OrderedHash.new atom_names.uniq.collect{|a| encoded_prefix(a) }.uniq.each do |prefix| pattern = @path.join(prefix.to_s).to_s pattern += '*' if start pattern += INDEX_FILE_EXTENSION Pathname.glob(pattern).each do |atom_file| atom_file.open do |f| atoms.merge!(Marshal.load(f)) end end # Pathname.glob end # atom_names.uniq atoms end
[ "def", "fetch", "(", "atom_names", ",", "start", "=", "false", ")", "atoms", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "atom_names", ".", "uniq", ".", "collect", "{", "|", "a", "|", "encoded_prefix", "(", "a", ")", "}", ".", "uniq", ".", "each", "do", "|", "prefix", "|", "pattern", "=", "@path", ".", "join", "(", "prefix", ".", "to_s", ")", ".", "to_s", "pattern", "+=", "'*'", "if", "start", "pattern", "+=", "INDEX_FILE_EXTENSION", "Pathname", ".", "glob", "(", "pattern", ")", ".", "each", "do", "|", "atom_file", "|", "atom_file", ".", "open", "do", "|", "f", "|", "atoms", ".", "merge!", "(", "Marshal", ".", "load", "(", "f", ")", ")", "end", "end", "# Pathname.glob", "end", "# atom_names.uniq", "atoms", "end" ]
Takes a string array of atoms names return a hash of the relevant atoms.
[ "Takes", "a", "string", "array", "of", "atoms", "names", "return", "a", "hash", "of", "the", "relevant", "atoms", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L35-L51
23,081
dougal/acts_as_indexed
lib/acts_as_indexed/storage.rb
ActsAsIndexed.Storage.operate
def operate(operation, atoms) # ActiveSupport always available? atoms_sorted = ActiveSupport::OrderedHash.new # Sort the atoms into the appropriate shards for writing to individual # files. atoms.each do |atom_name, records| (atoms_sorted[encoded_prefix(atom_name)] ||= ActiveSupport::OrderedHash.new)[atom_name] = records end atoms_sorted.each do |e_p, atoms| path = @path.join(e_p.to_s + INDEX_FILE_EXTENSION) lock_file(path) do if path.exist? from_file = path.open do |f| Marshal.load(f) end else from_file = ActiveSupport::OrderedHash.new end atoms = from_file.merge(atoms){ |k,o,n| o.send(operation, n) } write_file(path) do |f| Marshal.dump(atoms,f) end end # end lock. end end
ruby
def operate(operation, atoms) # ActiveSupport always available? atoms_sorted = ActiveSupport::OrderedHash.new # Sort the atoms into the appropriate shards for writing to individual # files. atoms.each do |atom_name, records| (atoms_sorted[encoded_prefix(atom_name)] ||= ActiveSupport::OrderedHash.new)[atom_name] = records end atoms_sorted.each do |e_p, atoms| path = @path.join(e_p.to_s + INDEX_FILE_EXTENSION) lock_file(path) do if path.exist? from_file = path.open do |f| Marshal.load(f) end else from_file = ActiveSupport::OrderedHash.new end atoms = from_file.merge(atoms){ |k,o,n| o.send(operation, n) } write_file(path) do |f| Marshal.dump(atoms,f) end end # end lock. end end
[ "def", "operate", "(", "operation", ",", "atoms", ")", "# ActiveSupport always available?", "atoms_sorted", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "# Sort the atoms into the appropriate shards for writing to individual", "# files.", "atoms", ".", "each", "do", "|", "atom_name", ",", "records", "|", "(", "atoms_sorted", "[", "encoded_prefix", "(", "atom_name", ")", "]", "||=", "ActiveSupport", "::", "OrderedHash", ".", "new", ")", "[", "atom_name", "]", "=", "records", "end", "atoms_sorted", ".", "each", "do", "|", "e_p", ",", "atoms", "|", "path", "=", "@path", ".", "join", "(", "e_p", ".", "to_s", "+", "INDEX_FILE_EXTENSION", ")", "lock_file", "(", "path", ")", "do", "if", "path", ".", "exist?", "from_file", "=", "path", ".", "open", "do", "|", "f", "|", "Marshal", ".", "load", "(", "f", ")", "end", "else", "from_file", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "end", "atoms", "=", "from_file", ".", "merge", "(", "atoms", ")", "{", "|", "k", ",", "o", ",", "n", "|", "o", ".", "send", "(", "operation", ",", "n", ")", "}", "write_file", "(", "path", ")", "do", "|", "f", "|", "Marshal", ".", "dump", "(", "atoms", ",", "f", ")", "end", "end", "# end lock.", "end", "end" ]
Takes atoms and adds or removes them from the index depending on the passed operation.
[ "Takes", "atoms", "and", "adds", "or", "removes", "them", "from", "the", "index", "depending", "on", "the", "passed", "operation", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L68-L99
23,082
dougal/acts_as_indexed
lib/acts_as_indexed/storage.rb
ActsAsIndexed.Storage.lock_file
def lock_file(file_path, &block) # :nodoc: @@file_lock.synchronize do # Windows does not support file locking. if !windows? && file_path.exist? file_path.open('r+') do |f| begin f.flock File::LOCK_EX yield ensure f.flock File::LOCK_UN end end else yield end end end
ruby
def lock_file(file_path, &block) # :nodoc: @@file_lock.synchronize do # Windows does not support file locking. if !windows? && file_path.exist? file_path.open('r+') do |f| begin f.flock File::LOCK_EX yield ensure f.flock File::LOCK_UN end end else yield end end end
[ "def", "lock_file", "(", "file_path", ",", "&", "block", ")", "# :nodoc:", "@@file_lock", ".", "synchronize", "do", "# Windows does not support file locking.", "if", "!", "windows?", "&&", "file_path", ".", "exist?", "file_path", ".", "open", "(", "'r+'", ")", "do", "|", "f", "|", "begin", "f", ".", "flock", "File", "::", "LOCK_EX", "yield", "ensure", "f", ".", "flock", "File", "::", "LOCK_UN", "end", "end", "else", "yield", "end", "end", "end" ]
Borrowed from Rails' ActiveSupport FileStore. Also under MIT licence. Lock a file for a block so only one process or thread can modify it at a time.
[ "Borrowed", "from", "Rails", "ActiveSupport", "FileStore", ".", "Also", "under", "MIT", "licence", ".", "Lock", "a", "file", "for", "a", "block", "so", "only", "one", "process", "or", "thread", "can", "modify", "it", "at", "a", "time", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/storage.rb#L174-L192
23,083
tsrivishnu/alexa-rails
lib/alexa/device.rb
Alexa.Device.location
def location @_location ||= begin if Alexa.configuration.location_permission_type == :full_address get_address elsif Alexa.configuration.location_permission_type == :country_and_postal_code get_address(only: :country_and_postal_code) end end end
ruby
def location @_location ||= begin if Alexa.configuration.location_permission_type == :full_address get_address elsif Alexa.configuration.location_permission_type == :country_and_postal_code get_address(only: :country_and_postal_code) end end end
[ "def", "location", "@_location", "||=", "begin", "if", "Alexa", ".", "configuration", ".", "location_permission_type", "==", ":full_address", "get_address", "elsif", "Alexa", ".", "configuration", ".", "location_permission_type", "==", ":country_and_postal_code", "get_address", "(", "only", ":", ":country_and_postal_code", ")", "end", "end", "end" ]
Return device location from amazon. Makes an API to amazon alexa's device location service and returns the location hash
[ "Return", "device", "location", "from", "amazon", ".", "Makes", "an", "API", "to", "amazon", "alexa", "s", "device", "location", "service", "and", "returns", "the", "location", "hash" ]
bc9fda6610c8e563116bc53d64af7c41a13f1014
https://github.com/tsrivishnu/alexa-rails/blob/bc9fda6610c8e563116bc53d64af7c41a13f1014/lib/alexa/device.rb#L30-L38
23,084
odlp/simplify_rb
lib/simplify_rb/douglas_peucker_simplifier.rb
SimplifyRb.DouglasPeuckerSimplifier.get_sq_seg_dist
def get_sq_seg_dist(point, point_1, point_2) x = point_1.x y = point_1.y dx = point_2.x - x dy = point_2.y - y if dx != 0 || dy != 0 t = ((point.x - x) * dx + (point.y - y) * dy) / (dx * dx + dy * dy) if t > 1 x = point_2.x y = point_2.y elsif t > 0 x += dx * t y += dy * t end end dx = point.x - x dy = point.y - y dx * dx + dy * dy end
ruby
def get_sq_seg_dist(point, point_1, point_2) x = point_1.x y = point_1.y dx = point_2.x - x dy = point_2.y - y if dx != 0 || dy != 0 t = ((point.x - x) * dx + (point.y - y) * dy) / (dx * dx + dy * dy) if t > 1 x = point_2.x y = point_2.y elsif t > 0 x += dx * t y += dy * t end end dx = point.x - x dy = point.y - y dx * dx + dy * dy end
[ "def", "get_sq_seg_dist", "(", "point", ",", "point_1", ",", "point_2", ")", "x", "=", "point_1", ".", "x", "y", "=", "point_1", ".", "y", "dx", "=", "point_2", ".", "x", "-", "x", "dy", "=", "point_2", ".", "y", "-", "y", "if", "dx", "!=", "0", "||", "dy", "!=", "0", "t", "=", "(", "(", "point", ".", "x", "-", "x", ")", "*", "dx", "+", "(", "point", ".", "y", "-", "y", ")", "*", "dy", ")", "/", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", "if", "t", ">", "1", "x", "=", "point_2", ".", "x", "y", "=", "point_2", ".", "y", "elsif", "t", ">", "0", "x", "+=", "dx", "*", "t", "y", "+=", "dy", "*", "t", "end", "end", "dx", "=", "point", ".", "x", "-", "x", "dy", "=", "point", ".", "y", "-", "y", "dx", "*", "dx", "+", "dy", "*", "dy", "end" ]
Square distance from a point to a segment
[ "Square", "distance", "from", "a", "point", "to", "a", "segment" ]
e5a68f049051a64184ada02e47df751cbda1e14b
https://github.com/odlp/simplify_rb/blob/e5a68f049051a64184ada02e47df751cbda1e14b/lib/simplify_rb/douglas_peucker_simplifier.rb#L57-L80
23,085
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.acts_as_indexed
def acts_as_indexed(options = {}) class_eval do extend ActsAsIndexed::SingletonMethods end include ActsAsIndexed::InstanceMethods after_create :add_to_index before_update :update_index after_destroy :remove_from_index # scope for Rails 3.x, named_scope for Rails 2.x. if self.respond_to?(:where) scope :with_query, lambda { |query| where("#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true})) } else named_scope :with_query, lambda { |query| { :conditions => ["#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true}) ] } } end cattr_accessor :aai_config, :aai_fields self.aai_fields = options.delete(:fields) raise(ArgumentError, 'no fields specified') if self.aai_fields.nil? || self.aai_fields.empty? self.aai_config = ActsAsIndexed.configuration.dup self.aai_config.if_proc = options.delete(:if) options.each do |k, v| self.aai_config.send("#{k}=", v) end # Add the Rails environment and this model's name to the index file path. self.aai_config.index_file = self.aai_config.index_file.join(Rails.env, self.name.underscore) end
ruby
def acts_as_indexed(options = {}) class_eval do extend ActsAsIndexed::SingletonMethods end include ActsAsIndexed::InstanceMethods after_create :add_to_index before_update :update_index after_destroy :remove_from_index # scope for Rails 3.x, named_scope for Rails 2.x. if self.respond_to?(:where) scope :with_query, lambda { |query| where("#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true})) } else named_scope :with_query, lambda { |query| { :conditions => ["#{table_name}.#{primary_key} IN (?)", search_index(query, {}, {:ids_only => true}) ] } } end cattr_accessor :aai_config, :aai_fields self.aai_fields = options.delete(:fields) raise(ArgumentError, 'no fields specified') if self.aai_fields.nil? || self.aai_fields.empty? self.aai_config = ActsAsIndexed.configuration.dup self.aai_config.if_proc = options.delete(:if) options.each do |k, v| self.aai_config.send("#{k}=", v) end # Add the Rails environment and this model's name to the index file path. self.aai_config.index_file = self.aai_config.index_file.join(Rails.env, self.name.underscore) end
[ "def", "acts_as_indexed", "(", "options", "=", "{", "}", ")", "class_eval", "do", "extend", "ActsAsIndexed", "::", "SingletonMethods", "end", "include", "ActsAsIndexed", "::", "InstanceMethods", "after_create", ":add_to_index", "before_update", ":update_index", "after_destroy", ":remove_from_index", "# scope for Rails 3.x, named_scope for Rails 2.x.", "if", "self", ".", "respond_to?", "(", ":where", ")", "scope", ":with_query", ",", "lambda", "{", "|", "query", "|", "where", "(", "\"#{table_name}.#{primary_key} IN (?)\"", ",", "search_index", "(", "query", ",", "{", "}", ",", "{", ":ids_only", "=>", "true", "}", ")", ")", "}", "else", "named_scope", ":with_query", ",", "lambda", "{", "|", "query", "|", "{", ":conditions", "=>", "[", "\"#{table_name}.#{primary_key} IN (?)\"", ",", "search_index", "(", "query", ",", "{", "}", ",", "{", ":ids_only", "=>", "true", "}", ")", "]", "}", "}", "end", "cattr_accessor", ":aai_config", ",", ":aai_fields", "self", ".", "aai_fields", "=", "options", ".", "delete", "(", ":fields", ")", "raise", "(", "ArgumentError", ",", "'no fields specified'", ")", "if", "self", ".", "aai_fields", ".", "nil?", "||", "self", ".", "aai_fields", ".", "empty?", "self", ".", "aai_config", "=", "ActsAsIndexed", ".", "configuration", ".", "dup", "self", ".", "aai_config", ".", "if_proc", "=", "options", ".", "delete", "(", ":if", ")", "options", ".", "each", "do", "|", "k", ",", "v", "|", "self", ".", "aai_config", ".", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "# Add the Rails environment and this model's name to the index file path.", "self", ".", "aai_config", ".", "index_file", "=", "self", ".", "aai_config", ".", "index_file", ".", "join", "(", "Rails", ".", "env", ",", "self", ".", "name", ".", "underscore", ")", "end" ]
Declares a class as searchable. ====options: fields:: Names of fields to include in the index. Symbols pointing to instance methods of your model may also be given here. index_file_depth:: Tuning value for the index partitioning. Larger values result in quicker searches, but slower indexing. Default is 3. min_word_size:: Sets the minimum length for a word in a query. Words shorter than this value are ignored in searches unless preceded by the '+' operator. Default is 3. index_file:: Sets the location for the index. By default this is RAILS_ROOT/tmp/index. Specify as an array. The default, for example, would be set as [Rails.root,'tmp','index].
[ "Declares", "a", "class", "as", "searchable", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L20-L50
23,086
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.index_add
def index_add(record) return if self.aai_config.disable_auto_indexing build_index index = new_index index.add_record(record) @query_cache = {} end
ruby
def index_add(record) return if self.aai_config.disable_auto_indexing build_index index = new_index index.add_record(record) @query_cache = {} end
[ "def", "index_add", "(", "record", ")", "return", "if", "self", ".", "aai_config", ".", "disable_auto_indexing", "build_index", "index", "=", "new_index", "index", ".", "add_record", "(", "record", ")", "@query_cache", "=", "{", "}", "end" ]
Adds the passed +record+ to the index. Index is built if it does not already exist. Clears the query cache.
[ "Adds", "the", "passed", "+", "record", "+", "to", "the", "index", ".", "Index", "is", "built", "if", "it", "does", "not", "already", "exist", ".", "Clears", "the", "query", "cache", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L54-L61
23,087
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.index_update
def index_update(record) return if self.aai_config.disable_auto_indexing build_index index = new_index index.update_record(record,find(record.id)) @query_cache = {} end
ruby
def index_update(record) return if self.aai_config.disable_auto_indexing build_index index = new_index index.update_record(record,find(record.id)) @query_cache = {} end
[ "def", "index_update", "(", "record", ")", "return", "if", "self", ".", "aai_config", ".", "disable_auto_indexing", "build_index", "index", "=", "new_index", "index", ".", "update_record", "(", "record", ",", "find", "(", "record", ".", "id", ")", ")", "@query_cache", "=", "{", "}", "end" ]
Updates the index. 1. Removes the previous version of the record from the index 2. Adds the new version to the index.
[ "Updates", "the", "index", ".", "1", ".", "Removes", "the", "previous", "version", "of", "the", "record", "from", "the", "index", "2", ".", "Adds", "the", "new", "version", "to", "the", "index", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L77-L84
23,088
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.search_index
def search_index(query, find_options={}, options={}) # Clear the query cache off if the key is set. @query_cache = {} if options[:no_query_cache] # Run the query if not already in cache. if !@query_cache || !@query_cache[query] build_index (@query_cache ||= {})[query] = new_index.search(query) end if options[:ids_only] find_option_keys = find_options.keys.map{ |k| k.to_sym } find_option_keys -= [:limit, :offset] if find_option_keys.any? raise ArgumentError, 'ids_only can not be combined with find option keys other than :offset or :limit' end end if find_options.include?(:order) part_query = @query_cache[query].map{ |r| r.first } else # slice up the results by offset and limit offset = find_options[:offset] || 0 limit = find_options.include?(:limit) ? find_options[:limit] : @query_cache[query].size part_query = sort(@query_cache[query]).slice(offset,limit).map{ |r| r.first } # Set these to nil as we are dealing with the pagination by setting # exactly what records we want. find_options[:offset] = nil find_options[:limit] = nil end return part_query if options[:ids_only] with_scope :find => find_options do # Doing the find like this eliminates the possibility of errors occuring # on either missing records (out-of-sync) or an empty results array. records = find(:all, :conditions => [ "#{table_name}.#{primary_key} IN (?)", part_query]) if find_options.include?(:order) records # Just return the records without ranking them. else # Results come back in random order from SQL, so order again. ranked_records = ActiveSupport::OrderedHash.new records.each do |r| ranked_records[r] = @query_cache[query][r.id] end sort(ranked_records.to_a).map{ |r| r.first } end end end
ruby
def search_index(query, find_options={}, options={}) # Clear the query cache off if the key is set. @query_cache = {} if options[:no_query_cache] # Run the query if not already in cache. if !@query_cache || !@query_cache[query] build_index (@query_cache ||= {})[query] = new_index.search(query) end if options[:ids_only] find_option_keys = find_options.keys.map{ |k| k.to_sym } find_option_keys -= [:limit, :offset] if find_option_keys.any? raise ArgumentError, 'ids_only can not be combined with find option keys other than :offset or :limit' end end if find_options.include?(:order) part_query = @query_cache[query].map{ |r| r.first } else # slice up the results by offset and limit offset = find_options[:offset] || 0 limit = find_options.include?(:limit) ? find_options[:limit] : @query_cache[query].size part_query = sort(@query_cache[query]).slice(offset,limit).map{ |r| r.first } # Set these to nil as we are dealing with the pagination by setting # exactly what records we want. find_options[:offset] = nil find_options[:limit] = nil end return part_query if options[:ids_only] with_scope :find => find_options do # Doing the find like this eliminates the possibility of errors occuring # on either missing records (out-of-sync) or an empty results array. records = find(:all, :conditions => [ "#{table_name}.#{primary_key} IN (?)", part_query]) if find_options.include?(:order) records # Just return the records without ranking them. else # Results come back in random order from SQL, so order again. ranked_records = ActiveSupport::OrderedHash.new records.each do |r| ranked_records[r] = @query_cache[query][r.id] end sort(ranked_records.to_a).map{ |r| r.first } end end end
[ "def", "search_index", "(", "query", ",", "find_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "# Clear the query cache off if the key is set.", "@query_cache", "=", "{", "}", "if", "options", "[", ":no_query_cache", "]", "# Run the query if not already in cache.", "if", "!", "@query_cache", "||", "!", "@query_cache", "[", "query", "]", "build_index", "(", "@query_cache", "||=", "{", "}", ")", "[", "query", "]", "=", "new_index", ".", "search", "(", "query", ")", "end", "if", "options", "[", ":ids_only", "]", "find_option_keys", "=", "find_options", ".", "keys", ".", "map", "{", "|", "k", "|", "k", ".", "to_sym", "}", "find_option_keys", "-=", "[", ":limit", ",", ":offset", "]", "if", "find_option_keys", ".", "any?", "raise", "ArgumentError", ",", "'ids_only can not be combined with find option keys other than :offset or :limit'", "end", "end", "if", "find_options", ".", "include?", "(", ":order", ")", "part_query", "=", "@query_cache", "[", "query", "]", ".", "map", "{", "|", "r", "|", "r", ".", "first", "}", "else", "# slice up the results by offset and limit", "offset", "=", "find_options", "[", ":offset", "]", "||", "0", "limit", "=", "find_options", ".", "include?", "(", ":limit", ")", "?", "find_options", "[", ":limit", "]", ":", "@query_cache", "[", "query", "]", ".", "size", "part_query", "=", "sort", "(", "@query_cache", "[", "query", "]", ")", ".", "slice", "(", "offset", ",", "limit", ")", ".", "map", "{", "|", "r", "|", "r", ".", "first", "}", "# Set these to nil as we are dealing with the pagination by setting", "# exactly what records we want.", "find_options", "[", ":offset", "]", "=", "nil", "find_options", "[", ":limit", "]", "=", "nil", "end", "return", "part_query", "if", "options", "[", ":ids_only", "]", "with_scope", ":find", "=>", "find_options", "do", "# Doing the find like this eliminates the possibility of errors occuring", "# on either missing records (out-of-sync) or an empty results array.", "records", "=", "find", "(", ":all", ",", ":conditions", "=>", "[", "\"#{table_name}.#{primary_key} IN (?)\"", ",", "part_query", "]", ")", "if", "find_options", ".", "include?", "(", ":order", ")", "records", "# Just return the records without ranking them.", "else", "# Results come back in random order from SQL, so order again.", "ranked_records", "=", "ActiveSupport", "::", "OrderedHash", ".", "new", "records", ".", "each", "do", "|", "r", "|", "ranked_records", "[", "r", "]", "=", "@query_cache", "[", "query", "]", "[", "r", ".", "id", "]", "end", "sort", "(", "ranked_records", ".", "to_a", ")", ".", "map", "{", "|", "r", "|", "r", ".", "first", "}", "end", "end", "end" ]
Finds instances matching the terms passed in +query+. Terms are ANDed by default. Returns an array of model instances or, if +ids_only+ is true, an array of integer IDs. Keeps a cache of matched IDs for the current session to speed up multiple identical searches. ====find_options Same as ActiveRecord#find options hash. An :order key will override the relevance ranking ====options ids_only:: Method returns an array of integer IDs when set to true. no_query_cache:: Turns off the query cache when set to true. Useful for testing.
[ "Finds", "instances", "matching", "the", "terms", "passed", "in", "+", "query", "+", ".", "Terms", "are", "ANDed", "by", "default", ".", "Returns", "an", "array", "of", "model", "instances", "or", "if", "+", "ids_only", "+", "is", "true", "an", "array", "of", "integer", "IDs", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L101-L156
23,089
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.build_index
def build_index return if aai_config.index_file.directory? index = new_index find_in_batches({ :batch_size => 500 }) do |records| index.add_records(records) end end
ruby
def build_index return if aai_config.index_file.directory? index = new_index find_in_batches({ :batch_size => 500 }) do |records| index.add_records(records) end end
[ "def", "build_index", "return", "if", "aai_config", ".", "index_file", ".", "directory?", "index", "=", "new_index", "find_in_batches", "(", "{", ":batch_size", "=>", "500", "}", ")", "do", "|", "records", "|", "index", ".", "add_records", "(", "records", ")", "end", "end" ]
Builds an index from scratch for the current model class. Does not run if the index already exists.
[ "Builds", "an", "index", "from", "scratch", "for", "the", "current", "model", "class", ".", "Does", "not", "run", "if", "the", "index", "already", "exists", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L161-L168
23,090
dougal/acts_as_indexed
lib/acts_as_indexed/class_methods.rb
ActsAsIndexed.ClassMethods.sort
def sort(ranked_records) ranked_records.sort { |a, b| a_score = a.last a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id b_score = b.last b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id if a_score == b_score a_id <=> b_id else b_score <=> a_score # We want the records with better relevance first. end } end
ruby
def sort(ranked_records) ranked_records.sort { |a, b| a_score = a.last a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id b_score = b.last b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id if a_score == b_score a_id <=> b_id else b_score <=> a_score # We want the records with better relevance first. end } end
[ "def", "sort", "(", "ranked_records", ")", "ranked_records", ".", "sort", "{", "|", "a", ",", "b", "|", "a_score", "=", "a", ".", "last", "a_id", "=", "a", ".", "first", ".", "is_a?", "(", "Fixnum", ")", "?", "a", ".", "first", ":", "a", ".", "first", ".", "id", "b_score", "=", "b", ".", "last", "b_id", "=", "b", ".", "first", ".", "is_a?", "(", "Fixnum", ")", "?", "b", ".", "first", ":", "b", ".", "first", ".", "id", "if", "a_score", "==", "b_score", "a_id", "<=>", "b_id", "else", "b_score", "<=>", "a_score", "# We want the records with better relevance first.", "end", "}", "end" ]
If two records or record IDs have the same rank, sort them by ID. This prevents a different order being returned by different Rubies.
[ "If", "two", "records", "or", "record", "IDs", "have", "the", "same", "rank", "sort", "them", "by", "ID", ".", "This", "prevents", "a", "different", "order", "being", "returned", "by", "different", "Rubies", "." ]
172dac7899b31857a6513786355b7c4a9bb75093
https://github.com/dougal/acts_as_indexed/blob/172dac7899b31857a6513786355b7c4a9bb75093/lib/acts_as_indexed/class_methods.rb#L174-L189
23,091
le0pard/mongodb_logger
lib/mongodb_logger.rb
MongodbLogger.Base.mongo_fix_session_keys
def mongo_fix_session_keys(session = {}) new_session = Hash.new session.to_hash.each do |i, j| new_session[i.gsub(/\./i, "|")] = j.inspect end unless session.empty? new_session end
ruby
def mongo_fix_session_keys(session = {}) new_session = Hash.new session.to_hash.each do |i, j| new_session[i.gsub(/\./i, "|")] = j.inspect end unless session.empty? new_session end
[ "def", "mongo_fix_session_keys", "(", "session", "=", "{", "}", ")", "new_session", "=", "Hash", ".", "new", "session", ".", "to_hash", ".", "each", "do", "|", "i", ",", "j", "|", "new_session", "[", "i", ".", "gsub", "(", "/", "\\.", "/i", ",", "\"|\"", ")", "]", "=", "j", ".", "inspect", "end", "unless", "session", ".", "empty?", "new_session", "end" ]
session keys can be with dots. It is invalid keys for BSON
[ "session", "keys", "can", "be", "with", "dots", ".", "It", "is", "invalid", "keys", "for", "BSON" ]
102ee484f8c93ae52a46b4605a8b9bdfd538bb66
https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger.rb#L40-L46
23,092
andreapavoni/panoramic
lib/panoramic/resolver.rb
Panoramic.Resolver.find_templates
def find_templates(name, prefix, partial, details, key=nil, locals=[]) return [] if @@resolver_options[:only] && !@@resolver_options[:only].include?(prefix) path = build_path(name, prefix) conditions = { :path => path, :locale => [normalize_array(details[:locale]).first, nil], :format => normalize_array(details[:formats]), :handler => normalize_array(details[:handlers]), :partial => partial || false }.merge(details[:additional_criteria].presence || {}) @@model.find_model_templates(conditions).map do |record| Rails.logger.debug "Rendering template from database: #{path} (#{record.format})" initialize_template(record) end end
ruby
def find_templates(name, prefix, partial, details, key=nil, locals=[]) return [] if @@resolver_options[:only] && !@@resolver_options[:only].include?(prefix) path = build_path(name, prefix) conditions = { :path => path, :locale => [normalize_array(details[:locale]).first, nil], :format => normalize_array(details[:formats]), :handler => normalize_array(details[:handlers]), :partial => partial || false }.merge(details[:additional_criteria].presence || {}) @@model.find_model_templates(conditions).map do |record| Rails.logger.debug "Rendering template from database: #{path} (#{record.format})" initialize_template(record) end end
[ "def", "find_templates", "(", "name", ",", "prefix", ",", "partial", ",", "details", ",", "key", "=", "nil", ",", "locals", "=", "[", "]", ")", "return", "[", "]", "if", "@@resolver_options", "[", ":only", "]", "&&", "!", "@@resolver_options", "[", ":only", "]", ".", "include?", "(", "prefix", ")", "path", "=", "build_path", "(", "name", ",", "prefix", ")", "conditions", "=", "{", ":path", "=>", "path", ",", ":locale", "=>", "[", "normalize_array", "(", "details", "[", ":locale", "]", ")", ".", "first", ",", "nil", "]", ",", ":format", "=>", "normalize_array", "(", "details", "[", ":formats", "]", ")", ",", ":handler", "=>", "normalize_array", "(", "details", "[", ":handlers", "]", ")", ",", ":partial", "=>", "partial", "||", "false", "}", ".", "merge", "(", "details", "[", ":additional_criteria", "]", ".", "presence", "||", "{", "}", ")", "@@model", ".", "find_model_templates", "(", "conditions", ")", ".", "map", "do", "|", "record", "|", "Rails", ".", "logger", ".", "debug", "\"Rendering template from database: #{path} (#{record.format})\"", "initialize_template", "(", "record", ")", "end", "end" ]
this method is mandatory to implement a Resolver
[ "this", "method", "is", "mandatory", "to", "implement", "a", "Resolver" ]
47b3e222b8611914863aa576694e6ee4b619c7f4
https://github.com/andreapavoni/panoramic/blob/47b3e222b8611914863aa576694e6ee4b619c7f4/lib/panoramic/resolver.rb#L7-L23
23,093
andreapavoni/panoramic
lib/panoramic/resolver.rb
Panoramic.Resolver.virtual_path
def virtual_path(path, partial) return path unless partial if index = path.rindex("/") path.insert(index + 1, "_") else "_#{path}" end end
ruby
def virtual_path(path, partial) return path unless partial if index = path.rindex("/") path.insert(index + 1, "_") else "_#{path}" end end
[ "def", "virtual_path", "(", "path", ",", "partial", ")", "return", "path", "unless", "partial", "if", "index", "=", "path", ".", "rindex", "(", "\"/\"", ")", "path", ".", "insert", "(", "index", "+", "1", ",", "\"_\"", ")", "else", "\"_#{path}\"", "end", "end" ]
returns a path depending if its a partial or template
[ "returns", "a", "path", "depending", "if", "its", "a", "partial", "or", "template" ]
47b3e222b8611914863aa576694e6ee4b619c7f4
https://github.com/andreapavoni/panoramic/blob/47b3e222b8611914863aa576694e6ee4b619c7f4/lib/panoramic/resolver.rb#L60-L67
23,094
rikas/slack-poster
lib/slack/poster.rb
Slack.Poster.send_message
def send_message(message) body = message.is_a?(String) ? options.merge(text: message) : options.merge(message.as_json) conn = Faraday.new(url: @base_uri) response = conn.post('', payload: body.to_json) response end
ruby
def send_message(message) body = message.is_a?(String) ? options.merge(text: message) : options.merge(message.as_json) conn = Faraday.new(url: @base_uri) response = conn.post('', payload: body.to_json) response end
[ "def", "send_message", "(", "message", ")", "body", "=", "message", ".", "is_a?", "(", "String", ")", "?", "options", ".", "merge", "(", "text", ":", "message", ")", ":", "options", ".", "merge", "(", "message", ".", "as_json", ")", "conn", "=", "Faraday", ".", "new", "(", "url", ":", "@base_uri", ")", "response", "=", "conn", ".", "post", "(", "''", ",", "payload", ":", "body", ".", "to_json", ")", "response", "end" ]
Initializes a Poster instance to post messages with an incoming webhook URL. It also accepts an options hash. If no options are given then the poster uses the default configuration from Slack integration. ==== Examples # Without options Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va') # With options using a custom username and icon avatar Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va', username: 'Ricardo', icon_url: 'http://www.gravatar.com/avatar/92e00fd27c64c94d04140cef88039468.png') # You can also use an emoji as avatar Slack::Poster.new('https://hooks.slack.com/services/T044G6VBA//TCIzZQQd7IKhQzCKc6W310va', username: 'Ricardo', icon_emoji: 'ghost') Sends a message to Slack. The message can be either plain text or a Slack::Message object. ==== Examples # Plain text message poster.send_message('hello world') # Using a message object poster.send_message(Slack::Message.new(text: 'hello world')) You can have messages with attachments if you build your message with a Slack::Message object and add Slack::Attachment objects.
[ "Initializes", "a", "Poster", "instance", "to", "post", "messages", "with", "an", "incoming", "webhook", "URL", ".", "It", "also", "accepts", "an", "options", "hash", ".", "If", "no", "options", "are", "given", "then", "the", "poster", "uses", "the", "default", "configuration", "from", "Slack", "integration", "." ]
b38d539f3162c286b33b1c3c3f3fbed5bde15654
https://github.com/rikas/slack-poster/blob/b38d539f3162c286b33b1c3c3f3fbed5bde15654/lib/slack/poster.rb#L59-L67
23,095
le0pard/mongodb_logger
lib/mongodb_logger/logger.rb
MongodbLogger.Logger.record_serializer
def record_serializer(rec, nice = true) [:messages, :params].each do |key| if msgs = rec[key] msgs.each do |i, j| msgs[i] = (true == nice ? nice_serialize_object(j) : j.inspect) end end end end
ruby
def record_serializer(rec, nice = true) [:messages, :params].each do |key| if msgs = rec[key] msgs.each do |i, j| msgs[i] = (true == nice ? nice_serialize_object(j) : j.inspect) end end end end
[ "def", "record_serializer", "(", "rec", ",", "nice", "=", "true", ")", "[", ":messages", ",", ":params", "]", ".", "each", "do", "|", "key", "|", "if", "msgs", "=", "rec", "[", "key", "]", "msgs", ".", "each", "do", "|", "i", ",", "j", "|", "msgs", "[", "i", "]", "=", "(", "true", "==", "nice", "?", "nice_serialize_object", "(", "j", ")", ":", "j", ".", "inspect", ")", "end", "end", "end", "end" ]
try to serialyze data by each key and found invalid object
[ "try", "to", "serialyze", "data", "by", "each", "key", "and", "found", "invalid", "object" ]
102ee484f8c93ae52a46b4605a8b9bdfd538bb66
https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger/logger.rb#L210-L218
23,096
le0pard/mongodb_logger
lib/mongodb_logger/replica_set_helper.rb
MongodbLogger.ReplicaSetHelper.rescue_connection_failure
def rescue_connection_failure(max_retries = 40) success = false retries = 0 while !success begin yield success = true rescue mongo_error_type => e raise e if (retries += 1) >= max_retries sleep 0.25 end end end
ruby
def rescue_connection_failure(max_retries = 40) success = false retries = 0 while !success begin yield success = true rescue mongo_error_type => e raise e if (retries += 1) >= max_retries sleep 0.25 end end end
[ "def", "rescue_connection_failure", "(", "max_retries", "=", "40", ")", "success", "=", "false", "retries", "=", "0", "while", "!", "success", "begin", "yield", "success", "=", "true", "rescue", "mongo_error_type", "=>", "e", "raise", "e", "if", "(", "retries", "+=", "1", ")", ">=", "max_retries", "sleep", "0.25", "end", "end", "end" ]
Use retry alg from mongodb to gobble up connection failures during replica set master vote Defaults to a 10 second wait
[ "Use", "retry", "alg", "from", "mongodb", "to", "gobble", "up", "connection", "failures", "during", "replica", "set", "master", "vote", "Defaults", "to", "a", "10", "second", "wait" ]
102ee484f8c93ae52a46b4605a8b9bdfd538bb66
https://github.com/le0pard/mongodb_logger/blob/102ee484f8c93ae52a46b4605a8b9bdfd538bb66/lib/mongodb_logger/replica_set_helper.rb#L5-L17
23,097
kameeoze/jruby-poi
lib/poi/workbook/cell.rb
POI.Cell.error_value
def error_value if poi_cell.cell_type == CELL_TYPE_ERROR error_value_from(poi_cell.error_cell_value) elsif poi_cell.cell_type == CELL_TYPE_FORMULA && poi_cell.cached_formula_result_type == CELL_TYPE_ERROR cell_value = formula_evaluator.evaluate(poi_cell) cell_value && error_value_from(cell_value.error_value) else nil end end
ruby
def error_value if poi_cell.cell_type == CELL_TYPE_ERROR error_value_from(poi_cell.error_cell_value) elsif poi_cell.cell_type == CELL_TYPE_FORMULA && poi_cell.cached_formula_result_type == CELL_TYPE_ERROR cell_value = formula_evaluator.evaluate(poi_cell) cell_value && error_value_from(cell_value.error_value) else nil end end
[ "def", "error_value", "if", "poi_cell", ".", "cell_type", "==", "CELL_TYPE_ERROR", "error_value_from", "(", "poi_cell", ".", "error_cell_value", ")", "elsif", "poi_cell", ".", "cell_type", "==", "CELL_TYPE_FORMULA", "&&", "poi_cell", ".", "cached_formula_result_type", "==", "CELL_TYPE_ERROR", "cell_value", "=", "formula_evaluator", ".", "evaluate", "(", "poi_cell", ")", "cell_value", "&&", "error_value_from", "(", "cell_value", ".", "error_value", ")", "else", "nil", "end", "end" ]
This is NOT an inexpensive operation. The purpose of this method is merely to get more information out of cell when one thinks the value returned is incorrect. It may have more value in development than in production.
[ "This", "is", "NOT", "an", "inexpensive", "operation", ".", "The", "purpose", "of", "this", "method", "is", "merely", "to", "get", "more", "information", "out", "of", "cell", "when", "one", "thinks", "the", "value", "returned", "is", "incorrect", ".", "It", "may", "have", "more", "value", "in", "development", "than", "in", "production", "." ]
c10b7e7ccfd19f132d153834ea0372a67a1d4981
https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/cell.rb#L51-L62
23,098
kameeoze/jruby-poi
lib/poi/workbook/cell.rb
POI.Cell.to_s
def to_s(evaluate_formulas=true) return '' if poi_cell.nil? if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false formula_value else value.to_s end end
ruby
def to_s(evaluate_formulas=true) return '' if poi_cell.nil? if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false formula_value else value.to_s end end
[ "def", "to_s", "(", "evaluate_formulas", "=", "true", ")", "return", "''", "if", "poi_cell", ".", "nil?", "if", "poi_cell", ".", "cell_type", "==", "CELL_TYPE_FORMULA", "&&", "evaluate_formulas", "==", "false", "formula_value", "else", "value", ".", "to_s", "end", "end" ]
Get the String representation of this Cell's value. If this Cell is a formula you can pass a false to this method and get the formula instead of the String representation.
[ "Get", "the", "String", "representation", "of", "this", "Cell", "s", "value", "." ]
c10b7e7ccfd19f132d153834ea0372a67a1d4981
https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/cell.rb#L106-L114
23,099
domgetter/dare
lib/dare/window.rb
Dare.Window.add_mouse_event_listener
def add_mouse_event_listener Element.find("##{@canvas.id}").on :mousemove do |event| coords = get_cursor_position(event) @mouse_x = coords.x[:x] @mouse_y = coords.x[:y] end end
ruby
def add_mouse_event_listener Element.find("##{@canvas.id}").on :mousemove do |event| coords = get_cursor_position(event) @mouse_x = coords.x[:x] @mouse_y = coords.x[:y] end end
[ "def", "add_mouse_event_listener", "Element", ".", "find", "(", "\"##{@canvas.id}\"", ")", ".", "on", ":mousemove", "do", "|", "event", "|", "coords", "=", "get_cursor_position", "(", "event", ")", "@mouse_x", "=", "coords", ".", "x", "[", ":x", "]", "@mouse_y", "=", "coords", ".", "x", "[", ":y", "]", "end", "end" ]
adds mousemove event listener to main canvas
[ "adds", "mousemove", "event", "listener", "to", "main", "canvas" ]
a017efd98275992912f016fefe45a17f00117fe5
https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/window.rb#L68-L74