repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.repeat
def repeat(nx=1, ny=1, nz=1) raise "Not a periodic system." if self.lattice_vectors.nil? u = self.copy v1 = self.lattice_vectors[0] v2 = self.lattice_vectors[1] v3 = self.lattice_vectors[2] nx_sign = (0 < nx) ? 1 : -1 ny_sign = (0 < ny) ? 1 : -1 nz_sign = (0 < nz) ? 1 : -1 new_atoms = [] nx.to_i.abs.times do |i| ny.to_i.abs.times do |j| nz.to_i.abs.times do |k| new_atoms << self.displace(nx_sign*i*v1[0] + ny_sign*j*v2[0] + nz_sign*k*v3[0], nx_sign*i*v1[1] + ny_sign*j*v2[1] + nz_sign*k*v3[1], nx_sign*i*v1[2] + ny_sign*j*v2[2] + nz_sign*k*v3[2]).atoms end end end u.atoms = new_atoms.flatten u.lattice_vectors = [Vector[nx.abs*v1[0], nx.abs*v1[1], nx.abs*v1[2]], Vector[ny.abs*v2[0], ny.abs*v2[1], ny.abs*v2[2]], Vector[nz.abs*v3[0], nz.abs*v3[1], nz.abs*v3[2]]] # u.make_bonds return u end
ruby
def repeat(nx=1, ny=1, nz=1) raise "Not a periodic system." if self.lattice_vectors.nil? u = self.copy v1 = self.lattice_vectors[0] v2 = self.lattice_vectors[1] v3 = self.lattice_vectors[2] nx_sign = (0 < nx) ? 1 : -1 ny_sign = (0 < ny) ? 1 : -1 nz_sign = (0 < nz) ? 1 : -1 new_atoms = [] nx.to_i.abs.times do |i| ny.to_i.abs.times do |j| nz.to_i.abs.times do |k| new_atoms << self.displace(nx_sign*i*v1[0] + ny_sign*j*v2[0] + nz_sign*k*v3[0], nx_sign*i*v1[1] + ny_sign*j*v2[1] + nz_sign*k*v3[1], nx_sign*i*v1[2] + ny_sign*j*v2[2] + nz_sign*k*v3[2]).atoms end end end u.atoms = new_atoms.flatten u.lattice_vectors = [Vector[nx.abs*v1[0], nx.abs*v1[1], nx.abs*v1[2]], Vector[ny.abs*v2[0], ny.abs*v2[1], ny.abs*v2[2]], Vector[nz.abs*v3[0], nz.abs*v3[1], nz.abs*v3[2]]] # u.make_bonds return u end
[ "def", "repeat", "(", "nx", "=", "1", ",", "ny", "=", "1", ",", "nz", "=", "1", ")", "raise", "\"Not a periodic system.\"", "if", "self", ".", "lattice_vectors", ".", "nil?", "u", "=", "self", ".", "copy", "v1", "=", "self", ".", "lattice_vectors", "[", "0", "]", "v2", "=", "self", ".", "lattice_vectors", "[", "1", "]", "v3", "=", "self", ".", "lattice_vectors", "[", "2", "]", "nx_sign", "=", "(", "0", "<", "nx", ")", "?", "1", ":", "-", "1", "ny_sign", "=", "(", "0", "<", "ny", ")", "?", "1", ":", "-", "1", "nz_sign", "=", "(", "0", "<", "nz", ")", "?", "1", ":", "-", "1", "new_atoms", "=", "[", "]", "nx", ".", "to_i", ".", "abs", ".", "times", "do", "|", "i", "|", "ny", ".", "to_i", ".", "abs", ".", "times", "do", "|", "j", "|", "nz", ".", "to_i", ".", "abs", ".", "times", "do", "|", "k", "|", "new_atoms", "<<", "self", ".", "displace", "(", "nx_sign", "*", "i", "*", "v1", "[", "0", "]", "+", "ny_sign", "*", "j", "*", "v2", "[", "0", "]", "+", "nz_sign", "*", "k", "*", "v3", "[", "0", "]", ",", "nx_sign", "*", "i", "*", "v1", "[", "1", "]", "+", "ny_sign", "*", "j", "*", "v2", "[", "1", "]", "+", "nz_sign", "*", "k", "*", "v3", "[", "1", "]", ",", "nx_sign", "*", "i", "*", "v1", "[", "2", "]", "+", "ny_sign", "*", "j", "*", "v2", "[", "2", "]", "+", "nz_sign", "*", "k", "*", "v3", "[", "2", "]", ")", ".", "atoms", "end", "end", "end", "u", ".", "atoms", "=", "new_atoms", ".", "flatten", "u", ".", "lattice_vectors", "=", "[", "Vector", "[", "nx", ".", "abs", "*", "v1", "[", "0", "]", ",", "nx", ".", "abs", "*", "v1", "[", "1", "]", ",", "nx", ".", "abs", "*", "v1", "[", "2", "]", "]", ",", "Vector", "[", "ny", ".", "abs", "*", "v2", "[", "0", "]", ",", "ny", ".", "abs", "*", "v2", "[", "1", "]", ",", "ny", ".", "abs", "*", "v2", "[", "2", "]", "]", ",", "Vector", "[", "nz", ".", "abs", "*", "v3", "[", "0", "]", ",", "nz", ".", "abs", "*", "v3", "[", "1", "]", ",", "nz", ".", "abs", "*", "v3", "[", "2", "]", "]", "]", "return", "u", "end" ]
Repeat a unit cell nx,ny,nz times in the directions of the lattice vectors. Negative values of nx,ny or nz results in displacement in the negative direction of the lattice vectors
[ "Repeat", "a", "unit", "cell", "nx", "ny", "nz", "times", "in", "the", "directions", "of", "the", "lattice", "vectors", ".", "Negative", "values", "of", "nx", "ny", "or", "nz", "results", "in", "displacement", "in", "the", "negative", "direction", "of", "the", "lattice", "vectors" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L474-L504
train
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.format_geometry_in
def format_geometry_in output = "" if self.lattice_vectors output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n") output << "\n" end output << self.atoms.collect{|a| a.format_geometry_in}.join("\n") output end
ruby
def format_geometry_in output = "" if self.lattice_vectors output << self.lattice_vectors.collect{|v| "lattice_vector #{v[0]} #{v[1]} #{v[2]}"}.join("\n") output << "\n" end output << self.atoms.collect{|a| a.format_geometry_in}.join("\n") output end
[ "def", "format_geometry_in", "output", "=", "\"\"", "if", "self", ".", "lattice_vectors", "output", "<<", "self", ".", "lattice_vectors", ".", "collect", "{", "|", "v", "|", "\"lattice_vector #{v[0]} #{v[1]} #{v[2]}\"", "}", ".", "join", "(", "\"\\n\"", ")", "output", "<<", "\"\\n\"", "end", "output", "<<", "self", ".", "atoms", ".", "collect", "{", "|", "a", "|", "a", ".", "format_geometry_in", "}", ".", "join", "(", "\"\\n\"", ")", "output", "end" ]
Return a string formatted in the Aims geometry.in format.
[ "Return", "a", "string", "formatted", "in", "the", "Aims", "geometry", ".", "in", "format", "." ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L520-L529
train
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.format_xyz
def format_xyz(title = "Aims Geoemtry") output = self.atoms.size.to_s + "\n" output << "#{title} \n" self.atoms.each{ |a| output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n" } output end
ruby
def format_xyz(title = "Aims Geoemtry") output = self.atoms.size.to_s + "\n" output << "#{title} \n" self.atoms.each{ |a| output << [a.species, a.x.to_s, a.y.to_s, a.z.to_s].join("\t") + "\n" } output end
[ "def", "format_xyz", "(", "title", "=", "\"Aims Geoemtry\"", ")", "output", "=", "self", ".", "atoms", ".", "size", ".", "to_s", "+", "\"\\n\"", "output", "<<", "\"#{title} \\n\"", "self", ".", "atoms", ".", "each", "{", "|", "a", "|", "output", "<<", "[", "a", ".", "species", ",", "a", ".", "x", ".", "to_s", ",", "a", ".", "y", ".", "to_s", ",", "a", ".", "z", ".", "to_s", "]", ".", "join", "(", "\"\\t\"", ")", "+", "\"\\n\"", "}", "output", "end" ]
return a string in xyz format
[ "return", "a", "string", "in", "xyz", "format" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L532-L539
train
jns/Aims
lib/aims/geometry.rb
Aims.Geometry.delta
def delta(aCell) raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size pseudo_atoms = [] self.atoms.size.times {|i| a1 = self.atoms[i] a2 = aCell.atoms[i] raise "Species do not match" unless a1.species == a2.species a = Atom.new a.species = a1.species a.x = a1.x - a2.x a.y = a1.y - a2.y a.z = a1.z - a2.z pseudo_atoms << a } Geometry.new(pseudo_atoms) end
ruby
def delta(aCell) raise "Cells do not have the same number of atoms" unless self.atoms.size == aCell.atoms.size pseudo_atoms = [] self.atoms.size.times {|i| a1 = self.atoms[i] a2 = aCell.atoms[i] raise "Species do not match" unless a1.species == a2.species a = Atom.new a.species = a1.species a.x = a1.x - a2.x a.y = a1.y - a2.y a.z = a1.z - a2.z pseudo_atoms << a } Geometry.new(pseudo_atoms) end
[ "def", "delta", "(", "aCell", ")", "raise", "\"Cells do not have the same number of atoms\"", "unless", "self", ".", "atoms", ".", "size", "==", "aCell", ".", "atoms", ".", "size", "pseudo_atoms", "=", "[", "]", "self", ".", "atoms", ".", "size", ".", "times", "{", "|", "i", "|", "a1", "=", "self", ".", "atoms", "[", "i", "]", "a2", "=", "aCell", ".", "atoms", "[", "i", "]", "raise", "\"Species do not match\"", "unless", "a1", ".", "species", "==", "a2", ".", "species", "a", "=", "Atom", ".", "new", "a", ".", "species", "=", "a1", ".", "species", "a", ".", "x", "=", "a1", ".", "x", "-", "a2", ".", "x", "a", ".", "y", "=", "a1", ".", "y", "-", "a2", ".", "y", "a", ".", "z", "=", "a1", ".", "z", "-", "a2", ".", "z", "pseudo_atoms", "<<", "a", "}", "Geometry", ".", "new", "(", "pseudo_atoms", ")", "end" ]
Find the difference between this cell and another cell Return a cell with Pseudo-Atoms whose positions are really the differences
[ "Find", "the", "difference", "between", "this", "cell", "and", "another", "cell", "Return", "a", "cell", "with", "Pseudo", "-", "Atoms", "whose", "positions", "are", "really", "the", "differences" ]
2dcb6c02cd05b2d0c8ab72be4e85d60375df296c
https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L543-L559
train
robertwahler/dynabix
lib/dynabix/metadata.rb
Dynabix.Metadata.has_metadata
def has_metadata(serializer=:metadata, *attributes) serialize(serializer, HashWithIndifferentAccess) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else # we can safely define additional accessors, Ruby 1.8 will only # be able to use the statically defined :metadata_accessor if serializer != :metadata # define the class accessor define_singleton_method "#{serializer}_accessor" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end # define the class read accessor define_singleton_method "#{serializer}_reader" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) end end # define the class write accessor define_singleton_method "#{serializer}_writer" do |*attrs| attrs.each do |attr| create_writer(serializer, attr) end end end end # Define each of the attributes for this serializer attributes.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end
ruby
def has_metadata(serializer=:metadata, *attributes) serialize(serializer, HashWithIndifferentAccess) if RUBY_VERSION < '1.9' raise "has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+" unless serializer == :metadata else # we can safely define additional accessors, Ruby 1.8 will only # be able to use the statically defined :metadata_accessor if serializer != :metadata # define the class accessor define_singleton_method "#{serializer}_accessor" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end # define the class read accessor define_singleton_method "#{serializer}_reader" do |*attrs| attrs.each do |attr| create_reader(serializer, attr) end end # define the class write accessor define_singleton_method "#{serializer}_writer" do |*attrs| attrs.each do |attr| create_writer(serializer, attr) end end end end # Define each of the attributes for this serializer attributes.each do |attr| create_reader(serializer, attr) create_writer(serializer, attr) end end
[ "def", "has_metadata", "(", "serializer", "=", ":metadata", ",", "*", "attributes", ")", "serialize", "(", "serializer", ",", "HashWithIndifferentAccess", ")", "if", "RUBY_VERSION", "<", "'1.9'", "raise", "\"has_metadata serializer must be named ':metadata', this restriction is lifted in Ruby 1.9+\"", "unless", "serializer", "==", ":metadata", "else", "if", "serializer", "!=", ":metadata", "define_singleton_method", "\"#{serializer}_accessor\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end", "define_singleton_method", "\"#{serializer}_reader\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "end", "end", "define_singleton_method", "\"#{serializer}_writer\"", "do", "|", "*", "attrs", "|", "attrs", ".", "each", "do", "|", "attr", "|", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end", "end", "end", "attributes", ".", "each", "do", "|", "attr", "|", "create_reader", "(", "serializer", ",", "attr", ")", "create_writer", "(", "serializer", ",", "attr", ")", "end", "end" ]
Set up the model for serialization to a HashWithIndifferentAccess. @example Using the default column name ":metadata", specify the attributes in a separate step class Thing < ActiveRecord::Base has_metadata # full accessors metadata_accessor :breakfast_food, :wheat_products, :needs_milk # read-only metadata_reader :friends_with_spoons end @example Specifying attributes for full attributes accessors in one step class Thing < ActiveRecord::Base has_metadata :metadata, :breakfast_food, :wheat_products, :needs_milk end @example Specifying multiple metadata serializers (Ruby 1.9 only) class Thing < ActiveRecord::Base has_metadata :cows has_metadata :chickens, :tasty, :feather_count # read-only cow_reader :likes_milk, :hates_eggs # write-only cow_writer :no_wheat_products # extra full accessors for chickens chicken_accessor :color, :likes_eggs end @param [Symbol] serializer, the symbolized name (:metadata) of the database text column used for serialization @param [Array<Symbol>] optional list of attribute names to add to the model as full accessors @return [void]
[ "Set", "up", "the", "model", "for", "serialization", "to", "a", "HashWithIndifferentAccess", "." ]
4a462c3d467433c76a1f7d308ba77ca9eedcbcb2
https://github.com/robertwahler/dynabix/blob/4a462c3d467433c76a1f7d308ba77ca9eedcbcb2/lib/dynabix/metadata.rb#L49-L89
train
barkerest/shells
lib/shells/shell_base/input.rb
Shells.ShellBase.queue_input
def queue_input(data) #:doc: sync do if options[:unbuffered_input] data = data.chars input_fifo.push *data else input_fifo.push data end end end
ruby
def queue_input(data) #:doc: sync do if options[:unbuffered_input] data = data.chars input_fifo.push *data else input_fifo.push data end end end
[ "def", "queue_input", "(", "data", ")", "sync", "do", "if", "options", "[", ":unbuffered_input", "]", "data", "=", "data", ".", "chars", "input_fifo", ".", "push", "*", "data", "else", "input_fifo", ".", "push", "data", "end", "end", "end" ]
Adds input to be sent to the shell.
[ "Adds", "input", "to", "be", "sent", "to", "the", "shell", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/input.rb#L31-L40
train
mrackwitz/CLIntegracon
lib/CLIntegracon/adapter/bacon.rb
CLIntegracon::Adapter::Bacon.Context.subject
def subject &block @subject ||= CLIntegracon::shared_config.subject.dup return @subject if block.nil? instance_exec(@subject, &block) end
ruby
def subject &block @subject ||= CLIntegracon::shared_config.subject.dup return @subject if block.nil? instance_exec(@subject, &block) end
[ "def", "subject", "&", "block", "@subject", "||=", "CLIntegracon", "::", "shared_config", ".", "subject", ".", "dup", "return", "@subject", "if", "block", ".", "nil?", "instance_exec", "(", "@subject", ",", "&", "block", ")", "end" ]
Get or configure the current subject @note On first call this will create a new subject on base of the shared configuration and store it in the ivar `@subject`. @param [Block<(Subject) -> ()>] This block, if given, will be evaluated on the caller. It receives as first argument the subject itself. @return [Subject] the subject
[ "Get", "or", "configure", "the", "current", "subject" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/adapter/bacon.rb#L25-L29
train
mrackwitz/CLIntegracon
lib/CLIntegracon/adapter/bacon.rb
CLIntegracon::Adapter::Bacon.Context.file_tree_spec_context
def file_tree_spec_context &block @file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup return @file_tree_spec_context if block.nil? instance_exec(@file_tree_spec_context, &block) end
ruby
def file_tree_spec_context &block @file_tree_spec_context ||= CLIntegracon.shared_config.file_tree_spec_context.dup return @file_tree_spec_context if block.nil? instance_exec(@file_tree_spec_context, &block) end
[ "def", "file_tree_spec_context", "&", "block", "@file_tree_spec_context", "||=", "CLIntegracon", ".", "shared_config", ".", "file_tree_spec_context", ".", "dup", "return", "@file_tree_spec_context", "if", "block", ".", "nil?", "instance_exec", "(", "@file_tree_spec_context", ",", "&", "block", ")", "end" ]
Get or configure the current context for FileTreeSpecs @note On first call this will create a new context on base of the shared configuration and store it in the ivar `@file_tree_spec_context`. @param [Block<(FileTreeSpecContext) -> ()>] This block, if given, will be evaluated on the caller. It receives as first argument the context itself. @return [FileTreeSpecContext] the spec context, will be lazily created if not already present.
[ "Get", "or", "configure", "the", "current", "context", "for", "FileTreeSpecs" ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/adapter/bacon.rb#L43-L47
train
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.acquire_read_lock
def acquire_read_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many reader threads' if max_readers?(c) if waiting_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if waiting_writer? end while(true) c = @counter.value if running_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if running_writer? end else return if @counter.compare_and_swap(c,c+1) end end else break if @counter.compare_and_swap(c,c+1) end end true end
ruby
def acquire_read_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many reader threads' if max_readers?(c) if waiting_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if waiting_writer? end while(true) c = @counter.value if running_writer?(c) @reader_mutex.synchronize do @reader_q.wait(@reader_mutex) if running_writer? end else return if @counter.compare_and_swap(c,c+1) end end else break if @counter.compare_and_swap(c,c+1) end end true end
[ "def", "acquire_read_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "raise", "ResourceLimitError", ",", "'Too many reader threads'", "if", "max_readers?", "(", "c", ")", "if", "waiting_writer?", "(", "c", ")", "@reader_mutex", ".", "synchronize", "do", "@reader_q", ".", "wait", "(", "@reader_mutex", ")", "if", "waiting_writer?", "end", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "running_writer?", "(", "c", ")", "@reader_mutex", ".", "synchronize", "do", "@reader_q", ".", "wait", "(", "@reader_mutex", ")", "if", "running_writer?", "end", "else", "return", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "1", ")", "end", "end", "else", "break", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "1", ")", "end", "end", "true", "end" ]
Acquire a read lock. If a write lock has been acquired will block until it is released. Will not block if other read locks have been acquired. @return [Boolean] True if the lock is successfully acquired. @raise [Garcon::ResourceLimitError] If the maximum number of readers is exceeded.
[ "Acquire", "a", "read", "lock", ".", "If", "a", "write", "lock", "has", "been", "acquired", "will", "block", "until", "it", "is", "released", ".", "Will", "not", "block", "if", "other", "read", "locks", "have", "been", "acquired", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L134-L159
train
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.release_read_lock
def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if waiting_writer?(c) && running_readers(c) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
ruby
def release_read_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-1) if waiting_writer?(c) && running_readers(c) == 1 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
[ "def", "release_read_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "-", "1", ")", "if", "waiting_writer?", "(", "c", ")", "&&", "running_readers", "(", "c", ")", "==", "1", "@writer_mutex", ".", "synchronize", "{", "@writer_q", ".", "signal", "}", "end", "break", "end", "end", "true", "end" ]
Release a previously acquired read lock. @return [Boolean] True if the lock is successfully released.
[ "Release", "a", "previously", "acquired", "read", "lock", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L166-L177
train
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.acquire_write_lock
def acquire_write_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many writer threads' if max_writers?(c) if c == 0 break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) @writer_mutex.synchronize do c = @counter.value if running_writer?(c) || running_readers?(c) @writer_q.wait(@writer_mutex) end end c = @counter.value break if !running_writer?(c) && !running_readers?(c) && @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER) end break end end true end
ruby
def acquire_write_lock while(true) c = @counter.value raise ResourceLimitError, 'Too many writer threads' if max_writers?(c) if c == 0 break if @counter.compare_and_swap(0,RUNNING_WRITER) elsif @counter.compare_and_swap(c,c+WAITING_WRITER) while(true) @writer_mutex.synchronize do c = @counter.value if running_writer?(c) || running_readers?(c) @writer_q.wait(@writer_mutex) end end c = @counter.value break if !running_writer?(c) && !running_readers?(c) && @counter.compare_and_swap(c,c+RUNNING_WRITER-WAITING_WRITER) end break end end true end
[ "def", "acquire_write_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "raise", "ResourceLimitError", ",", "'Too many writer threads'", "if", "max_writers?", "(", "c", ")", "if", "c", "==", "0", "break", "if", "@counter", ".", "compare_and_swap", "(", "0", ",", "RUNNING_WRITER", ")", "elsif", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "WAITING_WRITER", ")", "while", "(", "true", ")", "@writer_mutex", ".", "synchronize", "do", "c", "=", "@counter", ".", "value", "if", "running_writer?", "(", "c", ")", "||", "running_readers?", "(", "c", ")", "@writer_q", ".", "wait", "(", "@writer_mutex", ")", "end", "end", "c", "=", "@counter", ".", "value", "break", "if", "!", "running_writer?", "(", "c", ")", "&&", "!", "running_readers?", "(", "c", ")", "&&", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "+", "RUNNING_WRITER", "-", "WAITING_WRITER", ")", "end", "break", "end", "end", "true", "end" ]
Acquire a write lock. Will block and wait for all active readers and writers. @return [Boolean] True if the lock is successfully acquired. @raise [Garcon::ResourceLimitError] If the maximum number of writers is exceeded.
[ "Acquire", "a", "write", "lock", ".", "Will", "block", "and", "wait", "for", "all", "active", "readers", "and", "writers", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L188-L212
train
riddopic/garcun
lib/garcon/task/read_write_lock.rb
Garcon.ReadWriteLock.release_write_lock
def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) @reader_mutex.synchronize { @reader_q.broadcast } if waiting_writers(c) > 0 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
ruby
def release_write_lock while(true) c = @counter.value if @counter.compare_and_swap(c,c-RUNNING_WRITER) @reader_mutex.synchronize { @reader_q.broadcast } if waiting_writers(c) > 0 @writer_mutex.synchronize { @writer_q.signal } end break end end true end
[ "def", "release_write_lock", "while", "(", "true", ")", "c", "=", "@counter", ".", "value", "if", "@counter", ".", "compare_and_swap", "(", "c", ",", "c", "-", "RUNNING_WRITER", ")", "@reader_mutex", ".", "synchronize", "{", "@reader_q", ".", "broadcast", "}", "if", "waiting_writers", "(", "c", ")", ">", "0", "@writer_mutex", ".", "synchronize", "{", "@writer_q", ".", "signal", "}", "end", "break", "end", "end", "true", "end" ]
Release a previously acquired write lock. @return [Boolean] True if the lock is successfully released.
[ "Release", "a", "previously", "acquired", "write", "lock", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/read_write_lock.rb#L219-L231
train
jackc/command_model
lib/command_model/model.rb
CommandModel.Model.parameters
def parameters self.class.parameters.each_with_object({}) do |parameter, hash| hash[parameter.name] = send(parameter.name) end end
ruby
def parameters self.class.parameters.each_with_object({}) do |parameter, hash| hash[parameter.name] = send(parameter.name) end end
[ "def", "parameters", "self", ".", "class", ".", "parameters", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "parameter", ",", "hash", "|", "hash", "[", "parameter", ".", "name", "]", "=", "send", "(", "parameter", ".", "name", ")", "end", "end" ]
Returns hash of all parameter names and values
[ "Returns", "hash", "of", "all", "parameter", "names", "and", "values" ]
9c97ce7c9a51801c28b1b923396bad81505bf5dc
https://github.com/jackc/command_model/blob/9c97ce7c9a51801c28b1b923396bad81505bf5dc/lib/command_model/model.rb#L171-L175
train
neuron-digital/models_auditor
lib/models_auditor/controller.rb
ModelsAuditor.Controller.user_for_models_auditor
def user_for_models_auditor user = case when defined?(current_user) current_user when defined?(current_employee) current_employee else return end ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id) rescue NoMethodError user end
ruby
def user_for_models_auditor user = case when defined?(current_user) current_user when defined?(current_employee) current_employee else return end ActiveSupport::VERSION::MAJOR >= 4 ? user.try!(:id) : user.try(:id) rescue NoMethodError user end
[ "def", "user_for_models_auditor", "user", "=", "case", "when", "defined?", "(", "current_user", ")", "current_user", "when", "defined?", "(", "current_employee", ")", "current_employee", "else", "return", "end", "ActiveSupport", "::", "VERSION", "::", "MAJOR", ">=", "4", "?", "user", ".", "try!", "(", ":id", ")", ":", "user", ".", "try", "(", ":id", ")", "rescue", "NoMethodError", "user", "end" ]
Returns the user who is responsible for any changes that occur. By default this calls `current_user` or `current_employee` and returns the result. Override this method in your controller to call a different method, e.g. `current_person`, or anything you like.
[ "Returns", "the", "user", "who", "is", "responsible", "for", "any", "changes", "that", "occur", ".", "By", "default", "this", "calls", "current_user", "or", "current_employee", "and", "returns", "the", "result", "." ]
f5cf07416a7a7f7473fcc4dabc86f2300b76de7b
https://github.com/neuron-digital/models_auditor/blob/f5cf07416a7a7f7473fcc4dabc86f2300b76de7b/lib/models_auditor/controller.rb#L37-L50
train
neuron-digital/models_auditor
lib/models_auditor/controller.rb
ModelsAuditor.Controller.info_for_models_auditor
def info_for_models_auditor { ip: request.remote_ip, user_agent: request.user_agent, controller: self.class.name, action: action_name, path: request.path_info } end
ruby
def info_for_models_auditor { ip: request.remote_ip, user_agent: request.user_agent, controller: self.class.name, action: action_name, path: request.path_info } end
[ "def", "info_for_models_auditor", "{", "ip", ":", "request", ".", "remote_ip", ",", "user_agent", ":", "request", ".", "user_agent", ",", "controller", ":", "self", ".", "class", ".", "name", ",", "action", ":", "action_name", ",", "path", ":", "request", ".", "path_info", "}", "end" ]
Returns any information about the controller or request that you want ModelsAuditor to store alongside any changes that occur. By default this returns an empty hash. Override this method in your controller to return a hash of any information you need. The hash's keys must correspond to columns in your `auditor_requests` table, so don't forget to add any new columns you need. For example: {:ip => request.remote_ip, :user_agent => request.user_agent} The columns `ip` and `user_agent` must exist in your `versions` # table. Use the `:meta` option to `PaperTrail::Model::ClassMethods.has_paper_trail` to store any extra model-level data you need.
[ "Returns", "any", "information", "about", "the", "controller", "or", "request", "that", "you", "want", "ModelsAuditor", "to", "store", "alongside", "any", "changes", "that", "occur", ".", "By", "default", "this", "returns", "an", "empty", "hash", "." ]
f5cf07416a7a7f7473fcc4dabc86f2300b76de7b
https://github.com/neuron-digital/models_auditor/blob/f5cf07416a7a7f7473fcc4dabc86f2300b76de7b/lib/models_auditor/controller.rb#L69-L77
train
authrocket/authrocket-ruby
lib/authrocket/credential.rb
AuthRocket.Credential.verify
def verify(code, attribs={}) params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds parsed, _ = request(:post, url+'/verify', params) load(parsed) errors.empty? ? self : false end
ruby
def verify(code, attribs={}) params = parse_request_params(attribs.merge(code: code), json_root: json_root).merge credentials: api_creds parsed, _ = request(:post, url+'/verify', params) load(parsed) errors.empty? ? self : false end
[ "def", "verify", "(", "code", ",", "attribs", "=", "{", "}", ")", "params", "=", "parse_request_params", "(", "attribs", ".", "merge", "(", "code", ":", "code", ")", ",", "json_root", ":", "json_root", ")", ".", "merge", "credentials", ":", "api_creds", "parsed", ",", "_", "=", "request", "(", ":post", ",", "url", "+", "'/verify'", ",", "params", ")", "load", "(", "parsed", ")", "errors", ".", "empty?", "?", "self", ":", "false", "end" ]
code - required
[ "code", "-", "required" ]
6a0496035b219e6d0acbee24b1b483051c57b1ef
https://github.com/authrocket/authrocket-ruby/blob/6a0496035b219e6d0acbee24b1b483051c57b1ef/lib/authrocket/credential.rb#L16-L21
train
kindlinglabs/bullring
lib/bullring/workers/rhino_server.rb
Bullring.RhinoServer.fetch_library
def fetch_library(name) library_script = @server_registry['library', name] logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found."} raise NameError, "Server cannot find a script named #{name}" if library_script.nil? library_script end
ruby
def fetch_library(name) library_script = @server_registry['library', name] logger.debug {"#{logname}: Tried to fetch script '#{name}' from the registry and it " + "was #{'not ' if library_script.nil?}found."} raise NameError, "Server cannot find a script named #{name}" if library_script.nil? library_script end
[ "def", "fetch_library", "(", "name", ")", "library_script", "=", "@server_registry", "[", "'library'", ",", "name", "]", "logger", ".", "debug", "{", "\"#{logname}: Tried to fetch script '#{name}' from the registry and it \"", "+", "\"was #{'not ' if library_script.nil?}found.\"", "}", "raise", "NameError", ",", "\"Server cannot find a script named #{name}\"", "if", "library_script", ".", "nil?", "library_script", "end" ]
Grab the library from the registry server
[ "Grab", "the", "library", "from", "the", "registry", "server" ]
30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44
https://github.com/kindlinglabs/bullring/blob/30ea55f7ad3de4c8af710d141cf5dfda0f9c8a44/lib/bullring/workers/rhino_server.rb#L147-L156
train
jakewendt/rails_extension
lib/rails_extension/action_controller_extension/accessible_via_user.rb
RailsExtension::ActionControllerExtension::AccessibleViaUser.ClassMethods.assert_access_without_login
def assert_access_without_login(*actions) user_options = actions.extract_options! options = {} if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') ) options.merge!(self::ASSERT_ACCESS_OPTIONS) end options.merge!(user_options) actions += options[:actions]||[] m_key = options[:model].try(:underscore).try(:to_sym) test "#{brand}AWoL should get new without login" do get :new assert_response :success assert_template 'new' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:new) || options.keys.include?(:new) test "#{brand}AWoL should post create without login" do args = if options[:create] options[:create] elsif options[:attributes_for_create] {m_key => send(options[:attributes_for_create])} else {} end assert_difference("#{options[:model]}.count",1) do send(:post,:create,args) end assert_response :redirect assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:create) || options.keys.include?(:create) # test "should NOT get edit without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # send(:get,:edit, *args) # assert_redirected_to_login # end if actions.include?(:edit) || options.keys.include?(:edit) # # test "should NOT put update without login" do # args={} # if options[:factory] # obj = Factory(options[:factory]) # args[:id] = obj.id # args[options[:factory]] = Factory.attributes_for(options[:factory]) # end # send(:put,:update, args) # assert_redirected_to_login # end if actions.include?(:update) || options.keys.include?(:update) test "#{brand}AWoL should get show without login" do args={} if options[:method_for_create] obj = send(options[:method_for_create]) args[:id] = obj.id end send(:get,:show, args) assert_response :success assert_template 'show' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:show) || options.keys.include?(:show) # test "should NOT delete destroy without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # assert_no_difference("#{options[:model]}.count") do # send(:delete,:destroy,*args) # end # assert_redirected_to_login # end if actions.include?(:destroy) || options.keys.include?(:destroy) # # test "should NOT get index without login" do # get :index # assert_redirected_to_login # end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login" do get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login and items" do send(options[:before]) if !options[:before].blank? 3.times{ send(options[:method_for_create]) } if !options[:method_for_create].blank? get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) end
ruby
def assert_access_without_login(*actions) user_options = actions.extract_options! options = {} if ( self.constants.include?('ASSERT_ACCESS_OPTIONS') ) options.merge!(self::ASSERT_ACCESS_OPTIONS) end options.merge!(user_options) actions += options[:actions]||[] m_key = options[:model].try(:underscore).try(:to_sym) test "#{brand}AWoL should get new without login" do get :new assert_response :success assert_template 'new' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:new) || options.keys.include?(:new) test "#{brand}AWoL should post create without login" do args = if options[:create] options[:create] elsif options[:attributes_for_create] {m_key => send(options[:attributes_for_create])} else {} end assert_difference("#{options[:model]}.count",1) do send(:post,:create,args) end assert_response :redirect assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:create) || options.keys.include?(:create) # test "should NOT get edit without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # send(:get,:edit, *args) # assert_redirected_to_login # end if actions.include?(:edit) || options.keys.include?(:edit) # # test "should NOT put update without login" do # args={} # if options[:factory] # obj = Factory(options[:factory]) # args[:id] = obj.id # args[options[:factory]] = Factory.attributes_for(options[:factory]) # end # send(:put,:update, args) # assert_redirected_to_login # end if actions.include?(:update) || options.keys.include?(:update) test "#{brand}AWoL should get show without login" do args={} if options[:method_for_create] obj = send(options[:method_for_create]) args[:id] = obj.id end send(:get,:show, args) assert_response :success assert_template 'show' assert assigns(m_key), "#{m_key} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:show) || options.keys.include?(:show) # test "should NOT delete destroy without login" do # args=[] # if options[:factory] # obj = Factory(options[:factory]) # args.push(:id => obj.id) # end # assert_no_difference("#{options[:model]}.count") do # send(:delete,:destroy,*args) # end # assert_redirected_to_login # end if actions.include?(:destroy) || options.keys.include?(:destroy) # # test "should NOT get index without login" do # get :index # assert_redirected_to_login # end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login" do get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) test "#{brand}should get index without login and items" do send(options[:before]) if !options[:before].blank? 3.times{ send(options[:method_for_create]) } if !options[:method_for_create].blank? get :index assert_response :success assert_template 'index' assert assigns(m_key.try(:to_s).try(:pluralize).try(:to_sym)), "#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned." assert_nil flash[:error], "flash[:error] was not nil" end if actions.include?(:index) || options.keys.include?(:index) end
[ "def", "assert_access_without_login", "(", "*", "actions", ")", "user_options", "=", "actions", ".", "extract_options!", "options", "=", "{", "}", "if", "(", "self", ".", "constants", ".", "include?", "(", "'ASSERT_ACCESS_OPTIONS'", ")", ")", "options", ".", "merge!", "(", "self", "::", "ASSERT_ACCESS_OPTIONS", ")", "end", "options", ".", "merge!", "(", "user_options", ")", "actions", "+=", "options", "[", ":actions", "]", "||", "[", "]", "m_key", "=", "options", "[", ":model", "]", ".", "try", "(", ":underscore", ")", ".", "try", "(", ":to_sym", ")", "test", "\"#{brand}AWoL should get new without login\"", "do", "get", ":new", "assert_response", ":success", "assert_template", "'new'", "assert", "assigns", "(", "m_key", ")", ",", "\"#{m_key} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":new", ")", "||", "options", ".", "keys", ".", "include?", "(", ":new", ")", "test", "\"#{brand}AWoL should post create without login\"", "do", "args", "=", "if", "options", "[", ":create", "]", "options", "[", ":create", "]", "elsif", "options", "[", ":attributes_for_create", "]", "{", "m_key", "=>", "send", "(", "options", "[", ":attributes_for_create", "]", ")", "}", "else", "{", "}", "end", "assert_difference", "(", "\"#{options[:model]}.count\"", ",", "1", ")", "do", "send", "(", ":post", ",", ":create", ",", "args", ")", "end", "assert_response", ":redirect", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":create", ")", "||", "options", ".", "keys", ".", "include?", "(", ":create", ")", "test", "\"#{brand}AWoL should get show without login\"", "do", "args", "=", "{", "}", "if", "options", "[", ":method_for_create", "]", "obj", "=", "send", "(", "options", "[", ":method_for_create", "]", ")", "args", "[", ":id", "]", "=", "obj", ".", "id", "end", "send", "(", ":get", ",", ":show", ",", "args", ")", "assert_response", ":success", "assert_template", "'show'", "assert", "assigns", "(", "m_key", ")", ",", "\"#{m_key} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":show", ")", "||", "options", ".", "keys", ".", "include?", "(", ":show", ")", "test", "\"#{brand}should get index without login\"", "do", "get", ":index", "assert_response", ":success", "assert_template", "'index'", "assert", "assigns", "(", "m_key", ".", "try", "(", ":to_s", ")", ".", "try", "(", ":pluralize", ")", ".", "try", "(", ":to_sym", ")", ")", ",", "\"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":index", ")", "||", "options", ".", "keys", ".", "include?", "(", ":index", ")", "test", "\"#{brand}should get index without login and items\"", "do", "send", "(", "options", "[", ":before", "]", ")", "if", "!", "options", "[", ":before", "]", ".", "blank?", "3", ".", "times", "{", "send", "(", "options", "[", ":method_for_create", "]", ")", "}", "if", "!", "options", "[", ":method_for_create", "]", ".", "blank?", "get", ":index", "assert_response", ":success", "assert_template", "'index'", "assert", "assigns", "(", "m_key", ".", "try", "(", ":to_s", ")", ".", "try", "(", ":pluralize", ")", ".", "try", "(", ":to_sym", ")", ")", ",", "\"#{m_key.try(:to_s).try(:pluralize).try(:to_sym)} was not assigned.\"", "assert_nil", "flash", "[", ":error", "]", ",", "\"flash[:error] was not nil\"", "end", "if", "actions", ".", "include?", "(", ":index", ")", "||", "options", ".", "keys", ".", "include?", "(", ":index", ")", "end" ]
I can't imagine a whole lot of use for this one.
[ "I", "can", "t", "imagine", "a", "whole", "lot", "of", "use", "for", "this", "one", "." ]
310774fea4a07821aee8f87b9f30d2b4b0bbe548
https://github.com/jakewendt/rails_extension/blob/310774fea4a07821aee8f87b9f30d2b4b0bbe548/lib/rails_extension/action_controller_extension/accessible_via_user.rb#L279-L385
train
jinx/json
lib/jinx/json/collection.rb
Jinx.Collection.to_json
def to_json(state=nil) # Make a new State from the options if this is a top-level call. state = JSON::State.for(state) unless JSON::State === state to_a.to_json(state) end
ruby
def to_json(state=nil) # Make a new State from the options if this is a top-level call. state = JSON::State.for(state) unless JSON::State === state to_a.to_json(state) end
[ "def", "to_json", "(", "state", "=", "nil", ")", "state", "=", "JSON", "::", "State", ".", "for", "(", "state", ")", "unless", "JSON", "::", "State", "===", "state", "to_a", ".", "to_json", "(", "state", ")", "end" ]
Adds JSON serialization to collections. @param [State, Hash, nil] state the JSON state or serialization options @return [String] the JSON representation of this {Jinx::Resource}
[ "Adds", "JSON", "serialization", "to", "collections", "." ]
b9d596e3d1d56076182003104a5e363216357873
https://github.com/jinx/json/blob/b9d596e3d1d56076182003104a5e363216357873/lib/jinx/json/collection.rb#L10-L14
train
Raybeam/myreplicator
app/models/myreplicator/export.rb
Myreplicator.Export.export
def export Log.run(:job_type => "export", :name => schedule_name, :file => filename, :export_id => id) do |log| exporter = MysqlExporter.new exporter.export_table self # pass current object to exporter end end
ruby
def export Log.run(:job_type => "export", :name => schedule_name, :file => filename, :export_id => id) do |log| exporter = MysqlExporter.new exporter.export_table self # pass current object to exporter end end
[ "def", "export", "Log", ".", "run", "(", ":job_type", "=>", "\"export\"", ",", ":name", "=>", "schedule_name", ",", ":file", "=>", "filename", ",", ":export_id", "=>", "id", ")", "do", "|", "log", "|", "exporter", "=", "MysqlExporter", ".", "new", "exporter", ".", "export_table", "self", "end", "end" ]
Runs the export process using the required Exporter library
[ "Runs", "the", "export", "process", "using", "the", "required", "Exporter", "library" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/export.rb#L69-L75
train
Raybeam/myreplicator
app/models/myreplicator/export.rb
Myreplicator.Export.is_running?
def is_running? return false if state != "exporting" begin Process.getpgid(exporter_pid) raise Exceptions::ExportIgnored.new("Ignored") rescue Errno::ESRCH return false end end
ruby
def is_running? return false if state != "exporting" begin Process.getpgid(exporter_pid) raise Exceptions::ExportIgnored.new("Ignored") rescue Errno::ESRCH return false end end
[ "def", "is_running?", "return", "false", "if", "state", "!=", "\"exporting\"", "begin", "Process", ".", "getpgid", "(", "exporter_pid", ")", "raise", "Exceptions", "::", "ExportIgnored", ".", "new", "(", "\"Ignored\"", ")", "rescue", "Errno", "::", "ESRCH", "return", "false", "end", "end" ]
Throws ExportIgnored if the job is still running Checks the state of the job using PID and state
[ "Throws", "ExportIgnored", "if", "the", "job", "is", "still", "running", "Checks", "the", "state", "of", "the", "job", "using", "PID", "and", "state" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/app/models/myreplicator/export.rb#L280-L288
train
chef-workflow/furnish-ssh
lib/furnish/ssh.rb
Furnish.SSH.run
def run(cmd) ret = { :exit_status => 0, :stdout => "", :stderr => "" } port = ssh_args[:port] Net::SSH.start(host, username, ssh_args) do |ssh| ssh.open_channel do |ch| if stdin ch.send_data(stdin) ch.eof! end if require_pty ch.request_pty do |ch, success| unless success raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one." end end end ch.on_open_failed do |ch, code, desc| raise "Connection Error to #{username}@#{host}: #{desc}" end ch.exec(cmd) do |ch, success| unless success raise "Could not execute command '#{cmd}' on #{username}@#{host}" end if merge_output ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| if type == 1 log(host, port, data) ret[:stdout] << data end end else ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| ret[:stderr] << data if type == 1 end end ch.on_request("exit-status") do |ch, data| ret[:exit_status] = data.read_long end end end ssh.loop end return ret end
ruby
def run(cmd) ret = { :exit_status => 0, :stdout => "", :stderr => "" } port = ssh_args[:port] Net::SSH.start(host, username, ssh_args) do |ssh| ssh.open_channel do |ch| if stdin ch.send_data(stdin) ch.eof! end if require_pty ch.request_pty do |ch, success| unless success raise "The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one." end end end ch.on_open_failed do |ch, code, desc| raise "Connection Error to #{username}@#{host}: #{desc}" end ch.exec(cmd) do |ch, success| unless success raise "Could not execute command '#{cmd}' on #{username}@#{host}" end if merge_output ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| if type == 1 log(host, port, data) ret[:stdout] << data end end else ch.on_data do |ch, data| log(host, port, data) ret[:stdout] << data end ch.on_extended_data do |ch, type, data| ret[:stderr] << data if type == 1 end end ch.on_request("exit-status") do |ch, data| ret[:exit_status] = data.read_long end end end ssh.loop end return ret end
[ "def", "run", "(", "cmd", ")", "ret", "=", "{", ":exit_status", "=>", "0", ",", ":stdout", "=>", "\"\"", ",", ":stderr", "=>", "\"\"", "}", "port", "=", "ssh_args", "[", ":port", "]", "Net", "::", "SSH", ".", "start", "(", "host", ",", "username", ",", "ssh_args", ")", "do", "|", "ssh", "|", "ssh", ".", "open_channel", "do", "|", "ch", "|", "if", "stdin", "ch", ".", "send_data", "(", "stdin", ")", "ch", ".", "eof!", "end", "if", "require_pty", "ch", ".", "request_pty", "do", "|", "ch", ",", "success", "|", "unless", "success", "raise", "\"The use_sudo setting requires a PTY, and your SSH is rejecting our attempt to get one.\"", "end", "end", "end", "ch", ".", "on_open_failed", "do", "|", "ch", ",", "code", ",", "desc", "|", "raise", "\"Connection Error to #{username}@#{host}: #{desc}\"", "end", "ch", ".", "exec", "(", "cmd", ")", "do", "|", "ch", ",", "success", "|", "unless", "success", "raise", "\"Could not execute command '#{cmd}' on #{username}@#{host}\"", "end", "if", "merge_output", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "ch", ".", "on_extended_data", "do", "|", "ch", ",", "type", ",", "data", "|", "if", "type", "==", "1", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "end", "else", "ch", ".", "on_data", "do", "|", "ch", ",", "data", "|", "log", "(", "host", ",", "port", ",", "data", ")", "ret", "[", ":stdout", "]", "<<", "data", "end", "ch", ".", "on_extended_data", "do", "|", "ch", ",", "type", ",", "data", "|", "ret", "[", ":stderr", "]", "<<", "data", "if", "type", "==", "1", "end", "end", "ch", ".", "on_request", "(", "\"exit-status\"", ")", "do", "|", "ch", ",", "data", "|", "ret", "[", ":exit_status", "]", "=", "data", ".", "read_long", "end", "end", "end", "ssh", ".", "loop", "end", "return", "ret", "end" ]
Run the command on the remote host. Return value is a hash of symbol -> value, where symbol might be: * :stdout -- the standard output of the run. if #merge_output is supplied, this will be all the output. Will be an empty string by default. * :stderr -- standard error. Will be an empty string by default. * :exit_status -- the exit status. Will be zero by default.
[ "Run", "the", "command", "on", "the", "remote", "host", "." ]
1e2e2f720456f522a4d738134280701c6932f3a1
https://github.com/chef-workflow/furnish-ssh/blob/1e2e2f720456f522a4d738134280701c6932f3a1/lib/furnish/ssh.rb#L112-L178
train
jeremiahishere/trackable_tasks
app/models/trackable_tasks/task_run.rb
TrackableTasks.TaskRun.run_time_or_time_elapsed
def run_time_or_time_elapsed if self.end_time return Time.at(self.end_time - self.start_time) else return Time.at(Time.now - self.start_time) end end
ruby
def run_time_or_time_elapsed if self.end_time return Time.at(self.end_time - self.start_time) else return Time.at(Time.now - self.start_time) end end
[ "def", "run_time_or_time_elapsed", "if", "self", ".", "end_time", "return", "Time", ".", "at", "(", "self", ".", "end_time", "-", "self", ".", "start_time", ")", "else", "return", "Time", ".", "at", "(", "Time", ".", "now", "-", "self", ".", "start_time", ")", "end", "end" ]
Creates run time based on start and end time If there is no end_time, returns time between start and now @return [Time] The run time object
[ "Creates", "run", "time", "based", "on", "start", "and", "end", "time", "If", "there", "is", "no", "end_time", "returns", "time", "between", "start", "and", "now" ]
8702672a7b38efa936fd285a0025e04e4b025908
https://github.com/jeremiahishere/trackable_tasks/blob/8702672a7b38efa936fd285a0025e04e4b025908/app/models/trackable_tasks/task_run.rb#L90-L96
train
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_label
def extra_label(index) return nil if index < 1 || index > 5 txt = send("extra_#{index}_label") txt = extra_name(index).to_s.humanize.capitalize if txt.blank? txt end
ruby
def extra_label(index) return nil if index < 1 || index > 5 txt = send("extra_#{index}_label") txt = extra_name(index).to_s.humanize.capitalize if txt.blank? txt end
[ "def", "extra_label", "(", "index", ")", "return", "nil", "if", "index", "<", "1", "||", "index", ">", "5", "txt", "=", "send", "(", "\"extra_#{index}_label\"", ")", "txt", "=", "extra_name", "(", "index", ")", ".", "to_s", ".", "humanize", ".", "capitalize", "if", "txt", ".", "blank?", "txt", "end" ]
Gets the label for an extra value.
[ "Gets", "the", "label", "for", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L98-L103
train
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_field_type
def extra_field_type(index) t = extra_type(index).to_s case t when 'password' 'password' when 'integer', 'float' 'number' when 'boolean' 'checkbox' else if t.downcase.index('in:') 'select' else 'text' end end end
ruby
def extra_field_type(index) t = extra_type(index).to_s case t when 'password' 'password' when 'integer', 'float' 'number' when 'boolean' 'checkbox' else if t.downcase.index('in:') 'select' else 'text' end end end
[ "def", "extra_field_type", "(", "index", ")", "t", "=", "extra_type", "(", "index", ")", ".", "to_s", "case", "t", "when", "'password'", "'password'", "when", "'integer'", ",", "'float'", "'number'", "when", "'boolean'", "'checkbox'", "else", "if", "t", ".", "downcase", ".", "index", "(", "'in:'", ")", "'select'", "else", "'text'", "end", "end", "end" ]
Gets the field type for an extra value.
[ "Gets", "the", "field", "type", "for", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L114-L130
train
barkerest/barkest_core
app/models/barkest_core/database_config.rb
BarkestCore.DatabaseConfig.extra_value
def extra_value(index, convert = false) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type(index) when 'boolean' BarkestCore::BooleanParser.parse_for_boolean_column(val) when 'integer' BarkestCore::NumberParser.parse_for_int_column(val) when 'float' BarkestCore::NumberParser.parse_for_float_column(val) else val.to_s end end end
ruby
def extra_value(index, convert = false) return nil if index < 1 || index > 5 val = send "extra_#{index}_value" if convert case extra_type(index) when 'boolean' BarkestCore::BooleanParser.parse_for_boolean_column(val) when 'integer' BarkestCore::NumberParser.parse_for_int_column(val) when 'float' BarkestCore::NumberParser.parse_for_float_column(val) else val.to_s end end end
[ "def", "extra_value", "(", "index", ",", "convert", "=", "false", ")", "return", "nil", "if", "index", "<", "1", "||", "index", ">", "5", "val", "=", "send", "\"extra_#{index}_value\"", "if", "convert", "case", "extra_type", "(", "index", ")", "when", "'boolean'", "BarkestCore", "::", "BooleanParser", ".", "parse_for_boolean_column", "(", "val", ")", "when", "'integer'", "BarkestCore", "::", "NumberParser", ".", "parse_for_int_column", "(", "val", ")", "when", "'float'", "BarkestCore", "::", "NumberParser", ".", "parse_for_float_column", "(", "val", ")", "else", "val", ".", "to_s", "end", "end", "end" ]
Gets an extra value.
[ "Gets", "an", "extra", "value", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/database_config.rb#L144-L159
train
codez/mail_relay
lib/mail_relay/base.rb
MailRelay.Base.resend_to
def resend_to(destinations) if destinations.size > 0 message.smtp_envelope_to = destinations # Set envelope from and sender to local server to satisfy SPF: # http://www.openspf.org/Best_Practices/Webgenerated message.sender = envelope_sender message.smtp_envelope_from = envelope_sender # set list headers message.header['Precedence'] = 'list' message.header['List-Id'] = list_id deliver(message) end end
ruby
def resend_to(destinations) if destinations.size > 0 message.smtp_envelope_to = destinations # Set envelope from and sender to local server to satisfy SPF: # http://www.openspf.org/Best_Practices/Webgenerated message.sender = envelope_sender message.smtp_envelope_from = envelope_sender # set list headers message.header['Precedence'] = 'list' message.header['List-Id'] = list_id deliver(message) end end
[ "def", "resend_to", "(", "destinations", ")", "if", "destinations", ".", "size", ">", "0", "message", ".", "smtp_envelope_to", "=", "destinations", "message", ".", "sender", "=", "envelope_sender", "message", ".", "smtp_envelope_from", "=", "envelope_sender", "message", ".", "header", "[", "'Precedence'", "]", "=", "'list'", "message", ".", "header", "[", "'List-Id'", "]", "=", "list_id", "deliver", "(", "message", ")", "end", "end" ]
Send the same mail as is to all receivers, if any.
[ "Send", "the", "same", "mail", "as", "is", "to", "all", "receivers", "if", "any", "." ]
0ee7e5e7affea62b2338ad11d3bbe3e44448e968
https://github.com/codez/mail_relay/blob/0ee7e5e7affea62b2338ad11d3bbe3e44448e968/lib/mail_relay/base.rb#L64-L79
train
codez/mail_relay
lib/mail_relay/base.rb
MailRelay.Base.receiver_from_received_header
def receiver_from_received_header if received = message.received received = received.first if received.respond_to?(:first) received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1] end end
ruby
def receiver_from_received_header if received = message.received received = received.first if received.respond_to?(:first) received.info[/ for .*?([^\s<>]+)@[^\s<>]+/, 1] end end
[ "def", "receiver_from_received_header", "if", "received", "=", "message", ".", "received", "received", "=", "received", ".", "first", "if", "received", ".", "respond_to?", "(", ":first", ")", "received", ".", "info", "[", "/", "\\s", "\\s", "/", ",", "1", "]", "end", "end" ]
Heuristic method to find actual receiver of the message. May return nil if could not determine.
[ "Heuristic", "method", "to", "find", "actual", "receiver", "of", "the", "message", ".", "May", "return", "nil", "if", "could", "not", "determine", "." ]
0ee7e5e7affea62b2338ad11d3bbe3e44448e968
https://github.com/codez/mail_relay/blob/0ee7e5e7affea62b2338ad11d3bbe3e44448e968/lib/mail_relay/base.rb#L110-L115
train
rogerleite/http_monkey
lib/http_monkey/client/environment.rb
HttpMonkey.Client::Environment.uri=
def uri=(uri) self['SERVER_NAME'] = uri.host self['SERVER_PORT'] = uri.port.to_s self['QUERY_STRING'] = (uri.query || "") self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path self['rack.url_scheme'] = uri.scheme self['HTTPS'] = (uri.scheme == "https" ? "on" : "off") self['REQUEST_URI'] = uri.request_uri self['HTTP_HOST'] = uri.host end
ruby
def uri=(uri) self['SERVER_NAME'] = uri.host self['SERVER_PORT'] = uri.port.to_s self['QUERY_STRING'] = (uri.query || "") self['PATH_INFO'] = (!uri.path || uri.path.empty?) ? "/" : uri.path self['rack.url_scheme'] = uri.scheme self['HTTPS'] = (uri.scheme == "https" ? "on" : "off") self['REQUEST_URI'] = uri.request_uri self['HTTP_HOST'] = uri.host end
[ "def", "uri", "=", "(", "uri", ")", "self", "[", "'SERVER_NAME'", "]", "=", "uri", ".", "host", "self", "[", "'SERVER_PORT'", "]", "=", "uri", ".", "port", ".", "to_s", "self", "[", "'QUERY_STRING'", "]", "=", "(", "uri", ".", "query", "||", "\"\"", ")", "self", "[", "'PATH_INFO'", "]", "=", "(", "!", "uri", ".", "path", "||", "uri", ".", "path", ".", "empty?", ")", "?", "\"/\"", ":", "uri", ".", "path", "self", "[", "'rack.url_scheme'", "]", "=", "uri", ".", "scheme", "self", "[", "'HTTPS'", "]", "=", "(", "uri", ".", "scheme", "==", "\"https\"", "?", "\"on\"", ":", "\"off\"", ")", "self", "[", "'REQUEST_URI'", "]", "=", "uri", ".", "request_uri", "self", "[", "'HTTP_HOST'", "]", "=", "uri", ".", "host", "end" ]
Sets uri as Rack wants.
[ "Sets", "uri", "as", "Rack", "wants", "." ]
b57a972e97c60a017754200eef2094562ca546ef
https://github.com/rogerleite/http_monkey/blob/b57a972e97c60a017754200eef2094562ca546ef/lib/http_monkey/client/environment.rb#L62-L71
train
rogerleite/http_monkey
lib/http_monkey/client/environment.rb
HttpMonkey.Client::Environment.uri
def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI.parse(uri) rescue StandardError => e raise ArgumentError, "Invalid #{uri}", e.backtrace end end
ruby
def uri uri = %Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}} begin URI.parse(uri) rescue StandardError => e raise ArgumentError, "Invalid #{uri}", e.backtrace end end
[ "def", "uri", "uri", "=", "%Q{#{self['rack.url_scheme']}://#{self['SERVER_NAME']}:#{self['SERVER_PORT']}#{self['REQUEST_URI']}}", "begin", "URI", ".", "parse", "(", "uri", ")", "rescue", "StandardError", "=>", "e", "raise", "ArgumentError", ",", "\"Invalid #{uri}\"", ",", "e", ".", "backtrace", "end", "end" ]
Returns uri from Rack environment. Throws ArgumentError for invalid uri.
[ "Returns", "uri", "from", "Rack", "environment", ".", "Throws", "ArgumentError", "for", "invalid", "uri", "." ]
b57a972e97c60a017754200eef2094562ca546ef
https://github.com/rogerleite/http_monkey/blob/b57a972e97c60a017754200eef2094562ca546ef/lib/http_monkey/client/environment.rb#L75-L82
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/menus_controller.rb
Roroacms.Admin::MenusController.edit
def edit @menu = Menu.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name) set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name)) end
ruby
def edit @menu = Menu.find(params[:id]) # add breadcrumb and set title add_breadcrumb I18n.t("controllers.admin.menus.edit.breadcrumb", menu_name: @menu.name) set_title(I18n.t("controllers.admin.menus.edit.title", menu_name: @menu.name)) end
[ "def", "edit", "@menu", "=", "Menu", ".", "find", "(", "params", "[", ":id", "]", ")", "add_breadcrumb", "I18n", ".", "t", "(", "\"controllers.admin.menus.edit.breadcrumb\"", ",", "menu_name", ":", "@menu", ".", "name", ")", "set_title", "(", "I18n", ".", "t", "(", "\"controllers.admin.menus.edit.title\"", ",", "menu_name", ":", "@menu", ".", "name", ")", ")", "end" ]
get menu object and display it for editing
[ "get", "menu", "object", "and", "display", "it", "for", "editing" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/menus_controller.rb#L43-L49
train
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/menus_controller.rb
Roroacms.Admin::MenusController.destroy
def destroy @menu = Menu.find(params[:id]) @menu.destroy respond_to do |format| format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") } end end
ruby
def destroy @menu = Menu.find(params[:id]) @menu.destroy respond_to do |format| format.html { redirect_to admin_menus_path, notice: I18n.t("controllers.admin.menus.destroy.flash.success") } end end
[ "def", "destroy", "@menu", "=", "Menu", ".", "find", "(", "params", "[", ":id", "]", ")", "@menu", ".", "destroy", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "admin_menus_path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.menus.destroy.flash.success\"", ")", "}", "end", "end" ]
deletes the whole menu. Although there is a delete button on each menu option this just removes it from the list which is then interpreted when you save the menu as a whole.
[ "deletes", "the", "whole", "menu", ".", "Although", "there", "is", "a", "delete", "button", "on", "each", "menu", "option", "this", "just", "removes", "it", "from", "the", "list", "which", "is", "then", "interpreted", "when", "you", "save", "the", "menu", "as", "a", "whole", "." ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/menus_controller.rb#L55-L62
train
tongueroo/chap
lib/chap/hook.rb
Chap.Hook.symlink_configs
def symlink_configs paths = Dir.glob("#{shared_path}/config/**/*"). select {|p| File.file?(p) } paths.each do |src| relative_path = src.gsub(%r{.*config/},'config/') dest = "#{release_path}/#{relative_path}" # make sure the directory exist for symlink creation dirname = File.dirname(dest) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) FileUtils.rm_rf(dest) if File.exist?(dest) FileUtils.ln_s(src,dest) end end
ruby
def symlink_configs paths = Dir.glob("#{shared_path}/config/**/*"). select {|p| File.file?(p) } paths.each do |src| relative_path = src.gsub(%r{.*config/},'config/') dest = "#{release_path}/#{relative_path}" # make sure the directory exist for symlink creation dirname = File.dirname(dest) FileUtils.mkdir_p(dirname) unless File.exist?(dirname) FileUtils.rm_rf(dest) if File.exist?(dest) FileUtils.ln_s(src,dest) end end
[ "def", "symlink_configs", "paths", "=", "Dir", ".", "glob", "(", "\"#{shared_path}/config/**/*\"", ")", ".", "select", "{", "|", "p", "|", "File", ".", "file?", "(", "p", ")", "}", "paths", ".", "each", "do", "|", "src", "|", "relative_path", "=", "src", ".", "gsub", "(", "%r{", "}", ",", "'config/'", ")", "dest", "=", "\"#{release_path}/#{relative_path}\"", "dirname", "=", "File", ".", "dirname", "(", "dest", ")", "FileUtils", ".", "mkdir_p", "(", "dirname", ")", "unless", "File", ".", "exist?", "(", "dirname", ")", "FileUtils", ".", "rm_rf", "(", "dest", ")", "if", "File", ".", "exist?", "(", "dest", ")", "FileUtils", ".", "ln_s", "(", "src", ",", "dest", ")", "end", "end" ]
hook helper methods
[ "hook", "helper", "methods" ]
317cebeace6cbae793ecd0e4a3d357c671ac1106
https://github.com/tongueroo/chap/blob/317cebeace6cbae793ecd0e4a3d357c671ac1106/lib/chap/hook.rb#L18-L30
train
skellock/motion-mastr
lib/motion-mastr/mastr_builder.rb
MotionMastr.MastrBuilder.apply_attributes
def apply_attributes(attributed_string, start, length, styles) return unless attributed_string && start && length && styles # sanity return unless start >= 0 && length > 0 && styles.length > 0 # minimums return unless start + length <= attributed_string.length # maximums range = [start, length] ATTRIBUTES.each_pair do |method_name, attribute_name| value = send method_name, styles attributed_string.addAttribute(attribute_name, value: value, range: range) if value end end
ruby
def apply_attributes(attributed_string, start, length, styles) return unless attributed_string && start && length && styles # sanity return unless start >= 0 && length > 0 && styles.length > 0 # minimums return unless start + length <= attributed_string.length # maximums range = [start, length] ATTRIBUTES.each_pair do |method_name, attribute_name| value = send method_name, styles attributed_string.addAttribute(attribute_name, value: value, range: range) if value end end
[ "def", "apply_attributes", "(", "attributed_string", ",", "start", ",", "length", ",", "styles", ")", "return", "unless", "attributed_string", "&&", "start", "&&", "length", "&&", "styles", "return", "unless", "start", ">=", "0", "&&", "length", ">", "0", "&&", "styles", ".", "length", ">", "0", "return", "unless", "start", "+", "length", "<=", "attributed_string", ".", "length", "range", "=", "[", "start", ",", "length", "]", "ATTRIBUTES", ".", "each_pair", "do", "|", "method_name", ",", "attribute_name", "|", "value", "=", "send", "method_name", ",", "styles", "attributed_string", ".", "addAttribute", "(", "attribute_name", ",", "value", ":", "value", ",", "range", ":", "range", ")", "if", "value", "end", "end" ]
applies styles in a range to the attributed string
[ "applies", "styles", "in", "a", "range", "to", "the", "attributed", "string" ]
db95803be3a7865f967ad7499dff4e2d0aee8570
https://github.com/skellock/motion-mastr/blob/db95803be3a7865f967ad7499dff4e2d0aee8570/lib/motion-mastr/mastr_builder.rb#L72-L83
train
rsanders/transaction_reliability
lib/transaction_reliability.rb
TransactionReliability.Helpers.with_transaction_retry
def with_transaction_retry(options = {}) retry_count = options.fetch(:retry_count, 4) backoff = options.fetch(:backoff, 0.25) exit_on_fail = options.fetch(:exit_on_fail, false) exit_on_disconnect = options.fetch(:exit_on_disconnect, true) count = 0 # list of exceptions we may catch exceptions = ['ActiveRecord::StatementInvalid', 'PG::Error', 'Mysql2::Error']. map {|name| name.safe_constantize}. compact # # There are times when, for example, # a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid # # Also, connector-specific classes like PG::Error may not be defined # begin connection_lost = false yield rescue *exceptions => e translated = TransactionReliability.rewrap_exception(e) case translated when ConnectionLost (options[:connection] || ActiveRecord::Base.connection).reconnect! connection_lost = true when DeadlockDetected, SerializationFailure else raise translated end # Retry up to retry_count times if count < retry_count sleep backoff count += 1 backoff *= 2 retry else if (connection_lost && exit_on_disconnect) || exit_on_fail exit else raise(translated) end end end end
ruby
def with_transaction_retry(options = {}) retry_count = options.fetch(:retry_count, 4) backoff = options.fetch(:backoff, 0.25) exit_on_fail = options.fetch(:exit_on_fail, false) exit_on_disconnect = options.fetch(:exit_on_disconnect, true) count = 0 # list of exceptions we may catch exceptions = ['ActiveRecord::StatementInvalid', 'PG::Error', 'Mysql2::Error']. map {|name| name.safe_constantize}. compact # # There are times when, for example, # a raw PG::Error is throw rather than a wrapped ActiveRecord::StatementInvalid # # Also, connector-specific classes like PG::Error may not be defined # begin connection_lost = false yield rescue *exceptions => e translated = TransactionReliability.rewrap_exception(e) case translated when ConnectionLost (options[:connection] || ActiveRecord::Base.connection).reconnect! connection_lost = true when DeadlockDetected, SerializationFailure else raise translated end # Retry up to retry_count times if count < retry_count sleep backoff count += 1 backoff *= 2 retry else if (connection_lost && exit_on_disconnect) || exit_on_fail exit else raise(translated) end end end end
[ "def", "with_transaction_retry", "(", "options", "=", "{", "}", ")", "retry_count", "=", "options", ".", "fetch", "(", ":retry_count", ",", "4", ")", "backoff", "=", "options", ".", "fetch", "(", ":backoff", ",", "0.25", ")", "exit_on_fail", "=", "options", ".", "fetch", "(", ":exit_on_fail", ",", "false", ")", "exit_on_disconnect", "=", "options", ".", "fetch", "(", ":exit_on_disconnect", ",", "true", ")", "count", "=", "0", "exceptions", "=", "[", "'ActiveRecord::StatementInvalid'", ",", "'PG::Error'", ",", "'Mysql2::Error'", "]", ".", "map", "{", "|", "name", "|", "name", ".", "safe_constantize", "}", ".", "compact", "begin", "connection_lost", "=", "false", "yield", "rescue", "*", "exceptions", "=>", "e", "translated", "=", "TransactionReliability", ".", "rewrap_exception", "(", "e", ")", "case", "translated", "when", "ConnectionLost", "(", "options", "[", ":connection", "]", "||", "ActiveRecord", "::", "Base", ".", "connection", ")", ".", "reconnect!", "connection_lost", "=", "true", "when", "DeadlockDetected", ",", "SerializationFailure", "else", "raise", "translated", "end", "if", "count", "<", "retry_count", "sleep", "backoff", "count", "+=", "1", "backoff", "*=", "2", "retry", "else", "if", "(", "connection_lost", "&&", "exit_on_disconnect", ")", "||", "exit_on_fail", "exit", "else", "raise", "(", "translated", ")", "end", "end", "end", "end" ]
Intended to be included in an ActiveRecord model class. Retries a block (which usually contains a transaction) under certain failure conditions, up to a configurable number of times with an exponential backoff delay between each attempt. Conditions for retrying: 1. Database connection lost 2. Query or txn failed due to detected deadlock (Mysql/InnoDB and Postgres can both signal this for just about any transaction) 3. Query or txn failed due to serialization failure (Postgres will signal this for transactions in isolation level SERIALIZABLE) options: retry_count - how many retries to make; default 4 backoff - time period before 1st retry, in fractional seconds. will double at every retry. default 0.25 seconds. exit_on_disconnect - whether to call exit if no retry succeeds and the cause is a failed connection exit_on_fail - whether to call exit if no retry succeeds defaults:
[ "Intended", "to", "be", "included", "in", "an", "ActiveRecord", "model", "class", "." ]
9a314f7c3284452b5e3fb1bd17c6ff89784b5764
https://github.com/rsanders/transaction_reliability/blob/9a314f7c3284452b5e3fb1bd17c6ff89784b5764/lib/transaction_reliability.rb#L76-L124
train
rsanders/transaction_reliability
lib/transaction_reliability.rb
TransactionReliability.Helpers.transaction_with_retry
def transaction_with_retry(txn_options = {}, retry_options = {}) base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base with_transaction_retry(retry_options) do base_obj.transaction(txn_options) do yield end end end
ruby
def transaction_with_retry(txn_options = {}, retry_options = {}) base_obj = self.respond_to?(:transaction) ? self : ActiveRecord::Base with_transaction_retry(retry_options) do base_obj.transaction(txn_options) do yield end end end
[ "def", "transaction_with_retry", "(", "txn_options", "=", "{", "}", ",", "retry_options", "=", "{", "}", ")", "base_obj", "=", "self", ".", "respond_to?", "(", ":transaction", ")", "?", "self", ":", "ActiveRecord", "::", "Base", "with_transaction_retry", "(", "retry_options", ")", "do", "base_obj", ".", "transaction", "(", "txn_options", ")", "do", "yield", "end", "end", "end" ]
Execute some code in a DB transaction, with retry
[ "Execute", "some", "code", "in", "a", "DB", "transaction", "with", "retry" ]
9a314f7c3284452b5e3fb1bd17c6ff89784b5764
https://github.com/rsanders/transaction_reliability/blob/9a314f7c3284452b5e3fb1bd17c6ff89784b5764/lib/transaction_reliability.rb#L129-L137
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.connect_to_unit
def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket.new @host, @port @ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context @ssl_client.connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end
ruby
def connect_to_unit puts "Connecting to '#{@host}..." begin tcp_client = TCPSocket.new @host, @port @ssl_client = OpenSSL::SSL::SSLSocket.new tcp_client, @context @ssl_client.connect rescue Exception => e puts "Could not connect to '#{@host}: #{e}" end end
[ "def", "connect_to_unit", "puts", "\"Connecting to '#{@host}...\"", "begin", "tcp_client", "=", "TCPSocket", ".", "new", "@host", ",", "@port", "@ssl_client", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "tcp_client", ",", "@context", "@ssl_client", ".", "connect", "rescue", "Exception", "=>", "e", "puts", "\"Could not connect to '#{@host}: #{e}\"", "end", "end" ]
Initializes the TV class. @param [Object] cert SSL certificate for this client @param [String] host hostname or IP address of the Google TV @param [Number] port port number of the Google TV @return an instance of TV Connect this object to a Google TV
[ "Initializes", "the", "TV", "class", "." ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L35-L44
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.fling_uri
def fling_uri(uri) send_request RequestMessage.new(fling_message: Fling.new(uri: uri)) end
ruby
def fling_uri(uri) send_request RequestMessage.new(fling_message: Fling.new(uri: uri)) end
[ "def", "fling_uri", "(", "uri", ")", "send_request", "RequestMessage", ".", "new", "(", "fling_message", ":", "Fling", ".", "new", "(", "uri", ":", "uri", ")", ")", "end" ]
Fling a URI to the Google TV connected to this object This is used send the Google Chrome browser to a web page
[ "Fling", "a", "URI", "to", "the", "Google", "TV", "connected", "to", "this", "object", "This", "is", "used", "send", "the", "Google", "Chrome", "browser", "to", "a", "web", "page" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L55-L57
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_keycode
def send_keycode(keycode) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN)) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP)) end
ruby
def send_keycode(keycode) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::DOWN)) send_request RequestMessage.new(key_event_message: KeyEvent.new(keycode: keycode, action: Action::UP)) end
[ "def", "send_keycode", "(", "keycode", ")", "send_request", "RequestMessage", ".", "new", "(", "key_event_message", ":", "KeyEvent", ".", "new", "(", "keycode", ":", "keycode", ",", "action", ":", "Action", "::", "DOWN", ")", ")", "send_request", "RequestMessage", ".", "new", "(", "key_event_message", ":", "KeyEvent", ".", "new", "(", "keycode", ":", "keycode", ",", "action", ":", "Action", "::", "UP", ")", ")", "end" ]
Send a keystroke to the Google TV This is used for things like hitting the ENTER key
[ "Send", "a", "keystroke", "to", "the", "Google", "TV", "This", "is", "used", "for", "things", "like", "hitting", "the", "ENTER", "key" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L62-L65
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_data
def send_data(msg) send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg)) end
ruby
def send_data(msg) send_request RequestMessage.new(data_message: Data1.new(type: "com.google.tv.string", data: msg)) end
[ "def", "send_data", "(", "msg", ")", "send_request", "RequestMessage", ".", "new", "(", "data_message", ":", "Data1", ".", "new", "(", "type", ":", "\"com.google.tv.string\"", ",", "data", ":", "msg", ")", ")", "end" ]
Send a string to the Google TV. This is used for things like typing into text boxes.
[ "Send", "a", "string", "to", "the", "Google", "TV", ".", "This", "is", "used", "for", "things", "like", "typing", "into", "text", "boxes", "." ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L70-L72
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.move_mouse
def move_mouse(x_delta, y_delta) send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta)) end
ruby
def move_mouse(x_delta, y_delta) send_request RequestMessage.new(mouse_event_message: MouseEvent.new(x_delta: x_delta, y_delta: y_delta)) end
[ "def", "move_mouse", "(", "x_delta", ",", "y_delta", ")", "send_request", "RequestMessage", ".", "new", "(", "mouse_event_message", ":", "MouseEvent", ".", "new", "(", "x_delta", ":", "x_delta", ",", "y_delta", ":", "y_delta", ")", ")", "end" ]
Move the mouse relative to its current position
[ "Move", "the", "mouse", "relative", "to", "its", "current", "position" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L76-L78
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.scroll_mouse
def scroll_mouse(x_amount, y_amount) send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount)) end
ruby
def scroll_mouse(x_amount, y_amount) send_request RequestMessage.new(mouse_wheel_message: MouseWheel.new(x_scroll: x_amount, y_scroll: y_amount)) end
[ "def", "scroll_mouse", "(", "x_amount", ",", "y_amount", ")", "send_request", "RequestMessage", ".", "new", "(", "mouse_wheel_message", ":", "MouseWheel", ".", "new", "(", "x_scroll", ":", "x_amount", ",", "y_scroll", ":", "y_amount", ")", ")", "end" ]
Scroll the mouse wheel a certain amount
[ "Scroll", "the", "mouse", "wheel", "a", "certain", "amount" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L82-L84
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_request
def send_request(request) message = RemoteMessage.new(request_message: request).serialize_to_string message_size = [message.length].pack('N') @ssl_client.write(message_size + message) end
ruby
def send_request(request) message = RemoteMessage.new(request_message: request).serialize_to_string message_size = [message.length].pack('N') @ssl_client.write(message_size + message) end
[ "def", "send_request", "(", "request", ")", "message", "=", "RemoteMessage", ".", "new", "(", "request_message", ":", "request", ")", ".", "serialize_to_string", "message_size", "=", "[", "message", ".", "length", "]", ".", "pack", "(", "'N'", ")", "@ssl_client", ".", "write", "(", "message_size", "+", "message", ")", "end" ]
Send a request to the Google TV and don't wait for a response
[ "Send", "a", "request", "to", "the", "Google", "TV", "and", "don", "t", "wait", "for", "a", "response" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L90-L94
train
rnhurt/google_anymote
lib/google_anymote/tv.rb
GoogleAnymote.TV.send_message
def send_message(msg) # Build the message and get it's size message = msg.serialize_to_string message_size = [message.length].pack('N') # Try to send the message try_again = true begin data = "" @ssl_client.write(message_size + message) @ssl_client.readpartial(1000,data) rescue # Sometimes our connection might drop or something, so # we'll reconnect to the unit and try to send the message again. if try_again try_again = false connect_to_unit retry else # Looks like we couldn't connect to the unit after all. puts "message not sent" end end return data end
ruby
def send_message(msg) # Build the message and get it's size message = msg.serialize_to_string message_size = [message.length].pack('N') # Try to send the message try_again = true begin data = "" @ssl_client.write(message_size + message) @ssl_client.readpartial(1000,data) rescue # Sometimes our connection might drop or something, so # we'll reconnect to the unit and try to send the message again. if try_again try_again = false connect_to_unit retry else # Looks like we couldn't connect to the unit after all. puts "message not sent" end end return data end
[ "def", "send_message", "(", "msg", ")", "message", "=", "msg", ".", "serialize_to_string", "message_size", "=", "[", "message", ".", "length", "]", ".", "pack", "(", "'N'", ")", "try_again", "=", "true", "begin", "data", "=", "\"\"", "@ssl_client", ".", "write", "(", "message_size", "+", "message", ")", "@ssl_client", ".", "readpartial", "(", "1000", ",", "data", ")", "rescue", "if", "try_again", "try_again", "=", "false", "connect_to_unit", "retry", "else", "puts", "\"message not sent\"", "end", "end", "return", "data", "end" ]
Send a message to the Google TV and return the response
[ "Send", "a", "message", "to", "the", "Google", "TV", "and", "return", "the", "response" ]
2992aee3590df9e2cf6d31cebfba2e14be926b8f
https://github.com/rnhurt/google_anymote/blob/2992aee3590df9e2cf6d31cebfba2e14be926b8f/lib/google_anymote/tv.rb#L98-L123
train
williambarry007/caboose-store
lib/caboose-store/caboose_store_helper.rb
CabooseStore.CabooseStoreHelper.init_routes
def init_routes puts "Adding the caboose store routes..." filename = File.join(@app_path,'config','routes.rb') return if !File.exists?(filename) return if !@force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" file = File.open(filename, 'rb') contents = file.read file.close if (contents.index(str).nil?) arr = contents.split('end', -1) str2 = arr[0] + "\n" + str + "\nend" + arr[1] File.open(filename, 'w') {|file| file.write(str2) } end end
ruby
def init_routes puts "Adding the caboose store routes..." filename = File.join(@app_path,'config','routes.rb') return if !File.exists?(filename) return if !@force str = "" str << "\t# Catch everything with caboose\n" str << "\tmount CabooseStore::Engine => '/'\n" file = File.open(filename, 'rb') contents = file.read file.close if (contents.index(str).nil?) arr = contents.split('end', -1) str2 = arr[0] + "\n" + str + "\nend" + arr[1] File.open(filename, 'w') {|file| file.write(str2) } end end
[ "def", "init_routes", "puts", "\"Adding the caboose store routes...\"", "filename", "=", "File", ".", "join", "(", "@app_path", ",", "'config'", ",", "'routes.rb'", ")", "return", "if", "!", "File", ".", "exists?", "(", "filename", ")", "return", "if", "!", "@force", "str", "=", "\"\"", "str", "<<", "\"\\t# Catch everything with caboose\\n\"", "str", "<<", "\"\\tmount CabooseStore::Engine => '/'\\n\"", "file", "=", "File", ".", "open", "(", "filename", ",", "'rb'", ")", "contents", "=", "file", ".", "read", "file", ".", "close", "if", "(", "contents", ".", "index", "(", "str", ")", ".", "nil?", ")", "arr", "=", "contents", ".", "split", "(", "'end'", ",", "-", "1", ")", "str2", "=", "arr", "[", "0", "]", "+", "\"\\n\"", "+", "str", "+", "\"\\nend\"", "+", "arr", "[", "1", "]", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "file", "|", "file", ".", "write", "(", "str2", ")", "}", "end", "end" ]
Adds the routes to the host app to point everything to caboose
[ "Adds", "the", "routes", "to", "the", "host", "app", "to", "point", "everything", "to", "caboose" ]
997970e1e332f6180a8674324da5331c192d7d54
https://github.com/williambarry007/caboose-store/blob/997970e1e332f6180a8674324da5331c192d7d54/lib/caboose-store/caboose_store_helper.rb#L13-L32
train
subimage/cashboard-rb
lib/cashboard/errors.rb
Cashboard.BadRequest.errors
def errors parsed_errors = XmlSimple.xml_in(response.response.body) error_hash = {} parsed_errors['error'].each do |e| error_hash[e['field']] = e['content'] end return error_hash end
ruby
def errors parsed_errors = XmlSimple.xml_in(response.response.body) error_hash = {} parsed_errors['error'].each do |e| error_hash[e['field']] = e['content'] end return error_hash end
[ "def", "errors", "parsed_errors", "=", "XmlSimple", ".", "xml_in", "(", "response", ".", "response", ".", "body", ")", "error_hash", "=", "{", "}", "parsed_errors", "[", "'error'", "]", ".", "each", "do", "|", "e", "|", "error_hash", "[", "e", "[", "'field'", "]", "]", "=", "e", "[", "'content'", "]", "end", "return", "error_hash", "end" ]
Returns a hash of errors keyed on field name. Return Example { :field_name_one => "Error message", :field_name_two => "Error message" }
[ "Returns", "a", "hash", "of", "errors", "keyed", "on", "field", "name", "." ]
320e311ea1549cdd0dada0f8a0a4f9942213b28f
https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/errors.rb#L39-L46
train
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.clients
def clients(options = {}) post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj } end
ruby
def clients(options = {}) post("/clients", options)["clients"].map {|obj| Hashie::Mash.new obj } end
[ "def", "clients", "(", "options", "=", "{", "}", ")", "post", "(", "\"/clients\"", ",", "options", ")", "[", "\"clients\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The clients method will return a list of all clients and can only be accessed by admins on the subscription. Optional paramaters: open => [true|false]
[ "The", "clients", "method", "will", "return", "a", "list", "of", "all", "clients", "and", "can", "only", "be", "accessed", "by", "admins", "on", "the", "subscription", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L23-L25
train
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.projects
def projects(options = {}) post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj } end
ruby
def projects(options = {}) post("/projects", options)["projects"].map {|obj| Hashie::Mash.new obj } end
[ "def", "projects", "(", "options", "=", "{", "}", ")", "post", "(", "\"/projects\"", ",", "options", ")", "[", "\"projects\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The projects method will return projects filtered by the parameters provided. Admin can see all projects on the subscription, while non-admins can only access the projects they are assigned. Optional parameters: project_id open [true|false] project_billable [true|false]
[ "The", "projects", "method", "will", "return", "projects", "filtered", "by", "the", "parameters", "provided", ".", "Admin", "can", "see", "all", "projects", "on", "the", "subscription", "while", "non", "-", "admins", "can", "only", "access", "the", "projects", "they", "are", "assigned", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L36-L38
train
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.tasks
def tasks(options = {}) post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj } end
ruby
def tasks(options = {}) post("/tasks", options)["tasks"].map {|obj| Hashie::Mash.new obj } end
[ "def", "tasks", "(", "options", "=", "{", "}", ")", "post", "(", "\"/tasks\"", ",", "options", ")", "[", "\"tasks\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The tasks method will return a list of all the current tasks for a specified project and can only be accessed by admins on the subscription. Required parameters: project_id Optional Parameters: task_id open [true|false] task_billable [true|false]
[ "The", "tasks", "method", "will", "return", "a", "list", "of", "all", "the", "current", "tasks", "for", "a", "specified", "project", "and", "can", "only", "be", "accessed", "by", "admins", "on", "the", "subscription", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L51-L53
train
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.entries
def entries(options = {}) post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj } end
ruby
def entries(options = {}) post("/entries", options)["entries"].map {|obj| Hashie::Mash.new obj } end
[ "def", "entries", "(", "options", "=", "{", "}", ")", "post", "(", "\"/entries\"", ",", "options", ")", "[", "\"entries\"", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The entries method will return a list of all entries that meet the provided criteria. Either a start and end date have to be provided or an updated_at time. The entries will be in the start and end date range or they will be after the updated_at time depending on what criteria is provided. Each of the optional parameters will further filter the response. Required parameters: start_date end_date OR updated_at Optional Parameters: project_id task_id user_id user_email client_id entry_billable [true|false] billed [true|false]
[ "The", "entries", "method", "will", "return", "a", "list", "of", "all", "entries", "that", "meet", "the", "provided", "criteria", ".", "Either", "a", "start", "and", "end", "date", "have", "to", "be", "provided", "or", "an", "updated_at", "time", ".", "The", "entries", "will", "be", "in", "the", "start", "and", "end", "date", "range", "or", "they", "will", "be", "after", "the", "updated_at", "time", "depending", "on", "what", "criteria", "is", "provided", ".", "Each", "of", "the", "optional", "parameters", "will", "further", "filter", "the", "response", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L83-L85
train
cmason/tickspot-rb
lib/tickspot/client.rb
Tickspot.Client.users
def users(options = {}) post("/users", options)['users'].map {|obj| Hashie::Mash.new obj } end
ruby
def users(options = {}) post("/users", options)['users'].map {|obj| Hashie::Mash.new obj } end
[ "def", "users", "(", "options", "=", "{", "}", ")", "post", "(", "\"/users\"", ",", "options", ")", "[", "'users'", "]", ".", "map", "{", "|", "obj", "|", "Hashie", "::", "Mash", ".", "new", "obj", "}", "end" ]
The users method will return a list of users. Optional parameters: project_id
[ "The", "users", "method", "will", "return", "a", "list", "of", "users", "." ]
78cce0a8a6dcf36f754c6118618136b62de8cf34
https://github.com/cmason/tickspot-rb/blob/78cce0a8a6dcf36f754c6118618136b62de8cf34/lib/tickspot/client.rb#L99-L101
train
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.cache
def cache(key = nil) key ||= BasicCache.caller_name key = key.to_sym if include? key @store[key].value else value = yield @store[key] = TimeCacheItem.new Time.now, value value end end
ruby
def cache(key = nil) key ||= BasicCache.caller_name key = key.to_sym if include? key @store[key].value else value = yield @store[key] = TimeCacheItem.new Time.now, value value end end
[ "def", "cache", "(", "key", "=", "nil", ")", "key", "||=", "BasicCache", ".", "caller_name", "key", "=", "key", ".", "to_sym", "if", "include?", "key", "@store", "[", "key", "]", ".", "value", "else", "value", "=", "yield", "@store", "[", "key", "]", "=", "TimeCacheItem", ".", "new", "Time", ".", "now", ",", "value", "value", "end", "end" ]
Return a value from the cache, or calculate it and store it Recalculate if the cached value has expired
[ "Return", "a", "value", "from", "the", "cache", "or", "calculate", "it", "and", "store", "it", "Recalculate", "if", "the", "cached", "value", "has", "expired" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L34-L44
train
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.include?
def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end
ruby
def include?(key = nil) key ||= BasicCache.caller_name key = key.to_sym @store.include?(key) && Time.now - @store[key].stamp < @lifetime end
[ "def", "include?", "(", "key", "=", "nil", ")", "key", "||=", "BasicCache", ".", "caller_name", "key", "=", "key", ".", "to_sym", "@store", ".", "include?", "(", "key", ")", "&&", "Time", ".", "now", "-", "@store", "[", "key", "]", ".", "stamp", "<", "@lifetime", "end" ]
Check if a value is cached and not expired
[ "Check", "if", "a", "value", "is", "cached", "and", "not", "expired" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L49-L53
train
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.prune
def prune @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k } end
ruby
def prune @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k } end
[ "def", "prune", "@store", ".", "keys", ".", "reject", "{", "|", "k", "|", "include?", "k", "}", ".", "map", "{", "|", "k", "|", "clear!", "(", "k", ")", "&&", "k", "}", "end" ]
Prune expired keys
[ "Prune", "expired", "keys" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L73-L75
train
Raynes/rubyheap
lib/rubyheap/rubyheap.rb
Refheap.Paste.create
def create(contents, params = {:language => "Plain Text", :private => false}) params = params.merge({:contents => contents}.merge(@base_params)) self.class.post("/paste", :body => params).parsed_response end
ruby
def create(contents, params = {:language => "Plain Text", :private => false}) params = params.merge({:contents => contents}.merge(@base_params)) self.class.post("/paste", :body => params).parsed_response end
[ "def", "create", "(", "contents", ",", "params", "=", "{", ":language", "=>", "\"Plain Text\"", ",", ":private", "=>", "false", "}", ")", "params", "=", "params", ".", "merge", "(", "{", ":contents", "=>", "contents", "}", ".", "merge", "(", "@base_params", ")", ")", "self", ".", "class", ".", "post", "(", "\"/paste\"", ",", ":body", "=>", "params", ")", ".", "parsed_response", "end" ]
Create a new paste. If language isn't provided, it defaults to "Plain Text". If private isn't provided, it defaults to false.
[ "Create", "a", "new", "paste", ".", "If", "language", "isn", "t", "provided", "it", "defaults", "to", "Plain", "Text", ".", "If", "private", "isn", "t", "provided", "it", "defaults", "to", "false", "." ]
0f1c258b7643563b2d3e5dbccb3372a82e66c077
https://github.com/Raynes/rubyheap/blob/0f1c258b7643563b2d3e5dbccb3372a82e66c077/lib/rubyheap/rubyheap.rb#L29-L32
train
miguelzf/zomato2
lib/zomato2/restaurant.rb
Zomato2.Restaurant.details
def details(start: nil, count: nil) # warn "\tRestaurant#details: This method is currently useless, since, " + # "as of January 2017, Zomato's API doesn't give any additional info here." q = {res_id: @id } q[:start] = start if start q[:count] = count if count results = get('restaurant', q) @location ||= Location.new zom_conn, attributes["location"] @city_id ||= @location.city_id results.each do |k,v| if k == 'apikey' next elsif k == 'R' @id = v['res_id'] # Zomato never returns this?? bad API doc! elsif k == 'location' next elsif k == 'all_reviews' @reviews ||= v.map{ |r| Review.new(zom_conn, r) } elsif k == 'establishment_types' @establishments ||= v.map{ |e,ev| Establishment.new(zom_conn, @city_id, ev) } # elsif k == 'cuisines' the returned cuisines here are just a string.. else #puts "ATTR @#{k} val #{v}" self.instance_variable_set("@#{k}", v) end end self end
ruby
def details(start: nil, count: nil) # warn "\tRestaurant#details: This method is currently useless, since, " + # "as of January 2017, Zomato's API doesn't give any additional info here." q = {res_id: @id } q[:start] = start if start q[:count] = count if count results = get('restaurant', q) @location ||= Location.new zom_conn, attributes["location"] @city_id ||= @location.city_id results.each do |k,v| if k == 'apikey' next elsif k == 'R' @id = v['res_id'] # Zomato never returns this?? bad API doc! elsif k == 'location' next elsif k == 'all_reviews' @reviews ||= v.map{ |r| Review.new(zom_conn, r) } elsif k == 'establishment_types' @establishments ||= v.map{ |e,ev| Establishment.new(zom_conn, @city_id, ev) } # elsif k == 'cuisines' the returned cuisines here are just a string.. else #puts "ATTR @#{k} val #{v}" self.instance_variable_set("@#{k}", v) end end self end
[ "def", "details", "(", "start", ":", "nil", ",", "count", ":", "nil", ")", "q", "=", "{", "res_id", ":", "@id", "}", "q", "[", ":start", "]", "=", "start", "if", "start", "q", "[", ":count", "]", "=", "count", "if", "count", "results", "=", "get", "(", "'restaurant'", ",", "q", ")", "@location", "||=", "Location", ".", "new", "zom_conn", ",", "attributes", "[", "\"location\"", "]", "@city_id", "||=", "@location", ".", "city_id", "results", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", "==", "'apikey'", "next", "elsif", "k", "==", "'R'", "@id", "=", "v", "[", "'res_id'", "]", "elsif", "k", "==", "'location'", "next", "elsif", "k", "==", "'all_reviews'", "@reviews", "||=", "v", ".", "map", "{", "|", "r", "|", "Review", ".", "new", "(", "zom_conn", ",", "r", ")", "}", "elsif", "k", "==", "'establishment_types'", "@establishments", "||=", "v", ".", "map", "{", "|", "e", ",", "ev", "|", "Establishment", ".", "new", "(", "zom_conn", ",", "@city_id", ",", "ev", ")", "}", "else", "self", ".", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ")", "end", "end", "self", "end" ]
this doesn't actually give any more detailed info..
[ "this", "doesn", "t", "actually", "give", "any", "more", "detailed", "info", ".." ]
487d64af68a8b0f2735fe13edda3c4e9259504e6
https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/restaurant.rb#L55-L86
train
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.label_with_small
def label_with_small(f, method, text=nil, options = {}, &block) if text.is_a?(Hash) options = text text = nil end small_text = options.delete(:small_text) text = text || options.delete(:text) || method.to_s.humanize.capitalize lbl = f.label(method, text, options, &block) #do # contents = text # contents += "<small>#{h small_text}</small>" if small_text # contents += yield if block_given? # contents.html_safe #end lbl += "&nbsp;<small>(#{h small_text})</small>".html_safe if small_text lbl.html_safe end
ruby
def label_with_small(f, method, text=nil, options = {}, &block) if text.is_a?(Hash) options = text text = nil end small_text = options.delete(:small_text) text = text || options.delete(:text) || method.to_s.humanize.capitalize lbl = f.label(method, text, options, &block) #do # contents = text # contents += "<small>#{h small_text}</small>" if small_text # contents += yield if block_given? # contents.html_safe #end lbl += "&nbsp;<small>(#{h small_text})</small>".html_safe if small_text lbl.html_safe end
[ "def", "label_with_small", "(", "f", ",", "method", ",", "text", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "if", "text", ".", "is_a?", "(", "Hash", ")", "options", "=", "text", "text", "=", "nil", "end", "small_text", "=", "options", ".", "delete", "(", ":small_text", ")", "text", "=", "text", "||", "options", ".", "delete", "(", ":text", ")", "||", "method", ".", "to_s", ".", "humanize", ".", "capitalize", "lbl", "=", "f", ".", "label", "(", "method", ",", "text", ",", "options", ",", "&", "block", ")", "lbl", "+=", "\"&nbsp;<small>(#{h small_text})</small>\"", ".", "html_safe", "if", "small_text", "lbl", ".", "html_safe", "end" ]
Creates a label followed by small text. Set the :small_text option to include small text.
[ "Creates", "a", "label", "followed", "by", "small", "text", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L215-L230
train
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.text_form_group
def text_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = f.label_with_small method, lopt.delete(:text), lopt fld = gopt[:wrap].call(f.text_field(method, fopt)) form_group lbl, fld, gopt end
ruby
def text_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = f.label_with_small method, lopt.delete(:text), lopt fld = gopt[:wrap].call(f.text_field(method, fopt)) form_group lbl, fld, gopt end
[ "def", "text_form_group", "(", "f", ",", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "f", ".", "label_with_small", "method", ",", "lopt", ".", "delete", "(", ":text", ")", ",", "lopt", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "f", ".", "text_field", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a text field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "text", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L238-L243
train
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.multi_input_form_group
def multi_input_form_group(f, methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt fld = gopt[:wrap].call(multi_input_field(f, methods, fopt)) form_group lbl, fld, gopt end
ruby
def multi_input_form_group(f, methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt fld = gopt[:wrap].call(multi_input_field(f, methods, fopt)) form_group lbl, fld, gopt end
[ "def", "multi_input_form_group", "(", "f", ",", "methods", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lopt", "[", ":text", "]", "||=", "gopt", "[", ":label", "]", "if", "lopt", "[", ":text", "]", ".", "blank?", "lopt", "[", ":text", "]", "=", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", ".", "to_s", ".", "humanize", "}", ".", "join", "(", "', '", ")", "end", "lbl", "=", "f", ".", "label_with_small", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", "}", ".", "first", ",", "lopt", "[", ":text", "]", ",", "lopt", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "multi_input_field", "(", "f", ",", "methods", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a multiple input field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "multiple", "input", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L304-L313
train
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.checkbox_form_group
def checkbox_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = f.label method do f.check_box(method, fopt) + h(lopt[:text] || method.to_s.humanize) + if lopt[:small_text] "<small>#{h lopt[:small_text]}</small>" else '' end.html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
ruby
def checkbox_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = f.label method do f.check_box(method, fopt) + h(lopt[:text] || method.to_s.humanize) + if lopt[:small_text] "<small>#{h lopt[:small_text]}</small>" else '' end.html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
[ "def", "checkbox_form_group", "(", "f", ",", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "{", "class", ":", "'checkbox'", ",", "field_class", ":", "''", "}", ".", "merge", "(", "options", ")", ")", "if", "gopt", "[", ":h_align", "]", "gopt", "[", ":class", "]", "=", "gopt", "[", ":class", "]", ".", "blank?", "?", "\"col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", ":", "\"#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", "end", "lbl", "=", "f", ".", "label", "method", "do", "f", ".", "check_box", "(", "method", ",", "fopt", ")", "+", "h", "(", "lopt", "[", ":text", "]", "||", "method", ".", "to_s", ".", "humanize", ")", "+", "if", "lopt", "[", ":small_text", "]", "\"<small>#{h lopt[:small_text]}</small>\"", "else", "''", "end", ".", "html_safe", "end", "\"<div class=\\\"#{gopt[:h_align] ? 'row' : 'form-group'}\\\"><div class=\\\"#{gopt[:class]}\\\">#{lbl}</div></div>\"", ".", "html_safe", "end" ]
Creates a form group including a label and a checkbox. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "checkbox", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L321-L341
train
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.select_form_group
def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {}) gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options)) lbl = f.label_with_small method, lopt.delete(:text), lopt value_method ||= :to_s text_method ||= :to_s opt = {} [:include_blank, :prompt, :include_hidden].each do |attr| if fopt[attr] != nil opt[attr] = fopt[attr] fopt.except! attr end end fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt)) form_group lbl, fld, gopt end
ruby
def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {}) gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options)) lbl = f.label_with_small method, lopt.delete(:text), lopt value_method ||= :to_s text_method ||= :to_s opt = {} [:include_blank, :prompt, :include_hidden].each do |attr| if fopt[attr] != nil opt[attr] = fopt[attr] fopt.except! attr end end fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt)) form_group lbl, fld, gopt end
[ "def", "select_form_group", "(", "f", ",", "method", ",", "collection", ",", "value_method", "=", "nil", ",", "text_method", "=", "nil", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "{", "field_include_blank", ":", "true", "}", ".", "merge", "(", "options", ")", ")", "lbl", "=", "f", ".", "label_with_small", "method", ",", "lopt", ".", "delete", "(", ":text", ")", ",", "lopt", "value_method", "||=", ":to_s", "text_method", "||=", ":to_s", "opt", "=", "{", "}", "[", ":include_blank", ",", ":prompt", ",", ":include_hidden", "]", ".", "each", "do", "|", "attr", "|", "if", "fopt", "[", "attr", "]", "!=", "nil", "opt", "[", "attr", "]", "=", "fopt", "[", "attr", "]", "fopt", ".", "except!", "attr", "end", "end", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "f", ".", "collection_select", "(", "method", ",", "collection", ",", "value_method", ",", "text_method", ",", "opt", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a collection select field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "collection", "select", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L349-L363
train
codescrum/bebox
lib/bebox/commands/node_commands.rb
Bebox.NodeCommands.generate_node_command
def generate_node_command(node_command, command, send_command, description) node_command.desc description node_command.command command do |generated_command| generated_command.action do |global_options,options,args| environment = get_environment(options) info _('cli.current_environment')%{environment: environment} Bebox::NodeWizard.new.send(send_command, project_root, environment) end end end
ruby
def generate_node_command(node_command, command, send_command, description) node_command.desc description node_command.command command do |generated_command| generated_command.action do |global_options,options,args| environment = get_environment(options) info _('cli.current_environment')%{environment: environment} Bebox::NodeWizard.new.send(send_command, project_root, environment) end end end
[ "def", "generate_node_command", "(", "node_command", ",", "command", ",", "send_command", ",", "description", ")", "node_command", ".", "desc", "description", "node_command", ".", "command", "command", "do", "|", "generated_command", "|", "generated_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "environment", "=", "get_environment", "(", "options", ")", "info", "_", "(", "'cli.current_environment'", ")", "%", "{", "environment", ":", "environment", "}", "Bebox", "::", "NodeWizard", ".", "new", ".", "send", "(", "send_command", ",", "project_root", ",", "environment", ")", "end", "end", "end" ]
For new and set_role commands
[ "For", "new", "and", "set_role", "commands" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/node_commands.rb#L37-L46
train
delano/familia
lib/familia/object.rb
Familia.ClassMethods.install_redis_object
def install_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts ||= {} redis_objects_order << name redis_objects[name] = OpenStruct.new redis_objects[name].name = name redis_objects[name].klass = klass redis_objects[name].opts = opts self.send :attr_reader, name define_method "#{name}=" do |v| self.send(name).replace v end define_method "#{name}?" do !self.send(name).empty? end redis_objects[name] end
ruby
def install_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts ||= {} redis_objects_order << name redis_objects[name] = OpenStruct.new redis_objects[name].name = name redis_objects[name].klass = klass redis_objects[name].opts = opts self.send :attr_reader, name define_method "#{name}=" do |v| self.send(name).replace v end define_method "#{name}?" do !self.send(name).empty? end redis_objects[name] end
[ "def", "install_redis_object", "name", ",", "klass", ",", "opts", "raise", "ArgumentError", ",", "\"Name is blank\"", "if", "name", ".", "to_s", ".", "empty?", "name", "=", "name", ".", "to_s", ".", "to_sym", "opts", "||=", "{", "}", "redis_objects_order", "<<", "name", "redis_objects", "[", "name", "]", "=", "OpenStruct", ".", "new", "redis_objects", "[", "name", "]", ".", "name", "=", "name", "redis_objects", "[", "name", "]", ".", "klass", "=", "klass", "redis_objects", "[", "name", "]", ".", "opts", "=", "opts", "self", ".", "send", ":attr_reader", ",", "name", "define_method", "\"#{name}=\"", "do", "|", "v", "|", "self", ".", "send", "(", "name", ")", ".", "replace", "v", "end", "define_method", "\"#{name}?\"", "do", "!", "self", ".", "send", "(", "name", ")", ".", "empty?", "end", "redis_objects", "[", "name", "]", "end" ]
Creates an instance method called +name+ that returns an instance of the RedisObject +klass+
[ "Creates", "an", "instance", "method", "called", "+", "name", "+", "that", "returns", "an", "instance", "of", "the", "RedisObject", "+", "klass", "+" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L75-L92
train
delano/familia
lib/familia/object.rb
Familia.ClassMethods.install_class_redis_object
def install_class_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) # TODO: investigate using metaclass.redis_objects class_redis_objects_order << name class_redis_objects[name] = OpenStruct.new class_redis_objects[name].name = name class_redis_objects[name].klass = klass class_redis_objects[name].opts = opts # An accessor method created in the metclass will # access the instance variables for this class. metaclass.send :attr_reader, name metaclass.send :define_method, "#{name}=" do |v| send(name).replace v end metaclass.send :define_method, "#{name}?" do !send(name).empty? end redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set("@#{name}", redis_object) class_redis_objects[name] end
ruby
def install_class_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) # TODO: investigate using metaclass.redis_objects class_redis_objects_order << name class_redis_objects[name] = OpenStruct.new class_redis_objects[name].name = name class_redis_objects[name].klass = klass class_redis_objects[name].opts = opts # An accessor method created in the metclass will # access the instance variables for this class. metaclass.send :attr_reader, name metaclass.send :define_method, "#{name}=" do |v| send(name).replace v end metaclass.send :define_method, "#{name}?" do !send(name).empty? end redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set("@#{name}", redis_object) class_redis_objects[name] end
[ "def", "install_class_redis_object", "name", ",", "klass", ",", "opts", "raise", "ArgumentError", ",", "\"Name is blank\"", "if", "name", ".", "to_s", ".", "empty?", "name", "=", "name", ".", "to_s", ".", "to_sym", "opts", "=", "opts", ".", "nil?", "?", "{", "}", ":", "opts", ".", "clone", "opts", "[", ":parent", "]", "=", "self", "unless", "opts", ".", "has_key?", "(", ":parent", ")", "class_redis_objects_order", "<<", "name", "class_redis_objects", "[", "name", "]", "=", "OpenStruct", ".", "new", "class_redis_objects", "[", "name", "]", ".", "name", "=", "name", "class_redis_objects", "[", "name", "]", ".", "klass", "=", "klass", "class_redis_objects", "[", "name", "]", ".", "opts", "=", "opts", "metaclass", ".", "send", ":attr_reader", ",", "name", "metaclass", ".", "send", ":define_method", ",", "\"#{name}=\"", "do", "|", "v", "|", "send", "(", "name", ")", ".", "replace", "v", "end", "metaclass", ".", "send", ":define_method", ",", "\"#{name}?\"", "do", "!", "send", "(", "name", ")", ".", "empty?", "end", "redis_object", "=", "klass", ".", "new", "name", ",", "opts", "redis_object", ".", "freeze", "self", ".", "instance_variable_set", "(", "\"@#{name}\"", ",", "redis_object", ")", "class_redis_objects", "[", "name", "]", "end" ]
Creates a class method called +name+ that returns an instance of the RedisObject +klass+
[ "Creates", "a", "class", "method", "called", "+", "name", "+", "that", "returns", "an", "instance", "of", "the", "RedisObject", "+", "klass", "+" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L103-L127
train
delano/familia
lib/familia/object.rb
Familia.ClassMethods.load_or_create
def load_or_create idx return from_redis(idx) if exists?(idx) obj = from_index idx obj.save obj end
ruby
def load_or_create idx return from_redis(idx) if exists?(idx) obj = from_index idx obj.save obj end
[ "def", "load_or_create", "idx", "return", "from_redis", "(", "idx", ")", "if", "exists?", "(", "idx", ")", "obj", "=", "from_index", "idx", "obj", ".", "save", "obj", "end" ]
Returns an instance based on +idx+ otherwise it creates and saves a new instance base on +idx+. See from_index
[ "Returns", "an", "instance", "based", "on", "+", "idx", "+", "otherwise", "it", "creates", "and", "saves", "a", "new", "instance", "base", "on", "+", "idx", "+", ".", "See", "from_index" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L237-L242
train
delano/familia
lib/familia/object.rb
Familia.ClassMethods.rediskey
def rediskey idx, suffix=self.suffix raise RuntimeError, "No index for #{self}" if idx.to_s.empty? idx = Familia.join *idx if Array === idx idx &&= idx.to_s Familia.rediskey(prefix, idx, suffix) end
ruby
def rediskey idx, suffix=self.suffix raise RuntimeError, "No index for #{self}" if idx.to_s.empty? idx = Familia.join *idx if Array === idx idx &&= idx.to_s Familia.rediskey(prefix, idx, suffix) end
[ "def", "rediskey", "idx", ",", "suffix", "=", "self", ".", "suffix", "raise", "RuntimeError", ",", "\"No index for #{self}\"", "if", "idx", ".", "to_s", ".", "empty?", "idx", "=", "Familia", ".", "join", "*", "idx", "if", "Array", "===", "idx", "idx", "&&=", "idx", ".", "to_s", "Familia", ".", "rediskey", "(", "prefix", ",", "idx", ",", "suffix", ")", "end" ]
idx can be a value or an Array of values used to create the index. We don't enforce a default suffix; that's left up to the instance. A nil +suffix+ will not be included in the key.
[ "idx", "can", "be", "a", "value", "or", "an", "Array", "of", "values", "used", "to", "create", "the", "index", ".", "We", "don", "t", "enforce", "a", "default", "suffix", ";", "that", "s", "left", "up", "to", "the", "instance", ".", "A", "nil", "+", "suffix", "+", "will", "not", "be", "included", "in", "the", "key", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L283-L288
train
delano/familia
lib/familia/object.rb
Familia.InstanceMethods.initialize_redis_objects
def initialize_redis_objects # Generate instances of each RedisObject. These need to be # unique for each instance of this class so they can refer # to the index of this specific instance. # # i.e. # familia_object.rediskey == v1:bone:INDEXVALUE:object # familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name # # See RedisObject.install_redis_object self.class.redis_objects.each_pair do |name, redis_object_definition| klass, opts = redis_object_definition.klass, redis_object_definition.opts opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set "@#{name}", redis_object end end
ruby
def initialize_redis_objects # Generate instances of each RedisObject. These need to be # unique for each instance of this class so they can refer # to the index of this specific instance. # # i.e. # familia_object.rediskey == v1:bone:INDEXVALUE:object # familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name # # See RedisObject.install_redis_object self.class.redis_objects.each_pair do |name, redis_object_definition| klass, opts = redis_object_definition.klass, redis_object_definition.opts opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set "@#{name}", redis_object end end
[ "def", "initialize_redis_objects", "self", ".", "class", ".", "redis_objects", ".", "each_pair", "do", "|", "name", ",", "redis_object_definition", "|", "klass", ",", "opts", "=", "redis_object_definition", ".", "klass", ",", "redis_object_definition", ".", "opts", "opts", "=", "opts", ".", "nil?", "?", "{", "}", ":", "opts", ".", "clone", "opts", "[", ":parent", "]", "=", "self", "unless", "opts", ".", "has_key?", "(", ":parent", ")", "redis_object", "=", "klass", ".", "new", "name", ",", "opts", "redis_object", ".", "freeze", "self", ".", "instance_variable_set", "\"@#{name}\"", ",", "redis_object", "end", "end" ]
A default initialize method. This will be replaced if a class defines its own initialize method after including Familia. In that case, the replacement must call initialize_redis_objects. This needs to be called in the initialize method of any class that includes Familia.
[ "A", "default", "initialize", "method", ".", "This", "will", "be", "replaced", "if", "a", "class", "defines", "its", "own", "initialize", "method", "after", "including", "Familia", ".", "In", "that", "case", "the", "replacement", "must", "call", "initialize_redis_objects", ".", "This", "needs", "to", "be", "called", "in", "the", "initialize", "method", "of", "any", "class", "that", "includes", "Familia", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L319-L337
train
timstephenson/rHAPI
lib/r_hapi/lead.rb
RHapi.Lead.method_missing
def method_missing(method, *args, &block) attribute = ActiveSupport::Inflector.camelize(method.to_s, false) if attribute =~ /=$/ attribute = attribute.chop return super unless self.attributes.include?(attribute) self.changed_attributes[attribute] = args[0] self.attributes[attribute] = args[0] else return super unless self.attributes.include?(attribute) self.attributes[attribute] end end
ruby
def method_missing(method, *args, &block) attribute = ActiveSupport::Inflector.camelize(method.to_s, false) if attribute =~ /=$/ attribute = attribute.chop return super unless self.attributes.include?(attribute) self.changed_attributes[attribute] = args[0] self.attributes[attribute] = args[0] else return super unless self.attributes.include?(attribute) self.attributes[attribute] end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "attribute", "=", "ActiveSupport", "::", "Inflector", ".", "camelize", "(", "method", ".", "to_s", ",", "false", ")", "if", "attribute", "=~", "/", "/", "attribute", "=", "attribute", ".", "chop", "return", "super", "unless", "self", ".", "attributes", ".", "include?", "(", "attribute", ")", "self", ".", "changed_attributes", "[", "attribute", "]", "=", "args", "[", "0", "]", "self", ".", "attributes", "[", "attribute", "]", "=", "args", "[", "0", "]", "else", "return", "super", "unless", "self", ".", "attributes", ".", "include?", "(", "attribute", ")", "self", ".", "attributes", "[", "attribute", "]", "end", "end" ]
Work with data in the data hash
[ "Work", "with", "data", "in", "the", "data", "hash" ]
1490574e619b7564c9458ac8d967d40fe76fe7a5
https://github.com/timstephenson/rHAPI/blob/1490574e619b7564c9458ac8d967d40fe76fe7a5/lib/r_hapi/lead.rb#L65-L79
train
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.bank_holidays
def bank_holidays @bank_holidays ||= begin holidays = [ new_years_day, mlk_day, washingtons_birthday, memorial_day, independence_day, labor_day, columbus_day, veterans_day, thanksgiving, christmas ] if Date.new(year + 1, 1, 1).saturday? holidays << Date.new(year, 12, 31) end holidays.freeze end end
ruby
def bank_holidays @bank_holidays ||= begin holidays = [ new_years_day, mlk_day, washingtons_birthday, memorial_day, independence_day, labor_day, columbus_day, veterans_day, thanksgiving, christmas ] if Date.new(year + 1, 1, 1).saturday? holidays << Date.new(year, 12, 31) end holidays.freeze end end
[ "def", "bank_holidays", "@bank_holidays", "||=", "begin", "holidays", "=", "[", "new_years_day", ",", "mlk_day", ",", "washingtons_birthday", ",", "memorial_day", ",", "independence_day", ",", "labor_day", ",", "columbus_day", ",", "veterans_day", ",", "thanksgiving", ",", "christmas", "]", "if", "Date", ".", "new", "(", "year", "+", "1", ",", "1", ",", "1", ")", ".", "saturday?", "holidays", "<<", "Date", ".", "new", "(", "year", ",", "12", ",", "31", ")", "end", "holidays", ".", "freeze", "end", "end" ]
Initializes instance from a given year Returns the federal holidays for the given year on the dates they will actually be observed.
[ "Initializes", "instance", "from", "a", "given", "year", "Returns", "the", "federal", "holidays", "for", "the", "given", "year", "on", "the", "dates", "they", "will", "actually", "be", "observed", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L30-L48
train
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.init_fixed_holidays
def init_fixed_holidays # Third Monday of January @mlk_day = january.mondays[2] # Third Monday of February @washingtons_birthday = february.mondays[2] # Last Monday of May @memorial_day = may.mondays.last # First Monday of September @labor_day = september.mondays.first # Second Monday of October @columbus_day = october.mondays[1] # Fourth Thursday of November @thanksgiving = november.thursdays[3] end
ruby
def init_fixed_holidays # Third Monday of January @mlk_day = january.mondays[2] # Third Monday of February @washingtons_birthday = february.mondays[2] # Last Monday of May @memorial_day = may.mondays.last # First Monday of September @labor_day = september.mondays.first # Second Monday of October @columbus_day = october.mondays[1] # Fourth Thursday of November @thanksgiving = november.thursdays[3] end
[ "def", "init_fixed_holidays", "@mlk_day", "=", "january", ".", "mondays", "[", "2", "]", "@washingtons_birthday", "=", "february", ".", "mondays", "[", "2", "]", "@memorial_day", "=", "may", ".", "mondays", ".", "last", "@labor_day", "=", "september", ".", "mondays", ".", "first", "@columbus_day", "=", "october", ".", "mondays", "[", "1", "]", "@thanksgiving", "=", "november", ".", "thursdays", "[", "3", "]", "end" ]
These holidays are always fixed
[ "These", "holidays", "are", "always", "fixed" ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L74-L92
train
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.init_rolled_holidays
def init_rolled_holidays # First of the year, rolls either forward or back. @new_years_day = roll_nominal(Date.new(year, 1, 1)) # 4'th of July @independence_day = roll_nominal(Date.new(year, 7, 4)) # November 11 @veterans_day = roll_nominal(Date.new(year, 11, 11)) # December 25 @christmas = roll_nominal(Date.new(year, 12, 25)) end
ruby
def init_rolled_holidays # First of the year, rolls either forward or back. @new_years_day = roll_nominal(Date.new(year, 1, 1)) # 4'th of July @independence_day = roll_nominal(Date.new(year, 7, 4)) # November 11 @veterans_day = roll_nominal(Date.new(year, 11, 11)) # December 25 @christmas = roll_nominal(Date.new(year, 12, 25)) end
[ "def", "init_rolled_holidays", "@new_years_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "1", ",", "1", ")", ")", "@independence_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "7", ",", "4", ")", ")", "@veterans_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "11", ",", "11", ")", ")", "@christmas", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "12", ",", "25", ")", ")", "end" ]
These holidays are potentially rolled if they come on a weekend.
[ "These", "holidays", "are", "potentially", "rolled", "if", "they", "come", "on", "a", "weekend", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L95-L107
train
thejonanshow/guard-shopify
lib/guard/shopify.rb
Guard.Shopify.upgrade_config_file
def upgrade_config_file puts "Old config file found, upgrading..." credentials = File.read(config_file_path).split("\n") config = {} config['api_key'] = credentials[0] config['password'] = credentials[1] config['url'] = credentials[2] config['secret'] = prompt "Please enter your API Shared Secret" write_config config puts 'Upgraded old config file to new format' config end
ruby
def upgrade_config_file puts "Old config file found, upgrading..." credentials = File.read(config_file_path).split("\n") config = {} config['api_key'] = credentials[0] config['password'] = credentials[1] config['url'] = credentials[2] config['secret'] = prompt "Please enter your API Shared Secret" write_config config puts 'Upgraded old config file to new format' config end
[ "def", "upgrade_config_file", "puts", "\"Old config file found, upgrading...\"", "credentials", "=", "File", ".", "read", "(", "config_file_path", ")", ".", "split", "(", "\"\\n\"", ")", "config", "=", "{", "}", "config", "[", "'api_key'", "]", "=", "credentials", "[", "0", "]", "config", "[", "'password'", "]", "=", "credentials", "[", "1", "]", "config", "[", "'url'", "]", "=", "credentials", "[", "2", "]", "config", "[", "'secret'", "]", "=", "prompt", "\"Please enter your API Shared Secret\"", "write_config", "config", "puts", "'Upgraded old config file to new format'", "config", "end" ]
Old line-based config file format
[ "Old", "line", "-", "based", "config", "file", "format" ]
c2f4d468286284a6ec720fd1604c529a26f03c5d
https://github.com/thejonanshow/guard-shopify/blob/c2f4d468286284a6ec720fd1604c529a26f03c5d/lib/guard/shopify.rb#L32-L48
train
cmeiklejohn/seedable
lib/seedable/object_tracker.rb
Seedable.ObjectTracker.contains?
def contains?(object) key, id = to_key_and_id(object) @graph[key].is_a?(Enumerable) ? @graph[key].include?(id) : @graph[key] end
ruby
def contains?(object) key, id = to_key_and_id(object) @graph[key].is_a?(Enumerable) ? @graph[key].include?(id) : @graph[key] end
[ "def", "contains?", "(", "object", ")", "key", ",", "id", "=", "to_key_and_id", "(", "object", ")", "@graph", "[", "key", "]", ".", "is_a?", "(", "Enumerable", ")", "?", "@graph", "[", "key", "]", ".", "include?", "(", "id", ")", ":", "@graph", "[", "key", "]", "end" ]
Create a new instance of the object tracker. Determine if the object tracker has already picked this object up.
[ "Create", "a", "new", "instance", "of", "the", "object", "tracker", "." ]
b3383e460e1afc22715c92d920c0fc7910706903
https://github.com/cmeiklejohn/seedable/blob/b3383e460e1afc22715c92d920c0fc7910706903/lib/seedable/object_tracker.rb#L16-L20
train
cmeiklejohn/seedable
lib/seedable/object_tracker.rb
Seedable.ObjectTracker.add
def add(object) key, id = to_key_and_id(object) @graph[key] ? @graph[key] << id : @graph[key] = [id] end
ruby
def add(object) key, id = to_key_and_id(object) @graph[key] ? @graph[key] << id : @graph[key] = [id] end
[ "def", "add", "(", "object", ")", "key", ",", "id", "=", "to_key_and_id", "(", "object", ")", "@graph", "[", "key", "]", "?", "@graph", "[", "key", "]", "<<", "id", ":", "@graph", "[", "key", "]", "=", "[", "id", "]", "end" ]
Add this object to the object tracker.
[ "Add", "this", "object", "to", "the", "object", "tracker", "." ]
b3383e460e1afc22715c92d920c0fc7910706903
https://github.com/cmeiklejohn/seedable/blob/b3383e460e1afc22715c92d920c0fc7910706903/lib/seedable/object_tracker.rb#L24-L28
train
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.subgraph
def subgraph(included = nil, &selector) result = clone result.select_vertices!(included) unless included.nil? result.select_vertices!(&selector) if block_given? result end
ruby
def subgraph(included = nil, &selector) result = clone result.select_vertices!(included) unless included.nil? result.select_vertices!(&selector) if block_given? result end
[ "def", "subgraph", "(", "included", "=", "nil", ",", "&", "selector", ")", "result", "=", "clone", "result", ".", "select_vertices!", "(", "included", ")", "unless", "included", ".", "nil?", "result", ".", "select_vertices!", "(", "&", "selector", ")", "if", "block_given?", "result", "end" ]
Initialize a new graph, optionally preloading it with vertices and edges Graph.new() => Graph Graph.new(mixins: [MixinModule, ...], ...) => Graph +mixins+ is an array of modules that can be mixed into the various classes that makes up a graph. Initialization of a Graph, Vertex or Edge looks for submodules in each mixin, with the same name and extends any created object. Defaults to [Tangle::Mixin::Connectedness]. Any subclass of Graph should also subclass Edge to manage its unique constraints. Return a subgraph, optionally filtered by a vertex selector block subgraph => Graph subgraph { |vertex| ... } => Graph Unless a selector is provided, the subgraph contains the entire graph.
[ "Initialize", "a", "new", "graph", "optionally", "preloading", "it", "with", "vertices", "and", "edges" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L66-L71
train
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.add_vertex
def add_vertex(vertex, name: nil) name ||= callback(vertex, :name) insert_vertex(vertex, name) define_currified_methods(vertex, :vertex) if @currify callback(vertex, :added_to_graph, self) self end
ruby
def add_vertex(vertex, name: nil) name ||= callback(vertex, :name) insert_vertex(vertex, name) define_currified_methods(vertex, :vertex) if @currify callback(vertex, :added_to_graph, self) self end
[ "def", "add_vertex", "(", "vertex", ",", "name", ":", "nil", ")", "name", "||=", "callback", "(", "vertex", ",", ":name", ")", "insert_vertex", "(", "vertex", ",", "name", ")", "define_currified_methods", "(", "vertex", ",", ":vertex", ")", "if", "@currify", "callback", "(", "vertex", ",", ":added_to_graph", ",", "self", ")", "self", "end" ]
Add a vertex into the graph If a name: is given, or the vertex responds to :name, it will be registered by name in the graph
[ "Add", "a", "vertex", "into", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L102-L108
train
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.remove_vertex
def remove_vertex(vertex) @vertices[vertex].each do |edge| remove_edge(edge) if edge.include?(vertex) end delete_vertex(vertex) callback(vertex, :removed_from_graph, self) end
ruby
def remove_vertex(vertex) @vertices[vertex].each do |edge| remove_edge(edge) if edge.include?(vertex) end delete_vertex(vertex) callback(vertex, :removed_from_graph, self) end
[ "def", "remove_vertex", "(", "vertex", ")", "@vertices", "[", "vertex", "]", ".", "each", "do", "|", "edge", "|", "remove_edge", "(", "edge", ")", "if", "edge", ".", "include?", "(", "vertex", ")", "end", "delete_vertex", "(", "vertex", ")", "callback", "(", "vertex", ",", ":removed_from_graph", ",", "self", ")", "end" ]
Remove a vertex from the graph
[ "Remove", "a", "vertex", "from", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L112-L118
train
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.add_edge
def add_edge(*vertices, **kvargs) edge = new_edge(*vertices, mixins: @mixins, **kvargs) insert_edge(edge) vertices.each { |vertex| callback(vertex, :edge_added, edge) } edge end
ruby
def add_edge(*vertices, **kvargs) edge = new_edge(*vertices, mixins: @mixins, **kvargs) insert_edge(edge) vertices.each { |vertex| callback(vertex, :edge_added, edge) } edge end
[ "def", "add_edge", "(", "*", "vertices", ",", "**", "kvargs", ")", "edge", "=", "new_edge", "(", "*", "vertices", ",", "mixins", ":", "@mixins", ",", "**", "kvargs", ")", "insert_edge", "(", "edge", ")", "vertices", ".", "each", "{", "|", "vertex", "|", "callback", "(", "vertex", ",", ":edge_added", ",", "edge", ")", "}", "edge", "end" ]
Add a new edge to the graph add_edge(vtx1, vtx2, ...) => Edge
[ "Add", "a", "new", "edge", "to", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L135-L140
train
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.remove_edge
def remove_edge(edge) delete_edge(edge) edge.each_vertex { |vertex| callback(vertex, :edge_removed, edge) } end
ruby
def remove_edge(edge) delete_edge(edge) edge.each_vertex { |vertex| callback(vertex, :edge_removed, edge) } end
[ "def", "remove_edge", "(", "edge", ")", "delete_edge", "(", "edge", ")", "edge", ".", "each_vertex", "{", "|", "vertex", "|", "callback", "(", "vertex", ",", ":edge_removed", ",", "edge", ")", "}", "end" ]
Remove an edge from the graph
[ "Remove", "an", "edge", "from", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L143-L146
train
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.disconnect
def disconnect control_request LS_op: :destroy if @stream_connection @processing_thread.join 5 if @processing_thread ensure @stream_connection.disconnect if @stream_connection @processing_thread.exit if @processing_thread @subscriptions.each { |subscription| subscription.after_control_request :stop } @subscriptions = [] @processing_thread = @stream_connection = nil end
ruby
def disconnect control_request LS_op: :destroy if @stream_connection @processing_thread.join 5 if @processing_thread ensure @stream_connection.disconnect if @stream_connection @processing_thread.exit if @processing_thread @subscriptions.each { |subscription| subscription.after_control_request :stop } @subscriptions = [] @processing_thread = @stream_connection = nil end
[ "def", "disconnect", "control_request", "LS_op", ":", ":destroy", "if", "@stream_connection", "@processing_thread", ".", "join", "5", "if", "@processing_thread", "ensure", "@stream_connection", ".", "disconnect", "if", "@stream_connection", "@processing_thread", ".", "exit", "if", "@processing_thread", "@subscriptions", ".", "each", "{", "|", "subscription", "|", "subscription", ".", "after_control_request", ":stop", "}", "@subscriptions", "=", "[", "]", "@processing_thread", "=", "@stream_connection", "=", "nil", "end" ]
Disconnects this Lightstreamer session and terminates the session on the server. All worker threads are exited, and all subscriptions created during the connected session can no longer be used.
[ "Disconnects", "this", "Lightstreamer", "session", "and", "terminates", "the", "session", "on", "the", "server", ".", "All", "worker", "threads", "are", "exited", "and", "all", "subscriptions", "created", "during", "the", "connected", "session", "can", "no", "longer", "be", "used", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L97-L109
train
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.create_processing_thread
def create_processing_thread @processing_thread = Thread.new do Thread.current.abort_on_exception = true loop { break unless processing_thread_tick @stream_connection.read_line } @processing_thread = @stream_connection = nil end end
ruby
def create_processing_thread @processing_thread = Thread.new do Thread.current.abort_on_exception = true loop { break unless processing_thread_tick @stream_connection.read_line } @processing_thread = @stream_connection = nil end end
[ "def", "create_processing_thread", "@processing_thread", "=", "Thread", ".", "new", "do", "Thread", ".", "current", ".", "abort_on_exception", "=", "true", "loop", "{", "break", "unless", "processing_thread_tick", "@stream_connection", ".", "read_line", "}", "@processing_thread", "=", "@stream_connection", "=", "nil", "end", "end" ]
Starts the processing thread that reads and processes incoming data from the stream connection.
[ "Starts", "the", "processing", "thread", "that", "reads", "and", "processes", "incoming", "data", "from", "the", "stream", "connection", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L308-L316
train
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.process_stream_line
def process_stream_line(line) return if @mutex.synchronize { @subscriptions.any? { |subscription| subscription.process_stream_data line } } return if process_send_message_outcome line warn "Lightstreamer: unprocessed stream data '#{line}'" end
ruby
def process_stream_line(line) return if @mutex.synchronize { @subscriptions.any? { |subscription| subscription.process_stream_data line } } return if process_send_message_outcome line warn "Lightstreamer: unprocessed stream data '#{line}'" end
[ "def", "process_stream_line", "(", "line", ")", "return", "if", "@mutex", ".", "synchronize", "{", "@subscriptions", ".", "any?", "{", "|", "subscription", "|", "subscription", ".", "process_stream_data", "line", "}", "}", "return", "if", "process_send_message_outcome", "line", "warn", "\"Lightstreamer: unprocessed stream data '#{line}'\"", "end" ]
Processes a single line of incoming stream data. This method is always run on the processing thread.
[ "Processes", "a", "single", "line", "of", "incoming", "stream", "data", ".", "This", "method", "is", "always", "run", "on", "the", "processing", "thread", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L329-L334
train
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.process_send_message_outcome
def process_send_message_outcome(line) outcome = SendMessageOutcomeMessage.parse line return unless outcome @mutex.synchronize do @callbacks[:on_message_result].each do |callback| callback.call outcome.sequence, outcome.numbers, outcome.error end end true end
ruby
def process_send_message_outcome(line) outcome = SendMessageOutcomeMessage.parse line return unless outcome @mutex.synchronize do @callbacks[:on_message_result].each do |callback| callback.call outcome.sequence, outcome.numbers, outcome.error end end true end
[ "def", "process_send_message_outcome", "(", "line", ")", "outcome", "=", "SendMessageOutcomeMessage", ".", "parse", "line", "return", "unless", "outcome", "@mutex", ".", "synchronize", "do", "@callbacks", "[", ":on_message_result", "]", ".", "each", "do", "|", "callback", "|", "callback", ".", "call", "outcome", ".", "sequence", ",", "outcome", ".", "numbers", ",", "outcome", ".", "error", "end", "end", "true", "end" ]
Attempts to process the passed line as a send message outcome message.
[ "Attempts", "to", "process", "the", "passed", "line", "as", "a", "send", "message", "outcome", "message", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L337-L348
train
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.vote
def vote(value, voted_by) mark = Vote.new(value: value, voted_by_id: voted_by.id, voter_type: voted_by.class.name) add_vote_mark(mark) end
ruby
def vote(value, voted_by) mark = Vote.new(value: value, voted_by_id: voted_by.id, voter_type: voted_by.class.name) add_vote_mark(mark) end
[ "def", "vote", "(", "value", ",", "voted_by", ")", "mark", "=", "Vote", ".", "new", "(", "value", ":", "value", ",", "voted_by_id", ":", "voted_by", ".", "id", ",", "voter_type", ":", "voted_by", ".", "class", ".", "name", ")", "add_vote_mark", "(", "mark", ")", "end" ]
Creates an embedded vote record and updates number of votes and vote value. @param [Int,Float] value vote value @param [Mongoid::Document] voted_by object from which the vote is done @return [Boolean] success flag
[ "Creates", "an", "embedded", "vote", "record", "and", "updates", "number", "of", "votes", "and", "vote", "value", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L54-L57
train
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.retract
def retract(voted_by) mark = votes.find_by(voted_by_id: voted_by.id) mark && remove_vote_mark(mark) end
ruby
def retract(voted_by) mark = votes.find_by(voted_by_id: voted_by.id) mark && remove_vote_mark(mark) end
[ "def", "retract", "(", "voted_by", ")", "mark", "=", "votes", ".", "find_by", "(", "voted_by_id", ":", "voted_by", ".", "id", ")", "mark", "&&", "remove_vote_mark", "(", "mark", ")", "end" ]
Removes previously added vote. @param [Mongoid::Document] voted_by object from which the vote was done @return [Boolean] success flag
[ "Removes", "previously", "added", "vote", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L63-L66
train
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.voted_by?
def voted_by?(voted_by) !!votes.find_by(voted_by_id: voted_by.id) rescue NoMethodError, Mongoid::Errors::DocumentNotFound false end
ruby
def voted_by?(voted_by) !!votes.find_by(voted_by_id: voted_by.id) rescue NoMethodError, Mongoid::Errors::DocumentNotFound false end
[ "def", "voted_by?", "(", "voted_by", ")", "!", "!", "votes", ".", "find_by", "(", "voted_by_id", ":", "voted_by", ".", "id", ")", "rescue", "NoMethodError", ",", "Mongoid", "::", "Errors", "::", "DocumentNotFound", "false", "end" ]
Indicates whether the document has a vote from particular voter object. @param [Mongoid::Document] voted_by object from which the vote was done @return [Boolean]
[ "Indicates", "whether", "the", "document", "has", "a", "vote", "from", "particular", "voter", "object", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L79-L83
train
barkerest/shells
lib/shells/shell_base/run.rb
Shells.ShellBase.run
def run(&block) sync do raise Shells::AlreadyRunning if running? self.run_flag = true end begin run_hook :on_before_run debug 'Connecting...' connect debug 'Starting output buffering...' buffer_output debug 'Starting session thread...' self.session_thread = Thread.start(self) do |sh| begin begin debug 'Executing setup...' sh.instance_eval { setup } debug 'Executing block...' block.call sh ensure debug 'Executing teardown...' sh.instance_eval { teardown } end rescue Shells::QuitNow # just exit the session. rescue =>e # if the exception is handled by the hook no further processing is required, otherwise we store the exception # to propagate it in the main thread. unless sh.run_hook(:on_exception, e) == :break sh.sync { sh.instance_eval { self.session_exception = e } } end end end # process the input buffer while the thread is alive and the shell is active. debug 'Entering IO loop...' io_loop do if active? begin if session_thread.status # not dead # process input from the session. unless wait_for_output inp = next_input if inp send_data inp self.wait_for_output = (options[:unbuffered_input] == :echo) end end # continue running the IO loop true elsif session_exception # propagate the exception. raise session_exception.class, session_exception.message, session_exception.backtrace else # the thread has exited, but no exception exists. # regardless, the IO loop should now exit. false end rescue IOError if ignore_io_error # we were (sort of) expecting the IO error, so just tell the IO loop to exit. false else raise end end else # the shell session is no longer active, tell the IO loop to exit. false end end rescue # when an error occurs, try to disconnect, but ignore any further errors. begin debug 'Disconnecting...' disconnect rescue # ignore end raise else # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors). begin debug 'Disconnecting...' disconnect rescue IOError raise unless ignore_io_error end ensure # cleanup run_hook :on_after_run self.run_flag = false end self end
ruby
def run(&block) sync do raise Shells::AlreadyRunning if running? self.run_flag = true end begin run_hook :on_before_run debug 'Connecting...' connect debug 'Starting output buffering...' buffer_output debug 'Starting session thread...' self.session_thread = Thread.start(self) do |sh| begin begin debug 'Executing setup...' sh.instance_eval { setup } debug 'Executing block...' block.call sh ensure debug 'Executing teardown...' sh.instance_eval { teardown } end rescue Shells::QuitNow # just exit the session. rescue =>e # if the exception is handled by the hook no further processing is required, otherwise we store the exception # to propagate it in the main thread. unless sh.run_hook(:on_exception, e) == :break sh.sync { sh.instance_eval { self.session_exception = e } } end end end # process the input buffer while the thread is alive and the shell is active. debug 'Entering IO loop...' io_loop do if active? begin if session_thread.status # not dead # process input from the session. unless wait_for_output inp = next_input if inp send_data inp self.wait_for_output = (options[:unbuffered_input] == :echo) end end # continue running the IO loop true elsif session_exception # propagate the exception. raise session_exception.class, session_exception.message, session_exception.backtrace else # the thread has exited, but no exception exists. # regardless, the IO loop should now exit. false end rescue IOError if ignore_io_error # we were (sort of) expecting the IO error, so just tell the IO loop to exit. false else raise end end else # the shell session is no longer active, tell the IO loop to exit. false end end rescue # when an error occurs, try to disconnect, but ignore any further errors. begin debug 'Disconnecting...' disconnect rescue # ignore end raise else # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors). begin debug 'Disconnecting...' disconnect rescue IOError raise unless ignore_io_error end ensure # cleanup run_hook :on_after_run self.run_flag = false end self end
[ "def", "run", "(", "&", "block", ")", "sync", "do", "raise", "Shells", "::", "AlreadyRunning", "if", "running?", "self", ".", "run_flag", "=", "true", "end", "begin", "run_hook", ":on_before_run", "debug", "'Connecting...'", "connect", "debug", "'Starting output buffering...'", "buffer_output", "debug", "'Starting session thread...'", "self", ".", "session_thread", "=", "Thread", ".", "start", "(", "self", ")", "do", "|", "sh", "|", "begin", "begin", "debug", "'Executing setup...'", "sh", ".", "instance_eval", "{", "setup", "}", "debug", "'Executing block...'", "block", ".", "call", "sh", "ensure", "debug", "'Executing teardown...'", "sh", ".", "instance_eval", "{", "teardown", "}", "end", "rescue", "Shells", "::", "QuitNow", "rescue", "=>", "e", "unless", "sh", ".", "run_hook", "(", ":on_exception", ",", "e", ")", "==", ":break", "sh", ".", "sync", "{", "sh", ".", "instance_eval", "{", "self", ".", "session_exception", "=", "e", "}", "}", "end", "end", "end", "debug", "'Entering IO loop...'", "io_loop", "do", "if", "active?", "begin", "if", "session_thread", ".", "status", "unless", "wait_for_output", "inp", "=", "next_input", "if", "inp", "send_data", "inp", "self", ".", "wait_for_output", "=", "(", "options", "[", ":unbuffered_input", "]", "==", ":echo", ")", "end", "end", "true", "elsif", "session_exception", "raise", "session_exception", ".", "class", ",", "session_exception", ".", "message", ",", "session_exception", ".", "backtrace", "else", "false", "end", "rescue", "IOError", "if", "ignore_io_error", "false", "else", "raise", "end", "end", "else", "false", "end", "end", "rescue", "begin", "debug", "'Disconnecting...'", "disconnect", "rescue", "end", "raise", "else", "begin", "debug", "'Disconnecting...'", "disconnect", "rescue", "IOError", "raise", "unless", "ignore_io_error", "end", "ensure", "run_hook", ":on_after_run", "self", ".", "run_flag", "=", "false", "end", "self", "end" ]
Runs a shell session. The block provided will be run asynchronously with the shell. Returns the shell instance.
[ "Runs", "a", "shell", "session", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/run.rb#L55-L155
train
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.fast_forward
def fast_forward(dt) adjusted_dt = dt * @relative_rate @now += adjusted_dt @children.each { |sub_clock| sub_clock.fast_forward(adjusted_dt) } end
ruby
def fast_forward(dt) adjusted_dt = dt * @relative_rate @now += adjusted_dt @children.each { |sub_clock| sub_clock.fast_forward(adjusted_dt) } end
[ "def", "fast_forward", "(", "dt", ")", "adjusted_dt", "=", "dt", "*", "@relative_rate", "@now", "+=", "adjusted_dt", "@children", ".", "each", "{", "|", "sub_clock", "|", "sub_clock", ".", "fast_forward", "(", "adjusted_dt", ")", "}", "end" ]
fast-forward this clock and all children clocks by the given time delta
[ "fast", "-", "forward", "this", "clock", "and", "all", "children", "clocks", "by", "the", "given", "time", "delta" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L51-L55
train
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.schedule
def schedule(obj, time = nil) time ||= now @occurrences[obj] = time parent.schedule([:clock, self], unscale_time(time)) if parent && @occurrences.min_key == obj end
ruby
def schedule(obj, time = nil) time ||= now @occurrences[obj] = time parent.schedule([:clock, self], unscale_time(time)) if parent && @occurrences.min_key == obj end
[ "def", "schedule", "(", "obj", ",", "time", "=", "nil", ")", "time", "||=", "now", "@occurrences", "[", "obj", "]", "=", "time", "parent", ".", "schedule", "(", "[", ":clock", ",", "self", "]", ",", "unscale_time", "(", "time", ")", ")", "if", "parent", "&&", "@occurrences", ".", "min_key", "==", "obj", "end" ]
schedules an occurrence at the given time with the given object, defaulting to the current time
[ "schedules", "an", "occurrence", "at", "the", "given", "time", "with", "the", "given", "object", "defaulting", "to", "the", "current", "time" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L67-L71
train
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.unschedule
def unschedule(obj) if @occurrences.has_key? obj last_priority = @occurrences.min_priority obj, time = @occurrences.delete obj if parent && @occurrences.min_priority != last_priority if @occurrences.min_priority parent.schedule([:clock, self], unscale_time(@occurrences.min_priority)) else parent.unschedule([:clock, self]) end end unscale_time(time) else relative_time = @children.first_non_nil { |clock| clock.unschedule(obj) } unscale_relative_time(relative_time) if relative_time end end
ruby
def unschedule(obj) if @occurrences.has_key? obj last_priority = @occurrences.min_priority obj, time = @occurrences.delete obj if parent && @occurrences.min_priority != last_priority if @occurrences.min_priority parent.schedule([:clock, self], unscale_time(@occurrences.min_priority)) else parent.unschedule([:clock, self]) end end unscale_time(time) else relative_time = @children.first_non_nil { |clock| clock.unschedule(obj) } unscale_relative_time(relative_time) if relative_time end end
[ "def", "unschedule", "(", "obj", ")", "if", "@occurrences", ".", "has_key?", "obj", "last_priority", "=", "@occurrences", ".", "min_priority", "obj", ",", "time", "=", "@occurrences", ".", "delete", "obj", "if", "parent", "&&", "@occurrences", ".", "min_priority", "!=", "last_priority", "if", "@occurrences", ".", "min_priority", "parent", ".", "schedule", "(", "[", ":clock", ",", "self", "]", ",", "unscale_time", "(", "@occurrences", ".", "min_priority", ")", ")", "else", "parent", ".", "unschedule", "(", "[", ":clock", ",", "self", "]", ")", "end", "end", "unscale_time", "(", "time", ")", "else", "relative_time", "=", "@children", ".", "first_non_nil", "{", "|", "clock", "|", "clock", ".", "unschedule", "(", "obj", ")", "}", "unscale_relative_time", "(", "relative_time", ")", "if", "relative_time", "end", "end" ]
dequeues the earliest occurrence from this clock or any child clocks. returns nil if it wasn't there, or its relative_time otherwise
[ "dequeues", "the", "earliest", "occurrence", "from", "this", "clock", "or", "any", "child", "clocks", ".", "returns", "nil", "if", "it", "wasn", "t", "there", "or", "its", "relative_time", "otherwise" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L75-L91
train
jphager2/search_me
lib/search_me/search.rb
SearchMe.Search.attr_search
def attr_search(*attributes) options = attributes.last.is_a?(Hash) ? attributes.pop : {} type = (options.fetch(:type) { :simple }).to_sym accepted_keys = [:simple] + self.reflections.keys.map(&:to_sym) unless accepted_keys.include?(type.to_sym) raise ArgumentError, 'incorect type given' end search_attributes_hash!(attributes, type, search_attributes) end
ruby
def attr_search(*attributes) options = attributes.last.is_a?(Hash) ? attributes.pop : {} type = (options.fetch(:type) { :simple }).to_sym accepted_keys = [:simple] + self.reflections.keys.map(&:to_sym) unless accepted_keys.include?(type.to_sym) raise ArgumentError, 'incorect type given' end search_attributes_hash!(attributes, type, search_attributes) end
[ "def", "attr_search", "(", "*", "attributes", ")", "options", "=", "attributes", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "attributes", ".", "pop", ":", "{", "}", "type", "=", "(", "options", ".", "fetch", "(", ":type", ")", "{", ":simple", "}", ")", ".", "to_sym", "accepted_keys", "=", "[", ":simple", "]", "+", "self", ".", "reflections", ".", "keys", ".", "map", "(", "&", ":to_sym", ")", "unless", "accepted_keys", ".", "include?", "(", "type", ".", "to_sym", ")", "raise", "ArgumentError", ",", "'incorect type given'", "end", "search_attributes_hash!", "(", "attributes", ",", "type", ",", "search_attributes", ")", "end" ]
assuming the last attribute could be a hash
[ "assuming", "the", "last", "attribute", "could", "be", "a", "hash" ]
22057dd6008a7022247bca5ad30450a3abbee9df
https://github.com/jphager2/search_me/blob/22057dd6008a7022247bca5ad30450a3abbee9df/lib/search_me/search.rb#L18-L28
train
JuanGongora/mtg-card-finder
lib/mtg_card_finder/concerns/persistable.rb
Persistable.ClassMethods.reify_from_row
def reify_from_row(row) #the tap method allows preconfigured methods and values to #be associated with the instance during instantiation while also automatically returning #the object after its creation is concluded. self.new.tap do |card| self.attributes.keys.each.with_index do |key, index| #sending the new instance the key name as a setter with the value located at the 'row' index card.send("#{key}=", row[index]) #string interpolation is used as the method doesn't know the key name yet #but an = sign is implemented into the string in order to asssociate it as a setter end end end
ruby
def reify_from_row(row) #the tap method allows preconfigured methods and values to #be associated with the instance during instantiation while also automatically returning #the object after its creation is concluded. self.new.tap do |card| self.attributes.keys.each.with_index do |key, index| #sending the new instance the key name as a setter with the value located at the 'row' index card.send("#{key}=", row[index]) #string interpolation is used as the method doesn't know the key name yet #but an = sign is implemented into the string in order to asssociate it as a setter end end end
[ "def", "reify_from_row", "(", "row", ")", "self", ".", "new", ".", "tap", "do", "|", "card", "|", "self", ".", "attributes", ".", "keys", ".", "each", ".", "with_index", "do", "|", "key", ",", "index", "|", "card", ".", "send", "(", "\"#{key}=\"", ",", "row", "[", "index", "]", ")", "end", "end", "end" ]
opposite of abstraction is reification i.e. I'm getting the raw data of these variables
[ "opposite", "of", "abstraction", "is", "reification", "i", ".", "e", ".", "I", "m", "getting", "the", "raw", "data", "of", "these", "variables" ]
a4d2ed1368f4cff8c6f51a1b96ce3a4c3dabfbef
https://github.com/JuanGongora/mtg-card-finder/blob/a4d2ed1368f4cff8c6f51a1b96ce3a4c3dabfbef/lib/mtg_card_finder/concerns/persistable.rb#L130-L142
train
barkerest/shells
lib/shells/shell_base/exec.rb
Shells.ShellBase.exec
def exec(command, options = {}, &block) raise Shells::NotRunning unless running? options ||= {} options = { timeout_error: true, get_output: true }.merge(options) options = self.options.merge(options.inject({}) { |m,(k,v)| m[k.to_sym] = v; m }) options[:retrieve_exit_code] = self.options[:retrieve_exit_code] if options[:retrieve_exit_code] == :default options[:on_non_zero_exit_code] = self.options[:on_non_zero_exit_code] unless [:raise, :ignore].include?(options[:on_non_zero_exit_code]) options[:silence_timeout] = self.options[:silence_timeout] if options[:silence_timeout] == :default options[:command_timeout] = self.options[:command_timeout] if options[:command_timeout] == :default options[:command_is_echoed] = true if options[:command_is_echoed].nil? ret = '' merge_local_buffer do begin # buffer while also passing data to the supplied block. if block_given? buffer_output(&block) end command = command.to_s # send the command and wait for the prompt to return. debug 'Queueing command: ' + command queue_input command + line_ending if wait_for_prompt(options[:silence_timeout], options[:command_timeout], options[:timeout_error]) # get the output of the command, minus the trailing prompt. ret = if options[:get_output] debug 'Reading output of command...' command_output command, options[:command_is_echoed] else '' end if options[:retrieve_exit_code] self.last_exit_code = get_exit_code if options[:on_non_zero_exit_code] == :raise raise NonZeroExitCode.new(last_exit_code) unless last_exit_code == 0 || last_exit_code == :undefined end else self.last_exit_code = nil end else # A timeout occurred and timeout_error was set to false. self.last_exit_code = :timeout ret = output end ensure # return buffering to normal. if block_given? buffer_output end end end ret end
ruby
def exec(command, options = {}, &block) raise Shells::NotRunning unless running? options ||= {} options = { timeout_error: true, get_output: true }.merge(options) options = self.options.merge(options.inject({}) { |m,(k,v)| m[k.to_sym] = v; m }) options[:retrieve_exit_code] = self.options[:retrieve_exit_code] if options[:retrieve_exit_code] == :default options[:on_non_zero_exit_code] = self.options[:on_non_zero_exit_code] unless [:raise, :ignore].include?(options[:on_non_zero_exit_code]) options[:silence_timeout] = self.options[:silence_timeout] if options[:silence_timeout] == :default options[:command_timeout] = self.options[:command_timeout] if options[:command_timeout] == :default options[:command_is_echoed] = true if options[:command_is_echoed].nil? ret = '' merge_local_buffer do begin # buffer while also passing data to the supplied block. if block_given? buffer_output(&block) end command = command.to_s # send the command and wait for the prompt to return. debug 'Queueing command: ' + command queue_input command + line_ending if wait_for_prompt(options[:silence_timeout], options[:command_timeout], options[:timeout_error]) # get the output of the command, minus the trailing prompt. ret = if options[:get_output] debug 'Reading output of command...' command_output command, options[:command_is_echoed] else '' end if options[:retrieve_exit_code] self.last_exit_code = get_exit_code if options[:on_non_zero_exit_code] == :raise raise NonZeroExitCode.new(last_exit_code) unless last_exit_code == 0 || last_exit_code == :undefined end else self.last_exit_code = nil end else # A timeout occurred and timeout_error was set to false. self.last_exit_code = :timeout ret = output end ensure # return buffering to normal. if block_given? buffer_output end end end ret end
[ "def", "exec", "(", "command", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "options", "||=", "{", "}", "options", "=", "{", "timeout_error", ":", "true", ",", "get_output", ":", "true", "}", ".", "merge", "(", "options", ")", "options", "=", "self", ".", "options", ".", "merge", "(", "options", ".", "inject", "(", "{", "}", ")", "{", "|", "m", ",", "(", "k", ",", "v", ")", "|", "m", "[", "k", ".", "to_sym", "]", "=", "v", ";", "m", "}", ")", "options", "[", ":retrieve_exit_code", "]", "=", "self", ".", "options", "[", ":retrieve_exit_code", "]", "if", "options", "[", ":retrieve_exit_code", "]", "==", ":default", "options", "[", ":on_non_zero_exit_code", "]", "=", "self", ".", "options", "[", ":on_non_zero_exit_code", "]", "unless", "[", ":raise", ",", ":ignore", "]", ".", "include?", "(", "options", "[", ":on_non_zero_exit_code", "]", ")", "options", "[", ":silence_timeout", "]", "=", "self", ".", "options", "[", ":silence_timeout", "]", "if", "options", "[", ":silence_timeout", "]", "==", ":default", "options", "[", ":command_timeout", "]", "=", "self", ".", "options", "[", ":command_timeout", "]", "if", "options", "[", ":command_timeout", "]", "==", ":default", "options", "[", ":command_is_echoed", "]", "=", "true", "if", "options", "[", ":command_is_echoed", "]", ".", "nil?", "ret", "=", "''", "merge_local_buffer", "do", "begin", "if", "block_given?", "buffer_output", "(", "&", "block", ")", "end", "command", "=", "command", ".", "to_s", "debug", "'Queueing command: '", "+", "command", "queue_input", "command", "+", "line_ending", "if", "wait_for_prompt", "(", "options", "[", ":silence_timeout", "]", ",", "options", "[", ":command_timeout", "]", ",", "options", "[", ":timeout_error", "]", ")", "ret", "=", "if", "options", "[", ":get_output", "]", "debug", "'Reading output of command...'", "command_output", "command", ",", "options", "[", ":command_is_echoed", "]", "else", "''", "end", "if", "options", "[", ":retrieve_exit_code", "]", "self", ".", "last_exit_code", "=", "get_exit_code", "if", "options", "[", ":on_non_zero_exit_code", "]", "==", ":raise", "raise", "NonZeroExitCode", ".", "new", "(", "last_exit_code", ")", "unless", "last_exit_code", "==", "0", "||", "last_exit_code", "==", ":undefined", "end", "else", "self", ".", "last_exit_code", "=", "nil", "end", "else", "self", ".", "last_exit_code", "=", ":timeout", "ret", "=", "output", "end", "ensure", "if", "block_given?", "buffer_output", "end", "end", "end", "ret", "end" ]
Executes a command during the shell session. If called outside of the +new+ block, this will raise an error. The +command+ is the command to execute in the shell. The +options+ can be used to override the exit code behavior. In all cases, the :default option is the same as not providing the option and will cause +exec+ to inherit the option from the shell's options. +retrieve_exit_code+:: This can be one of :default, true, or false. +on_non_zero_exit_code+:: This can be on ot :default, :ignore, or :raise. +silence_timeout+:: This can be :default or the number of seconds to wait in silence before timing out. +command_timeout+:: This can be :default or the maximum number of seconds to wait for a command to finish before timing out. If provided, the +block+ is a chunk of code that will be processed every time the shell receives output from the program. If the block returns a string, the string will be sent to the shell. This can be used to monitor processes or monitor and interact with processes. The +block+ is optional. shell.exec('sudo -p "password:" nginx restart') do |data,type| return 'super-secret' if /password:$/.match(data) nil end
[ "Executes", "a", "command", "during", "the", "shell", "session", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/exec.rb#L51-L110
train
barkerest/shells
lib/shells/shell_base/exec.rb
Shells.ShellBase.command_output
def command_output(command, expect_command = true) #:doc: # get everything except for the ending prompt. ret = if (prompt_pos = (output =~ prompt_match)) output[0...prompt_pos] else output end if expect_command command_regex = command_match(command) # Go until we run out of data or we find one of the possible command starts. # Note that we EXPECT the command to the first line of the output from the command because we expect the # shell to echo it back to us. result_cmd,_,result_data = ret.partition("\n") until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex result_cmd,_,result_data = result_data.partition("\n") end if result_cmd.nil? || !(result_cmd =~ command_regex) STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}." end result_data else ret end end
ruby
def command_output(command, expect_command = true) #:doc: # get everything except for the ending prompt. ret = if (prompt_pos = (output =~ prompt_match)) output[0...prompt_pos] else output end if expect_command command_regex = command_match(command) # Go until we run out of data or we find one of the possible command starts. # Note that we EXPECT the command to the first line of the output from the command because we expect the # shell to echo it back to us. result_cmd,_,result_data = ret.partition("\n") until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex result_cmd,_,result_data = result_data.partition("\n") end if result_cmd.nil? || !(result_cmd =~ command_regex) STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}." end result_data else ret end end
[ "def", "command_output", "(", "command", ",", "expect_command", "=", "true", ")", "ret", "=", "if", "(", "prompt_pos", "=", "(", "output", "=~", "prompt_match", ")", ")", "output", "[", "0", "...", "prompt_pos", "]", "else", "output", "end", "if", "expect_command", "command_regex", "=", "command_match", "(", "command", ")", "result_cmd", ",", "_", ",", "result_data", "=", "ret", ".", "partition", "(", "\"\\n\"", ")", "until", "result_data", ".", "to_s", ".", "strip", "==", "''", "||", "result_cmd", ".", "strip", "=~", "command_regex", "result_cmd", ",", "_", ",", "result_data", "=", "result_data", ".", "partition", "(", "\"\\n\"", ")", "end", "if", "result_cmd", ".", "nil?", "||", "!", "(", "result_cmd", "=~", "command_regex", ")", "STDERR", ".", "puts", "\"SHELL WARNING: Failed to match #{command_regex.inspect}.\"", "end", "result_data", "else", "ret", "end", "end" ]
Gets the output from a command.
[ "Gets", "the", "output", "from", "a", "command", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/exec.rb#L135-L163
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.decrypt
def decrypt(encrypted_text, password = nil, salt = nil) password = password.nil? ? Garcon.crypto.password : password salt = salt.nil? ? Garcon.crypto.salt : salt iv_ciphertext = Base64.decode64(encrypted_text) cipher = new_cipher(:decrypt, password, salt) cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext) plain_text = cipher.update(ciphertext) plain_text << cipher.final plain_text end
ruby
def decrypt(encrypted_text, password = nil, salt = nil) password = password.nil? ? Garcon.crypto.password : password salt = salt.nil? ? Garcon.crypto.salt : salt iv_ciphertext = Base64.decode64(encrypted_text) cipher = new_cipher(:decrypt, password, salt) cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext) plain_text = cipher.update(ciphertext) plain_text << cipher.final plain_text end
[ "def", "decrypt", "(", "encrypted_text", ",", "password", "=", "nil", ",", "salt", "=", "nil", ")", "password", "=", "password", ".", "nil?", "?", "Garcon", ".", "crypto", ".", "password", ":", "password", "salt", "=", "salt", ".", "nil?", "?", "Garcon", ".", "crypto", ".", "salt", ":", "salt", "iv_ciphertext", "=", "Base64", ".", "decode64", "(", "encrypted_text", ")", "cipher", "=", "new_cipher", "(", ":decrypt", ",", "password", ",", "salt", ")", "cipher", ".", "iv", ",", "ciphertext", "=", "separate_iv_ciphertext", "(", "cipher", ",", "iv_ciphertext", ")", "plain_text", "=", "cipher", ".", "update", "(", "ciphertext", ")", "plain_text", "<<", "cipher", ".", "final", "plain_text", "end" ]
Decrypt the given string, using the salt and password supplied. @param [String] encrypted_text The text to decrypt, probably produced with #decrypt. @param [String] password Secret passphrase to decrypt with. @param [String] salt The cryptographically secure pseudo-random string used to spice up the encryption of your strings. @return [String] The decrypted plain_text. @api public
[ "Decrypt", "the", "given", "string", "using", "the", "salt", "and", "password", "supplied", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L180-L190
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.salted_hash
def salted_hash(password) salt = SecureRandom.random_bytes(SALT_BYTE_SIZE) pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1( password, salt, CRYPTERATIONS, HASH_BYTE_SIZE ) { salt: salt, pbkdf2: Base64.encode64(pbkdf2) } end
ruby
def salted_hash(password) salt = SecureRandom.random_bytes(SALT_BYTE_SIZE) pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1( password, salt, CRYPTERATIONS, HASH_BYTE_SIZE ) { salt: salt, pbkdf2: Base64.encode64(pbkdf2) } end
[ "def", "salted_hash", "(", "password", ")", "salt", "=", "SecureRandom", ".", "random_bytes", "(", "SALT_BYTE_SIZE", ")", "pbkdf2", "=", "OpenSSL", "::", "PKCS5", "::", "pbkdf2_hmac_sha1", "(", "password", ",", "salt", ",", "CRYPTERATIONS", ",", "HASH_BYTE_SIZE", ")", "{", "salt", ":", "salt", ",", "pbkdf2", ":", "Base64", ".", "encode64", "(", "pbkdf2", ")", "}", "end" ]
Generates a special hash known as a SPASH, a PBKDF2-HMAC-SHA1 Salted Password Hash for safekeeping. @param [String] password A password to generating the SPASH, salted password hash. @return [Hash] `:salt` contains the unique salt used, `:pbkdf2` contains the password hash. Save both the salt and the hash together. @see Garcon::Crypto#validate_salt @api public
[ "Generates", "a", "special", "hash", "known", "as", "a", "SPASH", "a", "PBKDF2", "-", "HMAC", "-", "SHA1", "Salted", "Password", "Hash", "for", "safekeeping", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L205-L212
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.new_cipher
def new_cipher(direction, password, salt) cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE) direction == :encrypt ? cipher.encrypt : cipher.decrypt cipher.key = encrypt_key(password, salt) cipher end
ruby
def new_cipher(direction, password, salt) cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE) direction == :encrypt ? cipher.encrypt : cipher.decrypt cipher.key = encrypt_key(password, salt) cipher end
[ "def", "new_cipher", "(", "direction", ",", "password", ",", "salt", ")", "cipher", "=", "OpenSSL", "::", "Cipher", "::", "Cipher", ".", "new", "(", "CIPHER_TYPE", ")", "direction", "==", ":encrypt", "?", "cipher", ".", "encrypt", ":", "cipher", ".", "decrypt", "cipher", ".", "key", "=", "encrypt_key", "(", "password", ",", "salt", ")", "cipher", "end" ]
A T T E N Z I O N E A R E A P R O T E T T A Create a new cipher machine, with its dials set in the given direction. @param [Symbol] direction Whether to `:encrypt` or `:decrypt`. @param [String] pass Secret passphrase to decrypt with. @api private
[ "A", "T", "T", "E", "N", "Z", "I", "O", "N", "E", "A", "R", "E", "A", "P", "R", "O", "T", "E", "T", "T", "A", "Create", "a", "new", "cipher", "machine", "with", "its", "dials", "set", "in", "the", "given", "direction", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L256-L261
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.combine_iv_ciphertext
def combine_iv_ciphertext(iv, message) message.force_encoding('BINARY') if message.respond_to?(:force_encoding) iv.force_encoding('BINARY') if iv.respond_to?(:force_encoding) iv + message end
ruby
def combine_iv_ciphertext(iv, message) message.force_encoding('BINARY') if message.respond_to?(:force_encoding) iv.force_encoding('BINARY') if iv.respond_to?(:force_encoding) iv + message end
[ "def", "combine_iv_ciphertext", "(", "iv", ",", "message", ")", "message", ".", "force_encoding", "(", "'BINARY'", ")", "if", "message", ".", "respond_to?", "(", ":force_encoding", ")", "iv", ".", "force_encoding", "(", "'BINARY'", ")", "if", "iv", ".", "respond_to?", "(", ":force_encoding", ")", "iv", "+", "message", "end" ]
Prepend the initialization vector to the encoded message. @api private
[ "Prepend", "the", "initialization", "vector", "to", "the", "encoded", "message", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L266-L270
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.separate_iv_ciphertext
def separate_iv_ciphertext(cipher, iv_ciphertext) idx = cipher.iv_len [iv_ciphertext[0..(idx - 1)], iv_ciphertext[idx..-1]] end
ruby
def separate_iv_ciphertext(cipher, iv_ciphertext) idx = cipher.iv_len [iv_ciphertext[0..(idx - 1)], iv_ciphertext[idx..-1]] end
[ "def", "separate_iv_ciphertext", "(", "cipher", ",", "iv_ciphertext", ")", "idx", "=", "cipher", ".", "iv_len", "[", "iv_ciphertext", "[", "0", "..", "(", "idx", "-", "1", ")", "]", ",", "iv_ciphertext", "[", "idx", "..", "-", "1", "]", "]", "end" ]
Pull the initialization vector from the front of the encoded message. @api private
[ "Pull", "the", "initialization", "vector", "from", "the", "front", "of", "the", "encoded", "message", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L275-L278
train
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.encrypt_key
def encrypt_key(password, salt) iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length) end
ruby
def encrypt_key(password, salt) iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length) end
[ "def", "encrypt_key", "(", "password", ",", "salt", ")", "iterations", ",", "length", "=", "CRYPTERATIONS", ",", "HASH_BYTE_SIZE", "OpenSSL", "::", "PKCS5", "::", "pbkdf2_hmac_sha1", "(", "password", ",", "salt", ",", "iterations", ",", "length", ")", "end" ]
Convert the password into a PBKDF2-HMAC-SHA1 salted key used for safely encrypting and decrypting all your ciphers strings. @api private
[ "Convert", "the", "password", "into", "a", "PBKDF2", "-", "HMAC", "-", "SHA1", "salted", "key", "used", "for", "safely", "encrypting", "and", "decrypting", "all", "your", "ciphers", "strings", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L284-L287
train