repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
marcandre/scheherazade
321e8e5f9f84c777168de10de8df6075141be215
lib/scheherazade/character_builder.rb
https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/character_builder.rb#L144-L163
ruby
test
# Converts an attribute_list to a single Hash; # some of the values may be set to AUTO. # # canonical [:foo, {:bar => 42}] # # => {:foo => AUTO, :bar => 42}
def canonical(attribute_list)
# Converts an attribute_list to a single Hash; # some of the values may be set to AUTO. # # canonical [:foo, {:bar => 42}] # # => {:foo => AUTO, :bar => 42} def canonical(attribute_list)
case attribute_list when nil then {} when Hash then attribute_list when Array attribute_list.map do |attributes| case attributes when Symbol {attributes => AUTO} when Hash attributes else raise "Unexpected attributes #{attributes}" end end .inject({}, :merge) else raise "Unexpected attribute_list #{attribute_list}" end end
marcandre/scheherazade
321e8e5f9f84c777168de10de8df6075141be215
lib/scheherazade/story.rb
https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/story.rb#L117-L133
ruby
test
# Creates a character with the given attributes # # A character can be designated either by the model (e.g. `User`), the corresponding # symbol (`:user`) or the symbol for a specialized type of character, defined using +fill+ # (e.g. `:admin`). # # The attributes can be nil, a list of symbols, a hash or a combination of both # These, along with attributes passed to +fill+ for the current stories # and the mandatory attributes for the model will be provided. # # If some fields generate validation errors, they will be provided also. # # For associations, the values can also be a character (Symbol or Model), # integers (meaning the default Model * that integer) or arrays of characters. # # imagine(:user, :account, :company => :fortune_500_company, :emails => 3) # # Similarly: # # User.imagine(...) # :user.imagine(...) # # This record (and any other imagined through associations) will become the # current character in the current story: # # story.current[User] # => nil # story.tell do # :admin.imagine # => A User record # story.current[:admin] # => same # story.current[User] # => same # end # story.current[User] # => nil
def imagine(character_or_model, attributes = nil)
# Creates a character with the given attributes # # A character can be designated either by the model (e.g. `User`), the corresponding # symbol (`:user`) or the symbol for a specialized type of character, defined using +fill+ # (e.g. `:admin`). # # The attributes can be nil, a list of symbols, a hash or a combination of both # These, along with attributes passed to +fill+ for the current stories # and the mandatory attributes for the model will be provided. # # If some fields generate validation errors, they will be provided also. # # For associations, the values can also be a character (Symbol or Model), # integers (meaning the default Model * that integer) or arrays of characters. # # imagine(:user, :account, :company => :fortune_500_company, :emails => 3) # # Similarly: # # User.imagine(...) # :user.imagine(...) # # This record (and any other imagined through associations) will become the # current character in the current story: # # story.current[User] # => nil # story.tell do # :admin.imagine # => A User record # story.current[:admin] # => same # story.current[User] # => same # end # story.current[User] # => nil def imagine(character_or_model, attributes = nil)
character = to_character(character_or_model) prev, @building = @building, [] # because method might be re-entrant CharacterBuilder.new(character).build(attributes) do |ar| ar.save! # While errors on records associated with :has_many will prevent records # from being saved, they won't for :belongs_to, so: @building.each do |built| raise ActiveRecord::RecordInvalid, built unless built.persisted? || built.valid? end Scheherazade.log(:saving, character, ar) handle_callbacks(@building) end ensure @built.concat(@building) @building = prev end
marcandre/scheherazade
321e8e5f9f84c777168de10de8df6075141be215
lib/scheherazade/story.rb
https://github.com/marcandre/scheherazade/blob/321e8e5f9f84c777168de10de8df6075141be215/lib/scheherazade/story.rb#L142-L149
ruby
test
# Allows one to temporarily override the current characters while # the given block executes
def with(temp_current)
# Allows one to temporarily override the current characters while # the given block executes def with(temp_current)
keys = temp_current.keys.map{|k| to_character(k)} previous_values = current.values_at(*keys) current.merge!(Hash[keys.zip(temp_current.values)]) yield ensure current.merge!(Hash[keys.zip(previous_values)]) end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L5-L12
ruby
test
# GET /achievements # GET /achievements.xml
def index
# GET /achievements # GET /achievements.xml def index
@achievements = Achievement.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @achievements } end end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L16-L24
ruby
test
# GET /achievements/1 # GET /achievements/1.xml
def show
# GET /achievements/1 # GET /achievements/1.xml def show
@achievement = Achievement.find(params[:id]) @conditions = @achievement.achievement_conditions respond_to do |format| format.html # show.html.erb format.xml { render :xml => @achievement } end end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L28-L35
ruby
test
# GET /achievements/new # GET /achievements/new.xml
def new
# GET /achievements/new # GET /achievements/new.xml def new
@achievement = Achievement.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @achievement } end end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L44-L59
ruby
test
# POST /achievements # POST /achievements.xml
def create
# POST /achievements # POST /achievements.xml def create
@achievement = Achievement.new(params[:triumph_achievement]) @achievement.observe_class.singularize.downcase! if @achievement.save achievement_condition = AchievementCondition.new(params[:achievement_condition]) achievement_condition.achievement_id = @achievement.id if achievement_condition.save redirect_to(@achievement, :notice => 'Achievement was successfully created.') else flash[:error] = "Failed to save achievement conditions" end else render :action => "new" end end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L63-L76
ruby
test
# PUT /achievements/1 # PUT /achievements/1.xml
def update
# PUT /achievements/1 # PUT /achievements/1.xml def update
@achievement = Achievement.find(params[:id]) @achievement.observe_class.downcase! respond_to do |format| if @achievement.update_attributes(params[:triumph_achievement]) format.html { redirect_to(@achievement, :notice => 'Achievement was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @achievement.errors, :status => :unprocessable_entity } end end end
adambray/triumph
e8b9ee9f8eff96e88b4e44a2a394b94f13811df1
app/controllers/triumph/achievements_controller.rb
https://github.com/adambray/triumph/blob/e8b9ee9f8eff96e88b4e44a2a394b94f13811df1/app/controllers/triumph/achievements_controller.rb#L80-L88
ruby
test
# DELETE /achievements/1 # DELETE /achievements/1.xml
def destroy
# DELETE /achievements/1 # DELETE /achievements/1.xml def destroy
@achievement = Achievement.find(params[:id]) @achievement.destroy respond_to do |format| format.html { redirect_to(triumph_achievements_url) } format.xml { head :ok } end end
menglifang/task-manager
c6196c0e30d27d008f406321b0abb7e3fb9c02c6
app/models/task_manager/task.rb
https://github.com/menglifang/task-manager/blob/c6196c0e30d27d008f406321b0abb7e3fb9c02c6/app/models/task_manager/task.rb#L46-L52
ruby
test
# 提醒任务执行者,任务即将到期,并且修改任务下次提醒时间。 # 如果`next_reminding_at`返回`nil`,则表示该任务不再需要提醒。
def remind
# 提醒任务执行者,任务即将到期,并且修改任务下次提醒时间。 # 如果`next_reminding_at`返回`nil`,则表示该任务不再需要提醒。 def remind
Task.transaction do assignee.remind_of_expiring_task(self) if assignee.respond_to?(:remind_of_expiring_task) update_attributes!(reminding_at: next_reminding_at) end end
samstokes/deferrable_gratification
254d72b5c65e4d2a264013420036a9012d7d8425
lib/deferrable_gratification/primitives.rb
https://github.com/samstokes/deferrable_gratification/blob/254d72b5c65e4d2a264013420036a9012d7d8425/lib/deferrable_gratification/primitives.rb#L37-L50
ruby
test
# Return a Deferrable which immediately fails with an exception. # # @overload failure(message) # Passes +RuntimeError.new(message)+ to errbacks. # @overload failure(exception_class) # Passes +exception_class.new+ to errbacks. # @overload failure(exception_class, message) # Passes +exception_class.new(message)+ to errbacks. # @overload failure(exception) # Passes +exception+ to errbacks.
def failure(exception_class_or_message, message_or_nil = nil)
# Return a Deferrable which immediately fails with an exception. # # @overload failure(message) # Passes +RuntimeError.new(message)+ to errbacks. # @overload failure(exception_class) # Passes +exception_class.new+ to errbacks. # @overload failure(exception_class, message) # Passes +exception_class.new(message)+ to errbacks. # @overload failure(exception) # Passes +exception+ to errbacks. def failure(exception_class_or_message, message_or_nil = nil)
blank.tap do |d| d.fail( case exception_class_or_message when Exception raise ArgumentError, "can't specify both exception and message" if message_or_nil exception_class_or_message when Class exception_class_or_message.new(message_or_nil) else RuntimeError.new(exception_class_or_message.to_s) end) end end
odarriba/fantastic_robot
5922d8d3a759a47a21ab9ac62ebc8759ad97495a
lib/fantastic_robot/request/send_audio.rb
https://github.com/odarriba/fantastic_robot/blob/5922d8d3a759a47a21ab9ac62ebc8759ad97495a/lib/fantastic_robot/request/send_audio.rb#L23-L30
ruby
test
# Function to check that the file size isn't excesive.
def file_length
# Function to check that the file size isn't excesive. def file_length
if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE self.errors.add :audio, "It's length is excesive. #{MAX_FILE_SIZE} is the limit." return false end return true end
odarriba/fantastic_robot
5922d8d3a759a47a21ab9ac62ebc8759ad97495a
lib/fantastic_robot/connection.rb
https://github.com/odarriba/fantastic_robot/blob/5922d8d3a759a47a21ab9ac62ebc8759ad97495a/lib/fantastic_robot/connection.rb#L19-L29
ruby
test
# Function to call API passing a payload
def api_call method, payload
# Function to call API passing a payload def api_call method, payload
raise ArgumentError, "API method not specified." if method.blank? payload ||= {} res = @conn.post method.to_s, payload raise Faraday::Error, "Wrong response: #{res.inspect}" if (res.status != 200) return res end
d11wtq/oedipus
37af27d0e5cd7d23896fd0d8f61134a962fc290f
lib/oedipus/index.rb
https://github.com/d11wtq/oedipus/blob/37af27d0e5cd7d23896fd0d8f61134a962fc290f/lib/oedipus/index.rb#L218-L244
ruby
test
# Perform a a batch search on the index. # # A Hash of queries is passed, whose keys are used to collate the results in # the return value. # # Each query may either by a string (fulltext search), a Hash (attribute search) # or an array containing both. In other words, the same arguments accepted by # the #search method. # # @example # index.multi_search( # cat_results: ["cats", { author_id: 57 }], # dog_results: ["dogs", { author_id: 57 }] # ) # # @param [Hash] queries # a hash whose keys map to queries # # @return [Hash] # a Hash whose keys map 1:1 with the input Hash, each element containing the # same results as those returned by the #search method.
def multi_search(queries)
# Perform a a batch search on the index. # # A Hash of queries is passed, whose keys are used to collate the results in # the return value. # # Each query may either by a string (fulltext search), a Hash (attribute search) # or an array containing both. In other words, the same arguments accepted by # the #search method. # # @example # index.multi_search( # cat_results: ["cats", { author_id: 57 }], # dog_results: ["dogs", { author_id: 57 }] # ) # # @param [Hash] queries # a hash whose keys map to queries # # @return [Hash] # a Hash whose keys map 1:1 with the input Hash, each element containing the # same results as those returned by the #search method. def multi_search(queries)
unless queries.kind_of?(Hash) raise ArgumentError, "Argument must be a Hash of named queries (#{queries.class} given)" end stmts = [] bind_values = [] queries.each do |key, args| str, *values = @builder.select(*extract_query_data(args)) stmts.push(str, "SHOW META") bind_values.push(*values) end rs = @conn.multi_query(stmts.join(";\n"), *bind_values) Hash[].tap do |result| queries.keys.each do |key| records, meta = rs.shift, rs.shift result[key] = meta_to_hash(meta).tap do |r| r[:records] = records.map { |hash| hash.inject({}) { |o, (k, v)| o.merge!(k.to_sym => v) } } end end end end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/users_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/users_commands.rb#L16-L21
ruby
test
# Usage hints # https://github.com/google/google-api-ruby-client/issues/360 # get multiple users # if you don't want the defaults { max_results: 10, order_by: 'email' } # you must override (a nil disables the option)
def users_list( attributes: {} )
# Usage hints # https://github.com/google/google-api-ruby-client/issues/360 # get multiple users # if you don't want the defaults { max_results: 10, order_by: 'email' } # you must override (a nil disables the option) def users_list( attributes: {} )
defaults = { max_results: 10, order_by: 'email' } filters = defaults.merge( attributes ) response = service.list_users( filters ) {response: response, attributes: filters, command: :users_list} end
yrgoldteeth/whereabouts
2b56ca4fb7e0298b78c30d51605986096863606d
lib/whereabouts_methods.rb
https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L7-L38
ruby
test
# Accepts a symbol that will define the inherited # type of Address. Defaults to the parent class.
def has_whereabouts klass=:address, *args
# Accepts a symbol that will define the inherited # type of Address. Defaults to the parent class. def has_whereabouts klass=:address, *args
options = args.extract_options! # extend Address with class name if not defined. unless klass == :address || Object.const_defined?(klass.to_s.camelize) create_address_class(klass.to_s.camelize) end # Set the has_one relationship and accepts_nested_attributes_for. has_one klass, :as => :addressable, :dependent => :destroy accepts_nested_attributes_for klass # Define a singleton on the class that returns an array # that includes the address fields to validate presence of # or an empty array if options[:validate] && options[:validate].is_a?(Array) validators = options[:validate] set_validators(klass, validators) else validators = [] end define_singleton_method validate_singleton_for(klass) do validators end # Check for geocode in options and confirm geocoder is defined. # Also defines a singleton to return a boolean about geocoding. if options[:geocode] && options[:geocode] == true && defined?(Geocoder) geocode = true set_geocoding(klass) else geocode = false end define_singleton_method geocode_singleton_for(klass) do geocode end end
yrgoldteeth/whereabouts
2b56ca4fb7e0298b78c30d51605986096863606d
lib/whereabouts_methods.rb
https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L57-L65
ruby
test
# Sets validates_presence_of fields for the Address based on the # singleton method created on the Address addressable_type class.
def set_validators klass, fields=[]
# Sets validates_presence_of fields for the Address based on the # singleton method created on the Address addressable_type class. def set_validators klass, fields=[]
_single = validate_singleton_for(klass) klass.to_s.camelize.constantize.class_eval do fields.each do |f| validates_presence_of f, :if => lambda {|a| a.addressable_type.constantize.send(_single).include?(f)} end end end
yrgoldteeth/whereabouts
2b56ca4fb7e0298b78c30d51605986096863606d
lib/whereabouts_methods.rb
https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L70-L77
ruby
test
# Geocode the address using Address#geocode_address if the # geocode_singleton is true and the record is either new or # has been updated.
def set_geocoding klass
# Geocode the address using Address#geocode_address if the # geocode_singleton is true and the record is either new or # has been updated. def set_geocoding klass
_single = geocode_singleton_for(klass) klass.to_s.camelize.constantize.class_eval do geocoded_by :geocode_address after_validation :geocode, :if => lambda {|a| a.addressable_type.constantize.send(_single) && (a.new_record? || a.changed?)} end end
yrgoldteeth/whereabouts
2b56ca4fb7e0298b78c30d51605986096863606d
lib/whereabouts_methods.rb
https://github.com/yrgoldteeth/whereabouts/blob/2b56ca4fb7e0298b78c30d51605986096863606d/lib/whereabouts_methods.rb#L81-L84
ruby
test
# Generate a new class using Address as the superclass. # Accepts a string defining the inherited type.
def create_address_class(class_name, &block)
# Generate a new class using Address as the superclass. # Accepts a string defining the inherited type. def create_address_class(class_name, &block)
klass = Class.new Address, &block Object.const_set class_name, klass end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/worker.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/worker.rb#L174-L202
ruby
test
# Start the event loop for handling messages off the queue
def event_loop
# Start the event loop for handling messages off the queue def event_loop
Qwirk.logger.debug "#{self}: Starting receive loop" @start_worker_time = Time.now until @stopped || (config.stopped? && @impl.ready_to_stop?) Qwirk.logger.debug "#{self}: Waiting for read" @start_read_time = Time.now msg = @impl.receive_message if msg @start_processing_time = Time.now Qwirk.logger.debug {"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds"} delta = config.timer.measure do @processing_mutex.synchronize do on_message(msg) @impl.acknowledge_message(msg) end end Qwirk.logger.info {"#{self}::on_message (#{'%.1f' % delta}ms)"} if self.config.log_times Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush) end end Qwirk.logger.info "#{self}: Exiting" rescue Exception => e @status = "Terminated: #{e.message}" Qwirk.logger.error "#{self}: Exception, thread terminating: #{e.message}\n\t#{e.backtrace.join("\n\t")}" ensure @status = 'Stopped' Qwirk.logger.flush if Qwirk.logger.respond_to?(:flush) config.worker_stopped(self) end
jtvjt/activerecord-postgres-hstore-core
053a9c006da4d3d7a1f0e9f530c0ea966cc17b82
lib/activerecord_postgres_hstore_core/activerecord.rb
https://github.com/jtvjt/activerecord-postgres-hstore-core/blob/053a9c006da4d3d7a1f0e9f530c0ea966cc17b82/lib/activerecord_postgres_hstore_core/activerecord.rb#L75-L91
ruby
test
# This method is replaced for Rails 3 compatibility. # All I do is add the condition when the field is a hash that converts the value # to hstore format. # IMHO this should be delegated to the column, so it won't be necessary to rewrite all # this method.
def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
# This method is replaced for Rails 3 compatibility. # All I do is add the condition when the field is a hash that converts the value # to hstore format. # IMHO this should be delegated to the column, so it won't be necessary to rewrite all # this method. def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
attrs = {} attribute_names.each do |name| if (column = column_for_attribute(name)) && (include_primary_key || !column.primary) if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name)) value = read_attribute(name) if self.class.columns_hash[name].type == :hstore && value && value.is_a?(Hash) value = value.to_hstore # Done! elsif value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time) || value.is_a?(Hash) || value.is_a?(Array)) value = value.to_yaml end attrs[self.class.arel_table[name]] = value end end end attrs end
arvicco/my_scripts
e75ba2ec22adf15a8d6e224ca4bf2fdae044a754
lib/my_scripts/scripts/gitto.rb
https://github.com/arvicco/my_scripts/blob/e75ba2ec22adf15a8d6e224ca4bf2fdae044a754/lib/my_scripts/scripts/gitto.rb#L14-L47
ruby
test
# or, one digit followed by 0-2 zeroes (100/10/1 - bump major/minor/patch)
def run
# or, one digit followed by 0-2 zeroes (100/10/1 - bump major/minor/patch) def run
usage "[0.1.2 - version, 100/10/1 - bump major/minor/patch, .build - add build] Commit message goes here" if @argv.empty? # First Arg may indicate version command if it matches pattern version_command = @argv[0] =~ COMMAND_PATTERN ? @argv.shift : nil # All the other args lumped into message, or default message if @argv.empty? commit_message = "Commit #{Time.now.to_s[0..-6]}" history_message = nil else commit_message = history_message = @argv.join(' ') end # Updating version only if version command set if version_command puts "Updating version with #{version_command}" if history_message system %Q{rake "version[#{version_command},#{history_message}]"} else system %Q{rake version[#{version_command}]} end end puts "Adding all the changes" system "git add --all" puts "Committing everything with message: #{commit_message}" system %Q[git commit -a -m "#{commit_message}" --author arvicco] current_branch = `git branch`.strip puts "Pushing to (default) remote for branch: #{current_branch}" system "git push" end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/product.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/product.rb#L141-L167
ruby
test
# def _get_accessible_products
def _get(cmd, ids, *_args) # This is still in experimental and apparently the behavior was changed since 4.2. # We don't keep the backward-compatibility and just require the proper version here.
# def _get_accessible_products def _get(cmd, ids, *_args) # This is still in experimental and apparently the behavior was changed since 4.2. # We don't keep the backward-compatibility and just require the proper version here.
requires_version(cmd, 4.2) params = {} if ids.is_a?(Hash) raise ArgumentError, format('Invalid parameter: %s', ids.inspect) unless ids.include?('ids') || ids.include?('names') params[:ids] = ids['ids'] || ids['names'] elsif ids.is_a?(Array) r = ids.map { |x| x.is_a?(Integer) ? x : nil }.compact if r.length != ids.length params[:names] = ids else params[:ids] = ids end else if ids.is_a?(Integer) params[:ids] = [ids] else params[:names] = [ids] end end @iface.call(cmd, params) end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bugzilla.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bugzilla.rb#L41-L50
ruby
test
# rdoc # # ==== Bugzilla::Bugzilla#check_version(version_) # # Returns Array contains the result of the version check and # Bugzilla version that is running on.
def check_version(version_)
# rdoc # # ==== Bugzilla::Bugzilla#check_version(version_) # # Returns Array contains the result of the version check and # Bugzilla version that is running on. def check_version(version_)
v = version f = false if v.is_a?(Hash) && v.include?('version') && Gem::Version.new(v['version']) >= Gem::Version.new(version_.to_s) f = true end [f, v['version']] end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bugzilla.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bugzilla.rb#L60-L63
ruby
test
# def check_version # rdoc # # ==== Bugzilla::Bugzilla#requires_version(cmd, version_) # # Raise an exception if the Bugzilla doesn't satisfy # the requirement of the _version_.
def requires_version(cmd, version_)
# def check_version # rdoc # # ==== Bugzilla::Bugzilla#requires_version(cmd, version_) # # Raise an exception if the Bugzilla doesn't satisfy # the requirement of the _version_. def requires_version(cmd, version_)
v = check_version(version_) raise NoMethodError, format('%s is not supported in Bugzilla %s', cmd, v[1]) unless v[0] end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/service.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L16-L29
ruby
test
# default 10 minutes
def run
# default 10 minutes def run
begin Clacks.logger.info "Clacks v#{Clacks::VERSION} started" if Clacks.config[:pop3] run_pop3 elsif Clacks.config[:imap] run_imap else raise "Either a POP3 or an IMAP server must be configured" end rescue Exception => e fatal(e) end end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/service.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L73-L86
ruby
test
# Follows mostly the defaults from the Mail gem
def imap_validate_options(options)
# Follows mostly the defaults from the Mail gem def imap_validate_options(options)
options ||= {} options[:mailbox] ||= 'INBOX' options[:count] ||= 5 options[:order] ||= :asc options[:what] ||= :first options[:keys] ||= 'ALL' options[:delete_after_find] ||= false options[:mailbox] = Net::IMAP.encode_utf7(options[:mailbox]) if options[:archivebox] options[:archivebox] = Net::IMAP.encode_utf7(options[:archivebox]) end options end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/service.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L133-L150
ruby
test
# http://tools.ietf.org/rfc/rfc2177.txt
def imap_watchdog
# http://tools.ietf.org/rfc/rfc2177.txt def imap_watchdog
Thread.new do loop do begin Clacks.logger.debug('watchdog sleeps') sleep(WATCHDOG_SLEEP) Clacks.logger.debug('watchdog woke up') @imap.idle_done Clacks.logger.debug('watchdog signalled idle process') rescue StandardError => e Clacks.logger.debug { "watchdog received error: #{e.message} (#{e.class})\n#{(e.backtrace || []).join("\n")}" } # noop rescue Exception => e fatal(e) end end end end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/service.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/service.rb#L154-L191
ruby
test
# Keep processing emails until nothing is found anymore, # or until a QUIT signal is received to stop the process.
def imap_find(imap)
# Keep processing emails until nothing is found anymore, # or until a QUIT signal is received to stop the process. def imap_find(imap)
options = Clacks.config[:find_options] delete_after_find = options[:delete_after_find] begin break if stopping? uids = imap.uid_search(options[:keys] || 'ALL') uids.reverse! if options[:what].to_sym == :last uids = uids.first(options[:count]) if options[:count].is_a?(Integer) uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) || (options[:what].to_sym != :last && options[:order].to_sym == :desc) processed = 0 expunge = false uids.each do |uid| break if stopping? source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822'] mail = nil begin mail = Mail.new(source) mail.mark_for_delete = true if delete_after_find Clacks.config[:on_mail].call(mail) rescue StandardError => e Clacks.logger.error(e.message) Clacks.logger.error(e.backtrace) end begin imap.uid_copy(uid, options[:archivebox]) if options[:archivebox] if delete_after_find && (mail.nil? || mail.is_marked_for_delete?) expunge = true imap.uid_store(uid, "+FLAGS", [Net::IMAP::DELETED]) end rescue StandardError => e Clacks.logger.error(e.message) end processed += 1 end imap.expunge if expunge end while uids.any? && processed == uids.length end
jronallo/mead
119e25d762d228a17612afe327ac13227aa9825b
lib/mead/ead.rb
https://github.com/jronallo/mead/blob/119e25d762d228a17612afe327ac13227aa9825b/lib/mead/ead.rb#L20-L33
ruby
test
# options include :file and :base_url
def get_ead
# options include :file and :base_url def get_ead
if @eadid.nil? and @url.nil? and @file.nil? and @baseurl raise 'Cannot get EAD based on params.' end if @file and @file.is_a? File @file.rewind if @file.eof? @ead = @file.read elsif @url @ead = open(@url).read elsif @baseurl @ead = open(File.join(@baseurl, @eadid + '.xml')).read end @doc = Nokogiri::XML(@ead) end
OSC/osc_machete_rails
103bb9b37b40684d4745b7198ebab854a5f6121e
lib/osc_machete_rails/statusable.rb
https://github.com/OSC/osc_machete_rails/blob/103bb9b37b40684d4745b7198ebab854a5f6121e/lib/osc_machete_rails/statusable.rb#L20-L25
ruby
test
# delete the batch job and update status # may raise PBS::Error as it is unhandled here!
def stop(update: true)
# delete the batch job and update status # may raise PBS::Error as it is unhandled here! def stop(update: true)
return unless status.active? job.delete update(status: OSC::Machete::Status.failed) if update end
OSC/osc_machete_rails
103bb9b37b40684d4745b7198ebab854a5f6121e
lib/osc_machete_rails/statusable.rb
https://github.com/OSC/osc_machete_rails/blob/103bb9b37b40684d4745b7198ebab854a5f6121e/lib/osc_machete_rails/statusable.rb#L99-L120
ruby
test
# Setter that accepts an OSC::Machete::Job instance # # @param [Job] new_job The Job object to be assigned to the Statusable instance.
def job=(new_job)
# Setter that accepts an OSC::Machete::Job instance # # @param [Job] new_job The Job object to be assigned to the Statusable instance. def job=(new_job)
if self.has_attribute?(:job_cache) self.script = new_job.script_path.to_s self.pbsid = new_job.pbsid self.host = new_job.host if new_job.respond_to?(:host) else self.script_name = new_job.script_name self.job_path = new_job.path.to_s self.pbsid = new_job.pbsid end begin self.status = new_job.status rescue PBS::Error => e # a safe default self.status = OSC::Machete::Status.queued # log the error Rails.logger.error("After submitting the job with pbsid: #{pbsid}," \ " checking the status raised a PBS::Error: #{e.message}") end end
OSC/osc_machete_rails
103bb9b37b40684d4745b7198ebab854a5f6121e
lib/osc_machete_rails/statusable.rb
https://github.com/OSC/osc_machete_rails/blob/103bb9b37b40684d4745b7198ebab854a5f6121e/lib/osc_machete_rails/statusable.rb#L144-L154
ruby
test
# A hook that can be overidden with custom code # also looks for default validation methods for existing # WARNING: THIS USES ActiveSupport::Inflector methods underscore and parameterize # # @return [Boolean] true if the results script is present
def results_valid?
# A hook that can be overidden with custom code # also looks for default validation methods for existing # WARNING: THIS USES ActiveSupport::Inflector methods underscore and parameterize # # @return [Boolean] true if the results script is present def results_valid?
valid = true if self.respond_to?(:script_name) && !script_name.nil? if self.respond_to?(results_validation_method_name) valid = self.send(results_validation_method_name) end end valid end
OSC/osc_machete_rails
103bb9b37b40684d4745b7198ebab854a5f6121e
lib/osc_machete_rails/statusable.rb
https://github.com/OSC/osc_machete_rails/blob/103bb9b37b40684d4745b7198ebab854a5f6121e/lib/osc_machete_rails/statusable.rb#L173-L197
ruby
test
# FIXME: should have a unit test for this! # job.update_status! will update and save object # if submitted? and ! completed? and status changed from previous state # force will cause status to update regardless of completion status, # redoing the validations. This way, if you are fixing validation methods # you can use the Rails console to update the status of a Workflow by doing this: # # Container.last.jobs.each {|j| j.update_status!(force: true) } # # Or for a single statusable such as job: # # job.update_status!(force: true) # # FIXME: should log whether a validation method was called or # throw a warning that no validation method was found (the one that would have been called) # # @param [Boolean, nil] force Force the update. (Default: false)
def update_status!(force: false) # this will make it easier to differentiate from current_status
# FIXME: should have a unit test for this! # job.update_status! will update and save object # if submitted? and ! completed? and status changed from previous state # force will cause status to update regardless of completion status, # redoing the validations. This way, if you are fixing validation methods # you can use the Rails console to update the status of a Workflow by doing this: # # Container.last.jobs.each {|j| j.update_status!(force: true) } # # Or for a single statusable such as job: # # job.update_status!(force: true) # # FIXME: should log whether a validation method was called or # throw a warning that no validation method was found (the one that would have been called) # # @param [Boolean, nil] force Force the update. (Default: false) def update_status!(force: false) # this will make it easier to differentiate from current_status
cached_status = status # by default only update if its an active job if (cached_status.not_submitted? && pbsid) || cached_status.active? || force # get the current status from the system current_status = job.status # if job is done, lets re-validate if current_status.completed? current_status = results_valid? ? OSC::Machete::Status.passed : OSC::Machete::Status.failed end if (current_status != cached_status) || force self.status = current_status self.save end end rescue PBS::Error => e # we log the error but we just don't update the status Rails.logger.error("During update_status! call on job with pbsid #{pbsid} and id #{id}" \ " a PBS::Error was thrown: #{e.message}") end
arvicco/my_scripts
e75ba2ec22adf15a8d6e224ca4bf2fdae044a754
lib/my_scripts/script.rb
https://github.com/arvicco/my_scripts/blob/e75ba2ec22adf15a8d6e224ca4bf2fdae044a754/lib/my_scripts/script.rb#L38-L43
ruby
test
# Outputs usage notes (and optional extended explanation), then exits with code 1
def usage( examples, explanation = nil )
# Outputs usage notes (and optional extended explanation), then exits with code 1 def usage( examples, explanation = nil )
puts "Script #{@name} #{version} - Usage:" (examples.respond_to?(:split) ? examples.split("\n") : examples).map {|line| puts " #{@name} #{line}"} puts explanation if explanation exit 1 end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/colors.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/colors.rb#L66-L72
ruby
test
# TODO support a block (solo dentro l blocco fai il nocolor)
def set_color(bool)
# TODO support a block (solo dentro l blocco fai il nocolor) def set_color(bool)
b = bool ? true : false deb "Setting color mode to: #{yellow bool} --> #{white b.to_s}" b = false if bool.to_s.match( /(off|false)/ ) deb "Setting color mode to: #{yellow bool} --> #{white b.to_s}" $colors_active = bool end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/colors.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/colors.rb#L123-L134
ruby
test
# carattere per carattere...
def rainbow(str)
# carattere per carattere... def rainbow(str)
i=0 ret = '' str=str.to_s while(i < str.length) ch = str[i] palette = $color_db[0][i % $color_db[0].length ] ret << (colora(palette,str[i,1])) i += 1 end ret end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/colors.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/colors.rb#L186-L188
ruby
test
# italia: green white red # ireland: green white orange # france: green white orange # UK: blue white red white blue # google:
def _flag_nations
# italia: green white red # ireland: green white orange # france: green white orange # UK: blue white red white blue # google: def _flag_nations
%w{cc it de ie fr es en goo br pt} end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/colors.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/colors.rb#L220-L228
ruby
test
# for simmetry padding # m = length / 3 # 6: 2 2 2 m m m REST 0 # 5: 2 1 2 m+1 m m+1 2 # 4: 1 2 1 m m+1 m 1
def flag3(str,left_color='brown',middle_color='pink',right_color='red')
# for simmetry padding # m = length / 3 # 6: 2 2 2 m m m REST 0 # 5: 2 1 2 m+1 m m+1 2 # 4: 1 2 1 m m+1 m 1 def flag3(str,left_color='brown',middle_color='pink',right_color='red')
m = str.length / 3 remainder = str.length % 3 central_length = remainder == 1 ? m+1 : m lateral_length = remainder == 2 ? m+1 : m colora( left_color, str[ 0 .. lateral_length-1] ) + colora( middle_color, str[ lateral_length .. lateral_length+central_length-1] ) + colora( right_color, str[ lateral_length+central_length .. str.length ] ) end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/prime.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/prime.rb#L19-L24
ruby
test
# Retrieves the next largest prime for the largest number in batch # # Example # # Prime.large_enough_prime 4 # # => 7 # # @param input [Integer] the integer to find the next largest prime for # @return [Integer] the next largest prime # @raise [CannotFindLargeEnoughPrime] raised when input is too large and # no large enough prime can be found
def large_enough_prime(input)
# Retrieves the next largest prime for the largest number in batch # # Example # # Prime.large_enough_prime 4 # # => 7 # # @param input [Integer] the integer to find the next largest prime for # @return [Integer] the next largest prime # @raise [CannotFindLargeEnoughPrime] raised when input is too large and # no large enough prime can be found def large_enough_prime(input)
standard_primes.each do |prime| return prime if prime > input end fail CannotFindLargeEnoughPrime, "Input too large" end
ebsaral/sentence-builder
4f3691323dbbcf370f7b2530ae0967f4ec16a3e9
lib/sentence_builder/sentence_node.rb
https://github.com/ebsaral/sentence-builder/blob/4f3691323dbbcf370f7b2530ae0967f4ec16a3e9/lib/sentence_builder/sentence_node.rb#L116-L118
ruby
test
# Combines array into a string with given separator
def enhance_content(value, separator = ', ')
# Combines array into a string with given separator def enhance_content(value, separator = ', ')
value.is_a?(Array) ? value.join(separator) : value end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/charset.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L37-L48
ruby
test
# The "null-byte" character is prepended to be the first character in the # charset to avoid loosing the first character of the charset when it is # also the first character in a string to convert. # # Example # # SecretSharing::Charset::DynamicCharset.new ["a", "b", "c"] # => # #<SecretSharing::Charset::DynamicCharset @charset=[...]> # # @param charset [Array] array of characters to use for the charset. # Calculate a string from an integer. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.i_to_s 6 # # => "ab" # # @param input [Integer] integer to convert to string # @return [String] converted string
def i_to_s(input)
# The "null-byte" character is prepended to be the first character in the # charset to avoid loosing the first character of the charset when it is # also the first character in a string to convert. # # Example # # SecretSharing::Charset::DynamicCharset.new ["a", "b", "c"] # => # #<SecretSharing::Charset::DynamicCharset @charset=[...]> # # @param charset [Array] array of characters to use for the charset. # Calculate a string from an integer. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.i_to_s 6 # # => "ab" # # @param input [Integer] integer to convert to string # @return [String] converted string def i_to_s(input)
if !input.is_a?(Integer) || input < 0 fail NotPositiveInteger, "input must be a non-negative integer" end output = "" while input > 0 input, codepoint = input.divmod(charset.length) output.prepend(codepoint_to_char(codepoint)) end output end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/charset.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L60-L64
ruby
test
# Calculate an integer from a string. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.s_to_i "ab" # # => 6 # # @param string [Integer] integer to convert to string # @return [String] converted string
def s_to_i(string)
# Calculate an integer from a string. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.s_to_i "ab" # # => 6 # # @param string [Integer] integer to convert to string # @return [String] converted string def s_to_i(string)
string.chars.reduce(0) do |output, char| output * charset.length + char_to_codepoint(char) end end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/charset.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L77-L82
ruby
test
# Convert an integer into its string representation according to the # charset. (only one character) # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.codepoint_to_char 1 # # => "a" # # @param codepoint [Integer] Codepoint to retrieve the character for # @return [String] Retrieved character
def codepoint_to_char(codepoint)
# Convert an integer into its string representation according to the # charset. (only one character) # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.codepoint_to_char 1 # # => "a" # # @param codepoint [Integer] Codepoint to retrieve the character for # @return [String] Retrieved character def codepoint_to_char(codepoint)
if charset.at(codepoint).nil? fail NotInCharset, "Codepoint #{codepoint} does not exist in charset" end charset.at(codepoint) end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/charset.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L95-L101
ruby
test
# Convert a single character into its integer representation according to # the charset. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.char_to_codepoint "a" # # => 1 # # @param c [String] Character to retrieve its codepoint in the charset # @return [Integer] Codepoint within the charset
def char_to_codepoint(c)
# Convert a single character into its integer representation according to # the charset. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.char_to_codepoint "a" # # => 1 # # @param c [String] Character to retrieve its codepoint in the charset # @return [Integer] Codepoint within the charset def char_to_codepoint(c)
codepoint = charset.index c if codepoint.nil? fail NotInCharset, "Char \"#{c}\" not part of the supported charset" end codepoint end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/charset.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/charset.rb#L115-L117
ruby
test
# Check if the provided string can be represented by the charset. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.subset? "d" # # => false # charset.subset? "a" # # => true # # @param string [String] Character to retrieve the for codepoint # @return [TrueClass|FalseClass]
def subset?(string)
# Check if the provided string can be represented by the charset. # # Example # # charset = SecretSharing::Charset.by_charset_string "abc" # charset.subset? "d" # # => false # charset.subset? "a" # # => true # # @param string [String] Character to retrieve the for codepoint # @return [TrueClass|FalseClass] def subset?(string)
(Set.new(string.chars) - Set.new(charset)).empty? end
duse-io/secret_sharing_ruby
a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6
lib/secret_sharing/polynomial.rb
https://github.com/duse-io/secret_sharing_ruby/blob/a5e4202427f0b566dc0cd157b94d2e9f4c3bc4b6/lib/secret_sharing/polynomial.rb#L41-L50
ruby
test
# Create a new instance of a Polynomial with n coefficients, when having # the polynomial in standard polynomial form. # # Example # # For the polynomial f(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n the # coefficients are [a0, a1, a2, ..., an] # # Polynomial.new [1, 2, 3] # # => #<SecretSharing::Polynomial:0x0000000 @coefficients=[1, 2, 3]> # # @param coefficients [Array] an array of integers as the coefficients # Generate points on the polynomial, that can be used to reconstruct the # polynomial with. # # Example # # SecretSharing::Polynomial.new([1, 2, 3, 4]).points(3, 7) # # => [#<Point: @x=1 @y=3>, #<Point: @x=2 @y=0>, #<Point: @x=3 @y=2>] # # @param num_points [Integer] number of points to generate # @param prime [Integer] prime for calculation in finite field # @return [Array] array of calculated points
def points(num_points, prime)
# Create a new instance of a Polynomial with n coefficients, when having # the polynomial in standard polynomial form. # # Example # # For the polynomial f(x) = a0 + a1 * x + a2 * x^2 + ... + an * x^n the # coefficients are [a0, a1, a2, ..., an] # # Polynomial.new [1, 2, 3] # # => #<SecretSharing::Polynomial:0x0000000 @coefficients=[1, 2, 3]> # # @param coefficients [Array] an array of integers as the coefficients # Generate points on the polynomial, that can be used to reconstruct the # polynomial with. # # Example # # SecretSharing::Polynomial.new([1, 2, 3, 4]).points(3, 7) # # => [#<Point: @x=1 @y=3>, #<Point: @x=2 @y=0>, #<Point: @x=3 @y=2>] # # @param num_points [Integer] number of points to generate # @param prime [Integer] prime for calculation in finite field # @return [Array] array of calculated points def points(num_points, prime)
intercept = @coefficients[0] # the first coefficient is the intercept (1..num_points).map do |x| y = intercept ([email protected]).each do |i| y = (y + @coefficients[i] * x ** i) % prime end Point.new(x, y) end end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/utils.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/utils.rb#L42-L51
ruby
test
# def read_config
def save_config(opts, conf)
# def read_config def save_config(opts, conf)
fname = opts[:config].nil? ? @defaultyamlfile : opts[:config] if File.exist?(fname) st = File.lstat(fname) if st.mode & 0o600 != 0o600 raise format('The permissions of %s has to be 0600', fname) end end File.open(fname, 'w') { |f| f.chmod(0o600); f.write(conf.to_yaml) } end
jronallo/mead
119e25d762d228a17612afe327ac13227aa9825b
lib/mead/ead_validator.rb
https://github.com/jronallo/mead/blob/119e25d762d228a17612afe327ac13227aa9825b/lib/mead/ead_validator.rb#L13-L34
ruby
test
# Creates a new EadValidator when given the path to a directory as a String
def validate!
# Creates a new EadValidator when given the path to a directory as a String def validate!
files = Dir.glob(File.join(@directory, '*.xml')).sort threads = [] files.map do |path| threads << Thread.new(path) do |path_t| eadid = File.basename(path_t, '.xml') begin ead = Mead::Ead.new({:file => File.open(path_t), :eadid => eadid}) rescue => e record_invalid(eadid, ead, e) next end if ead.valid? @valid << eadid else record_invalid(eadid, ead) end end end threads.each { |thread| thread.join } metadata end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/model.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L84-L98
ruby
test
# Broadcast notifications when a new record is created
def notify_create
# Broadcast notifications when a new record is created def notify_create
self.ChannelPublications.each do |publication, options| if options[:actions].include? :create # Checks if records is within scope before broadcasting records = self.class.scoped_collection(options[:scope]) if options[:scope]==:all or record_within_scope(records) ActionCable.server.broadcast publication, msg: 'create', id: self.id, data: self end end end end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/model.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L119-L179
ruby
test
# Broadcast notifications when a record is updated. Only changed fields will be sent # if they are within configured scope
def notify_update # Get model changes
# Broadcast notifications when a record is updated. Only changed fields will be sent # if they are within configured scope def notify_update # Get model changes
if self.respond_to?(:saved_changes) # For Rails >= 5.1 changes = self.saved_changes.transform_values(&:second) else # For Rails < 5.1 changes = self.changes.transform_values(&:second) end # Checks if there are changes in the model if !changes.empty? self.ChannelPublications.each do |publication, options| if options[:actions].include? :update # Checks if previous record was within scope record = record_within_scope(options[:records]) was_in_scope = record.present? options[:records].delete(record) if was_in_scope # Checks if current record is within scope if options[:track_scope_changes]==true is_in_scope = false if options[:scope]==:all record = self is_in_scope = true else record = record_within_scope(self.class.scoped_collection(options[:scope])) if record.present? is_in_scope = true end end else is_in_scope = was_in_scope end # Broadcasts notifications about model changes if is_in_scope if was_in_scope # Get model changes and applies them to the scoped collection record changes.select!{|k,v| record.respond_to?(k)} if !changes.empty? ActionCable.server.broadcast publication, msg: 'update', id: self.id, data: changes end else ActionCable.server.broadcast publication, msg: 'create', id: record.id, data: record end elsif was_in_scope # checks if needs to delete the record if its no longer in scope ActionCable.server.broadcast publication, msg: 'destroy', id: self.id end end end end end
bys-control/action_cable_notifications
dc455e690ce87d4864a0833c89b77438da48da65
lib/action_cable_notifications/model.rb
https://github.com/bys-control/action_cable_notifications/blob/dc455e690ce87d4864a0833c89b77438da48da65/lib/action_cable_notifications/model.rb#L184-L195
ruby
test
# Broadcast notifications when a record is destroyed.
def notify_destroy
# Broadcast notifications when a record is destroyed. def notify_destroy
self.ChannelPublications.each do |publication, options| if options[:scope]==:all or options[:actions].include? :destroy # Checks if record is within scope before broadcasting if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope])).present? ActionCable.server.broadcast publication, msg: 'destroy', id: self.id end end end end
itrp/clacks
54714facb9cc5290246fe562c107b058a683f91d
lib/clacks/configurator.rb
https://github.com/itrp/clacks/blob/54714facb9cc5290246fe562c107b058a683f91d/lib/clacks/configurator.rb#L37-L43
ruby
test
# Sets the Logger-like object. # The default Logger will log its output to Rails.logger if # you're running within a rails environment, otherwise it will # output to the path specified by +stdout_path+.
def logger(obj)
# Sets the Logger-like object. # The default Logger will log its output to Rails.logger if # you're running within a rails environment, otherwise it will # output to the path specified by +stdout_path+. def logger(obj)
%w(debug info warn error fatal level).each do |m| next if obj.respond_to?(m) raise ArgumentError, "logger #{obj} does not respond to method #{m}" end map[:logger] = obj end
AlphaHydrae/errapi
8bf02124079f7fbb505ae837cc828a20b277dcc6
lib/errapi/validations/clusivity.rb
https://github.com/AlphaHydrae/errapi/blob/8bf02124079f7fbb505ae837cc828a20b277dcc6/lib/errapi/validations/clusivity.rb#L30-L41
ruby
test
# From rails/activemodel/lib/active_model/validations/clusivity.rb: # In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all # possible values in the range for equality, which is slower but more accurate. # <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range # endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges.
def inclusion_method enumerable
# From rails/activemodel/lib/active_model/validations/clusivity.rb: # In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all # possible values in the range for equality, which is slower but more accurate. # <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range # endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges. def inclusion_method enumerable
if enumerable.is_a? Range case enumerable.first when Numeric, Time, DateTime :cover? else :include? end else :include? end end
lbadura/currency_spy
be0689715649ff952d3d797a4b3f087793580924
lib/currency_spy/scraper_base.rb
https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scraper_base.rb#L28-L36
ruby
test
# Base constructor # Returns a Mechanize::Page instance which is the being searched on. # If the page was once fetched it's reuse. To reload, call with an argument # evaluating to true.
def page(reload = false)
# Base constructor # Returns a Mechanize::Page instance which is the being searched on. # If the page was once fetched it's reuse. To reload, call with an argument # evaluating to true. def page(reload = false)
return nil if url.nil? if reload @page = Mechanize.new.get(url) else @page ||= Mechanize.new.get(url) end @page end
lbadura/currency_spy
be0689715649ff952d3d797a4b3f087793580924
lib/currency_spy/scraper_base.rb
https://github.com/lbadura/currency_spy/blob/be0689715649ff952d3d797a4b3f087793580924/lib/currency_spy/scraper_base.rb#L40-L55
ruby
test
# Method which calls all rate fetching methods from the sub class and returns # a Hash with appropriate values.
def fetch_rates
# Method which calls all rate fetching methods from the sub class and returns # a Hash with appropriate values. def fetch_rates
if self.class.superclass.eql?(Object) raise Exception.new("This method should be invoked from CurrencySpy::Scraper sub class") else check_currency_code_validity rate_results = {} RATE_DATA.each do |rate| symbol = rate.to_sym if self.class.instance_methods.include?(symbol) value = self.send(symbol) rate_results[symbol] = value unless value.nil? end end rate_results end end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/publisher.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/publisher.rb#L39-L44
ruby
test
# Parameters: # One of the following must be specified # :queue_name => String: Name of the Queue to publish to # :topic_name => String: Name of the Topic to publish to # Optional: # :time_to_live => expiration time in ms for the message (JMS) # :persistent => true or false (defaults to false) (JMS) # :marshal => Symbol: One of :ruby, :string, :json, :bson, :yaml or any registered types (See Qwirk::MarshalStrategy), defaults to :ruby # :response => if true or a hash of response options, a temporary reply queue will be setup for handling responses # :time_to_live => expiration time in ms for the response message(s) (JMS)) # :persistent => true or false for the response message(s), set to false if you don't want timed out messages ending up in the DLQ (defaults to true unless time_to_live is set) # Publish the given object to the address.
def publish(object, props={})
# Parameters: # One of the following must be specified # :queue_name => String: Name of the Queue to publish to # :topic_name => String: Name of the Topic to publish to # Optional: # :time_to_live => expiration time in ms for the message (JMS) # :persistent => true or false (defaults to false) (JMS) # :marshal => Symbol: One of :ruby, :string, :json, :bson, :yaml or any registered types (See Qwirk::MarshalStrategy), defaults to :ruby # :response => if true or a hash of response options, a temporary reply queue will be setup for handling responses # :time_to_live => expiration time in ms for the response message(s) (JMS)) # :persistent => true or false for the response message(s), set to false if you don't want timed out messages ending up in the DLQ (defaults to true unless time_to_live is set) # Publish the given object to the address. def publish(object, props={})
start = Time.now marshaled_object = @marshaler.marshal(object) adapter_info = @impl.publish(marshaled_object, @marshaler, nil, props) return PublishHandle.new(self, adapter_info, start) end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/spec_info.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/spec_info.rb#L47-L65
ruby
test
# Parse the source string for a target string or regex or return nil.
def parse(target) #Handle the width option if specified.
# Parse the source string for a target string or regex or return nil. def parse(target) #Handle the width option if specified.
if (width = fmt.width) > 0 head, tail = src[0...width], src[width..-1] || "" else head, tail = src, "" end #Do the parse on the input string or regex. @prematch, @match, @postmatch = head.partition(target) #Analyze the results. if found? @src = @postmatch + tail @match else nil end end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/spec_info.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/spec_info.rb#L74-L88
ruby
test
# Grab some text
def grab
# Grab some text def grab
width = fmt.width if width > 0 result, @src = src[0...width], src[width..-1] || "" elsif width == 0 result, @src = src[0...1], src[1..-1] || "" elsif width == -1 result, @src = src, "" else result, @src = src[0..width], src[(width+1)..-1] || "" end result end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bug.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L102-L131
ruby
test
# def get_bugs # rdoc # # ==== Bugzilla::Bug#get_comments(bugs)
def get_comments(bugs)
# def get_bugs # rdoc # # ==== Bugzilla::Bug#get_comments(bugs) def get_comments(bugs)
params = {} # TODO # this construction should be refactored to a method params['ids'] = case bugs when Array bugs when Integer || String [bugs] else raise ArgumentError, format('Unknown type of arguments: %s', bugs.class) end result = comments(params) # not supporting comment_ids. so drop "comments". ret = result['bugs'] # creation_time was added in Bugzilla 4.4. copy the 'time' value to creation_time if not available for compatibility. unless check_version(4.4)[0] ret.each do |_id, o| o['comments'].each do |c| c['creation_time'] = c['time'] unless c.include?('creation_time') end end end ret end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bug.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L236-L240
ruby
test
# def _fields
def _legal_values(cmd, *args)
# def _fields def _legal_values(cmd, *args)
raise ArgumentError, 'Invalid parameters' unless args[0].is_a?(Hash) @iface.call(cmd, args[0]) end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bug.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L258-L277
ruby
test
# def _comments
def _get(cmd, *args)
# def _comments def _get(cmd, *args)
params = {} a = args[0] case a when Hash params = a when Array params['ids'] = a when Integer || String params['ids'] = [a] else raise ArgumentError, 'Invalid parameters' end params['permissive'] = true if check_version(3.4)[0] @iface.call(cmd, params) end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bug.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L279-L296
ruby
test
# def _get
def _history(cmd, *args)
# def _get def _history(cmd, *args)
requires_version(cmd, 3.4) params = {} a = args[0] case a when Hash params = a when Array params['ids'] = a when Integer || String params['ids'] = [a] else raise ArgumentError, 'Invalid parameters' end @iface.call(cmd, params) end
vpereira/bugzilla
6832b6741adacbff7d177467325822dd90424a9d
lib/bugzilla/bug.rb
https://github.com/vpereira/bugzilla/blob/6832b6741adacbff7d177467325822dd90424a9d/lib/bugzilla/bug.rb#L306-L329
ruby
test
# def _search
def _create(cmd, *args)
# def _search def _create(cmd, *args)
raise ArgumentError, 'Invalid parameters' unless args[0].is_a?(Hash) required_fields = %i[product component summary version] defaulted_fields = %i[description op_sys platform priority severity] res = check_version('3.0.4') required_fields.push(*defaulted_fields) unless res[0] required_fields.each do |f| raise ArgumentError, format("Required fields isn't given: %s", f) unless args[0].include?(f) end res = check_version(4.0) if res[0] if args[0].include?('commentprivacy') args[0]['comment_is_private'] = args[0]['commentprivacy'] args[0].delete('commentprivacy') end else raise ArgumentError, "groups field isn't available in this bugzilla" if args[0].include?('groups') raise ArgumentError, "comment_is_private field isn't available in this bugzilla" if args[0].include?('comment_is_private') end @iface.call(cmd, args[0]) end
juandebravo/hash-blue
e2004bf4a5fcfea868d98fcd7b1cdf0f7ccee435
lib/hash_blue/message.rb
https://github.com/juandebravo/hash-blue/blob/e2004bf4a5fcfea868d98fcd7b1cdf0f7ccee435/lib/hash_blue/message.rb#L69-L71
ruby
test
# Create message
def save!
# Create message def save!
self.class.create!(contact.is_a? HashBlue::Contact ? contact.phone_number : contact, content) end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/attr_parser.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/attr_parser.rb#L22-L31
ruby
test
# Define a parser for the current class. # <br>Parameters # * method - A symbol used to name the parsing method created by this method. # * library - A hash of parsing rules the define the parsing # capabilities supported by this parser. # <br>Meta-effects # * Creates a class method (named after the symbol in method) that parses in # a string and creates an instance of the class. The created method takes # two parameters: # <br>Meta-method Parameters # * src - A string of formatted data to be parsed. # * spec_str - A format specification string with %x etc qualifiers. # <br>Meta-method Returns # * An instance of the host class. # <br>Returns # * The format engine used by this method.
def attr_parser(method, library)
# Define a parser for the current class. # <br>Parameters # * method - A symbol used to name the parsing method created by this method. # * library - A hash of parsing rules the define the parsing # capabilities supported by this parser. # <br>Meta-effects # * Creates a class method (named after the symbol in method) that parses in # a string and creates an instance of the class. The created method takes # two parameters: # <br>Meta-method Parameters # * src - A string of formatted data to be parsed. # * spec_str - A format specification string with %x etc qualifiers. # <br>Meta-method Returns # * An instance of the host class. # <br>Returns # * The format engine used by this method. def attr_parser(method, library)
engine = Engine.new(library) #Create a class method to do the parsing. define_singleton_method(method) do |src, spec_str| engine.do_parse(src, self, spec_str) end engine end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L14-L17
ruby
test
# @note Get GoogleDirectory User Info # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_get, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_get( attributes: )
# @note Get GoogleDirectory User Info # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_get, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_get( attributes: )
response = service.get_user( attributes[:primary_email] ) {response: response, attributes: attributes[:primary_email], command: :user_get} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L23-L34
ruby
test
# @note Test if user exists in Google Directory # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_exists?, attributes: {primary_email: "user@domain"}, response: Boolean } }
def user_exists?( attributes: )
# @note Test if user exists in Google Directory # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_exists?, attributes: {primary_email: "user@domain"}, response: Boolean } } def user_exists?( attributes: )
begin response = service.get_user( attributes[:primary_email] ) return {response: true, attributes: attributes[:primary_email], command: :user_exists?} rescue Google::Apis::ClientError => error if error.message.include? 'notFound' return {response: false, attributes: attributes[:primary_email], command: :user_exists?} else raise error end end end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L40-L50
ruby
test
# @note creates a new Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", name: {given_name: "First Names", family_name: "LAST NAMES" } } # @return [Hash] formatted as {success: {command: :user_create, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_create( attributes: ) # http://blog.liveedu.tv/ruby-generate-random-string/
# @note creates a new Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", name: {given_name: "First Names", family_name: "LAST NAMES" } } # @return [Hash] formatted as {success: {command: :user_create, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_create( attributes: ) # http://blog.liveedu.tv/ruby-generate-random-string/
password = SecureRandom.base64 defaults = { suspended: true, password: password, change_password_at_next_login: true } user_attr = defaults.merge( attributes ) # create a google user object user_object = Google::Apis::AdminDirectoryV1::User.new user_attr # create user in directory services response = service.insert_user( user_object ) {response: response, attributes: attributes[:primary_email], command: :user_create} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L56-L60
ruby
test
# @note updates an exising Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", attributes_to_change: "" } } # @return [Hash] formatted as {success: {command: :user_update, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_update( attributes: ) # create a user object for google to update
# @note updates an exising Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", attributes_to_change: "" } } # @return [Hash] formatted as {success: {command: :user_update, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_update( attributes: ) # create a user object for google to update
response = update_user( attributes ) {response: response, attributes: attributes[:primary_email], command: :user_update} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L66-L73
ruby
test
# @note updates an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", password: "secret" } - if no password is included a random password will be assigned # @return [Hash] formatted as {success: {command: :user_change_password, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_change_password( attributes: )
# @note updates an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]", password: "secret" } - if no password is included a random password will be assigned # @return [Hash] formatted as {success: {command: :user_change_password, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_change_password( attributes: )
password = SecureRandom.base64 defaults = { password: password, change_password_at_next_login: true } user_attr = defaults.merge( attributes ) response = update_user( user_attr ) {response: response, attributes: attributes[:primary_email], command: :user_change_password} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L79-L85
ruby
test
# @note activates an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_reactivate, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_reactivate( attributes: )
# @note activates an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_reactivate, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_reactivate( attributes: )
defaults = { :suspended => false } user_attr = defaults.merge( attributes ) response = update_user( user_attr ) {response: response, attributes: attributes[:primary_email], command: :user_reactivate} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L91-L97
ruby
test
# @note suspends an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_suspend, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } }
def user_suspend( attributes: )
# @note suspends an exising Google Directory User password - convience method instead of using :user_update # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_suspend, attributes: {primary_email: "user@domain"}, response: GoogleUserObject } } def user_suspend( attributes: )
defaults = { :suspended => true } user_attr = defaults.merge( attributes ) response = update_user( user_attr ) {response: response, attributes: attributes[:primary_email], command: :user_suspend} end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/user_commands.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/user_commands.rb#L103-L106
ruby
test
# @note deletes an exising Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_delete, attributes: {primary_email: "user@domain"}, response: "" } }
def user_delete( attributes: )
# @note deletes an exising Google Directory User # # @param attributes [Hash] this attribute MUST include: { primary_email: "[email protected]" } # @return [Hash] formatted as {success: {command: :user_delete, attributes: {primary_email: "user@domain"}, response: "" } } def user_delete( attributes: )
response = service.delete_user( attributes[:primary_email] ) {response: response, attributes: attributes[:primary_email], command: :user_delete} end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/manager.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/manager.rb#L61-L74
ruby
test
# Constructs a manager. Accepts a hash of config options # name - name which this bean will be added # env - environment being executed under. For a rails project, this will be the value of Rails.env # worker_file - the worker file is a hash with the environment or hostname as the primary key and a subhash with the worker names # as the keys and the config options for the value. In this file, the env will be searched first and if that doesn't exist, # the hostname will then be searched. Workers can be defined for development without having to specify the hostname. For # production, a set of workers could be defined under production or specific workers for each host name. # persist_file - WorkerConfig attributes that are modified externally (via Rumx interface) will be stored in this file. Without this # option, external config changes that are made will be lost when the Manager is restarted. # Create a timer_thread to make periodic calls to the worker_configs in order to do such things as expand/contract # workers, etc.
def start_timer_thread
# Constructs a manager. Accepts a hash of config options # name - name which this bean will be added # env - environment being executed under. For a rails project, this will be the value of Rails.env # worker_file - the worker file is a hash with the environment or hostname as the primary key and a subhash with the worker names # as the keys and the config options for the value. In this file, the env will be searched first and if that doesn't exist, # the hostname will then be searched. Workers can be defined for development without having to specify the hostname. For # production, a set of workers could be defined under production or specific workers for each host name. # persist_file - WorkerConfig attributes that are modified externally (via Rumx interface) will be stored in this file. Without this # option, external config changes that are made will be lost when the Manager is restarted. # Create a timer_thread to make periodic calls to the worker_configs in order to do such things as expand/contract # workers, etc. def start_timer_thread
@timer_thread = Thread.new do begin while !@stopped @worker_configs.each do |worker_config| worker_config.periodic_call(@poll_time) end sleep @poll_time end rescue Exception => e Qwirk.logger.error "Timer thread failed with exception: #{e.message}\n\t#{e.backtrace.join("\n\t")}" end end end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/manager.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/manager.rb#L100-L126
ruby
test
# Store off any options that are no longer set to default
def save_persist_state
# Store off any options that are no longer set to default def save_persist_state
return unless @persist_file new_persist_options = {} BaseWorker.worker_classes.each do |worker_class| worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options| static_options = default_options.merge(@worker_options[config_name] || {}) worker_config = self[config_name] hash = {} # Only store off the config values that are specifically different from default values or values set in the workers.yml file # Then updates to these values will be allowed w/o being hardcoded to an old default value. worker_config.bean_get_attributes do |attribute_info| if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1 param_name = attribute_info.ancestry[0].to_sym value = attribute_info.value hash[param_name] = value if static_options[param_name] != value end end new_persist_options[config_name] = hash unless hash.empty? end end if new_persist_options != @persist_options @persist_options = new_persist_options File.open(@persist_file, 'w') do |out| YAML.dump(@persist_options, out ) end end end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/wiki/redmine_wiki.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/redmine_wiki.rb#L18-L76
ruby
test
# after calling this action, I expect the titles and revisions to be filled
def read_pages # get all projects
# after calling this action, I expect the titles and revisions to be filled def read_pages # get all projects
results_projects = database.query("SELECT id, identifier, name FROM projects;") results_projects.each do |row_project| #collect all namespaces namespaces << OpenStruct.new(identifier: row_project["identifier"], name: row_project["name"]) end # get all wikis results_wikis = database.query("SELECT id, project_id FROM wikis;") # get all lemmas results_pages = database.query("SELECT id, title, wiki_id FROM wiki_pages;") results_pages.each do |row_page| results_contents = database.query("SELECT * FROM wiki_content_versions WHERE page_id='#{row_page["id"]}' ORDER BY updated_on;") # get wiki for page wiki_row = nil project_row = nil results_wikis.each do |wiki| wiki_row = wiki if wiki["id"] == row_page["wiki_id"] end if wiki_row # get project from wiki-id results_projects.each do |project| project_row = project if project["id"] == wiki_row["project_id"] end end project_identifier = project_row ? project_row["identifier"] + '/' : "" title = project_identifier + row_page["title"] titles << title @latest_revisions = {} results_contents.each do |row_content| author = authors[row_content["author_id"]] ? @authors[row_content["author_id"]] : nil page = Page.new({:id => row_content["id"], :title => title, :body => row_content["data"], :markup => :textile, :latest => false, :time => row_content["updated_on"], :message => row_content["comments"], :author => author, :author_name => author.name}) revisions << page @latest_revisions[title] = page end end titles.uniq! @latest_revisions.each { |rev| rev[1].set_latest } revisions.sort! { |a,b| a.time <=> b.time } # TODO find latest revision for each limit revisions end
dcu/mongomapper_ext
ef82e95339cd039b3146a86a763053f89f9aef10
lib/mongomapper_ext/storage.rb
https://github.com/dcu/mongomapper_ext/blob/ef82e95339cd039b3146a86a763053f89f9aef10/lib/mongomapper_ext/storage.rb#L115-L144
ruby
test
# NOTE: this method will be removed on next release
def upgrade_file_key(key, save = true)
# NOTE: this method will be removed on next release def upgrade_file_key(key, save = true)
cname = self.collection.name files = self.database["#{cname}.files"] chunks = self.database["#{cname}.chunks"] fname = self["_#{key}"] rescue nil return if fname.blank? begin n = Mongo::GridIO.new(files, chunks, fname, "r", :query => {:filename => fname}) v = n.read if !v.empty? data = StringIO.new(v) self.put_file(key, data) self["_#{key}"] = nil self.save(:validate => false) if save end rescue => e puts "ERROR: #{e}" puts e.backtrace.join("\t\n") return end files.remove(:_id => fname) chunks.remove(:_id => fname) end
bpardee/qwirk
5fb9700cff5511a01181be8ff9cfa9172036a531
lib/qwirk/publish_handle.rb
https://github.com/bpardee/qwirk/blob/5fb9700cff5511a01181be8ff9cfa9172036a531/lib/qwirk/publish_handle.rb#L57-L77
ruby
test
# Waits the given timeout for a response message on the queue. # # If called w/o a block: # Returns the message # Returns nil on timeout # Raises RemoteException on a remote exception # # If called with a block, for instance: # handle.read_response(timeout) do |response| # response.on_message 'CharCount' do |hash| # puts "CharCount returned #{hash.inspect}" # end # response.on_message 'Length', 'Reverse' do |val| # puts "#{response.name} returned #{val}" # end # response.on_message 'ExceptionRaiser' do |val| # puts "#{response.name} didn't raise an exception but returned #{val}" # end # response.on_timeout 'Reverse' do # puts "Reverse has it's own timeout handler" # end # response.on_timeout do # puts "#{response.name} did not respond in time" # end # response.on_remote_exception 'ExceptionRaiser' do # puts "It figures that ExceptionRaiser would raise an exception" # end # response.on_remote_exception do |e| # puts "#{response.name} raised an exception #{e.message}\n\t#{e.backtrace.join("\n\t")}" # end # end # # The specified blocks will be called for each response. For instance, LengthWorker#request # might return 4 and "Length returned 4" would be displayed. If it failed to respond within the # timeout, then "Length did no respond in time" would be displayed. # For Workers that raise an exception, they will either be handled by their specific handler if it exists or # the default exception handler. If that doesn't exist either, then the RemoteException will be raised for the # whole read_response call. Timeouts will also be handled by the default timeout handler unless a specific one # is specified. All messages must have a specific handler specified because the call won't return until all # specified handlers either return, timeout, or return an exception.
def read_response(timeout, &block)
# Waits the given timeout for a response message on the queue. # # If called w/o a block: # Returns the message # Returns nil on timeout # Raises RemoteException on a remote exception # # If called with a block, for instance: # handle.read_response(timeout) do |response| # response.on_message 'CharCount' do |hash| # puts "CharCount returned #{hash.inspect}" # end # response.on_message 'Length', 'Reverse' do |val| # puts "#{response.name} returned #{val}" # end # response.on_message 'ExceptionRaiser' do |val| # puts "#{response.name} didn't raise an exception but returned #{val}" # end # response.on_timeout 'Reverse' do # puts "Reverse has it's own timeout handler" # end # response.on_timeout do # puts "#{response.name} did not respond in time" # end # response.on_remote_exception 'ExceptionRaiser' do # puts "It figures that ExceptionRaiser would raise an exception" # end # response.on_remote_exception do |e| # puts "#{response.name} raised an exception #{e.message}\n\t#{e.backtrace.join("\n\t")}" # end # end # # The specified blocks will be called for each response. For instance, LengthWorker#request # might return 4 and "Length returned 4" would be displayed. If it failed to respond within the # timeout, then "Length did no respond in time" would be displayed. # For Workers that raise an exception, they will either be handled by their specific handler if it exists or # the default exception handler. If that doesn't exist either, then the RemoteException will be raised for the # whole read_response call. Timeouts will also be handled by the default timeout handler unless a specific one # is specified. All messages must have a specific handler specified because the call won't return until all # specified handlers either return, timeout, or return an exception. def read_response(timeout, &block)
raise "Invalid call to read_response for #{@producer}, not setup for responding" unless @producer.response_options # Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object # that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read. # This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond. @producer.impl.with_response(@adapter_info) do |consumer| if block_given? return read_multiple_response(consumer, timeout, &block) else tri = read_single_response(consumer, timeout) if tri response = tri[1] raise response if response.kind_of?(Qwirk::RemoteException) return response else @timeout = !tri return nil end end end end
chrisjones-tripletri/rake_command_filter
0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f
lib/command_definition.rb
https://github.com/chrisjones-tripletri/rake_command_filter/blob/0c55e58f261b088d5ba67ea3bf28e6ad8b2be68f/lib/command_definition.rb#L23-L26
ruby
test
# if a line doesn't match any of the patterns, then # @param name a name used to identify the command in ouput # add a new filter for output from this command # @param id [Symbol] an identifier for the filter within the command # @param pattern [RegEx] a regular expression which matches a pattern in a line # @yield yields back an array of matches from the pattern. The block should return # a CommmandDefinition#result_... variant
def add_filter(id, pattern, &block)
# if a line doesn't match any of the patterns, then # @param name a name used to identify the command in ouput # add a new filter for output from this command # @param id [Symbol] an identifier for the filter within the command # @param pattern [RegEx] a regular expression which matches a pattern in a line # @yield yields back an array of matches from the pattern. The block should return # a CommmandDefinition#result_... variant def add_filter(id, pattern, &block)
filter = LineFilter.new(id, pattern, block) @filters << filter end
Dervol03/watir-formhandler
5bde899fd4e1f6d4293f8797bdeb32499507f798
lib/watir-formhandler/select.rb
https://github.com/Dervol03/watir-formhandler/blob/5bde899fd4e1f6d4293f8797bdeb32499507f798/lib/watir-formhandler/select.rb#L32-L35
ruby
test
# Selected option(s) of this Select. # @return [String, Array<String>] if only one option is selected, return it as string, # otherwise, return it as an array of strings.
def field_value
# Selected option(s) of this Select. # @return [String, Array<String>] if only one option is selected, return it as string, # otherwise, return it as an array of strings. def field_value
opts = selected_options opts.count == 1 ? opts.first.text : opts.map(&:text) end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/attr_formatter.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/attr_formatter.rb#L20-L29
ruby
test
# Define a formatter for instances of the current class. # <br>Parameters # * method - A symbol used to name the formatting method created by this method. # * library - A hash of formatting rules that define the formatting # capabilities supported by this formatter. # <br>Meta-effects # * Creates a method (named after the symbol in method) that formats the # instance of the class. The created method takes one parameter: # <br>Meta-method Parameters # * spec_str - A format specification string with %x etc qualifiers. # <br>Meta-method Returns # * A formatted string # <br>Returns # * The format engine used by this method.
def attr_formatter(method, library)
# Define a formatter for instances of the current class. # <br>Parameters # * method - A symbol used to name the formatting method created by this method. # * library - A hash of formatting rules that define the formatting # capabilities supported by this formatter. # <br>Meta-effects # * Creates a method (named after the symbol in method) that formats the # instance of the class. The created method takes one parameter: # <br>Meta-method Parameters # * spec_str - A format specification string with %x etc qualifiers. # <br>Meta-method Returns # * A formatted string # <br>Returns # * The format engine used by this method. def attr_formatter(method, library)
engine = Engine.new(library) #Create an instance method to do the formatting. define_method(method) do |spec_str| engine.do_format(self, spec_str) end engine end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/selection.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L27-L40
ruby
test
# Print selected nodes to stdout # # @param template [Template::Base] Template to evaluate and print
def write(template = nil)
# Print selected nodes to stdout # # @param template [Template::Base] Template to evaluate and print def write(template = nil)
if not template.nil? then template = template.to_mixml_template end each_node do |node| if template.nil? then node.write_xml_to($stdout) puts else puts template.evaluate(node) end end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/selection.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L45-L52
ruby
test
# Replace selected nodes with a template # # @param template [Template::Base] Template to replace nodes with
def replace(template)
# Replace selected nodes with a template # # @param template [Template::Base] Template to replace nodes with def replace(template)
template = template.to_mixml_template each_node do |node| value = template.evaluate(node) node.replace(value) end end
jochenseeber/mixml
0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214
lib/mixml/selection.rb
https://github.com/jochenseeber/mixml/blob/0cf20b995a5d050ff533b6dec2f6fa1ddd0e3214/lib/mixml/selection.rb#L81-L88
ruby
test
# Rename selected nodes with a template # # @param template [Template::Base] Template for new name
def rename(template)
# Rename selected nodes with a template # # @param template [Template::Base] Template for new name def rename(template)
template = template.to_mixml_template each_node do |node| value = template.evaluate(node) node.name = value end end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/gollum_output.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/gollum_output.rb#L22-L29
ruby
test
# Commit the given page into the gollum-wiki-repository. # Make sure the target markup is correct before calling this method.
def commit_revision(page, markup)
# Commit the given page into the gollum-wiki-repository. # Make sure the target markup is correct before calling this method. def commit_revision(page, markup)
gollum_page = gollum.page(page.title) if gollum_page gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page)) else gollum.write_page(page.title, markup, page.body, build_commit(page)) end end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/gollum_output.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/gollum_output.rb#L32-L39
ruby
test
# Commit all revisions of the given history into this gollum-wiki-repository.
def commit_history(revisions, options = {}, &block)
# Commit all revisions of the given history into this gollum-wiki-repository. def commit_history(revisions, options = {}, &block)
options[:markup] = :markdown if !options[:markup] # target markup revisions.each_with_index do |page, index| # call debug output from outside block.call(page, index) if block_given? commit_revision(page, options[:markup]) end end
PeterCamilleri/format_engine
f8df6e44895a0bf223882cf7526d5770c8a26d03
lib/format_engine/format_spec.rb
https://github.com/PeterCamilleri/format_engine/blob/f8df6e44895a0bf223882cf7526d5770c8a26d03/lib/format_engine/format_spec.rb#L30-L50
ruby
test
# Scan the format string extracting literals and variables.
def scan_spec(fmt_string)
# Scan the format string extracting literals and variables. def scan_spec(fmt_string)
until fmt_string.empty? if (match_data = PARSE_REGEX.match(fmt_string)) mid = match_data.to_s pre = match_data.pre_match @specs << FormatLiteral.new(pre) unless pre.empty? @specs << case when match_data[:var] then FormatVariable.new(mid) when match_data[:set] then FormatSet.new(mid) when match_data[:rgx] then FormatRgx.new(mid) when match_data[:per] then FormatLiteral.new("\%") else fail "Impossible case in scan_spec." end fmt_string = match_data.post_match else @specs << FormatLiteral.new(fmt_string) fmt_string = "" end end end
LAS-IT/google_directory
7945f5c228dc58a0c58233b4e511152f2009b492
lib/google_directory/connection.rb
https://github.com/LAS-IT/google_directory/blob/7945f5c228dc58a0c58233b4e511152f2009b492/lib/google_directory/connection.rb#L57-L68
ruby
test
# @note Run a command against Google Directory # # @param command [Symbol] choose command to perform these include: :user_get, :user_exists? (t/f), :user_create, :user_delete, :user_update & convience commands :user_suspend, :user_reactivate, :user_change_password # @param attributes [Hash] attributes needed to perform command # @return [Hash] formatted as: `{success: {command: :command, attributes: {primary_email: "user@domain"}, response: GoogleAnswer} }`
def run( command:, attributes: {} )
# @note Run a command against Google Directory # # @param command [Symbol] choose command to perform these include: :user_get, :user_exists? (t/f), :user_create, :user_delete, :user_update & convience commands :user_suspend, :user_reactivate, :user_change_password # @param attributes [Hash] attributes needed to perform command # @return [Hash] formatted as: `{success: {command: :command, attributes: {primary_email: "user@domain"}, response: GoogleAnswer} }` def run( command:, attributes: {} )
response = {} begin response = send( command, attributes: attributes ) response[:status] = 'success' rescue Google::Apis::ClientError => error response = {status: 'error', response: error, attributes: attributes, command: command, } end response end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/wiki/trac_converter.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/trac_converter.rb#L6-L41
ruby
test
# take an input stream and convert all wikka syntax to markdown syntax # taken from 'trac_wiki_to_textile' at
def to_textile str
# take an input stream and convert all wikka syntax to markdown syntax # taken from 'trac_wiki_to_textile' at def to_textile str
body = body.dup body.gsub!(/\r/, '') body.gsub!(/\{\{\{([^\n]+?)\}\}\}/, '@\1@') body.gsub!(/\{\{\{\n#!([^\n]+?)(.+?)\}\}\}/m, '<pre><code class="\1">\2</code></pre>') body.gsub!(/\{\{\{(.+?)\}\}\}/m, '<pre>\1</pre>') # macro body.gsub!(/\[\[BR\]\]/, '') body.gsub!(/\[\[PageOutline.*\]\]/, '{{toc}}') body.gsub!(/\[\[Image\((.+?)\)\]\]/, '!\1!') # header body.gsub!(/=====\s(.+?)\s=====/, "h5. #{'\1'} \n\n") body.gsub!(/====\s(.+?)\s====/, "h4. #{'\1'} \n\n") body.gsub!(/===\s(.+?)\s===/, "h3. #{'\1'} \n\n") body.gsub!(/==\s(.+?)\s==/, "h2. #{'\1'} \n\n") body.gsub!(/=\s(.+?)\s=[\s\n]*/, "h1. #{'\1'} \n\n") # table body.gsub!(/\|\|/, "|") # link body.gsub!(/\[(http[^\s\[\]]+)\s([^\[\]]+)\]/, ' "\2":\1' ) body.gsub!(/\[([^\s]+)\s(.+)\]/, ' [[\1 | \2]] ') body.gsub!(/([^"\/\!])(([A-Z][a-z0-9]+){2,})/, ' \1[[\2]] ') body.gsub!(/\!(([A-Z][a-z0-9]+){2,})/, '\1') # text decoration body.gsub!(/'''(.+)'''/, '*\1*') body.gsub!(/''(.+)''/, '_\1_') body.gsub!(/`(.+)`/, '@\1@') # itemize body.gsub!(/^\s\s\s\*/, '***') body.gsub!(/^\s\s\*/, '**') body.gsub!(/^\s\*/, '*') body.gsub!(/^\s\s\s\d\./, '###') body.gsub!(/^\s\s\d\./, '##') body.gsub!(/^\s\d\./, '#') body end
Dahie/caramelize
6bb93b65924edaaf071a8b3947d0545d5759bc5d
lib/caramelize/wiki/trac_converter.rb
https://github.com/Dahie/caramelize/blob/6bb93b65924edaaf071a8b3947d0545d5759bc5d/lib/caramelize/wiki/trac_converter.rb#L45-L80
ruby
test
# TODO this is so far only copy of textile conversion # not tested!
def to_markdown str
# TODO this is so far only copy of textile conversion # not tested! def to_markdown str
body = body.dup body.gsub!(/\r/, '') body.gsub!(/\{\{\{([^\n]+?)\}\}\}/, '@\1@') body.gsub!(/\{\{\{\n#!([^\n]+?)(.+?)\}\}\}/m, '<pre><code class="\1">\2</code></pre>') body.gsub!(/\{\{\{(.+?)\}\}\}/m, '<pre>\1</pre>') # macro body.gsub!(/\[\[BR\]\]/, '') body.gsub!(/\[\[PageOutline.*\]\]/, '{{toc}}') body.gsub!(/\[\[Image\((.+?)\)\]\]/, '!\1!') # header body.gsub!(/=====\s(.+?)\s=====/, "== #{'\1'} ==\n\n") body.gsub!(/====\s(.+?)\s====/, "=== #{'\1'} ===\n\n") body.gsub!(/===\s(.+?)\s===/, "==== #{'\1'} ====\n\n") body.gsub!(/==\s(.+?)\s==/, "===== #{'\1'} =====\n\n") body.gsub!(/=\s(.+?)\s=[\s\n]*/, "====== #{'\1'} ======\n\n") # table body.gsub!(/\|\|/, "|") # link body.gsub!(/\[(http[^\s\[\]]+)\s([^\[\]]+)\]/, ' "\2":\1' ) body.gsub!(/\[([^\s]+)\s(.+)\]/, ' [[\1 | \2]] ') body.gsub!(/([^"\/\!])(([A-Z][a-z0-9]+){2,})/, ' \1[[\2]] ') body.gsub!(/\!(([A-Z][a-z0-9]+){2,})/, '\1') # text decoration body.gsub!(/'''(.+)'''/, '*\1*') body.gsub!(/''(.+)''/, '_\1_') body.gsub!(/`(.+)`/, '@\1@') # itemize body.gsub!(/^\s\s\s\*/, '***') body.gsub!(/^\s\s\*/, '**') body.gsub!(/^\s\*/, '*') body.gsub!(/^\s\s\s\d\./, '###') body.gsub!(/^\s\s\d\./, '##') body.gsub!(/^\s\d\./, '#') body end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ruby_classes/strings.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ruby_classes/strings.rb#L259-L277
ruby
test
# supports: strings, arrays and regexes :) # @returns a Regexp
def autoregex(anything)
# supports: strings, arrays and regexes :) # @returns a Regexp def autoregex(anything)
deb "Autoregex() supercool! With a #{blue anything.class}" case anything.class.to_s when 'String' if anything.match(/^\/.*\/$/) # '/asd/' is probably an error! The regex builder trails with '/' automatically fatal 23,"Attention, the regex is a string with trailing '/', are you really SURE this is what you want?!?" end return Regexp.new(anything) when 'Regexp' return anything # already ok when 'Array' return Regexp.new(anything.join('|')) else msg = "Unknown class for autoregexing: #{red anything.class}" $stderr.puts( msg ) raise( msg ) end return nil end
palladius/ric
3078a1d917ffbc96a87cc5090485ca948631ddfb
lib/ric/debug.rb
https://github.com/palladius/ric/blob/3078a1d917ffbc96a87cc5090485ca948631ddfb/lib/ric/debug.rb#L16-L30
ruby
test
# shouldnt work right now yet..
def debug2(s, opts = {} )
# shouldnt work right now yet.. def debug2(s, opts = {} )
out = opts.fetch(:out, $stdout) tag = opts.fetch(:tag, '_DFLT_') really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false write_always = opts.fetch(:write_always, false) raise "ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?" if ( opts[:tags] && opts[:tags].class != Array ) final_str = "#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}" final_str = "\033[1;30m" +final_str + "\033[0m" if opts.fetch(:coloured_debug, true) # color by gray by default if (debug_tags_enabled? ) # tags puts( final_str ) if debug_tag_include?( opts ) else # normal behaviour: if NOT tag puts( final_str ) if ((really_write && $DEBUG) || write_always) && ! opts[:tag] end end
barkerest/barkest_ssh
605f8dc697a7ad0794949054f6fc360c00b2e54e
lib/barkest_ssh/secure_shell.rb
https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L224-L272
ruby
test
# 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+ parameter can include the following keys. # * The :on_non_zero_exit_code option can be :default, :ignore, or :raise_error. # # 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
def exec(command, options={}, &block)
# 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+ parameter can include the following keys. # * The :on_non_zero_exit_code option can be :default, :ignore, or :raise_error. # # 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 def exec(command, options={}, &block)
raise ConnectionClosed.new('Connection is closed.') unless @channel options = { on_non_zero_exit_code: :default }.merge(options || {}) options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :default push_buffer # store the current buffer and start a fresh buffer # buffer while also passing data to the supplied block. if block_given? buffer_input( &block ) end # send the command and wait for the prompt to return. @channel.send_data command + "\n" wait_for_prompt # return buffering to normal. if block_given? buffer_input end # get the output from the command, minus the trailing prompt. ret = command_output(command) # restore the original buffer and merge the output from the command. pop_merge_buffer if @options[:retrieve_exit_code] # get the exit code for the command. push_buffer retrieve_command = 'echo $?' @channel.send_data retrieve_command + "\n" wait_for_prompt @last_exit_code = command_output(retrieve_command).strip.to_i # restore the original buffer and discard the output from this command. pop_discard_buffer # if we are expected to raise an error, do so. if options[:on_non_zero_exit_code] == :raise_error raise NonZeroExitCode.new("Exit code was #{@last_exit_code}.") unless @last_exit_code == 0 end end ret end
barkerest/barkest_ssh
605f8dc697a7ad0794949054f6fc360c00b2e54e
lib/barkest_ssh/secure_shell.rb
https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L322-L325
ruby
test
# Uses SFTP to upload a single file to the host.
def upload(local_file, remote_file)
# Uses SFTP to upload a single file to the host. def upload(local_file, remote_file)
raise ConnectionClosed.new('Connection is closed.') unless @ssh sftp.upload!(local_file, remote_file) end
barkerest/barkest_ssh
605f8dc697a7ad0794949054f6fc360c00b2e54e
lib/barkest_ssh/secure_shell.rb
https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L329-L332
ruby
test
# Uses SFTP to download a single file from the host.
def download(remote_file, local_file)
# Uses SFTP to download a single file from the host. def download(remote_file, local_file)
raise ConnectionClosed.new('Connection is closed.') unless @ssh sftp.download!(remote_file, local_file) end
barkerest/barkest_ssh
605f8dc697a7ad0794949054f6fc360c00b2e54e
lib/barkest_ssh/secure_shell.rb
https://github.com/barkerest/barkest_ssh/blob/605f8dc697a7ad0794949054f6fc360c00b2e54e/lib/barkest_ssh/secure_shell.rb#L345-L350
ruby
test
# Uses SFTP to write data to a single file.
def write_file(remote_file, data)
# Uses SFTP to write data to a single file. def write_file(remote_file, data)
raise ConnectionClosed.new('Connection is closed.') unless @ssh sftp.file.open(remote_file, 'w') do |f| f.write data end end
megamoose/gpsutils
77db6e2c47c1237a687abe05e52f1717fed364b1
lib/gpsutils.rb
https://github.com/megamoose/gpsutils/blob/77db6e2c47c1237a687abe05e52f1717fed364b1/lib/gpsutils.rb#L52-L64
ruby
test
# Measure the distance between this point and another. # # Distance is calculated using equirectangular projection. # @see https://en.wikipedia.org/wiki/Equirectangular_projection # # @param other [Point] # @return [Float] # @raise [ArgumentError] if other is not a Point
def distance(other)
# Measure the distance between this point and another. # # Distance is calculated using equirectangular projection. # @see https://en.wikipedia.org/wiki/Equirectangular_projection # # @param other [Point] # @return [Float] # @raise [ArgumentError] if other is not a Point def distance(other)
unless other.is_a? Point raise ArgumentError.new 'other must be a Point.' end dlng = GpsUtils::to_radians(other.lng - @lng) dlat = GpsUtils::to_radians(other.lat - @lat) x = dlng * Math.cos(dlat / 2) y = GpsUtils::to_radians(other.lat - @lat) Math.sqrt(x**2 + y**2) * GpsUtils::R end
megamoose/gpsutils
77db6e2c47c1237a687abe05e52f1717fed364b1
lib/gpsutils.rb
https://github.com/megamoose/gpsutils/blob/77db6e2c47c1237a687abe05e52f1717fed364b1/lib/gpsutils.rb#L103-L110
ruby
test
# Initialize BoundingBox. # # @param nw_point [Point] North-West corner # @param se_point [Point] South-East corner # Determine whether point is inside bounding box. # # @param point [Point]
def cover?(point)
# Initialize BoundingBox. # # @param nw_point [Point] North-West corner # @param se_point [Point] South-East corner # Determine whether point is inside bounding box. # # @param point [Point] def cover?(point)
p = [point.lat - @nw.lat, point.lng - @se.lng] p21x = p[0] * @p21 p41x = p[1] * @p41 0 < p21x and p21x < @p21ms and 0 <= p41x and p41x <= @p41ms end
dcu/mongomapper_ext
ef82e95339cd039b3146a86a763053f89f9aef10
lib/mongomapper_ext/paginator.rb
https://github.com/dcu/mongomapper_ext/blob/ef82e95339cd039b3146a86a763053f89f9aef10/lib/mongomapper_ext/paginator.rb#L37-L43
ruby
test
# for will paginate support
def send(method, *args, &block)
# for will paginate support def send(method, *args, &block)
if respond_to?(method) super else subject.send(method, *args, &block) end end