repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
bronto/foreman_hooks-host_rename
|
lib/foreman_hooks/host_rename.rb
|
ForemanHook.HostRename.parse_config
|
def parse_config(conffile = nil)
conffile ||= Dir.glob([
"/etc/foreman_hooks-host_rename/settings.yaml",
"#{confdir}/settings.yaml"])[0]
raise "Could not locate the configuration file" if conffile.nil?
# Parse the configuration file
config = {
hook_user: 'foreman',
database_path: '/var/tmp/foreman_hooks-host_rename.db',
log_path: '/var/tmp/foreman_hooks-host_rename.log',
log_level: 'warn',
rename_hook_command: '/bin/true',
}.merge(symbolize(YAML.load(File.read(conffile))))
config.each do |k,v|
instance_variable_set("@#{k}",v)
end
# Validate the schema
document = Kwalify::Yaml.load_file(conffile)
schema = Kwalify::Yaml.load_file("#{confdir}/schema.yaml")
validator = Kwalify::Validator.new(schema)
errors = validator.validate(document)
if errors && !errors.empty?
puts "WARNING: The following errors were found in #{conffile}:"
for e in errors
puts "[#{e.path}] #{e.message}"
end
raise "Errors in the configuration file"
end
check_script @rename_hook_command
end
|
ruby
|
def parse_config(conffile = nil)
conffile ||= Dir.glob([
"/etc/foreman_hooks-host_rename/settings.yaml",
"#{confdir}/settings.yaml"])[0]
raise "Could not locate the configuration file" if conffile.nil?
# Parse the configuration file
config = {
hook_user: 'foreman',
database_path: '/var/tmp/foreman_hooks-host_rename.db',
log_path: '/var/tmp/foreman_hooks-host_rename.log',
log_level: 'warn',
rename_hook_command: '/bin/true',
}.merge(symbolize(YAML.load(File.read(conffile))))
config.each do |k,v|
instance_variable_set("@#{k}",v)
end
# Validate the schema
document = Kwalify::Yaml.load_file(conffile)
schema = Kwalify::Yaml.load_file("#{confdir}/schema.yaml")
validator = Kwalify::Validator.new(schema)
errors = validator.validate(document)
if errors && !errors.empty?
puts "WARNING: The following errors were found in #{conffile}:"
for e in errors
puts "[#{e.path}] #{e.message}"
end
raise "Errors in the configuration file"
end
check_script @rename_hook_command
end
|
[
"def",
"parse_config",
"(",
"conffile",
"=",
"nil",
")",
"conffile",
"||=",
"Dir",
".",
"glob",
"(",
"[",
"\"/etc/foreman_hooks-host_rename/settings.yaml\"",
",",
"\"#{confdir}/settings.yaml\"",
"]",
")",
"[",
"0",
"]",
"raise",
"\"Could not locate the configuration file\"",
"if",
"conffile",
".",
"nil?",
"config",
"=",
"{",
"hook_user",
":",
"'foreman'",
",",
"database_path",
":",
"'/var/tmp/foreman_hooks-host_rename.db'",
",",
"log_path",
":",
"'/var/tmp/foreman_hooks-host_rename.log'",
",",
"log_level",
":",
"'warn'",
",",
"rename_hook_command",
":",
"'/bin/true'",
",",
"}",
".",
"merge",
"(",
"symbolize",
"(",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"conffile",
")",
")",
")",
")",
"config",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"v",
")",
"end",
"document",
"=",
"Kwalify",
"::",
"Yaml",
".",
"load_file",
"(",
"conffile",
")",
"schema",
"=",
"Kwalify",
"::",
"Yaml",
".",
"load_file",
"(",
"\"#{confdir}/schema.yaml\"",
")",
"validator",
"=",
"Kwalify",
"::",
"Validator",
".",
"new",
"(",
"schema",
")",
"errors",
"=",
"validator",
".",
"validate",
"(",
"document",
")",
"if",
"errors",
"&&",
"!",
"errors",
".",
"empty?",
"puts",
"\"WARNING: The following errors were found in #{conffile}:\"",
"for",
"e",
"in",
"errors",
"puts",
"\"[#{e.path}] #{e.message}\"",
"end",
"raise",
"\"Errors in the configuration file\"",
"end",
"check_script",
"@rename_hook_command",
"end"
] |
Parse the configuration file
|
[
"Parse",
"the",
"configuration",
"file"
] |
b80b398e7f881efe0b97492d23979899d475d33d
|
https://github.com/bronto/foreman_hooks-host_rename/blob/b80b398e7f881efe0b97492d23979899d475d33d/lib/foreman_hooks/host_rename.rb#L44-L76
|
valid
|
bronto/foreman_hooks-host_rename
|
lib/foreman_hooks/host_rename.rb
|
ForemanHook.HostRename.check_script
|
def check_script(path)
binary=path.split(' ')[0]
raise "#{path} does not exist" unless File.exist? binary
raise "#{path} is not executable" unless File.executable? binary
path
end
|
ruby
|
def check_script(path)
binary=path.split(' ')[0]
raise "#{path} does not exist" unless File.exist? binary
raise "#{path} is not executable" unless File.executable? binary
path
end
|
[
"def",
"check_script",
"(",
"path",
")",
"binary",
"=",
"path",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"raise",
"\"#{path} does not exist\"",
"unless",
"File",
".",
"exist?",
"binary",
"raise",
"\"#{path} is not executable\"",
"unless",
"File",
".",
"executable?",
"binary",
"path",
"end"
] |
Do additional sanity checking on a hook script
|
[
"Do",
"additional",
"sanity",
"checking",
"on",
"a",
"hook",
"script"
] |
b80b398e7f881efe0b97492d23979899d475d33d
|
https://github.com/bronto/foreman_hooks-host_rename/blob/b80b398e7f881efe0b97492d23979899d475d33d/lib/foreman_hooks/host_rename.rb#L85-L90
|
valid
|
bronto/foreman_hooks-host_rename
|
lib/foreman_hooks/host_rename.rb
|
ForemanHook.HostRename.sync_host_table
|
def sync_host_table
uri = foreman_uri('/hosts?per_page=9999999')
debug "Loading hosts from #{uri}"
json = RestClient.get uri
debug "Got JSON: #{json}"
JSON.parse(json)['results'].each do |rec|
@db.execute "insert into host (id,name) values ( ?, ? )",
rec['id'], rec['name']
end
end
|
ruby
|
def sync_host_table
uri = foreman_uri('/hosts?per_page=9999999')
debug "Loading hosts from #{uri}"
json = RestClient.get uri
debug "Got JSON: #{json}"
JSON.parse(json)['results'].each do |rec|
@db.execute "insert into host (id,name) values ( ?, ? )",
rec['id'], rec['name']
end
end
|
[
"def",
"sync_host_table",
"uri",
"=",
"foreman_uri",
"(",
"'/hosts?per_page=9999999'",
")",
"debug",
"\"Loading hosts from #{uri}\"",
"json",
"=",
"RestClient",
".",
"get",
"uri",
"debug",
"\"Got JSON: #{json}\"",
"JSON",
".",
"parse",
"(",
"json",
")",
"[",
"'results'",
"]",
".",
"each",
"do",
"|",
"rec",
"|",
"@db",
".",
"execute",
"\"insert into host (id,name) values ( ?, ? )\"",
",",
"rec",
"[",
"'id'",
"]",
",",
"rec",
"[",
"'name'",
"]",
"end",
"end"
] |
Get all the host IDs and FQDNs and populate the host table
|
[
"Get",
"all",
"the",
"host",
"IDs",
"and",
"FQDNs",
"and",
"populate",
"the",
"host",
"table"
] |
b80b398e7f881efe0b97492d23979899d475d33d
|
https://github.com/bronto/foreman_hooks-host_rename/blob/b80b398e7f881efe0b97492d23979899d475d33d/lib/foreman_hooks/host_rename.rb#L100-L109
|
valid
|
bronto/foreman_hooks-host_rename
|
lib/foreman_hooks/host_rename.rb
|
ForemanHook.HostRename.initialize_database
|
def initialize_database
@db = SQLite3::Database.new @database_path
File.chmod 0600, @database_path
begin
@db.execute 'drop table if exists host;'
@db.execute <<-SQL
create table host (
id INT,
name varchar(254)
);
SQL
sync_host_table
rescue
File.unlink @database_path
raise
end
end
|
ruby
|
def initialize_database
@db = SQLite3::Database.new @database_path
File.chmod 0600, @database_path
begin
@db.execute 'drop table if exists host;'
@db.execute <<-SQL
create table host (
id INT,
name varchar(254)
);
SQL
sync_host_table
rescue
File.unlink @database_path
raise
end
end
|
[
"def",
"initialize_database",
"@db",
"=",
"SQLite3",
"::",
"Database",
".",
"new",
"@database_path",
"File",
".",
"chmod",
"0600",
",",
"@database_path",
"begin",
"@db",
".",
"execute",
"'drop table if exists host;'",
"@db",
".",
"execute",
"<<-SQL",
"SQL",
"sync_host_table",
"rescue",
"File",
".",
"unlink",
"@database_path",
"raise",
"end",
"end"
] |
Initialize an empty database
|
[
"Initialize",
"an",
"empty",
"database"
] |
b80b398e7f881efe0b97492d23979899d475d33d
|
https://github.com/bronto/foreman_hooks-host_rename/blob/b80b398e7f881efe0b97492d23979899d475d33d/lib/foreman_hooks/host_rename.rb#L112-L128
|
valid
|
bronto/foreman_hooks-host_rename
|
lib/foreman_hooks/host_rename.rb
|
ForemanHook.HostRename.execute_hook_action
|
def execute_hook_action
@rename = false
name = @rec['host']['name']
id = @rec['host']['id']
case @action
when 'create'
sql = "insert into host (id, name) values (?, ?)"
params = [id, name]
when 'update'
# Check if we are renaming the host
@old_name = @db.get_first_row('select name from host where id = ?', id)
@old_name = @old_name[0] unless @old_name.nil?
if @old_name.nil?
warn 'received an update for a non-existent host'
else
@rename = @old_name != name
end
debug "checking for a rename: old=#{@old_name} new=#{name} rename?=#{@rename}"
sql = 'update host set name = ? where id = ?'
params = [name, id]
when 'destroy'
sql = 'delete from host where id = ?'
params = [id]
else
raise ArgumentError, "unsupported action: #{ARGV[0]}"
end
debug "updating database; id=#{id} name=#{name} sql=#{sql}"
stm = @db.prepare sql
stm.bind_params *params
stm.execute
end
|
ruby
|
def execute_hook_action
@rename = false
name = @rec['host']['name']
id = @rec['host']['id']
case @action
when 'create'
sql = "insert into host (id, name) values (?, ?)"
params = [id, name]
when 'update'
# Check if we are renaming the host
@old_name = @db.get_first_row('select name from host where id = ?', id)
@old_name = @old_name[0] unless @old_name.nil?
if @old_name.nil?
warn 'received an update for a non-existent host'
else
@rename = @old_name != name
end
debug "checking for a rename: old=#{@old_name} new=#{name} rename?=#{@rename}"
sql = 'update host set name = ? where id = ?'
params = [name, id]
when 'destroy'
sql = 'delete from host where id = ?'
params = [id]
else
raise ArgumentError, "unsupported action: #{ARGV[0]}"
end
debug "updating database; id=#{id} name=#{name} sql=#{sql}"
stm = @db.prepare sql
stm.bind_params *params
stm.execute
end
|
[
"def",
"execute_hook_action",
"@rename",
"=",
"false",
"name",
"=",
"@rec",
"[",
"'host'",
"]",
"[",
"'name'",
"]",
"id",
"=",
"@rec",
"[",
"'host'",
"]",
"[",
"'id'",
"]",
"case",
"@action",
"when",
"'create'",
"sql",
"=",
"\"insert into host (id, name) values (?, ?)\"",
"params",
"=",
"[",
"id",
",",
"name",
"]",
"when",
"'update'",
"@old_name",
"=",
"@db",
".",
"get_first_row",
"(",
"'select name from host where id = ?'",
",",
"id",
")",
"@old_name",
"=",
"@old_name",
"[",
"0",
"]",
"unless",
"@old_name",
".",
"nil?",
"if",
"@old_name",
".",
"nil?",
"warn",
"'received an update for a non-existent host'",
"else",
"@rename",
"=",
"@old_name",
"!=",
"name",
"end",
"debug",
"\"checking for a rename: old=#{@old_name} new=#{name} rename?=#{@rename}\"",
"sql",
"=",
"'update host set name = ? where id = ?'",
"params",
"=",
"[",
"name",
",",
"id",
"]",
"when",
"'destroy'",
"sql",
"=",
"'delete from host where id = ?'",
"params",
"=",
"[",
"id",
"]",
"else",
"raise",
"ArgumentError",
",",
"\"unsupported action: #{ARGV[0]}\"",
"end",
"debug",
"\"updating database; id=#{id} name=#{name} sql=#{sql}\"",
"stm",
"=",
"@db",
".",
"prepare",
"sql",
"stm",
".",
"bind_params",
"*",
"params",
"stm",
".",
"execute",
"end"
] |
Update the database based on the foreman_hook
|
[
"Update",
"the",
"database",
"based",
"on",
"the",
"foreman_hook"
] |
b80b398e7f881efe0b97492d23979899d475d33d
|
https://github.com/bronto/foreman_hooks-host_rename/blob/b80b398e7f881efe0b97492d23979899d475d33d/lib/foreman_hooks/host_rename.rb#L141-L173
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.read_list
|
def read_list(name)
opts = self.class.persisted_attrs[name]
if !lists[name] && opts[:default]
opts[:default]
else
send("#{name}=", lists[name].value) if lists[name].is_a?(Redis::Future)
lists[name]
end
end
|
ruby
|
def read_list(name)
opts = self.class.persisted_attrs[name]
if !lists[name] && opts[:default]
opts[:default]
else
send("#{name}=", lists[name].value) if lists[name].is_a?(Redis::Future)
lists[name]
end
end
|
[
"def",
"read_list",
"(",
"name",
")",
"opts",
"=",
"self",
".",
"class",
".",
"persisted_attrs",
"[",
"name",
"]",
"if",
"!",
"lists",
"[",
"name",
"]",
"&&",
"opts",
"[",
":default",
"]",
"opts",
"[",
":default",
"]",
"else",
"send",
"(",
"\"#{name}=\"",
",",
"lists",
"[",
"name",
"]",
".",
"value",
")",
"if",
"lists",
"[",
"name",
"]",
".",
"is_a?",
"(",
"Redis",
"::",
"Future",
")",
"lists",
"[",
"name",
"]",
"end",
"end"
] |
Transform and read a list attribute
|
[
"Transform",
"and",
"read",
"a",
"list",
"attribute"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L260-L269
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.read_hash
|
def read_hash(name)
opts = self.class.persisted_attrs[name]
if !hashes[name] && opts[:default]
opts[:default]
else
self.send("#{name}=", hashes[name].value) if hashes[name].is_a?(Redis::Future)
hashes[name]
end
end
|
ruby
|
def read_hash(name)
opts = self.class.persisted_attrs[name]
if !hashes[name] && opts[:default]
opts[:default]
else
self.send("#{name}=", hashes[name].value) if hashes[name].is_a?(Redis::Future)
hashes[name]
end
end
|
[
"def",
"read_hash",
"(",
"name",
")",
"opts",
"=",
"self",
".",
"class",
".",
"persisted_attrs",
"[",
"name",
"]",
"if",
"!",
"hashes",
"[",
"name",
"]",
"&&",
"opts",
"[",
":default",
"]",
"opts",
"[",
":default",
"]",
"else",
"self",
".",
"send",
"(",
"\"#{name}=\"",
",",
"hashes",
"[",
"name",
"]",
".",
"value",
")",
"if",
"hashes",
"[",
"name",
"]",
".",
"is_a?",
"(",
"Redis",
"::",
"Future",
")",
"hashes",
"[",
"name",
"]",
"end",
"end"
] |
Transform and read a hash attribute
|
[
"Transform",
"and",
"read",
"a",
"hash",
"attribute"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L272-L281
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.write_attribute
|
def write_attribute(name, val)
if attributes.is_a?(Redis::Future)
value = attributes.value
self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten] : {}
end
attributes[name] = self.class.transform(:to, name, val)
end
|
ruby
|
def write_attribute(name, val)
if attributes.is_a?(Redis::Future)
value = attributes.value
self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten] : {}
end
attributes[name] = self.class.transform(:to, name, val)
end
|
[
"def",
"write_attribute",
"(",
"name",
",",
"val",
")",
"if",
"attributes",
".",
"is_a?",
"(",
"Redis",
"::",
"Future",
")",
"value",
"=",
"attributes",
".",
"value",
"self",
".",
"attributes",
"=",
"value",
"?",
"Hash",
"[",
"*",
"self",
".",
"class",
".",
"fields",
".",
"keys",
".",
"zip",
"(",
"value",
")",
".",
"flatten",
"]",
":",
"{",
"}",
"end",
"attributes",
"[",
"name",
"]",
"=",
"self",
".",
"class",
".",
"transform",
"(",
":to",
",",
"name",
",",
"val",
")",
"end"
] |
Transform and write a standard attribute value
|
[
"Transform",
"and",
"write",
"a",
"standard",
"attribute",
"value"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L285-L292
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.write_list
|
def write_list(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Array" unless val.is_a?(Array)
lists[name] = val
end
|
ruby
|
def write_list(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Array" unless val.is_a?(Array)
lists[name] = val
end
|
[
"def",
"write_list",
"(",
"name",
",",
"val",
")",
"raise",
"\"RedisAssist: tried to store a #{val.class.name} as Array\"",
"unless",
"val",
".",
"is_a?",
"(",
"Array",
")",
"lists",
"[",
"name",
"]",
"=",
"val",
"end"
] |
Transform and write a list value
|
[
"Transform",
"and",
"write",
"a",
"list",
"value"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L295-L298
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.write_hash
|
def write_hash(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Hash" unless val.is_a?(Hash)
hashes[name] = val
end
|
ruby
|
def write_hash(name, val)
raise "RedisAssist: tried to store a #{val.class.name} as Hash" unless val.is_a?(Hash)
hashes[name] = val
end
|
[
"def",
"write_hash",
"(",
"name",
",",
"val",
")",
"raise",
"\"RedisAssist: tried to store a #{val.class.name} as Hash\"",
"unless",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"hashes",
"[",
"name",
"]",
"=",
"val",
"end"
] |
Transform and write a hash attribute
|
[
"Transform",
"and",
"write",
"a",
"hash",
"attribute"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L301-L304
|
valid
|
bustle/redis_assist
|
lib/redis_assist/base.rb
|
RedisAssist.Base.update_columns
|
def update_columns(attrs)
redis.multi do
attrs.each do |attr, value|
if self.class.fields.has_key?(attr)
write_attribute(attr, value)
redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record?
end
if self.class.lists.has_key?(attr)
write_list(attr, value)
unless new_record?
redis.del(key_for(attr))
redis.rpush(key_for(attr), value) unless value.empty?
end
end
if self.class.hashes.has_key?(attr)
write_hash(attr, value)
unless new_record?
hash_as_args = hash_to_redis(value)
redis.hmset(key_for(attr), *hash_as_args)
end
end
end
end
end
|
ruby
|
def update_columns(attrs)
redis.multi do
attrs.each do |attr, value|
if self.class.fields.has_key?(attr)
write_attribute(attr, value)
redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record?
end
if self.class.lists.has_key?(attr)
write_list(attr, value)
unless new_record?
redis.del(key_for(attr))
redis.rpush(key_for(attr), value) unless value.empty?
end
end
if self.class.hashes.has_key?(attr)
write_hash(attr, value)
unless new_record?
hash_as_args = hash_to_redis(value)
redis.hmset(key_for(attr), *hash_as_args)
end
end
end
end
end
|
[
"def",
"update_columns",
"(",
"attrs",
")",
"redis",
".",
"multi",
"do",
"attrs",
".",
"each",
"do",
"|",
"attr",
",",
"value",
"|",
"if",
"self",
".",
"class",
".",
"fields",
".",
"has_key?",
"(",
"attr",
")",
"write_attribute",
"(",
"attr",
",",
"value",
")",
"redis",
".",
"hset",
"(",
"key_for",
"(",
":attributes",
")",
",",
"attr",
",",
"self",
".",
"class",
".",
"transform",
"(",
":to",
",",
"attr",
",",
"value",
")",
")",
"unless",
"new_record?",
"end",
"if",
"self",
".",
"class",
".",
"lists",
".",
"has_key?",
"(",
"attr",
")",
"write_list",
"(",
"attr",
",",
"value",
")",
"unless",
"new_record?",
"redis",
".",
"del",
"(",
"key_for",
"(",
"attr",
")",
")",
"redis",
".",
"rpush",
"(",
"key_for",
"(",
"attr",
")",
",",
"value",
")",
"unless",
"value",
".",
"empty?",
"end",
"end",
"if",
"self",
".",
"class",
".",
"hashes",
".",
"has_key?",
"(",
"attr",
")",
"write_hash",
"(",
"attr",
",",
"value",
")",
"unless",
"new_record?",
"hash_as_args",
"=",
"hash_to_redis",
"(",
"value",
")",
"redis",
".",
"hmset",
"(",
"key_for",
"(",
"attr",
")",
",",
"*",
"hash_as_args",
")",
"end",
"end",
"end",
"end",
"end"
] |
Update fields without hitting the callbacks
|
[
"Update",
"fields",
"without",
"hitting",
"the",
"callbacks"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/base.rb#L311-L338
|
valid
|
BlakeWilliams/Minican
|
lib/minican/controller_additions.rb
|
Minican.ControllerAdditions.filter_authorized!
|
def filter_authorized!(method, objects, user = current_user)
object_array = Array(objects)
object_array.select do |object|
policy = policy_for(object)
policy.can?(method, user)
end
end
|
ruby
|
def filter_authorized!(method, objects, user = current_user)
object_array = Array(objects)
object_array.select do |object|
policy = policy_for(object)
policy.can?(method, user)
end
end
|
[
"def",
"filter_authorized!",
"(",
"method",
",",
"objects",
",",
"user",
"=",
"current_user",
")",
"object_array",
"=",
"Array",
"(",
"objects",
")",
"object_array",
".",
"select",
"do",
"|",
"object",
"|",
"policy",
"=",
"policy_for",
"(",
"object",
")",
"policy",
".",
"can?",
"(",
"method",
",",
"user",
")",
"end",
"end"
] |
Controller helper method to filter out non-authorized
objects from the passed in array
@param method [Symbol] method to be called on each policy
@param objects [Array] array of objects to filter
@param user [User] The current user object to pass
@return (Array)
@visibility public
|
[
"Controller",
"helper",
"method",
"to",
"filter",
"out",
"non",
"-",
"authorized",
"objects",
"from",
"the",
"passed",
"in",
"array"
] |
fa8903f235a1471fa357af48070ba68c94a731a6
|
https://github.com/BlakeWilliams/Minican/blob/fa8903f235a1471fa357af48070ba68c94a731a6/lib/minican/controller_additions.rb#L33-L40
|
valid
|
BlakeWilliams/Minican
|
lib/minican/controller_additions.rb
|
Minican.ControllerAdditions.can?
|
def can?(method, object, user = current_user)
policy = policy_for(object)
policy.can?(method, user)
end
|
ruby
|
def can?(method, object, user = current_user)
policy = policy_for(object)
policy.can?(method, user)
end
|
[
"def",
"can?",
"(",
"method",
",",
"object",
",",
"user",
"=",
"current_user",
")",
"policy",
"=",
"policy_for",
"(",
"object",
")",
"policy",
".",
"can?",
"(",
"method",
",",
"user",
")",
"end"
] |
Helper method available in controllers and views
that returns the value of the policy method
@param (see #authorize!)
@return (Boolean)
@visibility public
|
[
"Helper",
"method",
"available",
"in",
"controllers",
"and",
"views",
"that",
"returns",
"the",
"value",
"of",
"the",
"policy",
"method"
] |
fa8903f235a1471fa357af48070ba68c94a731a6
|
https://github.com/BlakeWilliams/Minican/blob/fa8903f235a1471fa357af48070ba68c94a731a6/lib/minican/controller_additions.rb#L49-L52
|
valid
|
jorge-d/dogecoin
|
lib/doge_coin/client.rb
|
DogeCoin.Client.nethash
|
def nethash interval = 500, start = 0, stop = false
suffixe = stop ? "/#{stop}" : ''
JSON.parse(call_blockchain_api("nethash/#{interval}/#{start}#{suffixe}?format=json"))
end
|
ruby
|
def nethash interval = 500, start = 0, stop = false
suffixe = stop ? "/#{stop}" : ''
JSON.parse(call_blockchain_api("nethash/#{interval}/#{start}#{suffixe}?format=json"))
end
|
[
"def",
"nethash",
"interval",
"=",
"500",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"false",
"suffixe",
"=",
"stop",
"?",
"\"/#{stop}\"",
":",
"''",
"JSON",
".",
"parse",
"(",
"call_blockchain_api",
"(",
"\"nethash/#{interval}/#{start}#{suffixe}?format=json\"",
")",
")",
"end"
] |
shows statistics about difficulty and network power
/nethash/INTERVAL/START/STOP
Default INTERVAL=500, START=0, STOP=infinity.
See http://dogechain.info/chain/Dogecoin/q/nethash
|
[
"shows",
"statistics",
"about",
"difficulty",
"and",
"network",
"power"
] |
320c68d1ce6181aa60c86003b185b99fbb856b47
|
https://github.com/jorge-d/dogecoin/blob/320c68d1ce6181aa60c86003b185b99fbb856b47/lib/doge_coin/client.rb#L44-L47
|
valid
|
bustle/redis_assist
|
lib/redis_assist/finders.rb
|
RedisAssist.Finders.last
|
def last(limit=1, offset=0)
from = offset
to = from + limit - 1
members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from * -1) + -1).reverse
find(limit > 1 ? members : members.first)
end
|
ruby
|
def last(limit=1, offset=0)
from = offset
to = from + limit - 1
members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from * -1) + -1).reverse
find(limit > 1 ? members : members.first)
end
|
[
"def",
"last",
"(",
"limit",
"=",
"1",
",",
"offset",
"=",
"0",
")",
"from",
"=",
"offset",
"to",
"=",
"from",
"+",
"limit",
"-",
"1",
"members",
"=",
"redis",
".",
"zrange",
"(",
"index_key_for",
"(",
":id",
")",
",",
"(",
"to",
"*",
"-",
"1",
")",
"+",
"-",
"1",
",",
"(",
"from",
"*",
"-",
"1",
")",
"+",
"-",
"1",
")",
".",
"reverse",
"find",
"(",
"limit",
">",
"1",
"?",
"members",
":",
"members",
".",
"first",
")",
"end"
] |
Find the first saved record
@note `last` uses a sorted set as an index of `ids` and finds the highest id.
@param limit [Integer] returns one or many
@param offset [Integer] from the end of the index, back
@return [Base, Array]
|
[
"Find",
"the",
"first",
"saved",
"record"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/finders.rb#L39-L45
|
valid
|
bustle/redis_assist
|
lib/redis_assist/finders.rb
|
RedisAssist.Finders.find
|
def find(ids, opts={})
ids.is_a?(Array) ? find_by_ids(ids, opts) : find_by_id(ids, opts)
end
|
ruby
|
def find(ids, opts={})
ids.is_a?(Array) ? find_by_ids(ids, opts) : find_by_id(ids, opts)
end
|
[
"def",
"find",
"(",
"ids",
",",
"opts",
"=",
"{",
"}",
")",
"ids",
".",
"is_a?",
"(",
"Array",
")",
"?",
"find_by_ids",
"(",
"ids",
",",
"opts",
")",
":",
"find_by_id",
"(",
"ids",
",",
"opts",
")",
"end"
] |
Find a record by `id`
@param ids [Integer, Array<Integer>] of the record(s) to lookup.
@return [Base, Array] matching records
|
[
"Find",
"a",
"record",
"by",
"id"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/finders.rb#L50-L52
|
valid
|
bustle/redis_assist
|
lib/redis_assist/finders.rb
|
RedisAssist.Finders.find_in_batches
|
def find_in_batches(options={})
start = options[:start] || 0
marker = start
batch_size = options[:batch_size] || 500
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
while record_ids.length > 0
records_count = record_ids.length
marker += records_count
records = find(record_ids)
yield records
break if records_count < batch_size
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
end
end
|
ruby
|
def find_in_batches(options={})
start = options[:start] || 0
marker = start
batch_size = options[:batch_size] || 500
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
while record_ids.length > 0
records_count = record_ids.length
marker += records_count
records = find(record_ids)
yield records
break if records_count < batch_size
record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1)
end
end
|
[
"def",
"find_in_batches",
"(",
"options",
"=",
"{",
"}",
")",
"start",
"=",
"options",
"[",
":start",
"]",
"||",
"0",
"marker",
"=",
"start",
"batch_size",
"=",
"options",
"[",
":batch_size",
"]",
"||",
"500",
"record_ids",
"=",
"redis",
".",
"zrange",
"(",
"index_key_for",
"(",
":id",
")",
",",
"marker",
",",
"marker",
"+",
"batch_size",
"-",
"1",
")",
"while",
"record_ids",
".",
"length",
">",
"0",
"records_count",
"=",
"record_ids",
".",
"length",
"marker",
"+=",
"records_count",
"records",
"=",
"find",
"(",
"record_ids",
")",
"yield",
"records",
"break",
"if",
"records_count",
"<",
"batch_size",
"record_ids",
"=",
"redis",
".",
"zrange",
"(",
"index_key_for",
"(",
":id",
")",
",",
"marker",
",",
"marker",
"+",
"batch_size",
"-",
"1",
")",
"end",
"end"
] |
Iterate over all records in batches
@param options [Hash] accepts options
`:start` to offset from the beginning of index,
`:batch_size` the size of the batch, default is 500.
@param &block [Proc] passes each batch of articles to the Proc.
|
[
"Iterate",
"over",
"all",
"records",
"in",
"batches"
] |
a10232e72fcf520982cb4b7e8da890b63db86313
|
https://github.com/bustle/redis_assist/blob/a10232e72fcf520982cb4b7e8da890b63db86313/lib/redis_assist/finders.rb#L82-L99
|
valid
|
mlins/active_migration
|
lib/active_migration/key_mapper.rb
|
ActiveMigration.KeyMapper.load_keymap
|
def load_keymap(map) #:nodoc:
@maps ||= Hash.new
if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml"))
@maps[map] = YAML.load(File.open(File.join(self.storage_path, map.to_s + "_map.yml")))
logger.debug("#{self.class.to_s} lazy loaded #{map} successfully.")
end
end
|
ruby
|
def load_keymap(map) #:nodoc:
@maps ||= Hash.new
if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml"))
@maps[map] = YAML.load(File.open(File.join(self.storage_path, map.to_s + "_map.yml")))
logger.debug("#{self.class.to_s} lazy loaded #{map} successfully.")
end
end
|
[
"def",
"load_keymap",
"(",
"map",
")",
"@maps",
"||=",
"Hash",
".",
"new",
"if",
"@maps",
"[",
"map",
"]",
".",
"nil?",
"&&",
"File",
".",
"file?",
"(",
"File",
".",
"join",
"(",
"self",
".",
"storage_path",
",",
"map",
".",
"to_s",
"+",
"\"_map.yml\"",
")",
")",
"@maps",
"[",
"map",
"]",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"open",
"(",
"File",
".",
"join",
"(",
"self",
".",
"storage_path",
",",
"map",
".",
"to_s",
"+",
"\"_map.yml\"",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"#{self.class.to_s} lazy loaded #{map} successfully.\"",
")",
"end",
"end"
] |
Lazy loader...
|
[
"Lazy",
"loader",
"..."
] |
0a24d700d1b750c97fb00f3cf185848c32993eba
|
https://github.com/mlins/active_migration/blob/0a24d700d1b750c97fb00f3cf185848c32993eba/lib/active_migration/key_mapper.rb#L90-L96
|
valid
|
mlins/active_migration
|
lib/active_migration/key_mapper.rb
|
ActiveMigration.KeyMapper.mapped_key
|
def mapped_key(map, key)
load_keymap(map.to_s)
@maps[map.to_s][handle_composite(key)]
end
|
ruby
|
def mapped_key(map, key)
load_keymap(map.to_s)
@maps[map.to_s][handle_composite(key)]
end
|
[
"def",
"mapped_key",
"(",
"map",
",",
"key",
")",
"load_keymap",
"(",
"map",
".",
"to_s",
")",
"@maps",
"[",
"map",
".",
"to_s",
"]",
"[",
"handle_composite",
"(",
"key",
")",
"]",
"end"
] |
Returns the deserialized mapped key when provided with the former key.
mapped_key(:products, 2)
|
[
"Returns",
"the",
"deserialized",
"mapped",
"key",
"when",
"provided",
"with",
"the",
"former",
"key",
"."
] |
0a24d700d1b750c97fb00f3cf185848c32993eba
|
https://github.com/mlins/active_migration/blob/0a24d700d1b750c97fb00f3cf185848c32993eba/lib/active_migration/key_mapper.rb#L102-L105
|
valid
|
kingsleyh/totally_lazy
|
lib/parallel/processor_count.rb
|
Parallel.ProcessorCount.processor_count
|
def processor_count
@processor_count ||= begin
os_name = RbConfig::CONFIG["target_os"]
if os_name =~ /mingw|mswin/
require 'win32ole'
result = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfLogicalProcessors from Win32_Processor")
result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
elsif File.readable?("/proc/cpuinfo")
IO.read("/proc/cpuinfo").scan(/^processor/).size
elsif File.executable?("/usr/bin/hwprefs")
IO.popen("/usr/bin/hwprefs thread_count").read.to_i
elsif File.executable?("/usr/sbin/psrinfo")
IO.popen("/usr/sbin/psrinfo").read.scan(/^.*on-*line/).size
elsif File.executable?("/usr/sbin/ioscan")
IO.popen("/usr/sbin/ioscan -kC processor") do |out|
out.read.scan(/^.*processor/).size
end
elsif File.executable?("/usr/sbin/pmcycles")
IO.popen("/usr/sbin/pmcycles -m").read.count("\n")
elsif File.executable?("/usr/sbin/lsdev")
IO.popen("/usr/sbin/lsdev -Cc processor -S 1").read.count("\n")
elsif File.executable?("/usr/sbin/sysconf") and os_name =~ /irix/i
IO.popen("/usr/sbin/sysconf NPROC_ONLN").read.to_i
elsif File.executable?("/usr/sbin/sysctl")
IO.popen("/usr/sbin/sysctl -n hw.ncpu").read.to_i
elsif File.executable?("/sbin/sysctl")
IO.popen("/sbin/sysctl -n hw.ncpu").read.to_i
else
$stderr.puts "Unknown platform: " + RbConfig::CONFIG["target_os"]
$stderr.puts "Assuming 1 processor."
1
end
end
end
|
ruby
|
def processor_count
@processor_count ||= begin
os_name = RbConfig::CONFIG["target_os"]
if os_name =~ /mingw|mswin/
require 'win32ole'
result = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfLogicalProcessors from Win32_Processor")
result.to_enum.collect(&:NumberOfLogicalProcessors).reduce(:+)
elsif File.readable?("/proc/cpuinfo")
IO.read("/proc/cpuinfo").scan(/^processor/).size
elsif File.executable?("/usr/bin/hwprefs")
IO.popen("/usr/bin/hwprefs thread_count").read.to_i
elsif File.executable?("/usr/sbin/psrinfo")
IO.popen("/usr/sbin/psrinfo").read.scan(/^.*on-*line/).size
elsif File.executable?("/usr/sbin/ioscan")
IO.popen("/usr/sbin/ioscan -kC processor") do |out|
out.read.scan(/^.*processor/).size
end
elsif File.executable?("/usr/sbin/pmcycles")
IO.popen("/usr/sbin/pmcycles -m").read.count("\n")
elsif File.executable?("/usr/sbin/lsdev")
IO.popen("/usr/sbin/lsdev -Cc processor -S 1").read.count("\n")
elsif File.executable?("/usr/sbin/sysconf") and os_name =~ /irix/i
IO.popen("/usr/sbin/sysconf NPROC_ONLN").read.to_i
elsif File.executable?("/usr/sbin/sysctl")
IO.popen("/usr/sbin/sysctl -n hw.ncpu").read.to_i
elsif File.executable?("/sbin/sysctl")
IO.popen("/sbin/sysctl -n hw.ncpu").read.to_i
else
$stderr.puts "Unknown platform: " + RbConfig::CONFIG["target_os"]
$stderr.puts "Assuming 1 processor."
1
end
end
end
|
[
"def",
"processor_count",
"@processor_count",
"||=",
"begin",
"os_name",
"=",
"RbConfig",
"::",
"CONFIG",
"[",
"\"target_os\"",
"]",
"if",
"os_name",
"=~",
"/",
"/",
"require",
"'win32ole'",
"result",
"=",
"WIN32OLE",
".",
"connect",
"(",
"\"winmgmts://\"",
")",
".",
"ExecQuery",
"(",
"\"select NumberOfLogicalProcessors from Win32_Processor\"",
")",
"result",
".",
"to_enum",
".",
"collect",
"(",
"&",
":NumberOfLogicalProcessors",
")",
".",
"reduce",
"(",
":+",
")",
"elsif",
"File",
".",
"readable?",
"(",
"\"/proc/cpuinfo\"",
")",
"IO",
".",
"read",
"(",
"\"/proc/cpuinfo\"",
")",
".",
"scan",
"(",
"/",
"/",
")",
".",
"size",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/bin/hwprefs\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/bin/hwprefs thread_count\"",
")",
".",
"read",
".",
"to_i",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/psrinfo\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/psrinfo\"",
")",
".",
"read",
".",
"scan",
"(",
"/",
"/",
")",
".",
"size",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/ioscan\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/ioscan -kC processor\"",
")",
"do",
"|",
"out",
"|",
"out",
".",
"read",
".",
"scan",
"(",
"/",
"/",
")",
".",
"size",
"end",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/pmcycles\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/pmcycles -m\"",
")",
".",
"read",
".",
"count",
"(",
"\"\\n\"",
")",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/lsdev\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/lsdev -Cc processor -S 1\"",
")",
".",
"read",
".",
"count",
"(",
"\"\\n\"",
")",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/sysconf\"",
")",
"and",
"os_name",
"=~",
"/",
"/i",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/sysconf NPROC_ONLN\"",
")",
".",
"read",
".",
"to_i",
"elsif",
"File",
".",
"executable?",
"(",
"\"/usr/sbin/sysctl\"",
")",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/sysctl -n hw.ncpu\"",
")",
".",
"read",
".",
"to_i",
"elsif",
"File",
".",
"executable?",
"(",
"\"/sbin/sysctl\"",
")",
"IO",
".",
"popen",
"(",
"\"/sbin/sysctl -n hw.ncpu\"",
")",
".",
"read",
".",
"to_i",
"else",
"$stderr",
".",
"puts",
"\"Unknown platform: \"",
"+",
"RbConfig",
"::",
"CONFIG",
"[",
"\"target_os\"",
"]",
"$stderr",
".",
"puts",
"\"Assuming 1 processor.\"",
"1",
"end",
"end",
"end"
] |
Number of processors seen by the OS and used for process scheduling.
* AIX: /usr/sbin/pmcycles (AIX 5+), /usr/sbin/lsdev
* BSD: /sbin/sysctl
* Cygwin: /proc/cpuinfo
* Darwin: /usr/bin/hwprefs, /usr/sbin/sysctl
* HP-UX: /usr/sbin/ioscan
* IRIX: /usr/sbin/sysconf
* Linux: /proc/cpuinfo
* Minix 3+: /proc/cpuinfo
* Solaris: /usr/sbin/psrinfo
* Tru64 UNIX: /usr/sbin/psrinfo
* UnixWare: /usr/sbin/psrinfo
|
[
"Number",
"of",
"processors",
"seen",
"by",
"the",
"OS",
"and",
"used",
"for",
"process",
"scheduling",
"."
] |
716411121b15983a6c56f2e48dc22212aeea49fd
|
https://github.com/kingsleyh/totally_lazy/blob/716411121b15983a6c56f2e48dc22212aeea49fd/lib/parallel/processor_count.rb#L17-L51
|
valid
|
kingsleyh/totally_lazy
|
lib/parallel/processor_count.rb
|
Parallel.ProcessorCount.physical_processor_count
|
def physical_processor_count
@physical_processor_count ||= begin
ppc = case RbConfig::CONFIG["target_os"]
when /darwin1/
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
when /linux/
cores = {} # unique physical ID / core ID combinations
phy = 0
IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
if ln.start_with?("physical")
phy = ln[/\d+/]
elsif ln.start_with?("core")
cid = phy + ":" + ln[/\d+/]
cores[cid] = true if not cores[cid]
end
end
cores.count
when /mswin|mingw/
require 'win32ole'
result_set = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfCores from Win32_Processor")
result_set.to_enum.collect(&:NumberOfCores).reduce(:+)
else
processor_count
end
# fall back to logical count if physical info is invalid
ppc > 0 ? ppc : processor_count
end
end
|
ruby
|
def physical_processor_count
@physical_processor_count ||= begin
ppc = case RbConfig::CONFIG["target_os"]
when /darwin1/
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
when /linux/
cores = {} # unique physical ID / core ID combinations
phy = 0
IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
if ln.start_with?("physical")
phy = ln[/\d+/]
elsif ln.start_with?("core")
cid = phy + ":" + ln[/\d+/]
cores[cid] = true if not cores[cid]
end
end
cores.count
when /mswin|mingw/
require 'win32ole'
result_set = WIN32OLE.connect("winmgmts://").ExecQuery(
"select NumberOfCores from Win32_Processor")
result_set.to_enum.collect(&:NumberOfCores).reduce(:+)
else
processor_count
end
# fall back to logical count if physical info is invalid
ppc > 0 ? ppc : processor_count
end
end
|
[
"def",
"physical_processor_count",
"@physical_processor_count",
"||=",
"begin",
"ppc",
"=",
"case",
"RbConfig",
"::",
"CONFIG",
"[",
"\"target_os\"",
"]",
"when",
"/",
"/",
"IO",
".",
"popen",
"(",
"\"/usr/sbin/sysctl -n hw.physicalcpu\"",
")",
".",
"read",
".",
"to_i",
"when",
"/",
"/",
"cores",
"=",
"{",
"}",
"phy",
"=",
"0",
"IO",
".",
"read",
"(",
"\"/proc/cpuinfo\"",
")",
".",
"scan",
"(",
"/",
"/",
")",
"do",
"|",
"ln",
"|",
"if",
"ln",
".",
"start_with?",
"(",
"\"physical\"",
")",
"phy",
"=",
"ln",
"[",
"/",
"\\d",
"/",
"]",
"elsif",
"ln",
".",
"start_with?",
"(",
"\"core\"",
")",
"cid",
"=",
"phy",
"+",
"\":\"",
"+",
"ln",
"[",
"/",
"\\d",
"/",
"]",
"cores",
"[",
"cid",
"]",
"=",
"true",
"if",
"not",
"cores",
"[",
"cid",
"]",
"end",
"end",
"cores",
".",
"count",
"when",
"/",
"/",
"require",
"'win32ole'",
"result_set",
"=",
"WIN32OLE",
".",
"connect",
"(",
"\"winmgmts://\"",
")",
".",
"ExecQuery",
"(",
"\"select NumberOfCores from Win32_Processor\"",
")",
"result_set",
".",
"to_enum",
".",
"collect",
"(",
"&",
":NumberOfCores",
")",
".",
"reduce",
"(",
":+",
")",
"else",
"processor_count",
"end",
"ppc",
">",
"0",
"?",
"ppc",
":",
"processor_count",
"end",
"end"
] |
Number of physical processor cores on the current system.
|
[
"Number",
"of",
"physical",
"processor",
"cores",
"on",
"the",
"current",
"system",
"."
] |
716411121b15983a6c56f2e48dc22212aeea49fd
|
https://github.com/kingsleyh/totally_lazy/blob/716411121b15983a6c56f2e48dc22212aeea49fd/lib/parallel/processor_count.rb#L55-L83
|
valid
|
asceth/ruby_reportable
|
lib/ruby_reportable/report.rb
|
RubyReportable.Report.valid?
|
def valid?(options = {})
options = {:input => {}}.merge(options)
errors = []
# initial sandbox
sandbox = _source(options)
# add in inputs
sandbox[:inputs] = options[:input]
validity = @filters.map do |filter_name, filter|
# find input for given filter
sandbox[:input] = options[:input][filter[:key]] if options[:input].is_a?(Hash)
filter_validity = filter[:valid].nil? || sandbox.instance_eval(&filter[:valid])
if filter_validity == false
# Ignore an empty filter unless it's required
if !sandbox[:input].to_s.blank?
errors << "#{filter_name} is invalid."
false
else
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
end
elsif filter_validity == true
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
elsif !filter_validity.nil? && !filter_validity[:status].nil? && filter_validity[:status] == false
# Ignore an empty filter unless it's required or the error is forced.
if !sandbox[:input].to_s.blank? || filter_validity[:force_error] == true
errors << filter_validity[:errors]
false
else
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
end
end
end
return {:status => !validity.include?(false), :errors => errors}
end
|
ruby
|
def valid?(options = {})
options = {:input => {}}.merge(options)
errors = []
# initial sandbox
sandbox = _source(options)
# add in inputs
sandbox[:inputs] = options[:input]
validity = @filters.map do |filter_name, filter|
# find input for given filter
sandbox[:input] = options[:input][filter[:key]] if options[:input].is_a?(Hash)
filter_validity = filter[:valid].nil? || sandbox.instance_eval(&filter[:valid])
if filter_validity == false
# Ignore an empty filter unless it's required
if !sandbox[:input].to_s.blank?
errors << "#{filter_name} is invalid."
false
else
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
end
elsif filter_validity == true
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
elsif !filter_validity.nil? && !filter_validity[:status].nil? && filter_validity[:status] == false
# Ignore an empty filter unless it's required or the error is forced.
if !sandbox[:input].to_s.blank? || filter_validity[:force_error] == true
errors << filter_validity[:errors]
false
else
if sandbox[:input].to_s.blank? && !filter[:require].blank?
errors << "#{filter_name} is required."
false
else
true
end
end
end
end
return {:status => !validity.include?(false), :errors => errors}
end
|
[
"def",
"valid?",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":input",
"=>",
"{",
"}",
"}",
".",
"merge",
"(",
"options",
")",
"errors",
"=",
"[",
"]",
"sandbox",
"=",
"_source",
"(",
"options",
")",
"sandbox",
"[",
":inputs",
"]",
"=",
"options",
"[",
":input",
"]",
"validity",
"=",
"@filters",
".",
"map",
"do",
"|",
"filter_name",
",",
"filter",
"|",
"sandbox",
"[",
":input",
"]",
"=",
"options",
"[",
":input",
"]",
"[",
"filter",
"[",
":key",
"]",
"]",
"if",
"options",
"[",
":input",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"filter_validity",
"=",
"filter",
"[",
":valid",
"]",
".",
"nil?",
"||",
"sandbox",
".",
"instance_eval",
"(",
"&",
"filter",
"[",
":valid",
"]",
")",
"if",
"filter_validity",
"==",
"false",
"if",
"!",
"sandbox",
"[",
":input",
"]",
".",
"to_s",
".",
"blank?",
"errors",
"<<",
"\"#{filter_name} is invalid.\"",
"false",
"else",
"if",
"sandbox",
"[",
":input",
"]",
".",
"to_s",
".",
"blank?",
"&&",
"!",
"filter",
"[",
":require",
"]",
".",
"blank?",
"errors",
"<<",
"\"#{filter_name} is required.\"",
"false",
"else",
"true",
"end",
"end",
"elsif",
"filter_validity",
"==",
"true",
"if",
"sandbox",
"[",
":input",
"]",
".",
"to_s",
".",
"blank?",
"&&",
"!",
"filter",
"[",
":require",
"]",
".",
"blank?",
"errors",
"<<",
"\"#{filter_name} is required.\"",
"false",
"else",
"true",
"end",
"elsif",
"!",
"filter_validity",
".",
"nil?",
"&&",
"!",
"filter_validity",
"[",
":status",
"]",
".",
"nil?",
"&&",
"filter_validity",
"[",
":status",
"]",
"==",
"false",
"if",
"!",
"sandbox",
"[",
":input",
"]",
".",
"to_s",
".",
"blank?",
"||",
"filter_validity",
"[",
":force_error",
"]",
"==",
"true",
"errors",
"<<",
"filter_validity",
"[",
":errors",
"]",
"false",
"else",
"if",
"sandbox",
"[",
":input",
"]",
".",
"to_s",
".",
"blank?",
"&&",
"!",
"filter",
"[",
":require",
"]",
".",
"blank?",
"errors",
"<<",
"\"#{filter_name} is required.\"",
"false",
"else",
"true",
"end",
"end",
"end",
"end",
"return",
"{",
":status",
"=>",
"!",
"validity",
".",
"include?",
"(",
"false",
")",
",",
":errors",
"=>",
"errors",
"}",
"end"
] |
end def run
|
[
"end",
"def",
"run"
] |
07880afb9b2ee97f915d5afa3e42be1d9014c1eb
|
https://github.com/asceth/ruby_reportable/blob/07880afb9b2ee97f915d5afa3e42be1d9014c1eb/lib/ruby_reportable/report.rb#L275-L330
|
valid
|
tamouse/elapsed_watch
|
lib/elapsed_watch/event_collection.rb
|
ElapsedWatch.EventCollection.reload
|
def reload()
self.clear
self.concat File.read(event_file).split(/\r?\n/).map{|e| Event.new(e)}
end
|
ruby
|
def reload()
self.clear
self.concat File.read(event_file).split(/\r?\n/).map{|e| Event.new(e)}
end
|
[
"def",
"reload",
"(",
")",
"self",
".",
"clear",
"self",
".",
"concat",
"File",
".",
"read",
"(",
"event_file",
")",
".",
"split",
"(",
"/",
"\\r",
"\\n",
"/",
")",
".",
"map",
"{",
"|",
"e",
"|",
"Event",
".",
"new",
"(",
"e",
")",
"}",
"end"
] |
Reload the events from the event file. Existing events are
deleted first.
|
[
"Reload",
"the",
"events",
"from",
"the",
"event",
"file",
".",
"Existing",
"events",
"are",
"deleted",
"first",
"."
] |
fec9b3a49c0a0af33e26553d661037bcaeb180a5
|
https://github.com/tamouse/elapsed_watch/blob/fec9b3a49c0a0af33e26553d661037bcaeb180a5/lib/elapsed_watch/event_collection.rb#L39-L42
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/followable.rb
|
Mongoid.Followable.followee_of?
|
def followee_of?(model)
0 < self.followers.by_model(model).limit(1).count * model.followees.by_model(self).limit(1).count
end
|
ruby
|
def followee_of?(model)
0 < self.followers.by_model(model).limit(1).count * model.followees.by_model(self).limit(1).count
end
|
[
"def",
"followee_of?",
"(",
"model",
")",
"0",
"<",
"self",
".",
"followers",
".",
"by_model",
"(",
"model",
")",
".",
"limit",
"(",
"1",
")",
".",
"count",
"*",
"model",
".",
"followees",
".",
"by_model",
"(",
"self",
")",
".",
"limit",
"(",
"1",
")",
".",
"count",
"end"
] |
see if this model is followee of some model
Example:
>> @ruby.followee_of?(@jim)
=> true
|
[
"see",
"if",
"this",
"model",
"is",
"followee",
"of",
"some",
"model"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/followable.rb#L92-L94
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/followable.rb
|
Mongoid.Followable.ever_followed
|
def ever_followed
follow = []
self.followed_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end
|
ruby
|
def ever_followed
follow = []
self.followed_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end
|
[
"def",
"ever_followed",
"follow",
"=",
"[",
"]",
"self",
".",
"followed_history",
".",
"each",
"do",
"|",
"h",
"|",
"follow",
"<<",
"h",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
".",
"constantize",
".",
"find",
"(",
"h",
".",
"split",
"(",
"'_'",
")",
"[",
"1",
"]",
")",
"end",
"follow",
"end"
] |
see model's followed history
Example:
>> @ruby.ever_followed
=> [@jim]
|
[
"see",
"model",
"s",
"followed",
"history"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/followable.rb#L142-L148
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/condition_variable.rb
|
QuackConcurrency.ConditionVariable.wait
|
def wait(mutex, timeout = nil)
validate_mutex(mutex)
validate_timeout(timeout)
waitable = waitable_for_current_thread
@mutex.synchronize do
@waitables.push(waitable)
@waitables_to_resume.push(waitable)
end
waitable.wait(mutex, timeout)
self
end
|
ruby
|
def wait(mutex, timeout = nil)
validate_mutex(mutex)
validate_timeout(timeout)
waitable = waitable_for_current_thread
@mutex.synchronize do
@waitables.push(waitable)
@waitables_to_resume.push(waitable)
end
waitable.wait(mutex, timeout)
self
end
|
[
"def",
"wait",
"(",
"mutex",
",",
"timeout",
"=",
"nil",
")",
"validate_mutex",
"(",
"mutex",
")",
"validate_timeout",
"(",
"timeout",
")",
"waitable",
"=",
"waitable_for_current_thread",
"@mutex",
".",
"synchronize",
"do",
"@waitables",
".",
"push",
"(",
"waitable",
")",
"@waitables_to_resume",
".",
"push",
"(",
"waitable",
")",
"end",
"waitable",
".",
"wait",
"(",
"mutex",
",",
"timeout",
")",
"self",
"end"
] |
Puts this thread to sleep until another thread resumes it.
Threads will be woken in the chronological order that this was called.
@note Will block until resumed
@param mutex [Mutex] mutex to be unlocked while this thread is sleeping
@param timeout [nil,Numeric] maximum time to sleep in seconds, +nil+ for forever
@raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
@raise [ArgumentError] if +timeout+ is negative
@raise [Exception] any exception raised by +::ConditionVariable#wait+ (eg. interrupts, +ThreadError+)
@return [self]
|
[
"Puts",
"this",
"thread",
"to",
"sleep",
"until",
"another",
"thread",
"resumes",
"it",
".",
"Threads",
"will",
"be",
"woken",
"in",
"the",
"chronological",
"order",
"that",
"this",
"was",
"called",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/condition_variable.rb#L59-L69
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/condition_variable.rb
|
QuackConcurrency.ConditionVariable.validate_timeout
|
def validate_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
end
|
ruby
|
def validate_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
end
|
[
"def",
"validate_timeout",
"(",
"timeout",
")",
"unless",
"timeout",
"==",
"nil",
"raise",
"TypeError",
",",
"\"'timeout' must be nil or a Numeric\"",
"unless",
"timeout",
".",
"is_a?",
"(",
"Numeric",
")",
"raise",
"ArgumentError",
",",
"\"'timeout' must not be negative\"",
"if",
"timeout",
".",
"negative?",
"end",
"end"
] |
Validates a timeout value
@api private
@param timeout [nil,Numeric]
@raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
@raise [ArgumentError] if +timeout+ is negative
@return [void]
|
[
"Validates",
"a",
"timeout",
"value"
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/condition_variable.rb#L119-L124
|
valid
|
redding/deas-erubis
|
lib/deas-erubis.rb
|
Deas::Erubis.TemplateEngine.render
|
def render(template_name, view_handler, locals, &content)
self.erb_source.render(template_name, render_locals(view_handler, locals), &content)
end
|
ruby
|
def render(template_name, view_handler, locals, &content)
self.erb_source.render(template_name, render_locals(view_handler, locals), &content)
end
|
[
"def",
"render",
"(",
"template_name",
",",
"view_handler",
",",
"locals",
",",
"&",
"content",
")",
"self",
".",
"erb_source",
".",
"render",
"(",
"template_name",
",",
"render_locals",
"(",
"view_handler",
",",
"locals",
")",
",",
"&",
"content",
")",
"end"
] |
render the template including the handler as a local
|
[
"render",
"the",
"template",
"including",
"the",
"handler",
"as",
"a",
"local"
] |
05ff5c5dc2cb1e27606522ecb94d912397bf6190
|
https://github.com/redding/deas-erubis/blob/05ff5c5dc2cb1e27606522ecb94d912397bf6190/lib/deas-erubis.rb#L34-L36
|
valid
|
dmlond/spreadsheet_agent
|
lib/spreadsheet_agent/agent.rb
|
SpreadsheetAgent.Agent.run_entry
|
def run_entry
entry = get_entry()
output = '';
@keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key|
output += [ key, @keys[key] ].join(' ') + " "
end
unless entry
$stderr.puts "#{ output } is not supported on #{ @page_name }" if @debug
return
end
unless entry['ready'] == "1"
$stderr.puts "#{ output } is not ready to run #{ @agent_name }" if @debug
return false, entry
end
if entry['complete'] == "1"
$stderr.puts "All goals are completed for #{ output }" if @debug
return false, entry
end
if entry[@agent_name]
(status, running_hostname) = entry[@agent_name].split(':')
case status
when 'r'
$stderr.puts " #{ output } is already running #{ @agent_name } on #{ running_hostname }" if @debug
return false, entry
when "1"
$stderr.puts " #{ output } has already run #{ @agent_name }" if @debug
return false, entry
when 'F'
$stderr.puts " #{ output } has already Failed #{ @agent_name }" if @debug
return false, entry
end
end
if @prerequisites
@prerequisites.each do |prereq_field|
unless entry[prereq_field] == "1"
$stderr.puts " #{ output } has not finished #{ prereq_field }" if @debug
return false, entry
end
end
end
# first attempt to set the hostname of the machine as the value of the agent
hostname = Socket.gethostname;
begin
entry.update @agent_name => "r:#{ hostname }"
@worksheet.save
rescue GoogleDrive::Error
# this is a collision, which is to be treated as if it is not runnable
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
sleep 3
begin
@worksheet.reload
rescue GoogleDrive::Error
# this is a collision, which is to be treated as if it is not runnable
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
check = entry[@agent_name]
(status, running_hostname) = check.split(':')
if hostname == running_hostname
return true, entry
end
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
|
ruby
|
def run_entry
entry = get_entry()
output = '';
@keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key|
output += [ key, @keys[key] ].join(' ') + " "
end
unless entry
$stderr.puts "#{ output } is not supported on #{ @page_name }" if @debug
return
end
unless entry['ready'] == "1"
$stderr.puts "#{ output } is not ready to run #{ @agent_name }" if @debug
return false, entry
end
if entry['complete'] == "1"
$stderr.puts "All goals are completed for #{ output }" if @debug
return false, entry
end
if entry[@agent_name]
(status, running_hostname) = entry[@agent_name].split(':')
case status
when 'r'
$stderr.puts " #{ output } is already running #{ @agent_name } on #{ running_hostname }" if @debug
return false, entry
when "1"
$stderr.puts " #{ output } has already run #{ @agent_name }" if @debug
return false, entry
when 'F'
$stderr.puts " #{ output } has already Failed #{ @agent_name }" if @debug
return false, entry
end
end
if @prerequisites
@prerequisites.each do |prereq_field|
unless entry[prereq_field] == "1"
$stderr.puts " #{ output } has not finished #{ prereq_field }" if @debug
return false, entry
end
end
end
# first attempt to set the hostname of the machine as the value of the agent
hostname = Socket.gethostname;
begin
entry.update @agent_name => "r:#{ hostname }"
@worksheet.save
rescue GoogleDrive::Error
# this is a collision, which is to be treated as if it is not runnable
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
sleep 3
begin
@worksheet.reload
rescue GoogleDrive::Error
# this is a collision, which is to be treated as if it is not runnable
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
check = entry[@agent_name]
(status, running_hostname) = check.split(':')
if hostname == running_hostname
return true, entry
end
$stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug
return false, entry
end
|
[
"def",
"run_entry",
"entry",
"=",
"get_entry",
"(",
")",
"output",
"=",
"''",
";",
"@keys",
".",
"keys",
".",
"select",
"{",
"|",
"k",
"|",
"@config",
"[",
"'key_fields'",
"]",
"[",
"k",
"]",
"&&",
"@keys",
"[",
"k",
"]",
"}",
".",
"each",
"do",
"|",
"key",
"|",
"output",
"+=",
"[",
"key",
",",
"@keys",
"[",
"key",
"]",
"]",
".",
"join",
"(",
"' '",
")",
"+",
"\" \"",
"end",
"unless",
"entry",
"$stderr",
".",
"puts",
"\"#{ output } is not supported on #{ @page_name }\"",
"if",
"@debug",
"return",
"end",
"unless",
"entry",
"[",
"'ready'",
"]",
"==",
"\"1\"",
"$stderr",
".",
"puts",
"\"#{ output } is not ready to run #{ @agent_name }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"if",
"entry",
"[",
"'complete'",
"]",
"==",
"\"1\"",
"$stderr",
".",
"puts",
"\"All goals are completed for #{ output }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"if",
"entry",
"[",
"@agent_name",
"]",
"(",
"status",
",",
"running_hostname",
")",
"=",
"entry",
"[",
"@agent_name",
"]",
".",
"split",
"(",
"':'",
")",
"case",
"status",
"when",
"'r'",
"$stderr",
".",
"puts",
"\" #{ output } is already running #{ @agent_name } on #{ running_hostname }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"when",
"\"1\"",
"$stderr",
".",
"puts",
"\" #{ output } has already run #{ @agent_name }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"when",
"'F'",
"$stderr",
".",
"puts",
"\" #{ output } has already Failed #{ @agent_name }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"end",
"if",
"@prerequisites",
"@prerequisites",
".",
"each",
"do",
"|",
"prereq_field",
"|",
"unless",
"entry",
"[",
"prereq_field",
"]",
"==",
"\"1\"",
"$stderr",
".",
"puts",
"\" #{ output } has not finished #{ prereq_field }\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"end",
"end",
"hostname",
"=",
"Socket",
".",
"gethostname",
";",
"begin",
"entry",
".",
"update",
"@agent_name",
"=>",
"\"r:#{ hostname }\"",
"@worksheet",
".",
"save",
"rescue",
"GoogleDrive",
"::",
"Error",
"$stderr",
".",
"puts",
"\" #{ output } lost #{ @agent_name } on #{hostname}\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"sleep",
"3",
"begin",
"@worksheet",
".",
"reload",
"rescue",
"GoogleDrive",
"::",
"Error",
"$stderr",
".",
"puts",
"\" #{ output } lost #{ @agent_name } on #{hostname}\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end",
"check",
"=",
"entry",
"[",
"@agent_name",
"]",
"(",
"status",
",",
"running_hostname",
")",
"=",
"check",
".",
"split",
"(",
"':'",
")",
"if",
"hostname",
"==",
"running_hostname",
"return",
"true",
",",
"entry",
"end",
"$stderr",
".",
"puts",
"\" #{ output } lost #{ @agent_name } on #{hostname}\"",
"if",
"@debug",
"return",
"false",
",",
"entry",
"end"
] |
this call initiates a race resistant attempt to make sure that there is only 1
clear 'winner' among N potential agents attempting to run the same goal on the
same spreadsheet agent's cell
|
[
"this",
"call",
"initiates",
"a",
"race",
"resistant",
"attempt",
"to",
"make",
"sure",
"that",
"there",
"is",
"only",
"1",
"clear",
"winner",
"among",
"N",
"potential",
"agents",
"attempting",
"to",
"run",
"the",
"same",
"goal",
"on",
"the",
"same",
"spreadsheet",
"agent",
"s",
"cell"
] |
8fb21508470c41a1100289f4b0b52847b6d52d79
|
https://github.com/dmlond/spreadsheet_agent/blob/8fb21508470c41a1100289f4b0b52847b6d52d79/lib/spreadsheet_agent/agent.rb#L268-L345
|
valid
|
KevinMcHugh/kevins_propietary_brain
|
lib/kevins_propietary_brain.rb
|
KevinsPropietaryBrain.Brain.pick
|
def pick(number, *cards)
ordered = cards.flatten.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.first(number).map {|h| h[:card] }
end
|
ruby
|
def pick(number, *cards)
ordered = cards.flatten.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.first(number).map {|h| h[:card] }
end
|
[
"def",
"pick",
"(",
"number",
",",
"*",
"cards",
")",
"ordered",
"=",
"cards",
".",
"flatten",
".",
"map",
"do",
"|",
"card",
"|",
"i",
"=",
"card_preference",
".",
"map",
"{",
"|",
"preference",
"|",
"card",
".",
"type",
"==",
"preference",
"}",
".",
"index",
"(",
"true",
")",
"{",
"card",
":",
"card",
",",
"index",
":",
"i",
"}",
"end",
"ordered",
".",
"sort_by",
"{",
"|",
"h",
"|",
"h",
"[",
":index",
"]",
"||",
"99",
"}",
".",
"first",
"(",
"number",
")",
".",
"map",
"{",
"|",
"h",
"|",
"h",
"[",
":card",
"]",
"}",
"end"
] |
you have the option of picking from many cards, pick the best one.
|
[
"you",
"have",
"the",
"option",
"of",
"picking",
"from",
"many",
"cards",
"pick",
"the",
"best",
"one",
"."
] |
a734f40926f0a1415ef0294f1500525a621b1727
|
https://github.com/KevinMcHugh/kevins_propietary_brain/blob/a734f40926f0a1415ef0294f1500525a621b1727/lib/kevins_propietary_brain.rb#L23-L29
|
valid
|
KevinMcHugh/kevins_propietary_brain
|
lib/kevins_propietary_brain.rb
|
KevinsPropietaryBrain.Brain.discard
|
def discard
ordered = player.hand.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.last.try(:fetch, :card)
end
|
ruby
|
def discard
ordered = player.hand.map do |card|
i = card_preference.map { |preference| card.type == preference }.index(true)
{card: card, index: i}
end
ordered.sort_by { |h| h[:index] || 99 }.last.try(:fetch, :card)
end
|
[
"def",
"discard",
"ordered",
"=",
"player",
".",
"hand",
".",
"map",
"do",
"|",
"card",
"|",
"i",
"=",
"card_preference",
".",
"map",
"{",
"|",
"preference",
"|",
"card",
".",
"type",
"==",
"preference",
"}",
".",
"index",
"(",
"true",
")",
"{",
"card",
":",
"card",
",",
"index",
":",
"i",
"}",
"end",
"ordered",
".",
"sort_by",
"{",
"|",
"h",
"|",
"h",
"[",
":index",
"]",
"||",
"99",
"}",
".",
"last",
".",
"try",
"(",
":fetch",
",",
":card",
")",
"end"
] |
This method is called if your hand is over the hand limit, it returns the card that you would like to discard.
Returning nil or a card you don't have is a very bad idea. Bad things will happen to you.
|
[
"This",
"method",
"is",
"called",
"if",
"your",
"hand",
"is",
"over",
"the",
"hand",
"limit",
"it",
"returns",
"the",
"card",
"that",
"you",
"would",
"like",
"to",
"discard",
".",
"Returning",
"nil",
"or",
"a",
"card",
"you",
"don",
"t",
"have",
"is",
"a",
"very",
"bad",
"idea",
".",
"Bad",
"things",
"will",
"happen",
"to",
"you",
"."
] |
a734f40926f0a1415ef0294f1500525a621b1727
|
https://github.com/KevinMcHugh/kevins_propietary_brain/blob/a734f40926f0a1415ef0294f1500525a621b1727/lib/kevins_propietary_brain.rb#L68-L74
|
valid
|
KevinMcHugh/kevins_propietary_brain
|
lib/kevins_propietary_brain.rb
|
KevinsPropietaryBrain.Brain.play
|
def play
bangs_played = 0
while !player.hand.find_all(&:draws_cards?).empty?
player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)}
end
play_guns
player.hand.each do |card|
target = find_target(card)
next if skippable?(card, target, bangs_played)
bangs_played += 1 if card.type == Card.bang_card
player.play_card(card, target, :hand)
end
end
|
ruby
|
def play
bangs_played = 0
while !player.hand.find_all(&:draws_cards?).empty?
player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)}
end
play_guns
player.hand.each do |card|
target = find_target(card)
next if skippable?(card, target, bangs_played)
bangs_played += 1 if card.type == Card.bang_card
player.play_card(card, target, :hand)
end
end
|
[
"def",
"play",
"bangs_played",
"=",
"0",
"while",
"!",
"player",
".",
"hand",
".",
"find_all",
"(",
"&",
":draws_cards?",
")",
".",
"empty?",
"player",
".",
"hand",
".",
"find_all",
"(",
"&",
":draws_cards?",
")",
".",
"each",
"{",
"|",
"card",
"|",
"player",
".",
"play_card",
"(",
"card",
")",
"}",
"end",
"play_guns",
"player",
".",
"hand",
".",
"each",
"do",
"|",
"card",
"|",
"target",
"=",
"find_target",
"(",
"card",
")",
"next",
"if",
"skippable?",
"(",
"card",
",",
"target",
",",
"bangs_played",
")",
"bangs_played",
"+=",
"1",
"if",
"card",
".",
"type",
"==",
"Card",
".",
"bang_card",
"player",
".",
"play_card",
"(",
"card",
",",
"target",
",",
":hand",
")",
"end",
"end"
] |
This is the method that is called on your turn.
|
[
"This",
"is",
"the",
"method",
"that",
"is",
"called",
"on",
"your",
"turn",
"."
] |
a734f40926f0a1415ef0294f1500525a621b1727
|
https://github.com/KevinMcHugh/kevins_propietary_brain/blob/a734f40926f0a1415ef0294f1500525a621b1727/lib/kevins_propietary_brain.rb#L77-L89
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/mutex.rb
|
QuackConcurrency.Mutex.sleep
|
def sleep(timeout = nil)
validate_timeout(timeout)
unlock do
if timeout == nil || timeout == Float::INFINITY
elapsed_time = (timer { Thread.stop }).round
else
elapsed_time = Kernel.sleep(timeout)
end
end
end
|
ruby
|
def sleep(timeout = nil)
validate_timeout(timeout)
unlock do
if timeout == nil || timeout == Float::INFINITY
elapsed_time = (timer { Thread.stop }).round
else
elapsed_time = Kernel.sleep(timeout)
end
end
end
|
[
"def",
"sleep",
"(",
"timeout",
"=",
"nil",
")",
"validate_timeout",
"(",
"timeout",
")",
"unlock",
"do",
"if",
"timeout",
"==",
"nil",
"||",
"timeout",
"==",
"Float",
"::",
"INFINITY",
"elapsed_time",
"=",
"(",
"timer",
"{",
"Thread",
".",
"stop",
"}",
")",
".",
"round",
"else",
"elapsed_time",
"=",
"Kernel",
".",
"sleep",
"(",
"timeout",
")",
"end",
"end",
"end"
] |
Releases the lock and puts this thread to sleep.
@param timeout [nil, Numeric] time to sleep in seconds or +nil+ to sleep forever
@raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
@raise [ArgumentError] if +timeout+ is not positive
@return [Integer] elapsed time sleeping
|
[
"Releases",
"the",
"lock",
"and",
"puts",
"this",
"thread",
"to",
"sleep",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/mutex.rb#L75-L84
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/mutex.rb
|
QuackConcurrency.Mutex.temporarily_release
|
def temporarily_release(&block)
raise ArgumentError, 'no block given' unless block_given?
unlock
begin
return_value = yield
lock
rescue Exception
lock_immediately
raise
end
return_value
end
|
ruby
|
def temporarily_release(&block)
raise ArgumentError, 'no block given' unless block_given?
unlock
begin
return_value = yield
lock
rescue Exception
lock_immediately
raise
end
return_value
end
|
[
"def",
"temporarily_release",
"(",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"'no block given'",
"unless",
"block_given?",
"unlock",
"begin",
"return_value",
"=",
"yield",
"lock",
"rescue",
"Exception",
"lock_immediately",
"raise",
"end",
"return_value",
"end"
] |
Temporarily unlocks it while a block is run.
If an error is raised in the block the it will try to be immediately relocked
before passing the error up. If unsuccessful, a +ThreadError+ will be raised to
imitate the core's behavior.
@api private
@raise [ThreadError] if relock unsuccessful after an error
@raise [ArgumentError] if no block given
@return [void]
|
[
"Temporarily",
"unlocks",
"it",
"while",
"a",
"block",
"is",
"run",
".",
"If",
"an",
"error",
"is",
"raised",
"in",
"the",
"block",
"the",
"it",
"will",
"try",
"to",
"be",
"immediately",
"relocked",
"before",
"passing",
"the",
"error",
"up",
".",
"If",
"unsuccessful",
"a",
"+",
"ThreadError",
"+",
"will",
"be",
"raised",
"to",
"imitate",
"the",
"core",
"s",
"behavior",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/mutex.rb#L185-L196
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/mutex.rb
|
QuackConcurrency.Mutex.timer
|
def timer(&block)
start_time = Time.now
yield(start_time)
time_elapsed = Time.now - start_time
end
|
ruby
|
def timer(&block)
start_time = Time.now
yield(start_time)
time_elapsed = Time.now - start_time
end
|
[
"def",
"timer",
"(",
"&",
"block",
")",
"start_time",
"=",
"Time",
".",
"now",
"yield",
"(",
"start_time",
")",
"time_elapsed",
"=",
"Time",
".",
"now",
"-",
"start_time",
"end"
] |
Calculate time elapsed when running block.
@api private
@yield called while running timer
@yieldparam start_time [Time]
@raise [Exception] any exception raised in block
@return [Float] time elapsed while running block
|
[
"Calculate",
"time",
"elapsed",
"when",
"running",
"block",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/mutex.rb#L204-L208
|
valid
|
matschaffer/capybara_rails
|
lib/capybara_rails/selenium.rb
|
CapybaraRails.Selenium.wait
|
def wait
continue = false
trap "SIGINT" do
puts "Continuing..."
continue = true
end
puts "Waiting. Press ^C to continue test..."
wait_until(3600) { continue }
trap "SIGINT", "DEFAULT"
end
|
ruby
|
def wait
continue = false
trap "SIGINT" do
puts "Continuing..."
continue = true
end
puts "Waiting. Press ^C to continue test..."
wait_until(3600) { continue }
trap "SIGINT", "DEFAULT"
end
|
[
"def",
"wait",
"continue",
"=",
"false",
"trap",
"\"SIGINT\"",
"do",
"puts",
"\"Continuing...\"",
"continue",
"=",
"true",
"end",
"puts",
"\"Waiting. Press ^C to continue test...\"",
"wait_until",
"(",
"3600",
")",
"{",
"continue",
"}",
"trap",
"\"SIGINT\"",
",",
"\"DEFAULT\"",
"end"
] |
stalls test until ^C is hit
useful for inspecting page state via firebug
|
[
"stalls",
"test",
"until",
"^C",
"is",
"hit",
"useful",
"for",
"inspecting",
"page",
"state",
"via",
"firebug"
] |
ebfc919694f7516b2f74921ac2ffdb746b6ee45a
|
https://github.com/matschaffer/capybara_rails/blob/ebfc919694f7516b2f74921ac2ffdb746b6ee45a/lib/capybara_rails/selenium.rb#L14-L23
|
valid
|
blambeau/quickl
|
lib/quickl/ruby_tools.rb
|
Quickl.RubyTools.optional_args_block_call
|
def optional_args_block_call(block, args)
if RUBY_VERSION >= "1.9.0"
if block.arity == 0
block.call
else
block.call(*args)
end
else
block.call(*args)
end
end
|
ruby
|
def optional_args_block_call(block, args)
if RUBY_VERSION >= "1.9.0"
if block.arity == 0
block.call
else
block.call(*args)
end
else
block.call(*args)
end
end
|
[
"def",
"optional_args_block_call",
"(",
"block",
",",
"args",
")",
"if",
"RUBY_VERSION",
">=",
"\"1.9.0\"",
"if",
"block",
".",
"arity",
"==",
"0",
"block",
".",
"call",
"else",
"block",
".",
"call",
"(",
"*",
"args",
")",
"end",
"else",
"block",
".",
"call",
"(",
"*",
"args",
")",
"end",
"end"
] |
Makes a call to a block that accepts optional arguments
|
[
"Makes",
"a",
"call",
"to",
"a",
"block",
"that",
"accepts",
"optional",
"arguments"
] |
f0692a32156a48ac0d6083c38c58cb8cbbd2394f
|
https://github.com/blambeau/quickl/blob/f0692a32156a48ac0d6083c38c58cb8cbbd2394f/lib/quickl/ruby_tools.rb#L19-L29
|
valid
|
blambeau/quickl
|
lib/quickl/ruby_tools.rb
|
Quickl.RubyTools.extract_file_rdoc
|
def extract_file_rdoc(file, from = nil, reverse = false)
lines = File.readlines(file)
if from.nil? and reverse
lines = lines.reverse
elsif !reverse
lines = lines[(from || 0)..-1]
else
lines = lines[0...(from || -1)].reverse
end
doc, started = [], false
lines.each{|line|
if /^\s*[#]/ =~ line
doc << line
started = true
elsif started
break
end
}
doc = reverse ? doc.reverse[0..-1] : doc[0..-1]
doc = doc.join("\n")
doc.gsub(/^\s*[#] ?/, "")
end
|
ruby
|
def extract_file_rdoc(file, from = nil, reverse = false)
lines = File.readlines(file)
if from.nil? and reverse
lines = lines.reverse
elsif !reverse
lines = lines[(from || 0)..-1]
else
lines = lines[0...(from || -1)].reverse
end
doc, started = [], false
lines.each{|line|
if /^\s*[#]/ =~ line
doc << line
started = true
elsif started
break
end
}
doc = reverse ? doc.reverse[0..-1] : doc[0..-1]
doc = doc.join("\n")
doc.gsub(/^\s*[#] ?/, "")
end
|
[
"def",
"extract_file_rdoc",
"(",
"file",
",",
"from",
"=",
"nil",
",",
"reverse",
"=",
"false",
")",
"lines",
"=",
"File",
".",
"readlines",
"(",
"file",
")",
"if",
"from",
".",
"nil?",
"and",
"reverse",
"lines",
"=",
"lines",
".",
"reverse",
"elsif",
"!",
"reverse",
"lines",
"=",
"lines",
"[",
"(",
"from",
"||",
"0",
")",
"..",
"-",
"1",
"]",
"else",
"lines",
"=",
"lines",
"[",
"0",
"...",
"(",
"from",
"||",
"-",
"1",
")",
"]",
".",
"reverse",
"end",
"doc",
",",
"started",
"=",
"[",
"]",
",",
"false",
"lines",
".",
"each",
"{",
"|",
"line",
"|",
"if",
"/",
"\\s",
"/",
"=~",
"line",
"doc",
"<<",
"line",
"started",
"=",
"true",
"elsif",
"started",
"break",
"end",
"}",
"doc",
"=",
"reverse",
"?",
"doc",
".",
"reverse",
"[",
"0",
"..",
"-",
"1",
"]",
":",
"doc",
"[",
"0",
"..",
"-",
"1",
"]",
"doc",
"=",
"doc",
".",
"join",
"(",
"\"\\n\"",
")",
"doc",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"\"\"",
")",
"end"
] |
Extracts the rdoc of a given ruby file source.
|
[
"Extracts",
"the",
"rdoc",
"of",
"a",
"given",
"ruby",
"file",
"source",
"."
] |
f0692a32156a48ac0d6083c38c58cb8cbbd2394f
|
https://github.com/blambeau/quickl/blob/f0692a32156a48ac0d6083c38c58cb8cbbd2394f/lib/quickl/ruby_tools.rb#L33-L56
|
valid
|
ciconia/toughguy
|
lib/toughguy/query.rb
|
ToughGuy.Query.select
|
def select(fields)
if (fields == []) || (fields.nil?)
fields = [:_id]
end
clone.tap {|q| q.options[:fields] = fields}
end
|
ruby
|
def select(fields)
if (fields == []) || (fields.nil?)
fields = [:_id]
end
clone.tap {|q| q.options[:fields] = fields}
end
|
[
"def",
"select",
"(",
"fields",
")",
"if",
"(",
"fields",
"==",
"[",
"]",
")",
"||",
"(",
"fields",
".",
"nil?",
")",
"fields",
"=",
"[",
":_id",
"]",
"end",
"clone",
".",
"tap",
"{",
"|",
"q",
"|",
"q",
".",
"options",
"[",
":fields",
"]",
"=",
"fields",
"}",
"end"
] |
Add select method to select the fields to return
|
[
"Add",
"select",
"method",
"to",
"select",
"the",
"fields",
"to",
"return"
] |
6d2aa40f16fc133b127ae5ca31db93d7bee3fd98
|
https://github.com/ciconia/toughguy/blob/6d2aa40f16fc133b127ae5ca31db93d7bee3fd98/lib/toughguy/query.rb#L130-L135
|
valid
|
ciconia/toughguy
|
lib/toughguy/query.rb
|
ToughGuy.Query.set_pagination_info
|
def set_pagination_info(page_no, page_size, record_count)
@current_page = page_no
@per_page = page_size
@total_count = record_count
@total_pages = (record_count / page_size.to_f).ceil
extend PaginationMethods
self
end
|
ruby
|
def set_pagination_info(page_no, page_size, record_count)
@current_page = page_no
@per_page = page_size
@total_count = record_count
@total_pages = (record_count / page_size.to_f).ceil
extend PaginationMethods
self
end
|
[
"def",
"set_pagination_info",
"(",
"page_no",
",",
"page_size",
",",
"record_count",
")",
"@current_page",
"=",
"page_no",
"@per_page",
"=",
"page_size",
"@total_count",
"=",
"record_count",
"@total_pages",
"=",
"(",
"record_count",
"/",
"page_size",
".",
"to_f",
")",
".",
"ceil",
"extend",
"PaginationMethods",
"self",
"end"
] |
Sets the pagination info
|
[
"Sets",
"the",
"pagination",
"info"
] |
6d2aa40f16fc133b127ae5ca31db93d7bee3fd98
|
https://github.com/ciconia/toughguy/blob/6d2aa40f16fc133b127ae5ca31db93d7bee3fd98/lib/toughguy/query.rb#L156-L165
|
valid
|
jarrett/echo_uploads
|
lib/echo_uploads/model.rb
|
EchoUploads.Model.echo_uploads_data=
|
def echo_uploads_data=(data)
parsed = JSON.parse Base64.decode64(data)
# parsed will look like:
# { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
unless parsed.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
parsed.each do |attr, attr_data|
# If the :map option was passed, there may be multiple variants of the uploaded
# file. Even if not, attr_data is still a one-element array.
unless attr_data.is_a? Array
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
attr_data.each do |variant_data|
unless variant_data.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
if meta = ::EchoUploads::File.where(
id: variant_data['id'], key: variant_data['key'], temporary: true
).first
if send("#{attr}_tmp_metadata").nil?
send "#{attr}_tmp_metadata=", []
end
send("#{attr}_tmp_metadata") << meta
end
end
end
end
|
ruby
|
def echo_uploads_data=(data)
parsed = JSON.parse Base64.decode64(data)
# parsed will look like:
# { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
unless parsed.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
parsed.each do |attr, attr_data|
# If the :map option was passed, there may be multiple variants of the uploaded
# file. Even if not, attr_data is still a one-element array.
unless attr_data.is_a? Array
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
attr_data.each do |variant_data|
unless variant_data.is_a? Hash
raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
end
if meta = ::EchoUploads::File.where(
id: variant_data['id'], key: variant_data['key'], temporary: true
).first
if send("#{attr}_tmp_metadata").nil?
send "#{attr}_tmp_metadata=", []
end
send("#{attr}_tmp_metadata") << meta
end
end
end
end
|
[
"def",
"echo_uploads_data",
"=",
"(",
"data",
")",
"parsed",
"=",
"JSON",
".",
"parse",
"Base64",
".",
"decode64",
"(",
"data",
")",
"unless",
"parsed",
".",
"is_a?",
"Hash",
"raise",
"ArgumentError",
",",
"\"Invalid JSON structure in: #{parsed.inspect}\"",
"end",
"parsed",
".",
"each",
"do",
"|",
"attr",
",",
"attr_data",
"|",
"unless",
"attr_data",
".",
"is_a?",
"Array",
"raise",
"ArgumentError",
",",
"\"Invalid JSON structure in: #{parsed.inspect}\"",
"end",
"attr_data",
".",
"each",
"do",
"|",
"variant_data",
"|",
"unless",
"variant_data",
".",
"is_a?",
"Hash",
"raise",
"ArgumentError",
",",
"\"Invalid JSON structure in: #{parsed.inspect}\"",
"end",
"if",
"meta",
"=",
"::",
"EchoUploads",
"::",
"File",
".",
"where",
"(",
"id",
":",
"variant_data",
"[",
"'id'",
"]",
",",
"key",
":",
"variant_data",
"[",
"'key'",
"]",
",",
"temporary",
":",
"true",
")",
".",
"first",
"if",
"send",
"(",
"\"#{attr}_tmp_metadata\"",
")",
".",
"nil?",
"send",
"\"#{attr}_tmp_metadata=\"",
",",
"[",
"]",
"end",
"send",
"(",
"\"#{attr}_tmp_metadata\"",
")",
"<<",
"meta",
"end",
"end",
"end",
"end"
] |
Pass in a hash that's been encoded as JSON and then Base64.
|
[
"Pass",
"in",
"a",
"hash",
"that",
"s",
"been",
"encoded",
"as",
"JSON",
"and",
"then",
"Base64",
"."
] |
60eb0bd9c3d04dc13bf6ebbfa598492475102d77
|
https://github.com/jarrett/echo_uploads/blob/60eb0bd9c3d04dc13bf6ebbfa598492475102d77/lib/echo_uploads/model.rb#L31-L58
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/follower.rb
|
Mongoid.Follower.follower_of?
|
def follower_of?(model)
0 < self.followees.by_model(model).limit(1).count * model.followers.by_model(self).limit(1).count
end
|
ruby
|
def follower_of?(model)
0 < self.followees.by_model(model).limit(1).count * model.followers.by_model(self).limit(1).count
end
|
[
"def",
"follower_of?",
"(",
"model",
")",
"0",
"<",
"self",
".",
"followees",
".",
"by_model",
"(",
"model",
")",
".",
"limit",
"(",
"1",
")",
".",
"count",
"*",
"model",
".",
"followers",
".",
"by_model",
"(",
"self",
")",
".",
"limit",
"(",
"1",
")",
".",
"count",
"end"
] |
see if this model is follower of some model
Example:
>> @jim.follower_of?(@ruby)
=> true
|
[
"see",
"if",
"this",
"model",
"is",
"follower",
"of",
"some",
"model"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/follower.rb#L94-L96
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/follower.rb
|
Mongoid.Follower.follow
|
def follow(*models)
models.each do |model|
unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.create!(:f_type => self.class.name, :f_id => self.id.to_s)
model.followed_history << self.class.name + '_' + self.id.to_s
model.save
self.followees.create!(:f_type => model.class.name, :f_id => model.id.to_s)
self.follow_history << model.class.name + '_' + model.id.to_s
self.save
end
end
end
|
ruby
|
def follow(*models)
models.each do |model|
unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.create!(:f_type => self.class.name, :f_id => self.id.to_s)
model.followed_history << self.class.name + '_' + self.id.to_s
model.save
self.followees.create!(:f_type => model.class.name, :f_id => model.id.to_s)
self.follow_history << model.class.name + '_' + model.id.to_s
self.save
end
end
end
|
[
"def",
"follow",
"(",
"*",
"models",
")",
"models",
".",
"each",
"do",
"|",
"model",
"|",
"unless",
"model",
"==",
"self",
"or",
"self",
".",
"follower_of?",
"(",
"model",
")",
"or",
"model",
".",
"followee_of?",
"(",
"self",
")",
"or",
"self",
".",
"cannot_follow",
".",
"include?",
"(",
"model",
".",
"class",
".",
"name",
")",
"or",
"model",
".",
"cannot_followed",
".",
"include?",
"(",
"self",
".",
"class",
".",
"name",
")",
"model",
".",
"followers",
".",
"create!",
"(",
":f_type",
"=>",
"self",
".",
"class",
".",
"name",
",",
":f_id",
"=>",
"self",
".",
"id",
".",
"to_s",
")",
"model",
".",
"followed_history",
"<<",
"self",
".",
"class",
".",
"name",
"+",
"'_'",
"+",
"self",
".",
"id",
".",
"to_s",
"model",
".",
"save",
"self",
".",
"followees",
".",
"create!",
"(",
":f_type",
"=>",
"model",
".",
"class",
".",
"name",
",",
":f_id",
"=>",
"model",
".",
"id",
".",
"to_s",
")",
"self",
".",
"follow_history",
"<<",
"model",
".",
"class",
".",
"name",
"+",
"'_'",
"+",
"model",
".",
"id",
".",
"to_s",
"self",
".",
"save",
"end",
"end",
"end"
] |
follow some model
|
[
"follow",
"some",
"model"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/follower.rb#L120-L131
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/follower.rb
|
Mongoid.Follower.unfollow
|
def unfollow(*models)
models.each do |model|
unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.by_model(self).first.destroy
self.followees.by_model(model).first.destroy
end
end
end
|
ruby
|
def unfollow(*models)
models.each do |model|
unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name)
model.followers.by_model(self).first.destroy
self.followees.by_model(model).first.destroy
end
end
end
|
[
"def",
"unfollow",
"(",
"*",
"models",
")",
"models",
".",
"each",
"do",
"|",
"model",
"|",
"unless",
"model",
"==",
"self",
"or",
"!",
"self",
".",
"follower_of?",
"(",
"model",
")",
"or",
"!",
"model",
".",
"followee_of?",
"(",
"self",
")",
"or",
"self",
".",
"cannot_follow",
".",
"include?",
"(",
"model",
".",
"class",
".",
"name",
")",
"or",
"model",
".",
"cannot_followed",
".",
"include?",
"(",
"self",
".",
"class",
".",
"name",
")",
"model",
".",
"followers",
".",
"by_model",
"(",
"self",
")",
".",
"first",
".",
"destroy",
"self",
".",
"followees",
".",
"by_model",
"(",
"model",
")",
".",
"first",
".",
"destroy",
"end",
"end",
"end"
] |
unfollow some model
|
[
"unfollow",
"some",
"model"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/follower.rb#L135-L142
|
valid
|
lastomato/mongoid_followable
|
lib/mongoid_followable/follower.rb
|
Mongoid.Follower.ever_follow
|
def ever_follow
follow = []
self.follow_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end
|
ruby
|
def ever_follow
follow = []
self.follow_history.each do |h|
follow << h.split('_')[0].constantize.find(h.split('_')[1])
end
follow
end
|
[
"def",
"ever_follow",
"follow",
"=",
"[",
"]",
"self",
".",
"follow_history",
".",
"each",
"do",
"|",
"h",
"|",
"follow",
"<<",
"h",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
".",
"constantize",
".",
"find",
"(",
"h",
".",
"split",
"(",
"'_'",
")",
"[",
"1",
"]",
")",
"end",
"follow",
"end"
] |
see user's follow history
Example:
>> @jim.ever_follow
=> [@ruby]
|
[
"see",
"user",
"s",
"follow",
"history"
] |
6bc53a6e64d6c2732379fa588ed91b28d0680f15
|
https://github.com/lastomato/mongoid_followable/blob/6bc53a6e64d6c2732379fa588ed91b28d0680f15/lib/mongoid_followable/follower.rb#L170-L176
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/queue.rb
|
QuackConcurrency.Queue.pop
|
def pop(non_block = false)
@pop_mutex.lock do
@mutex.synchronize do
if empty?
return if closed?
raise ThreadError if non_block
@mutex.unlock
@waiter.wait
@mutex.lock
return if closed?
end
@items.shift
end
end
end
|
ruby
|
def pop(non_block = false)
@pop_mutex.lock do
@mutex.synchronize do
if empty?
return if closed?
raise ThreadError if non_block
@mutex.unlock
@waiter.wait
@mutex.lock
return if closed?
end
@items.shift
end
end
end
|
[
"def",
"pop",
"(",
"non_block",
"=",
"false",
")",
"@pop_mutex",
".",
"lock",
"do",
"@mutex",
".",
"synchronize",
"do",
"if",
"empty?",
"return",
"if",
"closed?",
"raise",
"ThreadError",
"if",
"non_block",
"@mutex",
".",
"unlock",
"@waiter",
".",
"wait",
"@mutex",
".",
"lock",
"return",
"if",
"closed?",
"end",
"@items",
".",
"shift",
"end",
"end",
"end"
] |
Retrieves an item from it.
@note If it is empty, the method will block until an item is available.
If +non_block+ is +true+, a +ThreadError+ will be raised.
@raise [ThreadError] if it is empty and +non_block+ is +true+
@param non_block [Boolean]
@return [Object]
|
[
"Retrieves",
"an",
"item",
"from",
"it",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/queue.rb#L73-L87
|
valid
|
bitfinexcom/grenache-ruby-base
|
lib/grenache/base.rb
|
Grenache.Base.lookup
|
def lookup(key, opts={}, &block)
unless addr = cache.has?(key)
addr = link.send('lookup', key, opts, &block)
cache.save(key, addr)
end
yield addr if block_given?
addr
end
|
ruby
|
def lookup(key, opts={}, &block)
unless addr = cache.has?(key)
addr = link.send('lookup', key, opts, &block)
cache.save(key, addr)
end
yield addr if block_given?
addr
end
|
[
"def",
"lookup",
"(",
"key",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"unless",
"addr",
"=",
"cache",
".",
"has?",
"(",
"key",
")",
"addr",
"=",
"link",
".",
"send",
"(",
"'lookup'",
",",
"key",
",",
"opts",
",",
"&",
"block",
")",
"cache",
".",
"save",
"(",
"key",
",",
"addr",
")",
"end",
"yield",
"addr",
"if",
"block_given?",
"addr",
"end"
] |
Initialize can accept custom configuration parameters
Lookup for a specific service `key`
passed block is called with the result values
in case of `http` backend it return the result directly
@param key [string] identifier of the service
|
[
"Initialize",
"can",
"accept",
"custom",
"configuration",
"parameters",
"Lookup",
"for",
"a",
"specific",
"service",
"key",
"passed",
"block",
"is",
"called",
"with",
"the",
"result",
"values",
"in",
"case",
"of",
"http",
"backend",
"it",
"return",
"the",
"result",
"directly"
] |
ded83de9529b4c8ce4a773cfc26a1bc58bb7428e
|
https://github.com/bitfinexcom/grenache-ruby-base/blob/ded83de9529b4c8ce4a773cfc26a1bc58bb7428e/lib/grenache/base.rb#L24-L31
|
valid
|
bitfinexcom/grenache-ruby-base
|
lib/grenache/base.rb
|
Grenache.Base.announce
|
def announce(key, port, opts={}, &block)
payload = [key,port]
link.send 'announce', payload, opts, &block
if config.auto_announce
periodically(config.auto_announce_interval) do
link.send 'announce', payload, opts, &block
end
end
end
|
ruby
|
def announce(key, port, opts={}, &block)
payload = [key,port]
link.send 'announce', payload, opts, &block
if config.auto_announce
periodically(config.auto_announce_interval) do
link.send 'announce', payload, opts, &block
end
end
end
|
[
"def",
"announce",
"(",
"key",
",",
"port",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"payload",
"=",
"[",
"key",
",",
"port",
"]",
"link",
".",
"send",
"'announce'",
",",
"payload",
",",
"opts",
",",
"&",
"block",
"if",
"config",
".",
"auto_announce",
"periodically",
"(",
"config",
".",
"auto_announce_interval",
")",
"do",
"link",
".",
"send",
"'announce'",
",",
"payload",
",",
"opts",
",",
"&",
"block",
"end",
"end",
"end"
] |
Announce a specific service `key` available on specific `port`
passed block is called when the announce is sent
@param key [string] service identifier
@param port [int] service port number
@block callback
|
[
"Announce",
"a",
"specific",
"service",
"key",
"available",
"on",
"specific",
"port",
"passed",
"block",
"is",
"called",
"when",
"the",
"announce",
"is",
"sent"
] |
ded83de9529b4c8ce4a773cfc26a1bc58bb7428e
|
https://github.com/bitfinexcom/grenache-ruby-base/blob/ded83de9529b4c8ce4a773cfc26a1bc58bb7428e/lib/grenache/base.rb#L38-L46
|
valid
|
kachick/validation
|
lib/validation/condition.rb
|
Validation.Condition._logical_operator
|
def _logical_operator(delegated, *conditions)
unless conditions.all?{|c|conditionable? c}
raise TypeError, 'wrong object for condition'
end
->v{
conditions.__send__(delegated) {|condition|
_valid? condition, v
}
}
end
|
ruby
|
def _logical_operator(delegated, *conditions)
unless conditions.all?{|c|conditionable? c}
raise TypeError, 'wrong object for condition'
end
->v{
conditions.__send__(delegated) {|condition|
_valid? condition, v
}
}
end
|
[
"def",
"_logical_operator",
"(",
"delegated",
",",
"*",
"conditions",
")",
"unless",
"conditions",
".",
"all?",
"{",
"|",
"c",
"|",
"conditionable?",
"c",
"}",
"raise",
"TypeError",
",",
"'wrong object for condition'",
"end",
"->",
"v",
"{",
"conditions",
".",
"__send__",
"(",
"delegated",
")",
"{",
"|",
"condition",
"|",
"_valid?",
"condition",
",",
"v",
"}",
"}",
"end"
] |
Condition Builders
A innner method for some condition builders.
For build conditions AND, NAND, OR, NOR, XOR, XNOR.
@param delegated [Symbol]
@return [lambda]
|
[
"Condition",
"Builders",
"A",
"innner",
"method",
"for",
"some",
"condition",
"builders",
".",
"For",
"build",
"conditions",
"AND",
"NAND",
"OR",
"NOR",
"XOR",
"XNOR",
"."
] |
43390cb6d9adc45c2f040d59f22ee514629309e6
|
https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/condition.rb#L24-L34
|
valid
|
mark-rushakoff/right_hook
|
lib/right_hook/spec_helpers.rb
|
RightHook.SpecHelpers.post_with_signature
|
def post_with_signature(opts)
path = opts.fetch(:path)
payload = opts.fetch(:payload)
secret = opts.fetch(:secret)
post path, {payload: payload}, generate_secret_header(secret, URI.encode_www_form(payload: payload))
end
|
ruby
|
def post_with_signature(opts)
path = opts.fetch(:path)
payload = opts.fetch(:payload)
secret = opts.fetch(:secret)
post path, {payload: payload}, generate_secret_header(secret, URI.encode_www_form(payload: payload))
end
|
[
"def",
"post_with_signature",
"(",
"opts",
")",
"path",
"=",
"opts",
".",
"fetch",
"(",
":path",
")",
"payload",
"=",
"opts",
".",
"fetch",
"(",
":payload",
")",
"secret",
"=",
"opts",
".",
"fetch",
"(",
":secret",
")",
"post",
"path",
",",
"{",
"payload",
":",
"payload",
"}",
",",
"generate_secret_header",
"(",
"secret",
",",
"URI",
".",
"encode_www_form",
"(",
"payload",
":",
"payload",
")",
")",
"end"
] |
Post to the given path, including the correct signature header based on the payload and secret.
@param [Hash] opts The options to use when crafting the request.
@option opts [String] :path The full path of the endpoint to which to post
@option opts [String] :payload A JSON-parseable string containing a payload as described in http://developer.github.com/v3/activity/events/types/
@option opts [String] :secret The secret to use when calculating the HMAC for the X-Hub-Signature header
|
[
"Post",
"to",
"the",
"given",
"path",
"including",
"the",
"correct",
"signature",
"header",
"based",
"on",
"the",
"payload",
"and",
"secret",
"."
] |
d5b92f57b22a7d819cb557cdaf6eabaa086a40bc
|
https://github.com/mark-rushakoff/right_hook/blob/d5b92f57b22a7d819cb557cdaf6eabaa086a40bc/lib/right_hook/spec_helpers.rb#L16-L22
|
valid
|
ddbrennan/rothko
|
lib/rothko.rb
|
Rothko.Drawing.get_height
|
def get_height(img)
new_height = (img.height / (img.width.to_f / self.width.to_f)).ceil
end
|
ruby
|
def get_height(img)
new_height = (img.height / (img.width.to_f / self.width.to_f)).ceil
end
|
[
"def",
"get_height",
"(",
"img",
")",
"new_height",
"=",
"(",
"img",
".",
"height",
"/",
"(",
"img",
".",
"width",
".",
"to_f",
"/",
"self",
".",
"width",
".",
"to_f",
")",
")",
".",
"ceil",
"end"
] |
Finds height of the image relative to provided width
|
[
"Finds",
"height",
"of",
"the",
"image",
"relative",
"to",
"provided",
"width"
] |
4d520e647179282775d212edac7aa1a69e6956c3
|
https://github.com/ddbrennan/rothko/blob/4d520e647179282775d212edac7aa1a69e6956c3/lib/rothko.rb#L52-L54
|
valid
|
ddbrennan/rothko
|
lib/rothko.rb
|
Rothko.Drawing.create_color_string
|
def create_color_string
(0...img.height).map do |y|
(0...img.width).map do |x|
pix = self.img[x,y]
pix_vals = [r(pix), g(pix), b(pix)]
find_closest_term_color(pix_vals)
end
end.join
end
|
ruby
|
def create_color_string
(0...img.height).map do |y|
(0...img.width).map do |x|
pix = self.img[x,y]
pix_vals = [r(pix), g(pix), b(pix)]
find_closest_term_color(pix_vals)
end
end.join
end
|
[
"def",
"create_color_string",
"(",
"0",
"...",
"img",
".",
"height",
")",
".",
"map",
"do",
"|",
"y",
"|",
"(",
"0",
"...",
"img",
".",
"width",
")",
".",
"map",
"do",
"|",
"x",
"|",
"pix",
"=",
"self",
".",
"img",
"[",
"x",
",",
"y",
"]",
"pix_vals",
"=",
"[",
"r",
"(",
"pix",
")",
",",
"g",
"(",
"pix",
")",
",",
"b",
"(",
"pix",
")",
"]",
"find_closest_term_color",
"(",
"pix_vals",
")",
"end",
"end",
".",
"join",
"end"
] |
Iterates over each pixel of resized image to find closest color
|
[
"Iterates",
"over",
"each",
"pixel",
"of",
"resized",
"image",
"to",
"find",
"closest",
"color"
] |
4d520e647179282775d212edac7aa1a69e6956c3
|
https://github.com/ddbrennan/rothko/blob/4d520e647179282775d212edac7aa1a69e6956c3/lib/rothko.rb#L57-L65
|
valid
|
ddbrennan/rothko
|
lib/rothko.rb
|
Rothko.Drawing.find_closest_term_color
|
def find_closest_term_color(pixel_values)
color = ""
lil_dist = 195075
@@palette.each do |col_name, col_values|
dist = find_distance(col_values, pixel_values)
if dist < lil_dist
lil_dist = dist
color = col_name
end
end
color
end
|
ruby
|
def find_closest_term_color(pixel_values)
color = ""
lil_dist = 195075
@@palette.each do |col_name, col_values|
dist = find_distance(col_values, pixel_values)
if dist < lil_dist
lil_dist = dist
color = col_name
end
end
color
end
|
[
"def",
"find_closest_term_color",
"(",
"pixel_values",
")",
"color",
"=",
"\"\"",
"lil_dist",
"=",
"195075",
"@@palette",
".",
"each",
"do",
"|",
"col_name",
",",
"col_values",
"|",
"dist",
"=",
"find_distance",
"(",
"col_values",
",",
"pixel_values",
")",
"if",
"dist",
"<",
"lil_dist",
"lil_dist",
"=",
"dist",
"color",
"=",
"col_name",
"end",
"end",
"color",
"end"
] |
Iterates over the palette to find the most similar color
|
[
"Iterates",
"over",
"the",
"palette",
"to",
"find",
"the",
"most",
"similar",
"color"
] |
4d520e647179282775d212edac7aa1a69e6956c3
|
https://github.com/ddbrennan/rothko/blob/4d520e647179282775d212edac7aa1a69e6956c3/lib/rothko.rb#L68-L79
|
valid
|
ddbrennan/rothko
|
lib/rothko.rb
|
Rothko.Drawing.draw_line
|
def draw_line(pixels)
pix_line = ""
pixels.each do |pixel|
pix_line = pix_line + " ".colorize(:background => find_color(pixel))
end
puts pix_line
end
|
ruby
|
def draw_line(pixels)
pix_line = ""
pixels.each do |pixel|
pix_line = pix_line + " ".colorize(:background => find_color(pixel))
end
puts pix_line
end
|
[
"def",
"draw_line",
"(",
"pixels",
")",
"pix_line",
"=",
"\"\"",
"pixels",
".",
"each",
"do",
"|",
"pixel",
"|",
"pix_line",
"=",
"pix_line",
"+",
"\" \"",
".",
"colorize",
"(",
":background",
"=>",
"find_color",
"(",
"pixel",
")",
")",
"end",
"puts",
"pix_line",
"end"
] |
Takes in a string of colors and puts them out as background colored spaces
For example, "rGK" creates a light_red square, a green square, and a black square
|
[
"Takes",
"in",
"a",
"string",
"of",
"colors",
"and",
"puts",
"them",
"out",
"as",
"background",
"colored",
"spaces",
"For",
"example",
"rGK",
"creates",
"a",
"light_red",
"square",
"a",
"green",
"square",
"and",
"a",
"black",
"square"
] |
4d520e647179282775d212edac7aa1a69e6956c3
|
https://github.com/ddbrennan/rothko/blob/4d520e647179282775d212edac7aa1a69e6956c3/lib/rothko.rb#L91-L97
|
valid
|
charly/jail
|
app/models/jail/cdnjs.rb
|
Jail.Cdnjs.tree
|
def tree
@tree and return @tree
@tree = []
file_set = version_files
while child = file_set.shift
tree << child #if child.dir?
if child.type == "dir"
file_set.unshift( github.where(child.path).contents ).flatten!
end
end
@tree
end
|
ruby
|
def tree
@tree and return @tree
@tree = []
file_set = version_files
while child = file_set.shift
tree << child #if child.dir?
if child.type == "dir"
file_set.unshift( github.where(child.path).contents ).flatten!
end
end
@tree
end
|
[
"def",
"tree",
"@tree",
"and",
"return",
"@tree",
"@tree",
"=",
"[",
"]",
"file_set",
"=",
"version_files",
"while",
"child",
"=",
"file_set",
".",
"shift",
"tree",
"<<",
"child",
"if",
"child",
".",
"type",
"==",
"\"dir\"",
"file_set",
".",
"unshift",
"(",
"github",
".",
"where",
"(",
"child",
".",
"path",
")",
".",
"contents",
")",
".",
"flatten!",
"end",
"end",
"@tree",
"end"
] |
build a depth first tree
|
[
"build",
"a",
"depth",
"first",
"tree"
] |
2d1177c8119e7288977d183eca4bb637a43928bb
|
https://github.com/charly/jail/blob/2d1177c8119e7288977d183eca4bb637a43928bb/app/models/jail/cdnjs.rb#L52-L66
|
valid
|
gdomingu/nasa_apod
|
lib/nasa_apod/client.rb
|
NasaApod.Client.search
|
def search(options = {})
self.date = options[:date] || date
self.hd = options[:hd] || hd
response = HTTParty.get(DEFAULT_URL, query: attributes)
handle_response(response)
end
|
ruby
|
def search(options = {})
self.date = options[:date] || date
self.hd = options[:hd] || hd
response = HTTParty.get(DEFAULT_URL, query: attributes)
handle_response(response)
end
|
[
"def",
"search",
"(",
"options",
"=",
"{",
"}",
")",
"self",
".",
"date",
"=",
"options",
"[",
":date",
"]",
"||",
"date",
"self",
".",
"hd",
"=",
"options",
"[",
":hd",
"]",
"||",
"hd",
"response",
"=",
"HTTParty",
".",
"get",
"(",
"DEFAULT_URL",
",",
"query",
":",
"attributes",
")",
"handle_response",
"(",
"response",
")",
"end"
] |
Returns APOD info for specified day.
@see https://api.nasa.gov/api.html#apod
@rate_limited Yes https://api.nasa.gov/api.html#authentication
@image_permissions http://apod.nasa.gov/apod/lib/about_apod.html#srapply
@authentication optional NASA api key https://api.nasa.gov/index.html#apply-for-an-api-key
@option options [String] :api_key Optional. Uses DEMO_KEY as default.
@option options [String] :date Optional. Returns the APOD results for
the given date. Date should be formatted as YYYY-MM-DD. Defaults as today.
@return [NasaApod::SearchResults] Return APOD post for a specified date.
|
[
"Returns",
"APOD",
"info",
"for",
"specified",
"day",
"."
] |
f8068be3c9e87c0733fc332f6bf11d956dd39ec0
|
https://github.com/gdomingu/nasa_apod/blob/f8068be3c9e87c0733fc332f6bf11d956dd39ec0/lib/nasa_apod/client.rb#L28-L33
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/sleeper.rb
|
QuackConcurrency.Sleeper.process_timeout
|
def process_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
timeout = nil if timeout == Float::INFINITY
timeout
end
|
ruby
|
def process_timeout(timeout)
unless timeout == nil
raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric)
raise ArgumentError, "'timeout' must not be negative" if timeout.negative?
end
timeout = nil if timeout == Float::INFINITY
timeout
end
|
[
"def",
"process_timeout",
"(",
"timeout",
")",
"unless",
"timeout",
"==",
"nil",
"raise",
"TypeError",
",",
"\"'timeout' must be nil or a Numeric\"",
"unless",
"timeout",
".",
"is_a?",
"(",
"Numeric",
")",
"raise",
"ArgumentError",
",",
"\"'timeout' must not be negative\"",
"if",
"timeout",
".",
"negative?",
"end",
"timeout",
"=",
"nil",
"if",
"timeout",
"==",
"Float",
"::",
"INFINITY",
"timeout",
"end"
] |
Validates a timeout value, converting to a acceptable value if necessary
@api private
@param timeout [nil,Numeric]
@raise [TypeError] if +timeout+ is not +nil+ or +Numeric+
@raise [ArgumentError] if +timeout+ is negative
@return [nil,Numeric]
|
[
"Validates",
"a",
"timeout",
"value",
"converting",
"to",
"a",
"acceptable",
"value",
"if",
"necessary"
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/sleeper.rb#L90-L97
|
valid
|
mark-rushakoff/right_hook
|
lib/right_hook/authenticator.rb
|
RightHook.Authenticator.find_or_create_authorization_by_note
|
def find_or_create_authorization_by_note(note)
found_auth = list_authorizations.find {|auth| auth.note == note}
if found_auth
found_auth.token
else
create_authorization(note)
end
end
|
ruby
|
def find_or_create_authorization_by_note(note)
found_auth = list_authorizations.find {|auth| auth.note == note}
if found_auth
found_auth.token
else
create_authorization(note)
end
end
|
[
"def",
"find_or_create_authorization_by_note",
"(",
"note",
")",
"found_auth",
"=",
"list_authorizations",
".",
"find",
"{",
"|",
"auth",
"|",
"auth",
".",
"note",
"==",
"note",
"}",
"if",
"found_auth",
"found_auth",
".",
"token",
"else",
"create_authorization",
"(",
"note",
")",
"end",
"end"
] |
If there is already an authorization by this note, use it; otherwise create it
|
[
"If",
"there",
"is",
"already",
"an",
"authorization",
"by",
"this",
"note",
"use",
"it",
";",
"otherwise",
"create",
"it"
] |
d5b92f57b22a7d819cb557cdaf6eabaa086a40bc
|
https://github.com/mark-rushakoff/right_hook/blob/d5b92f57b22a7d819cb557cdaf6eabaa086a40bc/lib/right_hook/authenticator.rb#L38-L45
|
valid
|
bitfinexcom/grenache-ruby-base
|
lib/grenache/link.rb
|
Grenache.Link.send
|
def send(type, payload, opts = {}, &block)
res = http_send type, Oj.dump({"rid" => uuid, "data" => payload})
block.call(res) if block
res
end
|
ruby
|
def send(type, payload, opts = {}, &block)
res = http_send type, Oj.dump({"rid" => uuid, "data" => payload})
block.call(res) if block
res
end
|
[
"def",
"send",
"(",
"type",
",",
"payload",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"res",
"=",
"http_send",
"type",
",",
"Oj",
".",
"dump",
"(",
"{",
"\"rid\"",
"=>",
"uuid",
",",
"\"data\"",
"=>",
"payload",
"}",
")",
"block",
".",
"call",
"(",
"res",
")",
"if",
"block",
"res",
"end"
] |
Initialize passing configuration
Send a message to grape
|
[
"Initialize",
"passing",
"configuration",
"Send",
"a",
"message",
"to",
"grape"
] |
ded83de9529b4c8ce4a773cfc26a1bc58bb7428e
|
https://github.com/bitfinexcom/grenache-ruby-base/blob/ded83de9529b4c8ce4a773cfc26a1bc58bb7428e/lib/grenache/link.rb#L11-L15
|
valid
|
NickLaMuro/jquids
|
lib/jquids/includes_helper.rb
|
Jquids.IncludesHelper.jquids_includes
|
def jquids_includes(options = {})
# Set the format for the datepickers
Jquids.format = options[:format] if options.has_key?(:format)
html_out = ""
if options.has_key?(:style)
html_out << stylesheet_link_tag(jq_ui_stylesheet(options[:style])) + "\n" unless options[:style] == nil or options[:style] == :none or options[:style] == false
else
html_out << stylesheet_link_tag(jq_ui_stylesheet) + "\n"
end
jq_vrs = options.has_key?(:jQuery) ? options[:jQuery] : Jquids::JQVersions.last
ui_vrs = options.has_key?(:jQueryUI) ? options[:jQueryUI] : Jquids::UIVersions.last
trtp_vrs = options.has_key?(:TRTimepicker) ? options[:TRTimepicker] : :none
# A little bit of css of the timepicker, and it is not added if the
# timepicker javascript file is not included
unless trtp_vrs == :none or trtp_vrs == false or trtp_vrs == nil
html_out << "<style type=\"text/css\">.ui-timepicker-div .ui-widget-header{margin-bottom:8px;}.ui-timepicker-div dl{text-align:left;}.ui-timepicker-div dl dt{height:25px;}.ui-timepicker-div dl dd{margin:-25px 0 10px 65px;}.ui-timepicker-div td{font-size:90%;}</style>\n"
end
html_out << javascript_include_tag(jq_ui_javascripts(jq_vrs, ui_vrs, trtp_vrs)) + "\n"
options[:datepicker_options] ||= {}
# Some opiniated defaults (basically an attempt to make the jQuery
# datepicker similar to the calendar_date_select with out making
# modifications or having local dependencies)
options[:datepicker_options][:showOtherMonths] = true if options[:datepicker_options][:showOtherMonths].nil?
options[:datepicker_options][:selectOtherMonths] = true if options[:datepicker_options][:selectOtherMonths].nil?
options[:datepicker_options][:changeMonth] = true if options[:datepicker_options][:changeMonth].nil?
options[:datepicker_options][:changeYear] = true if options[:datepicker_options][:changeYear].nil?
options[:datepicker_options][:dateFormat] = Jquids.format[:js_date]
Jquids.jquids_process_options(options)
# Decides whether the 'to_json' method exists (part of rails 3) or if the
# gem needs to us the json gem
datepicker_options =
if options[:datepicker_options].respond_to?(:to_json)
options.delete(:datepicker_options).to_json
else
begin
JSON.unparse(options.delete(:datepicker_options))
rescue
""
end
end
html_out << '<script type="text/javascript">$.datepicker.setDefaults(' + datepicker_options + ');'
unless trtp_vrs == :none or trtp_vrs == false or trtp_vrs == nil
options[:timepicker_options] ||= {}
# Some opiniated defaults (basically an attempt to make the jQuery
# datepicker similar to the calendar_date_select with out making
# modifications or having local dependencies)
# Sets the time format based off of the current format
options[:timepicker_options][:ampm] = Jquids.format[:ampm]
options[:timepicker_options][:timeFormat] = Jquids.format[:tr_js_time]
timepicker_options =
if options[:timepicker_options].respond_to?(:to_json)
options.delete(:timepicker_options).to_json
else
begin
JSON.unparse(options.delete(:timepicker_options))
rescue
""
end
end
html_out << '$.timepicker.setDefaults(' + timepicker_options + ');'
end
# A minified version of this javascript.
# <script type="text/javascript">
# $(document).ready(function(){
# $(".jquids_dp").each(function(){
# var s = $(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker") ? $(this).datepicker(JSON.parse(s)) : $(this).datepicker();
# });
# $(".jquids_tp").each(function(){
# var s = $(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker") ? $(this).timepicker(JSON.parse(s)) : $(this).timepicker();
# });
# $(".jquids_dtp").each(function(){
# var s=$(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker")?$(this).datetimepicker(JSON.parse(s)) : $(this).datetimepicker()
# })
# });
# </script>
#
# Used to parse out options for each datepicker instance
html_out << '$(document).ready(function(){$(".jquids_dp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).datepicker(JSON.parse(s)):$(this).datepicker()});$(".jquids_tp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).timepicker(JSON.parse(s)):$(this).timepicker()});$(".jquids_dtp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).datetimepicker(JSON.parse(s)):$(this).datetimepicker()})});</script>'
if html_out.respond_to?(:html_safe)
return html_out.html_safe
else
return html_out
end
end
|
ruby
|
def jquids_includes(options = {})
# Set the format for the datepickers
Jquids.format = options[:format] if options.has_key?(:format)
html_out = ""
if options.has_key?(:style)
html_out << stylesheet_link_tag(jq_ui_stylesheet(options[:style])) + "\n" unless options[:style] == nil or options[:style] == :none or options[:style] == false
else
html_out << stylesheet_link_tag(jq_ui_stylesheet) + "\n"
end
jq_vrs = options.has_key?(:jQuery) ? options[:jQuery] : Jquids::JQVersions.last
ui_vrs = options.has_key?(:jQueryUI) ? options[:jQueryUI] : Jquids::UIVersions.last
trtp_vrs = options.has_key?(:TRTimepicker) ? options[:TRTimepicker] : :none
# A little bit of css of the timepicker, and it is not added if the
# timepicker javascript file is not included
unless trtp_vrs == :none or trtp_vrs == false or trtp_vrs == nil
html_out << "<style type=\"text/css\">.ui-timepicker-div .ui-widget-header{margin-bottom:8px;}.ui-timepicker-div dl{text-align:left;}.ui-timepicker-div dl dt{height:25px;}.ui-timepicker-div dl dd{margin:-25px 0 10px 65px;}.ui-timepicker-div td{font-size:90%;}</style>\n"
end
html_out << javascript_include_tag(jq_ui_javascripts(jq_vrs, ui_vrs, trtp_vrs)) + "\n"
options[:datepicker_options] ||= {}
# Some opiniated defaults (basically an attempt to make the jQuery
# datepicker similar to the calendar_date_select with out making
# modifications or having local dependencies)
options[:datepicker_options][:showOtherMonths] = true if options[:datepicker_options][:showOtherMonths].nil?
options[:datepicker_options][:selectOtherMonths] = true if options[:datepicker_options][:selectOtherMonths].nil?
options[:datepicker_options][:changeMonth] = true if options[:datepicker_options][:changeMonth].nil?
options[:datepicker_options][:changeYear] = true if options[:datepicker_options][:changeYear].nil?
options[:datepicker_options][:dateFormat] = Jquids.format[:js_date]
Jquids.jquids_process_options(options)
# Decides whether the 'to_json' method exists (part of rails 3) or if the
# gem needs to us the json gem
datepicker_options =
if options[:datepicker_options].respond_to?(:to_json)
options.delete(:datepicker_options).to_json
else
begin
JSON.unparse(options.delete(:datepicker_options))
rescue
""
end
end
html_out << '<script type="text/javascript">$.datepicker.setDefaults(' + datepicker_options + ');'
unless trtp_vrs == :none or trtp_vrs == false or trtp_vrs == nil
options[:timepicker_options] ||= {}
# Some opiniated defaults (basically an attempt to make the jQuery
# datepicker similar to the calendar_date_select with out making
# modifications or having local dependencies)
# Sets the time format based off of the current format
options[:timepicker_options][:ampm] = Jquids.format[:ampm]
options[:timepicker_options][:timeFormat] = Jquids.format[:tr_js_time]
timepicker_options =
if options[:timepicker_options].respond_to?(:to_json)
options.delete(:timepicker_options).to_json
else
begin
JSON.unparse(options.delete(:timepicker_options))
rescue
""
end
end
html_out << '$.timepicker.setDefaults(' + timepicker_options + ');'
end
# A minified version of this javascript.
# <script type="text/javascript">
# $(document).ready(function(){
# $(".jquids_dp").each(function(){
# var s = $(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker") ? $(this).datepicker(JSON.parse(s)) : $(this).datepicker();
# });
# $(".jquids_tp").each(function(){
# var s = $(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker") ? $(this).timepicker(JSON.parse(s)) : $(this).timepicker();
# });
# $(".jquids_dtp").each(function(){
# var s=$(this).attr("data-jquipicker");
# $(this).attr("data-jquipicker")?$(this).datetimepicker(JSON.parse(s)) : $(this).datetimepicker()
# })
# });
# </script>
#
# Used to parse out options for each datepicker instance
html_out << '$(document).ready(function(){$(".jquids_dp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).datepicker(JSON.parse(s)):$(this).datepicker()});$(".jquids_tp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).timepicker(JSON.parse(s)):$(this).timepicker()});$(".jquids_dtp").each(function(){var s=$(this).attr("data-jquipicker");$(this).attr("data-jquipicker")?$(this).datetimepicker(JSON.parse(s)):$(this).datetimepicker()})});</script>'
if html_out.respond_to?(:html_safe)
return html_out.html_safe
else
return html_out
end
end
|
[
"def",
"jquids_includes",
"(",
"options",
"=",
"{",
"}",
")",
"Jquids",
".",
"format",
"=",
"options",
"[",
":format",
"]",
"if",
"options",
".",
"has_key?",
"(",
":format",
")",
"html_out",
"=",
"\"\"",
"if",
"options",
".",
"has_key?",
"(",
":style",
")",
"html_out",
"<<",
"stylesheet_link_tag",
"(",
"jq_ui_stylesheet",
"(",
"options",
"[",
":style",
"]",
")",
")",
"+",
"\"\\n\"",
"unless",
"options",
"[",
":style",
"]",
"==",
"nil",
"or",
"options",
"[",
":style",
"]",
"==",
":none",
"or",
"options",
"[",
":style",
"]",
"==",
"false",
"else",
"html_out",
"<<",
"stylesheet_link_tag",
"(",
"jq_ui_stylesheet",
")",
"+",
"\"\\n\"",
"end",
"jq_vrs",
"=",
"options",
".",
"has_key?",
"(",
":jQuery",
")",
"?",
"options",
"[",
":jQuery",
"]",
":",
"Jquids",
"::",
"JQVersions",
".",
"last",
"ui_vrs",
"=",
"options",
".",
"has_key?",
"(",
":jQueryUI",
")",
"?",
"options",
"[",
":jQueryUI",
"]",
":",
"Jquids",
"::",
"UIVersions",
".",
"last",
"trtp_vrs",
"=",
"options",
".",
"has_key?",
"(",
":TRTimepicker",
")",
"?",
"options",
"[",
":TRTimepicker",
"]",
":",
":none",
"unless",
"trtp_vrs",
"==",
":none",
"or",
"trtp_vrs",
"==",
"false",
"or",
"trtp_vrs",
"==",
"nil",
"html_out",
"<<",
"\"<style type=\\\"text/css\\\">.ui-timepicker-div .ui-widget-header{margin-bottom:8px;}.ui-timepicker-div dl{text-align:left;}.ui-timepicker-div dl dt{height:25px;}.ui-timepicker-div dl dd{margin:-25px 0 10px 65px;}.ui-timepicker-div td{font-size:90%;}</style>\\n\"",
"end",
"html_out",
"<<",
"javascript_include_tag",
"(",
"jq_ui_javascripts",
"(",
"jq_vrs",
",",
"ui_vrs",
",",
"trtp_vrs",
")",
")",
"+",
"\"\\n\"",
"options",
"[",
":datepicker_options",
"]",
"||=",
"{",
"}",
"options",
"[",
":datepicker_options",
"]",
"[",
":showOtherMonths",
"]",
"=",
"true",
"if",
"options",
"[",
":datepicker_options",
"]",
"[",
":showOtherMonths",
"]",
".",
"nil?",
"options",
"[",
":datepicker_options",
"]",
"[",
":selectOtherMonths",
"]",
"=",
"true",
"if",
"options",
"[",
":datepicker_options",
"]",
"[",
":selectOtherMonths",
"]",
".",
"nil?",
"options",
"[",
":datepicker_options",
"]",
"[",
":changeMonth",
"]",
"=",
"true",
"if",
"options",
"[",
":datepicker_options",
"]",
"[",
":changeMonth",
"]",
".",
"nil?",
"options",
"[",
":datepicker_options",
"]",
"[",
":changeYear",
"]",
"=",
"true",
"if",
"options",
"[",
":datepicker_options",
"]",
"[",
":changeYear",
"]",
".",
"nil?",
"options",
"[",
":datepicker_options",
"]",
"[",
":dateFormat",
"]",
"=",
"Jquids",
".",
"format",
"[",
":js_date",
"]",
"Jquids",
".",
"jquids_process_options",
"(",
"options",
")",
"datepicker_options",
"=",
"if",
"options",
"[",
":datepicker_options",
"]",
".",
"respond_to?",
"(",
":to_json",
")",
"options",
".",
"delete",
"(",
":datepicker_options",
")",
".",
"to_json",
"else",
"begin",
"JSON",
".",
"unparse",
"(",
"options",
".",
"delete",
"(",
":datepicker_options",
")",
")",
"rescue",
"\"\"",
"end",
"end",
"html_out",
"<<",
"'<script type=\"text/javascript\">$.datepicker.setDefaults('",
"+",
"datepicker_options",
"+",
"');'",
"unless",
"trtp_vrs",
"==",
":none",
"or",
"trtp_vrs",
"==",
"false",
"or",
"trtp_vrs",
"==",
"nil",
"options",
"[",
":timepicker_options",
"]",
"||=",
"{",
"}",
"options",
"[",
":timepicker_options",
"]",
"[",
":ampm",
"]",
"=",
"Jquids",
".",
"format",
"[",
":ampm",
"]",
"options",
"[",
":timepicker_options",
"]",
"[",
":timeFormat",
"]",
"=",
"Jquids",
".",
"format",
"[",
":tr_js_time",
"]",
"timepicker_options",
"=",
"if",
"options",
"[",
":timepicker_options",
"]",
".",
"respond_to?",
"(",
":to_json",
")",
"options",
".",
"delete",
"(",
":timepicker_options",
")",
".",
"to_json",
"else",
"begin",
"JSON",
".",
"unparse",
"(",
"options",
".",
"delete",
"(",
":timepicker_options",
")",
")",
"rescue",
"\"\"",
"end",
"end",
"html_out",
"<<",
"'$.timepicker.setDefaults('",
"+",
"timepicker_options",
"+",
"');'",
"end",
"html_out",
"<<",
"'$(document).ready(function(){$(\".jquids_dp\").each(function(){var s=$(this).attr(\"data-jquipicker\");$(this).attr(\"data-jquipicker\")?$(this).datepicker(JSON.parse(s)):$(this).datepicker()});$(\".jquids_tp\").each(function(){var s=$(this).attr(\"data-jquipicker\");$(this).attr(\"data-jquipicker\")?$(this).timepicker(JSON.parse(s)):$(this).timepicker()});$(\".jquids_dtp\").each(function(){var s=$(this).attr(\"data-jquipicker\");$(this).attr(\"data-jquipicker\")?$(this).datetimepicker(JSON.parse(s)):$(this).datetimepicker()})});</script>'",
"if",
"html_out",
".",
"respond_to?",
"(",
":html_safe",
")",
"return",
"html_out",
".",
"html_safe",
"else",
"return",
"html_out",
"end",
"end"
] |
Includes the stylesheets and javescripts into what ever view this is
called to.
By adding a :datepicker_options hash the options hash, you can change the
defaults styles that are intially applied to all datepicker instances.
Those defaults can be overwritten by each instance of the datepicker.
To not include the style sheet into the layout, just pass :style => :none
(false or nil will also work)
|
[
"Includes",
"the",
"stylesheets",
"and",
"javescripts",
"into",
"what",
"ever",
"view",
"this",
"is",
"called",
"to",
"."
] |
3128688802bd85b4f5544ed30cd5a15e8a3954d2
|
https://github.com/NickLaMuro/jquids/blob/3128688802bd85b4f5544ed30cd5a15e8a3954d2/lib/jquids/includes_helper.rb#L40-L143
|
valid
|
yaworsw/euler-manager
|
lib/euler.rb
|
Euler.ConfigOptions.method_missing
|
def method_missing method, *args, &block
if args.empty?
@config.send(method)
else
@config.send("#{method}=", args.first)
end
end
|
ruby
|
def method_missing method, *args, &block
if args.empty?
@config.send(method)
else
@config.send("#{method}=", args.first)
end
end
|
[
"def",
"method_missing",
"method",
",",
"*",
"args",
",",
"&",
"block",
"if",
"args",
".",
"empty?",
"@config",
".",
"send",
"(",
"method",
")",
"else",
"@config",
".",
"send",
"(",
"\"#{method}=\"",
",",
"args",
".",
"first",
")",
"end",
"end"
] |
Initialize an empty OpenStruct to hold configuration options
To set a config option call the corresponding method with an argument.
To retrieve a config option call the corresponding method without an argument.
|
[
"Initialize",
"an",
"empty",
"OpenStruct",
"to",
"hold",
"configuration",
"options",
"To",
"set",
"a",
"config",
"option",
"call",
"the",
"corresponding",
"method",
"with",
"an",
"argument",
".",
"To",
"retrieve",
"a",
"config",
"option",
"call",
"the",
"corresponding",
"method",
"without",
"an",
"argument",
"."
] |
ad4323a80873433bf411a4ce643d3b0b0f6deb02
|
https://github.com/yaworsw/euler-manager/blob/ad4323a80873433bf411a4ce643d3b0b0f6deb02/lib/euler.rb#L23-L29
|
valid
|
moh-alsheikh/hijri_ummalqura
|
lib/hijri_umm_alqura.rb
|
HijriUmmAlqura.Hijri.to_s
|
def to_s
today = arabno_to_hindi(day) + " "
today = today + HijriUmmAlqura::MONTHNAMES[month] + " "
today = today + arabno_to_hindi(year) + " هـ"
end
|
ruby
|
def to_s
today = arabno_to_hindi(day) + " "
today = today + HijriUmmAlqura::MONTHNAMES[month] + " "
today = today + arabno_to_hindi(year) + " هـ"
end
|
[
"def",
"to_s",
"today",
"=",
"arabno_to_hindi",
"(",
"day",
")",
"+",
"\" \"",
"today",
"=",
"today",
"+",
"HijriUmmAlqura",
"::",
"MONTHNAMES",
"[",
"month",
"]",
"+",
"\" \"",
"today",
"=",
"today",
"+",
"arabno_to_hindi",
"(",
"year",
")",
"+",
"\" هـ\" ",
"end"
] |
constructor
return hijri date with month and day names
|
[
"constructor",
"return",
"hijri",
"date",
"with",
"month",
"and",
"day",
"names"
] |
4f183f3769c95e81e3aeb275ba1cfb5717084a77
|
https://github.com/moh-alsheikh/hijri_ummalqura/blob/4f183f3769c95e81e3aeb275ba1cfb5717084a77/lib/hijri_umm_alqura.rb#L28-L32
|
valid
|
moh-alsheikh/hijri_ummalqura
|
lib/hijri_umm_alqura.rb
|
HijriUmmAlqura.Hijri.jd
|
def jd(date = self)
index = (12 * (date.year - 1)) + date.month - 16260
mcjdn = date.day + HijriUmmAlqura::UMMALQURA_DAT[index - 1] - 1
mcjdn = mcjdn + 2400000 - 0.5
return mcjdn
end
|
ruby
|
def jd(date = self)
index = (12 * (date.year - 1)) + date.month - 16260
mcjdn = date.day + HijriUmmAlqura::UMMALQURA_DAT[index - 1] - 1
mcjdn = mcjdn + 2400000 - 0.5
return mcjdn
end
|
[
"def",
"jd",
"(",
"date",
"=",
"self",
")",
"index",
"=",
"(",
"12",
"*",
"(",
"date",
".",
"year",
"-",
"1",
")",
")",
"+",
"date",
".",
"month",
"-",
"16260",
"mcjdn",
"=",
"date",
".",
"day",
"+",
"HijriUmmAlqura",
"::",
"UMMALQURA_DAT",
"[",
"index",
"-",
"1",
"]",
"-",
"1",
"mcjdn",
"=",
"mcjdn",
"+",
"2400000",
"-",
"0.5",
"return",
"mcjdn",
"end"
] |
Hijri to julian
|
[
"Hijri",
"to",
"julian"
] |
4f183f3769c95e81e3aeb275ba1cfb5717084a77
|
https://github.com/moh-alsheikh/hijri_ummalqura/blob/4f183f3769c95e81e3aeb275ba1cfb5717084a77/lib/hijri_umm_alqura.rb#L35-L40
|
valid
|
moh-alsheikh/hijri_ummalqura
|
lib/hijri_umm_alqura.rb
|
HijriUmmAlqura.Hijri.gd
|
def gd(date = self)
j_date = jd(date)
g_date = HijriUmmAlqura.jd_to_gd(j_date)
return g_date
end
|
ruby
|
def gd(date = self)
j_date = jd(date)
g_date = HijriUmmAlqura.jd_to_gd(j_date)
return g_date
end
|
[
"def",
"gd",
"(",
"date",
"=",
"self",
")",
"j_date",
"=",
"jd",
"(",
"date",
")",
"g_date",
"=",
"HijriUmmAlqura",
".",
"jd_to_gd",
"(",
"j_date",
")",
"return",
"g_date",
"end"
] |
Hijri to gregorian
|
[
"Hijri",
"to",
"gregorian"
] |
4f183f3769c95e81e3aeb275ba1cfb5717084a77
|
https://github.com/moh-alsheikh/hijri_ummalqura/blob/4f183f3769c95e81e3aeb275ba1cfb5717084a77/lib/hijri_umm_alqura.rb#L43-L47
|
valid
|
moh-alsheikh/hijri_ummalqura
|
lib/hijri_umm_alqura.rb
|
HijriUmmAlqura.Hijri.add
|
def add(date = self, offset, period)
y = period == 'y' ? (date.year + offset) : date.year
m = period == 'm' ? (month_of_year(date.year, date.month) + offset) : month_of_year(date.year, date.month)
d = date.day
begin
if (period == 'd' || period == 'w')
week_days = period == 'w' ? 7 : 1
j_date = jd
j_date = j_date + offset * week_days
result = HijriUmmAlqura.jd(j_date)
return result
elsif (period == 'm')
rys = resync_year_month(y, m)
y = rys[0]
m = rys[1]
return HijriUmmAlqura.format_date([y, m, d])
elsif (period == 'y')
return HijriUmmAlqura.format_date([y, m, d])
end
rescue Exception => e
puts "Exception details: #{e.class} #{e.message}"
end
end
|
ruby
|
def add(date = self, offset, period)
y = period == 'y' ? (date.year + offset) : date.year
m = period == 'm' ? (month_of_year(date.year, date.month) + offset) : month_of_year(date.year, date.month)
d = date.day
begin
if (period == 'd' || period == 'w')
week_days = period == 'w' ? 7 : 1
j_date = jd
j_date = j_date + offset * week_days
result = HijriUmmAlqura.jd(j_date)
return result
elsif (period == 'm')
rys = resync_year_month(y, m)
y = rys[0]
m = rys[1]
return HijriUmmAlqura.format_date([y, m, d])
elsif (period == 'y')
return HijriUmmAlqura.format_date([y, m, d])
end
rescue Exception => e
puts "Exception details: #{e.class} #{e.message}"
end
end
|
[
"def",
"add",
"(",
"date",
"=",
"self",
",",
"offset",
",",
"period",
")",
"y",
"=",
"period",
"==",
"'y'",
"?",
"(",
"date",
".",
"year",
"+",
"offset",
")",
":",
"date",
".",
"year",
"m",
"=",
"period",
"==",
"'m'",
"?",
"(",
"month_of_year",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
")",
"+",
"offset",
")",
":",
"month_of_year",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
")",
"d",
"=",
"date",
".",
"day",
"begin",
"if",
"(",
"period",
"==",
"'d'",
"||",
"period",
"==",
"'w'",
")",
"week_days",
"=",
"period",
"==",
"'w'",
"?",
"7",
":",
"1",
"j_date",
"=",
"jd",
"j_date",
"=",
"j_date",
"+",
"offset",
"*",
"week_days",
"result",
"=",
"HijriUmmAlqura",
".",
"jd",
"(",
"j_date",
")",
"return",
"result",
"elsif",
"(",
"period",
"==",
"'m'",
")",
"rys",
"=",
"resync_year_month",
"(",
"y",
",",
"m",
")",
"y",
"=",
"rys",
"[",
"0",
"]",
"m",
"=",
"rys",
"[",
"1",
"]",
"return",
"HijriUmmAlqura",
".",
"format_date",
"(",
"[",
"y",
",",
"m",
",",
"d",
"]",
")",
"elsif",
"(",
"period",
"==",
"'y'",
")",
"return",
"HijriUmmAlqura",
".",
"format_date",
"(",
"[",
"y",
",",
"m",
",",
"d",
"]",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"Exception details: #{e.class} #{e.message}\"",
"end",
"end"
] |
Add Days - Weeks - Months - Years
|
[
"Add",
"Days",
"-",
"Weeks",
"-",
"Months",
"-",
"Years"
] |
4f183f3769c95e81e3aeb275ba1cfb5717084a77
|
https://github.com/moh-alsheikh/hijri_ummalqura/blob/4f183f3769c95e81e3aeb275ba1cfb5717084a77/lib/hijri_umm_alqura.rb#L50-L72
|
valid
|
moh-alsheikh/hijri_ummalqura
|
lib/hijri_umm_alqura.rb
|
HijriUmmAlqura.Hijri.+
|
def + (n)
case n
when Numeric then
j_date = jd + n * 1
result = HijriUmmAlqura.jd(j_date)
return result
end
raise TypeError, 'expected numeric'
end
|
ruby
|
def + (n)
case n
when Numeric then
j_date = jd + n * 1
result = HijriUmmAlqura.jd(j_date)
return result
end
raise TypeError, 'expected numeric'
end
|
[
"def",
"+",
"(",
"n",
")",
"case",
"n",
"when",
"Numeric",
"then",
"j_date",
"=",
"jd",
"+",
"n",
"*",
"1",
"result",
"=",
"HijriUmmAlqura",
".",
"jd",
"(",
"j_date",
")",
"return",
"result",
"end",
"raise",
"TypeError",
",",
"'expected numeric'",
"end"
] |
comparison operator
return hijri date plus n days
|
[
"comparison",
"operator",
"return",
"hijri",
"date",
"plus",
"n",
"days"
] |
4f183f3769c95e81e3aeb275ba1cfb5717084a77
|
https://github.com/moh-alsheikh/hijri_ummalqura/blob/4f183f3769c95e81e3aeb275ba1cfb5717084a77/lib/hijri_umm_alqura.rb#L125-L133
|
valid
|
robfors/quack_concurrency
|
lib/quack_concurrency/future.rb
|
QuackConcurrency.Future.raise
|
def raise(exception = nil)
exception = case
when exception == nil then StandardError.new
when exception.is_a?(Exception) then exception
when Exception >= exception then exception.new
else
Kernel.raise(TypeError, "'exception' must be nil or an instance of or descendant of Exception")
end
@mutex.synchronize do
Kernel.raise(Complete) if @complete
@complete = true
@exception = exception
@waiter.resume_all_indefinitely
end
nil
end
|
ruby
|
def raise(exception = nil)
exception = case
when exception == nil then StandardError.new
when exception.is_a?(Exception) then exception
when Exception >= exception then exception.new
else
Kernel.raise(TypeError, "'exception' must be nil or an instance of or descendant of Exception")
end
@mutex.synchronize do
Kernel.raise(Complete) if @complete
@complete = true
@exception = exception
@waiter.resume_all_indefinitely
end
nil
end
|
[
"def",
"raise",
"(",
"exception",
"=",
"nil",
")",
"exception",
"=",
"case",
"when",
"exception",
"==",
"nil",
"then",
"StandardError",
".",
"new",
"when",
"exception",
".",
"is_a?",
"(",
"Exception",
")",
"then",
"exception",
"when",
"Exception",
">=",
"exception",
"then",
"exception",
".",
"new",
"else",
"Kernel",
".",
"raise",
"(",
"TypeError",
",",
"\"'exception' must be nil or an instance of or descendant of Exception\"",
")",
"end",
"@mutex",
".",
"synchronize",
"do",
"Kernel",
".",
"raise",
"(",
"Complete",
")",
"if",
"@complete",
"@complete",
"=",
"true",
"@exception",
"=",
"exception",
"@waiter",
".",
"resume_all_indefinitely",
"end",
"nil",
"end"
] |
Sets it to an error.
@raise [Complete] if the it has already completed
@param exception [nil,Object] +Exception+ class or instance to set, otherwise a +StandardError+ will be set
@return [void]
|
[
"Sets",
"it",
"to",
"an",
"error",
"."
] |
fb42bbd48b4e4994297431e926bbbcc777a3cd08
|
https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/future.rb#L48-L63
|
valid
|
megamsys/megam_scmmanager.rb
|
lib/megam/core/scmm/scmmaccount.rb
|
Megam.ScmmAccount.to_hash
|
def to_hash
index_hash = Hash.new
index_hash["json_claz"] = self.class.name
index_hash["creationDate"] = creationDate
index_hash["admin"] = admin
index_hash["type"] = type
index_hash["password"] = password
index_hash["name"] = name
index_hahs["mail"] = mail
index_hash["displayName"] = displayName
index_hash["lastModified"] = lastModified
index_hash["active"] = active
index_hash["some_msg"] = some_msg
index_hash
end
|
ruby
|
def to_hash
index_hash = Hash.new
index_hash["json_claz"] = self.class.name
index_hash["creationDate"] = creationDate
index_hash["admin"] = admin
index_hash["type"] = type
index_hash["password"] = password
index_hash["name"] = name
index_hahs["mail"] = mail
index_hash["displayName"] = displayName
index_hash["lastModified"] = lastModified
index_hash["active"] = active
index_hash["some_msg"] = some_msg
index_hash
end
|
[
"def",
"to_hash",
"index_hash",
"=",
"Hash",
".",
"new",
"index_hash",
"[",
"\"json_claz\"",
"]",
"=",
"self",
".",
"class",
".",
"name",
"index_hash",
"[",
"\"creationDate\"",
"]",
"=",
"creationDate",
"index_hash",
"[",
"\"admin\"",
"]",
"=",
"admin",
"index_hash",
"[",
"\"type\"",
"]",
"=",
"type",
"index_hash",
"[",
"\"password\"",
"]",
"=",
"password",
"index_hash",
"[",
"\"name\"",
"]",
"=",
"name",
"index_hahs",
"[",
"\"mail\"",
"]",
"=",
"mail",
"index_hash",
"[",
"\"displayName\"",
"]",
"=",
"displayName",
"index_hash",
"[",
"\"lastModified\"",
"]",
"=",
"lastModified",
"index_hash",
"[",
"\"active\"",
"]",
"=",
"active",
"index_hash",
"[",
"\"some_msg\"",
"]",
"=",
"some_msg",
"index_hash",
"end"
] |
Transform the ruby obj -> to a Hash
|
[
"Transform",
"the",
"ruby",
"obj",
"-",
">",
"to",
"a",
"Hash"
] |
fae0fe0f9519dabd3625e5fdc0b24006de5746fb
|
https://github.com/megamsys/megam_scmmanager.rb/blob/fae0fe0f9519dabd3625e5fdc0b24006de5746fb/lib/megam/core/scmm/scmmaccount.rb#L123-L137
|
valid
|
arusarka/mingle4r
|
lib/mingle4r/common_class_methods.rb
|
Mingle4r.CommonClassMethods.site=
|
def site=(site)
if site != self.site
@site = site
uri = URI.parse(site)
@user = URI.decode(uri.user) if(uri.user)
@password = URI.decode(uri.password) if(uri.password)
@resource_class = self.send(:create_resource_class)
end
@site
end
|
ruby
|
def site=(site)
if site != self.site
@site = site
uri = URI.parse(site)
@user = URI.decode(uri.user) if(uri.user)
@password = URI.decode(uri.password) if(uri.password)
@resource_class = self.send(:create_resource_class)
end
@site
end
|
[
"def",
"site",
"=",
"(",
"site",
")",
"if",
"site",
"!=",
"self",
".",
"site",
"@site",
"=",
"site",
"uri",
"=",
"URI",
".",
"parse",
"(",
"site",
")",
"@user",
"=",
"URI",
".",
"decode",
"(",
"uri",
".",
"user",
")",
"if",
"(",
"uri",
".",
"user",
")",
"@password",
"=",
"URI",
".",
"decode",
"(",
"uri",
".",
"password",
")",
"if",
"(",
"uri",
".",
"password",
")",
"@resource_class",
"=",
"self",
".",
"send",
"(",
":create_resource_class",
")",
"end",
"@site",
"end"
] |
sets the site for the class in which this module is extended
|
[
"sets",
"the",
"site",
"for",
"the",
"class",
"in",
"which",
"this",
"module",
"is",
"extended"
] |
02cd31d074f959d05395e6165c12af66c4d90636
|
https://github.com/arusarka/mingle4r/blob/02cd31d074f959d05395e6165c12af66c4d90636/lib/mingle4r/common_class_methods.rb#L14-L23
|
valid
|
arusarka/mingle4r
|
lib/mingle4r/common_class_methods.rb
|
Mingle4r.CommonClassMethods.find
|
def find(*args)
scope = args.slice!(0)
options = args.slice!(0) || {}
@resource_class.find(scope, options)
end
|
ruby
|
def find(*args)
scope = args.slice!(0)
options = args.slice!(0) || {}
@resource_class.find(scope, options)
end
|
[
"def",
"find",
"(",
"*",
"args",
")",
"scope",
"=",
"args",
".",
"slice!",
"(",
"0",
")",
"options",
"=",
"args",
".",
"slice!",
"(",
"0",
")",
"||",
"{",
"}",
"@resource_class",
".",
"find",
"(",
"scope",
",",
"options",
")",
"end"
] |
def all_attributes_set?
site && user && password
end
routes to active resource find
|
[
"def",
"all_attributes_set?",
"site",
"&&",
"user",
"&&",
"password",
"end",
"routes",
"to",
"active",
"resource",
"find"
] |
02cd31d074f959d05395e6165c12af66c4d90636
|
https://github.com/arusarka/mingle4r/blob/02cd31d074f959d05395e6165c12af66c4d90636/lib/mingle4r/common_class_methods.rb#L74-L78
|
valid
|
arusarka/mingle4r
|
lib/mingle4r/common_class_methods.rb
|
Mingle4r.CommonClassMethods.create_resource_class
|
def create_resource_class
raise "Please set the site for #{self} class." unless(self.site)
created_class = Class.new(MingleResource)
created_class.format = :xml
setup_class(created_class)
created_class
end
|
ruby
|
def create_resource_class
raise "Please set the site for #{self} class." unless(self.site)
created_class = Class.new(MingleResource)
created_class.format = :xml
setup_class(created_class)
created_class
end
|
[
"def",
"create_resource_class",
"raise",
"\"Please set the site for #{self} class.\"",
"unless",
"(",
"self",
".",
"site",
")",
"created_class",
"=",
"Class",
".",
"new",
"(",
"MingleResource",
")",
"created_class",
".",
"format",
"=",
":xml",
"setup_class",
"(",
"created_class",
")",
"created_class",
"end"
] |
creates an active resource class dynamically. All the attributes are set automatically. Avoid calling
this method directly
|
[
"creates",
"an",
"active",
"resource",
"class",
"dynamically",
".",
"All",
"the",
"attributes",
"are",
"set",
"automatically",
".",
"Avoid",
"calling",
"this",
"method",
"directly"
] |
02cd31d074f959d05395e6165c12af66c4d90636
|
https://github.com/arusarka/mingle4r/blob/02cd31d074f959d05395e6165c12af66c4d90636/lib/mingle4r/common_class_methods.rb#L83-L89
|
valid
|
chetan/bixby-agent
|
lib/bixby-agent/app.rb
|
Bixby.App.run!
|
def run!
# load agent from config or cli opts
agent = load_agent()
fix_ownership()
# debug mode, stay in front
if @config[:debug] then
Logging::Logger.root.add_appenders("stdout")
return start_websocket_client()
end
# start daemon
validate_argv()
daemon_dir = Bixby.path("var")
ensure_state_dir(daemon_dir)
close_fds()
daemon_opts = {
:dir => daemon_dir,
:dir_mode => :normal,
:log_output => true,
:stop_proc => lambda { logger.info "Agent shutdown on service stop command" }
}
Daemons.run_proc("bixby-agent", daemon_opts) do
Logging.logger.root.clear_appenders
start_websocket_client()
end
end
|
ruby
|
def run!
# load agent from config or cli opts
agent = load_agent()
fix_ownership()
# debug mode, stay in front
if @config[:debug] then
Logging::Logger.root.add_appenders("stdout")
return start_websocket_client()
end
# start daemon
validate_argv()
daemon_dir = Bixby.path("var")
ensure_state_dir(daemon_dir)
close_fds()
daemon_opts = {
:dir => daemon_dir,
:dir_mode => :normal,
:log_output => true,
:stop_proc => lambda { logger.info "Agent shutdown on service stop command" }
}
Daemons.run_proc("bixby-agent", daemon_opts) do
Logging.logger.root.clear_appenders
start_websocket_client()
end
end
|
[
"def",
"run!",
"agent",
"=",
"load_agent",
"(",
")",
"fix_ownership",
"(",
")",
"if",
"@config",
"[",
":debug",
"]",
"then",
"Logging",
"::",
"Logger",
".",
"root",
".",
"add_appenders",
"(",
"\"stdout\"",
")",
"return",
"start_websocket_client",
"(",
")",
"end",
"validate_argv",
"(",
")",
"daemon_dir",
"=",
"Bixby",
".",
"path",
"(",
"\"var\"",
")",
"ensure_state_dir",
"(",
"daemon_dir",
")",
"close_fds",
"(",
")",
"daemon_opts",
"=",
"{",
":dir",
"=>",
"daemon_dir",
",",
":dir_mode",
"=>",
":normal",
",",
":log_output",
"=>",
"true",
",",
":stop_proc",
"=>",
"lambda",
"{",
"logger",
".",
"info",
"\"Agent shutdown on service stop command\"",
"}",
"}",
"Daemons",
".",
"run_proc",
"(",
"\"bixby-agent\"",
",",
"daemon_opts",
")",
"do",
"Logging",
".",
"logger",
".",
"root",
".",
"clear_appenders",
"start_websocket_client",
"(",
")",
"end",
"end"
] |
Run the agent app!
This is the main method. Will boot and configure the agent, connect to the
server and start the daemon.
|
[
"Run",
"the",
"agent",
"app!"
] |
cb79b001570118b5b5e2a50674df7691e906a6cd
|
https://github.com/chetan/bixby-agent/blob/cb79b001570118b5b5e2a50674df7691e906a6cd/lib/bixby-agent/app.rb#L87-L116
|
valid
|
chetan/bixby-agent
|
lib/bixby-agent/app.rb
|
Bixby.App.start_websocket_client
|
def start_websocket_client
# make sure log level is still set correctly here
Bixby::Log.setup_logger(:level => Logging.appenders["file"].level)
logger.info "Started Bixby Agent #{Bixby::Agent::VERSION}"
@client = Bixby::WebSocket::Client.new(Bixby.agent.manager_ws_uri, AgentHandler)
trap_signals()
@client.start
end
|
ruby
|
def start_websocket_client
# make sure log level is still set correctly here
Bixby::Log.setup_logger(:level => Logging.appenders["file"].level)
logger.info "Started Bixby Agent #{Bixby::Agent::VERSION}"
@client = Bixby::WebSocket::Client.new(Bixby.agent.manager_ws_uri, AgentHandler)
trap_signals()
@client.start
end
|
[
"def",
"start_websocket_client",
"Bixby",
"::",
"Log",
".",
"setup_logger",
"(",
":level",
"=>",
"Logging",
".",
"appenders",
"[",
"\"file\"",
"]",
".",
"level",
")",
"logger",
".",
"info",
"\"Started Bixby Agent #{Bixby::Agent::VERSION}\"",
"@client",
"=",
"Bixby",
"::",
"WebSocket",
"::",
"Client",
".",
"new",
"(",
"Bixby",
".",
"agent",
".",
"manager_ws_uri",
",",
"AgentHandler",
")",
"trap_signals",
"(",
")",
"@client",
".",
"start",
"end"
] |
Open the WebSocket channel with the Manager
NOTE: this call will not return!
|
[
"Open",
"the",
"WebSocket",
"channel",
"with",
"the",
"Manager"
] |
cb79b001570118b5b5e2a50674df7691e906a6cd
|
https://github.com/chetan/bixby-agent/blob/cb79b001570118b5b5e2a50674df7691e906a6cd/lib/bixby-agent/app.rb#L121-L128
|
valid
|
chetan/bixby-agent
|
lib/bixby-agent/app.rb
|
Bixby.App.fix_ownership
|
def fix_ownership
return if Process.uid != 0
begin
uid = Etc.getpwnam("bixby").uid
gid = Etc.getgrnam("bixby").gid
# user/group exists, chown
File.chown(uid, gid, Bixby.path("var"), Bixby.path("etc"))
rescue ArgumentError
end
end
|
ruby
|
def fix_ownership
return if Process.uid != 0
begin
uid = Etc.getpwnam("bixby").uid
gid = Etc.getgrnam("bixby").gid
# user/group exists, chown
File.chown(uid, gid, Bixby.path("var"), Bixby.path("etc"))
rescue ArgumentError
end
end
|
[
"def",
"fix_ownership",
"return",
"if",
"Process",
".",
"uid",
"!=",
"0",
"begin",
"uid",
"=",
"Etc",
".",
"getpwnam",
"(",
"\"bixby\"",
")",
".",
"uid",
"gid",
"=",
"Etc",
".",
"getgrnam",
"(",
"\"bixby\"",
")",
".",
"gid",
"File",
".",
"chown",
"(",
"uid",
",",
"gid",
",",
"Bixby",
".",
"path",
"(",
"\"var\"",
")",
",",
"Bixby",
".",
"path",
"(",
"\"etc\"",
")",
")",
"rescue",
"ArgumentError",
"end",
"end"
] |
If running as root, fix ownership of var and etc dirs
|
[
"If",
"running",
"as",
"root",
"fix",
"ownership",
"of",
"var",
"and",
"etc",
"dirs"
] |
cb79b001570118b5b5e2a50674df7691e906a6cd
|
https://github.com/chetan/bixby-agent/blob/cb79b001570118b5b5e2a50674df7691e906a6cd/lib/bixby-agent/app.rb#L147-L156
|
valid
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.