repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
sight-labs/enchanted_quill
lib/enchanted_quill/label.rb
EnchantedQuill.Label.add_link_attribute
def add_link_attribute(mut_attr_string) range_pointer = Pointer.new(NSRange.type) attributes = mut_attr_string.attributesAtIndex(0, effectiveRange: range_pointer).dup attributes[NSFontAttributeName] = self.font attributes[NSForegroundColorAttributeName] = self.textColor mut_attr_string.addAttributes(attributes, range: range_pointer[0]) active_elements.each do |type, elements| case type when :mention then attributes[NSForegroundColorAttributeName] = mention_color when :hashtag then attributes[NSForegroundColorAttributeName] = hashtag_color when :url then attributes[NSForegroundColorAttributeName] = url_color when :category then attributes[NSForegroundColorAttributeName] = category_color end elements.each do |element| mut_attr_string.setAttributes(attributes, range: element.range) end end end
ruby
def add_link_attribute(mut_attr_string) range_pointer = Pointer.new(NSRange.type) attributes = mut_attr_string.attributesAtIndex(0, effectiveRange: range_pointer).dup attributes[NSFontAttributeName] = self.font attributes[NSForegroundColorAttributeName] = self.textColor mut_attr_string.addAttributes(attributes, range: range_pointer[0]) active_elements.each do |type, elements| case type when :mention then attributes[NSForegroundColorAttributeName] = mention_color when :hashtag then attributes[NSForegroundColorAttributeName] = hashtag_color when :url then attributes[NSForegroundColorAttributeName] = url_color when :category then attributes[NSForegroundColorAttributeName] = category_color end elements.each do |element| mut_attr_string.setAttributes(attributes, range: element.range) end end end
[ "def", "add_link_attribute", "(", "mut_attr_string", ")", "range_pointer", "=", "Pointer", ".", "new", "(", "NSRange", ".", "type", ")", "attributes", "=", "mut_attr_string", ".", "attributesAtIndex", "(", "0", ",", "effectiveRange", ":", "range_pointer", ")", ".", "dup", "attributes", "[", "NSFontAttributeName", "]", "=", "self", ".", "font", "attributes", "[", "NSForegroundColorAttributeName", "]", "=", "self", ".", "textColor", "mut_attr_string", ".", "addAttributes", "(", "attributes", ",", "range", ":", "range_pointer", "[", "0", "]", ")", "active_elements", ".", "each", "do", "|", "type", ",", "elements", "|", "case", "type", "when", ":mention", "then", "attributes", "[", "NSForegroundColorAttributeName", "]", "=", "mention_color", "when", ":hashtag", "then", "attributes", "[", "NSForegroundColorAttributeName", "]", "=", "hashtag_color", "when", ":url", "then", "attributes", "[", "NSForegroundColorAttributeName", "]", "=", "url_color", "when", ":category", "then", "attributes", "[", "NSForegroundColorAttributeName", "]", "=", "category_color", "end", "elements", ".", "each", "do", "|", "element", "|", "mut_attr_string", ".", "setAttributes", "(", "attributes", ",", "range", ":", "element", ".", "range", ")", "end", "end", "end" ]
add link attribute
[ "add", "link", "attribute" ]
d8c70f50fea320878249fec7ed3ea134a4975f32
https://github.com/sight-labs/enchanted_quill/blob/d8c70f50fea320878249fec7ed3ea134a4975f32/lib/enchanted_quill/label.rb#L384-L404
train
bradleyd/shelltastic
lib/shelltastic/utils.rb
ShellTastic.Utils.empty_nil_blank?
def empty_nil_blank?(str, raize=false) result = (str !~ /[^[:space:]]/ || str.nil? || str.empty?) raise ShellTastic::CommandException.new("Command is emtpy or nil") if result and raize result end
ruby
def empty_nil_blank?(str, raize=false) result = (str !~ /[^[:space:]]/ || str.nil? || str.empty?) raise ShellTastic::CommandException.new("Command is emtpy or nil") if result and raize result end
[ "def", "empty_nil_blank?", "(", "str", ",", "raize", "=", "false", ")", "result", "=", "(", "str", "!~", "/", "/", "||", "str", ".", "nil?", "||", "str", ".", "empty?", ")", "raise", "ShellTastic", "::", "CommandException", ".", "new", "(", "\"Command is emtpy or nil\"", ")", "if", "result", "and", "raize", "result", "end" ]
like the other methods but allow to set an exception flag @param [String] str the string the needs to be checked @param [Boolean] to raise an exception or not. DEFAULT is false @return [Boolean] @return [ShellTastic::CommandException]
[ "like", "the", "other", "methods", "but", "allow", "to", "set", "an", "exception", "flag" ]
4004c2b98efb8882d5b702b9c5d69e15cc38cc38
https://github.com/bradleyd/shelltastic/blob/4004c2b98efb8882d5b702b9c5d69e15cc38cc38/lib/shelltastic/utils.rb#L25-L29
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.load_config
def load_config path = ENV['HOME'] + '/.nadb.config' if !File.exists?(path) return end @config = JSON.parse(File.read(path)) end
ruby
def load_config path = ENV['HOME'] + '/.nadb.config' if !File.exists?(path) return end @config = JSON.parse(File.read(path)) end
[ "def", "load_config", "path", "=", "ENV", "[", "'HOME'", "]", "+", "'/.nadb.config'", "if", "!", "File", ".", "exists?", "(", "path", ")", "return", "end", "@config", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "path", ")", ")", "end" ]
Load config from the file if any exists
[ "Load", "config", "from", "the", "file", "if", "any", "exists" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L41-L48
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.run_adb_command
def run_adb_command(command, device = nil) full_command = construct_adb_command command, device puts full_command pio = IO.popen(full_command, 'w') Process.wait(pio.pid) end
ruby
def run_adb_command(command, device = nil) full_command = construct_adb_command command, device puts full_command pio = IO.popen(full_command, 'w') Process.wait(pio.pid) end
[ "def", "run_adb_command", "(", "command", ",", "device", "=", "nil", ")", "full_command", "=", "construct_adb_command", "command", ",", "device", "puts", "full_command", "pio", "=", "IO", ".", "popen", "(", "full_command", ",", "'w'", ")", "Process", ".", "wait", "(", "pio", ".", "pid", ")", "end" ]
Run an adb commd on specified device, optionally printing the output
[ "Run", "an", "adb", "commd", "on", "specified", "device", "optionally", "printing", "the", "output" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L66-L72
train
hamidp/nadb
lib/nadb.rb
Nadb.Tool.get_connected_devices
def get_connected_devices get_adb_command_output('devices') .drop(1) .map { |line| line.split[0] } .reject { |d| d.nil? || d.empty? } end
ruby
def get_connected_devices get_adb_command_output('devices') .drop(1) .map { |line| line.split[0] } .reject { |d| d.nil? || d.empty? } end
[ "def", "get_connected_devices", "get_adb_command_output", "(", "'devices'", ")", ".", "drop", "(", "1", ")", ".", "map", "{", "|", "line", "|", "line", ".", "split", "[", "0", "]", "}", ".", "reject", "{", "|", "d", "|", "d", ".", "nil?", "||", "d", ".", "empty?", "}", "end" ]
Get all currently connected android devices
[ "Get", "all", "currently", "connected", "android", "devices" ]
8d97f00045af988d551a1e9dc5aa076615628035
https://github.com/hamidp/nadb/blob/8d97f00045af988d551a1e9dc5aa076615628035/lib/nadb.rb#L75-L80
train
fridge-cms/jekyll-fridge
lib/jekyll-fridge/fridge_filters.rb
Jekyll.FridgeFilters.fridge_asset
def fridge_asset(input) return input unless input if input.respond_to?('first') input = input.first['name'] end site = @context.registers[:site] asset_dir = site.config['fridge'].config['asset_dir'] dest_path = File.join(site.dest, asset_dir, input) path = File.join(asset_dir, input) # Check if file already exists if site.keep_files.index(path) != nil return "/#{path}" end asset = site.config['fridge'].client.get("content/upload/#{input}") return input unless asset # play for keeps # this is so jekyll won't clean up the file site.keep_files << path # write file to destination FileUtils.mkdir_p(File.dirname(dest_path)) File.write(dest_path, asset) "/#{path}" end
ruby
def fridge_asset(input) return input unless input if input.respond_to?('first') input = input.first['name'] end site = @context.registers[:site] asset_dir = site.config['fridge'].config['asset_dir'] dest_path = File.join(site.dest, asset_dir, input) path = File.join(asset_dir, input) # Check if file already exists if site.keep_files.index(path) != nil return "/#{path}" end asset = site.config['fridge'].client.get("content/upload/#{input}") return input unless asset # play for keeps # this is so jekyll won't clean up the file site.keep_files << path # write file to destination FileUtils.mkdir_p(File.dirname(dest_path)) File.write(dest_path, asset) "/#{path}" end
[ "def", "fridge_asset", "(", "input", ")", "return", "input", "unless", "input", "if", "input", ".", "respond_to?", "(", "'first'", ")", "input", "=", "input", ".", "first", "[", "'name'", "]", "end", "site", "=", "@context", ".", "registers", "[", ":site", "]", "asset_dir", "=", "site", ".", "config", "[", "'fridge'", "]", ".", "config", "[", "'asset_dir'", "]", "dest_path", "=", "File", ".", "join", "(", "site", ".", "dest", ",", "asset_dir", ",", "input", ")", "path", "=", "File", ".", "join", "(", "asset_dir", ",", "input", ")", "# Check if file already exists", "if", "site", ".", "keep_files", ".", "index", "(", "path", ")", "!=", "nil", "return", "\"/#{path}\"", "end", "asset", "=", "site", ".", "config", "[", "'fridge'", "]", ".", "client", ".", "get", "(", "\"content/upload/#{input}\"", ")", "return", "input", "unless", "asset", "# play for keeps", "# this is so jekyll won't clean up the file", "site", ".", "keep_files", "<<", "path", "# write file to destination", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "dest_path", ")", ")", "File", ".", "write", "(", "dest_path", ",", "asset", ")", "\"/#{path}\"", "end" ]
Filter for fetching assets Writes static file to asset_dir and returns absolute file path
[ "Filter", "for", "fetching", "assets", "Writes", "static", "file", "to", "asset_dir", "and", "returns", "absolute", "file", "path" ]
ac5fa7bd861ba6544ca14cf47eafcf0d15601e4c
https://github.com/fridge-cms/jekyll-fridge/blob/ac5fa7bd861ba6544ca14cf47eafcf0d15601e4c/lib/jekyll-fridge/fridge_filters.rb#L5-L31
train
lacravate/git-trifle
lib/git/trifle.rb
Git.Trifle.cover
def cover(path, options={}) reset = options.delete :reset cook_layer do @dressing << Proc.new { self.reset if commits.any? } if reset Git::Base.open path if can_cover? path end end
ruby
def cover(path, options={}) reset = options.delete :reset cook_layer do @dressing << Proc.new { self.reset if commits.any? } if reset Git::Base.open path if can_cover? path end end
[ "def", "cover", "(", "path", ",", "options", "=", "{", "}", ")", "reset", "=", "options", ".", "delete", ":reset", "cook_layer", "do", "@dressing", "<<", "Proc", ".", "new", "{", "self", ".", "reset", "if", "commits", ".", "any?", "}", "if", "reset", "Git", "::", "Base", ".", "open", "path", "if", "can_cover?", "path", "end", "end" ]
hands on the handler
[ "hands", "on", "the", "handler" ]
43d18284c5b772bb5a2ecd412e8d11d4e8444531
https://github.com/lacravate/git-trifle/blob/43d18284c5b772bb5a2ecd412e8d11d4e8444531/lib/git/trifle.rb#L54-L61
train
tubbo/active_copy
lib/active_copy/finders.rb
ActiveCopy.Finders.matches?
def matches? query query.reduce(true) do |matches, (key, value)| matches = if key == 'tag' return false unless tags.present? tags.include? value else attributes[key] == value end end end
ruby
def matches? query query.reduce(true) do |matches, (key, value)| matches = if key == 'tag' return false unless tags.present? tags.include? value else attributes[key] == value end end end
[ "def", "matches?", "query", "query", ".", "reduce", "(", "true", ")", "do", "|", "matches", ",", "(", "key", ",", "value", ")", "|", "matches", "=", "if", "key", "==", "'tag'", "return", "false", "unless", "tags", ".", "present?", "tags", ".", "include?", "value", "else", "attributes", "[", "key", "]", "==", "value", "end", "end", "end" ]
Test if the query matches this particular model.
[ "Test", "if", "the", "query", "matches", "this", "particular", "model", "." ]
63716fdd9283231e9ed0d8ac6af97633d3e97210
https://github.com/tubbo/active_copy/blob/63716fdd9283231e9ed0d8ac6af97633d3e97210/lib/active_copy/finders.rb#L9-L18
train
alfa-jpn/rails-kvs-driver
lib/rails_kvs_driver/validation_driver_config.rb
RailsKvsDriver.ValidationDriverConfig.validate_driver_config!
def validate_driver_config!(driver_config) raise_argument_error!(:host) unless driver_config.has_key? :host raise_argument_error!(:port) unless driver_config.has_key? :port raise_argument_error!(:namespace) unless driver_config.has_key? :namespace raise_argument_error!(:timeout_sec) unless driver_config.has_key? :timeout_sec raise_argument_error!(:pool_size) unless driver_config.has_key? :pool_size driver_config[:config_key] = :none unless driver_config.has_key? :config_key return driver_config end
ruby
def validate_driver_config!(driver_config) raise_argument_error!(:host) unless driver_config.has_key? :host raise_argument_error!(:port) unless driver_config.has_key? :port raise_argument_error!(:namespace) unless driver_config.has_key? :namespace raise_argument_error!(:timeout_sec) unless driver_config.has_key? :timeout_sec raise_argument_error!(:pool_size) unless driver_config.has_key? :pool_size driver_config[:config_key] = :none unless driver_config.has_key? :config_key return driver_config end
[ "def", "validate_driver_config!", "(", "driver_config", ")", "raise_argument_error!", "(", ":host", ")", "unless", "driver_config", ".", "has_key?", ":host", "raise_argument_error!", "(", ":port", ")", "unless", "driver_config", ".", "has_key?", ":port", "raise_argument_error!", "(", ":namespace", ")", "unless", "driver_config", ".", "has_key?", ":namespace", "raise_argument_error!", "(", ":timeout_sec", ")", "unless", "driver_config", ".", "has_key?", ":timeout_sec", "raise_argument_error!", "(", ":pool_size", ")", "unless", "driver_config", ".", "has_key?", ":pool_size", "driver_config", "[", ":config_key", "]", "=", ":none", "unless", "driver_config", ".", "has_key?", ":config_key", "return", "driver_config", "end" ]
Validate driver_config. This method raise ArgumentError, if missing driver_config. @param driver_config [Hash] driver config. @return [Hash] driver_config
[ "Validate", "driver_config", ".", "This", "method", "raise", "ArgumentError", "if", "missing", "driver_config", "." ]
0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982
https://github.com/alfa-jpn/rails-kvs-driver/blob/0eaf5c649071f9d82dc5f2ff2f4d7efcf32d8982/lib/rails_kvs_driver/validation_driver_config.rb#L8-L18
train
jasonrclark/hometown
lib/hometown/creation_tracer.rb
Hometown.CreationTracer.update_on_instance_created
def update_on_instance_created(clazz, on_instance_created) return unless on_instance_created clazz.instance_eval do def instance_hooks hooks = (self.ancestors + [self]).map do |target| target.instance_variable_get(:@instance_hooks) end hooks.flatten! hooks.compact! hooks.uniq! hooks end @instance_hooks ||= [] @instance_hooks << on_instance_created end end
ruby
def update_on_instance_created(clazz, on_instance_created) return unless on_instance_created clazz.instance_eval do def instance_hooks hooks = (self.ancestors + [self]).map do |target| target.instance_variable_get(:@instance_hooks) end hooks.flatten! hooks.compact! hooks.uniq! hooks end @instance_hooks ||= [] @instance_hooks << on_instance_created end end
[ "def", "update_on_instance_created", "(", "clazz", ",", "on_instance_created", ")", "return", "unless", "on_instance_created", "clazz", ".", "instance_eval", "do", "def", "instance_hooks", "hooks", "=", "(", "self", ".", "ancestors", "+", "[", "self", "]", ")", ".", "map", "do", "|", "target", "|", "target", ".", "instance_variable_get", "(", ":@instance_hooks", ")", "end", "hooks", ".", "flatten!", "hooks", ".", "compact!", "hooks", ".", "uniq!", "hooks", "end", "@instance_hooks", "||=", "[", "]", "@instance_hooks", "<<", "on_instance_created", "end", "end" ]
This hook allows other tracing in Hometown to get a whack at an object after it's been created without forcing them to patch new themselves
[ "This", "hook", "allows", "other", "tracing", "in", "Hometown", "to", "get", "a", "whack", "at", "an", "object", "after", "it", "s", "been", "created", "without", "forcing", "them", "to", "patch", "new", "themselves" ]
1d955bd684d5f9a81134332ae0b474252b793687
https://github.com/jasonrclark/hometown/blob/1d955bd684d5f9a81134332ae0b474252b793687/lib/hometown/creation_tracer.rb#L64-L81
train
mnipper/serket
lib/serket/field_encrypter.rb
Serket.FieldEncrypter.encrypt
def encrypt(field) return if field !~ /\S/ aes = OpenSSL::Cipher.new(symmetric_algorithm) aes_key = aes.random_key iv = aes.random_iv encrypt_data(iv, aes_key, field.force_encoding(encoding)) end
ruby
def encrypt(field) return if field !~ /\S/ aes = OpenSSL::Cipher.new(symmetric_algorithm) aes_key = aes.random_key iv = aes.random_iv encrypt_data(iv, aes_key, field.force_encoding(encoding)) end
[ "def", "encrypt", "(", "field", ")", "return", "if", "field", "!~", "/", "\\S", "/", "aes", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "symmetric_algorithm", ")", "aes_key", "=", "aes", ".", "random_key", "iv", "=", "aes", ".", "random_iv", "encrypt_data", "(", "iv", ",", "aes_key", ",", "field", ".", "force_encoding", "(", "encoding", ")", ")", "end" ]
Return encrypted string according to specified format. Return nil if field is whitespace.
[ "Return", "encrypted", "string", "according", "to", "specified", "format", ".", "Return", "nil", "if", "field", "is", "whitespace", "." ]
a4606071fde8982d794ff1f8fc09c399ac92ba17
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_encrypter.rb#L22-L28
train
mnipper/serket
lib/serket/field_encrypter.rb
Serket.FieldEncrypter.parse
def parse(iv, encrypted_key, encrypted_text) case @format when :delimited [iv, field_delimiter, encrypted_key, field_delimiter, encrypted_text].join('') when :json hash = {} hash['iv'] = iv hash['key'] = encrypted_key hash['message'] = encrypted_text hash.to_json end end
ruby
def parse(iv, encrypted_key, encrypted_text) case @format when :delimited [iv, field_delimiter, encrypted_key, field_delimiter, encrypted_text].join('') when :json hash = {} hash['iv'] = iv hash['key'] = encrypted_key hash['message'] = encrypted_text hash.to_json end end
[ "def", "parse", "(", "iv", ",", "encrypted_key", ",", "encrypted_text", ")", "case", "@format", "when", ":delimited", "[", "iv", ",", "field_delimiter", ",", "encrypted_key", ",", "field_delimiter", ",", "encrypted_text", "]", ".", "join", "(", "''", ")", "when", ":json", "hash", "=", "{", "}", "hash", "[", "'iv'", "]", "=", "iv", "hash", "[", "'key'", "]", "=", "encrypted_key", "hash", "[", "'message'", "]", "=", "encrypted_text", "hash", ".", "to_json", "end", "end" ]
Format the final encrypted string to be returned depending on specified format.
[ "Format", "the", "final", "encrypted", "string", "to", "be", "returned", "depending", "on", "specified", "format", "." ]
a4606071fde8982d794ff1f8fc09c399ac92ba17
https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_encrypter.rb#L55-L66
train
sunchess/cfror
lib/cfror.rb
Cfror.Data.save_cfror_fields
def save_cfror_fields(fields) fields.each do |field, value| field = Cfror::Field.find(field) field.save_value!(self, value) end end
ruby
def save_cfror_fields(fields) fields.each do |field, value| field = Cfror::Field.find(field) field.save_value!(self, value) end end
[ "def", "save_cfror_fields", "(", "fields", ")", "fields", ".", "each", "do", "|", "field", ",", "value", "|", "field", "=", "Cfror", "::", "Field", ".", "find", "(", "field", ")", "field", ".", "save_value!", "(", "self", ",", "value", ")", "end", "end" ]
save fields value
[ "save", "fields", "value" ]
0e5771f7eb50bfab84992c6187572080a63e7a58
https://github.com/sunchess/cfror/blob/0e5771f7eb50bfab84992c6187572080a63e7a58/lib/cfror.rb#L45-L50
train
sunchess/cfror
lib/cfror.rb
Cfror.Data.value_fields_for
def value_fields_for(source, order=nil) fields = self.send(source).fields fields = fields.order(order) if order fields.each do |i| i.set_value_for(self) end fields end
ruby
def value_fields_for(source, order=nil) fields = self.send(source).fields fields = fields.order(order) if order fields.each do |i| i.set_value_for(self) end fields end
[ "def", "value_fields_for", "(", "source", ",", "order", "=", "nil", ")", "fields", "=", "self", ".", "send", "(", "source", ")", ".", "fields", "fields", "=", "fields", ".", "order", "(", "order", ")", "if", "order", "fields", ".", "each", "do", "|", "i", "|", "i", ".", "set_value_for", "(", "self", ")", "end", "fields", "end" ]
set values for fields @param source is symbol of relation method contains include Cfror::Fields
[ "set", "values", "for", "fields" ]
0e5771f7eb50bfab84992c6187572080a63e7a58
https://github.com/sunchess/cfror/blob/0e5771f7eb50bfab84992c6187572080a63e7a58/lib/cfror.rb#L54-L64
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.FormatHandler.method_missing
def method_missing(meth, *_args, &block) format = FormatRegistry.formats[meth] return unless format && format.match?(@route_handler.request) @candidates << format @blocks[meth] = block end
ruby
def method_missing(meth, *_args, &block) format = FormatRegistry.formats[meth] return unless format && format.match?(@route_handler.request) @candidates << format @blocks[meth] = block end
[ "def", "method_missing", "(", "meth", ",", "*", "_args", ",", "&", "block", ")", "format", "=", "FormatRegistry", ".", "formats", "[", "meth", "]", "return", "unless", "format", "&&", "format", ".", "match?", "(", "@route_handler", ".", "request", ")", "@candidates", "<<", "format", "@blocks", "[", "meth", "]", "=", "block", "end" ]
Creates a format handler for a route handler @param [Kawaii::RouteHandler] current route handler @return {FormatHandler} Matches method invoked in end-user code with {FormatBase#key}. If format matches the current request, it saves it for negotiation in {FormatHandler#response}.
[ "Creates", "a", "format", "handler", "for", "a", "route", "handler" ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L31-L36
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.JsonFormat.parse_params
def parse_params(request) json = request.body.read JSON.parse(json).symbolize_keys if json.is_a?(String) && !json.empty? end
ruby
def parse_params(request) json = request.body.read JSON.parse(json).symbolize_keys if json.is_a?(String) && !json.empty? end
[ "def", "parse_params", "(", "request", ")", "json", "=", "request", ".", "body", ".", "read", "JSON", ".", "parse", "(", "json", ")", ".", "symbolize_keys", "if", "json", ".", "is_a?", "(", "String", ")", "&&", "!", "json", ".", "empty?", "end" ]
Parses JSON string in request body if present and converts it to a hash. @param request [Rack::Request] contains information about the current HTTP request @return {Hash} including parsed params or nil
[ "Parses", "JSON", "string", "in", "request", "body", "if", "present", "and", "converts", "it", "to", "a", "hash", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L126-L129
train
bilus/kawaii
lib/kawaii/formats.rb
Kawaii.JsonFormat.encode
def encode(response) json = response.to_json [200, { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => json.length.to_s }, [json]] end
ruby
def encode(response) json = response.to_json [200, { Rack::CONTENT_TYPE => 'application/json', Rack::CONTENT_LENGTH => json.length.to_s }, [json]] end
[ "def", "encode", "(", "response", ")", "json", "=", "response", ".", "to_json", "[", "200", ",", "{", "Rack", "::", "CONTENT_TYPE", "=>", "'application/json'", ",", "Rack", "::", "CONTENT_LENGTH", "=>", "json", ".", "length", ".", "to_s", "}", ",", "[", "json", "]", "]", "end" ]
Encodes response appropriately by converting it to a JSON string. @param response [String, Hash, Array] response from format handler block. @return Rack response {Array}
[ "Encodes", "response", "appropriately", "by", "converting", "it", "to", "a", "JSON", "string", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/formats.rb#L134-L140
train
wenzowski/closync
lib/closync/sync.rb
Closync.Sync.upload!
def upload!(local_file) @remote.directory.files.create( key: local_file.key, body: local_file.body, cache_control: "public, max-age=#{max_age(local_file)}", public: true ) end
ruby
def upload!(local_file) @remote.directory.files.create( key: local_file.key, body: local_file.body, cache_control: "public, max-age=#{max_age(local_file)}", public: true ) end
[ "def", "upload!", "(", "local_file", ")", "@remote", ".", "directory", ".", "files", ".", "create", "(", "key", ":", "local_file", ".", "key", ",", "body", ":", "local_file", ".", "body", ",", "cache_control", ":", "\"public, max-age=#{max_age(local_file)}\"", ",", "public", ":", "true", ")", "end" ]
If file already exists on remote it will be overwritten.
[ "If", "file", "already", "exists", "on", "remote", "it", "will", "be", "overwritten", "." ]
67730c160bcbd25420fb03d749ac086be429284c
https://github.com/wenzowski/closync/blob/67730c160bcbd25420fb03d749ac086be429284c/lib/closync/sync.rb#L46-L53
train
seblindberg/ruby-adam6050
lib/adam6050/password.rb
ADAM6050.Password.obfuscate
def obfuscate(plain) codepoints = plain.codepoints raise FormatError if codepoints.length > 8 password = Array.new(8, 0x0E) codepoints.each_with_index do |c, i| password[i] = (c & 0x40) | (~c & 0x3F) end password.pack 'c*' end
ruby
def obfuscate(plain) codepoints = plain.codepoints raise FormatError if codepoints.length > 8 password = Array.new(8, 0x0E) codepoints.each_with_index do |c, i| password[i] = (c & 0x40) | (~c & 0x3F) end password.pack 'c*' end
[ "def", "obfuscate", "(", "plain", ")", "codepoints", "=", "plain", ".", "codepoints", "raise", "FormatError", "if", "codepoints", ".", "length", ">", "8", "password", "=", "Array", ".", "new", "(", "8", ",", "0x0E", ")", "codepoints", ".", "each_with_index", "do", "|", "c", ",", "i", "|", "password", "[", "i", "]", "=", "(", "c", "&", "0x40", ")", "|", "(", "~", "c", "&", "0x3F", ")", "end", "password", ".", "pack", "'c*'", "end" ]
Transforms a plain text password into an 8 character string recognised by the ADAM-6050. The algorithm, if you can even call it that, used to perform the transformation was found by trial and error. @raise [FormatError] if the plain text password is longer than 8 characters. @param plain [String] the plain text version of the password. @return [String] the obfuscated, 8 character password.
[ "Transforms", "a", "plain", "text", "password", "into", "an", "8", "character", "string", "recognised", "by", "the", "ADAM", "-", "6050", ".", "The", "algorithm", "if", "you", "can", "even", "call", "it", "that", "used", "to", "perform", "the", "transformation", "was", "found", "by", "trial", "and", "error", "." ]
7a8e8c344cc770b25d18ddf43f105d0f19e14d50
https://github.com/seblindberg/ruby-adam6050/blob/7a8e8c344cc770b25d18ddf43f105d0f19e14d50/lib/adam6050/password.rb#L54-L64
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/base.rb
ActiveRecord.Base.to_yaml
def to_yaml(opts = {}) #:nodoc: if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? super else coder = {} encode_with(coder) YAML.quick_emit(self, opts) do |out| out.map(taguri, to_yaml_style) do |map| coder.each { |k, v| map.add(k, v) } end end end end
ruby
def to_yaml(opts = {}) #:nodoc: if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? super else coder = {} encode_with(coder) YAML.quick_emit(self, opts) do |out| out.map(taguri, to_yaml_style) do |map| coder.each { |k, v| map.add(k, v) } end end end end
[ "def", "to_yaml", "(", "opts", "=", "{", "}", ")", "#:nodoc:", "if", "YAML", ".", "const_defined?", "(", ":ENGINE", ")", "&&", "!", "YAML", "::", "ENGINE", ".", "syck?", "super", "else", "coder", "=", "{", "}", "encode_with", "(", "coder", ")", "YAML", ".", "quick_emit", "(", "self", ",", "opts", ")", "do", "|", "out", "|", "out", ".", "map", "(", "taguri", ",", "to_yaml_style", ")", "do", "|", "map", "|", "coder", ".", "each", "{", "|", "k", ",", "v", "|", "map", ".", "add", "(", "k", ",", "v", ")", "}", "end", "end", "end", "end" ]
Hackery to accomodate Syck. Remove for 4.0.
[ "Hackery", "to", "accomodate", "Syck", ".", "Remove", "for", "4", ".", "0", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/base.rb#L652-L664
train
ktonon/code_node
lib/code_node/sexp_walker.rb
CodeNode.SexpWalker.walk
def walk(s = nil) s ||= @root if [:module, :class].member?(s[0]) add_node s elsif find_relations? && s[0] == :call && s.length >= 4 && [:extend, :include].member?(s[2]) && !@graph.scope.empty? add_relation s else walk_siblings s.slice(1..-1) end end
ruby
def walk(s = nil) s ||= @root if [:module, :class].member?(s[0]) add_node s elsif find_relations? && s[0] == :call && s.length >= 4 && [:extend, :include].member?(s[2]) && !@graph.scope.empty? add_relation s else walk_siblings s.slice(1..-1) end end
[ "def", "walk", "(", "s", "=", "nil", ")", "s", "||=", "@root", "if", "[", ":module", ",", ":class", "]", ".", "member?", "(", "s", "[", "0", "]", ")", "add_node", "s", "elsif", "find_relations?", "&&", "s", "[", "0", "]", "==", ":call", "&&", "s", ".", "length", ">=", "4", "&&", "[", ":extend", ",", ":include", "]", ".", "member?", "(", "s", "[", "2", "]", ")", "&&", "!", "@graph", ".", "scope", ".", "empty?", "add_relation", "s", "else", "walk_siblings", "s", ".", "slice", "(", "1", "..", "-", "1", ")", "end", "end" ]
Initialize a walker with a graph and sexp All files in a code base should be walked once in <tt>:find_nodes</tt> mode, and then walked again in <tt>:find_relations</tt> mode. @param graph [IR::Graph] a graph to which nodes and relations will be added @param sexp [Sexp] the root sexp of a ruby file @option opt [Symbol] :mode (:find_nodes) one of <tt>:find_nodes</tt> or <tt>:find_relations</tt> Walk the tree rooted at the given sexp @param s [Sexp] if +nil+ will be the root sexp @return [nil]
[ "Initialize", "a", "walker", "with", "a", "graph", "and", "sexp" ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/lib/code_node/sexp_walker.rb#L23-L32
train
mbj/aql
lib/aql/buffer.rb
AQL.Buffer.delimited
def delimited(nodes, delimiter = ', ') max = nodes.length - 1 nodes.each_with_index do |element, index| element.visit(self) append(delimiter) if index < max end self end
ruby
def delimited(nodes, delimiter = ', ') max = nodes.length - 1 nodes.each_with_index do |element, index| element.visit(self) append(delimiter) if index < max end self end
[ "def", "delimited", "(", "nodes", ",", "delimiter", "=", "', '", ")", "max", "=", "nodes", ".", "length", "-", "1", "nodes", ".", "each_with_index", "do", "|", "element", ",", "index", "|", "element", ".", "visit", "(", "self", ")", "append", "(", "delimiter", ")", "if", "index", "<", "max", "end", "self", "end" ]
Emit delimited nodes @param [Enumerable<Node>] nodes @return [self] @api private
[ "Emit", "delimited", "nodes" ]
b271162935d8351d99be50dab5025d56c972fa25
https://github.com/mbj/aql/blob/b271162935d8351d99be50dab5025d56c972fa25/lib/aql/buffer.rb#L52-L59
train
FronteraConsulting/oanda_ruby_client
lib/oanda_ruby_client/exchange_rates_client.rb
OandaRubyClient.ExchangeRatesClient.rates
def rates(rates_request) rates_uri = "#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}" rates_response = HTTParty.get(rates_uri, headers: oanda_headers) handle_response(rates_response.response) OpenStruct.new(rates_response.parsed_response) end
ruby
def rates(rates_request) rates_uri = "#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}" rates_response = HTTParty.get(rates_uri, headers: oanda_headers) handle_response(rates_response.response) OpenStruct.new(rates_response.parsed_response) end
[ "def", "rates", "(", "rates_request", ")", "rates_uri", "=", "\"#{oanda_endpoint}#{RATES_BASE_PATH}#{rates_request.base_currency}.json?#{rates_request.query_string}\"", "rates_response", "=", "HTTParty", ".", "get", "(", "rates_uri", ",", "headers", ":", "oanda_headers", ")", "handle_response", "(", "rates_response", ".", "response", ")", "OpenStruct", ".", "new", "(", "rates_response", ".", "parsed_response", ")", "end" ]
Returns the exchanges rates based on the specified request @param rates_request [OandaRubyClient::RatesRequest] Request criteria @return [OpenStruct] An object structured similarly to the response from the Exchange Rate API
[ "Returns", "the", "exchanges", "rates", "based", "on", "the", "specified", "request" ]
1230e6a011ea4448597349ea7f46548bcbff2e86
https://github.com/FronteraConsulting/oanda_ruby_client/blob/1230e6a011ea4448597349ea7f46548bcbff2e86/lib/oanda_ruby_client/exchange_rates_client.rb#L30-L35
train
FronteraConsulting/oanda_ruby_client
lib/oanda_ruby_client/exchange_rates_client.rb
OandaRubyClient.ExchangeRatesClient.remaining_quotes
def remaining_quotes remaining_quotes_response = HTTParty.get("#{oanda_endpoint}#{REMAINING_QUOTES_PATH}", headers: oanda_headers) handle_response(remaining_quotes_response.response) remaining_quotes_response.parsed_response['remaining_quotes'] end
ruby
def remaining_quotes remaining_quotes_response = HTTParty.get("#{oanda_endpoint}#{REMAINING_QUOTES_PATH}", headers: oanda_headers) handle_response(remaining_quotes_response.response) remaining_quotes_response.parsed_response['remaining_quotes'] end
[ "def", "remaining_quotes", "remaining_quotes_response", "=", "HTTParty", ".", "get", "(", "\"#{oanda_endpoint}#{REMAINING_QUOTES_PATH}\"", ",", "headers", ":", "oanda_headers", ")", "handle_response", "(", "remaining_quotes_response", ".", "response", ")", "remaining_quotes_response", ".", "parsed_response", "[", "'remaining_quotes'", "]", "end" ]
Returns the number of remaining quote requests @return [Fixnum, 'unlimited'] Number of remaining quote requests
[ "Returns", "the", "number", "of", "remaining", "quote", "requests" ]
1230e6a011ea4448597349ea7f46548bcbff2e86
https://github.com/FronteraConsulting/oanda_ruby_client/blob/1230e6a011ea4448597349ea7f46548bcbff2e86/lib/oanda_ruby_client/exchange_rates_client.rb#L40-L44
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.reset_motor_position
def reset_motor_position port, set_relative transmit( DirectOps::NO_RESPONSE, DirectOps::RESETMOTORPOSITION, normalize_motor_port(port), normalize_boolean(set_relative) ) end
ruby
def reset_motor_position port, set_relative transmit( DirectOps::NO_RESPONSE, DirectOps::RESETMOTORPOSITION, normalize_motor_port(port), normalize_boolean(set_relative) ) end
[ "def", "reset_motor_position", "port", ",", "set_relative", "transmit", "(", "DirectOps", "::", "NO_RESPONSE", ",", "DirectOps", "::", "RESETMOTORPOSITION", ",", "normalize_motor_port", "(", "port", ")", ",", "normalize_boolean", "(", "set_relative", ")", ")", "end" ]
Resets the tracking for the motor position. @param [Symbol] port The port the motor is attached to. Should be `:a`, `:b`, or `:c` @param [Boolean] set_relative Sets the position tracking to relative if true, otherwise absolute if false. @return [nil]
[ "Resets", "the", "tracking", "for", "the", "motor", "position", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L104-L111
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.run_motor
def run_motor port, power=100 raise ArgumentError.new("Power must be -100 through 100") if power < -100 || power > 100 transmit( DirectOps::NO_RESPONSE, DirectOps::SETOUTPUTSTATE, normalize_motor_port(port, true), sbyte(power), # power set point byte(1), # mode byte(0), # regulation mode sbyte(0), # turn ratio byte(0x20), # run state long(0), # tacho limit ) end
ruby
def run_motor port, power=100 raise ArgumentError.new("Power must be -100 through 100") if power < -100 || power > 100 transmit( DirectOps::NO_RESPONSE, DirectOps::SETOUTPUTSTATE, normalize_motor_port(port, true), sbyte(power), # power set point byte(1), # mode byte(0), # regulation mode sbyte(0), # turn ratio byte(0x20), # run state long(0), # tacho limit ) end
[ "def", "run_motor", "port", ",", "power", "=", "100", "raise", "ArgumentError", ".", "new", "(", "\"Power must be -100 through 100\"", ")", "if", "power", "<", "-", "100", "||", "power", ">", "100", "transmit", "(", "DirectOps", "::", "NO_RESPONSE", ",", "DirectOps", "::", "SETOUTPUTSTATE", ",", "normalize_motor_port", "(", "port", ",", "true", ")", ",", "sbyte", "(", "power", ")", ",", "# power set point", "byte", "(", "1", ")", ",", "# mode", "byte", "(", "0", ")", ",", "# regulation mode", "sbyte", "(", "0", ")", ",", "# turn ratio", "byte", "(", "0x20", ")", ",", "# run state", "long", "(", "0", ")", ",", "# tacho limit", ")", "end" ]
Runs the motor @param [Symbol] port The port the motor is attached to. Should be `:a`, `:b`, `:c`, `:all` @param [Integer] power A number between -100 through 100 inclusive. Defaults to 100. @return [nil]
[ "Runs", "the", "motor" ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L118-L131
train
docwhat/lego_nxt
lib/lego_nxt/low_level/brick.rb
LegoNXT::LowLevel.Brick.transceive
def transceive *bits bitstring = bits.map(&:byte_string).join("") retval = connection.transceive bitstring # Check that it's a response bit. raise ::LegoNXT::BadResponseError unless retval[0] == "\x02" # Check that it's for this command. raise ::LegoNXT::BadResponseError unless retval[1] == bitstring[1] # Check that there is no error. # TODO: This should raise a specific error based on the status bit. raise ::LegoNXT::StatusError unless retval[2] == "\x00" return retval[3..-1] end
ruby
def transceive *bits bitstring = bits.map(&:byte_string).join("") retval = connection.transceive bitstring # Check that it's a response bit. raise ::LegoNXT::BadResponseError unless retval[0] == "\x02" # Check that it's for this command. raise ::LegoNXT::BadResponseError unless retval[1] == bitstring[1] # Check that there is no error. # TODO: This should raise a specific error based on the status bit. raise ::LegoNXT::StatusError unless retval[2] == "\x00" return retval[3..-1] end
[ "def", "transceive", "*", "bits", "bitstring", "=", "bits", ".", "map", "(", ":byte_string", ")", ".", "join", "(", "\"\"", ")", "retval", "=", "connection", ".", "transceive", "bitstring", "# Check that it's a response bit.", "raise", "::", "LegoNXT", "::", "BadResponseError", "unless", "retval", "[", "0", "]", "==", "\"\\x02\"", "# Check that it's for this command.", "raise", "::", "LegoNXT", "::", "BadResponseError", "unless", "retval", "[", "1", "]", "==", "bitstring", "[", "1", "]", "# Check that there is no error.", "# TODO: This should raise a specific error based on the status bit.", "raise", "::", "LegoNXT", "::", "StatusError", "unless", "retval", "[", "2", "]", "==", "\"\\x00\"", "return", "retval", "[", "3", "..", "-", "1", "]", "end" ]
A wrapper around the transceive function for the connection. The first three bytes of the return value are stripped off. Errors are raised if they show a problem. @param [LegoNXT::Type] bits A list of bytes. @return [String] The bytes returned; bytes 0 through 2 are stripped.
[ "A", "wrapper", "around", "the", "transceive", "function", "for", "the", "connection", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/brick.rb#L157-L168
train