blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
137
path
stringlengths
2
355
src_encoding
stringclasses
31 values
length_bytes
int64
11
3.9M
score
float64
2.52
5.47
int_score
int64
3
5
detected_licenses
listlengths
0
49
license_type
stringclasses
2 values
text
stringlengths
11
3.93M
download_success
bool
1 class
11df08cd511839f8df2e58519c87d3223783f9fd
Ruby
outlyerapp/dataloop-chef-handler
/files/default/dataloop_annotations.rb
UTF-8
2,123
2.625
3
[ "Apache-2.0" ]
permissive
require "chef" require "chef/handler" require "timeout" require "net/http" require "net/https" require "uri" class Chef::Handler::Dataloop < Chef::Handler attr_writer :api_token, :host, :org, :account, :stream def initialize(options = {}) @host = options[:host] || 'app.dataloop.io' @api_token = options[:api_token] || '' @org = options[:org] || '' @account = options[:account] || '' @stream = options[:stream] || "chef" end def report Chef::Log.debug("Loaded dataloop chef handler") metrics = Hash.new metrics[:updated_resources] = run_status.updated_resources.length if run_status.updated_resources metrics[:all_resources] = run_status.all_resources.length if run_status.all_resources metrics[:elapsed_time] = run_status.elapsed_time if run_status.success? metrics[:success] = 1 metrics[:fail] = 0 status_message = "success: " else metrics[:success] = 0 metrics[:fail] = 1 status_message = "failed: " end # metrics.each do |metric, value| # puts "#{metric} #{value}" # end status_message += "#{metrics[:updated_resources]}/#{metrics[:all_resources]} updated in #{metrics[:elapsed_time]} seconds" uri = URI.parse("https://#{@host}/api/v1/orgs/#{@org}/accounts/#{@account}/annotations/#{@stream}") https = Net::HTTP.new(uri.host,uri.port) https.use_ssl = true req = Net::HTTP::Post.new(uri.path) req.add_field('Authorization', "Bearer #{@api_token}") req.add_field('Content-Type', 'application/json') req.body = '{"name": "'+run_status.node.name.to_s+'", "description": "'+status_message+'"}' begin response = https.request(req) Chef::Log.info("annotation status: #{response.code}") # rescue StandardError => e rescue Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e Chef::Log.error("failed to annotate Dataloop @ '#{@host}' :- #{e}") end end end
true
69e4ed310f87a7da9081881db7ae905bccb0fe39
Ruby
tayloredwebsites/curriculum
/app/models/tree.rb
UTF-8
10,517
2.578125
3
[]
no_license
class Tree < BaseRec # Note: Found english version of letters mixed in with cryllic # mapped english version of aejko cyrillic letters to match the corresponding english letter so both versions of the letter would map out properly to the english # then mapped cyrillic letters, so english to cyrillic would return cryllic INDICATOR_SEQ_ENG = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'a', 'e', 'j', 'k', 'o'] INDICATOR_SEQ_CYR = ['а', 'б', 'ц', 'д', 'е', 'ф', 'г', 'х', 'и', 'ј', 'к', 'л', 'м', 'н', 'о', 'п', 'a', 'e', 'j', 'k', 'o'] # hash to return english letter for cyrillic letter GET_ENG_IND_H = INDICATOR_SEQ_CYR.zip(INDICATOR_SEQ_ENG).to_h # hash to return cyrillic letter for english letter GET_CYR_IND_H = INDICATOR_SEQ_ENG.zip(INDICATOR_SEQ_CYR).to_h # indicator sequence in cyrillic order (not in western order) INDICATOR_CYR_SEQ_CYR = ['а', 'б', 'в', 'г' ,'д' ,'ђ' ,'е' ,'ж' ,'з' ,'и' ,'ј' ,'к' ,'л' ,'љ' ,'м' ,'н', 'a', 'e', 'j', 'k', 'o'] # hash to return cyrillic letter for english letter in sequence order GET_ENG_SEQ_CYR_IND_H = INDICATOR_CYR_SEQ_CYR.zip(INDICATOR_SEQ_ENG).to_h belongs_to :tree_type belongs_to :version belongs_to :subject belongs_to :grade_band has_and_belongs_to_many :sectors # has_and_belongs_to_many :related_trees, class_name: "Tree", join_table: "related_trees_trees" has_and_belongs_to_many(:related_trees, :class_name => "Tree", :join_table => "related_trees_trees", :foreign_key => "tree_id", :association_foreign_key => "related_tree_id") # does not seem to be working ? # has_many :my_translations # are these necessary? validates :tree_type, presence: true validates :version, presence: true validates :subject, presence: true validates :grade_band, presence: true validates :code, presence: true, allow_blank: false # removed for testing issues. set values in controller # # scope for hard coded variables # scope :otc_tree, -> { # where(tree_type_id: TREE_TYPE_ID, version_id: VERSION_ID) # } scope :otc_listing, -> { order('subjects.code', 'grade_bands.code', 'locales.name') # where(active: true) } def code_by_ix(ix) if depth == 3 if self.matching_codes.length > ix mcs = JSON.load(matching_codes) return mcs[ix] end end return code end def codeArray if self.code.present? return self.code.split('.') else return nil end end # return the last code in the code string (return c from a.b.c) def subCode if self.code.present? return self.codeArray[-1] else return nil end end def parentCode arr = self.codeArray if arr && arr.length > 0 arr.pop(1) return arr.join('.') else return '' end end def area return self.codeArray[0] end def component if self.depth.present? && self.depth > 0 return self.codeArray[1] else return nil end end def outcome if self.depth.present? && self.depth > 1 return self.codeArray[2] else return nil end end def indicator if self.depth.present? && self.depth > 2 return self.codeArray[3] else return nil end end def self.engIndicatorLetter(letter, seq) # convert cyrillic to western alphabet depending upon sequencing ret = '' if seq == 'c' ret = GET_ENG_SEQ_CYR_IND_H[letter] else ret = GET_ENG_IND_H[letter] end if ret.present? return ret else return "#{letter}(#{letter.bytes})-INVALID" end end def self.validCyrIndicatorLetter?(letter) if INDICATOR_SEQ_CYR.include?(letter) return true else return false end end # return the indicator letter by locale (translating SR to latin equivalent) # indicators are mapped in either: # a cyrillic sequenced mapping абвгдђ... to abcde... # or a western sequenced mapping from абцде... to abcde...) def self.indicatorLetterByLocale(locale, letter, seq='c') if locale == BaseRec::LOCALE_SR return Tree.engIndicatorLetter(letter, seq) else if INDICATOR_SEQ_ENG.include?(letter) return letter else return "#{letter}(#{letter.bytes})-INVALID" end end end def self.cyrIndicatorCode(codeIn) # indicator code letter is in english - map to cyrillic codeArray = codeIn.split('.') if codeArray.length > 3 indicLetter = codeArray[3] if INDICATOR_SEQ_ENG.include?(indicLetter) codeArray[3] = GET_CYR_IND_H[indicLetter] return codeArray.join('.') end end end def codeByLocale(locale, ix=0) retCode = code_by_ix(ix) if locale == BaseRec::LOCALE_SR return Tree.cyrIndicatorCode(code) else return retCode end end def self.buildNameKey(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) return "#{treeTypeRec.code}.#{versionRec.code}.#{subjectRec.code}.#{gradeBandRec.code}.#{fullCode}.name" end def buildNameKey return "#{self.tree_type.code}.#{self.version.code}.#{self.subject.code}.#{self.grade_band.code}.#{self.code}.name" end def self.buildBaseKey(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) return "#{treeTypeRec.code}.#{versionRec.code}.#{subjectRec.code}.#{gradeBandRec.code}.#{fullCode}" end def buildBaseKey return "#{self.tree_type.code}.#{self.version.code}.#{self.subject.code}.#{self.grade_band.code}.#{self.code}" end def buildRootKey return "#{self.tree_type.code}.#{self.version.code}.#{self.subject.code}.#{self.grade_band.code}" end # get parent record for this item (by hierarchy code as appropriate) def getParentRec outcomes = Tree.where( tree_type_id: self.tree_type_id, version_id: self.version_id, subject_id: self.subject_id, grade_band_id: self.grade_band_id, code: self.parentCode ) if outcomes.count == 0 return nil else return outcomes.first end end # get all parent records for this item as appropriate (e.g. Area, Componrnt, and Outcome for indicator record) def getAllParents parents = [] parent = self.getParentRec while parent.present? do parents << parent parent = parent.getParentRec end return parents end # get all translation name keys needed for this record and parents (Area, Component and Outcome) def getAllTransNameKeys parents = self.getAllParents allRecs = parents.concat([self]) treeKeys = (allRecs).map { |rec| rec.name_key} end # Tree.find_or_add_code_in_tree # treeTypeRec - tree type 'OTC' record # versionRec - version 'v01' record # subjectRec - subject record # gradeBandRec - grade band record # fullCode - code including parent codes (e.g. 1.1.1.a for a indicator). # codeArray - all indicator codes that match this indicator (when indicator has multiple codes) # parentRec - parent (area for component, component for outcome, outcome for indicator) # matchRec - last record processed (at this depth), to prevent attempting to add more than once. def self.find_or_add_code_in_tree(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode, codeArray, parentRec, matchRec, depth) # if this record is the same as matchRec, then it was already updated. matchCode = (matchRec ? matchRec.code : '') # name_key = Tree.buildNameKey(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) if fullCode == matchCode return fullCode, matchRec, BaseRec::REC_SKIP, "#{fullCode}" else # get the tree records for this hierarchy item # where() matched_codes = Tree.where( tree_type_id: treeTypeRec.id, version_id: versionRec.id, subject_id: subjectRec.id, grade_band_id: gradeBandRec.id, code: fullCode, depth: depth ) if matched_codes.count == 0 # It has not been uploaded yet. create it. tree = Tree.new tree.tree_type_id = treeTypeRec.id tree.version_id = versionRec.id tree.subject_id = subjectRec.id tree.grade_band_id = gradeBandRec.id tree.code = fullCode tree.matching_codes = codeArray tree.depth = depth # fill in parent id if parent passed in, and parent codes match. tree.name_key = Tree.buildNameKey(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) tree.base_key = Tree.buildBaseKey(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) ret = tree.save if tree.errors.count > 0 return fullCode, nil, BaseRec::REC_ERROR, "#{I18n.t('trees.errors.save_curriculum_code_error', code: fullCode)} #{tree.errors.full_messages}" else return fullCode, tree, BaseRec::REC_ADDED, "#{fullCode}" end elsif matched_codes.count == 1 # it already exists, skip matched = matched_codes.first if matched.name_key.blank? # fixed if existing record is missing translation key or parent record id matched.name_key = matched.buildNameKey matched.base_key = matched.buildBaseKey matched.save # to do - do we need error checking here? end return fullCode, matched_codes.first, BaseRec::REC_NO_CHANGE, "#{fullCode}" else # too many matching items in database: system error. err_str = I18n.t('trees.errors.too_many_match_subject_gb_code', subject: @upload.subject_id, gb: @upload.grade_band_id, code: fullCode) Rails.logger.error("ERROR: #{err_str} ") return fullCode, nil, BaseRec::REC_ERROR, err_str end # if end # if code == matchCode end def self.find_code_in_tree(treeTypeRec, versionRec, subjectRec, gradeBandRec, fullCode) # get the tree records for this hierarchy item matched_codes = Tree.where( tree_type_id: treeTypeRec.id, version_id: versionRec.id, subject_id: subjectRec.id, grade_band_id: gradeBandRec.id, code: fullCode ) Rails.logger.debug ("*** find code: #{fullCode}") if matched_codes.count == 1 # it already exists, skip matched = matched_codes.first return matched elsif matched_codes.count == 0 Rails.logger.error ("ERROR - missing tree rec for: #{subjectRec.code}, #{gradeBandRec.code}, #{fullCode}") return nil end # if end end
true
570039566722b4f53f3a897061b16731af1e9424
Ruby
litvinok/mongo-meta-driver
/ruby/lib/bson/extensions/time.rb
UTF-8
389
2.515625
3
[]
no_license
module BSON module Extensions module Time BSON_TYPE = "\x09" def to_bson [BSON_TYPE, [(to_i * 1000) + (usec / 1000)].pack(INT64_PACK)] end module ClassMethods def from_bson(bson) seconds, fragment = bson.read(8).unpack(INT64_PACK).first.divmod 1000 at(seconds, fragment * 1000).utc end end end end end
true
f87ba3c35d819eb6344dd7bcb1879a6e91d39933
Ruby
mfeinLearn/OO-Art-Gallery-dumbo-web-080618
/tools/console.rb
UTF-8
2,504
3.03125
3
[]
no_license
require_relative '../config/environment.rb' require 'pry' def reload load 'config/environment.rb' end # Declare variables here pablo_picasso = Artist.new("Pablo Picasso", 1) leonardo_da_vinci = Artist.new("Leonardo da Vinci", 1) vincent_van_gogh = Artist.new("Vincent van Gogh", 1) peter_paul_rubens = Artist.new("Peter Paul Rubens", 1) joan_miro = Artist.new("joan_miro", 17) paul_klee = Artist.new("Paul Klee", 4) gallery_1 = Gallery.new("1_Gallery","New York City") gallery_2 = Gallery.new("2_Gallery","Rochester") gallery_3 = Gallery.new("3_Gallery","Buffalo") gallery_4 = Gallery.new("4_Gallery","Albany") gallery_5 = Gallery.new("5_Gallery","Syracuse") gallery_6 = Gallery.new("6_Gallery","Niagara Falls") gallery_7 = Gallery.new("7_Gallery","Niagara Falls") painting_1= Painting.new("title of painting 1", "style of painting 1", pablo_picasso, gallery_1) painting_2= Painting.new("title of painting 2", "style of painting 2", leonardo_da_vinci, gallery_2) painting_3= Painting.new("title of painting 3", "style of painting 3", vincent_van_gogh, gallery_3) painting_4= Painting.new("title of painting 4", "style of painting 4", peter_paul_rubens, gallery_4) painting_5= Painting.new("title of painting 5", "style of painting 5", joan_miro, gallery_6) painting_6= Painting.new("title of painting 6", "style of painting 6", paul_klee, gallery_6) #ARTIST # Get a list of all artists Artist.all # Get a list of all the paintings by a specific artists pablo_picasso.artists # Get a list of all the galleries that a specific artist has paintings in pablo_picasso.galleries # Get a list of all cities that contain galleries that a specific artist has paintings in pablo_picasso.cities # Find the average years of experience of all artists Artist.average_years #PAINTING # Get a list of all paintings Painting.list_of_painting # Get a list of all painting styles (a style should not appear more than once in the list) Painting.painting_styles # GALLERY # Get a list of all galleries Gallery.list_all_galleries # Get a list of all cities that have a gallery. A city should not appear more than once in the list. #Gallery.all # arr = @@all.map {|a|a.city} # arr.uniq Gallery.gallery_city #Get a list of artists that have paintings at a specific gallery gallery_5.artists #Gallery.specific_gallery # Get a list of the names of artists that have paintings at a specific gallery gallery_6.all_artist_names # Get the combined years of experience of all artists at a specific gallery gallery_6.artist_years_of_exp binding.pry 0
true
18773c647f80cc263c36d426a02c0f4166fe8299
Ruby
ptn/chess_validator
/lib/chess_validator/board/invalid_move.rb
UTF-8
566
2.890625
3
[]
no_license
module ChessValidator class Board # Raised when a board is asked to validate a move that is not in algebraic # notation. class InvalidMove < Exception def self.for_origin(origin) new("Origin move '#{origin}' is not in valid algebraic notation") end def self.for_destination(destination) new("Destination move '#{destination}' is not in valid algebraic notation") end def self.for_indexing(index) new("Cannot retrieve piece at '#{index}' - invalid algebraic notation") end end end end
true
72a4dee6ca2f63f58760eb618e319e4baa7a2f89
Ruby
kasperbn/failsafe-control-for-DTUSat2
/server/link_fs/link_fs_devel.rb
UTF-8
1,583
2.6875
3
[]
no_license
require 'serialport' require ROOT_DIR + "/lib/logger" require ROOT_DIR + "/lib/constants" module Link_fs class << self include Constants include Loggable DEVICE = "/dev/ttyUSB0" BAUD = 9600 DATA_BITS = 8 STOP_BITS = 1 PARITY = SerialPort::NONE def link_fs_init(rw) begin $sp = SerialPort.new(DEVICE, BAUD, DATA_BITS, STOP_BITS, PARITY) return PRO_OK rescue => e log "SerialPort init error: #{e}" return PRO_FAILURE end end def link_fs_send_packet(data, length) begin data.each do |s| sleep(0.2) $sp.putc(s) end return PRO_OK rescue => e log "SerialPort write error: #{e}" return PRO_FAILURE end end def link_fs_receive_packet(buffer, maxlength, timeout) done_reading = false status = "" # Read thread r = Thread.new do begin return_code = $sp.getc downlink = $sp.getc data_length_raw = $sp.read(2) data_length = data_length_raw.unpack("v").first data = $sp.read(data_length) done_reading = true buffer << return_code << downlink << data_length_raw << data status = PRO_OK rescue => e log "SerialPort read error: #{e}" status = PRO_FAILURE end end # Timeout thread sleep_step = 0.5 t = Thread.new do (0..(timeout/(100*sleep_step))).each do sleep(sleep_step) Thread.current.kill! if done_reading end r.kill! status = PRO_TIMEOUT end # Wait for read thread and timeout r.join t.join return buffer, status end end end
true
122c9fbb4174ba3e4547a322c8eb881e12b1ce60
Ruby
blarxfj/deli-counter-cb-gh-000
/deli_counter.rb
UTF-8
539
4.09375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def line(katz_deli) string = "The line is currently:" if katz_deli.empty? string = "The line is currently empty." else katz_deli.each_with_index { |e, i| string << " #{i+1}. #{e}" } end puts string end def take_a_number(katz_deli, name) katz_deli << name puts "Welcome, #{name}. You are number #{katz_deli.size} in line." end def now_serving(katz_deli) if katz_deli.empty? puts "There is nobody waiting to be served!" else puts "Currently serving #{katz_deli.shift}." end end
true
b6084a45af97dcc01c27adbffe23293be8616edf
Ruby
xbenjii/YuelaBot
/app/bot/commands/time_command.rb
UTF-8
804
2.859375
3
[]
no_license
module Commands class TimeCommand class << self def name :time end def attributes { description: "Displays the current time in a timezone", usage: "time <timezone>", aliases: [] } end def command(event, *args) return if event.from_bot? return "Please pass a timezone" if args.empty? timezone = args.join(' ') begin timezone_identifier = (timezone.length == 2) ? TZInfo::Country.get(timezone).zone_info.first.identifier : TZInfo::Timezone.get(timezone) rescue return "Timezone #{timezone} not found" end # Use block so we don't break anything else Time.use_zone(timezone_identifier) { Time.zone.now } end end end end
true
a1a1eb83c9295b2e36ab4c3113d434987b211eea
Ruby
kristofkovacs/meetup.sch
/app/Rakefile
UTF-8
748
2.53125
3
[]
no_license
require "bundler/setup" require "sequel" require "yaml" require "digest" namespace :db do task :create do env = ENV['RACK_ENV'] || 'development' DB = Sequel.sqlite "#{env}.db" DB.create_table :attendees do primary_key :id column :name, String, :null => false column :organization, String, :null => false column :email, String, :null => false column :phone, String end end end namespace :users do task :create do password = 10.times.map { [*'0'..'9', *'a'..'z', *'A'..'Z'].sample }.join pass_digest = Digest::SHA256.hexdigest password File.open "users.yml", "w" do |f| f.write({ "meetup" => pass_digest }.to_yaml) end puts "generated password: #{password}" end end
true
1856d4422234e0a7ad9e62ac0259b6a39c1b3ef2
Ruby
Envek/snils
/spec/snils_spec.rb
UTF-8
3,500
3.046875
3
[ "MIT" ]
permissive
require 'rspec' require 'snils' describe Snils do # DISCLAIMER: All SNILS used there ARE GENERATED AND RANDOM. Any coincidences are accidental. describe '#initialize' do it 'should initialize with formatted snils' do snils = described_class.new('963-117-158 08') expect(snils.raw).to eq('96311715808') end it 'should initialize with unformatted snils' do snils = described_class.new('96311715808') expect(snils.raw).to eq('96311715808') end it 'should initialize with numeric snils' do snils = described_class.new(963_117_158_08) expect(snils.raw).to eq('96311715808') end it 'should generate new snils if nothing provided' do snils = described_class.new expect(snils.raw.length).to eq(11) expect(snils.valid?).to be true end end describe '#valid?' do it 'should validate valid snils' do snils = described_class.new('963-117-158 08') expect(snils.valid?).to be true end it 'should not validate invalid snils (with wrong checksum)' do snils = described_class.new('963-117-158 00') expect(snils.valid?).to be false end it 'should not validate invalid snils (with wrong length)' do snils = described_class.new('963-117-158 000') expect(snils.valid?).to be false end it 'should not validate invalid snils (with wrong length)' do snils = described_class.new('963-117-158') expect(snils.valid?).to be false end end describe '#errors' do it 'should return empty array for valid snils' do snils = described_class.new('963-117-158 08') expect(snils.errors).to eq [] end it 'should not validate invalid snils (with wrong checksum)' do snils = described_class.new('963-117-158 00') expect(snils.errors).to include :invalid end it 'should not validate invalid snils (with wrong length)' do snils = described_class.new('963-117-158 080') expect(snils.errors).to include [:wrong_length, { :count => 11 }] end it 'should not validate invalid snils (with wrong length)' do snils = described_class.new('963-117-158') expect(snils.errors).to include [:wrong_length, { :count => 11 }] end end describe '#checksum' do it 'calculates valid checksum' do snils = described_class.new('96311715808') expect(snils.checksum).to eq('08') snils = described_class.new('83568300320') expect(snils.checksum).to eq('20') snils = described_class.new('61310200300') expect(snils.checksum).to eq('00') end it 'calculates valid checksum even for invalid snils' do snils = described_class.new('96311715800') expect(snils.checksum).to eq('08') end it 'calculates valid checksum even for incomplete snils' do snils = described_class.new('188299822') expect(snils.checksum).to eq('50') snils = described_class.new('563-725-063') expect(snils.checksum).to eq('00') end end describe '#formatted' do it 'outputs formatted snils' do snils = described_class.new('96311715808') expect(snils.formatted).to eq('963-117-158 08') end end describe '.generate' do it 'generates valid snils' do expect(described_class.valid?(described_class.generate)).to be true end end describe '.validate' do it 'validates valid snils' do expect(described_class.valid?(described_class.generate)).to be true end end end
true
3726f866e1fd5db674fbfc4508315c39c17a4b79
Ruby
travis-ci/travis-conditions
/lib/travis/conditions/v1/helper.rb
UTF-8
659
2.671875
3
[ "MIT" ]
permissive
module Travis module Conditions module V1 module Helper QUOTE = /["']{1}/ OPEN = /\(/ CLOSE = /\)/ SPACE = /\s*/ def quoted return unless quote = scan(QUOTE) scan(/[^#{quote}]*/).tap { scan(/#{quote}/) || err(quote) } end def parens space { skip(OPEN) } and space { yield }.tap { skip(CLOSE) || err(')') } end def space skip(SPACE) yield.tap { skip(SPACE) } end def err(char) raise ParseError, "expected #{char} at position #{pos} in: #{string.inspect}" end end end end end
true
8325885456ffde025a4fc8d71ab0a9f160a5454d
Ruby
Emmyn5600/PrivateEvent
/app/helpers/user_helper.rb
UTF-8
1,542
2.53125
3
[ "MIT" ]
permissive
module UserHelper # rubocop:disable Layout/LineLength def show_user_event_list(events) out = '' events.each do |event| out += '<div class="box">' out += "<ul class=\"is-flex is-justify-content-space-between is-align-content-center\"><li class=\"mt-2 has-text-weight-bold\">#{event.title}</li>" out += "<li>#{link_to 'More Informations', event_url(event), class: 'button is-primary is-outlined'}</li></ul>" out += '</div>' end out.html_safe end def user_upcoming_events out = '' @user_attendance.each do |attendance| out += "<li class=\"ml-6\">#{attendance.title}</li>" if attendance.date > Time.now end out.html_safe end def user_past_events out = '' @user_attendance.each do |attendance| out += "<li class=\"ml-6\">#{attendance.title}</li>" if attendance.date < Time.now end out.html_safe end def no_created_events out = '' if show_user_event_list(@user_events).empty? out += link_to "You haven't created any events, click here to create one", new_event_path, class: 'ml-5' end out.html_safe end def no_upcoming_events out = '' if user_upcoming_events.empty? out += link_to "You don't have any events to attend, click here to search for one", root_path, class: 'ml-5' end out.html_safe end def no_past_events out = '' out += "<p class=\"ml-5\">You didn't attend any events so far.</p>" if user_past_events.empty? out.html_safe end end # rubocop:enable Layout/LineLength
true
49912bf496a441e40ff116a52deee30011d2286b
Ruby
kenhys/hibahub-client
/lib/yomou/config.rb
UTF-8
1,886
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "yaml" module Yomou class Config YOMOU_CONFIG = 'yomou.yaml' DOT_YOMOU = '.yomou' def initialize @keys = [] if File.exist?(path) load else src = File.dirname(__FILE__) + "/../../examples/#{YOMOU_CONFIG}" FileUtils.cp(src, path) load if ENV['YOMOU_HOME'] path = File.join(ENV['YOMOU_HOME'], 'db/yomou.db') instance_variable_set('@database', path) end save end end def directory directory = File.join(ENV['HOME'], DOT_YOMOU) directory = ENV['YOMOU_HOME'] if ENV['YOMOU_HOME'] Dir.mkdir(directory) unless Dir.exist?(directory) directory end def path File.join(directory, YOMOU_CONFIG) end def narou_novel_directory(category) path = File.join(narou_category_directory(category), @narou_novel) path end def narou_category_directory(category) path = File.join(directory, 'narou', format("%02d", category.to_i)) path end def load YAML.load_file(path).each do |key, value| @keys << key instance_variable_set("@#{key}", value) end end def save config = {} instance_variables.each do |var| key = var.to_s.sub(/^@/, '') config[key] = instance_variable_get(var.to_s) unless key == 'keys' end File.open(path, 'w+') do |file| file.puts(YAML.dump(config)) end end def method_missing(method, *args) method_name = method.to_s if method_name.end_with?('=') property = method_name.sub(/=$/, '') @keys << property instance_variable_set("@#{property}", *args) else instance_variable_get("@#{method_name}") end end end end
true
40a3ac58a7d4f20aacb9946efe2567a04308a457
Ruby
shawnkaku/Blackjack_Webapp
/classes/player.rb
UTF-8
828
3.53125
4
[]
no_license
class Player #includ calculate_point attr_accessor :name, :status, :hold_cards, :money, :turn_bet def initialize(name) @name = name self.money = 500 self.turn_bet = 0 # Player got all cards. @hold_cards = Array.new init end def init # "RUN" => OK, "BST" => bust @status = "RUN" self.turn_bet = 0 # Player got all cards. @hold_cards.clear() # Player's point of this turn. end def hit(card) @hold_cards.push(card) end def win self.money += (self.turn_bet * 1.5).to_i self.turn_bet = 0 end def loss self.turn_bet = 0 end def tie self.money += self.turn_bet self.turn_bet = 0 end def win_bet (self.turn_bet * 1.5).to_i end def bet(bet_money) self.turn_bet = bet_money self.money -= self.turn_bet end end
true
a67359eb3f247c2791154f91caff2c40bbee12e7
Ruby
elivickery/phase-0-tracks
/ruby/iteration_drill.rb
UTF-8
5,012
3.53125
4
[]
no_license
# Array Drills zombie_apocalypse_supplies = ["hatchet", "rations", "water jug", "binoculars", "shotgun", "compass", "CB radio", "batteries"] # 1. Iterate through the zombie_apocalypse_supplies array, # printing each item in the array separated by an asterisk # ---- def print_the_array(array) i = 0 array.each do |item| print item if (i < array.length - 1) print ' * ' end i += 1 end end print_the_array(zombie_apocalypse_supplies) # 2. In order to keep yourself organized, sort your zombie_apocalypse_supplies # in alphabetical order. Do not use any special built-in methods. # ---- def alphabetize(array) i = 0 while i < array.length i2 = i + 1 while i2 < array.length if array[i].downcase > array[i2].downcase array[i], array[i2] = array[i2], array[i] end i2 += 1 end i += 1 end return array end puts alphabetize(zombie_apocalypse_supplies) # 3. Create a method to see if a particular item (string) is in the # zombie_apocalypse_supplies. Do not use any special built-in methods. # For instance: are boots in your list of supplies? # ---- def do_we_have_zombie_supplies(list) puts "What item are you looking for?" item = gets.chomp.to_s item_in_list = false list.each do |list_item| if list_item == item item_in_list = true end end if item_in_list == true return "We have that item." else return "That item isn't in our supplies." end end puts do_we_have_zombie_supplies(zombie_apocalypse_supplies) # 4. You can't carry too many things, you've only got room in your pack for 5. # Remove items in your zombie_apocalypse_supplies in any way you'd like, # leaving only 5. Do not use any special built-in methods. # ---- def only_the_essentials(list) essentials = [] i = 0 list.each do |item| essentials << item if i == 4 break end i += 1 end puts 'Only the essential 5 items:' return essentials end puts only_the_essentials(zombie_apocalypse_supplies) # 5. You found another survivor! This means you can combine your supplies. # Create a new combined supplies list out of your zombie_apocalypse_supplies # and their supplies below. You should get rid of any duplicate items. # Find the built-in method that helps you accomplish this in the Ruby # documentation for Arrays. other_survivor_supplies = [ "warm clothes", "rations", "compass", "camp stove", "solar battery", "flashlight"] # # ---- def combine_our_supplies(my_supplies, your_supplies) combined_supplies = (my_supplies + your_supplies).uniq end puts combine_our_supplies(zombie_apocalypse_supplies,other_survivor_supplies) # Hash Drills extinct_animals = { "Tasmanian Tiger" => 1936, "Eastern Hare Wallaby" => 1890, "Dodo" => 1662, "Pyrenean Ibex" => 2000, "Passenger Pigeon" => 1914, "West African Black Rhinoceros" => 2011, "Laysan Crake" => 1923 } # 1. Iterate through extinct_animals hash, printing each key/value pair # with a dash in between the key and value, and an asterisk between each pair. # ---- def print_animals(array) array.each { |key, value| print key.to_s + ' - ' + value.to_s + ' * ' } end print_animals(extinct_animals) # 2. Keep only animals in extinct_animals if they were extinct before # the year 2000. Do not use any special built-in methods. # ---- def only_before_2000(array) before_2000 = {} array.each { |key, value| if value < 2000 before_2000[key] = value end } array = before_2000 end puts only_before_2000(extinct_animals) # 3. Our calculations were completely off, turns out all of those animals went # extinct 3 years before the date provided. Update the values in extinct_animals # so they accurately reflect what year the animal went extinct. # Do not use any special built-in methods. # ---- extinct_animals.each { |key, value| extinct_animals[key] = value - 3 } puts extinct_animals # 4. You've heard that the following animals might be extinct, but you're not sure. # Check if they're included in extinct_animals, one by one: # "Andean Cat" # "Dodo" # "Saiga Antelope" # Do not use any special built-in methods. # ---- animals_to_check = ['Andean Cat','Dodo','Saiga Antelope'] def are_they_extinct(list1,list2) list1.each do |animal| animal_is_extinct = false list2.each { |key, value| if animal == key animal_is_extinct = true break end } if(animal_is_extinct) puts "The " +animal+ " is extinct." else puts "The " +animal+ " is still kickin'." end end end are_they_extinct(animals_to_check,extinct_animals) # 5. We just found out that the Passenger Pigeon is actually not extinct! # Remove them from extinct_animals and return the key value pair as a two item array. # Find the built-in method that helps you accomplish this in the Ruby documentation # for Hashes. # ---- def delete_an_item(item,list) item_to_delete = list.select{|key| key == item} list.delete(item_to_delete) item_to_delete.to_a end puts delete_an_item('Passenger Pigeon',extinct_animals)
true
5adc36eda6cdf6156cba345dddeeb12bd59c1c26
Ruby
Khetti/homework_w2d1
/team/team.rb
UTF-8
1,177
3.421875
3
[]
no_license
class Team attr_accessor :team_name, :players, :coach, :points # constructor def initialize(input_team_name, input_players, input_coach) @team_name = input_team_name @players = input_players @coach = input_coach @points = 0 end # does a methods def add_new_player(new_player) @players << new_player end # i considered a gets.chomp to take input for a player search, # but it would make passing the test awkward so i'm leaving it commented # out for now, thought it would let us test for a false case as well # which isn't possible with this method as it stands def search_for_player # p "Please enter a player name:" # player_search = gets.chomp player_search = "dupreeh" return @players.include?(player_search) end def match_result(result) if result == "win" return @points += 3 end if result == "loss" return @points end end # # getters methods # def get_name # return @team_name # end # # def get_players # return @players # end # # def get_coach # return @coach # end # # # setter methods # def set_coach(new_coach) # @coach = new_coach # end end
true
bcb34d723bb351212f4437ac80c95dfc93115331
Ruby
brendannee/bikesy-server
/rbgs/extension/tiger_gtfs/link_tiger_gtfs_extend.rb
UTF-8
5,389
2.578125
3
[ "BSD-3-Clause" ]
permissive
class Graphserver SEARCH_RANGE = 0.0006 #degrees #returns the next stop id and location each time that is called def each_stop stops = conn.exec "SELECT stop_id, location FROM gtf_stops" stops.each do |stop_id, location| yield stop_id, location end end def nearest_tiger_line( stop_geom, search_range ) lines = conn.exec <<-SQL SELECT id, geom, distance(geom, '#{stop_geom}') AS dist FROM tiger_streets WHERE geom && expand( '#{stop_geom}'::geometry, #{search_range} ) ORDER BY dist LIMIT 1 SQL if lines.num_tuples == 0 then return nil, nil else return lines[0][0..1] end end def split_tiger_line line_geom, stop_geom ret = [] split = conn.exec("SELECT line_locate_point('#{line_geom}', '#{stop_geom}')").getvalue(0, 0).to_f #no need to split the line if the splitpoint is at the end if split == 0 or split == 1 then return nil end ret << conn.exec("SELECT line_substring('#{line_geom}', 0, #{split})").getvalue(0,0) ret << conn.exec("SELECT line_substring('#{line_geom}', #{split}, 1)").getvalue(0,0) return ret; end #tlid : line_id of the record to replace #tlid_l : line_id of the left line #tlid_r : line_id of the right line #tzid : endpoint-id joining the new split line #left : WKB of the lefthand line #right : WKB of he righthand line def split_tiger_line! tlid, tlid_l, tlid_r, tzid, left, right res = conn.exec("SELECT * FROM tiger_streets WHERE id = '#{tlid}'") nid = res.fieldnum( 'id' ) nto_id = res.fieldnum( 'to_id' ) nfrom_id = res.fieldnum( 'from_id' ) ngeom = res.fieldnum( 'geom' ) row = res[0] leftrow = row.dup rightrow = row.dup leftrow[ nid ] = tlid_l leftrow[ nto_id] = tzid leftrow[ ngeom ] = left rightrow[ nid ] = tlid_r rightrow[ nfrom_id ] = tzid rightrow[ ngeom ] = right transaction = ["BEGIN;"] transaction << "DELETE FROM tiger_streets WHERE id = '#{tlid}';" transaction << "INSERT INTO tiger_streets (#{res.fields.join(',')}) VALUES (#{leftrow.map do |x| if x then "'"+x+"'" else '' end end.join(",")});" transaction << "INSERT INTO tiger_streets (#{res.fields.join(',')}) VALUES (#{rightrow.map do |x| if x then "'"+x+"'" else '' end end.join(",")});" transaction << "COMMIT;" conn.exec( transaction.join ) end def split_tiger_lines! i=0 each_stop do |stop_id, stop_geom| i+=1 print "\r#{i}" STDOUT.flush line_id, line_geom = nearest_tiger_line( stop_geom, SEARCH_RANGE ) if line_id then left, right = split_tiger_line( line_geom, stop_geom ) if left then split_tiger_line!( line_id, stop_id+"0", stop_id+"1", stop_id, left, right ) end end end print "\n" end def nearest_street_node stop_geom point, location, dist = conn.exec(<<-SQL)[0] SELECT from_id AS point, StartPoint(geom) AS location, distance_sphere(StartPoint(geom), '#{stop_geom}') AS dist FROM tiger_streets WHERE geom && expand( '#{stop_geom}'::geometry, #{SEARCH_RANGE} ) UNION (SELECT to_id AS point, EndPoint(geom) AS location, distance_sphere(EndPoint(geom), '#{stop_geom}') AS dist FROM tiger_streets WHERE geom && expand( '#{stop_geom}'::geometry, #{SEARCH_RANGE})) ORDER BY dist LIMIT 1 SQL return point, location end def remove_link_table! begin conn.exec "DROP TABLE street_gtfs_links" rescue nil end end def create_link_table! #an extremely simple join table conn.exec <<-SQL create table street_gtfs_links ( stop_id text NOT NULL, node_id text NOT NULL ); select AddGeometryColumn( 'street_gtfs_links', 'geom', #{WGS84_LATLONG_EPSG}, 'LINESTRING', 2 ); SQL end def link_street_gtfs! stops_linked = 0 stops_isolated = 0 each_stop do |stop_id, stop_geom| node_id, location = nearest_street_node( stop_geom ) if node_id geom_wkt = "MakeLine('#{stop_geom}', '#{location}')" conn.exec "INSERT INTO street_gtfs_links (stop_id, node_id, geom) VALUES ('#{stop_id}', '#{node_id}', #{geom_wkt})" puts "Linked stop #{stop_id}" stops_linked += 1 else puts "Didn't find a node close to the stop #{stop_id}" stops_isolated += 1 end end #Vacuum analyze table conn.exec "VACUUM ANALYZE street_gtfs_links" #Report linked stops puts "Linked #{stops_linked}." puts "Remaining #{stops_isolated} without link." end def load_tiger_gtfs_links res = conn.exec "SELECT stop_id, node_id, AsText(geom), AsText(Reverse(geom)) FROM street_gtfs_links" res.each do |stop_id, node_id, coords, rcoords| #In KML LineStrings have the spaces and the comas swapped with respect to postgis #We just substitute a space for a comma and viceversa coords.gsub!(/[ ,()A-Z]/) {|s| if (s==' ') then ',' else if (s==',') then ' ' end end} rcoords.gsub!(/[ ,()A-Z]/) {|s| if (s==' ') then ',' else if (s==',') then ' ' end end} @gg.add_edge_geom( GTFS_PREFIX+stop_id, TIGER_PREFIX+node_id, Link.new, coords ) @gg.add_edge_geom( TIGER_PREFIX+node_id, GTFS_PREFIX+stop_id, Link.new, rcoords ) end end end
true
39642abff4884348750c9c7af5db8207c40375cc
Ruby
Aryk/dead_simple_cms
/lib/dead_simple_cms/attribute/type/base.rb
UTF-8
2,819
2.640625
3
[ "MIT" ]
permissive
module DeadSimpleCMS module Attribute module Type class Base include Util::Identifier class << self # Public: the method name used to identify this type in the Builder attr_writer :builder_method_name # If not provided on the subclass infer it from the class name. Because of how class_attribute works, this # method will be overwritten when someone explicitly calls .builder_method_name= on a subclass. def builder_method_name @builder_method_name ||= name.demodulize.underscore end end # Public: a Symbol representing the default input type required for forms class_attribute :default_input_type, :instance_writer => false VALID_INPUT_TYPES = [:string, :text, :select, :file, :radio, :datetime, :check_box].freeze attr_reader :input_type, :group_hierarchy, :required attr_accessor :section def initialize(identifier, options={}) options.reverse_merge!(:group_hierarchy => [], :input_type => default_input_type, :required => false) @hint, @default, @input_type, @group_hierarchy, @section, @required, @length = options.values_at(:hint, :default, :input_type, :group_hierarchy, :section, :required, :length) raise("Invalid input type: #{input_type.inspect}. Should be one of #{VALID_INPUT_TYPES}.") unless VALID_INPUT_TYPES.include?(input_type) super end def root_group? group_hierarchy.last.try(:root?) end # Public: The identifier on the section level. It must be unique amongst the groups. def section_identifier (group_hierarchy + [self]).map(&:identifier).join("_").to_sym end def hint @hint.is_a?(Proc) ? @hint.call : @hint end def length @length.is_a?(Proc) ? @length.call : @length end def default @default.is_a?(Proc) ? @default.call : @default end def value=(value) attributes_from_storage[section_identifier] = convert_value(value) end # Public: Returns the non-blank value from the storage or the default. def value attributes = attributes_from_storage attributes.key?(section_identifier) ? attributes[section_identifier] : default end def inspect ivars = [:identifier, :hint, :default, :required, :input_type].map { |m| ivar = "@#{m}" ; "#{ivar}=#{instance_variable_get(ivar).inspect}" } "#<#{self.class} #{ivars.join(", ")}" end private def attributes_from_storage section.storage.read end def convert_value(value) value.presence end end end end end
true
9f46ad44d802f095a5cc0dde688a1dbb9bbf6fec
Ruby
TominagaRyuto/ruby
/lesson7-2.rb
UTF-8
400
3.65625
4
[]
no_license
p "計算を始めます" p "何回計算を繰り返しますか" kaisuu = gets.to_i x = 1 while x <= kaisuu do p "#{x}回目の計算" p "2つの値を入力して下さい" a = gets.to_i b = gets.to_i p "a=#{a}" p "b=#{b}" p "計算結果を出力します" p "a+b=#{a + b}" p "a-b=#{a - b}" p "a*b=#{a * b}" p "a/b=#{a / b}" x += 1 end p "計算を終了します"
true
711748cf8bc45433a5d36cbdb806a6eea3e95d8d
Ruby
jeffreyguenther/olympics
/app/models/import/athlete_with_records.rb
UTF-8
584
2.6875
3
[]
no_license
class Import::AthleteWithRecords def initialize(athlete, records = {}) @athlete = athlete @records = records end delegate :id, to: :@athlete def opening_weight(meet_type, movement) current_max = @records[movement] if current_max.blank? || current_max <= 0 meet_type.opening_weight_for(movement) else current_max - 10 end end def update_records_for(movement, performance_max) current_max = @records[movement] if current_max.blank? || current_max < performance_max @records[movement] = performance_max end end end
true
b990e2ef6b2814a18455c490623742e23a0f8dc6
Ruby
mpletcher/phase-0-tracks
/ruby/hashes.rb
UTF-8
3,185
4.625
5
[]
no_license
=begin 5.2 Arrays and Hashes Author: Marcos Pletcher -------------Pseudocode ----------------- Prompt the user for his/her name, age, number of children, decor theme, If user inputs unvalid data, re-promt the user Convert any user input to the appropriate data type Prompt the user if any information needs to be changed Prompt the user to enter the new value Otherwise, print last information =end # Greetings def greet(say_something_dependening_on_time) if say_something_dependening_on_time >= 00 && say_something_dependening_on_time <= 11 puts "Good Morning. Welcome to your Decor Assistant!\n" elsif say_something_dependening_on_time >= 12 && say_something_dependening_on_time <= 16 puts "Good Afternoon. Welcome to your Decor Assistant!\n" elsif say_something_dependening_on_time >= 17 && say_something_dependening_on_time <= 20 puts "Good Evening. Welcome to your Decor Assistant!\n" else puts "Good Night. Welcome to your Decor Assistant!\n" end end # call greetings greet(Time.new.hour) # Prompt the user to enter his/her name puts "Let me know please what is your name?" name = gets.chomp.capitalize # Prompt the user to enter the following information # Convert any user input to the appropriate data type. puts "How old are you?" age = gets.chomp.to_i # Convert any user input to the appropriate data type. puts "How may children do you have?" number_children = gets.chomp.to_i puts "What kind of theme would you like to use?" decor_theme = gets.chomp.capitalize # Create hash client_information = { name: "#{name}", age: age, number_children: number_children, decor_theme: "#{decor_theme}" } # Shows up the information puts "\nYour informartion:" puts "Name: #{client_information[:name]}" puts "Age: #{client_information[:age]}" puts "Number of Children: #{client_information[:number_children]}" puts "Decor Theme: #{client_information[:decor_theme]}" # Prompt the user if any information needs to be changed puts "\nIf you need to update any information you have entered, type the respective field you want to be changed (for example name, age, decor theme, the number of children). Otherwise, enter exit" # Prompt the user to enter the new value value = gets.chomp # If condition elaluates entered value and re-prompts user for entering correct data if value == "name" puts "Please enter your correct name:" client_information[:name] = gets.chomp.capitalize elsif value == "age" puts "Please enter your correct age:" client_information[:age] = gets.chomp.to_i elsif value == "decor theme" || value == "decor" || value == "theme" puts "Please enter your correct decor theme:" client_information[:decor_theme]= gets.chomp.capitalize elsif value == "number children" || value == "children" puts "Please enter your correct number of children:" client_information[:number_children]= gets.chomp.to_i else value == "exit" || value == "Exit" end # Shows up updated information puts "\nYour updated informartion:" puts "Name: #{client_information[:name]}" puts "Age: #{client_information[:age]}" puts "Number of Children: #{client_information[:number_children]}" puts "Decor Theme: #{client_information[:decor_theme]}"
true
a883b6cf8047fb0e4f4a21c742e596a6f017317a
Ruby
mlibrary/heliotrope
/app/services/json_web_token.rb
UTF-8
1,279
2.78125
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true module JsonWebToken # secret to encode and decode token HMAC_SECRET = Rails.application.secrets.secret_key_base # https://github.com/jwt/ruby-jwt # # JSON Web Token defines some reserved claim names # and defines how they should be used. # # JWT supports these reserved claim names: # # 'exp' (Expiration Time) Claim # 'nbf' (Not Before Time) Claim # 'iss' (Issuer) Claim # 'aud' (Audience) Claim # 'jti' (JWT ID) Claim # 'iat' (Issued At) Claim # 'sub' (Subject) Claim # # Ruby-jwt gem supports custom header fields # To add custom header fields you need to pass header_fields parameter # # expires = Time.now.to_i # payload = { data: 'test', exp: expires } # # token = JWT.encode payload, HMAC_SECRET, algorithm='HS256', header_fields={ typ: 'JWT' } # # leeway = 30 # seconds # # puts JWT.decode token, hmac_secret, true, { exp_leeway: leeway, algorithm: 'HS256' } # # [ # {"data"=>"test", "exp"=>expires }, # payload # {"typ"=>"JWT", "alg"=>"HS256" } # header # ] def self.encode(payload) JWT.encode(payload, HMAC_SECRET, 'HS256') end def self.decode(token) HashWithIndifferentAccess.new JWT.decode(token, HMAC_SECRET, true, algorithm: 'HS256')[0] end end
true
24be153304d7b0050db3c8dd70aacf61ac1f789d
Ruby
aliasmac/ruby-collaborating-objects-lab-london-web-082718
/lib/song.rb
UTF-8
353
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist @@all = [] def initialize(name) @name = name @@all << self end def artist_name=(artist_name) self.artist.name = artist_name end def self.new_by_filename(filename) song_name = filename.split(" - ") song = self.new(song_name[1]) # song.artist = song_name[0] end end
true
c89305df6303c655bfa85309b161462cded6d109
Ruby
abuisman/tukey
/lib/tukey/data_set/label.rb
UTF-8
824
2.96875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'ostruct' class DataSet class Label attr_accessor :id attr_accessor :name attr_accessor :meta def initialize(name, id: nil, meta: {}) @name = name @id = id || name raise ArgumentError, 'DataSet::Label meta must be a Hash' unless meta.is_a?(Hash) @meta = OpenStruct.new(meta) end # == is used for comparison of two instances directly def ==(other) other.id == id end # eql? and hash are both used for comparisons when you # call `.uniq` on an array of labels. def eql?(other) self == other end def hash id.hash end def deep_dup label = dup self.id = id.dup if id self.name = name.dup if name self.meta = meta.dup if meta label end end end
true
cc68ff86ccbeb6312e96dde6849abcf672f63c4d
Ruby
jmansor/mars_rover
/lib/mars_rover/rover_controller.rb
UTF-8
420
2.90625
3
[ "MIT" ]
permissive
module MarsRover class RoverController def move(current_position) orientation = current_position.orientation new_position = current_position.clone case orientation when 'N' new_position.y +=1 when 'S' new_position.y -=1 when 'W' new_position.x -=1 when 'E' new_position.x +=1 end new_position end end end
true
e9da9630e0e83691c929bd7e7887dbd63f512339
Ruby
eregon/project_euler
/065.rb
UTF-8
1,127
3.71875
4
[]
no_license
=begin The square root of 2 can be written as an infinite continued fraction. The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)]. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for √2. Hence the sequence of the first ten convergents for √2 are: 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ... What is most surprising is that the important mathematical constant, e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...]. The first ten terms in the sequence of convergents for e are: 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ... The sum of digits in the numerator of the 10^(th) convergent is 1+4+5+7=17. Find the sum of digits in the numerator of the 100^(th) convergent of the continued fraction for e. =end require_relative 'lib' p Math.continued_fraction([2] + ((100-1)/3).times.map { |i| [1,2*(i+1),1] }.reduce(:+)).numerator.digits.reduce(:+) # => 272
true
af5b2b44755cb41aa1751df25c9a70afe66f34aa
Ruby
vgvinay2/ruby_programme
/thread/program-1.rb
UTF-8
2,156
4.65625
5
[]
no_license
def calculate_sum(arr) sum = 0 arr.each do |item| sum += item end sum end @items1 = [12, 34, 55] @items2 = [45, 90, 2] @items3 = [99, 22, 31] puts "items1 = #{calculate_sum(@items1)}" puts "items2 = #{calculate_sum(@items2)}" puts "items3 = #{calculate_sum(@items3)}" ## The output of the above program would be items1 = 101 items2 = 137 items3 = 152 ## This is a very simple program that will help in # understanding why we should use threads. # In the above code listing, we have 3 arrays and # are calculating their sum. # All of this is pretty straightforward stuff. # However, there is a problem. We cannot get the sum # of the items2 array unless we have received the items1 result. # It’s the same issue for items3. Let’s change the code a bit to show what I mean. def calculate_sum(arr) sleep(2) sum = 0 arr.each do |item| sum += item end sum end # In the above code listing we have added a sleep(2) instruction which # will pause execution for 2 seconds and then continue. # This means items1 will get a sum after 2 seconds, items2 after 4 seconds (2 for items1 # + 2 seconds for items2) and items3 will get sum after 6 seconds. This is not what we want. # Our items arrays don’t depend upon each other, so it would be ideal to have their sums # calculated independently. This is where threads come in handy. # Threads allow us to move different parts of our program into different execution contexts # which can execute independently. Let’s write a threaded/multithreaded version of the above program: def calculate_sum(arr) sleep(2) sum = 0 arr.each do |item| sum += item end sum end @items1 = [12, 34, 55] @items2 = [45, 90, 2] @items3 = [99, 22, 31] threads = (1..3).map do |i| Thread.new(i) do |i| items = instance_variable_get("@items#{i}") puts "items#{i} = #{calculate_sum(items)}" end end threads.each {|t| t.join} ## If you run the above code sample, you might see the following # output (I use might because your output might be different in terms of items arrays sum sequence) items2 = 137 items3 = 152 items1 = 101 ## http://www.sitepoint.com/threads-ruby/
true
53fec716a2c45e7afb3210bcfae7f75cf6508d96
Ruby
gpatuwo/chess
/board.rb
UTF-8
2,129
3.578125
4
[]
no_license
require_relative "pieces" require 'colorize' class Board #1. make grid 2.populate grid 3. moves pieces (if valid move from Pieces) 4. game over? # def self.populate_board(board) # # create all the different pieces # # place the 16 pieces on each side # # place nil in remaining pos # end attr_accessor :grid def initialize(fill_board = true) @sentinel = NullPiece.instance.to_s make_starting_grid(fill_board) # Board.populate_board(@grid) end def [](pos) x, y = pos @grid[x][y] end def []=(pos, value) x, y = pos @grid[x][y] = value end def add_piece(piece, pos) end def checkmate?(color) end def dup end def empty?(pos) end def in_check?(color) end def move_piece(turn_color, start_pos, end_pos) # raise if start_pos.empty? # raise if end_pos is invalid move # else #delete the piece at board[start_pos] # board[end_pos] = piece end def move_piece!(from_pos, to_pos) end def pieces end def valid_pos?(pos) end protected def fill_back_row(color) row_num = color == :white ? 0 : 7 @grid[row_num] = [Rook.new(color, self, [row_num, 0]).to_s, Knight.new(color, self, [row_num, 1]).to_s, Bishop.new(color, self, [row_num, 2]).to_s, Queen.new(color, self, [row_num, 3]).to_s, King.new(color, self, [row_num, 4]).to_s, Bishop.new(color, self, [row_num, 5]).to_s, Knight.new(color, self, [row_num, 6]).to_s, Rook.new(color, self, [row_num, 7]).to_s] end def fill_pawns_row(color) row_num = color == :white ? 1 : 6 @grid[row_num].map!.with_index { |square, idx| square = Pawn.new(color, self, [row_num, idx]).to_s } end def find_king(color) end def make_starting_grid(fill_board) if fill_board @grid = Array.new(8) { Array.new(8) { @sentinel } } fill_back_row(:white) fill_pawns_row(:white) fill_back_row(:black) fill_pawns_row(:black) end end private attr_reader :sentinel end
true
aba8870be7c1e6eb8d77968d7d277e9601afc355
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/robot-name/3f42d76fca02419bae249d5fb709b58f.rb
UTF-8
231
3.28125
3
[]
no_license
class Robot def initialize @name = random_name end def name @name end def reset @name = random_name end def random_name ('A'..'Z').to_a.shuffle[0..1].join + (0..9).to_a.shuffle[0..2].join end end
true
24d091c497f11e0fb3583ba3bfb7712e81fdc2bd
Ruby
kellyarwine/iterator_example
/spec/vegetable_iterator_spec.rb
UTF-8
1,874
2.984375
3
[]
no_license
require 'vegetable_iterator' describe VegetableIterator do context "next" do before(:all) do vegetable_hash = {"Carrot" => "Fresh", "Red Bell Pepper" => "Expired", "Celery" => "Fresh"} @vegetable_iterator = VegetableIterator.new(vegetable_hash) end it "returns the next vegetable" do @vegetable_iterator.next.should == "Carrot" end it "returns the next vegetable" do @vegetable_iterator.next.should == "Red Bell Pepper" end end context "has_next" do before(:each) do vegetable_hash = {"Carrot" => "Fresh", "Red Bell Pepper" => "Expired", "Celery" => "Fresh"} @vegetable_iterator = VegetableIterator.new(vegetable_hash) end it "returns true when another element exists" do @vegetable_iterator.has_next.should == true @vegetable_iterator.next end it "returns true after next is called and the index is at the second position in the list" do @vegetable_iterator.next @vegetable_iterator.has_next.should == true end it "returns true after next is called twice and the index is at the third position in the list" do @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.has_next.should == true end it "returns false after next is called 3 times and the index is at the end of the list" do @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.has_next.should == false end it "returns false after next is called 4 times and the index is one past the end of the list" do @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.next @vegetable_iterator.has_next.should == false end end end
true
aa5d26b5bccffeb04006f766c26963ab5cf6b671
Ruby
Hpanora101/badges-and-schedules-online-web-pt-021119
/conference_badges.rb
UTF-8
481
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) return "Hello, my name is #{name}." end def batch_badge_creator(name) name.collect do |name| badge_maker(name) end end def assign_rooms(speakers) speakers.collect.each_with_index do |speaker, index| "Hello, #{speaker}! You'll be assigned to room #{index+1}!" end end def printer(speakers) batch_badge_creator(speakers). each do |speakers| puts speakers end assign_rooms(speakers).each do |speakers| puts speakers end end
true
2251869ebafab9e4e489d1fc011a09c60b2a332d
Ruby
eegrok/cleanify-epub
/lib/mapping.rb
UTF-8
5,101
2.640625
3
[]
no_license
require 'crypt' module Mapping extend self @@mappings = nil @@phrases = nil @@substring_phrases = nil # if the value is an array, then it's one we want to display when we replace (we'll display them all if we do verbose) # if it's not an array, we don't display it MAPPINGS = {'9768634b51ca38a98892c7086c9e3122' => ['doh', 'dangit', 'arrrggghhh'], '3f6c82c5640cbdb903ebffb536501e1b' => ['doh', 'dangit', 'arrrggghhh'], '77505a312e14133e2813677b42177e12' => ['doh', 'dangit', 'arrrggghhh'], 'de5ed538c7552a471ba1e69271af4e00' => ['doh', 'dangit', 'arrrggghhh'], '4a1387bafcfa3d3ebc29334e82f47d56' => ['loser', 'dork'], 'd6c79ee62074da77e988a7bca45017d9' => ['loser', 'dork'], '278139c2481ec87e71a4f421bdcaa7b9' => ['loser', 'dork'], 'cdf9360e37b1cea42eb3debfb91eec80' => ['loser', 'dork'], 'ede96167c49f2e8906c93567aa545aeb' => ['loser', 'dork'], '728bb4d112e685a8375336b0a228420b' => ['loser', 'dork'], 'f087d92fccba7cc5bf6e861dcf1d6773' => ['loser', 'dork'], '9ee708dd59ac58a35b4944cfa4cbed72' => ['loser', 'dork'], '95d28fed6cbc7f15f3a2419f8cbaf8bd' => "you're", '157be2f48759e163aca91e020174524b' => ['why not'], 'e60f02c41899c86e363f07ee147b6ac14f943e4f2cd619d546024f6a80f110cf' => ['you little'], 'f0cdf21ec6fbe6adfdfafc923cda98775ad0ff1c699ee33a5e5e1e0ae5d1f456' => ['eat them alive'], '957e057203245895f4f96e87e8cc9b3f43ee808bbd69858fdd0e63a2ccf140c4' => ['little bugger'], '81aefe89f51f77c4d161210b4fd4b1598f9d14042b17c10ec036a15f02977f46' => ['give me that'], '0d8a78dfe14e8666052176c8a941f1fa' => [','], 'ad4f47b31819d1b76e7ae7396cd67c94' => ['definitely'], '8e7f8eec77c0d110cc4a5af52e161c70' => ['go away'], '55e30a5bf531973037ae995d8f63f42d' => ['an idiot'], 'dcc1fa1c57f1df8ac17bb0f75c227a57' => ['mean person'], '47702b6eeaf339618807fb3ab165541e6a4492e953ebaf5c11b6c31a8609f890' => ['what to do'], 'c2482e6864f36962f9df51d290df8694' => ['really sure'], 'e61a511065e184efff52977a0a65dfb7ed7e2d01c1c4a652281a324132493d7a' => ['forget both of you'], '4eb98f87b53597c9ca65ac7f0733079d' => ['forget'], '47f2dfa2d66a40b571c66c2b4cf6a223' => ['definitely'], '7f25fa4c30a14f5db76ac877cb05b462' => ['messed up'], '22c2d858affd21075c7927d662d56529' => ['pain'], 'c6df290bf32413fb1957e138307b50f2' => ['no way'], '7bc51426dd87a8d9d55a1f9c7d77c79c' => ['beat you'], '90d5b6f40c2c2a3706e1c313b5a502a0' => ['near'], 'e88cc97da7881d263fa44e117ce3e4df' => [''], 'e4c775cf415cafbd3ebca958b7b32b45' => [''], '68c8f065a40d3fee03417f0ceb975908' => [''], 'f033bfcf308ae3f403a0812dbd5331fc' => [''], '7199f0e717ad3498d0c2ab70f9b186e3' => [''], 'f1760270cd808b6eb68459db4f305ee2' => [''], '476878ea14a4f9c0a0b9f25363ea6964' => [''], '3b7441fc643c17e7c1d22a287f877922' => [''], '1542d292740aee9182b5983181df9652' => [''], '7942755c29011b26a76790c462358d0c' => [''], 'a8431510c5f0fa2615f0cd4cccb13fa3' => [''], '6c384c9397b090abaed9a66f6f07d764' => [''], '906b71dcdcbb150699cb5408020e5c93' => [''], '71de4cc0b94aa632d4eab6375593c8f4' => [''], 'a8ef723d88f92662756cb4f666c790ac' => [''], '199885631d29ef5963e3a2bc473d0e60' => [''], 'ef50d8e9b1aa37150942f3fa27948bc9' => [''], '0566b1418d3d8dc155c74d983ec488f8' => [''], '0493697a9e8d46fd620e36fcd8b9fefb' => [''], '7517f66f4a9572c797577666d4e34a87' => [''], '1ad240f1a5d52fbc7be38f0a24e6b0d4' => [''], '8c186b24706636cdd9ed3bf946361c2e' => ['sitcom'], '8d2951a28a7049bd27733bbbc7c14e65' => [''], '922e92d7f53a19a4f1f6f9d040345946' => [''], '0fe4af2c8193a972f99d5e559e53cc93' => [''], '3b9d8438661cd96690bae8bfce47d02c' => ['asap'], '3876ecafc08cf20d2d441370b3330a13' => [''], '670882ba0c36f270cb613cb88b59c4b5' => [''], '9424317a185e71ccbb3a65f997656d9e' => [''], # DYNAMICALLY INSERT RIGHT BEFORE THIS LINE } WHITELIST = %w(assess class password assist assault assume passenger passage grass shell assign assumption assemble overpass massive embarrassing passed pass rachelle glass brass eyeglasses audiocassette cassette cassettes classic reassure hassled encompassed embarrassment sunglasses mass passing amass massively embarrassed assure reassurance embarrassing classes bypassed passive chassis masses hassles surpassing gods goddess godlike rechristened mechagodzilla cockpit moorcock cocky cocktail cockroaches godzilla hello christmas dickens christopher christian).freeze def get_regex(phrase) opens_non_word = phrase =~ /^\W/ ends_non_word = phrase =~ /\W$/ phrase = phrase.gsub(',', '[\s]*,[\s]*') phrase.gsub!(' ', '[\s\,\-\!-.]+') open_optional = opens_non_word ? '?' : '' end_optional = ends_non_word ? '?' : '' /(\W)#{open_optional}(#{phrase})(\W)#{end_optional}/i end def get_phrases return @@phrases if @@phrases @@phrases = MAPPINGS.collect do |key, value| [Crypt.decrypt(key), value] end @@phrases.sort! do |elem1, elem2| elem1[0].length <=> elem2[0].length end @@phrases end def get_substring_phrases return @@substring_phrases if @@substring_phrases @@substring_phrases = get_phrases.dup @@substring_phrases.collect! do |phrase, _replacement| [phrase, /\W?(\w*#{phrase}\w*)\W?/i] end end def get_mappings return @@mappings if @@mappings @@mappings = get_phrases.reverse @@mappings.collect! do |key, value| [get_regex(key), value] end @@mappings end def mapping_filename File.join(Doh.root, 'lib', 'mapping.rb') end def read_mapping_file File.readlines(mapping_filename) end def dynamic_insert_line(lines) lines.find_index {|line| line =~ /DYNAMICALLY INSERT RIGHT BEFORE THIS LINE/} end def write_mapping_file(lines) outf = File.new(mapping_filename, 'w+') lines.each do |line| outf << line end outf.close end end # make sure we match # your butt is to: # your, butt, is # your - butt, is
true
61dc91c04de4f05ea2b0c2d85f0453b9f6ccdc60
Ruby
PhilHuangSW/Leetcode
/valid_parentheses.rb
UTF-8
2,403
4.46875
4
[]
no_license
#################### VALID PARENTHESES #################### # Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', # determine if the input string is valid. # An input string is valid if: # Open brackets must be closed by the same type of brackets. # Open brackets must be closed in the correct order. # Example 1: # Input: s = "()" # Output: true # Example 2: # Input: s = "()[]{}" # Output: true # Example 3: # Input: s = "(]" # Output: false # Example 4: # Input: s = "([)]" # Output: false # Example 5: # Input: s = "{[]}" # Output: true # Constraints: # - 1 <= s.length <= 104 # - s consists of parentheses only '()[]{}'. #################### SOLUTION #################### # @param {String} s # @return {Boolean} # Using stacks and hashes # TIME: O(n) -- SPACE: O(n) def is_valid(s) # solution must be even length, otherwise there's a missing # closing/opening parenthesis somewhere return false if (s.length)%2 == 1 h = Hash.new{|h,right| h[right] = 0} valid_stack = [] for i in 0...s.length if s[i] == '(' valid_stack << s[i] h[')'] += 1 end if s[i] == '{' valid_stack << s[i] h['}'] += 1 end if s[i] == '[' valid_stack << s[i] h[']'] += 1 end if s[i] == ')' if h.has_key?(s[i]) && h[s[i]] != 0 if valid_stack.pop != '(' return false end h[s[i]] -= 1 else return false end end if s[i] == '}' if h.has_key?(s[i]) && h[s[i]] != 0 if valid_stack.pop != '{' return false end h[s[i]] -= 1 else return false end end if s[i] == ']' if h.has_key?(s[i]) && h[s[i]] != 0 if valid_stack.pop != '[' return false end h[s[i]] -= 1 else return false end end end valid_stack.empty? end s1 = "()" s2 = "()[]{}" s3 = "(]" s4 = "([)]" s5 = "{[()]}" s6 = "{{" s7 = "{{(([]))}}" s8 = "([()})" puts "Expected: true -- Actual: #{is_valid(s1)}" puts "Expected: true -- Actual: #{is_valid(s2)}" puts "Expected: false -- Actual: #{is_valid(s3)}" puts "Expected: false -- Actual: #{is_valid(s4)}" puts "Expected: true -- Actual: #{is_valid(s5)}" puts "Expected: false -- Actual: #{is_valid(s6)}" puts "Expected: true -- Actual: #{is_valid(s7)}" puts "Expected: false -- Actual: #{is_valid(s8)}"
true
3e6f5e48cc7523e3dbdd5d0986386d15e1bff45c
Ruby
NurfitraPujo/cli-turnbased-game
/lib/CharacterFactory.rb
UTF-8
574
3
3
[ "MIT" ]
permissive
require_relative './Character' require_relative './Hero' require_relative './Soldier/Archer' require_relative './Soldier/Spearman' require_relative './Soldier/Swordsman' def create_char(name, hit_point, attack_dmg, options = {}) return Hero.new(name, hit_point, attack_dmg) if options[:is_hero] return Archer.new(name, hit_point, attack_dmg) if options[:is_archer] return Swordsman.new(name, hit_point, attack_dmg) if options[:is_swordsman] return Spearman.new(name, hit_point, attack_dmg) if options[:is_spearman] Character.new(name, hit_point, attack_dmg) end
true
1b5ad16347461a6f712d7bad58d2d741548f378f
Ruby
xaviershay/dominion-solitaire
/lib/dominion/ui/ncurses/window.rb
UTF-8
693
2.6875
3
[]
no_license
module Dominion::UI::NCurses class Window include FFI::NCurses attr_accessor :window, :game def initialize(game) self.game = game end def print(color, text, bold = false) color_index = colors[color] || raise("Unknown color: #{color}") wattr_set window, bold ? A_BOLD : A_NORMAL, color_index, nil waddstr(window, text.to_s) end def colors { :white => 0, :yellow => 3, :blue => 4, :red => 1, :cyan_back => 14, :green_back => 10, :magenta_back => 13, :yellow_back => 11 } end def border true end end end
true
20cd698f2b4769a5322a2cd474307265173015b1
Ruby
jobberslayer/Prayer-Journal
/app/models/prayer_request.rb
UTF-8
3,437
2.578125
3
[]
no_license
require 'lib/myconfig' class PrayerRequest < ActiveRecord::Base has_many :prayer_updates validates_presence_of :title, :request def belongs_to_user?(user_id) super_user_id = get_super_user_id() return (self.user_id == user_id or user_id == super_user_id) end def can_be_viewed?(user_id) if user_id if @super_user_id == user_id return true elsif self.private >= 1 or self.user_id == user_id return true else return false end elsif self.private >=2 return true else return false end end def find_all_viewable(user_id, page=1, limit=10, search=nil, answered=nil) conditions = [] parameters = [] conds, params = get_security_conditions(user_id) conditions.push(conds) if !conds.nil? parameters.push(params) if !params.nil? if !search.nil? && search.strip != '' search_pattern = search.sub(/\s{1,}/, '%') conditions.push('(request like ? or title like? or user_name like ? or pu.message like ?)') parameters.push("\%#{search_pattern}\%") parameters.push("\%#{search_pattern}\%") parameters.push("\%#{search_pattern}\%") parameters.push("\%#{search_pattern}\%") end if answered.nil? elsif answered conditions.push("(answered = 't')") else conditions.push("(answered = 'f' or answered is null)") end conditions = build_conditions(conditions, parameters) #raise Array.pretty_print(conditions) join = nil if (!search.nil? && search.strip != '') join = 'LEFT JOIN prayer_updates pu on pu.prayer_request_id = prayer_requests.id' end PrayerRequest.paginate(:all, :conditions => conditions, :joins => join, :order => ["prayer_requests.created_at DESC, title"], :per_page => limit, :page => page) end def random(user_id) ids = find_all_viewable(user_id, nil, nil, nil, false) if ids.blank? return nil else return PrayerRequest.find(ids[rand(ids.length)]["id"].to_i) unless ids.blank? end end def find_id_viewable(user_id, id) conditions = [] parameters = [] conds, params = get_security_conditions(user_id) conditions.push(conds) if !conds.nil? parameters.concat(params) if !params.nil? conditions = build_conditions(conditions, parameters) #raise Array.pretty_print(conditions) if (conditions.length == 0) PrayerRequest.find(id) else PrayerRequest.find(id, :conditions => conditions) end end def get_security_conditions(user_id) super_user_id = get_super_user_id() if (user_id) if (super_user_id == user_id) return nil, nil else return "(private >= 1 or user_id = ?)", [user_id] end else return "private >= 2", nil end end def build_conditions(conditions, parameters) conditionStr = conditions.join(' and ') conditions = [] conditions.push(conditionStr) if !conditionStr.empty? conditions.concat(parameters) return conditions end def get_super_user_id myconfig = Myconfig.instance return myconfig.super_user_id end def private_text return private_to_s(private) end def private_to_s(level) case level when 0 then 'private' when 1 then 'protected' when 2 then 'public' else 'invalid' end end end
true
518ec2cc4b999aeb76b9f30ea6192891d586081b
Ruby
nxdf2015/odin-serialization
/event_manager/lib/event_manager.rb
UTF-8
1,203
3.03125
3
[]
no_license
require "csv" require 'sunlight/congress' require "erb" Sunlight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5" content =CSV.open "event_attendees.csv" , headers: true ,header_converters: :symbol def clean_zip_code(zipcode) zipcode.to_s.rjust(5,"0")[0..4] end def clear_phone(phone) phone = phone.gsub(/\(|\)|-|\.|\s|\+|e/i,"").strip phone = "" unless phone.length == 10 || (phone.length == 11 && phone[0] ==1 ) phone = phone[1..-1] if phone.length == 11 && phone[0] == 1 phone end def legislator_by_zip_code(zipcode) Sunlight::Congress::Legislator.by_zipcode(zipcode) #egislators.collect do |legislator| end def save_thank_you_letter(id,form_letter) Dir.mkdir("output") unless Dir.exist? "output" filename = "output/thanks_#{id}" open(filename,"w")do |f| f.puts form_letter end end puts "EventManager Initialized!" template_letter = File.read "form_letter.erb" erb_template = ERB.new template_letter content.each do |row| id = row[0] name = row[:first_name] zip = clean_zip_code( row[:zipcode] ) phone = clear_phone(row[:homephone]) legislators = legislator_by_zip_code(zip) form_letter = erb_template.result(binding) save_thank_you_letter(id,form_letter) end
true
2f6effc852d2eb76a06079ea0dac906243844a4f
Ruby
Tkam13/atcoder-problems
/abc169/d.rb
UTF-8
179
2.875
3
[]
no_license
n = gets.to_i require 'prime' factor = Prime.prime_division(n) ans = 0 factor.each do |_,i| cnt = 0 while cnt * (cnt + 1) <= 2 * i cnt += 1 end ans += cnt - 1 end puts ans
true
0f9c5a8ada5c8ad334c659cc8ae94849ffa7f6c9
Ruby
jparkSF/algorithms
/jiwoo_park_heap/lib/heap.rb
UTF-8
2,326
3.5
4
[]
no_license
class BinaryMinHeap attr_reader :store, :prc def initialize(&prc) @store = [] @count = 0 @prc = prc ? prc : Proc.new {|el1, el2| el1 <=> el2} # @prc = prc end def count @count end def extract val = @store[0] @store[0], @store[@store.length-1] = @store[@store.length-1], @store[0] @store.delete(@store[@store.length-1]) BinaryMinHeap.heapify_down(@store, 0) val end def peek end def push(val) @store.push(val) BinaryMinHeap.heapify_up(@store, @store.length-1) end public def self.child_indices(len, parent_index) left_child = (parent_index * 2) + 1 right_child = (parent_index * 2) + 2 if left_child < len && right_child < len return [left_child,right_child] elsif left_child < len && right_child >= len return [left_child] else [] end end def self.parent_index(child_index) raise "root has no parent" if child_index == 0 return (child_index - 1) / 2 end def self.heapify_down(array, parent_idx, len = array.length, &prc) prc = prc ? prc : Proc.new {|el1, el2| el1 <=> el2} swapped = true while swapped children = BinaryMinHeap.child_indices(len,parent_idx) swapped = false children.each_with_index do |child_idx, other_idx| other_child_idx = other_idx == 0? 1: 0 if prc.call(array[parent_idx],array[child_idx]) == 1 && children.length == 1 || prc.call(array[parent_idx],array[child_idx]) == 1 && prc.call(array[child_idx], array[children[other_child_idx]]) == -1 temp = array[parent_idx] array[parent_idx] = array[child_idx] array[child_idx] = temp parent_idx = child_idx swapped = true break end end end array end def self.heapify_up(array, child_idx, len = array.length, &prc) prc = prc ? prc : Proc.new {|el1, el2| el1 <=> el2} swapped = true while swapped && child_idx != 0 swapped = false parent_idx = BinaryMinHeap.parent_index(child_idx) if prc.call(array[parent_idx], array[child_idx]) == 1 temp = array[parent_idx] array[parent_idx] = array[child_idx] array[child_idx] = temp child_idx = parent_idx swapped = true end end array end end
true
5be06827aa4e91cf99681dec10ee0a761adaae44
Ruby
Slaan/seic
/lib/tracks_deserializer_mark.rb
UTF-8
420
2.625
3
[]
no_license
class TracksDeserializerMark def self.deserialize(track) Track.build_from_hash("name" => track["track_name"], "description" => track["track_description"], "keywords" => track["track_keywords"], "waypoints" => track["track_geojson"]) end def self.deserialize_all(tracks) tracks.reduce([]) do |accu, track| accu << self.deserialize(track) end end end
true
98288bf7b18bb973cd4dab46c0860a7d9149b2f3
Ruby
ysawa/sengine
/app/models/hand.rb
UTF-8
2,373
3.765625
4
[]
no_license
# -*- coding: utf-8 -*- class Hand # Hand means the numbers of pieces in hands of players KEY_NAMES = %w(fu ky ke gi ki ka hi ou) attr_reader *KEY_NAMES def to_a [nil, @fu, @ky, @ke, @gi, @ki, @ka, @hi, @ou] end def generate_name(key) case key when 0 nil when Integer KEY_NAMES[key - 1] else key.to_s end end def initialize(*objects) if objects[1] import_from_array(objects) else object = objects[0] case object when Array import_from_array(object) when Hash import_from_hash(object) when nil import_from_array([]) end end nil end def method_missing(method_name, *args) if method_name.to_s =~ /^(\w{2})=$/ value = args[0] value = 0 unless value return instance_variable_set("@#{$1}", value) end super end def mongoize result = {} KEY_NAMES.each do |name| result[name] = instance_variable_get("@#{name}") end result end def [](key) name = generate_name key if name instance_variable_get("@#{name}") end end def []=(key, value) name = generate_name key value = 0 unless value instance_variable_set("@#{name}", value) end class << self # Get the object as it was stored in the database, and instantiate # this custom class from it. def demongoize(object) new(object) end # Takes any possible object and converts it to how it would be # stored in the database. def mongoize(object) case object when Hand object.mongoize when Array, Hash new(object).mongoize else object end end # Converts the object that was supplied to a criteria and converts it # into a database friendly form. def evolve(object) case object when Hand object.mongoize else object end end end private def import_from_array(array) KEY_NAMES.each_with_index do |name, i| value = array[i + 1] value = 0 unless value instance_variable_set("@#{name}", value) end end def import_from_hash(hash) hash = hash.stringify_keys KEY_NAMES.each do |name| value = hash[name] value = 0 unless value instance_variable_set("@#{name}", value) end end end
true
d08fd39d7cd157ce778c259ea17c47a0b94b5821
Ruby
xm-71/ConcertTickets
/app/models/concert.rb
UTF-8
330
2.59375
3
[]
no_license
class Concert < ActiveRecord::Base has_many :purchases belongs_to :venue def tickets_remaining a = self.tickets_available b = self.purchases.sum(:ticket_quantity) return a-b end def tickets_percentage a = self.tickets_available b = tickets_remaining return (b.to_f / a.to_f) * 100 end end
true
49cb28773cf85bf5be3cb2ffc8f7edf9f09292d6
Ruby
SketchUp/ruby-api-stubs
/lib/sketchup-api-stubs/stubs/Sketchup/RenderingOptionsObserver.rb
UTF-8
1,489
2.9375
3
[ "MIT" ]
permissive
# Copyright:: Copyright 2023 Trimble Inc. # License:: The MIT License (MIT) # This observer interface is implemented to react to rendering options events. # # @abstract To implement this observer, create a Ruby class of this type, implement the # desired methods, and add an instance of the observer to the objects of # interests. # # @example # # This is an example of an observer that watches the rendering options # # for changes. # class MyRenderingOptionsObserver < Sketchup::RenderingOptionsObserver # def onRenderingOptionsChanged(rendering_options, type) # puts "onRenderingOptionsChanged(#{rendering_options}, #{type})" # end # end # # # Attach the observer. # rendering_options = Sketchup.active_model.rendering_options # rendering_options.add_observer(MyRenderingOptionsObserver.new) class Sketchup::RenderingOptionsObserver # Instance Methods # The onRenderingOptionsChanged method is invoked whenever the user changes # their rendering options. # # @example # def onRenderingOptionsChanged(rendering_options, type) # puts "onRenderingOptionsChanged(#{rendering_options}, #{type})" # end # # @param [Sketchup::RenderingOptions] rendering_options # # @param [Integer] type # A number indicating which option was changed # represented by one of the constants defined in # {Sketchup::RenderingOptions}. # # @version SketchUp 6.0 def onRenderingOptionsChanged(rendering_options, type) end end
true
649ace3d4c7e206572f4f33245a8777e92f135af
Ruby
devico/learning-ruby
/imdb_budgets.rb
UTF-8
550
2.6875
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'yaml' require 'ruby-progressbar' module ImdbBudgets def take_budget_from_file(file_name) YAML::load_file(File.open(file_name))[file_name[5,9]] end def take_budget_from_imdb(id) data = take_info data = if data =~ /^(\$|\€|\£|DEM|AUD|FRF)/ data else nil end File.write("data/#{id}.yml", {id => data}.to_yaml) end def take_info Nokogiri::HTML(open(self.link)).css('div.txt-block:nth-child(11)').text.split(' ')[1] end end
true
b14f29196b46e36bf3b294cc617464fb0588c8ba
Ruby
stevenchanin/find-unique-files
/file_record.rb
UTF-8
563
2.96875
3
[ "MIT" ]
permissive
class FileRecord attr_reader :path, :name, :size, :create_datetime, :modify_datetime def initialize(path) @path = path load_file_details end def ==(other) name == other.name && size == other.size && modify_datetime == other.modify_datetime end def to_s "#{name} [#{path}, #{size}, Modified: #{modify_datetime}]" end private def load_file_details @name = File.basename(path) stats = File.stat(path) @size = stats.size @create_datetime = stats.ctime @modify_datetime = stats.mtime end end
true
e2e1706d5176d06935a1981b85ea0e89da08c418
Ruby
thisduck/griddle
/lib/griddle/processor/image_magick.rb
UTF-8
1,650
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Griddle class Processor class ImageMagick def crop `convert #{File.expand_path(@destination_file.path)} -crop #{geometry} -gravity Center #{@destination_file.path}` end def crop? @style.geometry =~ /#/ end def file_width file_dimensions.first end def fit(geo = geometry) `convert #{File.expand_path(@file.path)} -resize #{geo} #{@destination_file.path}` end def geometry @geometry ||= @style.geometry.gsub(/#/,'') end def file_height file_dimensions.last end def height dimensions.last end def process_image file, style @style = style @file = file @destination_file = Tempfile.new @file.original_filename if crop? fit(resize_geometry_for_crop) crop else fit end @destination_file end def width dimensions.first end private def dimensions @dimensions ||= dimensions_for(geometry) end def dimensions_for geo geo.scan(/([0-9]*)x([0-9]*)/).flatten.collect{|v|v.to_f} end def file_dimensions @file_dimensions ||= dimensions_for(`identify -format "%[fx:w]x%[fx:h]" #{File.expand_path(@file.path)}`) end def resize_for_width? file_height*(width/file_width) >= height end def resize_geometry_for_crop resize_for_width? ? "#{width}x" : "x#{height}" end end end end
true
40582f13ad3b30e8a2b299b5cf6a86199313e370
Ruby
AJFaraday/ruby-buzz
/lib/ruby_buzz/button.rb
UTF-8
2,042
3.265625
3
[ "MIT" ]
permissive
module RubyBuzz # # Handles a single button on the Buzz controllers. # # Identified by event code, all between 704 and 723. # Also identifiable by pad and name. # # Possible names: # # * buzz # * yellow # * green # * orange # * blue # # Initialized in RubyBuzz::Pad.init_mappings # # Each button holds an array of events, each of which is a # Proc to be called without arguments. These are called when # the button is pushed. # class Button @@buttons = [] # events will be an array of lambdas attr_accessor :name, :code, :events # # Initialize a button # # called in RubyBuzz::Pad.init_mappings # # Arguments: # # * code - Integer, the evnt code generated by this button (704-723) # * name - Symbol, the name of the button, for referncing via the Pad object # * pad - RubyBuzz::Pad, the object this button belongs to # def initialize(code, name, pad) @code = code @name = name @pad = pad @events = [] @@buttons << self end # # Find a button by its event code. Used by trigger_key # to find a button when one is pushed. # # Arguments: # # * code - Integer, event code to retrieve button by. # def self.find(code) @@buttons.detect { |b| b.code == code } end # # Add a process to be triggered when this button is pressed. # # Arguments: # # * proc - Proc, ruby method to be called, without arguments on button press. # def add_event(proc) @events << proc end # # Trigger every proc in the @events array. # def trigger_events @events.each do |event| event.call end end # # Find a button and run all it's events. # # Used by RubyBuzz::Device when button is pushed. # # Arguments: # # * code - Integer, event code to retrieve button by. # def self.trigger_key(code) btn = self.find(code) btn.trigger_events end end end
true
78cd37edaebed138b44af78fd58d70e560aa7c87
Ruby
chris-ma/WDI_SYD_7_NEW
/chris/w03/d01/chris/blog_app/app.rb
UTF-8
1,241
2.53125
3
[]
no_license
require "pry" require "sinatra" require "sinatra/reloader" require "pg" def run_sql(sql_string) connection = PG.connect(dbname: "my_blog", host: "localhost") result = connection.exec(sql_string) connection.close return result end get '/' do @posts = run_sql("SELECT * FROM posts;") erb :home end get '/posts/new' do erb :new_post_form end get '/post/:id' do post_id = params[:id] @post = run_sql("SELECT * FROM posts WHERE id=#{post_id};") erb :post end get '/delete/:id' do post_id = params[:id] @post = run_sql("DELETE FROM posts WHERE id=#{post_id};") redirect "/" end get '/update/:id' do @post = run_sql("SELECT * FROM posts WHERE id='#{params[:id]}';")[0] erb :update_form end put '/update_post' do run_sql(" UPDATE posts SET title='#{params[:title]}', content='#{params[:content]}', author='#{params[:author]}', author_website='#{params[:author_website]}' WHERE id='#{params[:id]}; ") redirect "/" end post '/posts' do run_sql(" INSERT INTO posts (title, content, author, author_website) VALUES ( '#{params["title"]}', '#{params["content"]}', '#{params["author"]}', '#{params["author_website"]}' ) ") redirect "/" end
true
c51832324728d11abb73d97666fee476c84df5e0
Ruby
Lyle-Tafoya/entity_handler
/examples/systems/graphics_ncurses.rb
UTF-8
1,223
2.53125
3
[]
no_license
# Created on 10/22/2016 by Lyle Tafoya # require "entity_handler" require "ncurses" module EntityHandler class GraphicsNcurses < System @screen = nil def initialize() self.components_register(['position', 'scene_ncurses']) System.callback_register('shutdown', self.method(:shutdown)) System.callback_register('scene_update', self.method(:scene_update)) System.callback_register('time_passed', self.method(:update)) @screen = Ncurses.initscr() Ncurses.curs_set(0) end def scene_update(message) @entities[message['entity_id']]['scene_ncurses']['string'] = message['string'] end def update(message) @entities.each do |entity_id, components| position = components['position'] Ncurses.mvwaddstr(@screen, position['y'].to_i(), position['x'].to_i(), components['scene_ncurses']['string']) end Ncurses.wrefresh(@screen) @entities.each do |entity_id, components| position = components['position'] Ncurses.mvwaddstr(@screen, position['y'].to_i(), position['x'].to_i(), ' '*components['scene_ncurses']['string'].size()) end end def shutdown(message) Ncurses.endwin() end end end
true
8b42f4a0757e99167342adb9eaa482e8d51e1aed
Ruby
hejinxu/docverter
/lib/docverter-server/manifest.rb
UTF-8
2,633
2.734375
3
[ "MIT" ]
permissive
require 'yaml' class DocverterServer::Manifest def pdf @pdf end def pdf_page_size @pdf_page_size end def self.load_file(filename) File.open(filename) do |f| self.load_stream(f) end end def self.load_stream(stream) self.new(YAML.load(stream)) end def initialize(options={}) @options = options @options['input_files'] ||= [] end def [](key) @options[key] end def []=(key, val) @options[key] = val end def write(filename) File.open(filename, "w+") do |f| write_to_stream(f) end end def write_to_stream(stream) stream.write YAML.dump(@options) end def test_mode? @test_mode end def command_options options = @options.dup input_files = options.delete('input_files') raise "No input files provided!" unless input_files.length > 0 @pdf_page_size = options.delete('pdf_page_size') if options['to'] == 'pdf' _ = options.delete 'to' @pdf = true end command_options = [] @test_mode = options.delete('test_mode') options.each do |k,v| raise InvalidManifestError.new("Invalid option: #{k}") unless k.match(/^[a-z0-9-]+/) option_key = k.to_s.gsub('_', '-') [v].flatten.each do |option_val| raise InvalidManifestError.new("Invalid option value: #{option_val}") unless option_val.to_s.match(/^[a-zA-Z0-9._-]+/) if option_val.is_a?(TrueClass) || option_val == 'true' command_options << "--#{option_key}" else command_options << "--#{option_key}=#{option_val}" end end end command_options += [input_files].flatten.compact command_options end def validate!(dir) raise InvalidManifestError.new("No input files found") unless @options['input_files'] && @options['input_files'].length > 0 Dir.chdir(dir) do @options['input_files'].each do |filename| raise InvalidManifestError.new("Invalid input file: #{filename} not found") unless File.exists?(filename) raise InvalidManifestError.new("Invalid input file: #{filename} cannot start with /") if filename.strip[0] == '/' end raise InvalidManifestError.new("'from' key required") unless @options['from'] raise InvalidManifestError.new("'to' key required") unless @options['to'] raise InvalidManifestError.new("Not a valid 'from' type") unless DocverterServer::ConversionTypes.valid_input?(@options['from']) raise InvalidManifestError.new("Not a valid 'to' type") unless DocverterServer::ConversionTypes.valid_output?(@options['to']) end end end
true
c5106addc48eb9bf81af959a71b1bd1d066683fb
Ruby
darkogj/rambling-trie
/lib/rambling/trie/tasks/performance/flamegraph.rb
UTF-8
3,205
2.53125
3
[ "MIT" ]
permissive
namespace :performance do include Helpers::Path include Helpers::Time def performance_report @performance_report ||= PerformanceReport.new end def output performance_report.output end class FlamegraphProfile def initialize filename @filename = filename end def perform times, params = nil params = Array params params << nil unless params.any? dirname = path 'reports', Rambling::Trie::VERSION, 'flamegraph', time FileUtils.mkdir_p dirname path = File.join dirname, "#{filename}.html" result = Flamegraph.generate path do params.each do |param| times.times do yield param end end end end private attr_reader :filename end namespace :flamegraph do desc 'Output banner' task :banner do performance_report.start 'Flamegraph' end desc 'Generate flamegraph reports for creation' task creation: ['performance:directory', :banner] do output.puts 'Generating flamegraph reports for creation...' flamegraph = FlamegraphProfile.new 'new-trie' flamegraph.perform 1 do trie = Rambling::Trie.create dictionary end end desc 'Generate flamegraph reports for compression' task compression: ['performance:directory', :banner] do output.puts 'Generating flamegraph reports for compression...' tries = [ Rambling::Trie.create(dictionary) ] flamegraph = FlamegraphProfile.new 'compressed-trie' flamegraph.perform 1, tries do |trie| trie.compress! nil end end desc 'Generate flamegraph reports for lookups' task lookups: ['performance:directory', :banner] do output.puts 'Generating flamegraph reports for lookups...' words = %w(hi help beautiful impressionism anthropological) trie = Rambling::Trie.create dictionary compressed_trie = Rambling::Trie.create(dictionary).compress! [ trie, compressed_trie ].each do |trie| prefix = "#{trie.compressed? ? 'compressed' : 'uncompressed'}-trie" flamegraph = FlamegraphProfile.new "#{prefix}-word" flamegraph.perform 1, words do |word| trie.word? word end flamegraph = FlamegraphProfile.new "#{prefix}-partial-word" flamegraph.perform 1, words do |word| trie.partial_word? word end end end desc 'Generate flamegraph reports for scans' task scans: ['performance:directory', :banner] do output.puts 'Generating flamegraph reports for scans...' words = %w(hi help beautiful impressionism anthropological) trie = Rambling::Trie.create dictionary compressed_trie = Rambling::Trie.create(dictionary).compress! [ trie, compressed_trie ].each do |trie| prefix = "#{trie.compressed? ? 'compressed' : 'uncompressed'}-trie" flamegraph = FlamegraphProfile.new "#{prefix}-scan" flamegraph.perform 1, words do |word| trie.scan(word).size end end end desc 'Generate all flamegraph reports' task all: [ :creation, :compression, :lookups, :scans, ] end end
true
364bbd3c94748feb4ed812239c563e9b34ca171a
Ruby
yone0000/furima35821
/spec/models/item_spec.rb
UTF-8
3,832
2.515625
3
[]
no_license
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) @item.image = fixture_file_upload('app/assets/images/IMG_1368.JPG') end describe '商品出品機能' do context '商品出品できるとき' do it 'image,name,info,category_id,sales_status_id,shipping_fee_status_id,prefecture_id,schedule_delivery_id,priceがあれば出品できる' do expect(@item).to be_valid end it 'priceが300円なら出品できる' do @item.price = 300 expect(@item).to be_valid end it 'priceが9,999,999円なら出品できる' do @item.price = 9_999_999 expect(@item).to be_valid end it 'priceが半角なら出品できる' do @item.price = 300 expect(@item).to be_valid end end context '商品出品できないとき' do it 'imageがないと出品できない' do @item.image = nil @item.valid? expect(@item.errors.full_messages).to include("Image can't be blank") end it 'nameがないと出品できない' do @item.name = '' @item.valid? expect(@item.errors.full_messages).to include("Name can't be blank") end it 'infoがないと出品できない' do @item.info = '' @item.valid? expect(@item.errors.full_messages).to include("Info can't be blank") end it 'category_idがないと出品できない' do @item.category_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Category must be other than 1') end it 'sales_status_idがないと出品できない' do @item.sales_status_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Sales status must be other than 1') end it 'shipping_fee_status_idがないと出品できない' do @item.shipping_fee_status_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Shipping fee status must be other than 1') end it 'prefecture_idがないと出品できない' do @item.prefecture_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Prefecture must be other than 1') end it 'schedule_delivery_idがないと出品できない' do @item.schedule_delivery_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Schedule delivery must be other than 1') end it 'priceがないと出品できない' do @item.price = '' @item.valid? expect(@item.errors.full_messages).to include("Price can't be blank") end it 'priceが300円以下だと出品できない' do @item.price = 299 @item.valid? expect(@item.errors.full_messages).to include('Price is not included in the list') end it 'priceが9,999,999円以上だと出品できない' do @item.price = 10_000_000 @item.valid? expect(@item.errors.full_messages).to include('Price is not included in the list') end it 'priceが半角数字でないと出品できない' do @item.price = '300' @item.valid? expect(@item.errors.full_messages).to include('Price is not included in the list') end it "priceが半角英数混合では登録できないこと" do @item.price = "300dollars" @item.valid? expect(@item.errors.full_messages).to include("Price is not a number") end it "priceが半角英語だけでは登録できないこと" do @item.price = "threemillion" @item.valid? expect(@item.errors.full_messages).to include("Price is not included in the list") end end end end
true
bdba86c5074b17e42cc77d1ea1b9eafb88385133
Ruby
CodeCoreYVR/apr-2016-fundamentals
/ruby_day_2/method_return.rb
UTF-8
86
3.0625
3
[]
no_license
def my_method end def method_1(a, b) c = a + b a * c end puts method_1(3,4) * 3
true
7cf0104675404c1ad67084a28e2778184a656402
Ruby
mdnsean/lyrics
/app/helpers/scraper.rb
UTF-8
448
2.78125
3
[]
no_license
module Scraper def search_azlyrics(artist) agent = Mechanize.new artist = artist.gsub(' ', '') artist_url = artist[0] + '/' + artist + '.html' page = agent.get('http://azlyrics.com/' + artist_url) song_links = page.links_with(href: /lyrics\/#{artist}/) song = song_links[0].click lyrics = song.css('div.ringtone~div')[0].children lyrics.each do |line| end end end
true
38d33766f996645a516e5076351373c6527ed53c
Ruby
MattLemmon/cat-game
/bckgrnd/cpncat_gmst/CATCORE.rb
UTF-8
2,414
3.015625
3
[]
no_license
# # PAUSE CLASS # class Pause < Chingu::GameState def initialize(options = {}) super @title = Chingu::Text.create(:text=>"PAUSED (press 'p' to un-pause)", :x=>200, :y=>200, :size=>20, :color => Color.new(0xFF00FF00)) self.input = { :p => :un_pause, :q => DrdCat, :r => :reset } end def un_pause pop_game_state(:setup => false) # Return the previous game state, dont call setup() end def reset pop_game_state(:setup => true) end def draw previous_game_state.draw # Draw prev game state onto screen (in this case our level) super # Draw game objects in current game state, this includes Chingu::Texts end end # # WINDOW CLASS WINDOW CLASS WINDOW CLASS WINDOW CLASS # class Core < Chingu::Window def initialize super(800,600) self.input = {:esc => :exit, :enter => :next, :return => :next, :q => :pop, :z => :status, :f=>:fart} push_game_state(Welcome) end def pop if $window.current_game_state.to_s != "Welcome" then pop_game_state else puts "chill" end end def next if current_game_state.class == Welcome switch_game_state(DrdCat) else switch_game_state(Welcome) end end def status puts $window.current_game_state end def fart @fart = "&xo|kee<92ujjsllo8!!!" puts @fart end end # # WELCOME WELCOME WELCOME WELCOME WELCOME WELCOME WELCOME # class Welcome < Chingu::GameState def initialize super $window.caption = "Chingu Example Loader - WELCOME" self.input = { :b => :boom, :enter => DrdCat, :return => DrdCat } @t1 = Chingu::Text.create(:text=>"Chingu Example Loader" , :x=>98, :y=>70, :size=>70) @t2 = Chingu::Text.create(:text=>"Global Controls: Q - Previous Menu" , :x=>134, :y=>185, :size=>36) @t3 = Chingu::Text.create(:text=>"W - Previous Menu" , :x=>382, :y=>235, :size=>36) @t4 = Chingu::Text.create(:text=>"Z - Status Log" , :x=>388, :y=>335, :size=>36) @t4 = Chingu::Text.create(:text=>"F - Fart Feature" , :x=>391, :y=>285, :size=>36) @t5 = Chingu::Text.create(:text=>"Press Enter to Continue" , :x=>240, :y=>420, :size=>40) puts "Welcome" end def boom puts $window.current_game_state puts "Boom!" push_game_state(DrdCat) end def setup $window.caption = "Chingu Example Loader - WELCOME" end end
true
33116ba9f094d4dbf53dbd7d241547b40de3735b
Ruby
ndlib/sipity
/app/services/sipity/services/administrative/update_who_submitted_work.rb
UTF-8
5,930
2.640625
3
[ "Apache-2.0" ]
permissive
module Sipity module Services module Administrative # @api private # # Please Note: I have not written tests for this. In part because I chose to add an audit (e.g. "Are you sure you want to do this?") class UpdateWhoSubmittedWork class ErrorState < RuntimeError end # @api public # # The {Sipity::Forms::SubmissionWindows::Etd::StartASubmissionForm} class calls {CommandRepository#grant_creating_user_permission_for!} # to assign the {Sipity::Models::Role::CREATING_USER} role (e.g., 'creating_user'). # # We have had two cases in which we need to change the creating user. # # Case 1: A professor submitted it on another person's behalf. We chose to change the professor's netID to the other person's netID. # This, in essence, associated the database user from one person to another. # # Case 2: The graduate school submitted this on a person's behalf. Instead of replacing the netID (which would've cause significant # problems), we instead chose to change the relationships of the {Sipity::Models::Processing::Actor}. # # From a logging and provenance stand-point, Case 2 is perhaps most ideal. # # This class seeks to encode that logic. # # There are two primary functions: # # * #audit! # * #change_it! # # @param work [Object] An id or Sipity::Models::Work (e.g. something that can be converted via Conversions::ConvertToWork) # @param from_username [String] The netid of the current user that submitted # @param to_username [String] The netid of the user that you are assigning "submitter" status to. # @param role [String] The role we're going to change. # # @note This def initialize(work:, from_username:, to_username:, role: Sipity::Models::Role::CREATING_USER, logger: default_logger) self.work = work self.role = role @logger = logger @from_username = from_username @to_username = to_username @audited = false end attr_reader :work, :role def audit! @errors = false entity audit_from_username audit_to_username audit_work_for_from_user return false if @errors @audited = true end def audited? @audited end def errors? @errors end def change_it! raise ErrorState.new("First audit! this change") unless audited? raise ErrorState.new("There are errors in this request, run audit! for details") if errors? @to_user ||= User.find_or_create_by!(username: @to_username) move_work_role_assoication_from_user_to_user! end private # :nocov: def audit_from_username @from_user = User.find_by(username: @from_username) if @from_user logger.info("Found :from_username #{@from_username.inspect} for User ID=#{@from_user.id}") else logger.error("Could not find :from_username #{@from_username.inspect}") @errors = true end end def audit_to_username @to_user = User.find_by(username: @to_username) if @to_user logger.info("Found :to_username #{@to_username.inspect} for User ID=#{@to_user.id}") else logger.warn("Could not find :to_username #{@to_username.inspect}. The #change_it! method will create a new user with username #{@to_username}") end end # Ensure that the given work is associated with the from user. def audit_work_for_from_user return false unless @from_user # short circuit assumption that we have a from user if entity_specific_responsibility_for(user: @from_user) logger.info("The from_user #{@from_user.username.inspect} has the role \"#{role}\" for the given work ID=\"#{work.id}\"") else logger.error("The from_user #{@from_user.username.inspect} does not have the role \"#{role}\" for the given work ID=\"#{work.id}\"") @errors = true end end # :nocov: def move_work_role_assoication_from_user_to_user! # Alternatively, we could call the following: # # Sipity::Services::RevokeProcessingPermission.call(entity: entity, actor: @from_user, role: role) # Sipity::Services::GrantProcessingPermission.call(entity: entity, actor: @to_user, role: role) record = entity_specific_responsibility_for(user: @from_user) record.update!(actor: Conversions::ConvertToProcessingActor.call(@to_user)) end def entity_specific_responsibility_for(user:) esr = Sipity::Models::Processing::EntitySpecificResponsibility.arel_table sr = Sipity::Models::Processing::StrategyRole.arel_table Sipity::Models::Processing::EntitySpecificResponsibility.where( entity: entity, actor: Conversions::ConvertToProcessingActor.call(user), ).where( esr[:strategy_role_id].in( sr.project(sr[:id]).where( sr[:role_id].eq(role.id).and( sr[:strategy_id].eq(entity.strategy_id) ) ) ) ).first end def work=(input) @work = Conversions::ConvertToWork.call(input) end def entity @entity ||= Conversions::ConvertToProcessingEntity.call(work) end def role=(input) @role = Conversions::ConvertToRole.call(input) end # :nocov: def default_logger Logger.new(STDOUT) end # :nocov: end end end end
true
ba4fa6059f06aee4f2214768e83431ee1fbb2e83
Ruby
chatulli/sampleCodeRuby
/c1_hello_currentTime.rb
UTF-8
160
3.625
4
[]
no_license
puts "Hello, Ruby Programmer" puts "It is now #{Time.now}" def say_goodnight(name) result = "Good night," + name return result end puts say_goodnight("ed")
true
f98ff2df5b8cba4ab5bcecefd4f954b79ad011bb
Ruby
datacite/base32
/lib/base32/crockford.rb
UTF-8
4,648
3.453125
3
[]
no_license
# encoding: UTF-8 # # (c) 2008, Levin Alexander <http://levinalex.net> # # This file is released under the same license as ruby. require 'enumerator' module Base32 end # encode a value with the encoding defined by _Douglas_ _Crockford_ in # <http://www.crockford.com/wrmg/base32.html> # # this is *not* the same as the Base32 encoding defined in RFC 4648 # # # The Base32 symbol set is a superset of the Base16 symbol set. # # We chose a symbol set of 10 digits and 22 letters. We exclude 4 of the 26 # letters: I L O U. # # Excluded Letters # # I:: Can be confused with 1 # L:: Can be confused with 1 # O:: Can be confused with 0 # U:: Accidental obscenity # # When decoding, upper and lower case letters are accepted, and i and l will # be treated as 1 and o will be treated as 0. When encoding, only upper case # letters are used. # # If the bit-length of the number to be encoded is not a multiple of 5 bits, # then zero-extend the number to make its bit-length a multiple of 5. # # Hyphens (-) can be inserted into symbol strings. This can partition a # string into manageable pieces, improving readability by helping to prevent # confusion. Hyphens are ignored during decoding. An application may look for # hyphens to assure symbol string correctness. # # class Base32::Crockford VERSION = "0.2.3" ENCODE_CHARS = %w(0 1 2 3 4 5 6 7 8 9 A B C D E F G H J K M N P Q R S T V W X Y Z ?) DECODE_MAP = ENCODE_CHARS.to_enum(:each_with_index).inject({}) do |h,(c,i)| h[c] = i; h end.merge({'I' => 1, 'L' => 1, 'O' => 0}) CHECKSUM_CHARS = %w(* ~ $ = U) CHECKSUM_MAP = { "*" => 32, "~" => 33, "$" => 34, "=" => 35, "U" => 36 } # encodes an integer into a string # # when +checksum+ is given, a checksum is added at the end of the the string, # calculated as modulo 37 of +number+. Five additional checksum symbols are # used for symbol values 32-36 # # when +split+ is given a hyphen is inserted every <n> characters to improve # readability # # when +length+ is given, the resulting string is zero-padded to be exactly # this number of characters long (hyphens are ignored) # # Base32::Crockford.encode(1234) # => "16J" # Base32::Crockford.encode(123456789012345, :split=>5) # => "3G923-0VQVS" # def self.encode(number, opts = {}) # verify options raise ArgumentError unless (opts.keys - [:length, :split, :checksum] == []) str = number.to_s(2).reverse.scan(/.{1,5}/).map do |bits| ENCODE_CHARS[bits.reverse.to_i(2)] end.reverse.join str = str + (ENCODE_CHARS + CHECKSUM_CHARS)[number % 37] if opts[:checksum] str = str.rjust(opts[:length], '0') if opts[:length] if opts[:split] str = str.reverse str = str.scan(/.{1,#{opts[:split]}}/).map { |x| x.reverse } str = str.reverse.join("-") end str end # decode a string to an integer using Douglas Crockfords Base32 Encoding # # the string is converted to uppercase and hyphens are stripped before # decoding # # I,i,l,L decodes to 1 # O,o decodes to 0 # # Base32::Crockford.decode("16J") # => 1234 # Base32::Crockford.decode("OI") # => 1 # Base32::Crockford.decode("3G923-0VQVS") # => 123456789012345 # # returns +nil+ if the string contains invalid characters and can't be # decoded, or if checksum option is used and checksum is incorrect # def self.decode(string, opts = {}) if opts[:checksum] checksum_char = string.slice!(-1) checksum_number = DECODE_MAP.merge(CHECKSUM_MAP)[checksum_char] end number = clean(string).split(//).map { |char| DECODE_MAP[char] or return nil }.inject(0) { |result,val| (result << 5) + val } number % 37 == checksum_number or return nil if opts[:checksum] number end # same as decode, but raises ArgumentError when the string can't be decoded # def self.decode!(string, opts = {}) decode(string) or raise ArgumentError end # return the canonical encoding of a string. converts it to uppercase # and removes hyphens # # replaces invalid characters with a question mark ('?') # def self.normalize(string, opts = {}) checksum_char = string.slice!(-1) if opts[:checksum] string = clean(string).split(//).map { |char| ENCODE_CHARS[DECODE_MAP[char] || 32] }.join string = string + checksum_char if opts[:checksum] string end # returns false if the string contains invalid characters and can't be # decoded # def self.valid?(string, opts = {}) !(normalize(string, opts) =~ /\?/) end class << self def clean(string) string.gsub(/-/,'').upcase end private :clean end end
true
59c2938c1a0fbaf4f247d7353135f03bc28e7673
Ruby
BohanHsu/leetcode
/first_missing_positive.rb
UTF-8
898
3.734375
4
[]
no_license
# Given an unsorted integer array, find the first missing positive integer. # For example, # Given [1,2,0] return 3, # and [3,4,-1,1] return 2. # Your algorithm should run in O(n) time and uses constant space. # @param {Integer[]} nums # @return {Integer} def first_missing_positive(nums) nums.length.times do |i| if nums[i].nil? || nums[i] <= 0 || nums[i] > nums.length nums[i] = nil elsif nums[i] != i + 1 j = i prev = nil while nums[j] != j + 1 do unless nums[j].nil? new_j = nums[j] - 1 tmp = nums[new_j] nums[new_j] = new_j + 1 end nums[j] = prev if tmp.nil? || tmp <= 0 || tmp > nums.length j = new_j else prev = tmp j = tmp - 1 end end end end nums.each_with_index do |e, i| return i + 1 if e.nil? end nums.length + 1 end
true
ea578f02d8362b1527dc9f27d8d70ebacc9322d9
Ruby
zhshi/isjournals
/lib/journal.rb
UTF-8
3,218
2.796875
3
[]
no_license
require 'sequel' require 'open-uri' require 'nokogiri' require 'pdf-reader' class Journal def initialize(code, publisher, url) @code = code @publisher = publisher @url = url end def check(articles, authors, abstracts) case @publisher when "informs" puts "checking #{@code}" check_informs(articles, authors, abstracts) when "misq" puts "checking #{@code}" check_misq(articles, authors, abstracts) else puts "sorry, i don't know how to check #{@publisher} journals" end end :private def check_informs(articles, authors, abstracts) doc = Nokogiri::HTML(open(@url)) doc.search('div[@class="cit is-early-release has-earlier-version"]').each do |p| # get article info title = "" p.xpath('div[@class="cit-metadata"]/span[@class="cit-title"]').each do |t| title = t.text.strip end doi = "" p.xpath('div[@class="cit-metadata"]/cite/span[@class="cit-doi"]').each do |cdoi| doi = cdoi.text.sub(/^doi: */, '') end idx = articles.max(:idx) articles.insert_ignore.insert(:code => @code, :doi => doi, :title => title) if idx == articles.max(:idx) next end idx = articles.max(:idx) # get abstract abs_url = "" p.xpath('div[@class="cit-extra"]/ul/li[@class="first-item"]/a').each do |a| abs_url = a["href"] end abs_url = @url.sub(/([^\/]\/)[^\/].*/, '\1') + abs_url abs_doc = Nokogiri::HTML(open(abs_url)) abs = "" abs_doc.search('p[@id="p-1"]').each do |ap| abs = ap.text abs.gsub!(/\s*\n\s*/, ' ') abs.strip! break end abstracts.insert_ignore.insert(:idx => idx, :abstract => abs) # get authors p.xpath('div[@class="cit-metadata"]/ul/li/span[@class="cit-auth cit-auth-type-author"]').each do |auth| auth = auth.text authors.insert_ignore.insert(:idx => idx, :author => auth) end end end def check_misq(articles, authors, abstracts) # get the right portion of the page txt = "" right_sec = false open(@url) do |wp| wp.each do |l| if right_sec if l =~ /hr-red\.gif/ right_sec = false else txt += l end elsif l =~ /<h3>.*Research Articles/ right_sec = true end end end # parse papers doc = Nokogiri::HTML(txt) doc.search('p').each do |p| auths = p.children[2].text.strip.gsub(' and ', ', ').gsub(/,\s*,/, ',').split(',').map {|auth| auth.strip} title = p.children[0].children[0].text.strip abs_url = @url.sub(/([^\/])\/[^\/].*/, '\1') + p.children[0]["href"] abs = "" pdfreader = PDF::Reader.new(open(abs_url)) pdfreader.pages.each do |page| abs = page.text abs = (abs.split(/Abstract\s*\n/))[1] abs = (abs.split(/\n\s*Keywords/))[0] abs.gsub!(/\n/,' ') abs.gsub!(/ +/, ' ') break end # insert idx = articles.max(:idx) articles.insert_ignore.insert(:code => @code, :title => title) if idx == articles.max(:idx) next end idx = articles.max(:idx) abstracts.insert_ignore.insert(:idx => idx, :abstract => abs) auths.each do |auth| authors.insert_ignore.insert(:idx => idx, :author => auth) end end end end
true
23d8b9df13dd10809cfef76612cff5e5e400c2e4
Ruby
jas0nmjames/jas0nmjames.github.io
/vendor/bundle/ruby/3.2.0/gems/ttfunk-1.7.0/lib/ttfunk/table/hmtx.rb
UTF-8
1,498
2.53125
3
[ "GPL-2.0-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-or-later", "GPL-3.0-only", "Ruby", "MIT" ]
permissive
# frozen_string_literal: true require_relative '../table' module TTFunk class Table class Hmtx < Table attr_reader :metrics attr_reader :left_side_bearings attr_reader :widths def self.encode(hmtx, mapping) metrics = mapping.keys.sort.map do |new_id| metric = hmtx.for(mapping[new_id]) [metric.advance_width, metric.left_side_bearing] end { number_of_metrics: metrics.length, table: metrics.flatten.pack('n*') } end HorizontalMetric = Struct.new(:advance_width, :left_side_bearing) def for(glyph_id) @metrics[glyph_id] || metrics_cache[glyph_id] ||= HorizontalMetric.new( @metrics.last.advance_width, @left_side_bearings[glyph_id - @metrics.length] ) end private def metrics_cache @metrics_cache ||= {} end def parse! @metrics = [] file.horizontal_header.number_of_metrics.times do advance = read(2, 'n').first lsb = read_signed(1).first @metrics.push HorizontalMetric.new(advance, lsb) end lsb_count = file.maximum_profile.num_glyphs - file.horizontal_header.number_of_metrics @left_side_bearings = read_signed(lsb_count) @widths = @metrics.map(&:advance_width) @widths += [@widths.last] * @left_side_bearings.length end end end end
true
3e72a76a936c5223b1559cdd1ca546ac79cbda27
Ruby
miguelfajardoc/ruby_excercises
/test_dome/change.rb
UTF-8
576
3.75
4
[]
no_license
# given an amount of money, return the minimum cuantity of coins # with this options: 25, 10, 5, 2 and 1 cent. Returned in a hash # if there are not some type coin used, the key must not be in the hash def change(money) change = {} coins = [25, 10, 5, 2, 1] unless money puts "error" return end money = money.to_i coins.each do |coin| if money / coin > 0 amount = money / coin money -= (amount * coin) change[coin] = amount if money == 0 return change end end end return change end p change(ARGV[0])
true
b4bcc362c14c1e579b888728ac0b79ae5e74f1f0
Ruby
marksweston/acts_as_raytracer
/lib/acts_as_raytracer/plane.rb
UTF-8
539
2.5625
3
[]
no_license
class Plane < Shape def self.default_material return Material.new( ambient: 0.30, diffuse_reflection: 0.9, specular_reflection: 0, shininess: 0 ) end def intersect(ray:) return [] if object_space(ray).vector.y.round(epsilon).zero? t = (-object_space(ray).origin.y) / object_space(ray).vector.y if t > 0 return [Intersection.new(t: t, object: self)] else return [] end end def normal_at(intersect:) return world_space(Vector.new(0, 1, 0)).normalise end end
true
c2c38e3167c9be13cdad9ceda8d49c6ce0b3b0f8
Ruby
dkubb/ice_nine
/spec/unit/ice_nine/freezer/class_methods/element_reader_spec.rb
UTF-8
2,961
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# encoding: utf-8 require 'spec_helper' require 'ice_nine/freezer' require 'ice_nine/freezer/object' require 'ice_nine/freezer/array' require 'ice_nine/freezer/struct' describe IceNine::Freezer, '.[]' do subject { object[mod] } let(:object) { described_class } let(:freezer) { object::Object } describe 'when the module matches a descendant' do let(:freezer) { Class.new(object) } let(:mod) { Class } before do object.const_set(mod.name, freezer) end after do object.send(:remove_const, mod.name) end it 'returns the freezer' do should be(freezer) end end describe 'when the module matches a descendant inside a namespace' do let(:namespace) { Class.new(object) } let(:freezer) { Class.new(object) } let(:mod) { Application::User } before :all do module ::Application class User; end end end after :all do ::Application.send(:remove_const, :User) Object.send(:remove_const, :Application) end around do |example| namespace.const_set(:User, freezer) object.const_set(:Application, namespace) example.run namespace.send(:remove_const, :User) object.send(:remove_const, :Application) end it 'returns the freezer' do should be(freezer) end end describe 'when the module is a struct' do let(:mod) { Struct.new(:a) } let(:freezer) { IceNine::Freezer::Struct } it 'returns the freezer' do should be(freezer) end end describe 'when the module does not match a descendant' do let(:mod) { Object } it 'returns the freezer' do should be(freezer) end end describe 'when the module is an anonymous class' do let(:mod) { Class.new } it 'returns the freezer' do should be(freezer) end end describe 'when the module is an anonymous module' do let(:mod) { Module.new } it 'returns the freezer' do should be_nil end end describe 'when the module is under a freezer namespace' do let(:mod) { Hash::Test } let(:freezer) { IceNine::Freezer::Hash } around do |example| class Hash::Test; end example.run Hash.send(:remove_const, :Test) end it 'returns the freezer' do should be(freezer) end end describe 'when the module has a name of a freezer in another namespace' do let(:mod) { Mash::State } let(:freezer) { Class.new(IceNine::Freezer::Hash) } before :all do module ::Mash class State; end end end after :all do ::Mash.send(:remove_const, :State) Object.send(:remove_const, :Mash) end around do |example| object.const_set(:Mash, freezer) example.run object.send(:remove_const, :Mash) end it 'returns the freezer' do should be(freezer) end end end
true
3681474b51457d47a45081659be7852ad74b4bf4
Ruby
Vlado90/Unfuddled
/lib/unfuddled/error.rb
UTF-8
310
2.546875
3
[]
no_license
module Unfuddled class Error < StandardError class << self # Create an Error from an Erroneous HTTP Response # # @param response[Hash] # @return [Unfuddled::Error] def from_response(response = {}) new(response[:response_headers]) end end end end
true
1aefda5370a319f196cc4b2a239c9fe7ed420ba2
Ruby
protochron/Colonists-vs-Pirates
/lib/cannon.rb
UTF-8
1,318
3.171875
3
[]
no_license
# # Dan Norris and Cody Miller, 2011 require File.dirname(__FILE__) + '/game_object' require File.dirname(__FILE__) + '/projectile' # Implements a cannon object. This is a basic defensive structure for the player to destroy enemy ships with. class Cannon < GameObject attr_accessor :health, :projectiles attr_reader :cost def initialize(x,y) @x, @y = x, y @health = 50 @projectiles = [] @tick_counter = 0 @shoot_interval = 7 * 60 @cost = 15 end # Action to take every window update. def tick @tick_counter += 1 if @tick_counter >= @shoot_interval shoot @tick_counter = 0 end if !@projectiles.empty? @projectiles.each do |p| p.tick # Iterate over ships until we find one that intersects. $window.ships.each do |s| if p.x - s.x >= 1 and p.y - s.y < 100 s.health -= p.damage @projectiles.delete(p) next end end end end end # Shoot a projectile at a ship def shoot @projectiles << Projectile.new(@x + 55, @y + 20, $window.cannon_ball, 10, 0.3, :right) end end
true
290eb48ca878f78a251493c9b334eae89ab16133
Ruby
mSourire/pla
/spec/controllers/products_controller_spec.rb
UTF-8
4,630
2.640625
3
[]
no_license
require 'rails_helper' RSpec.describe ProductsController, type: :controller do let(:existing_product) { Product.create({ id: 5, name: 'Cucumber', price: 20, description: 'Green and crispy' }) } describe "GET index" do context "when a format is HTML" do it "renders the index template" do get :index expect(response).to render_template(:index) end end context "when a format is JSON" do context "if there are no products yet" do it "renders empty JSON" do get :index, format: :json expect(response.status).to be(200) puts JSON.parse(response.body) expect(JSON.parse(response.body).length).to eq(0) end end context "if products exist" do it "serves multiple products as JSON" do existing_product get :index, format: :json expect(response.status).to be(200) expect(JSON.parse(response.body).length).to eq(1) end end end end describe "POST create" do it "assigns @product" do post :create, format: :json expect(assigns(:product)).to be_kind_of(Product) end context "when successfully created" do it "returns empty response body with 201 status code" do post :create, params: { product: { name: 'Tomatos', price: 30, description: 'Red and juicy' } }, format: :json expect(response.status).to be(201) expect(response.body.length).to eq(0) end end context "when couldn't created" do it "returns JSON with error message and 400 status code" do post :create, params: { product: { name: 'Tomatos', price: 30 } }, format: :json expect(response.status).to be(400) expect(JSON.parse(response.body)['errors'].length).to be > 0 end end end describe "GET show" do context "when product exists" do context "when format is HTML" do it "renders the show template" do get :show, params: { id: existing_product.id } expect(response).to render_template(:show) end end context "when format is JSON" do it "renders the product in JSON" do get :show, params: { id: existing_product.id }, format: :json expect(JSON.parse(response.body)['id']).to eq(existing_product.idexisting_product.id) end end end context "when product does not exist" do context "when format is HTML" do it "redirects to root path" do get :show, params: { id: -1 } expect(response).to redirect_to root_path end end context "when format is JSON" do it "replies with 404 status code" do get :show, params: { id: -1 }, format: :json expect(response.status).to be(404) end end end end describe "GET edit" do context "when product exists" do it "renders an edit template" do get :edit, params: { id: existing_product.id } expect(response).to render_template(:edit) end end context "when product doesn't exist" do it "redirects to root path" do get :edit, params: { id: -1 } expect(response).to redirect_to root_path end end end describe "PUT update" do context "when product exists" do context "when it is successfully updated" do it "replies with 200 status code" do put :update, params: { id: existing_product.id, product: { name: 'Watermelon'} }, format: :json expect(response.status).to be(200) end end context "when couldn't update" do it "renders JSON with errors and 400 status code" do put :update, params: { id: existing_product.id, product: { price: -100 } }, format: :json expect(response.status).to be(400) expect(JSON.parse(response.body)['errors'].length).to be > 0 end end end context "when product doesn't exist" do it "replies with 404 status code" do put :update, params: { id: -1 }, format: :json expect(response.status).to be(404) end end end describe "DELETE destroy" do context "when product exists" do it "destroys it and replies with 204 status code" do delete :destroy, params: { id: existing_product.id } expect(response.status).to be(204) end end context "when product doesn't exist" do it "replies with 404 status code" do delete :destroy, params: { id: -1 } expect(response.status).to be(404) end end end end
true
97ecca6c99086b6e187aa646a14e7356d874dee7
Ruby
M1CH43L-S1M30N/Projects
/Michael_Chang_W6D5/Poker/spec/card_spec.rb
UTF-8
478
2.703125
3
[]
no_license
require 'rspec' require 'card' describe Card do describe '#initialize' do subject(:card) {Card.new(:hearts, :deuce)} it 'creates the card correctly' do expect(card.value).to eq(:deuce) expect(card.suit).to eq(:hearts) end it 'raises an error if invalid suit' do expect (Card.new(:test, :deuce)).to raise_error end it 'raises an error if invalid value' do expect (Card.new(:hearts, :test)).to raise_error end end end
true
a0e8533795221d54f1b0f4641a69ed43426be1ad
Ruby
ArcWhiz/Ruby
/Arrays/two_arrays.rb
UTF-8
67
3.0625
3
[]
no_license
arr1 = [1,2,3,4,5,6] arr2 = arr1.map {|val| val+2} p arr1 p arr2
true
ed7f164409feabeccd4f578ab37acad296c91d19
Ruby
monodelic/study
/test/exercise/fp2/solution.rb
UTF-8
1,032
3.46875
3
[]
no_license
module Exercise module Fp2 class MyArray < Array # Использовать стандартные функции массива для решения задач нельзя. # Использовать свои написанные функции для реализации следующих - можно. # Написать свою функцию my_each def my_each for element in self yield element end self end # Написать свою функцию my_map def my_map result = self.class.new([]) my_each do |element| result << yield(element) end result end # Написать свою функцию my_compact def my_compact myc = self.class.new for i in 0..(length - 1) myc << self[i] unless self[i].nil? end myc end # Написать свою функцию my_reduce def my_reduce end end end end
true
4ee0cad8827df170fda1bdbd869cfef7d8446aaf
Ruby
Mariana-21/launchschool_v2
/101_109_small_problems/easy_6/03_fibonacci_location.rb
UTF-8
1,001
3.96875
4
[]
no_license
# fibonacci_location.rb def find_fibonacci_index_by_length(length) first = 1 second = 1 fibonacci_number = first + second index = 3 until fibonacci_number.to_s.size >= length first = second second = fibonacci_number fibonacci_number = first + second index += 1 end index end p find_fibonacci_index_by_length(2) == 7 p find_fibonacci_index_by_length(10) == 45 p find_fibonacci_index_by_length(100) == 476 p find_fibonacci_index_by_length(1000) == 4782 p find_fibonacci_index_by_length(10000) == 47847 def find_fibonacci_index_by_length(length) first = 1 second = 1 index = 2 loop do index += 1 fibonacci = first + second break if fibonacci.to_s.size >= length first = second second = fibonacci end index end p find_fibonacci_index_by_length(2) == 7 p find_fibonacci_index_by_length(10) == 45 p find_fibonacci_index_by_length(100) == 476 p find_fibonacci_index_by_length(1000) == 4782 p find_fibonacci_index_by_length(10000) == 47847
true
b35efec2dd5c3e9ece32289c908a7f615ab6861c
Ruby
bean00/Ruby-Tic-Tac-Toe
/spec/view_spec.rb
UTF-8
2,131
3.28125
3
[]
no_license
require 'board' require 'view' describe 'display_board' do let(:b) { Board.new(3) } context 'when all positions are "x"s' do it 'displays a formatted board' do b.move(1, "X") b.move(2, "X") b.move(3, "X") b.move(4, "X") b.move(5, "X") b.move(6, "X") b.move(7, "X") b.move(8, "X") b.move(9, "X") v = View.new(b.to_string_array) formatted_board = " X | X | X \n" + "---+---+---\n" + " X | X | X \n" + "---+---+---\n" + " X | X | X \n" + "\n" expect{v.display_board}.to output(formatted_board).to_stdout end end context 'when all positions are empty' do it 'displays a formatted board' do v = View.new(b.to_string_array) formatted_board = " 1 | 2 | 3 \n" + "---+---+---\n" + " 4 | 5 | 6 \n" + "---+---+---\n" + " 7 | 8 | 9 \n" + "\n" expect{v.display_board}.to output(formatted_board).to_stdout end end context 'when positions are mixed' do it 'displays a formatted board' do b.move(5, "X") b.move(1, "O") b.move(9, "X") b.move(6, "O") v = View.new(b.to_string_array) formatted_board = " O | 2 | 3 \n" + "---+---+---\n" + " 4 | X | O \n" + "---+---+---\n" + " 7 | 8 | X \n" + "\n" expect{v.display_board}.to output(formatted_board).to_stdout end end end describe 'update_view' do context 'when an array of strings is passed in' do it 'sets the board' do b = Board.new(3) v = View.new(b.to_string_array) b.move(3, "X") b.move(4, "O") board_array = b.to_string_array expected_array = ["" , "", "X", "O", "", "", "", "", ""] expect(v.update_view(board_array)).to eq(expected_array) end end end
true
ff23b6a5f2414bc5af5e7d3fdaea1990b1c03c71
Ruby
pctj101/write_xlsx
/lib/write_xlsx.rb
UTF-8
1,948
2.96875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- require 'write_xlsx/workbook' # # write_xlsx is gem to create a new file in the Excel 2007+ XLSX format, # and you can use the same interface as writeexcel gem. # write_xlsx is converted from Perl’s module github.com/jmcnamara/excel-writer-xlsx . # # == Description # The WriteXLSX supports the following features: # # Multiple worksheets # Strings and numbers # Unicode text # Rich string formats # Formulas (including array formats) # cell formatting # Embedded images # Charts # Autofilters # Data validation # Hyperlinks # Defined names # Grouping/Outlines # Cell comments # Panes # Page set-up and printing options # WriteXLSX uses the same interface as WriteExcel gem. # # == Synopsis # To write a string, a formatted string, a number and a formula to the # first worksheet in an Excel XMLX spreadsheet called ruby.xlsx: # # require 'rubygems' # require 'write_xlsx' # # # Create a new Excel workbook # workbook = WriteXLSX.new('ruby.xlsx') # # # Add a worksheet # worksheet = workbook.add_worksheet # # # Add and define a format # format = workbook.add_format # Add a format # format.set_bold # format.set_color('red') # format.set_align('center') # # # Write a formatted and unformatted string, row and column notation. # col = row = 0 # worksheet.write(row, col, "Hi Excel!", format) # worksheet.write(1, col, "Hi Excel!") # # # Write a number and a formula using A1 notation # worksheet.write('A3', 1.2345) # worksheet.write('A4', '=SIN(PI()/4)') # workbook.close # # == Other Methods # # see Writexlsx::Workbook, Writexlsx::Worksheet, Writexlsx::Chart etc. # class WriteXLSX < Writexlsx::Workbook if RUBY_VERSION < '1.9' $KCODE = 'u' end end class WriteXLSXInsufficientArgumentError < StandardError end class WriteXLSXDimensionError < StandardError end class WriteXLSXOptionParameterError < StandardError end
true
fe1777706c7553ed8ed49da36590a29fa0a8b34a
Ruby
sato0208/Ruby_lesson
/lesson5/lesson5_2_2.rb
UTF-8
439
3.609375
4
[]
no_license
# ハッシュを使った繰り返し処理 currencies = ['japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'] currencies.each do |key, value| puts "#{key} : #{value}" end # ブロック引数を一つにするとキーと値が配列に格納されます currencies ={'japan' => 'yen', 'us' => 'dollar', 'india' => 'rupee'} currencies.each do |key_vaule| key = key_vaule[0] value = key_vaule[1] puts "#{key} : #{value}" end
true
68d337c02b7837f15b4fe422af1b8e3ed668509b
Ruby
exp-ndrew/survey
/main.rb
UTF-8
494
2.546875
3
[]
no_license
require './cli/helper_cli' @current_survey = nil @current_question = nil @current_user = nil def main_menu header puts "T > Take a survey!" puts "A > Create a survey!" puts "E > Edit a survey!" puts "D > Delete a survey" puts "V > View survey results" puts "X > Exit" case gets.chomp.upcase when 'T' user_login when 'A' create_survey when 'E' edit_survey when 'D' delete_survey when 'V' list_responses when 'X' exit end end main_menu
true
2e84969ca11ca3aa684b94d93d276cbb8ef5ba02
Ruby
OursDavid/Exercice-Scrapper
/lib/mairie-christmas.rb
UTF-8
871
2.859375
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' def get_townhall_email(townhall_url) page = Nokogiri::HTML(URI.open(townhall_url)) commune = page.css("body > div > main > section.text-center.well.well-sm > div > div > div > h1").text email= page.xpath('//*[contains(text(),"@")]').text.split arr =[] arr << {commune => email.join(" ")} return arr end #print get_townhall_email('https://www.annuaire-des-mairies.com/95/avernes.html') def get_townhall_urls page = Nokogiri::HTML(URI.open('https://www.annuaire-des-mairies.com/val-d-oise.html')) all_url = [] urls = page.xpath('//*[@class="lientxt"]//@href') urls.each{|m| result = "https://www.annuaire-des-mairies.com#{m.text[1..-1]}" all_url << result } return all_url end def perform email = get_townhall_urls result = [] email.each{|m| puts get_townhall_email(m) } end print perform
true
419918ee40d94422639d4713d33b681a72d4fa3d
Ruby
tibbon/battle
/lib/battle/player.rb
UTF-8
1,407
3.28125
3
[]
no_license
# Player # represents a player for the game, human or computer class Player attr_accessor :money, :troops, :camp INITIAL_SOLDIERS = 1 INITIAL_SCOUTS = 0 def initialize(money: 100) @money = money @troops = [] initialize_camp initialize_army end def to_s "Money: #{money} \n" + army_status + "\n" + @camp.position_string end def display_reports(world) puts map_near_camp(world) end def camp_troops troops.select do |troop| troop.x == camp.location[:x] && troop.y == camp.location[:y] end end def map_near_camp(world) # Most of these concerns feel out of place. Too much here blank_map = Array.new(World::MAP_X_SIZE) do Array.new(World::MAP_Y_SIZE) { Location.new('?') } end info = world.full_map.nearby(camp.location[:x], camp.location[:y], 1) blank_map = blank_map.overlay(camp.location[:x], camp.location[:y], info) blank_map.map do |row| row.map(&:tile_type).join(' ') end end def army_status troops.map(&:to_s).join("\n") end private def initialize_camp @camp = Camp.new end def initialize_army troops.concat(Array.new(INITIAL_SCOUTS) do Scout.new(x: @camp.location[:x], y: @camp.location[:y]) end) troops.concat(Array.new(INITIAL_SOLDIERS) do Soldier.new(x: @camp.location[:x], y: @camp.location[:y]) end) end end
true
b940f7507510034361cee3f507b8736ed1b88e32
Ruby
thebravoman/software_engineering_2015
/c13_trees_2.0_before_ast/A_19_Nikolay_Rangelov.rb
UTF-8
368
2.578125
3
[]
no_license
require 'rexml/document' include REXML xml_file = File.new("A_19_Nikolay_Rangelov.xml"); xml_doc = Document.new(xml_file); xml_doc.root.elements.each do |school| puts school.attributes["name"] school.elements.each do |school_class| puts "- " + school_class.attributes["name"] school_class.elements.each do |student| puts "-- " + student.text end end end
true
55144516f7f488225a46de3166050257f79ae04d
Ruby
apoc64/know_me
/lib/router.rb
UTF-8
4,340
3
3
[]
no_license
require 'pry' require_relative 'file_io' require_relative 'game' class Router attr_reader :should_continue def initialize @hello_counter = -1 @total_counter = 0 @should_continue = true @response_code = 200 @game = nil @req = nil @cm = nil end def response(request) @total_counter += 1 @req = request html_body = parse_path assemble_response_string(html_body) end def parse_path(req = @req) case req.path when "/" then debug(req) when "/hello" then hello_counter when "/datetime" then date_time when "/shutdown" then shutdown when "/word_search" then word_search(req.parameters["word"]) when "/start_game" then start_game(req) when "/game" then game when "/force_error" then force_error when "/sleepy" then sleepy else not_found end end def assemble_response_string(html_body) out = output(html_body) headers(out.length) + out end def output(html_body) "<html><head></head><body>#{html_body}</body></html>" end def headers(length, rc = @response_code) @response_code = 200 case rc when 200 then normal_header(length) when 302 then redirect_header(length) when 301 then normal_header(length, "301 Moved Permanently") #redirect ??? instructions/good luch ? when 401 then normal_header(length, "401 Unauthorized") when 403 then normal_header(length, "403 Forbidden") when 404 then normal_header(length, "404 Not Found") when 500 then normal_header(length, "500 Internal Server Error") end end def normal_header(length, info = "200 ok") (["http/1.1 #{info}"] + additional_headers(length)).join("\r\n") end def redirect_header(length) rh = ["http/1.1 302 Found", "Location: http://localhost:9292/game"] (rh + additional_headers(length)).join("\r\n") end def additional_headers(length) ["date: #{Time.now.strftime('%a, %e %b %Y %H:%M:%S %z')}", "server: ruby", "content-type: text/html; charset=iso-8859-1", "content-length: #{length}\r\n\r\n"] end def hello_counter @hello_counter += 1 "<h1>Hello, World! (#{@hello_counter})</h1>" end def date_time "<h1>#{Time.now.strftime('%I:%M%p on %A, %B %d, %Y')}</h1>" end def debug(req) response = "Verb: " + req.verb if req.verb response += "\nPath: " + req.path if req.path response += "\nProtocol: " + req.protocol if req.protocol response += "\nHost: " + req.host response += "\nPort: " + req.port response += "\nOrigin: " + req.origin response += "\nAccept: " + req.accept response = "<pre>" + response + "</pre>" end def shutdown @should_continue = false "<h1>Total Requests: #{@total_counter}</h1>" end def word_search(word) #grep? #require json? .. to_json pretty return "<h1>Not a valid word</h1>" if word.nil? accept_json = @req.accept.include?("application/json") if complete_me.include_word?(word) html = "<h1>#{word.upcase} is a known word</h1>" json = '{"word":"' + word + '","is_word":true}' accept_json ? json : html else html = "<h1>#{word.upcase} is not a known word</h1>" matches = complete_me.suggest(word) json = '{"word":"' + word + '","possible_matches":' + matches.to_s + '}' accept_json ? json : html end end def complete_me #so it doesn't have to keep reloading if @cm.nil? #memoization io = FileIO.new @cm = io.complete_me else @cm end end def start_game(req = @req) return "<h1>Must POST to start a game</h1>" if req.verb != "POST" if @game.nil? @game = Game.new @response_code = 301 "<h1>Good luck!</h1>" else @response_code = 403 "<h1>Game already running</h1>" end end def game(req = @req) return "<h1>You need to start a game first</h1>" if @game.nil? if (req.verb == "POST") && (req.body_params["guess"]) guess = req.body_params["guess"] @game.guess(guess) @response_code = 302 elsif req.verb == "GET" "<h1>" + @game.evaluate_guess + "</h1>" end end def not_found @response_code = 404 "<h1>Not Found 404</h1>" end def force_error @response_code = 500 call = caller "<p>#{call.join}</p>" end def sleepy sleep(3) "<h1>yawn...</h1>" end end
true
e7cc9d8d3358ec22b87f23220989e3e68dec0712
Ruby
clees227/rubypractice
/ProjectEuler/digit5thpowers.rb
UTF-8
437
3.328125
3
[]
no_license
#Problem 30 startTime = Time.now total = 0 totNums = 0 nums = [] #Honestly, the bounds were guess and check (2...300000).to_a.each do |num| sum = 0 num.to_s.each_char {|c| sum += (c.to_i ** 5)} if sum == num totNums += 1 nums << num end end nums.each{|i| total += i} endTime = Time.now puts "Answer: Total Nums : #{totNums} Total : #{total}" puts "Start Time: #{startTime}\nEnd Time: #{endTime}\nTotal Time: #{endTime-startTime}"
true
dd05aea52b317a23446dc1f604b00b9bb608bdc7
Ruby
alexmalus/Codility_code_dojo
/counting_elems/max_counters.rb
UTF-8
629
3.796875
4
[ "MIT" ]
permissive
# https://app.codility.com/programmers/lessons/4-counting_elements/max_counters/ # array A of M integers # output: array of integers with value of counters. # N and M are integers within the range [1..100,000]; # each element of array A is an integer within the range [1..N + 1]. def solution(number, arr) max = 0 counters = Array.new(number, max) arr.each do |el| if el <= number counters[el - 1] += 1 max = counters[el - 1] if max < counters[el - 1] else counters = Array.new(number, max) end end counters end # p solution(5, [3, 4, 4, 6, 1, 4, 4]) p solution(1, [1, 2, 1, 2, 1, 2])
true
73473b4ee10753d67238f49bd532b882b9c96efc
Ruby
dsaenztagarro/interpreter
/lib/interpreter.rb
UTF-8
658
3.328125
3
[]
no_license
Dir[File.join(".", "lib/**/*.rb")].each do |f| require f end ## # This class translate a block message into a String message # # Reader and Translator ared loaded using dependency injection # Reader translates the block message into a system "control information" # Translator takes the "control information" to build the String message class Interpreter def initialize(reader=Reader, translator=Translator.new, &message) @reader = reader @translator = translator @control_information = @reader.read(&message).output if message end def output @translator.translate(@control_information) if not @control_information.nil? end end
true
bd5621e5a56d57a89ac8bb3a67a7361f60e90603
Ruby
aaronsweeneyweb/boris-bikes
/spec/docking_station_spec.rb
UTF-8
861
2.671875
3
[]
no_license
require 'docking_station' describe DockingStation do it { is_expected.to respond_to :release_bike } docking_station = DockingStation.new bike = Bike.new docking_station.docks_bike(bike) bike1 = docking_station.release_bike describe bike1 do it { is_expected.to respond_to :working?} end it { is_expected.to respond_to(:docks_bike).with(1).argument } docking_station.docks_bike(bike) describe docking_station.bikes do it { is_expected.to include(bike)} end it "should raise an error when there are no more bikes available" do expect {subject.release_bike}.to raise_error("No more bikes available") end it "should raise an error when the docking station is full" do b = Bike.new subject.docks_bike(b) expect {21.times{subject.docks_bike(Bike.new)}}.to raise_error("Docking Station is full") end end
true
a0b9e0d12c6706da68f1df86b2448f4cd26e7f81
Ruby
acquia/sf-sdk-ruby
/lib/sfrest/site_update_priority.rb
UTF-8
1,190
2.546875
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true module SFRest # We need to keep this naming due to the way connection.rb autoloads things. # rubocop: disable Naming/ClassAndModuleCamelCase # Manage the site update priority feature. class Site_update_priority # rubocop: enable Naming/ClassAndModuleCamelCase # @param [SFRest::Connection] conn def initialize(conn) @conn = conn end # Get current site update priority. # # @return [Array] an array of the current site update priority. def current_update_priority @conn.get('/api/v1/site-update-priority') end # Set the site update priority list. # @param [Array] site node ids in the desired update order. # # @return [Array] an array containing the message given by the server. def change_update_priority(priority) payload = { 'priority' => priority }.to_json @conn.put('/api/v1/site-update-priority', payload) end # Reset the site update priority to the default. # # @return [Array] an array containing the message given by the server. def reset_update_priority @conn.delete('/api/v1/site-update-priority') end end end
true
f902b4af7cb10f517ffc892bdf471bc42b1a8d5f
Ruby
mogest/prawn-svg
/lib/prawn/svg/gradients.rb
UTF-8
1,142
2.59375
3
[ "MIT" ]
permissive
module Prawn::SVG class Gradients def initialize(document) @document = document @gradients_by_id = {} end def [](id) id &&= id.strip return unless id && id != '' if element = @gradients_by_id[id] element elsif raw_element = find_raw_gradient_element_by_id(id) create_gradient_element(raw_element) end end def []=(id, gradient) @gradients_by_id[id] = gradient end private def find_raw_gradient_element_by_id(id) raw_element = find_raw_element_by_id(id) raw_element if gradient_element?(raw_element) end def create_gradient_element(raw_element) Elements::Gradient.new(@document, raw_element, [], new_state).tap(&:process) end def find_raw_element_by_id(id) REXML::XPath.match(@document.root, %(//*[@id="#{id.gsub('"', '\"')}"])).first end def gradient_element?(raw_element) Elements::TAG_CLASS_MAPPING[raw_element.name.to_sym] == Elements::Gradient end def new_state State.new.tap do |state| state.viewport_sizing = @document.sizing end end end end
true
c1ba23ccc3bb910ee4289eb27e3f05d7ed22296f
Ruby
team-umlaut/umlaut
/app/controllers/umlaut_configurable.rb
UTF-8
16,283
2.625
3
[ "MIT" ]
permissive
# meant to be included in _controllers_, to get an # umlaut_config method as a class_attribute (avail on class, overrideable # on instance), exposed as helper method too, # that has a Confstruct configuration object that starts out # holding global config. (right now via a direct refernce to the global # one). require 'confstruct' module UmlautConfigurable extend ActiveSupport::Concern included do class_attribute :umlaut_config helper_method :umlaut_config self.umlaut_config = Confstruct::Configuration.new end # Used for `resolve_sections` config, like an Array but # we add a some custom methods into the resolve_sections array, # insert_section, remove_section. With a sub-class. class ResolveSectionsArray < Array # Deprecated. This was a silly confusing way to do this. # See #remove and #insert below instead. def ensure_order!(first, second) $stderr.puts "resolve_sections.ensure_order! is deprecated, please see resolve_sections.remove and resolve_sections.insert" list = self index1 = list.index {|s| s[:div_id].to_s == first.to_s} index2 = list.index {|s| s[:div_id].to_s == second.to_s} (list[index1], list[index2] = list[index2], list[index1]) if index1 && index2 && (index1 > index2) list end # Insert a section_config hash before or after an existing # section, by the existing section's div_id # # resolve_sections.insert_section({:div_id => "new"}, :after => "fulltext") # resolve_sections.insert_section( resolve_sections.remove_section("document_deliver"), :before => "fulltext") def insert_section(section_config, options = {}) list = self if options[:before] i = (list.find_index {|s| s[:div_id].to_s == options[:before].to_s}) || 0 list.insert(i, section_config) elsif options[:after] i = (list.find_index {|s| s[:div_id].to_s == options[:after].to_s}) || (list.length - 1) list.insert(i + 1, section_config) else # just add at end of list list << section_config end end # Remove a configuration block with a certain div_id from the configuration entirely, # returning the removed configuration block (or nil if none exists). # You can re-insert it with #insert if you like. def remove_section(div_id) list = self i = list.find_index {|s| s[:div_id].to_s == div_id.to_s} return list.delete_at(i) if i end # Make deep_dup work def deep_dup self.class.new.concat super end # Make map work returning same class, to avoid breaking Hashie::Mash. # Bah, this is a mess, yep. def map(*args, &block) self.class.new.concat super end alias_method :collect, :map end # Call as UmlautConfigurable.set_default_configuration!(confstruct_obj) # to initialize def self.set_default_configuration!(configuration) configuration.configure do app_name 'Find It' # Different navbar title? Defaults to app_name header_title deferred! {|c| c.app_name} # URL to image to use for link resolver, OR name of image asset in local app. #link_img_url "http//something" # string used in standard layout footer to identify your app. # mark it html_safe if it includes html # footer_credit "Find It service provided by <a href='http://www.university.edu/'>My University</a>".html_safe # Sometimes Umlaut sends out email, what email addr should it be from? from_email_addr 'no_reply@umlaut.example.com' layout "umlaut" resolve_layout deferred! {|c| c.layout} search_layout deferred! {|c| c.layout} # help url used on error page and a few other places. # help_url "http://www.library.jhu.edu/services/askalib/index.html" # Minimum height and width of browser window. We have little control over # what size a content provider generates a window for a link resolver. Often # it's too small for umlaut. So we resize in js, if these config params # are given. Set to 0 to disable. # Sadly, only some browsers let us resize the browser window, so this # feature only works in some browsers. minimum_window_width 820 minimum_window_height 400 # rfr_ids used for umlaut generated pages. rfr_ids do opensearch "info:sid/umlaut.code4lib.org:opensearch" citation "info:sid/umlaut.code4lib.org:citation" azlist 'info:sid/umlaut.code4lib.org:azlist' end # If you have a test umlaut set up at another location to stage/test # new features, link to it here, and a helper method in default # layout will provide a subtle debugging link to it in footer, # for current OpenURL. # test_resolve_base "http://app01.mse.jhu.edu/umlaut_dev" opensearch_short_name deferred! {|c| "Find Journals with #{c.app_name}" } opensearch_description deferred! {|c| "Search #{c.app_name} for journal names containing your term"} # Referent filters. Sort of like SFX source parsers. # hash, key is regexp to match a sid, value is filter object # (see lib/referent_filters ) add_referent_filters!( :match => /.*/, :filter => DissertationCatch.new ) # skip_resolve_menu can be used to control 'direct' linking, skipping # the resolve menu to deliver a full text link or other resource # directly to the user. # Possible values: # false : [default] Never skip menu # A hash with one or more keys.... # {:service_types => ['fulltext']} : list of service type values, if # they're present skip the menu with the first response available. # {:excluded_services => ['JH_HIP'] : list of service IDs, exclude responses # from these services for direct linking. (Not yet implemented) # {:excluded_urls => [/regexp/, 'string'] : list of regexps or strings, # exclude URLs that match this string from being skipped to. (Not yet implemented) # {:excluded_rfr_ids => ["info:sid/sfxit.com:citation", '"info:sid/umlaut.code4lib.org:citation"'] } # {:lambda => lambda {|p, l| return something}} : Not yet implemented. # lambda expression: A lambda expression can be provided that # should expect one argument, a hash with key :request # and value the Umlaut Request object. Return nil to # not skip menu, or a ServiceType join obj to skip # menu to that response. # A pretty typical direct-linking setup, excludes queries that come # from citation linker/azlist/opensearch from direct linking. # skip_resolve_menu {:service_types => ['fulltext'], #:services=>['JH_SFX'], :excluded_rfr_ids => ["info:sid/sfxit.com:citation", #'info:sid/umlaut.code4lib.org:citation', #'info:sid/umlaut.code4lib.org:azlist', #'info:sid/umlaut.code4lib.org:opensearch']} # # "umlaut.skip_resolve_menu" paramter can also be passed in per-request, with # 'true' or shortname of a service type. skip_resolve_menu false # How many seconds between updates of the background updater for background # services? poll_wait_seconds 2.0 # The FIRST AJAX callback for bg tasks should be much quicker. So we # get any bg tasks that executed nearly instantaneously, and on page # refresh when bg is really all loaded on back-end, but still needs JS to # fetch it. initial_poll_wait_seconds 0.250 # if a background service hasn't returned in this many seconds, consider # it failed. (May actually be slow, more likely raised an exception and # our exception handling failed to note it as failed.) background_service_timeout 30 # If a service has status FailedTemporary, and it's older than a # certain value, it will be re-queued in #serviceDispatch. # This value defaults to 10 times background_service_timeout, # but can be set in app config variable requeue_failedtemporary_services # If you set it too low, you can wind up with a request that never completes, # as it constantly re-queues a service which constantly fails. requeue_failedtemporary_services_in deferred! {|c| c.background_service_timeout * 10} # custom view template for resolve#index resolve_view nil # If OpenURL came from manual entry of title/ISSN, and no match is found in # link resolver knowledge base, display a warning to the user of potential # typo? entry_not_in_kb_warning true nightly_maintenance do # How old does a request have to be to be deleted by nightly_maintenance? # requests are only re-used within a session. Probably no reason to # change this. request_expire_seconds 1.day # How long to keep FAILED DispatchServices, for viewing problems/troubleshooting failed_dispatch_expire_seconds 4.weeks end resolve_display do # Where available, prefix links with year coverage summary # using ResolveHelper#coverage_summery helper. show_coverage_summary true end # Configuration for the 'search' functions -- A-Z lookup # and citation entry. search do # Is your SFX database connection, defined in database.yml under # sfx_db and used for A-Z searches, Sfx4 or do you want to use Sfx4Solr? # Other SearchMethods in addition to SFX direct db may be provided later. az_search_method SearchMethods::Sfx4 #az_search_method SearchMethods::Sfx4Solr::Local # When talking directly to the SFX A-Z list database, you may # need to set this, if you have multiple A-Z profiles configured # and don't want to use the 'default. sfx_az_profile "default" # Use your own custom search view? mention it here. #search_view "my_search" # can set to "_blank" etc. result_link_target nil end # config only relevant to SFX use sfx do # was: 'main_sfx_base_url' # base sfx url to use for search actions, error condition backup, # and some other purposes. For search actions (A-Z), direct database # connection to your SFX db also needs to be defined in database.yml # sfx_base_url 'http://sfx.library.jhu.edu:8000/jhu_sfx?' # # Umlaut tries to figure out from the SFX knowledge base # which hosts are "SFX controlled", to avoid duplicating SFX # urls with urls from catalog. But sometimes it misses some, or # alternate hostnames for some. Regexps matching against # urls can be included here. Eg, # additional_sfx_controlled_urls [ # %r{^http://([^\.]\.)*pubmedcentral\.com} # ] additional_sfx_controlled_urls [] # "web.archive.org" is listed in SFX, but that causes suppression # of MARC 856 tags from our catalog pointing to archive.org, which are # being used for some digitized books. We'd like to ignore that archive.org # is in SFX. Same for netlibrary. #sfx_load_ignore_hosts [/.*\.archive\.org/, /www\.netlibrary\.com/, 'www.loc.gov'] sfx_load_ignore_hosts [] end # config only relevant to holdings display holdings do # Holding statuses that should be styled as "Available" available_statuses ["Not Charged", "Available"] end # Output timing of service execution to logs log_service_timing (Rails.env == "development") # Execute service wave concurrently with threads? # Set to false to execute serially one after the other with # no threads instead. At this point, believed only useful # for debugging and analysis. threaded_service_wave true ##### # Pieces of content on a Resolve page can be declaritively configured. # Here are the defaults. You can add new elements to the resolve_sections # array in config and modify or delete existing resolve_sections elements. # # Look in comments at top of SectionRenderer class for what the keys # in each entry mean. # ResolveSectionsArray is like an Array, but with # some additional methods making it easier to do common # configuration tasks. resolve_sections ResolveSectionsArray.new ########## # # Names of these sections can be given in Rails i18n, under key # umlaut.display_sections.#{section_div_id}.title # If not given there, will be automatically calculated from # the display_name of the ServiceType Value included. # # Optional sub-head prompts can also be given in i18n, under # umlaut.display_sections.#{section_div_id}.prompt # ########### add_resolve_sections! do div_id "cover_image" partial "cover_image" visibility :responses_exist show_heading false show_spinner false end add_resolve_sections! do div_id "fulltext" html_area :main partial :fulltext show_partial_only true end add_resolve_sections! do div_id "audio" html_area :main visibility :responses_exist end add_resolve_sections! do div_id "holding" html_area :main partial 'holding' service_type_values ["holding","holding_search"] end add_resolve_sections! do div_id "document_delivery" html_area :main visibility :responses_exist #bg_update false end add_resolve_sections! do div_id "table_of_contents" html_area :main visibility :responses_exist end add_resolve_sections! do div_id "abstract" html_area :main visibility :responses_exist end add_resolve_sections! do div_id "help" html_area :sidebar bg_update false partial "help" show_heading false show_spinner false visibility :responses_exist end add_resolve_sections! do div_id "coins" html_area :sidebar partial "coins" service_type_values [] show_heading false show_spinner false bg_update false partial_html_api false end add_resolve_sections! do div_id "export_citation" html_area :sidebar visibility :in_progress end add_resolve_sections! do div_id "search_inside" html_area :sidebar partial "search_inside" show_partial_only true end add_resolve_sections! do div_id "excerpts" html_area :sidebar list_visible_limit 5 visibility :responses_exist end add_resolve_sections! do div_id "related_items" html_area :sidebar partial "related_items" # custom visibility, show it for item-level cites, # or if we actually have some visibility( lambda do |renderer| renderer.any_services? && (! renderer.request.title_level_citation?) || (! renderer.responses_empty?) end ) service_type_values ['cited_by', 'similar'] end add_resolve_sections! do div_id "highlighted_link" html_area :sidebar visibility :in_progress partial_locals( :show_source => true ) end add_resolve_sections! do div_id "service_errors" partial "service_errors" html_area :service_errors service_type_values [] end end end end
true
0209f3fa1567a411caad586b4f3ebf3ddd66bcf0
Ruby
Tkam13/atcoder-problems
/abc122/c.rb
UTF-8
326
2.9375
3
[]
no_license
n,q = gets.chomp.split.map(&:to_i) s = gets.chomp qs = q.times.map{gets.chomp.split.map(&:to_i)} array = Array.new(s.size,0) count = 0 1.upto(s.size-1) do |i| if s[i-1..i] == "AC" count += 1 array[i] = count else array[i] = count end end qs.each do |l,r| puts array[r-1] - array[l-1] end
true
66dfa6518aeda6622745e059ee7a5262302c173f
Ruby
marcelobarbosaO/avaliacao_desenvolvedor
/spec/models/sale_spec.rb
UTF-8
2,343
2.546875
3
[]
no_license
require 'rails_helper' describe Sale do describe '#save' do before do @customer = Customer.create!(customer_params) @address = Address.create!(address_params) @vendor = Vendor.create!(vendor_params) @sale = Sale.new(sale_params.merge({ customer: @customer, address: @address, vendor: @vendor })) end context 'validates' do context 'with customer and address and vendor' do it 'create sale' do expect{ @sale.save! }.to change { Sale.count }.by(1) end it 'sale is valid' do expect(@sale.valid?).to be_truthy end end context 'without customer' do before do @sale_without_customer = Sale.new(sale_params.merge({ address: @address, vendor: @vendor })) end it 'does not creates sale' do expect { @sale_without_customer.save }.to change { Sale.count }.by(0) end it 'sale is invalid' do expect(@sale_without_customer.valid?).to be_falsey end end context 'without address' do before do @sale_without_address = Sale.new(sale_params.merge({ customer: @customer, vendor: @vendor })) end it 'does not creates sale' do expect { @sale_without_address.save }.to change { Sale.count }.by(0) end it 'sale is invalid' do expect(@sale_without_address.valid?).to be_falsey end end context 'without vendor' do before do @sale_without_vendor = Sale.new(sale_params.merge({ customer: @customer, address: @address })) end it 'does not creates sale' do expect { @sale_without_vendor.save }.to change { Sale.count }.by(0) end it 'sale is invalid' do expect(@sale_without_vendor.valid?).to be_falsey end end end end def sale_params { description: 'Oferta nova de Cereal', quantity: 6, unit_price: 10.0} end def customer_params { name: "João Pedro" } end def address_params { name: "Rua Almirante Saboia" } end def vendor_params { name: "Bob's" } end end
true
3c6f9bc38c9a78e8e9d1c62aa5142fdf525b69d7
Ruby
blakewright1/learn-ruby
/Quizgame/question.rb
UTF-8
648
4.03125
4
[]
no_license
class Question #initializer run upon creation of a new Question def initialize(s, a, b, c, d, correct) @sentence = s @option1 = a @option2 = b @option3 = c @option4 = d @correct_answer = correct end def display_question puts @sentence puts "1: " + @option1 puts "2: " + @option2 puts "3: " + @option3 puts "4: " + @option4 end def take_answer print "\tYour answer: " answer = gets.chomp.to_i if answer == @correct_answer puts "correct!" return true else puts "incorrect, the correct answer was " + @correct_answer.to_s return false end end end
true
2d7329670ac5286b8625d6f3eb3c2f04c18db129
Ruby
sammarten/prag_studio_blocks_course
/enumerable/flyer.rb
UTF-8
1,588
3.546875
4
[]
no_license
class Flyer attr_reader :name, :email, :miles_flown attr_accessor :status def initialize(name, email, miles_flown, status=:bronze) @name = name @email = email @miles_flown = miles_flown @status = status end def to_s "#{name} (#{email}): #{miles_flown} - #{status}" end end flyers = [] flyers << Flyer.new("Larry", "larry@example.com", 4000, :platinum) flyers << Flyer.new("Moe", "moe@example.com", 1000) flyers << Flyer.new("Curly", "curly@example.com", 3000, :gold) flyers << Flyer.new("Shemp", "shemp@example.com", 2000) puts "Frequent Flyer Customers" puts flyers.select { |f| f.miles_flown >= 3000 } puts "---" puts "Need more incentives" puts flyers.select { |f| f.miles_flown < 3000 } puts "---" puts "Have any flyers achieve platinum status?" puts flyers.any? { |f| f.status == :platinum } puts "---" puts "First bronze status flyer to call" puts flyers.detect { |f| f.status == :bronze } puts "---" platinum, others = flyers.partition { |f| f.status == :platinum } puts "Platinum flyers" puts platinum puts "Others" puts others puts "---" puts flyers.map { |f| "#{f.name} (#{f.status.upcase})" } puts "---" puts flyers.map { |f| "#{f.name} - #{f.miles_flown * 1.6} kilometers"} puts "---" puts "Total Miles" puts flyers.map { |f| f.miles_flown }.reduce(:+) puts "---" puts "Total Kilometers" puts flyers.map { |f| f.miles_flown * 1.6 }.reduce(:+) puts "---" puts "Total Kilometers for Bronze members" puts flyers.select { |f| f.status == :bronze }.map { |f| f.miles_flown * 1.6 }.reduce(:+) puts "---" puts "Flyer with the Most Miles" puts flyers.max_by { |f| f.miles_flown }.name
true
2e3429f967f533e6ba3fc9c60ed1aa0fb753e2ee
Ruby
tmaher/corefoundation
/spec/extensions_spec.rb
UTF-8
3,018
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- coding: utf-8 -*- require 'spec_helper' describe 'extensions' do context 'with an integer' do it 'should return a cfnumber' do 1.to_cf.should be_a(CF::Number) end end context 'with a float' do it 'should return a cfnumber' do (1.0).to_cf.should be_a(CF::Number) end end context 'with a 8bit string' do it 'should be binary' do '123'.binary!.binary?.should be_true if CF::String::HAS_ENCODING '123'.encode(Encoding::ASCII_8BIT).binary?.should be_true else "\xff\xff\xff".binary?.should be_true end [0xff, 0xff, 0xff].pack("C*").binary?.should be_true end it 'should return a cf data' do if CF::String::HAS_ENCODING '123'.encode(Encoding::ASCII_8BIT).to_cf.should be_a(CF::Data) end '123'.binary!.to_cf.should be_a(CF::Data) [0xff, 0xff, 0xff].pack("C*").to_cf.should be_a(CF::Data) end it 'should return nil on garbage binary data flagged as text' do [0xff, 0xff, 0xff].pack("C*").binary!(false).to_cf.should be_nil end # the word "über" in utf-8 uber = [195, 188, 98, 101, 114] it 'should convert utf-8 to cf string' do uber.pack("C*").binary!(false).to_cf.should be_a(CF::String) if CF::String::HAS_ENCODING uber.pack("C*").force_encoding("UTF-8").to_cf.should be_a(CF::String) end end it 'should convert utf-8 flagged as binary to cf data' do uber.pack("C*").binary!.to_cf.should be_a(CF::Data) end end context 'with an asciistring' do it 'should be non-binary' do '123'.binary?.should be_false end it 'can round-trip' do '123'.binary!(true).binary!(false).binary?.should be_false end it 'should return a cf string' do '123'.to_cf.should be_a(CF::String) '123'.to_cf_string.should be_a(CF::String) end it 'should return cf data if asked nicely' do '123'.to_cf_data.should be_a(CF::Data) '123'.binary!.to_cf.should be_a(CF::Data) end end context 'with true' do it 'should return CF::Boolean::TRUE' do true.to_cf.should == CF::Boolean::TRUE end end context 'with false' do it 'should return CF::Boolean::FALSE' do false.to_cf.should == CF::Boolean::FALSE end end context 'with a time' do it 'should return a CFDate' do Time.now.to_cf.should be_a(CF::Date) end end context 'with an array' do it 'should return a cfarray containing cf objects' do cf_array = [true, 1, 'hello'].to_cf cf_array.should be_a(CF::Array) cf_array[0].should == CF::Boolean::TRUE cf_array[1].should be_a(CF::Number) cf_array[2].should == CF::String.from_string('hello') end end context 'with a dictionary' do it 'should return a cfdictionary containing cf objects' do cf_hash = {'key_1' => true, 'key_2' => false}.to_cf cf_hash['key_1'].should == CF::Boolean::TRUE cf_hash['key_2'].should == CF::Boolean::FALSE end end end
true
ab3a33f3dfaab73bf42adfa2077c936a14c9f6a8
Ruby
walterdavis/kno-ruby
/lib/kno.rb
UTF-8
2,393
2.59375
3
[ "Apache-2.0" ]
permissive
require 'erb' require 'faraday' module Kno class Helpers def initialize(persona_id, config) @persona_id = persona_id @config = config @template = """ <% if @persona_id %> <form action=\"/session/terminate\" method=\"post\"> <button type=\"submit\">Sign out</button> </form> <% else %> <form action=\"/session/new\" method=\"post\"> <script src=\"<%= @config.cdn_host %>/pass.js\" data-site=\"<%= @config.site_token %>\"></script> <button type=\"submit\">Sign in</button> </form> <% end %> """ end def session_button() ERB.new(@template).result(binding) end end class Config attr_reader :api_host, :api_token, :cdn_host, :site_token, :sign_in_redirect def initialize( api_host: "https://api.trykno.app", api_token: "API_AAAAAgDOxdmUqKpE9rw82Jj0Y6DM", cdn_host: "https://trykno.app", site_token: "site_UITYJw8kQJilzVnux5VOPw", sign_in_redirect: ) @api_host = api_host @api_token = api_token @cdn_host = cdn_host @site_token = site_token @sign_in_redirect = sign_in_redirect end end class API def initialize(config) @authenticate_url = format("%s/v0/authenticate", config.api_host) @api_token = config.api_token @headers = {"Content-Type" => "application/json", "Authorization" => "Basic " + Base64.encode64(config.api_token+":")} end def authenticate(kno_token) params = {token: kno_token} resp = Faraday.post(@authenticate_url, params.to_json(), @headers) if resp.status == 200 persona_id = JSON.parse(resp.body)['persona']['id'] else raise ArgumentError end end end class Session def initialize(app, options) @app = app @config = Kno::Config.new(options) @api = Kno::API.new(@config) end def call(env) req = Rack::Request.new(env) persona_id = req.session[:persona_id] env['kno'] = Helpers.new(persona_id, @config) if env['PATH_INFO'] == "/session/new" kno_token = req.params["knoToken"] persona_id = @api.authenticate(kno_token) req.session[:persona_id] = persona_id [303, {'location' => '/'}, nil] elsif env['PATH_INFO'] == "/session/terminate" req.session.clear [303, {'location' => "/"}, nil] else @app.call(env) end end end end
true
f143718ce78652b9d90346b73c12f992ba3885ca
Ruby
alanyeh20001/leetcode_ruby
/palindrome_number.rb
UTF-8
545
4.09375
4
[]
no_license
=begin Determine whether an integer is a palindrome. Do this without extra space. =end # @param {Integer} x # @return {Boolean} # 只 loop integer 長度的一半,依序比對第一&最後,第二&倒數第二...,如果有不相等的就直接 return false。 def is_palindrome(x) return false if x < 0 chars = x.to_s.chars length = chars.length result = true for i in 0..((length / 2.0).ceil - 1) do if chars[i] == chars[length - 1 - i] next else result = false break end end result end
true
b79eac8272f222dbd6ec98e710e138d62ef94185
Ruby
ttilberg/sequel
/lib/sequel/plugins/skip_saving_columns.rb
UTF-8
3,654
2.8125
3
[ "MIT" ]
permissive
# frozen-string-literal: true module Sequel module Plugins # The skip_saving_columms plugin allows skipping specific columns when # saving. By default, it skips columns that the database schema # indicates are generated columns: # # # Assume id column, name column, and id2 generated column # album = Album[1] # album.id # => 1 # album.name # => 'X' # album.id2 # => 2 # album.save # # UPDATE album SET name = 'X' WHERE (id = 1) # # You can override which columns will be skipped: # # Album.skip_saving_columns = [:name] # album.save # # UPDATE album SET id2 = 2 WHERE (id = 1) # # The skipping happens for all usage of Model#save and callers of it (e.g. # Model.create, Model.update). When using the plugin, the only way to get # it to save a column marked for skipping is to explicitly specify it: # # album.save(columns: [:name, :id2]) # album.save # # UPDATE album SET name = 'X', id2 = 2 WHERE (id = 1) # # Usage: # # # Support skipping saving columns in all Sequel::Model subclasses # # (called before loading subclasses) # Sequel::Model.plugin :skip_saving_columns # # # Support skipping saving columns in the Album class # Album.plugin :skip_saving_columns module SkipSavingColumns # Setup skipping of the generated columns for a model with an existing dataset. def self.configure(mod) mod.instance_exec do set_skip_saving_generated_columns if @dataset end end module ClassMethods # An array of column symbols for columns to skip when saving. attr_reader :skip_saving_columns # Over the default array of columns to skip. Once overridden, future # changes to the class's dataset and future subclasses will automatically # use these overridden columns, instead of introspecting the database schema. def skip_saving_columns=(v) @_skip_saving_columns_no_override = true @skip_saving_columns = v.dup.freeze end Plugins.after_set_dataset(self, :set_skip_saving_generated_columns) Plugins.inherited_instance_variables(self, :@skip_saving_columns=>:dup, :@_skip_saving_columns_no_override=>nil) private # If the skip saving columns has not been overridden, check the database # schema and automatically skip any generated columns. def set_skip_saving_generated_columns return if @_skip_saving_columns_no_override s = [] db_schema.each do |k, v| s << k if v[:generated] end @skip_saving_columns = s.freeze nil end end module InstanceMethods private # Skip the columns the model has marked to skip when inserting. def _insert_values _save_removed_skipped_columns(Hash[super]) end # Skip the columns the model has marked to skip when updating # all columns. def _save_update_all_columns_hash _save_removed_skipped_columns(super) end # Skip the columns the model has marked to skip when updating # only changed columns. def _save_update_changed_colums_hash _save_removed_skipped_columns(super) end # Remove any columns the model has marked to skip when saving. def _save_removed_skipped_columns(hash) model.skip_saving_columns.each do |column| hash.delete(column) end hash end end end end end
true
c2a45be467ea6fe37cb3802ebae58ab4d97af340
Ruby
davidrb/config
/status/rss
UTF-8
421
2.625
3
[]
no_license
#!/bin/env ruby require_relative 'color' require 'rss' require 'open-uri' # arch rss begin open('https://www.archlinux.org/feeds/news/') do |rss| feed = RSS::Parser.parse(rss) item = feed.items.first elapsed = ((Time.now - item.date)/60/60/24).to_i puts green("Arch News: #{feed.items.first.title}(#{elapsed} days ago)") end rescue puts red("could not open rss feed", "red") end
true
0879f1829ea78484b9e64131ff677e7f7c715397
Ruby
dbalatero/queue_stick
/lib/queue_stick/counter.rb
UTF-8
308
3.140625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module QueueStick class Counter attr_reader :name, :count def initialize(name, starting_value = 0) raise ArgumentError, 'Name must not be nil!' if name.nil? @name = name @count = starting_value end def increment!(by = 1) @count += by end end end
true
5f90514a3104528310863c814a82e110c024a1ad
Ruby
sensu-plugins/sensu-plugins-monit
/bin/check-monit-email.rb
UTF-8
3,133
2.84375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#! /usr/bin/env ruby # # check-monit-email.rb # # DESCRIPTION: # what is this thing supposed to do, monitor? How do alerts or # alarms work? # # OUTPUT: # plain text, metric data, etc # # PLATFORMS: # Linux, Windows, BSD, Solaris, etc # # DEPENDENCIES: # gem: sensu-plugin # gem: mail # # USAGE: # example commands # # NOTES: # Does it behave differently on specific platforms, specific use cases, etc # # LICENSE: # <your name> <your email> # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. # # !/usr/bin/env ruby require 'socket' require 'mail' require 'json' class ParseEmail def initialize @email = ARGF.read end def token @token ||= Mail.read_from_string(@email) end def body return @body if @body @body = "#{token.subject} ERROR BODY:#{token.body} ALERT:#{alert}" end def service return @service if @service service_string = token.body.match(/Service: .*/) @service = if service_string service_string.split(': ')[1] else token.subject.sub(/([^ ]+) *.*/, '\1') end end def alert return @alert if @alert alert_string = token.body.match(/Event: .*/) if alert_string @alert = alert_string.to_s.split(':')[1].strip else alert_string = token.body.to_s.split("\n")[0] @alert = alert_string.split(':')[-1].strip end end def failure? array_failure = [ 'Checksum failed', 'Connection failed', 'Content failed', 'Data access error', 'Execution failed', 'Filesystem flags failed', 'GID failed', 'ICMP failed', 'Monit instance changed', 'Invalid type', 'Does not exist', 'Permission failed', 'PID failed', 'PPID failed', 'Resource limit matched', 'Size failed', 'Status failed', 'Timeout', 'Timestamp failed', 'UID failed', 'Uptime failed', 'process is not running.' ] array_failure.include?(alert) end def recover? array_recovery = [ /^Checksum succeeded$/, /^Connection succeeded$/, /^Content succeeded$/, /^Data access succeeded$/, /^Execution succeeded$/, /^Filesystem flags succeeded$/, /^GID succeeded$/, /^ICMP succeeded$/, /^Monit instance changed not$/, /^Type succeeded$/, /^Exists$/, /^Permission succeeded$/, /^PID succeeded$/, /^PPID succeeded$/, /^Resource limit succeeded$/, /^Size succeeded$/, /^Status succeeded$/, /^Timeout recovery$/, /^Timestamp succeeded$/, /^UID succeeded$/, /^Uptime succeeded$/, /^process is running with pid \d+.$/ ] !array_recovery.find { |r| alert.match r }.nil? end def to_json { 'output' => body, 'name' => service, 'status' => alert_level, 'type' => 'monit' }.to_json end def alert_level if failure? 2 elsif recover? 0 else 3 end end end email = ParseEmail.new s = TCPSocket.new 'localhost', 3030 s.puts email.to_json s.close
true
8b96587ddbe7ec311e7344a2406fb9bc1154402d
Ruby
popsun007/Algorithms_and_Data_Structure
/power_of_three.rb
UTF-8
461
3.8125
4
[]
no_license
# @param {Integer} n # @return {Boolean} def is_power_of_three(n) if n < 1 return false end for i in 0...n if 3 ** i === n return true elsif 3 ** i > n break end end return false end #Math O(1): def is_power_of_three(n) test_num = Math.log10(n) / Math.log10(3) puts test_num % 1 === 0 end def is_power_of_three(n) test_num = Math.log(n) / Math.log(3) puts n === 3 ** test_num.round end is_power_of_three(243)
true
d9634b88fc37c9368833b7f02b152efe1ce7dd09
Ruby
mohammadaliawan/ls-prep
/ruby_basics_3rd/debugging/reading_error_msgs.rb
UTF-8
217
3.828125
4
[]
no_license
def find_first_nonzero_among(numbers) numbers.each do |n| return n if n.nonzero? end end # Examples p find_first_nonzero_among([0, 0, 1, 0, 2, 0]) # ArgumentError p find_first_nonzero_among(1)# NoMethodError
true
002ca897e28bc03c32fe24fcbc8c52d3fee16518
Ruby
alexreisner/smart_chart
/lib/smart_chart/charts/pie.rb
UTF-8
706
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module SmartChart class Pie < SingleDataSetChart # number of degrees to rotate start of first slice from 12 o'clock attr_accessor :rotate private # --------------------------------------------------------------- ## # Specify the Google Chart type. # def type case style.to_s when "concentric"; "pc" when "3d"; "p3" else "p" end end ## # Rotation. Google expects radians from 3 o'clock. # def chp r = rotate || 0 s = SmartChart.decimal_string( ((r - 90) % 360) * Math::PI / 180.0 ) s == "0" ? nil : s # omit parameter if zero end end end
true