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
24,400
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.require_module_to_base
def require_module_to_base file = File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") file.each do |line| while line == "require_relative './modules/#{@module_name}_apis'\n" do $stdout.puts "\e[33mModule already mounted.\e[0m" return true end end File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") do |f| pos = f.pos rest = f.read f.seek pos f.write("require_relative './modules/") f.write(@module_name) f.write("_apis'\n") f.write(rest) end return false end
ruby
def require_module_to_base file = File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") file.each do |line| while line == "require_relative './modules/#{@module_name}_apis'\n" do $stdout.puts "\e[33mModule already mounted.\e[0m" return true end end File.open("#{@target_dir}/app/apis/#{@project_name}/base.rb", "r+") do |f| pos = f.pos rest = f.read f.seek pos f.write("require_relative './modules/") f.write(@module_name) f.write("_apis'\n") f.write(rest) end return false end
[ "def", "require_module_to_base", "file", "=", "File", ".", "open", "(", "\"#{@target_dir}/app/apis/#{@project_name}/base.rb\"", ",", "\"r+\"", ")", "file", ".", "each", "do", "|", "line", "|", "while", "line", "==", "\"require_relative './modules/#{@module_name}_apis'\\n\"", "do", "$stdout", ".", "puts", "\"\\e[33mModule already mounted.\\e[0m\"", "return", "true", "end", "end", "File", ".", "open", "(", "\"#{@target_dir}/app/apis/#{@project_name}/base.rb\"", ",", "\"r+\"", ")", "do", "|", "f", "|", "pos", "=", "f", ".", "pos", "rest", "=", "f", ".", "read", "f", ".", "seek", "pos", "f", ".", "write", "(", "\"require_relative './modules/\"", ")", "f", ".", "write", "(", "@module_name", ")", "f", ".", "write", "(", "\"_apis'\\n\"", ")", "f", ".", "write", "(", "rest", ")", "end", "return", "false", "end" ]
=begin Checks whether the module is already mounted and if not then configures for mounting. =end
[ "=", "begin", "Checks", "whether", "the", "module", "is", "already", "mounted", "and", "if", "not", "then", "configures", "for", "mounting", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L96-L115
24,401
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.copy_module
def copy_module src = "#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb" dest = "#{@target_dir}/app/apis/#{@project_name}/modules" presence = File.exists?("#{dest}/#{@module_name}_apis.rb")? true : false FileUtils.mkdir dest unless File.exists?(dest) FileUtils.cp(src,dest) unless presence configure_module_files $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" unless presence end
ruby
def copy_module src = "#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb" dest = "#{@target_dir}/app/apis/#{@project_name}/modules" presence = File.exists?("#{dest}/#{@module_name}_apis.rb")? true : false FileUtils.mkdir dest unless File.exists?(dest) FileUtils.cp(src,dest) unless presence configure_module_files $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" unless presence end
[ "def", "copy_module", "src", "=", "\"#{@gem_path}/lib/modules/#{@module_name}/#{@module_name}_apis.rb\"", "dest", "=", "\"#{@target_dir}/app/apis/#{@project_name}/modules\"", "presence", "=", "File", ".", "exists?", "(", "\"#{dest}/#{@module_name}_apis.rb\"", ")", "?", "true", ":", "false", "FileUtils", ".", "mkdir", "dest", "unless", "File", ".", "exists?", "(", "dest", ")", "FileUtils", ".", "cp", "(", "src", ",", "dest", ")", "unless", "presence", "configure_module_files", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"", "unless", "presence", "end" ]
=begin Function to copy the module of interest to project location. =end
[ "=", "begin", "Function", "to", "copy", "the", "module", "of", "interest", "to", "project", "location", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L120-L128
24,402
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.create_migrations_and_models
def create_migrations_and_models src = "#{@gem_path}/lib/modules/migrations" dest = "#{@target_dir}/db/migrate" copy_files(src,dest,AUTH_MIGRATE) if @module_name == "oauth" copy_files(src,dest,OAUTH_MIGRATE) end src_path = "#{@gem_path}/lib/modules/models" dest_path = "#{@target_dir}/app/models" copy_files(src_path,dest_path,AUTH_MODELS) if @module_name == "oauth" copy_files(src_path,dest_path,OAUTH_MODELS) end end
ruby
def create_migrations_and_models src = "#{@gem_path}/lib/modules/migrations" dest = "#{@target_dir}/db/migrate" copy_files(src,dest,AUTH_MIGRATE) if @module_name == "oauth" copy_files(src,dest,OAUTH_MIGRATE) end src_path = "#{@gem_path}/lib/modules/models" dest_path = "#{@target_dir}/app/models" copy_files(src_path,dest_path,AUTH_MODELS) if @module_name == "oauth" copy_files(src_path,dest_path,OAUTH_MODELS) end end
[ "def", "create_migrations_and_models", "src", "=", "\"#{@gem_path}/lib/modules/migrations\"", "dest", "=", "\"#{@target_dir}/db/migrate\"", "copy_files", "(", "src", ",", "dest", ",", "AUTH_MIGRATE", ")", "if", "@module_name", "==", "\"oauth\"", "copy_files", "(", "src", ",", "dest", ",", "OAUTH_MIGRATE", ")", "end", "src_path", "=", "\"#{@gem_path}/lib/modules/models\"", "dest_path", "=", "\"#{@target_dir}/app/models\"", "copy_files", "(", "src_path", ",", "dest_path", ",", "AUTH_MODELS", ")", "if", "@module_name", "==", "\"oauth\"", "copy_files", "(", "src_path", ",", "dest_path", ",", "OAUTH_MODELS", ")", "end", "end" ]
=begin Function to create the necessary migrations and models. =end
[ "=", "begin", "Function", "to", "create", "the", "necessary", "migrations", "and", "models", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L133-L146
24,403
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.copy_files
def copy_files(src,dest,module_model) module_model.each do |file| presence = File.exists?("#{dest}/#{file}")? true : false unless presence FileUtils.cp("#{src}/#{file}",dest) path = if dest.include? "app" then "app/models" else "db/migrate" end $stdout.puts "\e[1;32m \tcreate\e[0m\t#{path}/#{file}" end end end
ruby
def copy_files(src,dest,module_model) module_model.each do |file| presence = File.exists?("#{dest}/#{file}")? true : false unless presence FileUtils.cp("#{src}/#{file}",dest) path = if dest.include? "app" then "app/models" else "db/migrate" end $stdout.puts "\e[1;32m \tcreate\e[0m\t#{path}/#{file}" end end end
[ "def", "copy_files", "(", "src", ",", "dest", ",", "module_model", ")", "module_model", ".", "each", "do", "|", "file", "|", "presence", "=", "File", ".", "exists?", "(", "\"#{dest}/#{file}\"", ")", "?", "true", ":", "false", "unless", "presence", "FileUtils", ".", "cp", "(", "\"#{src}/#{file}\"", ",", "dest", ")", "path", "=", "if", "dest", ".", "include?", "\"app\"", "then", "\"app/models\"", "else", "\"db/migrate\"", "end", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{path}/#{file}\"", "end", "end", "end" ]
=begin Function to copy the module files to project location. =end
[ "=", "begin", "Function", "to", "copy", "the", "module", "files", "to", "project", "location", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L151-L160
24,404
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.configure_module_files
def configure_module_files source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb" application_module = @project_name.split('_').map(&:capitalize)*'' file = File.read(source) replace = file.gsub(/module Rammer/, "module #{application_module}") File.open(source, "w"){|f| f.puts replace } end
ruby
def configure_module_files source = "#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb" application_module = @project_name.split('_').map(&:capitalize)*'' file = File.read(source) replace = file.gsub(/module Rammer/, "module #{application_module}") File.open(source, "w"){|f| f.puts replace } end
[ "def", "configure_module_files", "source", "=", "\"#{@target_dir}/app/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"", "application_module", "=", "@project_name", ".", "split", "(", "'_'", ")", ".", "map", "(", ":capitalize", ")", "*", "''", "file", "=", "File", ".", "read", "(", "source", ")", "replace", "=", "file", ".", "gsub", "(", "/", "/", ",", "\"module #{application_module}\"", ")", "File", ".", "open", "(", "source", ",", "\"w\"", ")", "{", "|", "f", "|", "f", ".", "puts", "replace", "}", "end" ]
=begin Function to configure the module files. =end
[ "=", "begin", "Function", "to", "configure", "the", "module", "files", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L165-L173
24,405
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.add_gems
def add_gems file = File.open("#{@target_dir}/Gemfile", "r+") file.each do |line| while line == "gem 'oauth2'\n" do return end end File.open("#{@target_dir}/Gemfile", "a+") do |f| f.write("gem 'multi_json'\ngem 'oauth2'\ngem 'songkick-oauth2-provider'\ngem 'ruby_regex'\ngem 'oauth'\n") end $stdout.puts "\e[1;35m \tGemfile\e[0m\tgem 'multi_json'\n\t\tgem 'oauth2' \t\tgem 'songkick-oauth2-provider'\n\t\tgem 'ruby_regex'\n\t\tgem 'oauth'\n" $stdout.puts "\e[1;32m \trun\e[0m\tbundle install" system("bundle install") end
ruby
def add_gems file = File.open("#{@target_dir}/Gemfile", "r+") file.each do |line| while line == "gem 'oauth2'\n" do return end end File.open("#{@target_dir}/Gemfile", "a+") do |f| f.write("gem 'multi_json'\ngem 'oauth2'\ngem 'songkick-oauth2-provider'\ngem 'ruby_regex'\ngem 'oauth'\n") end $stdout.puts "\e[1;35m \tGemfile\e[0m\tgem 'multi_json'\n\t\tgem 'oauth2' \t\tgem 'songkick-oauth2-provider'\n\t\tgem 'ruby_regex'\n\t\tgem 'oauth'\n" $stdout.puts "\e[1;32m \trun\e[0m\tbundle install" system("bundle install") end
[ "def", "add_gems", "file", "=", "File", ".", "open", "(", "\"#{@target_dir}/Gemfile\"", ",", "\"r+\"", ")", "file", ".", "each", "do", "|", "line", "|", "while", "line", "==", "\"gem 'oauth2'\\n\"", "do", "return", "end", "end", "File", ".", "open", "(", "\"#{@target_dir}/Gemfile\"", ",", "\"a+\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "\"gem 'multi_json'\\ngem 'oauth2'\\ngem 'songkick-oauth2-provider'\\ngem 'ruby_regex'\\ngem 'oauth'\\n\"", ")", "end", "$stdout", ".", "puts", "\"\\e[1;35m \\tGemfile\\e[0m\\tgem 'multi_json'\\n\\t\\tgem 'oauth2'\n\\t\\tgem 'songkick-oauth2-provider'\\n\\t\\tgem 'ruby_regex'\\n\\t\\tgem 'oauth'\\n\"", "$stdout", ".", "puts", "\"\\e[1;32m \\trun\\e[0m\\tbundle install\"", "system", "(", "\"bundle install\"", ")", "end" ]
=begin Function to add the module dependency gems to project Gemfile. =end
[ "=", "begin", "Function", "to", "add", "the", "module", "dependency", "gems", "to", "project", "Gemfile", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L178-L192
24,406
qburstruby/rammer-3.0.0
lib/rammer/module_generator.rb
Rammer.ModuleGenerator.unmount_module
def unmount_module path = "#{@target_dir}/app/apis/#{@project_name}" temp_file = "#{path}/tmp.rb" source = "#{path}/base.rb" delete_file = "#{path}/modules/#{@module_name}_apis.rb" File.open(temp_file, "w") do |out_file| File.foreach(source) do |line| unless line == "require_relative './modules/#{@module_name}_apis'\n" out_file.puts line unless line == "\t\tmount #{@module_class}\n" end end FileUtils.mv(temp_file, source) end if File.exists?(delete_file) FileUtils.rm(delete_file) $stdout.puts "\e[1;35m\tunmounted\e[0m\t#{@module_class}" $stdout.puts "\e[1;31m\tdelete\e[0m\t\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" else $stdout.puts "\e[33mModule already unmounted.\e[0m" end end
ruby
def unmount_module path = "#{@target_dir}/app/apis/#{@project_name}" temp_file = "#{path}/tmp.rb" source = "#{path}/base.rb" delete_file = "#{path}/modules/#{@module_name}_apis.rb" File.open(temp_file, "w") do |out_file| File.foreach(source) do |line| unless line == "require_relative './modules/#{@module_name}_apis'\n" out_file.puts line unless line == "\t\tmount #{@module_class}\n" end end FileUtils.mv(temp_file, source) end if File.exists?(delete_file) FileUtils.rm(delete_file) $stdout.puts "\e[1;35m\tunmounted\e[0m\t#{@module_class}" $stdout.puts "\e[1;31m\tdelete\e[0m\t\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb" else $stdout.puts "\e[33mModule already unmounted.\e[0m" end end
[ "def", "unmount_module", "path", "=", "\"#{@target_dir}/app/apis/#{@project_name}\"", "temp_file", "=", "\"#{path}/tmp.rb\"", "source", "=", "\"#{path}/base.rb\"", "delete_file", "=", "\"#{path}/modules/#{@module_name}_apis.rb\"", "File", ".", "open", "(", "temp_file", ",", "\"w\"", ")", "do", "|", "out_file", "|", "File", ".", "foreach", "(", "source", ")", "do", "|", "line", "|", "unless", "line", "==", "\"require_relative './modules/#{@module_name}_apis'\\n\"", "out_file", ".", "puts", "line", "unless", "line", "==", "\"\\t\\tmount #{@module_class}\\n\"", "end", "end", "FileUtils", ".", "mv", "(", "temp_file", ",", "source", ")", "end", "if", "File", ".", "exists?", "(", "delete_file", ")", "FileUtils", ".", "rm", "(", "delete_file", ")", "$stdout", ".", "puts", "\"\\e[1;35m\\tunmounted\\e[0m\\t#{@module_class}\"", "$stdout", ".", "puts", "\"\\e[1;31m\\tdelete\\e[0m\\t\\tapp/apis/#{@project_name}/modules/#{@module_name}_apis.rb\"", "else", "$stdout", ".", "puts", "\"\\e[33mModule already unmounted.\\e[0m\"", "end", "end" ]
=begin Unmounts the modules by removing the respective module files. =end
[ "=", "begin", "Unmounts", "the", "modules", "by", "removing", "the", "respective", "module", "files", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/module_generator.rb#L197-L219
24,407
zombor/Validator
lib/validation/validator.rb
Validation.Rules.rule
def rule(field, definition) field = field.to_sym rules[field] = [] if rules[field].nil? begin if definition.respond_to?(:each_pair) add_parameterized_rules(field, definition) elsif definition.respond_to?(:each) definition.each do |item| if item.respond_to?(:each_pair) add_parameterized_rules(field, item) else add_single_rule(field, item) end end else add_single_rule(field, definition) end rescue NameError => e raise InvalidRule.new(e) end self end
ruby
def rule(field, definition) field = field.to_sym rules[field] = [] if rules[field].nil? begin if definition.respond_to?(:each_pair) add_parameterized_rules(field, definition) elsif definition.respond_to?(:each) definition.each do |item| if item.respond_to?(:each_pair) add_parameterized_rules(field, item) else add_single_rule(field, item) end end else add_single_rule(field, definition) end rescue NameError => e raise InvalidRule.new(e) end self end
[ "def", "rule", "(", "field", ",", "definition", ")", "field", "=", "field", ".", "to_sym", "rules", "[", "field", "]", "=", "[", "]", "if", "rules", "[", "field", "]", ".", "nil?", "begin", "if", "definition", ".", "respond_to?", "(", ":each_pair", ")", "add_parameterized_rules", "(", "field", ",", "definition", ")", "elsif", "definition", ".", "respond_to?", "(", ":each", ")", "definition", ".", "each", "do", "|", "item", "|", "if", "item", ".", "respond_to?", "(", ":each_pair", ")", "add_parameterized_rules", "(", "field", ",", "item", ")", "else", "add_single_rule", "(", "field", ",", "item", ")", "end", "end", "else", "add_single_rule", "(", "field", ",", "definition", ")", "end", "rescue", "NameError", "=>", "e", "raise", "InvalidRule", ".", "new", "(", "e", ")", "end", "self", "end" ]
Define a rule for this object The rule parameter can be one of the following: * a symbol that matches to a class in the Validation::Rule namespace * e.g. rule(:field, :not_empty) * a hash containing the rule as the key and it's parameters as the values * e.g. rule(:field, :length => { :minimum => 3, :maximum => 5 }) * an array combining the two previous types
[ "Define", "a", "rule", "for", "this", "object" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L22-L44
24,408
zombor/Validator
lib/validation/validator.rb
Validation.Rules.valid?
def valid? valid = true rules.each_pair do |field, rules| if ! @obj.respond_to?(field) raise InvalidKey, "cannot validate non-existent field '#{field}'" end rules.each do |r| if ! r.valid_value?(@obj.send(field)) valid = false errors[field] = {:rule => r.error_key, :params => r.params} break end end end @valid = valid end
ruby
def valid? valid = true rules.each_pair do |field, rules| if ! @obj.respond_to?(field) raise InvalidKey, "cannot validate non-existent field '#{field}'" end rules.each do |r| if ! r.valid_value?(@obj.send(field)) valid = false errors[field] = {:rule => r.error_key, :params => r.params} break end end end @valid = valid end
[ "def", "valid?", "valid", "=", "true", "rules", ".", "each_pair", "do", "|", "field", ",", "rules", "|", "if", "!", "@obj", ".", "respond_to?", "(", "field", ")", "raise", "InvalidKey", ",", "\"cannot validate non-existent field '#{field}'\"", "end", "rules", ".", "each", "do", "|", "r", "|", "if", "!", "r", ".", "valid_value?", "(", "@obj", ".", "send", "(", "field", ")", ")", "valid", "=", "false", "errors", "[", "field", "]", "=", "{", ":rule", "=>", "r", ".", "error_key", ",", ":params", "=>", "r", ".", "params", "}", "break", "end", "end", "end", "@valid", "=", "valid", "end" ]
Determines if this object is valid. When a rule fails for a field, this will stop processing further rules. In this way, you'll only get one error per field
[ "Determines", "if", "this", "object", "is", "valid", ".", "When", "a", "rule", "fails", "for", "a", "field", "this", "will", "stop", "processing", "further", "rules", ".", "In", "this", "way", "you", "ll", "only", "get", "one", "error", "per", "field" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L49-L67
24,409
zombor/Validator
lib/validation/validator.rb
Validation.Rules.add_single_rule
def add_single_rule(field, key_or_klass, params = nil) klass = if key_or_klass.respond_to?(:new) key_or_klass else get_rule_class_by_name(key_or_klass) end args = [params].compact rule = klass.new(*args) rule.obj = @obj if rule.respond_to?(:obj=) rules[field] << rule end
ruby
def add_single_rule(field, key_or_klass, params = nil) klass = if key_or_klass.respond_to?(:new) key_or_klass else get_rule_class_by_name(key_or_klass) end args = [params].compact rule = klass.new(*args) rule.obj = @obj if rule.respond_to?(:obj=) rules[field] << rule end
[ "def", "add_single_rule", "(", "field", ",", "key_or_klass", ",", "params", "=", "nil", ")", "klass", "=", "if", "key_or_klass", ".", "respond_to?", "(", ":new", ")", "key_or_klass", "else", "get_rule_class_by_name", "(", "key_or_klass", ")", "end", "args", "=", "[", "params", "]", ".", "compact", "rule", "=", "klass", ".", "new", "(", "args", ")", "rule", ".", "obj", "=", "@obj", "if", "rule", ".", "respond_to?", "(", ":obj=", ")", "rules", "[", "field", "]", "<<", "rule", "end" ]
Adds a single rule to this object
[ "Adds", "a", "single", "rule", "to", "this", "object" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L72-L83
24,410
zombor/Validator
lib/validation/validator.rb
Validation.Rules.add_parameterized_rules
def add_parameterized_rules(field, rules) rules.each_pair do |key, params| add_single_rule(field, key, params) end end
ruby
def add_parameterized_rules(field, rules) rules.each_pair do |key, params| add_single_rule(field, key, params) end end
[ "def", "add_parameterized_rules", "(", "field", ",", "rules", ")", "rules", ".", "each_pair", "do", "|", "key", ",", "params", "|", "add_single_rule", "(", "field", ",", "key", ",", "params", ")", "end", "end" ]
Adds a set of parameterized rules to this object
[ "Adds", "a", "set", "of", "parameterized", "rules", "to", "this", "object" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L86-L90
24,411
zombor/Validator
lib/validation/validator.rb
Validation.Rules.get_rule_class_by_name
def get_rule_class_by_name(klass) klass = camelize(klass) Validation::Rule.const_get(klass) rescue NameError => e raise InvalidRule.new(e) end
ruby
def get_rule_class_by_name(klass) klass = camelize(klass) Validation::Rule.const_get(klass) rescue NameError => e raise InvalidRule.new(e) end
[ "def", "get_rule_class_by_name", "(", "klass", ")", "klass", "=", "camelize", "(", "klass", ")", "Validation", "::", "Rule", ".", "const_get", "(", "klass", ")", "rescue", "NameError", "=>", "e", "raise", "InvalidRule", ".", "new", "(", "e", ")", "end" ]
Resolves the specified rule name to a rule class
[ "Resolves", "the", "specified", "rule", "name", "to", "a", "rule", "class" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L93-L98
24,412
zombor/Validator
lib/validation/validator.rb
Validation.Rules.camelize
def camelize(term) string = term.to_s string = string.sub(/^[a-z\d]*/) { $&.capitalize } string.gsub(/(?:_|(\/))([a-z\d]*)/i) { $2.capitalize }.gsub('/', '::') end
ruby
def camelize(term) string = term.to_s string = string.sub(/^[a-z\d]*/) { $&.capitalize } string.gsub(/(?:_|(\/))([a-z\d]*)/i) { $2.capitalize }.gsub('/', '::') end
[ "def", "camelize", "(", "term", ")", "string", "=", "term", ".", "to_s", "string", "=", "string", ".", "sub", "(", "/", "\\d", "/", ")", "{", "$&", ".", "capitalize", "}", "string", ".", "gsub", "(", "/", "\\/", "\\d", "/i", ")", "{", "$2", ".", "capitalize", "}", ".", "gsub", "(", "'/'", ",", "'::'", ")", "end" ]
Converts a symbol to a class name, taken from rails
[ "Converts", "a", "symbol", "to", "a", "class", "name", "taken", "from", "rails" ]
d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8
https://github.com/zombor/Validator/blob/d0503c8c1c64ba3d90ccb8afe8d3e7ebfa030be8/lib/validation/validator.rb#L101-L105
24,413
redinger/validation_reflection
lib/validation_reflection.rb
ValidationReflection.ClassMethods.remember_validation_metadata
def remember_validation_metadata(validation_type, *attr_names) configuration = attr_names.last.is_a?(::Hash) ? attr_names.pop : {} self.validations ||= [] attr_names.flatten.each do |attr_name| self.validations << ::ActiveRecord::Reflection::MacroReflection.new(validation_type, attr_name.to_sym, configuration, self) end end
ruby
def remember_validation_metadata(validation_type, *attr_names) configuration = attr_names.last.is_a?(::Hash) ? attr_names.pop : {} self.validations ||= [] attr_names.flatten.each do |attr_name| self.validations << ::ActiveRecord::Reflection::MacroReflection.new(validation_type, attr_name.to_sym, configuration, self) end end
[ "def", "remember_validation_metadata", "(", "validation_type", ",", "*", "attr_names", ")", "configuration", "=", "attr_names", ".", "last", ".", "is_a?", "(", "::", "Hash", ")", "?", "attr_names", ".", "pop", ":", "{", "}", "self", ".", "validations", "||=", "[", "]", "attr_names", ".", "flatten", ".", "each", "do", "|", "attr_name", "|", "self", ".", "validations", "<<", "::", "ActiveRecord", "::", "Reflection", "::", "MacroReflection", ".", "new", "(", "validation_type", ",", "attr_name", ".", "to_sym", ",", "configuration", ",", "self", ")", "end", "end" ]
Store validation info for easy and fast access.
[ "Store", "validation", "info", "for", "easy", "and", "fast", "access", "." ]
7c3397e3a6ab32773cf7399455e5c63a0fdc66e9
https://github.com/redinger/validation_reflection/blob/7c3397e3a6ab32773cf7399455e5c63a0fdc66e9/lib/validation_reflection.rb#L81-L87
24,414
TWChennai/capypage
lib/capypage/element.rb
Capypage.Element.element
def element(name, selector, options = {}) define_singleton_method(name) { Element.new(selector, options.merge(:base_element => self)) } end
ruby
def element(name, selector, options = {}) define_singleton_method(name) { Element.new(selector, options.merge(:base_element => self)) } end
[ "def", "element", "(", "name", ",", "selector", ",", "options", "=", "{", "}", ")", "define_singleton_method", "(", "name", ")", "{", "Element", ".", "new", "(", "selector", ",", "options", ".", "merge", "(", ":base_element", "=>", "self", ")", ")", "}", "end" ]
Creates an element @param [String] selector to identify element @param [Hash] options @option options [Capypage::Element] :base_element Base element for the element to be created @option options [Symbol] :select_using Selector to switch at element level
[ "Creates", "an", "element" ]
9ff875b001688201a1008e751b8ccb57aeb59b8b
https://github.com/TWChennai/capypage/blob/9ff875b001688201a1008e751b8ccb57aeb59b8b/lib/capypage/element.rb#L25-L27
24,415
qburstruby/rammer-3.0.0
lib/rammer/rammer_generator.rb
Rammer.RammerGenerator.create_base_dirs
def create_base_dirs BASE_DIR.each do |dir| FileUtils.mkdir "#{@project_name}/#{dir}" $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" end FileUtils.mkdir "#{@project_name}/app/apis/#{@project_name}" $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}" end
ruby
def create_base_dirs BASE_DIR.each do |dir| FileUtils.mkdir "#{@project_name}/#{dir}" $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" end FileUtils.mkdir "#{@project_name}/app/apis/#{@project_name}" $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}" end
[ "def", "create_base_dirs", "BASE_DIR", ".", "each", "do", "|", "dir", "|", "FileUtils", ".", "mkdir", "\"#{@project_name}/#{dir}\"", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"", "end", "FileUtils", ".", "mkdir", "\"#{@project_name}/app/apis/#{@project_name}\"", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}\"", "end" ]
=begin Creates the application base directories. =end
[ "=", "begin", "Creates", "the", "application", "base", "directories", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L89-L96
24,416
qburstruby/rammer-3.0.0
lib/rammer/rammer_generator.rb
Rammer.RammerGenerator.create_api_module
def create_api_module File.open("#{@project_name}/app/apis/#{@project_name}/base.rb", "w") do |f| f.write('module ') f.puts(@module_name) f.write("\tclass Base < Grape::API\n\tend\nend") end $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/base.rb" end
ruby
def create_api_module File.open("#{@project_name}/app/apis/#{@project_name}/base.rb", "w") do |f| f.write('module ') f.puts(@module_name) f.write("\tclass Base < Grape::API\n\tend\nend") end $stdout.puts "\e[1;32m \tcreate\e[0m\tapp/apis/#{@project_name}/base.rb" end
[ "def", "create_api_module", "File", ".", "open", "(", "\"#{@project_name}/app/apis/#{@project_name}/base.rb\"", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "'module '", ")", "f", ".", "puts", "(", "@module_name", ")", "f", ".", "write", "(", "\"\\tclass Base < Grape::API\\n\\tend\\nend\"", ")", "end", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\tapp/apis/#{@project_name}/base.rb\"", "end" ]
=begin Function to create the API modules. =end
[ "=", "begin", "Function", "to", "create", "the", "API", "modules", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L110-L117
24,417
qburstruby/rammer-3.0.0
lib/rammer/rammer_generator.rb
Rammer.RammerGenerator.config_server
def config_server file = File.open("#{@project_name}/server.rb", "r+") file.each do |line| while line == " def response(env)\n" do pos = file.pos rest = file.read file.seek pos file.write("\t::") file.write(@module_name) file.write("::Base.call(env)\n") file.write(rest) $stdout.puts "\e[1;35m \tconfig\e[0m\tserver.rb" return end end end
ruby
def config_server file = File.open("#{@project_name}/server.rb", "r+") file.each do |line| while line == " def response(env)\n" do pos = file.pos rest = file.read file.seek pos file.write("\t::") file.write(@module_name) file.write("::Base.call(env)\n") file.write(rest) $stdout.puts "\e[1;35m \tconfig\e[0m\tserver.rb" return end end end
[ "def", "config_server", "file", "=", "File", ".", "open", "(", "\"#{@project_name}/server.rb\"", ",", "\"r+\"", ")", "file", ".", "each", "do", "|", "line", "|", "while", "line", "==", "\" def response(env)\\n\"", "do", "pos", "=", "file", ".", "pos", "rest", "=", "file", ".", "read", "file", ".", "seek", "pos", "file", ".", "write", "(", "\"\\t::\"", ")", "file", ".", "write", "(", "@module_name", ")", "file", ".", "write", "(", "\"::Base.call(env)\\n\"", ")", "file", ".", "write", "(", "rest", ")", "$stdout", ".", "puts", "\"\\e[1;35m \\tconfig\\e[0m\\tserver.rb\"", "return", "end", "end", "end" ]
=begin Function to configure the Goliath server. =end
[ "=", "begin", "Function", "to", "configure", "the", "Goliath", "server", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L122-L137
24,418
qburstruby/rammer-3.0.0
lib/rammer/rammer_generator.rb
Rammer.RammerGenerator.copy_files_to_target
def copy_files_to_target COMMON_RAMMER_FILES.each do |file| source = File.join("#{@gem_path}/lib/modules/common/",file) FileUtils.cp(source,"#{@project_name}") $stdout.puts "\e[1;32m \tcreate\e[0m\t#{file}" end end
ruby
def copy_files_to_target COMMON_RAMMER_FILES.each do |file| source = File.join("#{@gem_path}/lib/modules/common/",file) FileUtils.cp(source,"#{@project_name}") $stdout.puts "\e[1;32m \tcreate\e[0m\t#{file}" end end
[ "def", "copy_files_to_target", "COMMON_RAMMER_FILES", ".", "each", "do", "|", "file", "|", "source", "=", "File", ".", "join", "(", "\"#{@gem_path}/lib/modules/common/\"", ",", "file", ")", "FileUtils", ".", "cp", "(", "source", ",", "\"#{@project_name}\"", ")", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{file}\"", "end", "end" ]
=begin Function to copy the template files project location. =end
[ "=", "begin", "Function", "to", "copy", "the", "template", "files", "project", "location", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/rammer_generator.rb#L142-L148
24,419
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.create_model_file
def create_model_file dir = "/app/models/#{@scaffold_name}.rb" unless File.exists?(File.join(Dir.pwd,dir)) File.join(Dir.pwd,dir) source = "#{@gem_path}/lib/modules/scaffold/model.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_model @valid = true $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" else $stdout.puts "\e[1;31mError:\e[0m Model named #{@scaffold_name} already exists, aborting." end end
ruby
def create_model_file dir = "/app/models/#{@scaffold_name}.rb" unless File.exists?(File.join(Dir.pwd,dir)) File.join(Dir.pwd,dir) source = "#{@gem_path}/lib/modules/scaffold/model.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_model @valid = true $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" else $stdout.puts "\e[1;31mError:\e[0m Model named #{@scaffold_name} already exists, aborting." end end
[ "def", "create_model_file", "dir", "=", "\"/app/models/#{@scaffold_name}.rb\"", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", "source", "=", "\"#{@gem_path}/lib/modules/scaffold/model.rb\"", "FileUtils", ".", "cp", "(", "source", ",", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "config_model", "@valid", "=", "true", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"", "else", "$stdout", ".", "puts", "\"\\e[1;31mError:\\e[0m Model named #{@scaffold_name} already exists, aborting.\"", "end", "end" ]
=begin Generates the model file with CRED functionality. =end
[ "=", "begin", "Generates", "the", "model", "file", "with", "CRED", "functionality", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L70-L82
24,420
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.create_migration
def create_migration migration_version = Time.now.to_i dir = "/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" unless File.exists?(File.join(Dir.pwd,dir)) source = "#{@gem_path}/lib/modules/scaffold/migration.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_migration(migration_version) $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" end end
ruby
def create_migration migration_version = Time.now.to_i dir = "/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" unless File.exists?(File.join(Dir.pwd,dir)) source = "#{@gem_path}/lib/modules/scaffold/migration.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_migration(migration_version) $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" end end
[ "def", "create_migration", "migration_version", "=", "Time", ".", "now", ".", "to_i", "dir", "=", "\"/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb\"", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "source", "=", "\"#{@gem_path}/lib/modules/scaffold/migration.rb\"", "FileUtils", ".", "cp", "(", "source", ",", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "config_migration", "(", "migration_version", ")", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"", "end", "end" ]
=begin Generates migration files for the scaffold. =end
[ "=", "begin", "Generates", "migration", "files", "for", "the", "scaffold", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L96-L105
24,421
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.config_migration
def config_migration(migration_version) source = "#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" modify_content(source, 'CreateMigration', "Create#{@model_class}s") modify_content(source, 'migration', "#{@scaffold_name}s") @arguments.each do |value| @attributes << value.split(':').first @data_types << value.split(':').last end attribute_data_types = @data_types.reverse @attributes.reverse.each_with_index do |value,index| add_attributes(source, value, attribute_data_types[index]) end end
ruby
def config_migration(migration_version) source = "#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb" modify_content(source, 'CreateMigration', "Create#{@model_class}s") modify_content(source, 'migration', "#{@scaffold_name}s") @arguments.each do |value| @attributes << value.split(':').first @data_types << value.split(':').last end attribute_data_types = @data_types.reverse @attributes.reverse.each_with_index do |value,index| add_attributes(source, value, attribute_data_types[index]) end end
[ "def", "config_migration", "(", "migration_version", ")", "source", "=", "\"#{Dir.pwd}/db/migrate/#{migration_version}_create_#{@scaffold_name}s.rb\"", "modify_content", "(", "source", ",", "'CreateMigration'", ",", "\"Create#{@model_class}s\"", ")", "modify_content", "(", "source", ",", "'migration'", ",", "\"#{@scaffold_name}s\"", ")", "@arguments", ".", "each", "do", "|", "value", "|", "@attributes", "<<", "value", ".", "split", "(", "':'", ")", ".", "first", "@data_types", "<<", "value", ".", "split", "(", "':'", ")", ".", "last", "end", "attribute_data_types", "=", "@data_types", ".", "reverse", "@attributes", ".", "reverse", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "add_attributes", "(", "source", ",", "value", ",", "attribute_data_types", "[", "index", "]", ")", "end", "end" ]
=begin Configures the migration file with the required user input. =end
[ "=", "begin", "Configures", "the", "migration", "file", "with", "the", "required", "user", "input", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L110-L124
24,422
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.add_attributes
def add_attributes(source,attribute,data_type) file = File.open(source, "r+") file.each do |line| while line == " create_table :#{@scaffold_name}s do |t|\n" do pos = file.pos rest = file.read file.seek pos file.write(" t.#{data_type} :#{attribute}\n") file.write(rest) break end end end
ruby
def add_attributes(source,attribute,data_type) file = File.open(source, "r+") file.each do |line| while line == " create_table :#{@scaffold_name}s do |t|\n" do pos = file.pos rest = file.read file.seek pos file.write(" t.#{data_type} :#{attribute}\n") file.write(rest) break end end end
[ "def", "add_attributes", "(", "source", ",", "attribute", ",", "data_type", ")", "file", "=", "File", ".", "open", "(", "source", ",", "\"r+\"", ")", "file", ".", "each", "do", "|", "line", "|", "while", "line", "==", "\" create_table :#{@scaffold_name}s do |t|\\n\"", "do", "pos", "=", "file", ".", "pos", "rest", "=", "file", ".", "read", "file", ".", "seek", "pos", "file", ".", "write", "(", "\" t.#{data_type} :#{attribute}\\n\"", ")", "file", ".", "write", "(", "rest", ")", "break", "end", "end", "end" ]
=begin Edits the migration file with the user specified model attributes. =end
[ "=", "begin", "Edits", "the", "migration", "file", "with", "the", "user", "specified", "model", "attributes", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L129-L141
24,423
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.enable_apis
def enable_apis dir = "/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" base_dir = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s" unless File.exists?(File.join(Dir.pwd,dir)) FileUtils.mkdir base_dir unless File.exists?(base_dir) source = "#{@gem_path}/lib/modules/scaffold/base_apis.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_apis $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" mount_apis end end
ruby
def enable_apis dir = "/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" base_dir = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s" unless File.exists?(File.join(Dir.pwd,dir)) FileUtils.mkdir base_dir unless File.exists?(base_dir) source = "#{@gem_path}/lib/modules/scaffold/base_apis.rb" FileUtils.cp(source,File.join(Dir.pwd,dir)) config_apis $stdout.puts "\e[1;32m \tcreate\e[0m\t#{dir}" mount_apis end end
[ "def", "enable_apis", "dir", "=", "\"/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb\"", "base_dir", "=", "\"#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s\"", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "FileUtils", ".", "mkdir", "base_dir", "unless", "File", ".", "exists?", "(", "base_dir", ")", "source", "=", "\"#{@gem_path}/lib/modules/scaffold/base_apis.rb\"", "FileUtils", ".", "cp", "(", "source", ",", "File", ".", "join", "(", "Dir", ".", "pwd", ",", "dir", ")", ")", "config_apis", "$stdout", ".", "puts", "\"\\e[1;32m \\tcreate\\e[0m\\t#{dir}\"", "mount_apis", "end", "end" ]
=begin Generates the api file with CRED functionality apis enabled. =end
[ "=", "begin", "Generates", "the", "api", "file", "with", "CRED", "functionality", "apis", "enabled", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L146-L157
24,424
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.config_apis
def config_apis source = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" content = ['AppName','ScaffoldName', 'Model', 'model'] replacement = ["#{@project_class}", "#{model_class}s", "#{model_class}", "#{@scaffold_name}"] for i in 0..3 do modify_content(source, content[i], replacement[i]) end end
ruby
def config_apis source = "#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb" content = ['AppName','ScaffoldName', 'Model', 'model'] replacement = ["#{@project_class}", "#{model_class}s", "#{model_class}", "#{@scaffold_name}"] for i in 0..3 do modify_content(source, content[i], replacement[i]) end end
[ "def", "config_apis", "source", "=", "\"#{Dir.pwd}/app/apis/#{@project_name}/#{@scaffold_name}s/base_apis.rb\"", "content", "=", "[", "'AppName'", ",", "'ScaffoldName'", ",", "'Model'", ",", "'model'", "]", "replacement", "=", "[", "\"#{@project_class}\"", ",", "\"#{model_class}s\"", ",", "\"#{model_class}\"", ",", "\"#{@scaffold_name}\"", "]", "for", "i", "in", "0", "..", "3", "do", "modify_content", "(", "source", ",", "content", "[", "i", "]", ",", "replacement", "[", "i", "]", ")", "end", "end" ]
=begin Configures the api file with respect to the user input. =end
[ "=", "begin", "Configures", "the", "api", "file", "with", "respect", "to", "the", "user", "input", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L162-L169
24,425
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.mount_apis
def mount_apis require_apis_to_base mount_class = "::#{@project_class}::#{@model_class}s::BaseApis" file = File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") file.each do |line| while line == "\tclass Base < Grape::API\n" do pos = file.pos rest = file.read file.seek pos file.write("\t\tmount ") file.puts(mount_class) file.write(rest) break end end $stdout.puts "\e[1;35m\tmounted\e[0m\t#{mount_class}" end
ruby
def mount_apis require_apis_to_base mount_class = "::#{@project_class}::#{@model_class}s::BaseApis" file = File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") file.each do |line| while line == "\tclass Base < Grape::API\n" do pos = file.pos rest = file.read file.seek pos file.write("\t\tmount ") file.puts(mount_class) file.write(rest) break end end $stdout.puts "\e[1;35m\tmounted\e[0m\t#{mount_class}" end
[ "def", "mount_apis", "require_apis_to_base", "mount_class", "=", "\"::#{@project_class}::#{@model_class}s::BaseApis\"", "file", "=", "File", ".", "open", "(", "\"#{Dir.pwd}/app/apis/#{@project_name}/base.rb\"", ",", "\"r+\"", ")", "file", ".", "each", "do", "|", "line", "|", "while", "line", "==", "\"\\tclass Base < Grape::API\\n\"", "do", "pos", "=", "file", ".", "pos", "rest", "=", "file", ".", "read", "file", ".", "seek", "pos", "file", ".", "write", "(", "\"\\t\\tmount \"", ")", "file", ".", "puts", "(", "mount_class", ")", "file", ".", "write", "(", "rest", ")", "break", "end", "end", "$stdout", ".", "puts", "\"\\e[1;35m\\tmounted\\e[0m\\t#{mount_class}\"", "end" ]
=begin Mounts the scaffold apis onto the application. =end
[ "=", "begin", "Mounts", "the", "scaffold", "apis", "onto", "the", "application", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L174-L190
24,426
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.require_apis_to_base
def require_apis_to_base File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") do |f| pos = f.pos rest = f.read f.seek pos f.write("require_relative '#{@scaffold_name}s/base_apis'\n") f.write(rest) end end
ruby
def require_apis_to_base File.open("#{Dir.pwd}/app/apis/#{@project_name}/base.rb", "r+") do |f| pos = f.pos rest = f.read f.seek pos f.write("require_relative '#{@scaffold_name}s/base_apis'\n") f.write(rest) end end
[ "def", "require_apis_to_base", "File", ".", "open", "(", "\"#{Dir.pwd}/app/apis/#{@project_name}/base.rb\"", ",", "\"r+\"", ")", "do", "|", "f", "|", "pos", "=", "f", ".", "pos", "rest", "=", "f", ".", "read", "f", ".", "seek", "pos", "f", ".", "write", "(", "\"require_relative '#{@scaffold_name}s/base_apis'\\n\"", ")", "f", ".", "write", "(", "rest", ")", "end", "end" ]
=begin Configures for mounting the scaffold apis. =end
[ "=", "begin", "Configures", "for", "mounting", "the", "scaffold", "apis", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L195-L203
24,427
qburstruby/rammer-3.0.0
lib/rammer/scaffold_generator.rb
Rammer.ScaffoldGenerator.to_underscore
def to_underscore(value) underscore_value = value.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase return underscore_value end
ruby
def to_underscore(value) underscore_value = value.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase return underscore_value end
[ "def", "to_underscore", "(", "value", ")", "underscore_value", "=", "value", ".", "gsub", "(", "/", "/", ",", "'/'", ")", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "tr", "(", "\"-\"", ",", "\"_\"", ")", ".", "downcase", "return", "underscore_value", "end" ]
=begin Converts the string into snake case format. =end
[ "=", "begin", "Converts", "the", "string", "into", "snake", "case", "format", ".", "=", "end" ]
72e19d2eb07fcfe0da5ae8610d74dff44906b529
https://github.com/qburstruby/rammer-3.0.0/blob/72e19d2eb07fcfe0da5ae8610d74dff44906b529/lib/rammer/scaffold_generator.rb#L210-L214
24,428
cryptape/reth
lib/reth/chain_service.rb
Reth.ChainService.knows_block
def knows_block(blockhash) return true if @chain.include?(blockhash) @block_queue.queue.any? {|(block, proto)| block.header.full_hash == blockhash } end
ruby
def knows_block(blockhash) return true if @chain.include?(blockhash) @block_queue.queue.any? {|(block, proto)| block.header.full_hash == blockhash } end
[ "def", "knows_block", "(", "blockhash", ")", "return", "true", "if", "@chain", ".", "include?", "(", "blockhash", ")", "@block_queue", ".", "queue", ".", "any?", "{", "|", "(", "block", ",", "proto", ")", "|", "block", ".", "header", ".", "full_hash", "==", "blockhash", "}", "end" ]
if block is in chain or in queue
[ "if", "block", "is", "in", "chain", "or", "in", "queue" ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/chain_service.rb#L217-L220
24,429
NREL/haystack_ruby
lib/haystack_ruby/config.rb
HaystackRuby.Config.load!
def load!(path, environment = nil) require 'yaml' environment ||= Rails.env conf = YAML.load(File.new(path).read).with_indifferent_access[environment] load_configuration(conf) end
ruby
def load!(path, environment = nil) require 'yaml' environment ||= Rails.env conf = YAML.load(File.new(path).read).with_indifferent_access[environment] load_configuration(conf) end
[ "def", "load!", "(", "path", ",", "environment", "=", "nil", ")", "require", "'yaml'", "environment", "||=", "Rails", ".", "env", "conf", "=", "YAML", ".", "load", "(", "File", ".", "new", "(", "path", ")", ".", "read", ")", ".", "with_indifferent_access", "[", "environment", "]", "load_configuration", "(", "conf", ")", "end" ]
called in railtie
[ "called", "in", "railtie" ]
5ebf8ff74767732f51571ab47f8d10e08ffff1fb
https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/config.rb#L15-L20
24,430
hck/open_nlp
lib/open_nlp/chunker.rb
OpenNlp.Chunker.chunk
def chunk(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) tokens = tokenizer.tokenize(str) pos_tags = pos_tagger.tag(tokens).to_ary chunks = j_instance.chunk(tokens.to_java(:String), pos_tags.to_java(:String)).to_ary build_chunks(chunks, tokens, pos_tags) end
ruby
def chunk(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) tokens = tokenizer.tokenize(str) pos_tags = pos_tagger.tag(tokens).to_ary chunks = j_instance.chunk(tokens.to_java(:String), pos_tags.to_java(:String)).to_ary build_chunks(chunks, tokens, pos_tags) end
[ "def", "chunk", "(", "str", ")", "raise", "ArgumentError", ",", "'str must be a String'", "unless", "str", ".", "is_a?", "(", "String", ")", "tokens", "=", "tokenizer", ".", "tokenize", "(", "str", ")", "pos_tags", "=", "pos_tagger", ".", "tag", "(", "tokens", ")", ".", "to_ary", "chunks", "=", "j_instance", ".", "chunk", "(", "tokens", ".", "to_java", "(", ":String", ")", ",", "pos_tags", ".", "to_java", "(", ":String", ")", ")", ".", "to_ary", "build_chunks", "(", "chunks", ",", "tokens", ",", "pos_tags", ")", "end" ]
Initializes new instance of Chunker @param [OpenNlp::Model] model chunker model @param [Model::Tokenizer] token_model tokenizer model @param [Model::POSTagger] pos_model part-of-speech tagging model Chunks a string into part-of-sentence pieces @param [String] str string to chunk @return [Array] array of chunks with part-of-sentence information
[ "Initializes", "new", "instance", "of", "Chunker" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/chunker.rb#L27-L36
24,431
skroutz/greeklish
lib/greeklish/greeklish_generator.rb
Greeklish.GreeklishGenerator.generate_greeklish_words
def generate_greeklish_words(greek_words) @greeklish_list.clear greek_words.each do |greek_word| @per_word_greeklish.clear initial_token = greek_word digraphs.each_key do |key| greek_word = greek_word.gsub(key, digraphs[key]) end # Convert it back to array of characters. The iterations of each # character will take place through this array. input_token = greek_word.split(//) # Iterate through the characters of the token and generate # greeklish words. input_token.each do |greek_char| add_character(conversions[greek_char]) end @greeklish_list << per_word_greeklish.flatten end @greeklish_list.flatten end
ruby
def generate_greeklish_words(greek_words) @greeklish_list.clear greek_words.each do |greek_word| @per_word_greeklish.clear initial_token = greek_word digraphs.each_key do |key| greek_word = greek_word.gsub(key, digraphs[key]) end # Convert it back to array of characters. The iterations of each # character will take place through this array. input_token = greek_word.split(//) # Iterate through the characters of the token and generate # greeklish words. input_token.each do |greek_char| add_character(conversions[greek_char]) end @greeklish_list << per_word_greeklish.flatten end @greeklish_list.flatten end
[ "def", "generate_greeklish_words", "(", "greek_words", ")", "@greeklish_list", ".", "clear", "greek_words", ".", "each", "do", "|", "greek_word", "|", "@per_word_greeklish", ".", "clear", "initial_token", "=", "greek_word", "digraphs", ".", "each_key", "do", "|", "key", "|", "greek_word", "=", "greek_word", ".", "gsub", "(", "key", ",", "digraphs", "[", "key", "]", ")", "end", "# Convert it back to array of characters. The iterations of each", "# character will take place through this array.", "input_token", "=", "greek_word", ".", "split", "(", "/", "/", ")", "# Iterate through the characters of the token and generate", "# greeklish words.", "input_token", ".", "each", "do", "|", "greek_char", "|", "add_character", "(", "conversions", "[", "greek_char", "]", ")", "end", "@greeklish_list", "<<", "per_word_greeklish", ".", "flatten", "end", "@greeklish_list", ".", "flatten", "end" ]
Gets a list of greek words and generates the greeklish version of each word. @param greek_words a list of greek words @return a list of greeklish words
[ "Gets", "a", "list", "of", "greek", "words", "and", "generates", "the", "greeklish", "version", "of", "each", "word", "." ]
dcb414332d2f31fb281985e2b515b997a33f1bd9
https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greeklish_generator.rb#L87-L113
24,432
hck/open_nlp
lib/open_nlp/sentence_detector.rb
OpenNlp.SentenceDetector.detect
def detect(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.sentDetect(str).to_ary end
ruby
def detect(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.sentDetect(str).to_ary end
[ "def", "detect", "(", "str", ")", "raise", "ArgumentError", ",", "'str must be a String'", "unless", "str", ".", "is_a?", "(", "String", ")", "j_instance", ".", "sentDetect", "(", "str", ")", ".", "to_ary", "end" ]
Detects sentences in a string @param [String] string string to detect sentences in @return [Array<String>] array of detected sentences
[ "Detects", "sentences", "in", "a", "string" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/sentence_detector.rb#L9-L13
24,433
hck/open_nlp
lib/open_nlp/sentence_detector.rb
OpenNlp.SentenceDetector.pos_detect
def pos_detect(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.sentPosDetect(str).map do |span| OpenNlp::Util::Span.new(span.getStart, span.getEnd) end end
ruby
def pos_detect(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.sentPosDetect(str).map do |span| OpenNlp::Util::Span.new(span.getStart, span.getEnd) end end
[ "def", "pos_detect", "(", "str", ")", "raise", "ArgumentError", ",", "'str must be a String'", "unless", "str", ".", "is_a?", "(", "String", ")", "j_instance", ".", "sentPosDetect", "(", "str", ")", ".", "map", "do", "|", "span", "|", "OpenNlp", "::", "Util", "::", "Span", ".", "new", "(", "span", ".", "getStart", ",", "span", ".", "getEnd", ")", "end", "end" ]
Detects sentences in a string and returns array of spans @param [String] str @return [Array<OpenNlp::Util::Span>] array of spans for detected sentences
[ "Detects", "sentences", "in", "a", "string", "and", "returns", "array", "of", "spans" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/sentence_detector.rb#L19-L25
24,434
skroutz/greeklish
lib/greeklish/greek_reverse_stemmer.rb
Greeklish.GreekReverseStemmer.generate_greek_variants
def generate_greek_variants(token_string) # clear the list from variations of the previous greek token @greek_words.clear # add the initial greek token in the greek words @greek_words << token_string # Find the first matching suffix and generate the variants # of this word. SUFFIX_STRINGS.each do |suffix| if (token_string.end_with?(suffix[0])) # Add to greek_words the tokens with the desired suffixes generate_more_greek_words(token_string, suffix[0]) break end end greek_words end
ruby
def generate_greek_variants(token_string) # clear the list from variations of the previous greek token @greek_words.clear # add the initial greek token in the greek words @greek_words << token_string # Find the first matching suffix and generate the variants # of this word. SUFFIX_STRINGS.each do |suffix| if (token_string.end_with?(suffix[0])) # Add to greek_words the tokens with the desired suffixes generate_more_greek_words(token_string, suffix[0]) break end end greek_words end
[ "def", "generate_greek_variants", "(", "token_string", ")", "# clear the list from variations of the previous greek token", "@greek_words", ".", "clear", "# add the initial greek token in the greek words", "@greek_words", "<<", "token_string", "# Find the first matching suffix and generate the variants", "# of this word.", "SUFFIX_STRINGS", ".", "each", "do", "|", "suffix", "|", "if", "(", "token_string", ".", "end_with?", "(", "suffix", "[", "0", "]", ")", ")", "# Add to greek_words the tokens with the desired suffixes", "generate_more_greek_words", "(", "token_string", ",", "suffix", "[", "0", "]", ")", "break", "end", "end", "greek_words", "end" ]
This method generates the greek variants of the greek token that receives. @param token_string the greek word @return a list of the generated greek word variations
[ "This", "method", "generates", "the", "greek", "variants", "of", "the", "greek", "token", "that", "receives", "." ]
dcb414332d2f31fb281985e2b515b997a33f1bd9
https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greek_reverse_stemmer.rb#L82-L100
24,435
hck/open_nlp
lib/open_nlp/named_entity_detector.rb
OpenNlp.NamedEntityDetector.detect
def detect(tokens) raise ArgumentError, 'tokens must be an instance of Array' unless tokens.is_a?(Array) j_instance.find(tokens.to_java(:String)).to_ary end
ruby
def detect(tokens) raise ArgumentError, 'tokens must be an instance of Array' unless tokens.is_a?(Array) j_instance.find(tokens.to_java(:String)).to_ary end
[ "def", "detect", "(", "tokens", ")", "raise", "ArgumentError", ",", "'tokens must be an instance of Array'", "unless", "tokens", ".", "is_a?", "(", "Array", ")", "j_instance", ".", "find", "(", "tokens", ".", "to_java", "(", ":String", ")", ")", ".", "to_ary", "end" ]
Detects names for provided array of tokens @param [Array<String>] tokens tokens to run name detection on @return [Array<Java::opennlp.tools.util.Span>] names detected
[ "Detects", "names", "for", "provided", "array", "of", "tokens" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/named_entity_detector.rb#L9-L13
24,436
cryptape/reth
lib/reth/synchronizer.rb
Reth.Synchronizer.receive_newblock
def receive_newblock(proto, t_block, chain_difficulty) logger.debug 'newblock', proto: proto, block: t_block, chain_difficulty: chain_difficulty, client: proto.peer.remote_client_version if @chain.include?(t_block.header.full_hash) raise AssertError, 'chain difficulty mismatch' unless chain_difficulty == @chain.get(t_block.header.full_hash).chain_difficulty end @protocols[proto] = chain_difficulty if @chainservice.knows_block(t_block.header.full_hash) logger.debug 'known block' return end expected_difficulty = @chain.head.chain_difficulty + t_block.header.difficulty if chain_difficulty >= @chain.head.chain_difficulty # broadcast duplicates filtering is done in chainservice logger.debug 'sufficient difficulty, broadcasting', client: proto.peer.remote_client_version @chainservice.broadcast_newblock t_block, chain_difficulty, proto else age = @chain.head.number - t_block.header.number logger.debug "low difficulty", client: proto.peer.remote_client_version, chain_difficulty: chain_difficulty, expected_difficulty: expected_difficulty, block_age: age if age > MAX_NEWBLOCK_AGE logger.debug 'newblock is too old, not adding', block_age: age, max_age: MAX_NEWBLOCK_AGE return end end if @chainservice.knows_block(t_block.header.prevhash) logger.debug 'adding block' @chainservice.add_block t_block, proto else logger.debug 'missing parent' if @synctask logger.debug 'existing task, discarding' else @synctask = SyncTask.new self, proto, t_block.header.full_hash, chain_difficulty end end end
ruby
def receive_newblock(proto, t_block, chain_difficulty) logger.debug 'newblock', proto: proto, block: t_block, chain_difficulty: chain_difficulty, client: proto.peer.remote_client_version if @chain.include?(t_block.header.full_hash) raise AssertError, 'chain difficulty mismatch' unless chain_difficulty == @chain.get(t_block.header.full_hash).chain_difficulty end @protocols[proto] = chain_difficulty if @chainservice.knows_block(t_block.header.full_hash) logger.debug 'known block' return end expected_difficulty = @chain.head.chain_difficulty + t_block.header.difficulty if chain_difficulty >= @chain.head.chain_difficulty # broadcast duplicates filtering is done in chainservice logger.debug 'sufficient difficulty, broadcasting', client: proto.peer.remote_client_version @chainservice.broadcast_newblock t_block, chain_difficulty, proto else age = @chain.head.number - t_block.header.number logger.debug "low difficulty", client: proto.peer.remote_client_version, chain_difficulty: chain_difficulty, expected_difficulty: expected_difficulty, block_age: age if age > MAX_NEWBLOCK_AGE logger.debug 'newblock is too old, not adding', block_age: age, max_age: MAX_NEWBLOCK_AGE return end end if @chainservice.knows_block(t_block.header.prevhash) logger.debug 'adding block' @chainservice.add_block t_block, proto else logger.debug 'missing parent' if @synctask logger.debug 'existing task, discarding' else @synctask = SyncTask.new self, proto, t_block.header.full_hash, chain_difficulty end end end
[ "def", "receive_newblock", "(", "proto", ",", "t_block", ",", "chain_difficulty", ")", "logger", ".", "debug", "'newblock'", ",", "proto", ":", "proto", ",", "block", ":", "t_block", ",", "chain_difficulty", ":", "chain_difficulty", ",", "client", ":", "proto", ".", "peer", ".", "remote_client_version", "if", "@chain", ".", "include?", "(", "t_block", ".", "header", ".", "full_hash", ")", "raise", "AssertError", ",", "'chain difficulty mismatch'", "unless", "chain_difficulty", "==", "@chain", ".", "get", "(", "t_block", ".", "header", ".", "full_hash", ")", ".", "chain_difficulty", "end", "@protocols", "[", "proto", "]", "=", "chain_difficulty", "if", "@chainservice", ".", "knows_block", "(", "t_block", ".", "header", ".", "full_hash", ")", "logger", ".", "debug", "'known block'", "return", "end", "expected_difficulty", "=", "@chain", ".", "head", ".", "chain_difficulty", "+", "t_block", ".", "header", ".", "difficulty", "if", "chain_difficulty", ">=", "@chain", ".", "head", ".", "chain_difficulty", "# broadcast duplicates filtering is done in chainservice", "logger", ".", "debug", "'sufficient difficulty, broadcasting'", ",", "client", ":", "proto", ".", "peer", ".", "remote_client_version", "@chainservice", ".", "broadcast_newblock", "t_block", ",", "chain_difficulty", ",", "proto", "else", "age", "=", "@chain", ".", "head", ".", "number", "-", "t_block", ".", "header", ".", "number", "logger", ".", "debug", "\"low difficulty\"", ",", "client", ":", "proto", ".", "peer", ".", "remote_client_version", ",", "chain_difficulty", ":", "chain_difficulty", ",", "expected_difficulty", ":", "expected_difficulty", ",", "block_age", ":", "age", "if", "age", ">", "MAX_NEWBLOCK_AGE", "logger", ".", "debug", "'newblock is too old, not adding'", ",", "block_age", ":", "age", ",", "max_age", ":", "MAX_NEWBLOCK_AGE", "return", "end", "end", "if", "@chainservice", ".", "knows_block", "(", "t_block", ".", "header", ".", "prevhash", ")", "logger", ".", "debug", "'adding block'", "@chainservice", ".", "add_block", "t_block", ",", "proto", "else", "logger", ".", "debug", "'missing parent'", "if", "@synctask", "logger", ".", "debug", "'existing task, discarding'", "else", "@synctask", "=", "SyncTask", ".", "new", "self", ",", "proto", ",", "t_block", ".", "header", ".", "full_hash", ",", "chain_difficulty", "end", "end", "end" ]
Called if there's a newblock announced on the network.
[ "Called", "if", "there", "s", "a", "newblock", "announced", "on", "the", "network", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L74-L114
24,437
cryptape/reth
lib/reth/synchronizer.rb
Reth.Synchronizer.receive_status
def receive_status(proto, blockhash, chain_difficulty) logger.debug 'status received', proto: proto, chain_difficulty: chain_difficulty @protocols[proto] = chain_difficulty if @chainservice.knows_block(blockhash) || @synctask logger.debug 'existing task or known hash, discarding' return end if @force_sync blockhash, difficulty = force_sync logger.debug 'starting forced synctask', blockhash: Utils.encode_hex(blockhash) @synctask = SyncTask.new self, proto, blockhash, difficulty elsif chain_difficulty > @chain.head.chain_difficulty logger.debug 'sufficient difficulty' @synctask = SyncTask.new self, proto, blockhash, chain_difficulty end rescue logger.debug $! logger.debug $!.backtrace[0,10].join("\n") end
ruby
def receive_status(proto, blockhash, chain_difficulty) logger.debug 'status received', proto: proto, chain_difficulty: chain_difficulty @protocols[proto] = chain_difficulty if @chainservice.knows_block(blockhash) || @synctask logger.debug 'existing task or known hash, discarding' return end if @force_sync blockhash, difficulty = force_sync logger.debug 'starting forced synctask', blockhash: Utils.encode_hex(blockhash) @synctask = SyncTask.new self, proto, blockhash, difficulty elsif chain_difficulty > @chain.head.chain_difficulty logger.debug 'sufficient difficulty' @synctask = SyncTask.new self, proto, blockhash, chain_difficulty end rescue logger.debug $! logger.debug $!.backtrace[0,10].join("\n") end
[ "def", "receive_status", "(", "proto", ",", "blockhash", ",", "chain_difficulty", ")", "logger", ".", "debug", "'status received'", ",", "proto", ":", "proto", ",", "chain_difficulty", ":", "chain_difficulty", "@protocols", "[", "proto", "]", "=", "chain_difficulty", "if", "@chainservice", ".", "knows_block", "(", "blockhash", ")", "||", "@synctask", "logger", ".", "debug", "'existing task or known hash, discarding'", "return", "end", "if", "@force_sync", "blockhash", ",", "difficulty", "=", "force_sync", "logger", ".", "debug", "'starting forced synctask'", ",", "blockhash", ":", "Utils", ".", "encode_hex", "(", "blockhash", ")", "@synctask", "=", "SyncTask", ".", "new", "self", ",", "proto", ",", "blockhash", ",", "difficulty", "elsif", "chain_difficulty", ">", "@chain", ".", "head", ".", "chain_difficulty", "logger", ".", "debug", "'sufficient difficulty'", "@synctask", "=", "SyncTask", ".", "new", "self", ",", "proto", ",", "blockhash", ",", "chain_difficulty", "end", "rescue", "logger", ".", "debug", "$!", "logger", ".", "debug", "$!", ".", "backtrace", "[", "0", ",", "10", "]", ".", "join", "(", "\"\\n\"", ")", "end" ]
Called if a new peer is connected.
[ "Called", "if", "a", "new", "peer", "is", "connected", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L119-L140
24,438
cryptape/reth
lib/reth/synchronizer.rb
Reth.Synchronizer.receive_newblockhashes
def receive_newblockhashes(proto, newblockhashes) logger.debug 'received newblockhashes', num: newblockhashes.size, proto: proto newblockhashes = newblockhashes.select {|h| [email protected]_block(h) } known = @protocols.include?(proto) if !known || newblockhashes.empty? || @synctask logger.debug 'discarding', known: known, synctask: syncing?, num: newblockhashes.size return end if newblockhashes.size != 1 logger.warn 'supporting only one newblockhash', num: newblockhashes.size end blockhash = newblockhashes[0] logger.debug 'starting synctask for newblockhashes', blockhash: Utils.encode_hex(blockhash) @synctask = SyncTask.new self, proto, blockhash, 0, true end
ruby
def receive_newblockhashes(proto, newblockhashes) logger.debug 'received newblockhashes', num: newblockhashes.size, proto: proto newblockhashes = newblockhashes.select {|h| [email protected]_block(h) } known = @protocols.include?(proto) if !known || newblockhashes.empty? || @synctask logger.debug 'discarding', known: known, synctask: syncing?, num: newblockhashes.size return end if newblockhashes.size != 1 logger.warn 'supporting only one newblockhash', num: newblockhashes.size end blockhash = newblockhashes[0] logger.debug 'starting synctask for newblockhashes', blockhash: Utils.encode_hex(blockhash) @synctask = SyncTask.new self, proto, blockhash, 0, true end
[ "def", "receive_newblockhashes", "(", "proto", ",", "newblockhashes", ")", "logger", ".", "debug", "'received newblockhashes'", ",", "num", ":", "newblockhashes", ".", "size", ",", "proto", ":", "proto", "newblockhashes", "=", "newblockhashes", ".", "select", "{", "|", "h", "|", "!", "@chainservice", ".", "knows_block", "(", "h", ")", "}", "known", "=", "@protocols", ".", "include?", "(", "proto", ")", "if", "!", "known", "||", "newblockhashes", ".", "empty?", "||", "@synctask", "logger", ".", "debug", "'discarding'", ",", "known", ":", "known", ",", "synctask", ":", "syncing?", ",", "num", ":", "newblockhashes", ".", "size", "return", "end", "if", "newblockhashes", ".", "size", "!=", "1", "logger", ".", "warn", "'supporting only one newblockhash'", ",", "num", ":", "newblockhashes", ".", "size", "end", "blockhash", "=", "newblockhashes", "[", "0", "]", "logger", ".", "debug", "'starting synctask for newblockhashes'", ",", "blockhash", ":", "Utils", ".", "encode_hex", "(", "blockhash", ")", "@synctask", "=", "SyncTask", ".", "new", "self", ",", "proto", ",", "blockhash", ",", "0", ",", "true", "end" ]
No way to check if this really an interesting block at this point. Might lead to an amplification attack, need to track this proto and judge usefulness.
[ "No", "way", "to", "check", "if", "this", "really", "an", "interesting", "block", "at", "this", "point", ".", "Might", "lead", "to", "an", "amplification", "attack", "need", "to", "track", "this", "proto", "and", "judge", "usefulness", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/synchronizer.rb#L147-L165
24,439
NREL/haystack_ruby
lib/haystack_ruby/project.rb
HaystackRuby.Project.api_eval
def api_eval(expr_str) body = ["ver:\"#{@haystack_version}\""] body << "expr" body << '"'+expr_str+'"' res = self.connection.post('eval') do |req| req.headers['Content-Type'] = 'text/plain' req.body = body.join("\n") end JSON.parse! res.body end
ruby
def api_eval(expr_str) body = ["ver:\"#{@haystack_version}\""] body << "expr" body << '"'+expr_str+'"' res = self.connection.post('eval') do |req| req.headers['Content-Type'] = 'text/plain' req.body = body.join("\n") end JSON.parse! res.body end
[ "def", "api_eval", "(", "expr_str", ")", "body", "=", "[", "\"ver:\\\"#{@haystack_version}\\\"\"", "]", "body", "<<", "\"expr\"", "body", "<<", "'\"'", "+", "expr_str", "+", "'\"'", "res", "=", "self", ".", "connection", ".", "post", "(", "'eval'", ")", "do", "|", "req", "|", "req", ".", "headers", "[", "'Content-Type'", "]", "=", "'text/plain'", "req", ".", "body", "=", "body", ".", "join", "(", "\"\\n\"", ")", "end", "JSON", ".", "parse!", "res", ".", "body", "end" ]
this function will post expr_str exactly as encoded
[ "this", "function", "will", "post", "expr_str", "exactly", "as", "encoded" ]
5ebf8ff74767732f51571ab47f8d10e08ffff1fb
https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/project.rb#L64-L73
24,440
NREL/haystack_ruby
lib/haystack_ruby/project.rb
HaystackRuby.Project.equip_point_meta
def equip_point_meta begin equips = read({filter: '"equip"'})['rows'] puts equips equips.map! do |eq| eq.delete('disMacro') eq['description'] = eq['id'].match(/[(NWTC)|(\$siteRef)] (.*)/)[1] eq['id'] = eq['id'].match(/:([a-z0-9\-]*)/)[1] eq['points'] = [] read({filter: "\"point and equipRef==#{eq['id']}\""})['rows'].each do |p| p.delete('analytics') p.delete('disMacro') p.delete('csvUnit') p.delete('csvColumn') p.delete('equipRef') p.delete('point') p.delete('siteRef') p['id'] = p['id'].match(/:([a-z0-9\-]*)/)[1] p['name'] = p['navName'] p.delete('navName') eq['points'] << p end eq end rescue Exception => e puts "error: #{e}" nil end end
ruby
def equip_point_meta begin equips = read({filter: '"equip"'})['rows'] puts equips equips.map! do |eq| eq.delete('disMacro') eq['description'] = eq['id'].match(/[(NWTC)|(\$siteRef)] (.*)/)[1] eq['id'] = eq['id'].match(/:([a-z0-9\-]*)/)[1] eq['points'] = [] read({filter: "\"point and equipRef==#{eq['id']}\""})['rows'].each do |p| p.delete('analytics') p.delete('disMacro') p.delete('csvUnit') p.delete('csvColumn') p.delete('equipRef') p.delete('point') p.delete('siteRef') p['id'] = p['id'].match(/:([a-z0-9\-]*)/)[1] p['name'] = p['navName'] p.delete('navName') eq['points'] << p end eq end rescue Exception => e puts "error: #{e}" nil end end
[ "def", "equip_point_meta", "begin", "equips", "=", "read", "(", "{", "filter", ":", "'\"equip\"'", "}", ")", "[", "'rows'", "]", "puts", "equips", "equips", ".", "map!", "do", "|", "eq", "|", "eq", ".", "delete", "(", "'disMacro'", ")", "eq", "[", "'description'", "]", "=", "eq", "[", "'id'", "]", ".", "match", "(", "/", "\\$", "/", ")", "[", "1", "]", "eq", "[", "'id'", "]", "=", "eq", "[", "'id'", "]", ".", "match", "(", "/", "\\-", "/", ")", "[", "1", "]", "eq", "[", "'points'", "]", "=", "[", "]", "read", "(", "{", "filter", ":", "\"\\\"point and equipRef==#{eq['id']}\\\"\"", "}", ")", "[", "'rows'", "]", ".", "each", "do", "|", "p", "|", "p", ".", "delete", "(", "'analytics'", ")", "p", ".", "delete", "(", "'disMacro'", ")", "p", ".", "delete", "(", "'csvUnit'", ")", "p", ".", "delete", "(", "'csvColumn'", ")", "p", ".", "delete", "(", "'equipRef'", ")", "p", ".", "delete", "(", "'point'", ")", "p", ".", "delete", "(", "'siteRef'", ")", "p", "[", "'id'", "]", "=", "p", "[", "'id'", "]", ".", "match", "(", "/", "\\-", "/", ")", "[", "1", "]", "p", "[", "'name'", "]", "=", "p", "[", "'navName'", "]", "p", ".", "delete", "(", "'navName'", ")", "eq", "[", "'points'", "]", "<<", "p", "end", "eq", "end", "rescue", "Exception", "=>", "e", "puts", "\"error: #{e}\"", "nil", "end", "end" ]
return meta data for all equip with related points
[ "return", "meta", "data", "for", "all", "equip", "with", "related", "points" ]
5ebf8ff74767732f51571ab47f8d10e08ffff1fb
https://github.com/NREL/haystack_ruby/blob/5ebf8ff74767732f51571ab47f8d10e08ffff1fb/lib/haystack_ruby/project.rb#L76-L105
24,441
hck/open_nlp
lib/open_nlp/parser.rb
OpenNlp.Parser.parse
def parse(text) raise ArgumentError, 'passed text must be a String' unless text.is_a?(String) text.empty? ? {} : parse_tokens(tokenizer.tokenize(text), text) end
ruby
def parse(text) raise ArgumentError, 'passed text must be a String' unless text.is_a?(String) text.empty? ? {} : parse_tokens(tokenizer.tokenize(text), text) end
[ "def", "parse", "(", "text", ")", "raise", "ArgumentError", ",", "'passed text must be a String'", "unless", "text", ".", "is_a?", "(", "String", ")", "text", ".", "empty?", "?", "{", "}", ":", "parse_tokens", "(", "tokenizer", ".", "tokenize", "(", "text", ")", ",", "text", ")", "end" ]
Initializes new instance of Parser @param [OpenNlp::Model::Parser] parser_model @param [OpenNlp::Model::Tokenizer] token_model Parses text into instance of Parse class @param [String] text text to parse @return [OpenNlp::Parser::Parse]
[ "Initializes", "new", "instance", "of", "Parser" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/parser.rb#L22-L26
24,442
richard-viney/ig_markets
lib/ig_markets/response_parser.rb
IGMarkets.ResponseParser.parse
def parse(response) if response.is_a? Hash response.each_with_object({}) do |(key, value), new_hash| new_hash[camel_case_to_snake_case(key).to_sym] = parse(value) end elsif response.is_a? Array response.map { |item| parse item } else response end end
ruby
def parse(response) if response.is_a? Hash response.each_with_object({}) do |(key, value), new_hash| new_hash[camel_case_to_snake_case(key).to_sym] = parse(value) end elsif response.is_a? Array response.map { |item| parse item } else response end end
[ "def", "parse", "(", "response", ")", "if", "response", ".", "is_a?", "Hash", "response", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "new_hash", "|", "new_hash", "[", "camel_case_to_snake_case", "(", "key", ")", ".", "to_sym", "]", "=", "parse", "(", "value", ")", "end", "elsif", "response", ".", "is_a?", "Array", "response", ".", "map", "{", "|", "item", "|", "parse", "item", "}", "else", "response", "end", "end" ]
Parses the specified value that was returned from a call to the IG Markets API. @param [Hash, Array, Object] response The response or part of a response that should be parsed. If this is of type `Hash` then all hash keys will converted from camel case into snake case and their values will each be parsed individually by a recursive call. If this is of type `Array` then each item will be parsed individually by a recursive call. All other types are passed through unchanged. @return [Hash, Array, Object] The parsed object, the type depends on the type of the `response` parameter.
[ "Parses", "the", "specified", "value", "that", "was", "returned", "from", "a", "call", "to", "the", "IG", "Markets", "API", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/response_parser.rb#L16-L26
24,443
hck/open_nlp
lib/open_nlp/categorizer.rb
OpenNlp.Categorizer.categorize
def categorize(str) raise ArgumentError, 'str param must be a String' unless str.is_a?(String) outcomes = j_instance.categorize(str) j_instance.getBestCategory(outcomes) end
ruby
def categorize(str) raise ArgumentError, 'str param must be a String' unless str.is_a?(String) outcomes = j_instance.categorize(str) j_instance.getBestCategory(outcomes) end
[ "def", "categorize", "(", "str", ")", "raise", "ArgumentError", ",", "'str param must be a String'", "unless", "str", ".", "is_a?", "(", "String", ")", "outcomes", "=", "j_instance", ".", "categorize", "(", "str", ")", "j_instance", ".", "getBestCategory", "(", "outcomes", ")", "end" ]
Categorizes a string passed as parameter to one of the categories @param [String] str string to be categorized @return [String] category
[ "Categorizes", "a", "string", "passed", "as", "parameter", "to", "one", "of", "the", "categories" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/categorizer.rb#L9-L14
24,444
udongo/udongo
lib/udongo/pages/tree_node.rb
Udongo::Pages.TreeNode.data
def data { text: @page.description, type: :file, li_attr: list_attributes, data: { id: @page.id, url: @context.edit_translation_backend_page_path(@page, Udongo.config.i18n.app.default_locale), delete_url: @context.backend_page_path(@page, format: :json), deletable: @page.deletable?, draggable: @page.draggable?, update_position_url: @context.tree_drag_and_drop_backend_page_path(@page), visible: @page.visible?, toggle_visibility_url: @context.toggle_visibility_backend_page_path(@page, format: :json) }, children: [] # This gets filled through Udongo::Pages::Tree } end
ruby
def data { text: @page.description, type: :file, li_attr: list_attributes, data: { id: @page.id, url: @context.edit_translation_backend_page_path(@page, Udongo.config.i18n.app.default_locale), delete_url: @context.backend_page_path(@page, format: :json), deletable: @page.deletable?, draggable: @page.draggable?, update_position_url: @context.tree_drag_and_drop_backend_page_path(@page), visible: @page.visible?, toggle_visibility_url: @context.toggle_visibility_backend_page_path(@page, format: :json) }, children: [] # This gets filled through Udongo::Pages::Tree } end
[ "def", "data", "{", "text", ":", "@page", ".", "description", ",", "type", ":", ":file", ",", "li_attr", ":", "list_attributes", ",", "data", ":", "{", "id", ":", "@page", ".", "id", ",", "url", ":", "@context", ".", "edit_translation_backend_page_path", "(", "@page", ",", "Udongo", ".", "config", ".", "i18n", ".", "app", ".", "default_locale", ")", ",", "delete_url", ":", "@context", ".", "backend_page_path", "(", "@page", ",", "format", ":", ":json", ")", ",", "deletable", ":", "@page", ".", "deletable?", ",", "draggable", ":", "@page", ".", "draggable?", ",", "update_position_url", ":", "@context", ".", "tree_drag_and_drop_backend_page_path", "(", "@page", ")", ",", "visible", ":", "@page", ".", "visible?", ",", "toggle_visibility_url", ":", "@context", ".", "toggle_visibility_backend_page_path", "(", "@page", ",", "format", ":", ":json", ")", "}", ",", "children", ":", "[", "]", "# This gets filled through Udongo::Pages::Tree", "}", "end" ]
Context should contain accessible routes.
[ "Context", "should", "contain", "accessible", "routes", "." ]
868a55ab7107473ce9f3645756b6293759317d02
https://github.com/udongo/udongo/blob/868a55ab7107473ce9f3645756b6293759317d02/lib/udongo/pages/tree_node.rb#L9-L26
24,445
skroutz/greeklish
lib/greeklish/greeklish_converter.rb
Greeklish.GreeklishConverter.identify_greek_word
def identify_greek_word(input) input.each_char do |char| if (!GREEK_CHARACTERS.include?(char)) return false end end true end
ruby
def identify_greek_word(input) input.each_char do |char| if (!GREEK_CHARACTERS.include?(char)) return false end end true end
[ "def", "identify_greek_word", "(", "input", ")", "input", ".", "each_char", "do", "|", "char", "|", "if", "(", "!", "GREEK_CHARACTERS", ".", "include?", "(", "char", ")", ")", "return", "false", "end", "end", "true", "end" ]
Identifies words with only Greek lowercase characters. @param input The string that will examine @return true if the string contains only Greek characters
[ "Identifies", "words", "with", "only", "Greek", "lowercase", "characters", "." ]
dcb414332d2f31fb281985e2b515b997a33f1bd9
https://github.com/skroutz/greeklish/blob/dcb414332d2f31fb281985e2b515b997a33f1bd9/lib/greeklish/greeklish_converter.rb#L77-L85
24,446
richard-viney/ig_markets
lib/ig_markets/position.rb
IGMarkets.Position.close
def close(options = {}) options[:deal_id] = deal_id options[:direction] = { buy: :sell, sell: :buy }.fetch(direction) options[:size] ||= size model = PositionCloseAttributes.build options model.validate body = RequestBodyFormatter.format model @dealing_platform.session.delete('positions/otc', body).fetch :deal_reference end
ruby
def close(options = {}) options[:deal_id] = deal_id options[:direction] = { buy: :sell, sell: :buy }.fetch(direction) options[:size] ||= size model = PositionCloseAttributes.build options model.validate body = RequestBodyFormatter.format model @dealing_platform.session.delete('positions/otc', body).fetch :deal_reference end
[ "def", "close", "(", "options", "=", "{", "}", ")", "options", "[", ":deal_id", "]", "=", "deal_id", "options", "[", ":direction", "]", "=", "{", "buy", ":", ":sell", ",", "sell", ":", ":buy", "}", ".", "fetch", "(", "direction", ")", "options", "[", ":size", "]", "||=", "size", "model", "=", "PositionCloseAttributes", ".", "build", "options", "model", ".", "validate", "body", "=", "RequestBodyFormatter", ".", "format", "model", "@dealing_platform", ".", "session", ".", "delete", "(", "'positions/otc'", ",", "body", ")", ".", "fetch", ":deal_reference", "end" ]
Closes this position. If called with no options then this position will be fully closed at current market prices, partial closes and greater control over the close conditions can be achieved by using the relevant options. @param [Hash] options The options for the position close. @option options [Float] :level Required if and only if `:order_type` is `:limit` or `:quote`. @option options [:limit, :market, :quote] :order_type The order type. `:market` indicates to fill the order at current market level(s). `:limit` indicates to fill at the price specified by `:level` (or a more favorable one). `:quote` is only permitted following agreement with IG Markets. Defaults to `:market`. @option options [String] :quote_id The Lightstreamer quote ID. Required when `:order_type` is `:quote`. @option options [Float] :size The size of the position to close. Defaults to {#size} which will close the entire position, or alternatively specify a smaller value to partially close this position. @option options [:execute_and_eliminate, :fill_or_kill] :time_in_force The order fill strategy. `:execute_and_eliminate` will fill this order as much as possible within the constraints set by `:order_type`, `:level` and `:quote_id`. `:fill_or_kill` will try to fill this entire order within the constraints, however if this is not possible then the order will not be filled at all. If `:order_type` is `:market` (the default) then `:time_in_force` will be automatically set to `:execute_and_eliminate`. @return [String] The resulting deal reference, use {DealingPlatform#deal_confirmation} to check the result of the position close.
[ "Closes", "this", "position", ".", "If", "called", "with", "no", "options", "then", "this", "position", "will", "be", "fully", "closed", "at", "current", "market", "prices", "partial", "closes", "and", "greater", "control", "over", "the", "close", "conditions", "can", "be", "achieved", "by", "using", "the", "relevant", "options", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/position.rb#L90-L101
24,447
richard-viney/ig_markets
lib/ig_markets/position.rb
IGMarkets.Position.update
def update(new_attributes) new_attributes = { limit_level: limit_level, stop_level: stop_level, trailing_stop: trailing_stop?, trailing_stop_distance: trailing_stop_distance, trailing_stop_increment: trailing_step } .merge new_attributes unless new_attributes[:trailing_stop] new_attributes[:trailing_stop_distance] = new_attributes[:trailing_stop_increment] = nil end body = RequestBodyFormatter.format PositionUpdateAttributes.new(new_attributes) @dealing_platform.session.put("positions/otc/#{deal_id}", body, API_V2).fetch(:deal_reference) end
ruby
def update(new_attributes) new_attributes = { limit_level: limit_level, stop_level: stop_level, trailing_stop: trailing_stop?, trailing_stop_distance: trailing_stop_distance, trailing_stop_increment: trailing_step } .merge new_attributes unless new_attributes[:trailing_stop] new_attributes[:trailing_stop_distance] = new_attributes[:trailing_stop_increment] = nil end body = RequestBodyFormatter.format PositionUpdateAttributes.new(new_attributes) @dealing_platform.session.put("positions/otc/#{deal_id}", body, API_V2).fetch(:deal_reference) end
[ "def", "update", "(", "new_attributes", ")", "new_attributes", "=", "{", "limit_level", ":", "limit_level", ",", "stop_level", ":", "stop_level", ",", "trailing_stop", ":", "trailing_stop?", ",", "trailing_stop_distance", ":", "trailing_stop_distance", ",", "trailing_stop_increment", ":", "trailing_step", "}", ".", "merge", "new_attributes", "unless", "new_attributes", "[", ":trailing_stop", "]", "new_attributes", "[", ":trailing_stop_distance", "]", "=", "new_attributes", "[", ":trailing_stop_increment", "]", "=", "nil", "end", "body", "=", "RequestBodyFormatter", ".", "format", "PositionUpdateAttributes", ".", "new", "(", "new_attributes", ")", "@dealing_platform", ".", "session", ".", "put", "(", "\"positions/otc/#{deal_id}\"", ",", "body", ",", "API_V2", ")", ".", "fetch", "(", ":deal_reference", ")", "end" ]
Updates this position. No attributes are mandatory, and any attributes not specified will be kept at their current value. @param [Hash] new_attributes The attributes of this position to update. @option new_attributes [Float] :limit_level The new limit level for this position. @option new_attributes [Float] :stop_level The new stop level for this position. @option new_attributes [Boolean] :trailing_stop Whether to use a trailing stop for this position. @option new_attributes [Integer] :trailing_stop_distance The distance away in pips to place the trailing stop. @option new_attributes [Integer] :trailing_stop_increment The step increment to use for the trailing stop. @return [String] The deal reference of the update operation. Use {DealingPlatform#deal_confirmation} to check the result of the position update.
[ "Updates", "this", "position", ".", "No", "attributes", "are", "mandatory", "and", "any", "attributes", "not", "specified", "will", "be", "kept", "at", "their", "current", "value", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/position.rb#L115-L127
24,448
richard-viney/ig_markets
lib/ig_markets/password_encryptor.rb
IGMarkets.PasswordEncryptor.encoded_public_key=
def encoded_public_key=(encoded_public_key) self.public_key = OpenSSL::PKey::RSA.new Base64.strict_decode64 encoded_public_key end
ruby
def encoded_public_key=(encoded_public_key) self.public_key = OpenSSL::PKey::RSA.new Base64.strict_decode64 encoded_public_key end
[ "def", "encoded_public_key", "=", "(", "encoded_public_key", ")", "self", ".", "public_key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "Base64", ".", "strict_decode64", "encoded_public_key", "end" ]
Initializes this password encryptor with the specified encoded public key and timestamp. @param [String] encoded_public_key @param [String] time_stamp Takes an encoded public key and calls {#public_key=} with the decoded key. @param [String] encoded_public_key The public key encoded in Base64.
[ "Initializes", "this", "password", "encryptor", "with", "the", "specified", "encoded", "public", "key", "and", "timestamp", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/password_encryptor.rb#L28-L30
24,449
richard-viney/ig_markets
lib/ig_markets/password_encryptor.rb
IGMarkets.PasswordEncryptor.encrypt
def encrypt(password) encoded_password = Base64.strict_encode64 "#{password}|#{time_stamp}" encrypted_password = public_key.public_encrypt encoded_password Base64.strict_encode64 encrypted_password end
ruby
def encrypt(password) encoded_password = Base64.strict_encode64 "#{password}|#{time_stamp}" encrypted_password = public_key.public_encrypt encoded_password Base64.strict_encode64 encrypted_password end
[ "def", "encrypt", "(", "password", ")", "encoded_password", "=", "Base64", ".", "strict_encode64", "\"#{password}|#{time_stamp}\"", "encrypted_password", "=", "public_key", ".", "public_encrypt", "encoded_password", "Base64", ".", "strict_encode64", "encrypted_password", "end" ]
Encrypts a password using this encryptor's public key and time stamp, which must have been set prior to calling this method. @param [String] password The password to encrypt. @return [String] The encrypted password encoded in Base64.
[ "Encrypts", "a", "password", "using", "this", "encryptor", "s", "public", "key", "and", "time", "stamp", "which", "must", "have", "been", "set", "prior", "to", "calling", "this", "method", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/password_encryptor.rb#L38-L44
24,450
railslove/smurfville
lib/smurfville/typography_parser.rb
Smurfville.TypographyParser.is_typography_selector?
def is_typography_selector?(node) node.is_a?(Sass::Tree::RuleNode) && node.rule[0].start_with?("%f-") rescue false end
ruby
def is_typography_selector?(node) node.is_a?(Sass::Tree::RuleNode) && node.rule[0].start_with?("%f-") rescue false end
[ "def", "is_typography_selector?", "(", "node", ")", "node", ".", "is_a?", "(", "Sass", "::", "Tree", "::", "RuleNode", ")", "&&", "node", ".", "rule", "[", "0", "]", ".", "start_with?", "(", "\"%f-\"", ")", "rescue", "false", "end" ]
determines if node is a placeholder selector starting widht the %f- convention for typography rulesets
[ "determines", "if", "node", "is", "a", "placeholder", "selector", "starting", "widht", "the", "%f", "-", "convention", "for", "typography", "rulesets" ]
0e6a84500cc3d748e25dd398acaf6d94878b3f84
https://github.com/railslove/smurfville/blob/0e6a84500cc3d748e25dd398acaf6d94878b3f84/lib/smurfville/typography_parser.rb#L24-L26
24,451
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.coinbase
def coinbase cb_hex = (app.config[:pow] || {})[:coinbase_hex] if cb_hex raise ValueError, 'coinbase must be String' unless cb_hex.is_a?(String) begin cb = Utils.decode_hex Utils.remove_0x_head(cb_hex) rescue TypeError raise ValueError, 'invalid coinbase' end else accts = accounts_with_address return DEFAULT_COINBASE if accts.empty? cb = accts[0].address end raise ValueError, 'wrong coinbase length' if cb.size != 20 if config[:accounts][:must_include_coinbase] raise ValueError, 'no account for coinbase' if [email protected](&:address).include?(cb) end cb end
ruby
def coinbase cb_hex = (app.config[:pow] || {})[:coinbase_hex] if cb_hex raise ValueError, 'coinbase must be String' unless cb_hex.is_a?(String) begin cb = Utils.decode_hex Utils.remove_0x_head(cb_hex) rescue TypeError raise ValueError, 'invalid coinbase' end else accts = accounts_with_address return DEFAULT_COINBASE if accts.empty? cb = accts[0].address end raise ValueError, 'wrong coinbase length' if cb.size != 20 if config[:accounts][:must_include_coinbase] raise ValueError, 'no account for coinbase' if [email protected](&:address).include?(cb) end cb end
[ "def", "coinbase", "cb_hex", "=", "(", "app", ".", "config", "[", ":pow", "]", "||", "{", "}", ")", "[", ":coinbase_hex", "]", "if", "cb_hex", "raise", "ValueError", ",", "'coinbase must be String'", "unless", "cb_hex", ".", "is_a?", "(", "String", ")", "begin", "cb", "=", "Utils", ".", "decode_hex", "Utils", ".", "remove_0x_head", "(", "cb_hex", ")", "rescue", "TypeError", "raise", "ValueError", ",", "'invalid coinbase'", "end", "else", "accts", "=", "accounts_with_address", "return", "DEFAULT_COINBASE", "if", "accts", ".", "empty?", "cb", "=", "accts", "[", "0", "]", ".", "address", "end", "raise", "ValueError", ",", "'wrong coinbase length'", "if", "cb", ".", "size", "!=", "20", "if", "config", "[", ":accounts", "]", "[", ":must_include_coinbase", "]", "raise", "ValueError", ",", "'no account for coinbase'", "if", "!", "@accounts", ".", "map", "(", ":address", ")", ".", "include?", "(", "cb", ")", "end", "cb", "end" ]
Return the address that should be used as coinbase for new blocks. The coinbase address is given by the config field pow.coinbase_hex. If this does not exist, the address of the first account is used instead. If there are no accounts, the coinbase is `DEFAULT_COINBASE`. @raise [ValueError] if the coinbase is invalid (no string, wrong length) or there is no account for it and the config flag `accounts.check_coinbase` is set (does not apply to the default coinbase).
[ "Return", "the", "address", "that", "should", "be", "used", "as", "coinbase", "for", "new", "blocks", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L80-L102
24,452
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.add_account
def add_account(account, store=true, include_address=true, include_id=true) logger.info "adding account", account: account if account.uuid && @accounts.any? {|acct| acct.uuid == account.uuid } logger.error 'could not add account (UUID collision)', uuid: account.uuid raise ValueError, 'Could not add account (UUID collision)' end if store raise ValueError, 'Cannot store account without path' if account.path.nil? if File.exist?(account.path) logger.error 'File does already exist', path: account.path raise IOError, 'File does already exist' end raise AssertError if @accounts.any? {|acct| acct.path == account.path } begin directory = File.dirname account.path FileUtils.mkdir_p(directory) unless File.exist?(directory) File.open(account.path, 'w') do |f| f.write account.dump(include_address, include_id) end rescue IOError => e logger.error "Could not write to file", path: account.path, message: e.to_s raise e end end @accounts.push account @accounts.sort_by! {|acct| acct.path.to_s } end
ruby
def add_account(account, store=true, include_address=true, include_id=true) logger.info "adding account", account: account if account.uuid && @accounts.any? {|acct| acct.uuid == account.uuid } logger.error 'could not add account (UUID collision)', uuid: account.uuid raise ValueError, 'Could not add account (UUID collision)' end if store raise ValueError, 'Cannot store account without path' if account.path.nil? if File.exist?(account.path) logger.error 'File does already exist', path: account.path raise IOError, 'File does already exist' end raise AssertError if @accounts.any? {|acct| acct.path == account.path } begin directory = File.dirname account.path FileUtils.mkdir_p(directory) unless File.exist?(directory) File.open(account.path, 'w') do |f| f.write account.dump(include_address, include_id) end rescue IOError => e logger.error "Could not write to file", path: account.path, message: e.to_s raise e end end @accounts.push account @accounts.sort_by! {|acct| acct.path.to_s } end
[ "def", "add_account", "(", "account", ",", "store", "=", "true", ",", "include_address", "=", "true", ",", "include_id", "=", "true", ")", "logger", ".", "info", "\"adding account\"", ",", "account", ":", "account", "if", "account", ".", "uuid", "&&", "@accounts", ".", "any?", "{", "|", "acct", "|", "acct", ".", "uuid", "==", "account", ".", "uuid", "}", "logger", ".", "error", "'could not add account (UUID collision)'", ",", "uuid", ":", "account", ".", "uuid", "raise", "ValueError", ",", "'Could not add account (UUID collision)'", "end", "if", "store", "raise", "ValueError", ",", "'Cannot store account without path'", "if", "account", ".", "path", ".", "nil?", "if", "File", ".", "exist?", "(", "account", ".", "path", ")", "logger", ".", "error", "'File does already exist'", ",", "path", ":", "account", ".", "path", "raise", "IOError", ",", "'File does already exist'", "end", "raise", "AssertError", "if", "@accounts", ".", "any?", "{", "|", "acct", "|", "acct", ".", "path", "==", "account", ".", "path", "}", "begin", "directory", "=", "File", ".", "dirname", "account", ".", "path", "FileUtils", ".", "mkdir_p", "(", "directory", ")", "unless", "File", ".", "exist?", "(", "directory", ")", "File", ".", "open", "(", "account", ".", "path", ",", "'w'", ")", "do", "|", "f", "|", "f", ".", "write", "account", ".", "dump", "(", "include_address", ",", "include_id", ")", "end", "rescue", "IOError", "=>", "e", "logger", ".", "error", "\"Could not write to file\"", ",", "path", ":", "account", ".", "path", ",", "message", ":", "e", ".", "to_s", "raise", "e", "end", "end", "@accounts", ".", "push", "account", "@accounts", ".", "sort_by!", "{", "|", "acct", "|", "acct", ".", "path", ".", "to_s", "}", "end" ]
Add an account. If `store` is true the account will be stored as a key file at the location given by `account.path`. If this is `nil` a `ValueError` is raised. `include_address` and `include_id` determine if address and id should be removed for storage or not. This method will raise a `ValueError` if the new account has the same UUID as an account already known to the service. Note that address collisions do not result in an exception as those may slip through anyway for locked accounts with hidden addresses.
[ "Add", "an", "account", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L117-L149
24,453
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.update_account
def update_account(account, new_password, include_address=true, include_id=true) raise ValueError, "Account not managed by account service" unless @accounts.include?(account) raise ValueError, "Cannot update locked account" if account.locked? raise ValueError, 'Account not stored on disk' unless account.path logger.debug "creating new account" new_account = Account.create new_password, account.privkey, account.uuid, account.path backup_path = account.path + '~' i = 1 while File.exist?(backup_path) backup_path = backup_path[0, backup_path.rindex('~')+1] + i.to_s i += 1 end raise AssertError if File.exist?(backup_path) logger.info 'moving old keystore file to backup location', from: account.path, to: backup_path begin FileUtils.mv account.path, backup_path rescue logger.error "could not backup keystore, stopping account update", from: account.path, to: backup_path raise $! end raise AssertError unless File.exist?(backup_path) raise AssertError if File.exist?(new_account.path) account.path = backup_path @accounts.delete account begin add_account new_account, include_address, include_id rescue logger.error 'adding new account failed, recovering from backup' FileUtils.mv backup_path, new_account.path account.path = new_account.path @accounts.push account @accounts.sort_by! {|acct| acct.path.to_s } raise $! end raise AssertError unless File.exist?(new_account.path) logger.info "deleting backup of old keystore", path: backup_path begin FileUtils.rm backup_path rescue logger.error 'failed to delete no longer needed backup of old keystore', path: account.path raise $! end account.keystore = new_account.keystore account.path = new_account.path @accounts.push account @accounts.delete new_account @accounts.sort_by! {|acct| acct.path.to_s } logger.debug "account update successful" end
ruby
def update_account(account, new_password, include_address=true, include_id=true) raise ValueError, "Account not managed by account service" unless @accounts.include?(account) raise ValueError, "Cannot update locked account" if account.locked? raise ValueError, 'Account not stored on disk' unless account.path logger.debug "creating new account" new_account = Account.create new_password, account.privkey, account.uuid, account.path backup_path = account.path + '~' i = 1 while File.exist?(backup_path) backup_path = backup_path[0, backup_path.rindex('~')+1] + i.to_s i += 1 end raise AssertError if File.exist?(backup_path) logger.info 'moving old keystore file to backup location', from: account.path, to: backup_path begin FileUtils.mv account.path, backup_path rescue logger.error "could not backup keystore, stopping account update", from: account.path, to: backup_path raise $! end raise AssertError unless File.exist?(backup_path) raise AssertError if File.exist?(new_account.path) account.path = backup_path @accounts.delete account begin add_account new_account, include_address, include_id rescue logger.error 'adding new account failed, recovering from backup' FileUtils.mv backup_path, new_account.path account.path = new_account.path @accounts.push account @accounts.sort_by! {|acct| acct.path.to_s } raise $! end raise AssertError unless File.exist?(new_account.path) logger.info "deleting backup of old keystore", path: backup_path begin FileUtils.rm backup_path rescue logger.error 'failed to delete no longer needed backup of old keystore', path: account.path raise $! end account.keystore = new_account.keystore account.path = new_account.path @accounts.push account @accounts.delete new_account @accounts.sort_by! {|acct| acct.path.to_s } logger.debug "account update successful" end
[ "def", "update_account", "(", "account", ",", "new_password", ",", "include_address", "=", "true", ",", "include_id", "=", "true", ")", "raise", "ValueError", ",", "\"Account not managed by account service\"", "unless", "@accounts", ".", "include?", "(", "account", ")", "raise", "ValueError", ",", "\"Cannot update locked account\"", "if", "account", ".", "locked?", "raise", "ValueError", ",", "'Account not stored on disk'", "unless", "account", ".", "path", "logger", ".", "debug", "\"creating new account\"", "new_account", "=", "Account", ".", "create", "new_password", ",", "account", ".", "privkey", ",", "account", ".", "uuid", ",", "account", ".", "path", "backup_path", "=", "account", ".", "path", "+", "'~'", "i", "=", "1", "while", "File", ".", "exist?", "(", "backup_path", ")", "backup_path", "=", "backup_path", "[", "0", ",", "backup_path", ".", "rindex", "(", "'~'", ")", "+", "1", "]", "+", "i", ".", "to_s", "i", "+=", "1", "end", "raise", "AssertError", "if", "File", ".", "exist?", "(", "backup_path", ")", "logger", ".", "info", "'moving old keystore file to backup location'", ",", "from", ":", "account", ".", "path", ",", "to", ":", "backup_path", "begin", "FileUtils", ".", "mv", "account", ".", "path", ",", "backup_path", "rescue", "logger", ".", "error", "\"could not backup keystore, stopping account update\"", ",", "from", ":", "account", ".", "path", ",", "to", ":", "backup_path", "raise", "$!", "end", "raise", "AssertError", "unless", "File", ".", "exist?", "(", "backup_path", ")", "raise", "AssertError", "if", "File", ".", "exist?", "(", "new_account", ".", "path", ")", "account", ".", "path", "=", "backup_path", "@accounts", ".", "delete", "account", "begin", "add_account", "new_account", ",", "include_address", ",", "include_id", "rescue", "logger", ".", "error", "'adding new account failed, recovering from backup'", "FileUtils", ".", "mv", "backup_path", ",", "new_account", ".", "path", "account", ".", "path", "=", "new_account", ".", "path", "@accounts", ".", "push", "account", "@accounts", ".", "sort_by!", "{", "|", "acct", "|", "acct", ".", "path", ".", "to_s", "}", "raise", "$!", "end", "raise", "AssertError", "unless", "File", ".", "exist?", "(", "new_account", ".", "path", ")", "logger", ".", "info", "\"deleting backup of old keystore\"", ",", "path", ":", "backup_path", "begin", "FileUtils", ".", "rm", "backup_path", "rescue", "logger", ".", "error", "'failed to delete no longer needed backup of old keystore'", ",", "path", ":", "account", ".", "path", "raise", "$!", "end", "account", ".", "keystore", "=", "new_account", ".", "keystore", "account", ".", "path", "=", "new_account", ".", "path", "@accounts", ".", "push", "account", "@accounts", ".", "delete", "new_account", "@accounts", ".", "sort_by!", "{", "|", "acct", "|", "acct", ".", "path", ".", "to_s", "}", "logger", ".", "debug", "\"account update successful\"", "end" ]
Replace the password of an account. The update is carried out in three steps: 1. the old keystore file is renamed 2. the new keystore file is created at the previous location of the old keystore file 3. the old keystore file is removed In this way, at least one of the keystore files exists on disk at any time and can be recovered if the process is interrupted. @param account [Account] which must be unlocked, stored on disk and included in `@accounts` @param include_address [Bool] forwarded to `add_account` during step 2 @param include_id [Bool] forwarded to `add_account` during step 2 @raise [ValueError] if the account is locked, if it is not added to the account manager, or if it is not stored
[ "Replace", "the", "password", "of", "an", "account", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L172-L228
24,454
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.find
def find(identifier) identifier = identifier.downcase if identifier =~ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ # uuid return get_by_id(identifier) end begin address = Address.new(identifier).to_bytes raise AssertError unless address.size == 20 return self[address] rescue # do nothing end index = identifier.to_i raise ValueError, 'Index must be 1 or greater' if index <= 0 raise KeyError if index > @accounts.size @accounts[index-1] end
ruby
def find(identifier) identifier = identifier.downcase if identifier =~ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ # uuid return get_by_id(identifier) end begin address = Address.new(identifier).to_bytes raise AssertError unless address.size == 20 return self[address] rescue # do nothing end index = identifier.to_i raise ValueError, 'Index must be 1 or greater' if index <= 0 raise KeyError if index > @accounts.size @accounts[index-1] end
[ "def", "find", "(", "identifier", ")", "identifier", "=", "identifier", ".", "downcase", "if", "identifier", "=~", "/", "\\A", "\\z", "/", "# uuid", "return", "get_by_id", "(", "identifier", ")", "end", "begin", "address", "=", "Address", ".", "new", "(", "identifier", ")", ".", "to_bytes", "raise", "AssertError", "unless", "address", ".", "size", "==", "20", "return", "self", "[", "address", "]", "rescue", "# do nothing", "end", "index", "=", "identifier", ".", "to_i", "raise", "ValueError", ",", "'Index must be 1 or greater'", "if", "index", "<=", "0", "raise", "KeyError", "if", "index", ">", "@accounts", ".", "size", "@accounts", "[", "index", "-", "1", "]", "end" ]
Find an account by either its address, its id, or its index as string. Example identifiers: - '9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address) - '0x9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address with 0x prefix) - '01dd527b-f4a5-4b3c-9abb-6a8e7cd6722f' (UUID) - '3' (index) @param identifier [String] the accounts hex encoded, case insensitive address (with optional 0x prefix), its UUID or its index (as string, >= 1) @raise [ValueError] if the identifier could not be interpreted @raise [KeyError] if the identified account is not known to the account service
[ "Find", "an", "account", "by", "either", "its", "address", "its", "id", "or", "its", "index", "as", "string", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L256-L275
24,455
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.get_by_id
def get_by_id(id) accts = @accounts.select {|acct| acct.uuid == id } if accts.size == 0 raise KeyError, "account with id #{id} unknown" elsif accts.size > 1 logger.warn "multiple accounts with same UUID found", uuid: id end accts[0] end
ruby
def get_by_id(id) accts = @accounts.select {|acct| acct.uuid == id } if accts.size == 0 raise KeyError, "account with id #{id} unknown" elsif accts.size > 1 logger.warn "multiple accounts with same UUID found", uuid: id end accts[0] end
[ "def", "get_by_id", "(", "id", ")", "accts", "=", "@accounts", ".", "select", "{", "|", "acct", "|", "acct", ".", "uuid", "==", "id", "}", "if", "accts", ".", "size", "==", "0", "raise", "KeyError", ",", "\"account with id #{id} unknown\"", "elsif", "accts", ".", "size", ">", "1", "logger", ".", "warn", "\"multiple accounts with same UUID found\"", ",", "uuid", ":", "id", "end", "accts", "[", "0", "]", "end" ]
Return the account with a given id. Note that accounts are not required to have an id. @raise [KeyError] if no matching account can be found
[ "Return", "the", "account", "with", "a", "given", "id", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L284-L294
24,456
cryptape/reth
lib/reth/account_service.rb
Reth.AccountService.get_by_address
def get_by_address(address) raise ArgumentError, 'address must be 20 bytes' unless address.size == 20 accts = @accounts.select {|acct| acct.address == address } if accts.size == 0 raise KeyError, "account not found by address #{Utils.encode_hex(address)}" elsif accts.size > 1 logger.warn "multiple accounts with same address found", address: Utils.encode_hex(address) end accts[0] end
ruby
def get_by_address(address) raise ArgumentError, 'address must be 20 bytes' unless address.size == 20 accts = @accounts.select {|acct| acct.address == address } if accts.size == 0 raise KeyError, "account not found by address #{Utils.encode_hex(address)}" elsif accts.size > 1 logger.warn "multiple accounts with same address found", address: Utils.encode_hex(address) end accts[0] end
[ "def", "get_by_address", "(", "address", ")", "raise", "ArgumentError", ",", "'address must be 20 bytes'", "unless", "address", ".", "size", "==", "20", "accts", "=", "@accounts", ".", "select", "{", "|", "acct", "|", "acct", ".", "address", "==", "address", "}", "if", "accts", ".", "size", "==", "0", "raise", "KeyError", ",", "\"account not found by address #{Utils.encode_hex(address)}\"", "elsif", "accts", ".", "size", ">", "1", "logger", ".", "warn", "\"multiple accounts with same address found\"", ",", "address", ":", "Utils", ".", "encode_hex", "(", "address", ")", "end", "accts", "[", "0", "]", "end" ]
Get an account by its address. Note that even if an account with the given address exists, it might not be found if it is locked. Also, multiple accounts with the same address may exist, in which case the first one is returned (and a warning is logged). @raise [KeyError] if no matching account can be found
[ "Get", "an", "account", "by", "its", "address", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account_service.rb#L306-L318
24,457
richard-viney/ig_markets
lib/ig_markets/model.rb
IGMarkets.Model.to_h
def to_h attributes.each_with_object({}) do |(key, value), hash| hash[key] = if value.is_a? Model value.to_h else value end end end
ruby
def to_h attributes.each_with_object({}) do |(key, value), hash| hash[key] = if value.is_a? Model value.to_h else value end end end
[ "def", "to_h", "attributes", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "hash", "|", "hash", "[", "key", "]", "=", "if", "value", ".", "is_a?", "Model", "value", ".", "to_h", "else", "value", "end", "end", "end" ]
Compares this model to another, the attributes and class must match for them to be considered equal. @param [Model] other The other model to compare to. @return [Boolean] Converts this model into a nested hash of attributes. This is simlar to just calling {#attributes}, but in this case any attributes that are instances of {Model} will also be transformed into a hash in the return value. @return [Hash]
[ "Compares", "this", "model", "to", "another", "the", "attributes", "and", "class", "must", "match", "for", "them", "to", "be", "considered", "equal", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/model.rb#L49-L57
24,458
richard-viney/ig_markets
lib/ig_markets/dealing_platform.rb
IGMarkets.DealingPlatform.sign_in
def sign_in(username, password, api_key, platform) session.username = username session.password = password session.api_key = api_key session.platform = platform result = session.sign_in @client_account_summary = instantiate_models ClientAccountSummary, result end
ruby
def sign_in(username, password, api_key, platform) session.username = username session.password = password session.api_key = api_key session.platform = platform result = session.sign_in @client_account_summary = instantiate_models ClientAccountSummary, result end
[ "def", "sign_in", "(", "username", ",", "password", ",", "api_key", ",", "platform", ")", "session", ".", "username", "=", "username", "session", ".", "password", "=", "password", "session", ".", "api_key", "=", "api_key", "session", ".", "platform", "=", "platform", "result", "=", "session", ".", "sign_in", "@client_account_summary", "=", "instantiate_models", "ClientAccountSummary", ",", "result", "end" ]
Signs in to the IG Markets Dealing Platform, either the live platform or the demo platform. @param [String] username The IG Markets username. @param [String] password The IG Markets password. @param [String] api_key The IG Markets API key. @param [:live, :demo] platform The platform to use. @return [ClientAccountSummary] The client account summary returned by the sign in request. This result can also be accessed later using {#client_account_summary}.
[ "Signs", "in", "to", "the", "IG", "Markets", "Dealing", "Platform", "either", "the", "live", "platform", "or", "the", "demo", "platform", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/dealing_platform.rb#L90-L99
24,459
richard-viney/ig_markets
lib/ig_markets/format.rb
IGMarkets.Format.colored_currency
def colored_currency(amount, currency_name) return '' unless amount color = amount < 0 ? :red : :green ColorizedString[currency(amount, currency_name)].colorize color end
ruby
def colored_currency(amount, currency_name) return '' unless amount color = amount < 0 ? :red : :green ColorizedString[currency(amount, currency_name)].colorize color end
[ "def", "colored_currency", "(", "amount", ",", "currency_name", ")", "return", "''", "unless", "amount", "color", "=", "amount", "<", "0", "?", ":red", ":", ":green", "ColorizedString", "[", "currency", "(", "amount", ",", "currency_name", ")", "]", ".", "colorize", "color", "end" ]
Returns a formatted string for the specified currency amount and currency, and colors it red for negative values and green for positive values. Two decimal places are used for all currencies except the Japanese Yen. @param [Float, Integer] amount The currency amount to format. @param [String] currency_name The currency. @return [String] The formatted and colored currency amount, e.g. `"USD -130.40"`, `"AUD 539.10"`, `"JPY 3560"`.
[ "Returns", "a", "formatted", "string", "for", "the", "specified", "currency", "amount", "and", "currency", "and", "colors", "it", "red", "for", "negative", "values", "and", "green", "for", "positive", "values", ".", "Two", "decimal", "places", "are", "used", "for", "all", "currencies", "except", "the", "Japanese", "Yen", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/format.rb#L43-L49
24,460
richard-viney/ig_markets
lib/ig_markets/request_body_formatter.rb
IGMarkets.RequestBodyFormatter.snake_case_to_camel_case
def snake_case_to_camel_case(value) pieces = value.to_s.split '_' (pieces.first + pieces[1..-1].map(&:capitalize).join).to_sym end
ruby
def snake_case_to_camel_case(value) pieces = value.to_s.split '_' (pieces.first + pieces[1..-1].map(&:capitalize).join).to_sym end
[ "def", "snake_case_to_camel_case", "(", "value", ")", "pieces", "=", "value", ".", "to_s", ".", "split", "'_'", "(", "pieces", ".", "first", "+", "pieces", "[", "1", "..", "-", "1", "]", ".", "map", "(", ":capitalize", ")", ".", "join", ")", ".", "to_sym", "end" ]
Takes a string or symbol that uses snake case and converts it to a camel case symbol. @param [String, Symbol] value The string or symbol to convert to camel case. @return [Symbol]
[ "Takes", "a", "string", "or", "symbol", "that", "uses", "snake", "case", "and", "converts", "it", "to", "a", "camel", "case", "symbol", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/request_body_formatter.rb#L48-L52
24,461
cryptape/reth
lib/reth/account.rb
Reth.Account.dump
def dump(include_address=true, include_id=true) h = {} h[:crypto] = @keystore[:crypto] h[:version] = @keystore[:version] h[:address] = Utils.encode_hex address if include_address && address h[:id] = uuid if include_id && uuid JSON.dump(h) end
ruby
def dump(include_address=true, include_id=true) h = {} h[:crypto] = @keystore[:crypto] h[:version] = @keystore[:version] h[:address] = Utils.encode_hex address if include_address && address h[:id] = uuid if include_id && uuid JSON.dump(h) end
[ "def", "dump", "(", "include_address", "=", "true", ",", "include_id", "=", "true", ")", "h", "=", "{", "}", "h", "[", ":crypto", "]", "=", "@keystore", "[", ":crypto", "]", "h", "[", ":version", "]", "=", "@keystore", "[", ":version", "]", "h", "[", ":address", "]", "=", "Utils", ".", "encode_hex", "address", "if", "include_address", "&&", "address", "h", "[", ":id", "]", "=", "uuid", "if", "include_id", "&&", "uuid", "JSON", ".", "dump", "(", "h", ")", "end" ]
Dump the keystore for later disk storage. The result inherits the entries `crypto` and `version` from `Keystore`, and adds `address` and `id` in accordance with the parameters `include_address` and `include_id`. If address or id are not known, they are not added, even if requested. @param include_address [Bool] flag denoting if the address should be included or not @param include_id [Bool] flag denoting if the id should be included or not
[ "Dump", "the", "keystore", "for", "later", "disk", "storage", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account.rb#L83-L92
24,462
cryptape/reth
lib/reth/account.rb
Reth.Account.sign_tx
def sign_tx(tx) if privkey logger.info "signing tx", tx: tx, account: self tx.sign privkey else raise ValueError, "Locked account cannot sign tx" end end
ruby
def sign_tx(tx) if privkey logger.info "signing tx", tx: tx, account: self tx.sign privkey else raise ValueError, "Locked account cannot sign tx" end end
[ "def", "sign_tx", "(", "tx", ")", "if", "privkey", "logger", ".", "info", "\"signing tx\"", ",", "tx", ":", "tx", ",", "account", ":", "self", "tx", ".", "sign", "privkey", "else", "raise", "ValueError", ",", "\"Locked account cannot sign tx\"", "end", "end" ]
Sign a Transaction with the private key of this account. If the account is unlocked, this is equivalent to `tx.sign(account.privkey)`. @param tx [Transaction] the transaction to sign @raise [ValueError] if the account is locked
[ "Sign", "a", "Transaction", "with", "the", "private", "key", "of", "this", "account", "." ]
06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec
https://github.com/cryptape/reth/blob/06c5e9f5efa96e44933d7d5f9e11fd72f938c8ec/lib/reth/account.rb#L169-L176
24,463
projecttacoma/simplexml_parser
lib/model/document.rb
SimpleXml.Document.detect_unstratified
def detect_unstratified missing_populations = [] # populations are keyed off of values rather than the codes existing_populations = @populations.map{|p| p.values.join('-')}.uniq @populations.each do |population| keys = population.keys - ['STRAT','stratification'] missing_populations |= [population.values_at(*keys).compact.join('-')] end missing_populations -= existing_populations # reverse the order and prepend them to @populations missing_populations.reverse.each do |population| p = {} population.split('-').each do |code| p[code.split('_').first] = code end @populations.unshift p end end
ruby
def detect_unstratified missing_populations = [] # populations are keyed off of values rather than the codes existing_populations = @populations.map{|p| p.values.join('-')}.uniq @populations.each do |population| keys = population.keys - ['STRAT','stratification'] missing_populations |= [population.values_at(*keys).compact.join('-')] end missing_populations -= existing_populations # reverse the order and prepend them to @populations missing_populations.reverse.each do |population| p = {} population.split('-').each do |code| p[code.split('_').first] = code end @populations.unshift p end end
[ "def", "detect_unstratified", "missing_populations", "=", "[", "]", "# populations are keyed off of values rather than the codes", "existing_populations", "=", "@populations", ".", "map", "{", "|", "p", "|", "p", ".", "values", ".", "join", "(", "'-'", ")", "}", ".", "uniq", "@populations", ".", "each", "do", "|", "population", "|", "keys", "=", "population", ".", "keys", "-", "[", "'STRAT'", ",", "'stratification'", "]", "missing_populations", "|=", "[", "population", ".", "values_at", "(", "keys", ")", ".", "compact", ".", "join", "(", "'-'", ")", "]", "end", "missing_populations", "-=", "existing_populations", "# reverse the order and prepend them to @populations", "missing_populations", ".", "reverse", ".", "each", "do", "|", "population", "|", "p", "=", "{", "}", "population", ".", "split", "(", "'-'", ")", ".", "each", "do", "|", "code", "|", "p", "[", "code", ".", "split", "(", "'_'", ")", ".", "first", "]", "=", "code", "end", "@populations", ".", "unshift", "p", "end", "end" ]
Detects missing unstratified populations from the generated @populations array
[ "Detects", "missing", "unstratified", "populations", "from", "the", "generated" ]
9f83211e2407f0d933afbd1648c57f500b7527af
https://github.com/projecttacoma/simplexml_parser/blob/9f83211e2407f0d933afbd1648c57f500b7527af/lib/model/document.rb#L316-L335
24,464
livingsocial/ganapati
lib/ganapati/client.rb
Ganapati.Client.put
def put(localpath, destpath) create(destpath) { |dest| Kernel.open(localpath) { |source| # read 1 MB at a time while record = source.read(1048576) dest.write(record) end } } end
ruby
def put(localpath, destpath) create(destpath) { |dest| Kernel.open(localpath) { |source| # read 1 MB at a time while record = source.read(1048576) dest.write(record) end } } end
[ "def", "put", "(", "localpath", ",", "destpath", ")", "create", "(", "destpath", ")", "{", "|", "dest", "|", "Kernel", ".", "open", "(", "localpath", ")", "{", "|", "source", "|", "# read 1 MB at a time", "while", "record", "=", "source", ".", "read", "(", "1048576", ")", "dest", ".", "write", "(", "record", ")", "end", "}", "}", "end" ]
copy local file to remote
[ "copy", "local", "file", "to", "remote" ]
c583dfbbe12b417323e54aab3aa1ed80dc38f649
https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L24-L33
24,465
livingsocial/ganapati
lib/ganapati/client.rb
Ganapati.Client.get
def get(remotepath, destpath) Kernel.open(destpath, 'w') { |dest| readchunks(remotepath) { |chunk| dest.write chunk } } end
ruby
def get(remotepath, destpath) Kernel.open(destpath, 'w') { |dest| readchunks(remotepath) { |chunk| dest.write chunk } } end
[ "def", "get", "(", "remotepath", ",", "destpath", ")", "Kernel", ".", "open", "(", "destpath", ",", "'w'", ")", "{", "|", "dest", "|", "readchunks", "(", "remotepath", ")", "{", "|", "chunk", "|", "dest", ".", "write", "chunk", "}", "}", "end" ]
copy remote file to local
[ "copy", "remote", "file", "to", "local" ]
c583dfbbe12b417323e54aab3aa1ed80dc38f649
https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L36-L42
24,466
livingsocial/ganapati
lib/ganapati/client.rb
Ganapati.Client.readchunks
def readchunks(path, chunksize=1048576) open(path) { |source| size = source.length index = 0 while index < size yield source.read(index, chunksize) index += chunksize end } end
ruby
def readchunks(path, chunksize=1048576) open(path) { |source| size = source.length index = 0 while index < size yield source.read(index, chunksize) index += chunksize end } end
[ "def", "readchunks", "(", "path", ",", "chunksize", "=", "1048576", ")", "open", "(", "path", ")", "{", "|", "source", "|", "size", "=", "source", ".", "length", "index", "=", "0", "while", "index", "<", "size", "yield", "source", ".", "read", "(", "index", ",", "chunksize", ")", "index", "+=", "chunksize", "end", "}", "end" ]
yeild chunksize of path one chunk at a time
[ "yeild", "chunksize", "of", "path", "one", "chunk", "at", "a", "time" ]
c583dfbbe12b417323e54aab3aa1ed80dc38f649
https://github.com/livingsocial/ganapati/blob/c583dfbbe12b417323e54aab3aa1ed80dc38f649/lib/ganapati/client.rb#L45-L54
24,467
hck/open_nlp
lib/open_nlp/tokenizer.rb
OpenNlp.Tokenizer.tokenize
def tokenize(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.tokenize(str).to_ary end
ruby
def tokenize(str) raise ArgumentError, 'str must be a String' unless str.is_a?(String) j_instance.tokenize(str).to_ary end
[ "def", "tokenize", "(", "str", ")", "raise", "ArgumentError", ",", "'str must be a String'", "unless", "str", ".", "is_a?", "(", "String", ")", "j_instance", ".", "tokenize", "(", "str", ")", ".", "to_ary", "end" ]
Tokenizes a string @param [String] str string to tokenize @return [Array] array of string tokens
[ "Tokenizes", "a", "string" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/tokenizer.rb#L9-L13
24,468
hck/open_nlp
lib/open_nlp/pos_tagger.rb
OpenNlp.POSTagger.tag
def tag(tokens) !tokens.is_a?(Array) && !tokens.is_a?(String) && raise(ArgumentError, 'tokens must be an instance of String or Array') j_instance.tag(tokens.to_java(:String)) end
ruby
def tag(tokens) !tokens.is_a?(Array) && !tokens.is_a?(String) && raise(ArgumentError, 'tokens must be an instance of String or Array') j_instance.tag(tokens.to_java(:String)) end
[ "def", "tag", "(", "tokens", ")", "!", "tokens", ".", "is_a?", "(", "Array", ")", "&&", "!", "tokens", ".", "is_a?", "(", "String", ")", "&&", "raise", "(", "ArgumentError", ",", "'tokens must be an instance of String or Array'", ")", "j_instance", ".", "tag", "(", "tokens", ".", "to_java", "(", ":String", ")", ")", "end" ]
Adds tags to tokens passed as argument @param [Array<String>, String] tokens tokens to tag @return [Array<String>, String] array of part-of-speech tags or string with added part-of-speech tags
[ "Adds", "tags", "to", "tokens", "passed", "as", "argument" ]
1c006a37747d797a41aa72ef6068fae770464862
https://github.com/hck/open_nlp/blob/1c006a37747d797a41aa72ef6068fae770464862/lib/open_nlp/pos_tagger.rb#L9-L14
24,469
richard-viney/ig_markets
lib/ig_markets/account.rb
IGMarkets.Account.reload
def reload self.attributes = @dealing_platform.account.all.detect { |a| a.account_id == account_id }.attributes end
ruby
def reload self.attributes = @dealing_platform.account.all.detect { |a| a.account_id == account_id }.attributes end
[ "def", "reload", "self", ".", "attributes", "=", "@dealing_platform", ".", "account", ".", "all", ".", "detect", "{", "|", "a", "|", "a", ".", "account_id", "==", "account_id", "}", ".", "attributes", "end" ]
Reloads this account's attributes by re-querying the IG Markets API.
[ "Reloads", "this", "account", "s", "attributes", "by", "re", "-", "querying", "the", "IG", "Markets", "API", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/account.rb#L24-L26
24,470
contentstack/contentstack-ruby
lib/contentstack/query.rb
Contentstack.Query.only
def only(fields, fields_with_base=nil) q = {} if [Array, String].include?(fields_with_base.class) fields_with_base = [fields_with_base] if fields_with_base.class == String q[fields.to_sym] = fields_with_base else fields = [fields] if fields.class == String q = {BASE: fields} end @query[:only] = q self end
ruby
def only(fields, fields_with_base=nil) q = {} if [Array, String].include?(fields_with_base.class) fields_with_base = [fields_with_base] if fields_with_base.class == String q[fields.to_sym] = fields_with_base else fields = [fields] if fields.class == String q = {BASE: fields} end @query[:only] = q self end
[ "def", "only", "(", "fields", ",", "fields_with_base", "=", "nil", ")", "q", "=", "{", "}", "if", "[", "Array", ",", "String", "]", ".", "include?", "(", "fields_with_base", ".", "class", ")", "fields_with_base", "=", "[", "fields_with_base", "]", "if", "fields_with_base", ".", "class", "==", "String", "q", "[", "fields", ".", "to_sym", "]", "=", "fields_with_base", "else", "fields", "=", "[", "fields", "]", "if", "fields", ".", "class", "==", "String", "q", "=", "{", "BASE", ":", "fields", "}", "end", "@query", "[", ":only", "]", "=", "q", "self", "end" ]
Specifies an array of 'only' keys in BASE object that would be 'included' in the response. @param [Array] fields Array of the 'only' reference keys to be included in response. @param [Array] fields_with_base Can be used to denote 'only' fields of the reference class Example # Include only title and description field in response @query = @stack.content_type('category').query @query.only(['title', 'description']) # Query product and include only the title and description from category reference @query = @stack.content_type('product').query @query.include_reference('category') .only('category', ['title', 'description']) @return [Contentstack::Query]
[ "Specifies", "an", "array", "of", "only", "keys", "in", "BASE", "object", "that", "would", "be", "included", "in", "the", "response", "." ]
6aa499d6620c2741078d5a39c20dd4890004d8f2
https://github.com/contentstack/contentstack-ruby/blob/6aa499d6620c2741078d5a39c20dd4890004d8f2/lib/contentstack/query.rb#L403-L415
24,471
richard-viney/ig_markets
lib/ig_markets/working_order.rb
IGMarkets.WorkingOrder.update
def update(new_attributes) existing_attributes = { good_till_date: good_till_date, level: order_level, limit_distance: limit_distance, stop_distance: stop_distance, time_in_force: time_in_force, type: order_type } model = WorkingOrderUpdateAttributes.new existing_attributes, new_attributes model.validate body = RequestBodyFormatter.format model @dealing_platform.session.put("workingorders/otc/#{deal_id}", body, API_V2).fetch(:deal_reference) end
ruby
def update(new_attributes) existing_attributes = { good_till_date: good_till_date, level: order_level, limit_distance: limit_distance, stop_distance: stop_distance, time_in_force: time_in_force, type: order_type } model = WorkingOrderUpdateAttributes.new existing_attributes, new_attributes model.validate body = RequestBodyFormatter.format model @dealing_platform.session.put("workingorders/otc/#{deal_id}", body, API_V2).fetch(:deal_reference) end
[ "def", "update", "(", "new_attributes", ")", "existing_attributes", "=", "{", "good_till_date", ":", "good_till_date", ",", "level", ":", "order_level", ",", "limit_distance", ":", "limit_distance", ",", "stop_distance", ":", "stop_distance", ",", "time_in_force", ":", "time_in_force", ",", "type", ":", "order_type", "}", "model", "=", "WorkingOrderUpdateAttributes", ".", "new", "existing_attributes", ",", "new_attributes", "model", ".", "validate", "body", "=", "RequestBodyFormatter", ".", "format", "model", "@dealing_platform", ".", "session", ".", "put", "(", "\"workingorders/otc/#{deal_id}\"", ",", "body", ",", "API_V2", ")", ".", "fetch", "(", ":deal_reference", ")", "end" ]
Updates this working order. No attributes are mandatory, and any attributes not specified will be kept at their current values. @param [Hash] new_attributes The attributes of this working order to update. See {DealingPlatform::WorkingOrderMethods#create} for a description of the attributes. @option new_attributes [Time] :good_till_date @option new_attributes [Float] :level @option new_attributes [Integer] :limit_distance @option new_attributes [Float] :limit_level @option new_attributes [Integer] :stop_distance @option new_attributes [Float] :stop_level @option new_attributes [:limit, :stop] :type @return [String] The deal reference of the update operation. Use {DealingPlatform#deal_confirmation} to check the result of the working order update.
[ "Updates", "this", "working", "order", ".", "No", "attributes", "are", "mandatory", "and", "any", "attributes", "not", "specified", "will", "be", "kept", "at", "their", "current", "values", "." ]
c1989ec557b0ba643a76024c5bec624abd8c1c4c
https://github.com/richard-viney/ig_markets/blob/c1989ec557b0ba643a76024c5bec624abd8c1c4c/lib/ig_markets/working_order.rb#L53-L63
24,472
railslove/smurfville
lib/smurfville/color_variable_parser.rb
Smurfville.ColorVariableParser.add_color
def add_color(node, key = nil) key ||= node.expr.to_s self.colors[key] ||= { :variables => [], :alternate_values => [] } self.colors[key][:variables] << node.name self.colors[key][:alternate_values] |= ([node.expr.to_sass, node.expr.inspect] - [key]) end
ruby
def add_color(node, key = nil) key ||= node.expr.to_s self.colors[key] ||= { :variables => [], :alternate_values => [] } self.colors[key][:variables] << node.name self.colors[key][:alternate_values] |= ([node.expr.to_sass, node.expr.inspect] - [key]) end
[ "def", "add_color", "(", "node", ",", "key", "=", "nil", ")", "key", "||=", "node", ".", "expr", ".", "to_s", "self", ".", "colors", "[", "key", "]", "||=", "{", ":variables", "=>", "[", "]", ",", ":alternate_values", "=>", "[", "]", "}", "self", ".", "colors", "[", "key", "]", "[", ":variables", "]", "<<", "node", ".", "name", "self", ".", "colors", "[", "key", "]", "[", ":alternate_values", "]", "|=", "(", "[", "node", ".", "expr", ".", "to_sass", ",", "node", ".", "expr", ".", "inspect", "]", "-", "[", "key", "]", ")", "end" ]
add found color to @colors
[ "add", "found", "color", "to" ]
0e6a84500cc3d748e25dd398acaf6d94878b3f84
https://github.com/railslove/smurfville/blob/0e6a84500cc3d748e25dd398acaf6d94878b3f84/lib/smurfville/color_variable_parser.rb#L49-L56
24,473
hassox/rack-rescue
lib/rack/rescue.rb
Rack.Rescue.apply_layout
def apply_layout(env, content, opts) if layout = env['layout'] layout.format = opts[:format] layout.content = content layout.template_name = opts[:layout] if layout.template_name?(opts[:layout], opts) layout else content end end
ruby
def apply_layout(env, content, opts) if layout = env['layout'] layout.format = opts[:format] layout.content = content layout.template_name = opts[:layout] if layout.template_name?(opts[:layout], opts) layout else content end end
[ "def", "apply_layout", "(", "env", ",", "content", ",", "opts", ")", "if", "layout", "=", "env", "[", "'layout'", "]", "layout", ".", "format", "=", "opts", "[", ":format", "]", "layout", ".", "content", "=", "content", "layout", ".", "template_name", "=", "opts", "[", ":layout", "]", "if", "layout", ".", "template_name?", "(", "opts", "[", ":layout", "]", ",", "opts", ")", "layout", "else", "content", "end", "end" ]
Apply the layout if it exists @api private
[ "Apply", "the", "layout", "if", "it", "exists" ]
3826e28d9704d734659ac16374ee8b740bd42e48
https://github.com/hassox/rack-rescue/blob/3826e28d9704d734659ac16374ee8b740bd42e48/lib/rack/rescue.rb#L58-L67
24,474
david942j/memory_io
lib/memory_io/process.rb
MemoryIO.Process.read
def read(addr, num_elements, **options) mem_io(:read) { |io| io.read(num_elements, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
ruby
def read(addr, num_elements, **options) mem_io(:read) { |io| io.read(num_elements, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
[ "def", "read", "(", "addr", ",", "num_elements", ",", "**", "options", ")", "mem_io", "(", ":read", ")", "{", "|", "io", "|", "io", ".", "read", "(", "num_elements", ",", "from", ":", "MemoryIO", "::", "Util", ".", "safe_eval", "(", "addr", ",", "bases", ")", ",", "**", "options", ")", "}", "end" ]
Read from process's memory. This method has *almost* same arguements and return types as {IO#read}. The only difference is this method needs parameter +addr+ (which will be passed to paramter +from+ in {IO#read}). @param [Integer, String] addr The address start to read. When String is given, it will be safe-evaluated. You can use variables such as +'heap'/'stack'/'libc'+ in this parameter. See examples. @param [Integer] num_elements Number of elements to read. See {IO#read}. @return [String, Object, Array<Object>] See {IO#read}. @example process = MemoryIO.attach(`pidof victim`.to_i) puts process.read('heap', 4, as: :u64).map { |c| '0x%016x' % c } # 0x0000000000000000 # 0x0000000000000021 # 0x00000000deadbeef # 0x0000000000000000 #=> nil process.read('heap+0x10', 4, as: :u8).map { |c| '0x%x' % c } #=> ['0xef', '0xbe', '0xad', '0xde'] process.read('libc', 4) #=> "\x7fELF" @see IO#read
[ "Read", "from", "process", "s", "memory", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/process.rb#L109-L111
24,475
david942j/memory_io
lib/memory_io/process.rb
MemoryIO.Process.write
def write(addr, objects, **options) mem_io(:write) { |io| io.write(objects, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
ruby
def write(addr, objects, **options) mem_io(:write) { |io| io.write(objects, from: MemoryIO::Util.safe_eval(addr, bases), **options) } end
[ "def", "write", "(", "addr", ",", "objects", ",", "**", "options", ")", "mem_io", "(", ":write", ")", "{", "|", "io", "|", "io", ".", "write", "(", "objects", ",", "from", ":", "MemoryIO", "::", "Util", ".", "safe_eval", "(", "addr", ",", "bases", ")", ",", "**", "options", ")", "}", "end" ]
Write objects at +addr+. This method has *almost* same arguments as {IO#write}. @param [Integer, String] addr The address to start to write. See examples. @param [Object, Array<Object>] objects Objects to write. If +objects+ is an array, the write procedure will be invoked +objects.size+ times. @return [void] @example process = MemoryIO.attach('self') s = 'A' * 16 process.write(s.object_id * 2 + 16, 'BBBBCCCC') s #=> 'BBBBCCCCAAAAAAAA' @see IO#write
[ "Write", "objects", "at", "+", "addr", "+", "." ]
97a4206974b699767c57f3e113f78bdae69f950f
https://github.com/david942j/memory_io/blob/97a4206974b699767c57f3e113f78bdae69f950f/lib/memory_io/process.rb#L133-L135
24,476
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.netrc_path
def netrc_path unencrypted = Netrc.default_path encrypted = unencrypted + '.gpg' if File.exists?(encrypted) encrypted else unencrypted end end
ruby
def netrc_path unencrypted = Netrc.default_path encrypted = unencrypted + '.gpg' if File.exists?(encrypted) encrypted else unencrypted end end
[ "def", "netrc_path", "unencrypted", "=", "Netrc", ".", "default_path", "encrypted", "=", "unencrypted", "+", "'.gpg'", "if", "File", ".", "exists?", "(", "encrypted", ")", "encrypted", "else", "unencrypted", "end", "end" ]
Returns the path to the `.netrc` file containing the Turbot host's entry with the user's email address and API key. @return [String] the path to the `.netrc` file
[ "Returns", "the", "path", "to", "the", ".", "netrc", "file", "containing", "the", "Turbot", "host", "s", "entry", "with", "the", "user", "s", "email", "address", "and", "API", "key", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L23-L31
24,477
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.open_netrc
def open_netrc begin Netrc.read(netrc_path) rescue Netrc::Error => e error e.message end end
ruby
def open_netrc begin Netrc.read(netrc_path) rescue Netrc::Error => e error e.message end end
[ "def", "open_netrc", "begin", "Netrc", ".", "read", "(", "netrc_path", ")", "rescue", "Netrc", "::", "Error", "=>", "e", "error", "e", ".", "message", "end", "end" ]
Reads a `.netrc` file. @return [Netrc] the `.netrc` file
[ "Reads", "a", ".", "netrc", "file", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L43-L49
24,478
openc/turbot-client
lib/turbot/helpers/netrc_helper.rb
Turbot.Helpers.save_netrc_entry
def save_netrc_entry(email_address, api_key) netrc = open_netrc netrc["api.#{host}"] = [email_address, api_key] netrc.save end
ruby
def save_netrc_entry(email_address, api_key) netrc = open_netrc netrc["api.#{host}"] = [email_address, api_key] netrc.save end
[ "def", "save_netrc_entry", "(", "email_address", ",", "api_key", ")", "netrc", "=", "open_netrc", "netrc", "[", "\"api.#{host}\"", "]", "=", "[", "email_address", ",", "api_key", "]", "netrc", ".", "save", "end" ]
Saves the user's email address and AP key to the Turbot host's entry in the `.netrc` file.
[ "Saves", "the", "user", "s", "email", "address", "and", "AP", "key", "to", "the", "Turbot", "host", "s", "entry", "in", "the", ".", "netrc", "file", "." ]
01225a5c7e155b7b34f1ae8de107c0b97201b42d
https://github.com/openc/turbot-client/blob/01225a5c7e155b7b34f1ae8de107c0b97201b42d/lib/turbot/helpers/netrc_helper.rb#L60-L64
24,479
CocoaPods/Humus
lib/snapshots.rb
Humus.Snapshots.seed_from_dump
def seed_from_dump id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) raise "Dump #{id} could not be found." unless File.exists? target_path puts "Restoring #{ENV['RACK_ENV']} database from #{target_path}" # Ensure we're starting from a clean DB. system "dropdb trunk_cocoapods_org_test" system "createdb trunk_cocoapods_org_test" # Restore the DB. command = "pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}" puts "Executing:" puts command puts result = system command if result puts "Database #{ENV['RACK_ENV']} restored from #{target_path}" else warn "Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors." # exit 1 end end
ruby
def seed_from_dump id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) raise "Dump #{id} could not be found." unless File.exists? target_path puts "Restoring #{ENV['RACK_ENV']} database from #{target_path}" # Ensure we're starting from a clean DB. system "dropdb trunk_cocoapods_org_test" system "createdb trunk_cocoapods_org_test" # Restore the DB. command = "pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}" puts "Executing:" puts command puts result = system command if result puts "Database #{ENV['RACK_ENV']} restored from #{target_path}" else warn "Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors." # exit 1 end end
[ "def", "seed_from_dump", "id", "target_path", "=", "File", ".", "expand_path", "(", "\"../../fixtures/trunk-#{id}.dump\"", ",", "__FILE__", ")", "raise", "\"Dump #{id} could not be found.\"", "unless", "File", ".", "exists?", "target_path", "puts", "\"Restoring #{ENV['RACK_ENV']} database from #{target_path}\"", "# Ensure we're starting from a clean DB.", "system", "\"dropdb trunk_cocoapods_org_test\"", "system", "\"createdb trunk_cocoapods_org_test\"", "# Restore the DB.", "command", "=", "\"pg_restore --no-privileges --clean --no-acl --no-owner -h localhost -d trunk_cocoapods_org_test #{target_path}\"", "puts", "\"Executing:\"", "puts", "command", "puts", "result", "=", "system", "command", "if", "result", "puts", "\"Database #{ENV['RACK_ENV']} restored from #{target_path}\"", "else", "warn", "\"Database #{ENV['RACK_ENV']} restored from #{target_path} with some errors.\"", "# exit 1", "end", "end" ]
Seed the database from a downloaded dump.
[ "Seed", "the", "database", "from", "a", "downloaded", "dump", "." ]
dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e
https://github.com/CocoaPods/Humus/blob/dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e/lib/snapshots.rb#L43-L65
24,480
CocoaPods/Humus
lib/snapshots.rb
Humus.Snapshots.dump_prod
def dump_prod id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) puts "Dumping production database from Heroku (works only if you have access to the database)" command = "curl -o #{target_path} \`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\`" puts "Executing command:" puts command result = system command if result puts "Production database snapshot #{id} dumped into #{target_path}" else raise "Could not dump #{id} from production database." end end
ruby
def dump_prod id target_path = File.expand_path("../../fixtures/trunk-#{id}.dump", __FILE__) puts "Dumping production database from Heroku (works only if you have access to the database)" command = "curl -o #{target_path} \`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\`" puts "Executing command:" puts command result = system command if result puts "Production database snapshot #{id} dumped into #{target_path}" else raise "Could not dump #{id} from production database." end end
[ "def", "dump_prod", "id", "target_path", "=", "File", ".", "expand_path", "(", "\"../../fixtures/trunk-#{id}.dump\"", ",", "__FILE__", ")", "puts", "\"Dumping production database from Heroku (works only if you have access to the database)\"", "command", "=", "\"curl -o #{target_path} \\`heroku pg:backups public-url #{id} -a cocoapods-trunk-service\\`\"", "puts", "\"Executing command:\"", "puts", "command", "result", "=", "system", "command", "if", "result", "puts", "\"Production database snapshot #{id} dumped into #{target_path}\"", "else", "raise", "\"Could not dump #{id} from production database.\"", "end", "end" ]
Dump the production DB.
[ "Dump", "the", "production", "DB", "." ]
dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e
https://github.com/CocoaPods/Humus/blob/dd2b1b2b484cc5636bf16ecb4fc189c728dbb23e/lib/snapshots.rb#L69-L81
24,481
arvicco/win
lib/win/library.rb
Win.Library.try_function
def try_function(name, params, returns, options={}, &def_block) begin function name, params, returns, options, &def_block rescue Win::Errors::NotFoundError "This platform does not support function #{name}" end end
ruby
def try_function(name, params, returns, options={}, &def_block) begin function name, params, returns, options, &def_block rescue Win::Errors::NotFoundError "This platform does not support function #{name}" end end
[ "def", "try_function", "(", "name", ",", "params", ",", "returns", ",", "options", "=", "{", "}", ",", "&", "def_block", ")", "begin", "function", "name", ",", "params", ",", "returns", ",", "options", ",", "def_block", "rescue", "Win", "::", "Errors", "::", "NotFoundError", "\"This platform does not support function #{name}\"", "end", "end" ]
Try to define platform-specific function, rescue error, return message
[ "Try", "to", "define", "platform", "-", "specific", "function", "rescue", "error", "return", "message" ]
835a998100b5584a9b2b5c5888567c948929f36a
https://github.com/arvicco/win/blob/835a998100b5584a9b2b5c5888567c948929f36a/lib/win/library.rb#L299-L305
24,482
arvicco/win
lib/win/library.rb
Win.Library.define_api
def define_api(name, camel_name, effective_names, params, returns, options) params, returns = generate_signature(params.dup, returns) ffi_lib *(ffi_libraries.map(&:name) << options[:dll]) if options[:dll] libs = ffi_libraries.map(&:name) alternative = options.delete(:alternative) # Function may have alternative signature effective_name = if alternative alt_params, alt_returns, condition = generate_signature(*alternative) api = function name, params, returns, options.merge( camel_only: true, camel_name: "#{camel_name}Original") alt_api = function name, alt_params, alt_returns, options.merge( camel_only: true, camel_name: "#{camel_name}Alternative") define_method camel_name do |*args| (condition[*args] ? alt_api : api).call(*args) end module_function camel_name public camel_name api.effective_name else effective_names.inject(nil) do |func, effective_name| func || begin # Try to attach basic CamelCase method via FFI attach_function(camel_name, effective_name, params.dup, returns) effective_name rescue FFI::NotFoundError nil end end end raise Win::Errors::NotFoundError.new(name, libs) unless effective_name # Create API object that holds information about defined and effective function names, params, etc. # This object is further used by enhanced snake_case method to reflect on underlying API and # intelligently call it. API.new(namespace, camel_name, effective_name, params, returns, libs) end
ruby
def define_api(name, camel_name, effective_names, params, returns, options) params, returns = generate_signature(params.dup, returns) ffi_lib *(ffi_libraries.map(&:name) << options[:dll]) if options[:dll] libs = ffi_libraries.map(&:name) alternative = options.delete(:alternative) # Function may have alternative signature effective_name = if alternative alt_params, alt_returns, condition = generate_signature(*alternative) api = function name, params, returns, options.merge( camel_only: true, camel_name: "#{camel_name}Original") alt_api = function name, alt_params, alt_returns, options.merge( camel_only: true, camel_name: "#{camel_name}Alternative") define_method camel_name do |*args| (condition[*args] ? alt_api : api).call(*args) end module_function camel_name public camel_name api.effective_name else effective_names.inject(nil) do |func, effective_name| func || begin # Try to attach basic CamelCase method via FFI attach_function(camel_name, effective_name, params.dup, returns) effective_name rescue FFI::NotFoundError nil end end end raise Win::Errors::NotFoundError.new(name, libs) unless effective_name # Create API object that holds information about defined and effective function names, params, etc. # This object is further used by enhanced snake_case method to reflect on underlying API and # intelligently call it. API.new(namespace, camel_name, effective_name, params, returns, libs) end
[ "def", "define_api", "(", "name", ",", "camel_name", ",", "effective_names", ",", "params", ",", "returns", ",", "options", ")", "params", ",", "returns", "=", "generate_signature", "(", "params", ".", "dup", ",", "returns", ")", "ffi_lib", "(", "ffi_libraries", ".", "map", "(", ":name", ")", "<<", "options", "[", ":dll", "]", ")", "if", "options", "[", ":dll", "]", "libs", "=", "ffi_libraries", ".", "map", "(", ":name", ")", "alternative", "=", "options", ".", "delete", "(", ":alternative", ")", "# Function may have alternative signature", "effective_name", "=", "if", "alternative", "alt_params", ",", "alt_returns", ",", "condition", "=", "generate_signature", "(", "alternative", ")", "api", "=", "function", "name", ",", "params", ",", "returns", ",", "options", ".", "merge", "(", "camel_only", ":", "true", ",", "camel_name", ":", "\"#{camel_name}Original\"", ")", "alt_api", "=", "function", "name", ",", "alt_params", ",", "alt_returns", ",", "options", ".", "merge", "(", "camel_only", ":", "true", ",", "camel_name", ":", "\"#{camel_name}Alternative\"", ")", "define_method", "camel_name", "do", "|", "*", "args", "|", "(", "condition", "[", "args", "]", "?", "alt_api", ":", "api", ")", ".", "call", "(", "args", ")", "end", "module_function", "camel_name", "public", "camel_name", "api", ".", "effective_name", "else", "effective_names", ".", "inject", "(", "nil", ")", "do", "|", "func", ",", "effective_name", "|", "func", "||", "begin", "# Try to attach basic CamelCase method via FFI", "attach_function", "(", "camel_name", ",", "effective_name", ",", "params", ".", "dup", ",", "returns", ")", "effective_name", "rescue", "FFI", "::", "NotFoundError", "nil", "end", "end", "end", "raise", "Win", "::", "Errors", "::", "NotFoundError", ".", "new", "(", "name", ",", "libs", ")", "unless", "effective_name", "# Create API object that holds information about defined and effective function names, params, etc.", "# This object is further used by enhanced snake_case method to reflect on underlying API and", "# intelligently call it.", "API", ".", "new", "(", "namespace", ",", "camel_name", ",", "effective_name", ",", "params", ",", "returns", ",", "libs", ")", "end" ]
Defines CamelCase method calling Win32 API function, and associated API object
[ "Defines", "CamelCase", "method", "calling", "Win32", "API", "function", "and", "associated", "API", "object" ]
835a998100b5584a9b2b5c5888567c948929f36a
https://github.com/arvicco/win/blob/835a998100b5584a9b2b5c5888567c948929f36a/lib/win/library.rb#L309-L348
24,483
zdennis/yap-shell-core
lib/yap/shell/evaluation.rb
Yap::Shell.Evaluation.recursively_find_and_replace_command_substitutions
def recursively_find_and_replace_command_substitutions(input) input = input.dup Parser.each_command_substitution_for(input) do |substitution_result, start_position, end_position| debug_log "found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}" result = recursively_find_and_replace_command_substitutions(substitution_result.str) position = substitution_result.position ast = Parser.parse(result) with_standard_streams do |stdin, stdout, stderr| r,w = IO.pipe @stdout = w ast.accept(self) output = r.read.chomp # Treat consecutive newlines in output as a single space output = output.gsub(/\n+/, ' ') # Double quote the output and escape any double quotes already # existing output = %|"#{output.gsub(/"/, '\\"')}"| # Put thd output back into the original input debug_log "replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}" input[position.min...position.max] = output end end input end
ruby
def recursively_find_and_replace_command_substitutions(input) input = input.dup Parser.each_command_substitution_for(input) do |substitution_result, start_position, end_position| debug_log "found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}" result = recursively_find_and_replace_command_substitutions(substitution_result.str) position = substitution_result.position ast = Parser.parse(result) with_standard_streams do |stdin, stdout, stderr| r,w = IO.pipe @stdout = w ast.accept(self) output = r.read.chomp # Treat consecutive newlines in output as a single space output = output.gsub(/\n+/, ' ') # Double quote the output and escape any double quotes already # existing output = %|"#{output.gsub(/"/, '\\"')}"| # Put thd output back into the original input debug_log "replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}" input[position.min...position.max] = output end end input end
[ "def", "recursively_find_and_replace_command_substitutions", "(", "input", ")", "input", "=", "input", ".", "dup", "Parser", ".", "each_command_substitution_for", "(", "input", ")", "do", "|", "substitution_result", ",", "start_position", ",", "end_position", "|", "debug_log", "\"found command substitution at position=#{(start_position..end_position)} #{substitution_result.inspect}\"", "result", "=", "recursively_find_and_replace_command_substitutions", "(", "substitution_result", ".", "str", ")", "position", "=", "substitution_result", ".", "position", "ast", "=", "Parser", ".", "parse", "(", "result", ")", "with_standard_streams", "do", "|", "stdin", ",", "stdout", ",", "stderr", "|", "r", ",", "w", "=", "IO", ".", "pipe", "@stdout", "=", "w", "ast", ".", "accept", "(", "self", ")", "output", "=", "r", ".", "read", ".", "chomp", "# Treat consecutive newlines in output as a single space", "output", "=", "output", ".", "gsub", "(", "/", "\\n", "/", ",", "' '", ")", "# Double quote the output and escape any double quotes already", "# existing", "output", "=", "%|\"#{output.gsub(/\"/, '\\\\\"')}\"|", "# Put thd output back into the original input", "debug_log", "\"replacing command substitution at position=#{(position.min...position.max)} with #{output.inspect}\"", "input", "[", "position", ".", "min", "...", "position", ".", "max", "]", "=", "output", "end", "end", "input", "end" ]
+recursively_find_and_replace_command_substitutions+ is responsible for recursively finding and expanding command substitutions, in a depth first manner.
[ "+", "recursively_find_and_replace_command_substitutions", "+", "is", "responsible", "for", "recursively", "finding", "and", "expanding", "command", "substitutions", "in", "a", "depth", "first", "manner", "." ]
37f1c871c492215cbfad85c228ac19adb39d940e
https://github.com/zdennis/yap-shell-core/blob/37f1c871c492215cbfad85c228ac19adb39d940e/lib/yap/shell/evaluation.rb#L46-L73
24,484
zdennis/yap-shell-core
lib/yap/shell/evaluation.rb
Yap::Shell.Evaluation.visit_CommandNode
def visit_CommandNode(node) debug_visit(node) @aliases_expanded ||= [] @command_node_args_stack ||= [] with_standard_streams do |stdin, stdout, stderr| args = process_ArgumentNodes(node.args) if !node.literal? && !@aliases_expanded.include?(node.command) && Aliases.instance.has_key?(node.command) _alias=Aliases.instance.fetch_alias(node.command) @suppress_events = true @command_node_args_stack << args ast = Parser.parse(_alias) @aliases_expanded.push(node.command) ast.accept(self) @aliases_expanded.pop @suppress_events = false else cmd2execute = variable_expand(node.command) final_args = (args + @command_node_args_stack).flatten.map(&:shellescape) expanded_args = final_args command = CommandFactory.build_command_for( world: world, command: cmd2execute, args: expanded_args, heredoc: (node.heredoc && node.heredoc.value), internally_evaluate: node.internally_evaluate?, line: @input) @stdin, @stdout, @stderr = stream_redirections_for(node) set_last_result @blk.call command, @stdin, @stdout, @stderr, pipeline_stack.empty? @command_node_args_stack.clear end end end
ruby
def visit_CommandNode(node) debug_visit(node) @aliases_expanded ||= [] @command_node_args_stack ||= [] with_standard_streams do |stdin, stdout, stderr| args = process_ArgumentNodes(node.args) if !node.literal? && !@aliases_expanded.include?(node.command) && Aliases.instance.has_key?(node.command) _alias=Aliases.instance.fetch_alias(node.command) @suppress_events = true @command_node_args_stack << args ast = Parser.parse(_alias) @aliases_expanded.push(node.command) ast.accept(self) @aliases_expanded.pop @suppress_events = false else cmd2execute = variable_expand(node.command) final_args = (args + @command_node_args_stack).flatten.map(&:shellescape) expanded_args = final_args command = CommandFactory.build_command_for( world: world, command: cmd2execute, args: expanded_args, heredoc: (node.heredoc && node.heredoc.value), internally_evaluate: node.internally_evaluate?, line: @input) @stdin, @stdout, @stderr = stream_redirections_for(node) set_last_result @blk.call command, @stdin, @stdout, @stderr, pipeline_stack.empty? @command_node_args_stack.clear end end end
[ "def", "visit_CommandNode", "(", "node", ")", "debug_visit", "(", "node", ")", "@aliases_expanded", "||=", "[", "]", "@command_node_args_stack", "||=", "[", "]", "with_standard_streams", "do", "|", "stdin", ",", "stdout", ",", "stderr", "|", "args", "=", "process_ArgumentNodes", "(", "node", ".", "args", ")", "if", "!", "node", ".", "literal?", "&&", "!", "@aliases_expanded", ".", "include?", "(", "node", ".", "command", ")", "&&", "Aliases", ".", "instance", ".", "has_key?", "(", "node", ".", "command", ")", "_alias", "=", "Aliases", ".", "instance", ".", "fetch_alias", "(", "node", ".", "command", ")", "@suppress_events", "=", "true", "@command_node_args_stack", "<<", "args", "ast", "=", "Parser", ".", "parse", "(", "_alias", ")", "@aliases_expanded", ".", "push", "(", "node", ".", "command", ")", "ast", ".", "accept", "(", "self", ")", "@aliases_expanded", ".", "pop", "@suppress_events", "=", "false", "else", "cmd2execute", "=", "variable_expand", "(", "node", ".", "command", ")", "final_args", "=", "(", "args", "+", "@command_node_args_stack", ")", ".", "flatten", ".", "map", "(", ":shellescape", ")", "expanded_args", "=", "final_args", "command", "=", "CommandFactory", ".", "build_command_for", "(", "world", ":", "world", ",", "command", ":", "cmd2execute", ",", "args", ":", "expanded_args", ",", "heredoc", ":", "(", "node", ".", "heredoc", "&&", "node", ".", "heredoc", ".", "value", ")", ",", "internally_evaluate", ":", "node", ".", "internally_evaluate?", ",", "line", ":", "@input", ")", "@stdin", ",", "@stdout", ",", "@stderr", "=", "stream_redirections_for", "(", "node", ")", "set_last_result", "@blk", ".", "call", "command", ",", "@stdin", ",", "@stdout", ",", "@stderr", ",", "pipeline_stack", ".", "empty?", "@command_node_args_stack", ".", "clear", "end", "end", "end" ]
VISITOR METHODS FOR AST TREE WALKING
[ "VISITOR", "METHODS", "FOR", "AST", "TREE", "WALKING" ]
37f1c871c492215cbfad85c228ac19adb39d940e
https://github.com/zdennis/yap-shell-core/blob/37f1c871c492215cbfad85c228ac19adb39d940e/lib/yap/shell/evaluation.rb#L82-L113
24,485
fwal/danger-jazzy
lib/jazzy/plugin.rb
Danger.DangerJazzy.undocumented
def undocumented(scope = :modified) return [] unless scope != :ignore && File.exist?(undocumented_path) @undocumented = { modified: [], all: [] } if @undocumented.nil? load_undocumented(scope) if @undocumented[scope].empty? @undocumented[scope] end
ruby
def undocumented(scope = :modified) return [] unless scope != :ignore && File.exist?(undocumented_path) @undocumented = { modified: [], all: [] } if @undocumented.nil? load_undocumented(scope) if @undocumented[scope].empty? @undocumented[scope] end
[ "def", "undocumented", "(", "scope", "=", ":modified", ")", "return", "[", "]", "unless", "scope", "!=", ":ignore", "&&", "File", ".", "exist?", "(", "undocumented_path", ")", "@undocumented", "=", "{", "modified", ":", "[", "]", ",", "all", ":", "[", "]", "}", "if", "@undocumented", ".", "nil?", "load_undocumented", "(", "scope", ")", "if", "@undocumented", "[", "scope", "]", ".", "empty?", "@undocumented", "[", "scope", "]", "end" ]
Returns a list of undocumented symbols in the current diff. Available scopes: * `modified` * `all` @param [Key] scope @return [Array of symbol]
[ "Returns", "a", "list", "of", "undocumented", "symbols", "in", "the", "current", "diff", "." ]
a125fa61977621a07762c50fc44fb62942c3df68
https://github.com/fwal/danger-jazzy/blob/a125fa61977621a07762c50fc44fb62942c3df68/lib/jazzy/plugin.rb#L81-L86
24,486
kukareka/spree_liqpay
app/controllers/spree/liqpay_status_controller.rb
Spree.LiqpayStatusController.update
def update @payment_method = PaymentMethod.find params[:payment_method_id] data = JSON.parse Base64.strict_decode64 params[:data] render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature] @order = Order.find data['order_id'] raise ArgumentError unless @order.payments.completed.empty? && data['currency'] == @order.currency && BigDecimal(data['amount']) == @order.total && data['type'] == 'buy' && (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox')) payment = @order.payments.create amount: @order.total, payment_method: @payment_method payment.complete! render text: "Thank you.\n" end
ruby
def update @payment_method = PaymentMethod.find params[:payment_method_id] data = JSON.parse Base64.strict_decode64 params[:data] render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature] @order = Order.find data['order_id'] raise ArgumentError unless @order.payments.completed.empty? && data['currency'] == @order.currency && BigDecimal(data['amount']) == @order.total && data['type'] == 'buy' && (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox')) payment = @order.payments.create amount: @order.total, payment_method: @payment_method payment.complete! render text: "Thank you.\n" end
[ "def", "update", "@payment_method", "=", "PaymentMethod", ".", "find", "params", "[", ":payment_method_id", "]", "data", "=", "JSON", ".", "parse", "Base64", ".", "strict_decode64", "params", "[", ":data", "]", "render", "text", ":", "\"Bad signature\\n\"", ",", "status", ":", "401", "and", "return", "unless", "@payment_method", ".", "check_signature", "params", "[", ":data", "]", ",", "params", "[", ":signature", "]", "@order", "=", "Order", ".", "find", "data", "[", "'order_id'", "]", "raise", "ArgumentError", "unless", "@order", ".", "payments", ".", "completed", ".", "empty?", "&&", "data", "[", "'currency'", "]", "==", "@order", ".", "currency", "&&", "BigDecimal", "(", "data", "[", "'amount'", "]", ")", "==", "@order", ".", "total", "&&", "data", "[", "'type'", "]", "==", "'buy'", "&&", "(", "data", "[", "'status'", "]", "==", "'success'", "||", "(", "@payment_method", ".", "preferred_test_mode", "&&", "data", "[", "'status'", "]", "==", "'sandbox'", ")", ")", "payment", "=", "@order", ".", "payments", ".", "create", "amount", ":", "@order", ".", "total", ",", "payment_method", ":", "@payment_method", "payment", ".", "complete!", "render", "text", ":", "\"Thank you.\\n\"", "end" ]
callbacks from Liqpay server
[ "callbacks", "from", "Liqpay", "server" ]
996ef2908adbc512571e03dc148613f59fc05766
https://github.com/kukareka/spree_liqpay/blob/996ef2908adbc512571e03dc148613f59fc05766/app/controllers/spree/liqpay_status_controller.rb#L7-L23
24,487
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.brokers
def brokers @brokers_mutex.synchronize do @brokers ||= begin brokers = zk.get_children(path: "/brokers/ids") if brokers.fetch(:rc) != Zookeeper::Constants::ZOK raise NoClusterRegistered, "No Kafka cluster registered on this Zookeeper location." end result, mutex = {}, Mutex.new threads = brokers.fetch(:children).map do |id| Thread.new do Thread.abort_on_exception = true broker_info = zk.get(path: "/brokers/ids/#{id}") raise Kazoo::Error, "Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}" unless broker_info.fetch(:rc) == Zookeeper::Constants::ZOK broker = Kazoo::Broker.from_json(self, id, JSON.parse(broker_info.fetch(:data))) mutex.synchronize { result[id.to_i] = broker } end end threads.each(&:join) result end end end
ruby
def brokers @brokers_mutex.synchronize do @brokers ||= begin brokers = zk.get_children(path: "/brokers/ids") if brokers.fetch(:rc) != Zookeeper::Constants::ZOK raise NoClusterRegistered, "No Kafka cluster registered on this Zookeeper location." end result, mutex = {}, Mutex.new threads = brokers.fetch(:children).map do |id| Thread.new do Thread.abort_on_exception = true broker_info = zk.get(path: "/brokers/ids/#{id}") raise Kazoo::Error, "Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}" unless broker_info.fetch(:rc) == Zookeeper::Constants::ZOK broker = Kazoo::Broker.from_json(self, id, JSON.parse(broker_info.fetch(:data))) mutex.synchronize { result[id.to_i] = broker } end end threads.each(&:join) result end end end
[ "def", "brokers", "@brokers_mutex", ".", "synchronize", "do", "@brokers", "||=", "begin", "brokers", "=", "zk", ".", "get_children", "(", "path", ":", "\"/brokers/ids\"", ")", "if", "brokers", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "raise", "NoClusterRegistered", ",", "\"No Kafka cluster registered on this Zookeeper location.\"", "end", "result", ",", "mutex", "=", "{", "}", ",", "Mutex", ".", "new", "threads", "=", "brokers", ".", "fetch", "(", ":children", ")", ".", "map", "do", "|", "id", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "broker_info", "=", "zk", ".", "get", "(", "path", ":", "\"/brokers/ids/#{id}\"", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to retrieve broker info. Error code: #{broker_info.fetch(:rc)}\"", "unless", "broker_info", ".", "fetch", "(", ":rc", ")", "==", "Zookeeper", "::", "Constants", "::", "ZOK", "broker", "=", "Kazoo", "::", "Broker", ".", "from_json", "(", "self", ",", "id", ",", "JSON", ".", "parse", "(", "broker_info", ".", "fetch", "(", ":data", ")", ")", ")", "mutex", ".", "synchronize", "{", "result", "[", "id", ".", "to_i", "]", "=", "broker", "}", "end", "end", "threads", ".", "each", "(", ":join", ")", "result", "end", "end", "end" ]
Returns a hash of all the brokers in the
[ "Returns", "a", "hash", "of", "all", "the", "brokers", "in", "the" ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L22-L46
24,488
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.consumergroups
def consumergroups @consumergroups ||= begin consumers = zk.get_children(path: "/consumers") consumers.fetch(:children).map { |name| Kazoo::Consumergroup.new(self, name) } end end
ruby
def consumergroups @consumergroups ||= begin consumers = zk.get_children(path: "/consumers") consumers.fetch(:children).map { |name| Kazoo::Consumergroup.new(self, name) } end end
[ "def", "consumergroups", "@consumergroups", "||=", "begin", "consumers", "=", "zk", ".", "get_children", "(", "path", ":", "\"/consumers\"", ")", "consumers", ".", "fetch", "(", ":children", ")", ".", "map", "{", "|", "name", "|", "Kazoo", "::", "Consumergroup", ".", "new", "(", "self", ",", "name", ")", "}", "end", "end" ]
Returns a list of consumer groups that are registered against the Kafka cluster.
[ "Returns", "a", "list", "of", "consumer", "groups", "that", "are", "registered", "against", "the", "Kafka", "cluster", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L49-L54
24,489
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.topics
def topics(preload: Kazoo::Topic::DEFAULT_PRELOAD_METHODS) @topics_mutex.synchronize do @topics ||= begin topics = zk.get_children(path: "/brokers/topics") raise Kazoo::Error, "Failed to list topics. Error code: #{topics.fetch(:rc)}" unless topics.fetch(:rc) == Zookeeper::Constants::ZOK preload_topics_from_names(topics.fetch(:children), preload: preload) end end end
ruby
def topics(preload: Kazoo::Topic::DEFAULT_PRELOAD_METHODS) @topics_mutex.synchronize do @topics ||= begin topics = zk.get_children(path: "/brokers/topics") raise Kazoo::Error, "Failed to list topics. Error code: #{topics.fetch(:rc)}" unless topics.fetch(:rc) == Zookeeper::Constants::ZOK preload_topics_from_names(topics.fetch(:children), preload: preload) end end end
[ "def", "topics", "(", "preload", ":", "Kazoo", "::", "Topic", "::", "DEFAULT_PRELOAD_METHODS", ")", "@topics_mutex", ".", "synchronize", "do", "@topics", "||=", "begin", "topics", "=", "zk", ".", "get_children", "(", "path", ":", "\"/brokers/topics\"", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to list topics. Error code: #{topics.fetch(:rc)}\"", "unless", "topics", ".", "fetch", "(", ":rc", ")", "==", "Zookeeper", "::", "Constants", "::", "ZOK", "preload_topics_from_names", "(", "topics", ".", "fetch", "(", ":children", ")", ",", "preload", ":", "preload", ")", "end", "end", "end" ]
Returns a hash of all the topics in the Kafka cluster, indexed by the topic name.
[ "Returns", "a", "hash", "of", "all", "the", "topics", "in", "the", "Kafka", "cluster", "indexed", "by", "the", "topic", "name", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L65-L73
24,490
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.create_topic
def create_topic(name, partitions: nil, replication_factor: nil, config: nil) raise ArgumentError, "partitions must be a positive integer" if Integer(partitions) <= 0 raise ArgumentError, "replication_factor must be a positive integer" if Integer(replication_factor) <= 0 Kazoo::Topic.create(self, name, partitions: Integer(partitions), replication_factor: Integer(replication_factor), config: config) end
ruby
def create_topic(name, partitions: nil, replication_factor: nil, config: nil) raise ArgumentError, "partitions must be a positive integer" if Integer(partitions) <= 0 raise ArgumentError, "replication_factor must be a positive integer" if Integer(replication_factor) <= 0 Kazoo::Topic.create(self, name, partitions: Integer(partitions), replication_factor: Integer(replication_factor), config: config) end
[ "def", "create_topic", "(", "name", ",", "partitions", ":", "nil", ",", "replication_factor", ":", "nil", ",", "config", ":", "nil", ")", "raise", "ArgumentError", ",", "\"partitions must be a positive integer\"", "if", "Integer", "(", "partitions", ")", "<=", "0", "raise", "ArgumentError", ",", "\"replication_factor must be a positive integer\"", "if", "Integer", "(", "replication_factor", ")", "<=", "0", "Kazoo", "::", "Topic", ".", "create", "(", "self", ",", "name", ",", "partitions", ":", "Integer", "(", "partitions", ")", ",", "replication_factor", ":", "Integer", "(", "replication_factor", ")", ",", "config", ":", "config", ")", "end" ]
Creates a topic on the Kafka cluster, with the provided number of partitions and replication factor.
[ "Creates", "a", "topic", "on", "the", "Kafka", "cluster", "with", "the", "provided", "number", "of", "partitions", "and", "replication", "factor", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L82-L87
24,491
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.preferred_leader_election
def preferred_leader_election(partitions: nil) partitions = self.partitions if partitions.nil? result = zk.create(path: "/admin/preferred_replica_election", data: JSON.generate(version: 1, partitions: partitions)) case result.fetch(:rc) when Zookeeper::Constants::ZOK return true when Zookeeper::Constants::ZNODEEXISTS raise Kazoo::Error, "Another preferred leader election is still in progress" else raise Kazoo::Error, "Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}" end end
ruby
def preferred_leader_election(partitions: nil) partitions = self.partitions if partitions.nil? result = zk.create(path: "/admin/preferred_replica_election", data: JSON.generate(version: 1, partitions: partitions)) case result.fetch(:rc) when Zookeeper::Constants::ZOK return true when Zookeeper::Constants::ZNODEEXISTS raise Kazoo::Error, "Another preferred leader election is still in progress" else raise Kazoo::Error, "Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}" end end
[ "def", "preferred_leader_election", "(", "partitions", ":", "nil", ")", "partitions", "=", "self", ".", "partitions", "if", "partitions", ".", "nil?", "result", "=", "zk", ".", "create", "(", "path", ":", "\"/admin/preferred_replica_election\"", ",", "data", ":", "JSON", ".", "generate", "(", "version", ":", "1", ",", "partitions", ":", "partitions", ")", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", "return", "true", "when", "Zookeeper", "::", "Constants", "::", "ZNODEEXISTS", "raise", "Kazoo", "::", "Error", ",", "\"Another preferred leader election is still in progress\"", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to start preferred leadership election. Result code: #{result.fetch(:rc)}\"", "end", "end" ]
Triggers a preferred leader elections for the provided list of partitions. If no list of partitions is provided, the preferred leader will be elected for all partitions in the cluster.
[ "Triggers", "a", "preferred", "leader", "elections", "for", "the", "provided", "list", "of", "partitions", ".", "If", "no", "list", "of", "partitions", "is", "provided", "the", "preferred", "leader", "will", "be", "elected", "for", "all", "partitions", "in", "the", "cluster", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L107-L118
24,492
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.recursive_create
def recursive_create(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.stat(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK return when Zookeeper::Constants::ZNONODE recursive_create(path: File.dirname(path)) result = zk.create(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK, Zookeeper::Constants::ZNODEEXISTS return else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end end
ruby
def recursive_create(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.stat(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK return when Zookeeper::Constants::ZNONODE recursive_create(path: File.dirname(path)) result = zk.create(path: path) case result.fetch(:rc) when Zookeeper::Constants::ZOK, Zookeeper::Constants::ZNODEEXISTS return else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end else raise Kazoo::Error, "Failed to create node #{path}. Result code: #{result.fetch(:rc)}" end end
[ "def", "recursive_create", "(", "path", ":", "nil", ")", "raise", "ArgumentError", ",", "\"path is a required argument\"", "if", "path", ".", "nil?", "result", "=", "zk", ".", "stat", "(", "path", ":", "path", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", "return", "when", "Zookeeper", "::", "Constants", "::", "ZNONODE", "recursive_create", "(", "path", ":", "File", ".", "dirname", "(", "path", ")", ")", "result", "=", "zk", ".", "create", "(", "path", ":", "path", ")", "case", "result", ".", "fetch", "(", ":rc", ")", "when", "Zookeeper", "::", "Constants", "::", "ZOK", ",", "Zookeeper", "::", "Constants", "::", "ZNODEEXISTS", "return", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to create node #{path}. Result code: #{result.fetch(:rc)}\"", "end", "else", "raise", "Kazoo", "::", "Error", ",", "\"Failed to create node #{path}. Result code: #{result.fetch(:rc)}\"", "end", "end" ]
Recursively creates a node in Zookeeper, by recusrively trying to create its parent if it doesn not yet exist.
[ "Recursively", "creates", "a", "node", "in", "Zookeeper", "by", "recusrively", "trying", "to", "create", "its", "parent", "if", "it", "doesn", "not", "yet", "exist", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L131-L151
24,493
wvanbergen/kazoo
lib/kazoo/cluster.rb
Kazoo.Cluster.recursive_delete
def recursive_delete(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.get_children(path: path) raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK threads = result.fetch(:children).map do |name| Thread.new do Thread.abort_on_exception = true recursive_delete(path: File.join(path, name)) end end threads.each(&:join) result = zk.delete(path: path) raise Kazoo::Error, "Failed to delete node #{path}. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK end
ruby
def recursive_delete(path: nil) raise ArgumentError, "path is a required argument" if path.nil? result = zk.get_children(path: path) raise Kazoo::Error, "Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK threads = result.fetch(:children).map do |name| Thread.new do Thread.abort_on_exception = true recursive_delete(path: File.join(path, name)) end end threads.each(&:join) result = zk.delete(path: path) raise Kazoo::Error, "Failed to delete node #{path}. Result code: #{result.fetch(:rc)}" if result.fetch(:rc) != Zookeeper::Constants::ZOK end
[ "def", "recursive_delete", "(", "path", ":", "nil", ")", "raise", "ArgumentError", ",", "\"path is a required argument\"", "if", "path", ".", "nil?", "result", "=", "zk", ".", "get_children", "(", "path", ":", "path", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to list children of #{path} to delete them. Result code: #{result.fetch(:rc)}\"", "if", "result", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "threads", "=", "result", ".", "fetch", "(", ":children", ")", ".", "map", "do", "|", "name", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "recursive_delete", "(", "path", ":", "File", ".", "join", "(", "path", ",", "name", ")", ")", "end", "end", "threads", ".", "each", "(", ":join", ")", "result", "=", "zk", ".", "delete", "(", "path", ":", "path", ")", "raise", "Kazoo", "::", "Error", ",", "\"Failed to delete node #{path}. Result code: #{result.fetch(:rc)}\"", "if", "result", ".", "fetch", "(", ":rc", ")", "!=", "Zookeeper", "::", "Constants", "::", "ZOK", "end" ]
Deletes a node and all of its children from Zookeeper.
[ "Deletes", "a", "node", "and", "all", "of", "its", "children", "from", "Zookeeper", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/cluster.rb#L154-L170
24,494
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.find
def find(text) nodes = parser.parse(text) nodes.length.times.find do |index| if (song = Song.new(nodes[index..-1], rule: @rule)).valid? break song end end end
ruby
def find(text) nodes = parser.parse(text) nodes.length.times.find do |index| if (song = Song.new(nodes[index..-1], rule: @rule)).valid? break song end end end
[ "def", "find", "(", "text", ")", "nodes", "=", "parser", ".", "parse", "(", "text", ")", "nodes", ".", "length", ".", "times", ".", "find", "do", "|", "index", "|", "if", "(", "song", "=", "Song", ".", "new", "(", "nodes", "[", "index", "..", "-", "1", "]", ",", "rule", ":", "@rule", ")", ")", ".", "valid?", "break", "song", "end", "end", "end" ]
Find one valid song from given text. @return [Ikku::Song]
[ "Find", "one", "valid", "song", "from", "given", "text", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L12-L19
24,495
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.judge
def judge(text) Song.new(parser.parse(text), exactly: true, rule: @rule).valid? end
ruby
def judge(text) Song.new(parser.parse(text), exactly: true, rule: @rule).valid? end
[ "def", "judge", "(", "text", ")", "Song", ".", "new", "(", "parser", ".", "parse", "(", "text", ")", ",", "exactly", ":", "true", ",", "rule", ":", "@rule", ")", ".", "valid?", "end" ]
Judge if given text is valid song or not. @return [true, false]
[ "Judge", "if", "given", "text", "is", "valid", "song", "or", "not", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L23-L25
24,496
r7kamura/ikku
lib/ikku/reviewer.rb
Ikku.Reviewer.search
def search(text) nodes = parser.parse(text) nodes.length.times.map do |index| Song.new(nodes[index..-1], rule: @rule) end.select(&:valid?) end
ruby
def search(text) nodes = parser.parse(text) nodes.length.times.map do |index| Song.new(nodes[index..-1], rule: @rule) end.select(&:valid?) end
[ "def", "search", "(", "text", ")", "nodes", "=", "parser", ".", "parse", "(", "text", ")", "nodes", ".", "length", ".", "times", ".", "map", "do", "|", "index", "|", "Song", ".", "new", "(", "nodes", "[", "index", "..", "-", "1", "]", ",", "rule", ":", "@rule", ")", "end", ".", "select", "(", ":valid?", ")", "end" ]
Search all valid songs from given text. @return [Array<Array>]
[ "Search", "all", "valid", "songs", "from", "given", "text", "." ]
b1f8e51a25b485ec12c13f8650a1d8a1abc83e15
https://github.com/r7kamura/ikku/blob/b1f8e51a25b485ec12c13f8650a1d8a1abc83e15/lib/ikku/reviewer.rb#L29-L34
24,497
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.led_partitions
def led_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.leader == self mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
ruby
def led_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.leader == self mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
[ "def", "led_partitions", "result", ",", "mutex", "=", "[", "]", ",", "Mutex", ".", "new", "threads", "=", "cluster", ".", "partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "select", "=", "partition", ".", "leader", "==", "self", "mutex", ".", "synchronize", "{", "result", "<<", "partition", "}", "if", "select", "end", "end", "threads", ".", "each", "(", ":join", ")", "result", "end" ]
Returns a list of all partitions that are currently led by this broker.
[ "Returns", "a", "list", "of", "all", "partitions", "that", "are", "currently", "led", "by", "this", "broker", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L14-L25
24,498
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.replicated_partitions
def replicated_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.replicas.include?(self) mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
ruby
def replicated_partitions result, mutex = [], Mutex.new threads = cluster.partitions.map do |partition| Thread.new do Thread.abort_on_exception = true select = partition.replicas.include?(self) mutex.synchronize { result << partition } if select end end threads.each(&:join) result end
[ "def", "replicated_partitions", "result", ",", "mutex", "=", "[", "]", ",", "Mutex", ".", "new", "threads", "=", "cluster", ".", "partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "select", "=", "partition", ".", "replicas", ".", "include?", "(", "self", ")", "mutex", ".", "synchronize", "{", "result", "<<", "partition", "}", "if", "select", "end", "end", "threads", ".", "each", "(", ":join", ")", "result", "end" ]
Returns a list of all partitions that host a replica on this broker.
[ "Returns", "a", "list", "of", "all", "partitions", "that", "host", "a", "replica", "on", "this", "broker", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L28-L39
24,499
wvanbergen/kazoo
lib/kazoo/broker.rb
Kazoo.Broker.critical?
def critical?(replicas: 1) result, mutex = false, Mutex.new threads = replicated_partitions.map do |partition| Thread.new do Thread.abort_on_exception = true isr = partition.isr.reject { |r| r == self } mutex.synchronize { result = true if isr.length < Integer(replicas) } end end threads.each(&:join) result end
ruby
def critical?(replicas: 1) result, mutex = false, Mutex.new threads = replicated_partitions.map do |partition| Thread.new do Thread.abort_on_exception = true isr = partition.isr.reject { |r| r == self } mutex.synchronize { result = true if isr.length < Integer(replicas) } end end threads.each(&:join) result end
[ "def", "critical?", "(", "replicas", ":", "1", ")", "result", ",", "mutex", "=", "false", ",", "Mutex", ".", "new", "threads", "=", "replicated_partitions", ".", "map", "do", "|", "partition", "|", "Thread", ".", "new", "do", "Thread", ".", "abort_on_exception", "=", "true", "isr", "=", "partition", ".", "isr", ".", "reject", "{", "|", "r", "|", "r", "==", "self", "}", "mutex", ".", "synchronize", "{", "result", "=", "true", "if", "isr", ".", "length", "<", "Integer", "(", "replicas", ")", "}", "end", "end", "threads", ".", "each", "(", ":join", ")", "result", "end" ]
Returns whether this broker is currently considered critical. A broker is considered critical if it is the only in sync replica of any of the partitions it hosts. This means that if this broker were to go down, the partition woild become unavailable for writes, and may also lose data depending on the configuration and settings.
[ "Returns", "whether", "this", "broker", "is", "currently", "considered", "critical", "." ]
54a73612ef4b815fad37ba660eb47353e26165f1
https://github.com/wvanbergen/kazoo/blob/54a73612ef4b815fad37ba660eb47353e26165f1/lib/kazoo/broker.rb#L47-L58