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
f0dddbf80e4fc731627c14d6828406059713a567
Ruby
beaucouplus/programming_foundations
/exercises/delete_vowels.rb
UTF-8
630
4.46875
4
[]
no_license
# Write a method that takes an array of strings, and returns an array of the # same string values, except with the vowels (a, e, i, o, u) removed. # define an array of vowels to handle comparison # select every char from string which isn't a vowel # return the new string VOWELS = /[aeiouAEIOU]/ def remove_vowels(array) array.map { |string| string.gsub(VOWELS, "") } end p remove_vowels(%w(abcdefghijklmnopqrstuvwxyz)) p remove_vowels(%w(abcdefghijklmnopqrstuvwxyz)) == %w(bcdfghjklmnpqrstvwxyz) p remove_vowels(%w(green YELLOW black white)) == %w(grn YLLW blck wht) p remove_vowels(%w(ABC AEIOU XYZ)) == ['BC', '', 'XYZ']
true
4b81eba5b006c01a114fa81cbcf8e614dd9983b2
Ruby
barkinet/wistia-doc
/_plugins/indexer.rb
UTF-8
2,588
2.90625
3
[ "MIT" ]
permissive
require 'rubygems' require 'nokogiri' require 'tire' # Adapted from https://raw.github.com/PascalW/jekyll_indextank/master/indexer.rb && # https://github.com/jaysoo/jaysoo.ca/blob/master/_plugins/indexer.rb module Jekyll class Indexer < Generator attr_accessor :site def initialize(config = {}) super(config) Tire.configure do url config['elasticsearch_host'] end end def generate(site) # convenience, so we don't have to pass this around self.site = site print 'Indexing posts... ' exclude_from_search = site.config['exclude_from_search'] # get all the posts all_posts = site.posts. select{ |post| post.data['category'] != exclude_from_search }. map { |post| hash_for_post(post) } Tire.index 'posts' do # clear 'em all delete # some config stuff create :mappings => { :post => { :properties => { :id => { type: 'integer', index: 'not_analyzed', include_in_all: false }, :title => { type: 'string', analyzer: 'snowball', boost: '2.0' }, :text => { type: 'string', analyzer: 'snowball' }, :description => { type: 'string', analyzer: 'snowball', boost: '1.5' } } } } # add all posts to index import all_posts # stay cool refresh end puts 'done!' rescue Errno::ECONNREFUSED => e puts "elasticsearch isn't running FYI you idiot" end # returns the post as a hash suitable for jamming into elasticsearch! def hash_for_post(post) document = { :id => next_id, :title => post.data['title'], :text => text_for_post(post), :date => post.data['created_at'] || post.date.strftime('%Y-%m-%d %H:%MZ'), :url => post.url, :type => 'post', :description => post.data['description'] || "" } document['tags'] = post.tags if post.tags document['category'] = post.data['category'] if post.data.has_key?('category') document end # returns a string which is the raw text of the page def text_for_post(post) post.render(site.layouts, site.site_payload) doc = Nokogiri::HTML(post.output) doc.css('script').remove().css('#doc_nav').remove() # one line it doc.text.gsub(/[\r\n\s]+/," ") end # just makes IDs for posts def next_id @id ||= 0 @id += 1 end end end
true
0cf21ef4d50c41b5ee84a8643ea7a596f4026c6b
Ruby
saraemanuelsson/properties_lab
/models/property.rb
UTF-8
2,128
3.09375
3
[]
no_license
require('pg') class Property attr_accessor :address, :value, :square_footage, :build attr_reader :id def initialize(options) @id = options['id'].to_i if options['id'] @address = options['address'] @value = options['value'] @square_footage = options['square_footage'] @build = options['build'] end def save db = PG.connect( { dbname: 'properties', host: 'localhost' } ) sql = "INSERT INTO properties ( address, value, square_footage, build ) VALUES ($1,$2,$3,$4) RETURNING id" values = [@address, @value, @square_footage, @build] db.prepare("save", sql) @id = db.exec_prepared("save", values)[0]["id"].to_i db.close end def update() db = PG.connect( { dbname: 'properties', host: 'localhost' } ) sql = "UPDATE properties SET (address, value, square_footage, build) = ($1, $2, $3, $4) WHERE id = $5" values = [@address, @value, @square_footage, @build, @id] db.prepare("update", sql) db.exec_prepared("update", values) db.close() end def delete() db = PG.connect( { dbname: 'properties', host: 'localhost' } ) sql = "DELETE FROM properties WHERE id = $1" values = [@id] db.prepare("delete", sql) db.exec_prepared("delete", values) db.close() end def Property.find_by_field(field, value) db = PG.connect( { dbname: 'properties', host: 'localhost' } ) sql = "SELECT * FROM properties WHERE #{field} = $1" db.prepare("find", sql) property = db.exec_prepared("find", [value]) db.close() if property.num_tuples == 0 return nil else return Property.new(property[0]) end end def Property.find(id) Property.find_by_field("id", id) end def Property.find_by_address(address) Property.find_by_field("address", address) end end
true
7aa295c0f9314572308bac79b1732578b43fe974
Ruby
Mat24/Curso-Programacion-USC-2014
/Auditoria-USC/app/controllers/reportes_controller.rb
UTF-8
4,525
2.578125
3
[]
no_license
require 'prawn/table' class ReportesController < ApplicationController before_action :set_reporte, only: [:show, :edit, :update, :destroy] # GET /reportes # GET /reportes.json def index @reportes = Reporte.all respond_to do |format| format.html format.json format.csv {send_data @reportes.to_csv} format.pdf do pdf = ReportPdf.new(@reportes) send_data pdf.render, filename: "report_#{Time.now}.pdf", type: 'application/pdf' end end end # GET /reportes/1 # GET /reportes/1.json def show end # GET /reportes/new def new @reporte = Reporte.new end # GET /reportes/1/edit def edit end # POST /reportes # POST /reportes.json def create @reporte = Reporte.new(reporte_params) respond_to do |format| if @reporte.save format.html { redirect_to @reporte, notice: 'Reporte was successfully created.' } format.json { render :show, status: :created, location: @reporte } else format.html { render :new } format.json { render json: @reporte.errors, status: :unprocessable_entity } end end end # PATCH/PUT /reportes/1 # PATCH/PUT /reportes/1.json def update respond_to do |format| if @reporte.update(reporte_params) format.html { redirect_to @reporte, notice: 'Reporte was successfully updated.' } format.json { render :show, status: :ok, location: @reporte } else format.html { render :edit } format.json { render json: @reporte.errors, status: :unprocessable_entity } end end end # DELETE /reportes/1 # DELETE /reportes/1.json def destroy @reporte.destroy respond_to do |format| format.html { redirect_to reportes_url, notice: 'Reporte was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_reporte @reporte = Reporte.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def reporte_params params.require(:reporte).permit(:numero_estudiantes, :docente_id, :comentario, :asignatura_id) end end #----------------------------------------------------------------------------------------------------------------------- #Clase para Generar PDFs #----------------------------------------------------------------------------------------------------------------------- class ReportPdf < Prawn::Document def initialize(products) super() @products = products header text_content table_content end def header #inserta una imagen en el documento, en este caso es la cabezera de nuestro reporte image "#{Rails.root}/app/assets/images/usclogo.jpg", width: 80, height: 80 #inserta texto posicionado, en este caso es el texto de cabezera draw_text "Universidad Santiago De Cali", size: 20, style: :bold, :at => [81,695] draw_text "Generador de reportes - NotesTest V=1.0", size: 15, :at => [81,680] draw_text "Aplicacion creada por:", size: 15, :at => [81,665] draw_text "Mateo Aya sobre RoR", size: 15, style: :bold, :at => [230,665] draw_text "Software guia para los estudiantes del curso de programacion WEB", size: 12, style: :bold, :at => [65,600] draw_text "Espero que esto sea de apoyo y motivacion en su proceso de aprendizaje", size: 12, style: :bold, :at => [55,590] end def text_content # fijamos el cursor donde se emprezara a escribir el contenido de nuestro reporte y_position = cursor - 90 # Como ejemplo encapsulo el texto de la cabezera de la tabla de reportes bounding_box([0, y_position], :width => 270) do text "Listado de reportes", size: 15, style: :bold end bounding_box([280, y_position], :width => 270) do text "Feha: #{Time.now}", size: 10, style: :italic end end def table_content # Agrego estilos a las filas de la tabla table product_rows do row(0).font_style = :bold self.header = true self.row_colors = ['DDDDDD', 'FFFFFF'] end end def product_rows # Creo la 'data' de todo el contenido que ca a ir en la tabla [['Nº Reporte', 'Asignatura','Codigo','Nº Estudiantes', 'Docente','Comentario']] + @products.map do |product| [product.id, product.asignatura.nombre,product.asignatura.codigo,product.numero_estudiantes, product.docente.nombre,product.comentario] end end end
true
b8edcc15ed391345172fc5114903f4c54e864764
Ruby
jwass91/flatiron_labs
/hs-oo-stretch-challenges-lab-precollege-se1-nyda-061515-1-master/lib/path.rb
UTF-8
581
3.28125
3
[]
no_license
class Path attr_accessor :path def initialize(path) # Notice the power of an objects @path = path # properties. Because the object stores # the path variable, we no longer need to # pass it around to all the other methods # that rely on it. end def normalize_path "#{"#{Dir.pwd}/" if relative_path?}#{path}" end def relative_path? !absolute_path? end def absolute_path? path.start_with?("/") end end test = Path.new(" ../../") puts test # .absolute_path?
true
9f905a90030416600300228cffa5d868b3d8f3eb
Ruby
DanielOrtegaCar/ManejodeMemoriaVirtual
/ruby/hlTablaPagina.rb
UTF-8
851
3.203125
3
[]
no_license
#!usr/bin/ruby load 'EntradaTP.rb' class TablaPagina def initialize(cantidad, cantidad_marcos_de_pagina) @marco_actual = 0 @puntero_LRU = 0 @contador_de_fallos = 0 @cantidad_marcos_disponibles = cantidad_marcos_de_pagina @tamano = cantidad @tamano_mp = cantidad_marcos_de_pagina @entrada = Array.new(cantidad, EntradaTP.new) #esta wea no se ocupa @marcos_libres = Array.new(cantidad_marcos_de_pagina, false) end def get_entrada(posicion) if @posicion < @tamano return @entrada[posicion] else puts "indice fuera de rango" end end def imprimir @entrada.each{|x| puts "V: #{x.v}, R: #{x.r}, Nmp:#{x.nmp}"} end def circular @marco_actual += 1 return @marco_actual % @tamano end def circular_LRU @puntero_LRU += 1 return @puntero_LRU % @tamano end end tabla = TablaPagina.new(32, 16) tabla.imprimir
true
8dfcfca96c507380e5519f365b46a04b2de78081
Ruby
matin/pdf-reader
/lib/pdf/reader/explore.rb
UTF-8
3,861
2.5625
3
[ "MIT" ]
permissive
################################################################################ # # Copyright (C) 2006 Peter J Jones (pjones@pmade.com) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ################################################################################ require 'pathname' class PDF::Reader ################################################################################ class Explore ################################################################################ def self.file (name) PDF::Reader.new.parse(File.open(name), self) end ################################################################################ def initialize (receiver, xref) @xref = xref @pwd = '/' end ################################################################################ def document (root) @root = root self end ################################################################################ def output_parent (obj) case obj when Hash obj.each do |k,v| print "#{k}"; output_child(v); print "\n" Explore::const_set(k, k) if !Explore.const_defined?(k) end when Array obj.each_with_index {|o, i| print "#{i}: "; output_child(o); print "\n"} else output_child(obj) print "\n" end end ################################################################################ def output_child (obj) print ": #{obj.class}" case obj when Float print ": #{obj}" when String print ": #{obj[0, 20].sub(/\n/, ' ')}" end end ################################################################################ def cd (path) path = path.to_s if path[0,1] == "/" @pwd = path else @pwd = Pathname.new(@pwd + '/' + path).cleanpath.to_s end end ################################################################################ def pwd @pwd end ################################################################################ def ls (entry = nil) parts = @pwd.split('/') obj = @root parts.shift if parts[0] == "" parts.push(entry) if entry parts.each do |p| case obj when Hash unless obj.has_key?(p) puts "invalid path at #{p}" return end obj = obj[p] when Array obj = obj[p.to_i] end obj = @xref.object(obj) end output_parent(obj) "#{@pwd}: #{obj.class}" end ################################################################################ end ################################################################################ end ################################################################################
true
220ca1d387e453faf0f1ded913d7d38c341dbc07
Ruby
benjamintillett/airports
/spec/airport_spec.rb
UTF-8
3,531
3.40625
3
[]
no_license
require 'airport' require 'plane' require 'weather_spec' # A plane currently in the airport can be requested to take off. # # No more planes can be added to the airport, if it's full. # It is up to you how many planes can land in the airport and how that is impermented. # # If the airport is full then no planes can land describe Airport do include_examples "the weather" let(:airport) { Airport.new } let(:plane) { double :plane } let(:full_airport) { Airport.new } let(:half_full_airport) { Airport.new } before do fill_airport(full_airport) end context "self knowlage: " do it 'knows when its full' do expect(full_airport).to be_full end it 'knows when its not full' do expect(half_full_airport).not_to be_full end end context 'taking off and landing' do before { allow_any_instance_of(Airport).to receive(:stormy?).and_return( false) } it 'Can land a plane' do expect(airport.land(plane)).not_to eq nil end it 'has the plane after landing' do airport.land(plane) expect(airport).to have_plane(plane) end it 'will not land a plane if full' do expect(full_airport.land(plane)).to eq nil end it "does not have plane after failed landing attempt" do full_airport.land(plane) expect(airport).not_to have_plane(plane) end it 'can take off a plane' do airport.land(plane) expect(airport.take_off(plane)).to eq plane end it 'does not have the plane after take off' do airport.take_off(plane) expect(airport).not_to have_plane(plane) end it 'can not take off if plane is not in airport' do expect(airport.take_off(plane)).to eq nil end end context 'traffic control' do # Include a weather condition using a module. # The weather must be random and only have two states "sunny" or "stormy". # Try and take off a plane, but if the weather is stormy, the plane can not take off and must remain in the airport. # # This will require stubbing to stop the random return of the weather. # If the airport has a weather condition of stormy, # the plane can not land, and must not be in the airport context 'stormy weather:' do before { allow_any_instance_of(Airport).to receive(:stormy?).and_return( true ) } it 'a plane cannot take off' do airport.land(plane) expect(airport.take_off(plane)).to be nil end it 'a plane cannot land' do expect(airport.land(plane)).to be nil end end context 'good weather:' do before { allow_any_instance_of(Airport).to receive(:stormy?).and_return( false ) } it 'a plane can take off' do airport.land(plane) expect(airport.take_off(plane)).to eq plane end it 'a plane can land' do expect(airport.land(plane)).not_to eq nil end end end end # grand final # Given 6 planes, each plane must land. When the airport is full, every plane must take off again. # Be careful of the weather, it could be stormy! # Check when all the planes have landed that they have the right status "landed" # Once all the planes are in the air again, check that they have the status of flying! describe "The gand finale (last spec)" do it 'all planes can land and all planes can take off' do end end def fill_airport(airport) airport.capacity.times do allow(full_airport).to receive(:stormy?).and_return(false) full_airport.land(double :plane) end end
true
1c5e4e84cc36c5fd19806d0fe92f6517f06e0880
Ruby
sankage/eve.doctrinator
/app/models/doctrine_diff.rb
UTF-8
1,171
2.53125
3
[]
no_license
class DoctrineDiff attr_reader :doctrine, :pilots, :fittings def initialize(doctrine, pilots) @doctrine = doctrine @fittings = doctrine.fittings.sort_by { |fit| fit.full_name } @pilots = pilots end def doctrine_name doctrine.name end def fitting_names fittings.map(&:full_name) end def diffs pilots.map do |pilot| if pilot.updated_at < 12.hours.ago || pilot.pilot_skills.size == 0 SkillImportJob.perform_later(pilot) end { pilot: pilot, fittings: fitting_requirements(pilot) } end end private def fitting_requirements(pilot) fittings.map do |fitting| { fitting_id: fitting.id, fitting: fitting.requirements.map { |req| check_requirement(req, pilot.pilot_skills) } } end end def check_requirement(req, pilot_skills) pilot_skill = pilot_skills.detect { |ps| ps.skill_id == req.skill_id } { name: req.skill_name, diff: pilot_skill.nil? ? -9 : pilot_skill.level - req.level, pilot_skill_level: pilot_skill.nil? ? 0 : pilot_skill.level, requirement_level: req.level } end end
true
23a0dcdd3db4bbd9ca3bca7ef50d7643cc245a2e
Ruby
iolloyd/ProjectManager
/projectmanager.rb
UTF-8
8,655
2.75
3
[]
no_license
#!/usr/bin/ruby require 'cgi' require 'cgi/session' cgi = CGI.new print cgi.header("type" => "text/html") def compose(f,g) lambda{ |x| f(g(x)) } end def xtag (kind,title) "<#{kind}>text</#{kind}>" end def htmltag tags = ['div','p','h1','h2','h3','script'] tags.each do |t| #{t = lambda { | atts | "<#{t} #{atts.each {|k,a| print k; print a}} > </{t}>" }} end end htmltags() def br print "<br />" end def link(href,text,id='',cls='') print "<a id='#{id}' class='#{cls}' href='#{href}'>#{text}</a>" end def wrap(tag,data) print "<#{tag}> #{data} </#{tag}>" end def label(n,v='') print "<label for='#{n}'>#{n}</label><input name='#{n}' value='#{v}' />" end def submit print "<input type=submit name=submit value='Submit'>" end def hidden(n,v='') "<input type=hidden name='#{n}' value='#{v}' />" end def get_project_time(project) times = project['tasks'].map {|x| x['time']} total = 0 if len(times) > 0 hourlist = times.flatten!.map {|x| x['hours']} total = hourlist.inject {|x,y| x + y} if len(hourlist) > 0 end total end def datepicker(d=0,m=0,y=0) t = Time.new ypart = dselect('year',(2007 .. 2030).to_a, t.year) mpart = dselect('month',(1 .. 12).to_a,t.month) dpart = dselect('date',(1 .. 31),t.day) "#{ypart} #{mpart} #{dpart}" end def dselect(name, lst, default='') select = "<select name='#{name}'>" lst.each {|opt| selected = (opt==default) ? "selected='selected'" : selected = '' select = select + "<option value='#{opt}' #{selected} >#{opt}</option>" } select + "</select>" end def gettask(project_title, t) p = loadproject(project_title) task = p['tasks'].find {|x| x['title'] = t } print task['title'] task end def newproject(t) p = {'title' => t,'members' => [],'overview' => "",'comments' => [],'tasks' => [] } saveproject p end def loadproject(p) File.open("#{p}.prj") {|f| Marshal.load(f) } end def addproject() print " <form name=addproject method=post action='' />" label("name");br();submit(); hidden("saveproject",1) print "</form>" end def saveproject(p) File.open("#{p['title']}.prj",'w'){|f| Marshal.dump(p,f)} loadproject(p) end def showproject( p , all='normal') print "all is #{all}..." un = p['tasks'].find {|x| x['status']=='completed'} print "<h1>#{p['title']}</h1>" print "<p>#{p['overview']}</p>" if p['members'] != [] if un link("?showall=#{p['title']}", "Show All", "showall") link("?showproject=#{p['title']}", "Show incomplete", "noshowall") end link("?addtask=#{p['title']}","Add a task","","addtask") end print "<div id='members'><h3>Team members</h3>" p['members'].each {|i| print "#{i} "} link("?project=#{p['title']}&addmember=1", "Add a team member") print "</div><div id=tasklist>" p['tasks'].each {|i| i['status'] = 'incomplete' if not i.has_key?('status') continue if (i['status'] == 'completed' and all == "") print "<div class=taskline>" link("?project=#{p['title']}&addwork=#{i['title']}", "Add hours", i['status']) link("?project=#{p['title']}&setstatus=#{i['title']}", "Complete", i['status']) print "<span class='name'>#{i['person']}</span>" print " <span class='task'>#{i['title']}</span></div>" print "<div class=timedata>" i['time'].each {|x| print "<div><form style='displayinline' action='' method=post >" print "Date <span class=date>#{x['date']}</span> Duration <span class=hours>#{x['hours']}</span>" print "<a class=changehours project='#{p['title']}' task='#{i['title']}' date='#{x['date']}' hours='#{x['hours']}' href='#' >Change</a>" hidden('savechangehours',1); hidden('project',p['title']); hidden('task',i['title']) print "</form></div>" } print "</div>" } print "</div>" end def print_header print "<html><head>" print "<link type='text/css' rel='stylesheet' href='/project_manager/style.css' />" ['core','app','ajax'].each do |j| print "<script type='text/javascript' src='/project_manager/#{j}.js' />" end print "</head><body>" end def print_footer print "</div></div></body></html>" end def saveform(ob,post) keys = ob.keys post.each {|x| ob[x] = post[x] if ob.has_key?(x)} ob end def makeform(name,show,hide) frm = "" show.each {|x| frm += label(x) + "<br>"} hide.each {|x| frm += "<input type='hidden' name='#{x}' />"} frm end def showtasks(p) p['tasks'].each {|t| print t['title'] + "(" + t['person'] + ")"} end def show_all_projects() projects = Dir.entries('.').find_all {|p| p.split(".")[1] == "prj"} print "<ul id=projectlist><li id=createproject ><a href='?addproject=1'>Create Project</a></li>" projects.each {|p| p = p.split(".")[0] print "<li><a href='?showproject=#{p}'>#{p}</a></li>" } print "</ul><div id='cnt'>" end def addmember(p) print "<p>Project <b>#{p}</b></p>" print "<form name=addmember method=post action=''>" print "<fieldset><legend>Add a new member to the #{p} project</legend>" print label('person') print submit() print hidden('project',p) print hidden('savemember','1') print "</form>" end def savemember(project,person) project['members'] = [] if not project.has_key?('members') names = project['members'] << person names.uniq! project['members'] = names saveproject(project) end def addtask(p) proj = loadproject(p) people = proj['members'] print "<p>Project <b>#{p}</b></p>" print "<fieldset><legend>Add task to the #{p} project</legend>" print "<form name=addtask method=post action=''>" print "Task <input name='task' />" print " New team member <select name='person'>" people.each {|x| print "<option value=#{x}>#{x}</option>" } print "</select> " print "<input type=submit name=submit value=submit />" print hidden('project',p) print hidden('savetask','1') print "</fieldset></form>" end def savetask(project, title, person, status='incomplete' ) project = loadproject(project) project['tasks'] << {'person' => person, 'title' => title, 'status' => status, 'time' => []} print "Project is #{project}<br>" project = saveproject(project) print "and now Project is #{project}<br>" end def settaskstatus(p,t) task = gettask(p,t) p = loadproject(p) task['status'] = 'completed' tasks = p['tasks'].find_all {|x| x['title'] != t } p['tasks'] = tasks << task saveproject(p) end def addwork(p,t) print "<p>Project: <b>#{p}</b></p>" print "<form name=add_work method=post action=''>" print "<fieldset><legend>Task: <b>#{t}</b></legend>" print datepicker print label('hours') print submit print hidden('project',p) print hidden('task',t) print hidden('savework','1') print "</form>" end def savework(project,title,y,m,d,hours) date = "#{d}-#{m}-#{y}" task = project['tasks'].find {|x| x['title'] == title } tasks = project['tasks'].find_all {|x| x['title'] != title} samedate = (task) ? task['time'].find {|x| x['date'] == date} : false notsamedate = task['time'].find_all {|x| x['date'] != samedate['date'] } if samedate samedate['hours'] = samedate['hours'].to_f + hours.to_f task['time'] = notsamedate << samedate else task['time'] << {'date' => date, 'hours' => hours} end project['tasks'] = tasks << task saveproject(project) end def check_post(post) if post.has_key?('showproject') project = loadproject(post['showproject']) end if post.has_key?('showall') project = loadproject(post['showall']) end if post.has_key?('saveproject') project = newproject(post['name']) end if post.has_key?('addmember') project = addmember(post['project']) end if post.has_key?('addproject') project = addproject end if post.has_key?('addwork') project = addwork(post['project'], post['addwork']) end if post.has_key?('addtask') project = addtask(post['addtask']) end if post.has_key?('savechangehours') t,d,h = post['task'],post['date'],post['hours'] task = gettask(p,t) task['time'] = task['time'].find_all {|x| x['date'] != d} << {'date' => d,'hours' => h} p['tasks'] = p['tasks'].find_all {|x| x['title'] != t} << task project = saveproject(p) end if post.has_key?('savemember') project = savemember(post['project'],post['person']) end if post.has_key?('savetask') project = savetask(post['project'],post['task'],post['person']) end if post.has_key?('savework') p,t,y,m,d,hrs = post['project'],post['task'],post['year'],post['month'],post['date'],post['hours'] project = savework(p,t,y,m,d,hrs) end if post.has_key?('setstatus') project = settaskstatus(post['project'],post['setstatus']) end show = post['showall'] showproject(project,show) end print_header show_all_projects check_post(cgi) print_footer
true
dcb8d4014d2f962985c40483b594ba1831f5e9a6
Ruby
manuca/job_board
/models/plan.rb
UTF-8
441
2.859375
3
[]
no_license
class Plan POSTS = { "free" => 5, "small" => 1, "medium" => 5, "large" => 10, "punchgirls" => 1000 } PRICING = { "free" => 0, "small" => 50, "medium" => 100, "large" => 150, "punchgirls" => 0 } attr :id def self.[](id) new(id) end def initialize(id) @id = id end def posts POSTS[@id] end def price PRICING[@id] end def name @id end end
true
a320d13d0d1dad6729adbe4ee6661364d3ec074b
Ruby
alim16/refresher
/selenium/webdriverEx2.rb
UTF-8
2,132
3.046875
3
[]
no_license
require 'selenium-webdriver' #tested with firefox v47.0.1 searchText = ARGV[0] #type in something to look for as the first param requiredLang = ARGV[1] #type in a language e.g svenska as the second param #incase no args given if ARGV.empty? searchText = "FiReFOX" requiredLang = "Deutsch" end #Navigate to the Wikipedia home page driver = Selenium::WebDriver.for :firefox driver.navigate.to "http://www.wikipedia.org/" #Type in a string given as parameter in the search input field? search = driver.find_element(:id, 'searchInput') search.send_keys(searchText) #Select English as the search language. dropdown = driver.find_element(:id, 'searchLanguage') select_list = Selenium::WebDriver::Support::Select.new(dropdown) select_list.select_by(:text, 'English') #Click the search button. search.submit # Validate that the ?rst heading of the search results page matches the search string (ignoring case). if driver.find_element(:id => "firstHeading").text.downcase.include?(searchText.downcase) print "heading found #{searchText}\n" else print "text #{searchText} not found" end #Verify that the search results page is available in a language given as parameter list = driver.find_elements(:id => "p-lang") #working list.each do |element| if element.text.include? requiredLang puts "found #{requiredLang} language in list" end end #Navigate to the search results page in that language. langItem = driver.find_element(:xpath, "//*[@id=\"p-lang\"]/div/ul/li[contains(.,\"#{requiredLang}\")]") puts "link text found for: #{langItem.text}" #langItemLink = driver.find_element(:xpath, '//*[@id="p-lang"]/div/ul/li[contains(.,"Deutsch")]/a') #works langItem = driver.find_element(:xpath, "//*[@id=\"p-lang\"]/div/ul/li[contains(.,\"#{requiredLang}\")]/a") langItem.click #Validate that the search results page in the new language includes a link to the version in English. list = driver.find_elements(:id => "p-lang") #working list.each do |element| if element.text.include? "English" puts "found English language in list" end end driver.quit
true
565d34e0ab37541abbe887a153d5f8aedb924b26
Ruby
lbvf50mobile/til
/20230313_Monday/20230313.rb
UTF-8
1,172
3.640625
4
[]
no_license
# Leetcode: 101. Symmetric Tree. # https://leetcode.com/problems/symmetric-tree/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 83 ms, faster than 76.47% of Ruby online submissions for Symmetric Tree. # Memory Usage: 211 MB, less than 43.53% of Ruby online submissions for Symmetric Tree. # 2023.03.13 Daily Challenge. # Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val = 0, left = nil, right = nil) # @val = val # @left = left # @right = right # end # end # @param {TreeNode} root # @return {Boolean} def is_symmetric(root) q = [root] while ! q.empty? nq = [] # new queue. return false if ! sym(q) q.each do |x| next if ! x nq.push(x.left) nq.push(x.right) end q = nq end return true end def sym(arr) i,j = 0, arr.size - 1 while i < j if arr[i].nil? || arr[j].nil? return false if arr[i] || arr[j] else return false if arr[i].val != arr[j].val end # Need to move pointers on each interation. i += 1 j -= 1 end return true end
true
de7683a7ba501c23af50b2159e3215cabaa34207
Ruby
Sruthisarav/My-computer-science-journey
/Open App Academy/Software Engineering Foundations/Rspec/rspec_exercise_1/lib/part_1.rb
UTF-8
583
3.984375
4
[]
no_license
def average(n1, n2) return (n1 + n2)/2.to_f end def average_array(array) average = array.inject {|acc, ele| acc += ele} return average/array.length.to_f end def repeat(str, n) new_str = '' n.times {new_str += str} return new_str end def yell(str) return str.upcase + '!' end def alternating_case(str) up = true str = str.split(' ') new_str = [] str.each do |word| if (up) new_str << word.upcase else new_str << word.downcase end up = !up end return new_str.join(' ') end
true
abb70e2873b1e85898192c999f249f5dade0dbb8
Ruby
AnRenYiL/class_notes_and_labs
/day_35_rails_object/animals.rb
UTF-8
398
3.859375
4
[]
no_license
class Animals attr_accessor :name, :color def initialize(name,color) @name = name @color = color end def eat puts "I'm eating" end def walk puts "I'm walking" end end class Dog < Animals def eat super puts "Bones are yummy!" end end class Cat < Animals def eat puts "Fish is yummy!" end end
true
7a3fc8c17daa0bf02d03deb8fdc2a97000b747ee
Ruby
gitter-badger/vedeu
/test/lib/vedeu/models/buffer_test.rb
UTF-8
4,634
2.609375
3
[ "MIT" ]
permissive
require 'test_helper' module Vedeu describe Buffer do let(:attributes) { { name: '', back: back, front: front, previous: previous, } } let(:back) { {} } let(:front) { {} } let(:previous) { {} } describe '#initialize' do it 'returns an instance of Buffer' do Buffer.new(attributes).must_be_instance_of(Buffer) end end describe '#back' do subject { Buffer.new(attributes).back } it { subject.must_be_instance_of(Hash) } end describe '#front' do subject { Buffer.new(attributes).front } it { subject.must_be_instance_of(Hash) } context 'alias method: #current' do subject { Buffer.new(attributes).current } it { subject.must_be_instance_of(Hash) } end end describe '#name' do subject { Buffer.new(attributes).name } it { subject.must_be_instance_of(String) } end describe '#previous' do subject { Buffer.new(attributes).previous } it { subject.must_be_instance_of(Hash) } end describe '#back?' do subject { Buffer.new(attributes).back? } context 'when there is content on the back buffer' do let(:back) { { lines: [{ streams: [{ text: 'back' }] }] } } it { subject.must_equal(true) } end context 'when there is no content on the back buffer' do it { subject.must_equal(false) } end context 'when there is no content on the back buffer' do let(:back) { { lines: [] } } it { subject.must_equal(false) } end end describe '#front?' do subject { Buffer.new(attributes).front? } context 'when there is content on the front buffer' do let(:front) { { lines: [{ streams: [{ text: 'front' }] }] } } it { subject.must_equal(true) } end context 'when there is no content on the front buffer' do it { subject.must_equal(false) } end context 'when there is no content on the front buffer' do let(:front) { { lines: [] } } it { subject.must_equal(false) } end context 'alias method: #current?' do subject { Buffer.new(attributes).current? } context 'when there is no content on the front buffer' do it { subject.must_equal(false) } end end end describe '#previous?' do subject { Buffer.new(attributes).previous? } context 'when there is content on the previous buffer' do let(:previous) { { lines: [{ streams: [{ text: 'previous' }] }] } } it { subject.must_equal(true) } end context 'when there is no content on the previous buffer' do it { subject.must_equal(false) } end context 'when there is no content on the previous buffer' do let(:previous) { { lines: [] } } it { subject.must_equal(false) } end end describe '#add' do let(:attributes) { { back: { lines: [{ streams: [{ text: 'old_back' }] }] } } } let(:buffer) { Buffer.new(attributes) } let(:content) { { lines: [{ streams: [{ text: 'new_back' }] }] } } subject { buffer.add(content) } it { subject.must_equal(true) } it 'replaces the back buffer with the content' do buffer.back.must_equal({ lines: [{ streams: [{ text: 'old_back' }] }] }) subject buffer.back.must_equal({ lines: [{ streams: [{ text: 'new_back' }] }] }) end end describe '#swap' do let(:buffer) { Buffer.new(attributes) } subject { buffer.swap } context 'when there is new content on the back buffer' do let(:back) { { lines: [{ streams: [{ text: 'back' }] }] } } let(:front) { { lines: [{ streams: [{ text: 'front' }] }] } } let(:previous) { { lines: [{ streams: [{ text: 'previous' }] }] } } context 'when the buffer was updated successfully' do it { subject.must_equal(true) } end it 'replaces the previous buffer with the front buffer' do subject buffer.previous.must_equal(front) end it 'replaces the front buffer with the back buffer' do subject buffer.front.must_equal(back) end it 'replaces the back buffer with an empty buffer' do subject buffer.back.must_equal({}) end end context 'when there is no new content on the back buffer' do it { subject.must_equal(false) } end end end # Buffer end # Vedeu
true
cd7dc1411a817a2c8276741cc138dbf2a3af72cc
Ruby
dgonca/artistg
/app/helpers/session_helpers.rb
UTF-8
353
2.625
3
[]
no_license
#sets current user to session[:user_id] from login def current_user current_user ||= User.find_by(id: session_user) end def session_user session[:user_id] end #checks if session[:user_id] is not nil, which will only happen if someone is logged in def logged_in? session_user != nil end def authenticate! redirect '/404' unless logged_in? end
true
227041423fd90e1555a68dc38e79c7df0e6e67e3
Ruby
marcelopedras-ufvjm/gestaopatrimonial
/app/models/loan.rb
UTF-8
1,575
2.625
3
[]
no_license
class Loan < ActiveRecord::Base belongs_to :user belongs_to :resource has_many :resource_histories validates_presence_of :user, :resource validate :devolution_forecast_greater_than_start_date, :end_date_greater_than_start_date, :start_and_devolution_forecast_must_be_exist_to_loan, :start_and_end_date_must_be_present_to_booking def booking? booking end def loan? !booking? end def returned? booking? ? false : !self.end.nil? end #custom validations def devolution_forecast_greater_than_start_date if !devolution_forecast.nil? && !start.nil? if self.devolution_forecast <= self.start errors.add(:loan, "Devolution forecast must be greater than start date") end end end def end_date_greater_than_start_date if !self.start.nil? && !self.end.nil? if self.end <= self.start errors.add(:loan, "End date must be greater than start date") end end end def start_and_devolution_forecast_must_be_exist_to_loan if loan? unless self.start errors.add(:loan, "Start date must be present to loan") end unless self.devolution_forecast errors.add(:loan, "Devolution forecast must be present to loan") end end end def start_and_end_date_must_be_present_to_booking if booking? unless self.start errors.add(:loan, "Start date must be present to booking") end unless self.end errors.add(:loan, "End date must be present to booking") end end end end
true
b09e02b2b7dade057656af6931f11ff2468b9cb9
Ruby
smartlyio/logger-metadata
/lib/logger/metadata/formatter.rb
UTF-8
1,239
2.796875
3
[ "MIT" ]
permissive
require 'thread' class Logger module Metadata module Formatter def call(severity, timestamp, program_name, message) timestamp_string = '[' + timestamp.to_s + ']' formatted_message = "#{faint(timestamp_string)} #{message}#{faint(metadata_text)}" super(severity, timestamp, program_name, formatted_message) end def metadata_stack thread_key = @metadata_thread_key ||= "metadata_logging:#{object_id}".freeze Thread.current[thread_key] ||= [] end def current_metadata metadata_stack.inject({}, &:merge) end def metadata(attributes) push_metadata(attributes) yield self ensure pop_metadata end def push_metadata(attributes) metadata_stack.push attributes end def pop_metadata(size = 1) metadata_stack.pop size end def clear_metadata! metadata_stack.clear end def metadata_text current_metadata.map do |(key, value)| " (#{key}=#{value})" end.join('') end def faint(string) if string.empty? string else "\e[2m#{string}\e[0m" end end end end end
true
9850f9c09fc7b70041364ab8674479b572bbde08
Ruby
bettymakes/playing_with_lcbo_api
/html_generator.rb
UTF-8
2,546
3.359375
3
[]
no_license
require 'open-uri' require 'json' class HtmlGenerator # cost to help get clean water to those in need in Africa http://waterwellsforafrica.org/whats-the-cost/ WATER = 3.5 def print_header puts "<!DOCTYPE html>" puts "<html>" puts " <head></head>" puts " <body>" end def print_end puts " </body>" puts "</html>" end def feeling_guilty raw_data = open("http://lcboapi.com/products?q=ontario").read ontario_drinks = JSON.parse(raw_data) print_header ontario_drinks["result"].each do |attribute| if attribute["price_in_cents"] >= 1000 puts " <h1> #{attribute["name"]} </h1>" puts " <h4> $#{attribute["price_in_cents"]/100.to_f} <h4>" puts " <h4> #{((attribute["price_in_cents"]/100.to_f)/WATER).to_i} people<h4>" else next end end print_end end def random_drink raw_data = open("http://lcboapi.com/products").read random_drinks = JSON.parse(raw_data) print_header random_drink = random_drinks["result"].sample puts " <img src='#{random_drink["image_url"]}' style='height:200px; width:200px;'/>" puts " <h1> Name: #{random_drink["name"]} </h1>" puts " <h4> Package: #{random_drink["package"]} </h4>" puts " <h4> Total package units: #{random_drink["total_package_units"]} </h4>" puts " <h4> Price: $#{random_drink["price_in_cents"]/100.to_f} </h4>" print_end end def pick_type(type) raw_data = open("http://lcboapi.com/products?q=#{type}").read type_drinks = JSON.parse(raw_data) print_header type_drinks["result"].each do |attribute| puts " <h1> Name: #{attribute["name"]} </h1>" puts " <h4> Package: #{attribute["package"]} </h4>" puts " <h4> Total package units: #{attribute["total_package_units"]} </h4>" puts " <h4> Price: #{attribute["price_in_cents"]/100.to_f} </h4>" puts " <h4> Area: #{attribute["origin"]} </h4>" print_end end end def help puts "" puts "Need help with the commands? No problemo!" puts "That's why I'm here brejo! (that's a soft 'j' btw)" puts "--------------------------------------------------------------" puts "--------------------------------------------------------------" puts "" puts "'guilty-time' ................ Feel bad for buying alcohol" puts "'random-drink' ............... Need help picking a drink? Try this!" puts "'pick-type' + _word_ ......... Have a specific query? Enter your word after 'pick-type'" puts "'help' ....................... If you made it here, you already know this" puts "" puts "" end end
true
b8a0b522c7bf1fee0c53b8cef5518371766e1f37
Ruby
ungsophy/little-mrt
/lib/little-mrt/path.rb
UTF-8
926
3.046875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module LittleMRT class Path attr_reader :adjacencies def initialize(adjacencies = []) @adjacencies = adjacencies end def add_adjacency(adjacency) if adjacencies.empty? || last_adjacency.to == adjacency.from adjacencies << adjacency else raise ArgumentError, "Last adjacency is not connected. #{last_adjacency.to} == #{adjacency.from}" end end alias_method :<<, :add_adjacency def distance adjacencies.inject(0) { |result, adjacency| result + adjacency.distance } end def stops_count adjacencies.size end def to_s str, n = '', adjacencies.size - 1 adjacencies.each_with_index do |adjacency, index| str += "#{adjacency.from}-" if index == n return str += "#{adjacency.to}" end end end private def last_adjacency adjacencies.last end end end
true
452e0b86fd39297acba30392c945d5ab8ed22d37
Ruby
uehara55/fleamarket_sample_37d
/app/models/address.rb
UTF-8
1,207
2.5625
3
[]
no_license
class Address < ApplicationRecord belongs_to :user validates :first_name, presence: true validates :last_name, presence: true validates :first_name_kana, presence: true, format: { with: /\A[\p{katakana}\p{blank}ー-]+\z/, message: 'はカタカナで入力してください'} validates :last_name_kana, presence: true, format: { with: /\A[\p{katakana}\p{blank}ー-]+\z/, message: 'はカタカナで入力してください'} validates :postal_code, presence: true, format: { with: /\A\d{3}\-?\d{4}\z/ , message: 'は7桁の数字を入力して下さい'} validates :prefecture_code, presence: true validates :city, presence: true validates :street_number, presence: true VALID_PHONE_REGEX = /\A\d{10}$|^\d{11}\z/ validates :telephone_number, presence: true, format: { with: VALID_PHONE_REGEX , message: 'は10桁もしくは11桁の番号を入力してください'} include JpPrefecture jp_prefecture :prefecture_code def prefecture_name JpPrefecture::Prefecture.find(code: prefecture_code)&.to_s end def prefecture_name=(prefecture_name) self.prefecture_code = JpPrefecture::Prefecture.find(name: prefecture_name).code end end
true
1b90a028ace5d0c2fb938f5577e1431dce0659d5
Ruby
eloisecoveny/codeclan_cinema
/console.rb
UTF-8
1,473
2.734375
3
[]
no_license
require_relative("models/customer") require_relative("models/film") require_relative("models/ticket") require_relative("models/screening") require("pry") Ticket.delete_all() Screening.delete_all() Customer.delete_all() Film.delete_all() film1 = Film.new("title" => "Stalker", "price" => "8") film1.save() film2 = Film.new("title" => "The Passenger", "price" => "8") film2.save() customer1 = Customer.new("name" => "Eloise", "funds" => "12") customer1.save() customer2 = Customer.new("name" => "Bobby", "funds" => "10") customer2.save() customer3 = Customer.new("name" => "Elke", "funds" => "35") customer3.save() screening1 = Screening.new("screening_time" => "16:30", "film_id" => film1.id, "sold" => "0") screening1.save() screening2 = Screening.new("screening_time" => "17:30", "film_id" => film2.id, "sold" => "0") screening2.save() screening3 = Screening.new("screening_time" => "21:00", "film_id" => film1.id, "sold" => "0") screening3.save() ticket1 = Ticket.new("customer_id" => customer1.id, "film_id" => film1.id, "screening_id" => screening1.id) ticket1.save() ticket2 = Ticket.new("customer_id" => customer1.id, "film_id" => film2.id, "screening_id" => screening2.id) ticket2.save() ticket3 = Ticket.new("customer_id" => customer2.id, "film_id" => film1.id, "screening_id" => screening1.id) ticket3.save() ticket4 = Ticket.new("customer_id" => customer2.id, "film_id" => film1.id, "screening_id" => screening3.id) ticket4.save() binding.pry nil
true
5117832a52c893854f347614ae735e6a6a400934
Ruby
gruis/advent2018
/10_the_stars_align.rb
UTF-8
17,705
3.0625
3
[]
no_license
#!/usr/bin/env ruby VERBOSE = ARGV.delete('-v') SKIP = ARGV.delete('-s') def plot(data) minx,maxx = data.map(&:first).minmax miny,maxy = data.map(&:last).minmax height, width = dimensions(data) puts "#{width}:#{height} - #{maxx}:#{minx}; "\ "#{maxy}:#{miny}; #{maxx - minx}:#{maxy - miny}" grid = Array.new(width + 1) { Array.new(height + 1, ".") } data.each { |x,y| grid[x - minx][y - miny] = "#" } draw(grid) end def draw(grid) xmax = grid.length ymax = grid[0].length ymax.times do |y| xmax.times { |x| print grid[x][y] } print "\n" end end def draw(grid) xmax = grid.length ymax = grid[0].length ymax.times do |y| xmax.times { |x| print grid[x][y] } print "\n" end end def drift(positions, velocities) positions.each_index do |i| positions[i][0] = positions[i][0] + velocities[i][0] positions[i][1] = positions[i][1] + velocities[i][1] end positions end def undrift(positions, velocities) positions.each_index do |i| positions[i][0] = positions[i][0] - velocities[i][0] positions[i][1] = positions[i][1] - velocities[i][1] end positions end def dimensions(positions) minx,maxx = positions.map(&:first).minmax miny,maxy = positions.map(&:last).minmax height = maxy - miny width = maxx - minx [height, width] end def part1(data) poss = data.map { |d| [ d[0], d[1] ] } vels = data.map { |d| [ d[2], d[3] ] } last_height, last_width = 1.0 / 0.0, 1.0 / 0.0 step = 0 while true step += 1 poss = drift(poss, vels) height, width = dimensions(poss) print "\r#{step} (#{last_width}:#{width} #{last_height}:#{height})#{" " * 20}" if height > last_height print "\n" plot(undrift(poss, vels)) puts "-#{step - 1}-" break end last_height = height last_width = width end end input = (ARGV.empty? ? DATA : ARGF).read.split("\n---\n") input.each_index do |i| next if i > 0 && SKIP data = input[i] data = data.each_line.map do |line| cords = line.scan(/position=<\s*(-?\d+),\s*(-?\d+)> velocity=<\s*(-?\d+),\s*(-?\d+)>/)[0].map(&:to_i) end part1(data.clone) end __END__ position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2> position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0> position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1> position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0> position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2> position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1> position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0> position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1> position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0> position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1> position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1> position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0> position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0> position=<-3, 6> velocity=< 2, -1> --- position=< 42772, -21149> velocity=<-4, 2> position=< 42804, -31790> velocity=<-4, 3> position=<-10445, -10502> velocity=< 1, 1> position=<-31749, 21438> velocity=< 3, -2> position=<-31722, 32074> velocity=< 3, -3> position=< 53436, -21147> velocity=<-5, 2> position=<-42336, -42437> velocity=< 4, 4> position=<-42380, 21435> velocity=< 4, -2> position=< 21508, -10506> velocity=<-2, 1> position=<-31727, 42725> velocity=< 3, -4> position=<-42383, 32083> velocity=< 4, -3> position=< 42764, 21438> velocity=<-4, -2> position=<-53037, -53086> velocity=< 5, 5> position=< 53436, -10506> velocity=<-5, 1> position=<-10445, 32083> velocity=< 1, -3> position=<-53001, -53081> velocity=< 5, 5> position=<-31724, -21151> velocity=< 3, 2> position=<-21106, 42720> velocity=< 2, -4> position=< 10847, -53083> velocity=<-1, 5> position=< 21483, -21147> velocity=<-2, 2> position=< 53433, -21146> velocity=<-5, 2> position=< 32121, 42719> velocity=<-3, -4> position=< 10834, 53364> velocity=<-1, -5> position=<-31708, -42434> velocity=< 3, 4> position=<-21057, -10497> velocity=< 2, 1> position=<-42372, -53082> velocity=< 4, 5> position=< 32143, -10502> velocity=<-3, 1> position=<-31751, -53078> velocity=< 3, 5> position=<-21069, 42720> velocity=< 2, -4> position=<-21049, -42432> velocity=< 2, 4> position=<-42376, 42727> velocity=< 4, -4> position=< 42790, -21151> velocity=<-4, 2> position=< 10849, 32082> velocity=<-1, -3> position=<-31724, -21142> velocity=< 3, 2> position=< 32159, -10498> velocity=<-3, 1> position=< 32180, -21151> velocity=<-3, 2> position=< 21491, 53368> velocity=<-2, -5> position=< 32162, -21149> velocity=<-3, 2> position=< 21482, -10505> velocity=<-2, 1> position=<-52981, -53079> velocity=< 5, 5> position=< 42796, 32079> velocity=<-4, -3> position=<-21066, 42720> velocity=< 2, -4> position=< 10862, 32083> velocity=<-1, -3> position=< 21474, -53083> velocity=<-2, 5> position=<-10434, -10497> velocity=< 1, 1> position=<-21054, 53364> velocity=< 2, -5> position=< 21534, 42723> velocity=<-2, -4> position=< 10861, -21147> velocity=<-1, 2> position=< 10857, -10502> velocity=<-1, 1> position=< 53461, 32079> velocity=<-5, -3> position=< 32132, -10505> velocity=<-3, 1> position=<-42362, -21142> velocity=< 4, 2> position=<-42396, 32074> velocity=< 4, -3> position=< 53469, -21151> velocity=<-5, 2> position=<-21098, 42723> velocity=< 2, -4> position=<-42378, 32080> velocity=< 4, -3> position=<-21074, 42726> velocity=< 2, -4> position=< 10881, -10500> velocity=<-1, 1> position=< 21514, 53367> velocity=<-2, -5> position=< 42764, -53080> velocity=<-4, 5> position=< 32151, 53368> velocity=<-3, -5> position=<-21090, 21437> velocity=< 2, -2> position=< 10877, -53078> velocity=<-1, 5> position=<-10445, -31796> velocity=< 1, 3> position=< 42796, 42722> velocity=<-4, -4> position=<-31740, -21147> velocity=< 3, 2> position=<-42344, -53083> velocity=< 4, 5> position=<-21087, -31794> velocity=< 2, 3> position=<-31691, 32082> velocity=< 3, -3> position=< 21490, -31790> velocity=<-2, 3> position=< 42792, -10506> velocity=<-4, 1> position=< 53462, 32074> velocity=<-5, -3> position=<-53025, 53366> velocity=< 5, -5> position=<-31722, 21438> velocity=< 3, -2> position=< 53469, 10786> velocity=<-5, -1> position=< 10841, 32081> velocity=<-1, -3> position=< 53449, 21431> velocity=<-5, -2> position=<-21074, -10501> velocity=< 2, 1> position=< 21487, -53084> velocity=<-2, 5> position=<-53015, -53082> velocity=< 5, 5> position=< 42777, -31787> velocity=<-4, 3> position=< 42764, -10502> velocity=<-4, 1> position=< 53422, 10787> velocity=<-5, -1> position=< 42772, -10503> velocity=<-4, 1> position=< 53465, 32081> velocity=<-5, -3> position=<-10421, 10793> velocity=< 1, -1> position=< 42815, -42432> velocity=<-4, 4> position=<-21106, -53079> velocity=< 2, 5> position=<-53033, 53369> velocity=< 5, -5> position=< 42766, 53368> velocity=<-4, -5> position=< 42767, -21151> velocity=<-4, 2> position=< 21526, -31789> velocity=<-2, 3> position=<-21082, -21148> velocity=< 2, 2> position=< 53410, -21147> velocity=<-5, 2> position=<-31691, -10500> velocity=< 3, 1> position=< 42805, 32078> velocity=<-4, -3> position=<-42378, -31790> velocity=< 4, 3> position=<-21050, -21143> velocity=< 2, 2> position=<-21106, -42436> velocity=< 2, 4> position=<-53001, 53365> velocity=< 5, -5> position=< 53469, -21145> velocity=<-5, 2> position=< 10833, -31796> velocity=<-1, 3> position=<-53009, -10498> velocity=< 5, 1> position=< 32159, -31789> velocity=<-3, 3> position=<-53007, -53077> velocity=< 5, 5> position=< 21474, -21149> velocity=<-2, 2> position=< 53427, -53083> velocity=<-5, 5> position=< 10861, 42720> velocity=<-1, -4> position=<-53017, 10786> velocity=< 5, -1> position=<-42335, -42441> velocity=< 4, 4> position=<-31751, -42432> velocity=< 3, 4> position=< 32171, 21429> velocity=<-3, -2> position=<-53016, -53086> velocity=< 5, 5> position=< 21522, 21436> velocity=<-2, -2> position=<-53009, -53079> velocity=< 5, 5> position=< 53433, 42721> velocity=<-5, -4> position=< 53420, -42441> velocity=<-5, 4> position=< 42777, -10504> velocity=<-4, 1> position=<-10416, 32074> velocity=< 1, -3> position=<-42396, 10788> velocity=< 4, -1> position=< 21490, 10791> velocity=<-2, -1> position=< 32128, -21147> velocity=<-3, 2> position=< 53461, -21143> velocity=<-5, 2> position=<-21063, -21149> velocity=< 2, 2> position=<-31743, -31792> velocity=< 3, 3> position=< 21514, 21432> velocity=<-2, -2> position=< 10861, 10791> velocity=<-1, -1> position=< 10881, -31792> velocity=<-1, 3> position=< 10889, -31795> velocity=<-1, 3> position=< 32143, -21145> velocity=<-3, 2> position=<-21093, -42439> velocity=< 2, 4> position=<-10450, 21433> velocity=< 1, -2> position=<-31719, 21430> velocity=< 3, -2> position=< 10865, 53373> velocity=<-1, -5> position=<-10405, -21144> velocity=< 1, 2> position=< 21534, -42433> velocity=<-2, 4> position=<-31727, -53083> velocity=< 3, 5> position=<-53021, 21437> velocity=< 5, -2> position=< 53449, -42434> velocity=<-5, 4> position=<-21046, 10789> velocity=< 2, -1> position=< 21518, 32082> velocity=<-2, -3> position=<-31727, -10506> velocity=< 3, 1> position=<-53033, 10793> velocity=< 5, -1> position=< 10842, -10498> velocity=<-1, 1> position=< 53425, 32075> velocity=<-5, -3> position=<-53004, 32082> velocity=< 5, -3> position=<-53016, -53082> velocity=< 5, 5> position=<-21098, 21435> velocity=< 2, -2> position=<-10417, 42720> velocity=< 1, -4> position=<-42363, 21429> velocity=< 4, -2> position=< 32151, 10790> velocity=<-3, -1> position=<-53025, 21431> velocity=< 5, -2> position=<-10437, -42435> velocity=< 1, 4> position=<-31735, -10502> velocity=< 3, 1> position=<-21098, -21149> velocity=< 2, 2> position=< 10830, 10784> velocity=<-1, -1> position=< 10838, -21151> velocity=<-1, 2> position=<-21085, -21142> velocity=< 2, 2> position=< 32119, -53079> velocity=<-3, 5> position=<-31700, 21438> velocity=< 3, -2> position=<-31714, -31795> velocity=< 3, 3> position=< 32135, -10504> velocity=<-3, 1> position=< 10889, -21149> velocity=<-1, 2> position=<-31742, -53086> velocity=< 3, 5> position=<-31726, -42432> velocity=< 3, 4> position=<-31727, -53079> velocity=< 3, 5> position=<-42369, -31792> velocity=< 4, 3> position=< 10830, -42437> velocity=<-1, 4> position=< 32179, 42725> velocity=<-3, -4> position=< 21483, -31796> velocity=<-2, 3> position=< 53435, 32074> velocity=<-5, -3> position=< 32132, -31788> velocity=<-3, 3> position=< 53449, 10787> velocity=<-5, -1> position=<-21066, -42439> velocity=< 2, 4> position=<-21065, 10789> velocity=< 2, -1> position=<-31693, -31787> velocity=< 3, 3> position=<-42380, 42727> velocity=< 4, -4> position=< 42788, 10785> velocity=<-4, -1> position=<-21054, -21150> velocity=< 2, 2> position=< 42772, -42434> velocity=<-4, 4> position=<-31722, 42719> velocity=< 3, -4> position=< 10837, -31794> velocity=<-1, 3> position=< 21498, -42436> velocity=<-2, 4> position=< 42797, 10793> velocity=<-4, -1> position=<-42372, 42724> velocity=< 4, -4> position=< 32171, 10787> velocity=<-3, -1> position=<-21085, -42441> velocity=< 2, 4> position=<-21046, 10791> velocity=< 2, -1> position=<-31709, 53370> velocity=< 3, -5> position=< 21503, 21438> velocity=<-2, -2> position=<-31695, -10498> velocity=< 3, 1> position=<-10411, -53077> velocity=< 1, 5> position=< 32169, 21438> velocity=<-3, -2> position=< 53454, -42441> velocity=<-5, 4> position=< 21487, 10785> velocity=<-2, -1> position=<-31711, 10792> velocity=< 3, -1> position=<-21085, -10497> velocity=< 2, 1> position=<-42360, -42432> velocity=< 4, 4> position=<-21090, 21434> velocity=< 2, -2> position=<-31739, 32074> velocity=< 3, -3> position=< 53417, -10502> velocity=<-5, 1> position=<-42364, -21149> velocity=< 4, 2> position=< 42767, -21147> velocity=<-4, 2> position=< 21502, 10784> velocity=<-2, -1> position=<-53016, -53077> velocity=< 5, 5> position=<-10401, 10787> velocity=< 1, -1> position=<-31715, 53373> velocity=< 3, -5> position=< 10869, 53364> velocity=<-1, -5> position=< 10848, -10499> velocity=<-1, 1> position=< 10880, -10497> velocity=<-1, 1> position=<-31749, 32074> velocity=< 3, -3> position=<-42388, -31788> velocity=< 4, 3> position=<-10440, 42719> velocity=< 1, -4> position=< 10857, -53082> velocity=<-1, 5> position=< 53461, -21147> velocity=<-5, 2> position=<-21063, -10499> velocity=< 2, 1> position=< 32124, 42728> velocity=<-3, -4> position=<-21102, 10788> velocity=< 2, -1> position=< 32179, 32079> velocity=<-3, -3> position=< 10837, 32075> velocity=<-1, -3> position=<-42383, 32077> velocity=< 4, -3> position=< 42769, 21429> velocity=<-4, -2> position=< 21495, -10497> velocity=<-2, 1> position=< 32151, -42436> velocity=<-3, 4> position=< 32129, 10784> velocity=<-3, -1> position=<-31750, 10793> velocity=< 3, -1> position=< 53449, -42432> velocity=<-5, 4> position=< 32128, -42437> velocity=<-3, 4> position=<-42377, -21144> velocity=< 4, 2> position=< 10833, 53373> velocity=<-1, -5> position=< 32143, 32083> velocity=<-3, -3> position=< 42816, -31792> velocity=<-4, 3> position=<-31727, 42728> velocity=< 3, -4> position=<-21103, 42719> velocity=< 2, -4> position=<-42368, 21438> velocity=< 4, -2> position=<-21098, -10500> velocity=< 2, 1> position=<-31735, -10506> velocity=< 3, 1> position=<-42391, 32074> velocity=< 4, -3> position=<-21095, -53081> velocity=< 2, 5> position=<-21079, -21147> velocity=< 2, 2> position=< 32151, 53366> velocity=<-3, -5> position=<-42396, 10785> velocity=< 4, -1> position=< 32119, 21434> velocity=<-3, -2> position=<-31716, -42432> velocity=< 3, 4> position=< 32162, 32081> velocity=<-3, -3> position=< 10845, 21430> velocity=<-1, -2> position=< 32119, -21149> velocity=<-3, 2> position=< 53461, -10504> velocity=<-5, 1> position=<-21074, -42438> velocity=< 2, 4> position=< 10873, 53372> velocity=<-1, -5> position=<-42380, -31792> velocity=< 4, 3> position=<-31751, 10788> velocity=< 3, -1> position=<-31735, -53086> velocity=< 3, 5> position=< 21499, 10788> velocity=<-2, -1> position=< 32147, 10784> velocity=<-3, -1> position=<-10409, 42721> velocity=< 1, -4> position=< 21492, -42435> velocity=<-2, 4> position=< 10885, -42434> velocity=<-1, 4> position=< 53409, -42433> velocity=<-5, 4> position=<-31699, 10784> velocity=< 3, -1> position=< 53459, -31787> velocity=<-5, 3> position=<-21093, -42433> velocity=< 2, 4> position=< 53436, -42432> velocity=<-5, 4> position=< 42764, 42727> velocity=<-4, -4> position=<-52982, 10793> velocity=< 5, -1> position=<-21061, -53077> velocity=< 2, 5> position=< 21525, 10784> velocity=<-2, -1> position=<-10401, -53083> velocity=< 1, 5> position=< 10833, 10793> velocity=<-1, -1> position=< 42767, 10793> velocity=<-4, -1> position=< 10869, 21429> velocity=<-1, -2> position=<-42370, -53082> velocity=< 4, 5> position=< 10881, 53372> velocity=<-1, -5> position=<-10461, 21429> velocity=< 1, -2> position=<-21080, -42432> velocity=< 2, 4> position=< 42817, 10784> velocity=<-4, -1> position=< 42805, -10501> velocity=<-4, 1> position=<-42371, -31796> velocity=< 4, 3> position=<-42388, 32079> velocity=< 4, -3> position=< 21490, 21436> velocity=<-2, -2> position=<-10421, 42726> velocity=< 1, -4> position=< 21492, 42722> velocity=<-2, -4> position=< 42799, 42728> velocity=<-4, -4> position=<-53025, 10787> velocity=< 5, -1> position=< 21474, -42441> velocity=<-2, 4> position=< 53433, 10792> velocity=<-5, -1> position=< 32130, -31796> velocity=<-3, 3> position=< 53438, -10506> velocity=<-5, 1> position=<-10445, -21146> velocity=< 1, 2> position=< 21518, -10505> velocity=<-2, 1> position=< 32151, 42722> velocity=<-3, -4> position=< 21514, 42723> velocity=<-2, -4> position=<-31739, 21433> velocity=< 3, -2> position=<-21094, -10506> velocity=< 2, 1> position=< 32129, -31792> velocity=<-3, 3> position=< 42824, -53084> velocity=<-4, 5> position=<-52999, -42435> velocity=< 5, 4> position=< 53409, -31794> velocity=<-5, 3> position=<-42353, -10504> velocity=< 4, 1> position=< 32132, -42432> velocity=<-3, 4> position=< 42780, -42436> velocity=<-4, 4> position=< 10888, -31796> velocity=<-1, 3> position=<-10421, -53077> velocity=< 1, 5> position=<-53033, -21150> velocity=< 5, 2> position=< 21494, -53085> velocity=<-2, 5> position=< 21533, -10506> velocity=<-2, 1> position=< 53421, 32080> velocity=<-5, -3> position=< 32159, -10501> velocity=<-3, 1> position=< 10881, 21436> velocity=<-1, -2> position=< 21493, 32081> velocity=<-2, -3> position=<-42363, 53364> velocity=< 4, -5> position=<-52993, 42727> velocity=< 5, -4> position=< 10841, -31792> velocity=<-1, 3> position=< 10871, -53083> velocity=<-1, 5> position=<-42379, 53369> velocity=< 4, -5> position=< 21518, 21430> velocity=<-2, -2> position=<-31727, 32078> velocity=< 3, -3> position=<-42361, -31796> velocity=< 4, 3> position=< 32123, -21142> velocity=<-3, 2> position=< 10856, 10784> velocity=<-1, -1> position=< 10853, 21430> velocity=<-1, -2> position=< 21498, -31787> velocity=<-2, 3> position=<-21098, -10506> velocity=< 2, 1> position=<-42388, -10501> velocity=< 4, 1> position=<-42395, -31796> velocity=< 4, 3> position=< 10870, -42436> velocity=<-1, 4> position=< 42824, -10501> velocity=<-4, 1> position=< 42800, 10784> velocity=<-4, -1>
true
39fd9b1cd0f6ccdf1b21c17b1bfbe982eda2d334
Ruby
bdb2381/advanced-hashes-hashketball-sea01-seng-ft-071320
/hashketball.rb
UTF-8
8,639
3.6875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def game_hash { home: { team_name: "Brooklyn Nets", colors: ["Black", "White"], players: [ { player_name: "Alan Anderson", number: 0, shoe: 16, points: 22, rebounds: 12, assists: 12, steals: 3, blocks: 1, slam_dunks: 1 }, { player_name: "Reggie Evans", number: 30, shoe: 14, points: 12, rebounds: 12, assists: 12, steals: 12, blocks: 12, slam_dunks: 7 }, { player_name: "Brook Lopez", number: 11, shoe: 17, points: 17, rebounds: 19, assists: 10, steals: 3, blocks: 1, slam_dunks: 15 }, { player_name: "Mason Plumlee", number: 1, shoe: 19, points: 26, rebounds: 11, assists: 6, steals: 3, blocks: 8, slam_dunks: 5 }, { player_name: "Jason Terry", number: 31, shoe: 15, points: 19, rebounds: 2, assists: 2, steals: 4, blocks: 11, slam_dunks: 1 } ] }, away: { team_name: "Charlotte Hornets", colors: ["Turquoise", "Purple"], players: [ { player_name: "Jeff Adrien", number: 4, shoe: 18, points: 10, rebounds: 1, assists: 1, steals: 2, blocks: 7, slam_dunks: 2 }, { player_name: "Bismack Biyombo", number: 0, shoe: 16, points: 12, rebounds: 4, assists: 7, steals: 22, blocks: 15, slam_dunks: 10 }, { player_name: "DeSagna Diop", number: 2, shoe: 14, points: 24, rebounds: 12, assists: 12, steals: 4, blocks: 5, slam_dunks: 5 }, { player_name: "Ben Gordon", number: 8, shoe: 15, points: 33, rebounds: 3, assists: 2, steals: 1, blocks: 1, slam_dunks: 0 }, { player_name: "Kemba Walker", number: 33, shoe: 15, points: 6, rebounds: 12, assists: 12, steals: 7, blocks: 5, slam_dunks: 12 } ] } } end def num_points_scored(player_name) #for every player in :home and :away, return [:points] #test if the player_name == to :home, :player_name elseif == to :away, :player hash = game_hash() #access the main data player_stats = hash[:home][:players] + hash[:away][:players] #combine two arrays of :player into one array player_stats.each do |name| #for each player_name, loop through if name[:player_name] == player_name #if player_name = :player_name return name[:points] #return the :player_name's :points end #end if end #end player_stats do =begin ...........alt longer method of getting the same result index = 0 #counter for moving through array players[] which is an array of hashes while index < hash[:away][:players][index].length || index < hash[:home][:players][index].length do #so long as index is less then the lenght of either array of the team's roster if hash[:away][:players][index][:player_name] == player_name #find the away team player, and if there is a match, return the player's points return hash[:away][:players][index][:points] elsif hash[:home][:players][index][:player_name] == player_name #if not on away team, compare home team, if match, return points return hash[:home][:players][index][:points] end #end if block index+=1 end #while do loop :away #[:points] =end end #end num_points_scored() def shoe_size(player_name) #takes in an argument of a player's name and returns the shoe size for that player. hash = game_hash() #access the main data player_stats = hash[:home][:players] + hash[:away][:players] #combine 2 arrays of hashes :players into one array of hashes player_stats.each do |name| #for every name in player_stats if name[:player_name] == player_name #if names match, return the value of their :shoe size return name[:shoe] end #end if end #end player_stats do loop =begin ...........alt longer method of getting the same result index = 0 #counter for moving through array players[] which is an array of hashes while index < hash[:away][:players][index].length || index < hash[:home][:players][index].length do #so long as index is less then the lenght of either array of the team's roster if hash[:away][:players][index][:player_name] == player_name #find the away team player, and if there is a match, return the player's shoe size return hash[:away][:players][index][:shoe] elsif hash[:home][:players][index][:player_name] == player_name #if not on away team, compare home team, if match, return shoe size return hash[:home][:players][index][:shoe] end #end if block index += 1 end #while do loop =end end #end of shoe_size() def team_colors(team_name) hash = game_hash() #access the main data if hash[:home][:team_name] == team_name return hash[:home][:colors] elsif hash[:away][:team_name] == team_name return hash[:away][:colors] end #end if block end #end team_colors() def team_names () #return array of team names....["Brooklyn Nets", "Charlotte Hornets"] hash = game_hash() #access the main data team_names_array = [] #create blank array team_names_array[0] = hash[:home][:team_name] team_names_array[1] = hash[:away][:team_name] team_names_array end #end team_names() def player_numbers(team_name) #return player jersey numbers for a team # loop through the team_name's hash, if team_name == team_name, finding the jersey numbers, adding jersey numbers into array team_numbers = [] #create blank array hash = game_hash() #access the main data hash.each do |location_home_or_away, team_information| #loop through hash, to find the key/value pair of home/away status and its matching team name if team_name == team_information[:team_name] #compare the input of team_name to the key/value|key/value pair of :team_name, if match, execute next steps team_information[:players].each do |index| #for every player in the array :players, team_numbers << index[:number] #add the :number into a holding array end #end team_info do loop end end #end hash.each do loop team_numbers.sort #return array numbers of the team passed in end #player_numbers() def player_stats(player_name) #Build a method, player_stats, that takes in an argument of a player's name and returns a hash of that player's stats. #loop through hash, compare player_name to each player, if match, return the hash of player states # sequence/nesting of the hash/array: game_hash[:home][:players][array_index_var][:shoe] hash = game_hash() #access the main data hash.each do |location_home_or_away, team_information| #loop through the home and away values team_information[:players].each do |index| #loop through values looking for a player name if player_name == index[:player_name] #only at player_name level, if matching input, return the hash of player_name data return index end #end if end #team_information.each do end #end hash.each do end #end player_stats() def big_shoe_rebounds #return the number of rebounds associated with the player that has the largest shoe size. hash = game_hash() #access the main data all_player_data = hash[:home][:players] + hash[:away][:players] #Combine (concat) the two arrays hashes of players into one array of hashes to make it easier to compare #loop through with max, look to see which :shoe is bigger, based on 1, 0, -1, max returns the _hash_ of the largest shoe, not just the largest shoe player_with_largest_shoe = all_player_data.max do |first_player, second_player| first_player[:shoe] <=> second_player[:shoe] end player_with_largest_shoe[:rebounds] #return the number of rebounds of the player with largest shoe size #binding.pry end #end big_shoe_rebounds()
true
9ea7c8566892db4d9fd37a35a7b72e680a71dd80
Ruby
fifiteen82726/computer-security
/question_abc.rb
UTF-8
2,048
2.953125
3
[]
no_license
# 128 AES CBC require 'openssl' class MyEncryption def initialize(mode, size) @run_time_histroy = {} @mode = mode @size = size end def encryption_then_decrypt(data, file_name) size = data.size # Generate key start_time = Time.now cipher = OpenSSL::Cipher::AES.new(@size, @mode) cipher.encrypt key = cipher.random_key end_time = Time.now time = (end_time - start_time) * 1000 @run_time_histroy["AES-#{@mode}-#{@size}-key-generate"] = time # Encrypt start_time = Time.now iv = cipher.random_iv encrypted = cipher.update(data) + cipher.final end_time = Time.now time = (end_time - start_time) * 1000 @run_time_histroy["AES-#{@mode}-#{@size}-key-encrypt-#{file_name}"] = time @run_time_histroy["AES-#{@mode}-#{@size}-key-encrypt-#{file_name}-per-byte"] = time / size # Decrypt start_time = Time.now cipher.decrypt cipher.key = key cipher.iv = iv plain = cipher.update(encrypted) + cipher.final end_time = Time.now time = (end_time - start_time) * 1000 @run_time_histroy["AES-#{@mode}-#{@size}-key-decrypt-#{file_name}"] = time @run_time_histroy["AES-#{@mode}-#{@size}-key-decrypt-#{file_name}-per-byte"] = time / size return data == plain end def export_runtime @run_time_histroy.each do |k, v| p (k + (" %f" % v.to_s)) end end end def generate_data(size) return 'a' * size end def compute_with_different_mode_and_size(combinations) combinations.each do |combination| myencryption = MyEncryption.new(combination[0], combination[1]) # Generate 1KB data and do encryption, decryption file_1K = generate_data(10**3) myencryption.encryption_then_decrypt(file_1K, 'file_1K') # Generate 1MB data and do encryption, decryption file_1M = generate_data(10**6) myencryption.encryption_then_decrypt(file_1M, 'file_1M') myencryption.export_runtime end end combinations = [['CBC', 128], ['CTR', 128], ['CTR', 256]] compute_with_different_mode_and_size(combinations)
true
b084324d83e94f93302e387fb293b7a78d1cb5a0
Ruby
danielnaranjo/Ruby-Udemy
/guess.rb
UTF-8
570
3.71875
4
[]
no_license
answer = "Watson\n" puts("Let's play a guessing game. You get three tries.") print("What is the name of the computer that played on Jeopardy? ") response = gets if response == answer puts("That's right!") else print("Sorry. Guess again (Two tries left): ") response = gets if response == answer puts("That's right! ") else print("Sorry. Guess again (Only one try left): ") response = gets if response == answer puts("That's right") else print("Sorry. The answer s Watson..") end end end
true
b074a61de8245a5a6ff15f4f93f03524f0d91217
Ruby
sneharpatel/ruby-leetcode-problem-solving
/time_conversion.rb
UTF-8
544
3.796875
4
[]
no_license
# https://github.com/PaulNoth/hackerrank/tree/master/practice/algorithms/warmup/time_conversion # # def timeConversion(s) timeArr = s.split(":") hour = timeArr[0] min = timeArr[1] seconds = timeArr[2][0..1] am_pm = timeArr[2][2..3] if am_pm == "AM" if hour == "12" hour = "00" end else if hour != "12" hour = (hour.to_i + 12).to_s end end return (hour+":"+min+":"+seconds) end # s = "12:05:45PM" s1 = "07:05:45PM" # s = "12:05:45AM" p timeConversion(s) # o/p: "00:05:45" p timeConversion(s1)
true
7ba84c904bf40cf80f1782fb9ee159405756cfd6
Ruby
MiraMarshall/TaskList
/test/controllers/tasks_controller_test.rb
UTF-8
4,618
2.546875
3
[]
no_license
require "test_helper" require "test_helper" describe TasksController do # Note to students: Your Task model **may** be different and # you may need to modify this. let (:task) { Task.create name: "sample task", description: "this is an example for a test", completion_date: "date" } # Tests for Wave 1 describe "index" do it "can get the index path" do # Act get tasks_path # Assert must_respond_with :success end it "can get the root path" do # Act get root_path # Assert must_respond_with :success end end # Unskip these tests for Wave 2 describe "show" do it "can get a valid task" do # Act get task_path(task.id) # Assert must_respond_with :success end it "will redirect for an invalid task" do # Act get task_path(-1) # Assert must_respond_with :temporary_redirect end end describe "new" do it "can get the new task page" do # Act get new_task_path # Assert must_respond_with :success end end describe "create" do it "can create a new task" do # Arrange # Note to students: Your Task model **may** be different and # you may need to modify this. task_hash = { task: { name: "new task", description: "new task description", completion_date: "today", }, } # Act-Assert expect { post tasks_path, params: task_hash }.must_change "Task.count", 1 new_task = Task.find_by(name: task_hash[:task][:name]) expect(new_task.description).must_equal task_hash[:task][:description] expect(new_task.completion_date).must_equal task_hash[:task][:completion_date] must_respond_with :redirect must_redirect_to task_path(new_task.id) end end # Unskip and complete these tests for Wave 3 describe "edit" do it "can get the edit page for an existing task" do #Arrange existing_task = Task.create(name: "Study") # Act get edit_task_path(existing_task) # Assert must_respond_with :success end it "will respond with redirect when attempting to edit a nonexistant task" do bad_task_id = "THIS IS INVALID" # Act get edit_task_path(bad_task_id) # Assert must_redirect_to tasks_path end end # Uncomment and complete these tests for Wave 3 describe "update" do # Note: If there was a way to fail to save the changes to a task, that would be a great # thing to test. it "can update an existing task" do update_task_hash = { task: { name: "update task", description: "new task description", completion_date: "today", }, } existing_task = Task.create(name: "Hiking", description: "fun", completion_date: "Friday") patch task_path(existing_task), params: update_task_hash existing_task.reload expect(existing_task.completion_date).must_equal "today" end it "will redirect to the root page if given an invalid id" do # Arrange update_task_hash = { task: { name: "update task", description: "new task description", completion_date: "today", }, } invalid_task_id = "Invalid" #Act patch task_path(invalid_task_id), params: update_task_hash # Assert must_redirect_to root_path end end # Complete these tests for Wave 4 describe "destroy" do it "returns a 404 if the book is not found" do # Arrange invalid_task_id = "NOT A VALID ID" # Try to do the Books# destroy action expect { # Act delete task_path(invalid_task_id) }.must_change "Task.count", 0 must_respond_with :not_found end it "can delete a book" do # Arrange - Create a book new_task = Task.create(name: "Study") expect { # Act delete task_path(new_task.id) # Assert }.must_change "Task.count", -1 must_respond_with :redirect must_redirect_to tasks_path end end # Complete for Wave 4 describe "toggle_complete" do it "can mark a task as complete" do # Arrange complete_task = Task.create(name: "Study", description: "At Ada", completion_date: "Sunday", status: false) # Act patch toggle_path(complete_task.id) toggle = Task.find_by(id: complete_task.id) # Assert expect(toggle.status).must_equal true end end end
true
93c37c08956a293ff223019ac8d552efc1a89e6a
Ruby
donbader/DollayTon
/lib/triangle_arbitrage/strategy/base.rb
UTF-8
999
2.6875
3
[]
no_license
module TriangleArbitrage module Strategy class Base def initialize(base, coin1, coin2) @base = base @coin1 = coin1 @coin2 = coin2 @clients = [ Client::Cobinhood.corey, Client::Max.baimao, # Client::Binance.instance, ] end # @returns: <Hash> # { # orders: [ # { # client: # pair_name: for client args to place order # price: for client args to place order # method: for client args to place order # size: for client args to place order # } * 3 # ] # exchanged_percentage: after exchanging, the money will be how many times # max_invest_amount: max invest amount # invested_fund: invested fund # profit: profit calculated by invested fund # } def calculate(*_args, **_kwargs, &_block) raise NotImplementedError end end end end
true
8c206761981744e1dd0ca0e8fb4af70a1edd8a69
Ruby
eventide-project/virtual
/lib/virtual/protocol_method.rb
UTF-8
518
2.640625
3
[ "MIT" ]
permissive
module Virtual module ProtocolMethod Error = Class.new(RuntimeError) def self.define(target_class, method_name) method_defined = target_class.method_defined?(method_name, true) || target_class.private_method_defined?(method_name, true) if not method_defined target_class.send(:define_method, method_name) do |*args| raise Error, "Pure virtual (abstract) protocol method #{method_name} of #{self.class.name} must be implemented" end end end end end
true
a23282e2d5c6a17b55bdbfc11d784241d558c727
Ruby
edborden/MathFlowsAPI
/app/lib/processed_content.rb
UTF-8
975
2.65625
3
[]
no_license
module ProcessedContent def processed_content if content.blank? [Snippet.new] else EquationExtractor.new(content,try(:styles)).array end end def processed_content_lines element_width content_lines = [] unused_content = processed_content until unused_content.empty? content_line = ContentLine.new(unused_content,element_width) content_lines << content_line unused_content = content_line.unused_content_array end return content_lines end def write_to_pdf pdf content_lines = processed_content_lines pdf.bounds.right pdf.bounding_box [ 0, pdf.bounds.top ], width: pdf.bounds.right do y = 0 content_lines.each do |content_line| content_line_box = pdf.bounding_box [ 0, pdf.bounds.top - y ], width: pdf.bounds.right, height: content_line.height do content_line.write_to_pdf pdf end y += content_line_box.height end end end end
true
110f27383f5ab90f432356f92fdabaa506b61de6
Ruby
jpavioli/ruby-objects-has-many-through-lab-houston-web-career-040119
/lib/doctor.rb
UTF-8
653
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Doctor attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end def new_appointment(patient,date) #given a date and a patient, creates a new appointment Appointment.new(date,patient,self) end def appointments #returns an array of all apointments scheduled for the doctor Appointment.all.select {|appointment| appointment.doctor == self} end def patients #returns a unique array of all patients being treated by the docotr self.appointments.map {|appointment| appointment.patient}.uniq end def self.all #returns an array of all docotrs @@all end end
true
b793edcc5a64eb81a3e0f6c65f029aeaf5e9f6ab
Ruby
collabnix/dockerlabs
/vendor/bundle/ruby/2.6.0/gems/rubocop-0.93.1/lib/rubocop/cop/style/class_methods.rb
UTF-8
1,439
2.625
3
[ "CC-BY-NC-4.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
# frozen_string_literal: true module RuboCop module Cop module Style # This cop checks for uses of the class/module name instead of # self, when defining class/module methods. # # @example # # bad # class SomeClass # def SomeClass.class_method # # ... # end # end # # # good # class SomeClass # def self.class_method # # ... # end # end class ClassMethods < Base extend AutoCorrector MSG = 'Use `self.%<method>s` instead of `%<class>s.%<method>s`.' def on_class(node) return unless node.body if node.body.defs_type? check_defs(node.identifier, node.body) elsif node.body.begin_type? node.body.each_child_node(:defs) do |def_node| check_defs(node.identifier, def_node) end end end alias on_module on_class private def check_defs(name, node) # check if the class/module name matches the definee for the defs node return unless name == node.receiver message = format(MSG, method: node.method_name, class: name.source) add_offense(node.receiver.loc.name, message: message) do |corrector| corrector.replace(node.receiver, 'self') end end end end end end
true
1747bb78ebabe8ac82d1d6b34b00641f40b3515a
Ruby
pathawks/kibana-demo
/random.rb
UTF-8
648
2.984375
3
[]
no_license
def randomDay r = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 6, 6].sample return r * 24 * 60 * 60 end def randomHour r = [0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23].sample return r * 60 * 60 end def randomMinute r = rand(60) return r * 60 end def randomSecond r = rand(60) return r end def randomTimeOffset return randomDay + randomHour + randomMinute + randomSecond end
true
e13ff717cd6077d41675dad6c3cec97633287c53
Ruby
brgeen/App-Academy-Ruby-Practice
/advanced_problems/most_vowels.rb
UTF-8
481
3.796875
4
[]
no_license
def most_vowels(sentence) vowels = "aeiou" count = Hash.new(0) sentence.split.each do |ele| count[ele] = 0 end count.each_key do |key| key.each_char do |char| if vowels.include?(char) count[key] += 1 end end end sorted = count.sort_by { |k, v| v } return sorted[-1][0] end print most_vowels("what a wonderful life") #=> "wonderful" puts print most_vowels("Hello I am wondering which one of these words has the most vowels in it")
true
63c4af7c99e0db2d369f068654c0b72ac6ac0045
Ruby
MisterDeejay/Poker
/lib/deck.rb
UTF-8
837
3.921875
4
[]
no_license
require_relative 'card' class Deck attr_accessor :ary_of_cards def initialize @ary_of_cards = Deck.create_deck end def count ary_of_cards.count end def shuffle ary_of_cards.shuffle! end def deal_hand(number = 5) new_cards = ary_of_cards.take(number) self.ary_of_cards = ary_of_cards.drop(number) new_cards end def return_cards(cards) cards.each do |card| ary_of_cards << card end end private def self.create_deck temp_deck = [] Card::SUITS.each do |suit| Card::VALUES_HASH.each_key do |value| temp_deck << Card.new(suit, value) end end temp_deck end end d = Deck.new a = d.deal_hand p "Before returning cards, there are #{d.count} in the deck" d.return_cards(a) p "After returning cards, there are #{d.count} in the deck"
true
172b86bcbdca4b48dd63c2b0065eb6af3d668bcc
Ruby
ptolemybarnes/baby-steps
/katas/lib/instant_runoff_voting.rb
UTF-8
2,078
3.65625
4
[]
no_license
# CodeWars Kata: http://www.codewars.com/kata/52996b5c99fdcb5f20000004/train/ruby # Solution by Ptolemy Barnes. =begin Your task is to implement a function that calculates an election winner from a list of voter selections using an Instant Runoff Voting algorithm: 1) Each voter selects several candidates in order of preference. 2) The votes are tallied from the each voter's first choice. 3) If the first-place candidate has more than half the total votes, they win. 4) Otherwise, find the candidate who got the least votes and remove them from each person's voting list. 5) In case of a tie for least, remove all of the tying candidates. 6) In case of a complete tie between every candidate, return nil. 7) Start over. 8) Continue until somebody has more than half the votes; they are the winner. Your function will be given a list of voter ballots; each ballot will be a list of candidates (symbols) in descending order of preference. You should return the symbol corresponding to the winning candidate. See the default test for an example =end def runoff voters votes = get_leading_votes_from(voters) leading_candidate = who_has_most votes return leading_candidate if is_winner?(leading_candidate, votes) losers = who_has_least(votes, get_candidates_hash(voters)) return nil if losers.empty? runoff(next_round(voters,losers)) end def get_leading_votes_from voters voters.map {|votes| votes[0] } end def who_has_most votes votes.max_by {|x| votes.count(x) } end def is_winner? candidate, votes votes.count(candidate) / votes.size.to_f > 0.5 end def who_has_least votes, counts votes.each {|vote| counts[vote] += 1} losers = counts.select do |cand, votes| (votes == counts.values.min && votes != counts.values.max) end losers.keys end def get_candidates_hash voters vote_count = Hash.new voters.flatten.uniq.each {|candidate| vote_count[candidate] = 0 } vote_count end def next_round voters, losers losers.each do |loser| voters.each {|vote_card| vote_card.delete(loser)} end voters end
true
08246b4a3a70bb64a618335729101ee2358b7bb8
Ruby
bird1204/maoyuan_farm
/app/helpers/carts_helper.rb
UTF-8
670
2.765625
3
[ "MIT" ]
permissive
module CartsHelper def hello_message if current_user "會員:#{current_user.email.split('@').first} 您好!" else "非會員:您是會員嗎?請先登入" end end def cart_message(cart) "共購買 #{cart.total_unique_items} 項商品 運費共:$#{cart.shipping_cost} 消費總金額:$#{cart.total}" end def success_message(cart) "共購買&nbsp;<font size='4' color='#ff6666'>#{cart.total_unique_items}</font>&nbsp;項商品&nbsp;&nbsp;運費共:<font size='4' color='#ff6666'>$#{cart.shipping_cost}</font>&nbsp;&nbsp;消費總金額:<font size='4' color='#ff6666'>$#{cart.total}</font>".html_safe end end
true
96e98dbf111054872ea94c1277e3ae0f15ccc97c
Ruby
joshlacey/programming_languages-prework
/programming_languages.rb
UTF-8
416
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def reformat_languages(languages) new_hash = {} languages.each do |style, list| list.each do |language, attribute| new_hash[language]= attribute new_hash[language][:style] = [] end end languages.each do |style, list| list.each do |language, attribute| new_hash[language][:style] << style end end new_hash end
true
26c3ace8845c1b34d30394a6996eead7f61f0c70
Ruby
andrew-black512/tools
/file_with_head.rb
UTF-8
873
2.984375
3
[]
no_license
#!/usr/bin/ruby require 'colorize' require 'open3' #https://www.honeybadger.io/blog/capturing-stdout-stderr-from-shell-commands-via-ruby/ #--------------------------------------------------------------------- # Semi config #--------------------------------------------------------------------- def print_indented_text textstring indent = ' ' textarr = textstring.split "\n" textarr = textarr.reverse textarr.each do |l| l.sub! /\s/, ' ' puts "#{indent}#{l}" end end #--------------------------------------------------------------------- #puts "a".methods filename = ARGV.shift command = ARGV.join ' ' # remaining args puts filename.light_green.bold puts command.blue stdout, stderr, status = Open3.capture3( command ) #QUERY - can status be used? if stderr == '' print_indented_text stdout else puts stderr end
true
055f1ec14debe1770c2c6488c14546d8aab15a26
Ruby
Scooterlicious/twendy
/db/seeds.rb
UTF-8
1,183
2.78125
3
[]
no_license
# ================================ # CREATES COUNTRIES AND ADDS WOEID # ================================ client = Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] config.access_token = ENV['TWITTER_ACCESS_TOKEN'] config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET'] end countries = [] country_data = client.trends_available country_data.each do |x| countries.push(x[:attrs][:country]) end countries.uniq!.sort!.slice!(0,1) countries.each do |country| id = "Q6S.eLHV34GwNc79pswEdclgszSHyCyV7u5nb4kCEkfySEnahkUqyCEN1W1o2LsXR40GWpY" url_country = country.gsub(" ", "%20") pull = HTTParty.get("http://where.yahooapis.com/v1/places.q(#{url_country})?appid=#{id}") woeid = pull["places"]["place"]["woeid"] puts "======================" puts "#{country} // #{woeid}" puts "======================" if Country.where(name: country, woeid: woeid) == [] Country.create(name: country, woeid: woeid) else puts "=#{country} already exists=" end end if Country.where(name: "Worldwide", woeid: 1) == [] Country.create(name: "Worldwide", woeid: 1) else puts "=Worldwide already exists=" end
true
1aff40b183a65eecaf6a7f2086b219994f3efe16
Ruby
dmolesUC/xml-mapping_extensions
/example.rb
UTF-8
1,159
2.828125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'xml/mapping_extensions' require 'rexml/document' class MyElem include ::XML::Mapping root_element_name 'my_elem' date_node :plain_date, 'plain_date' date_node :zulu_date, 'zulu_date', zulu: true time_node :time, 'time' uri_node :uri, 'uri' mime_type_node :mime_type, 'mime_type' end # Reading XML xml_str = "<my_elem> <plain_date>1999-12-31</plain_date> <zulu_date>2000-01-01Z</zulu_date> <time>2000-01-01T02:34:56Z</time> <uri>http://example.org</uri> <mime_type>text/plain</mime_type> </my_elem>" xml_doc = REXML::Document.new(xml_str) xml_elem = xml_doc.root elem = MyElem.load_from_xml(xml_elem) puts elem.plain_date.inspect puts elem.zulu_date.inspect puts elem.time.inspect puts elem.uri.inspect puts elem.mime_type.inspect # Writing XML elem = MyElem.new elem.plain_date = Date.new(1999, 12, 31) elem.zulu_date = Date.new(2000, 1, 1) elem.time = Time.utc(2000, 1, 1, 2, 34, 56) elem.uri = URI('http://example.org') elem.mime_type = MIME::Types['text/plain'].first xml = elem.save_to_xml formatter = REXML::Formatters::Pretty.new formatter.compact = true puts(formatter.write(xml, ''))
true
202f9304320d5a8239e74e505282eb73c66de74c
Ruby
noda50/practis-dev
/lib/practis/executable.rb
UTF-8
697
2.625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'practis' module Practis #=== Store current executable. class ExecutableGroup include Practis def initialize @threads = ThreadGroup.new end def exec(*args) th = Thread.start do fork_exec(*args) end @threads.add(th) end def fork_exec(*args) if pid = fork Process.waitpid(pid) else Kernel.exec(*args) end end def wait @threads.list.each do |th| th.join end end def update @threads.list.each { |th| th.join unless th.alive? } end def length return @threads.list.length end end end
true
ce57eef29c01ca4cf427018db22e56ffad51f50a
Ruby
T-Dnzt/Moltin-Ruby-SDK
/lib/moltin/resource.rb
UTF-8
1,184
2.703125
3
[ "MIT" ]
permissive
module Moltin class Resource attr_accessor :config, :storage def initialize(config, storage) @config = config @storage = storage end # Public: Retrieve the access_token from storage or from the API # # Returns a valid access_token if the credentials were valid def get_access_token auth = storage['authentication'] return auth['access_token'] if auth && auth['expires'] > Time.now.to_i auth = authenticate_client storage['authentication'] = auth auth['access_token'] end # Public: Call the Moltin API passing the credentials to retrieve a valid # access_token # # Raises an Errors::AuthenticationError if the call fails. # Returns a valid access_token if the credentials were valid. def authenticate_client body = { grant_type: 'client_credentials', client_id: @config.client_id, client_secret: @config.client_secret } response = Faraday.new(url: @config.base_url).post("/#{@config.auth_uri}", body) body = JSON.parse(response.body) raise Errors::AuthenticationError unless body['access_token'] body end end end
true
c7cce8a9e9a500db6fdd76cfa62cd5825bb50e6f
Ruby
katcarr/recipe_box
/spec/recipe_spec.rb
UTF-8
1,627
2.59375
3
[ "MIT" ]
permissive
require("rspec") describe(Recipe) do it { should have_and_belong_to_many(:ingredients) } it { should have_and_belong_to_many(:categories) } describe('#update_ingredients') do it 'adds new, leaves same and deletes old ingredients from a recipe' do test_recipe = Recipe.new({:title => "Pea Soup", :instructions => "Cook"}) test_ingredient0 = Ingredient.create({:name => "peas"}) test_ingredient1 = Ingredient.create({:name => "salt"}) test_recipe.ingredients << test_ingredient0 test_recipe.ingredients << test_ingredient1 test_ingredients = [] test_ingredients.push(test_ingredient1) test_ingredient2 = Ingredient.create({:name => "potatoes"}) test_ingredients.push(test_ingredient2) test_recipe.update_ingredients(test_ingredients) expect(test_recipe.ingredients).to(eq([test_ingredient1, test_ingredient2])) end end describe('#update_categories') do it 'adds new, leaves same and deletes old categories from a recipe' do test_recipe = Recipe.new({:title => "Pea Soup", :instructions => "Cook"}) test_category0 = Category.create({:name => "peas"}) test_category1 = Category.create({:name => "salt"}) test_recipe.categories << test_category0 test_recipe.categories << test_category1 test_categories = [] test_categories.push(test_category1) test_category2 = Category.create({:name => "potatoes"}) test_categories.push(test_category2) test_recipe.update_categories(test_categories) expect(test_recipe.categories).to(eq([test_category1, test_category2])) end end end
true
f55e0e3012aa22d213bfca232e82f7fc64711902
Ruby
mohammad523/backend-capstone
/db/seeds.rb
UTF-8
1,470
2.59375
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Post.create( [ {username: '@mohaha', your_name: 'Mohammad Hasan', message: 'Wow cool website', likes:0 }, {username: '@mohaha', your_name: 'Mohammad Hasan', message: 'How many programmers does it take to change a light bulb? None – It’s a hardware problem', likes:0 }, {username: '@mohaha', your_name: 'Mohammad Hasan', message: '“I just saw my life flash before my eyes and all I could see was a html close tag…”', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: 'hows everyone doing', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: 'pretty cool', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: 'i love games!!', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: 'hey hows it going', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: 'I love pizza', likes:0 }, {username: '@person', your_name: 'Mysterious Person ', message: '"Half of knowledge is being able to say I dont know"', likes:0 }, ] )
true
06f52549388c69a061768aaf8684dc40887e3cee
Ruby
timgaleckas/oauth2_provider_engine
/app/models/oauth2_provider/access.rb
UTF-8
2,813
2.609375
3
[ "MIT" ]
permissive
# Access info related to a resource owner using a specific # client (block and statistics) if defined?(Mongoid::Document) module Oauth2Provider class Access include Mongoid::Document include Mongoid::Timestamps field :client_uri # client identifier (internal) field :resource_owner_uri # resource owner identifier field :blocked, type: Time, default: nil # authorization block (a user block a single client) embeds_many :daily_requests, class_name: 'Oauth2Provider::DailyRequest' # daily requests (one record per day) end end elsif defined?(ActiveRecord::Base) module Oauth2Provider class Access < ActiveRecord::Base set_table_name :oauth2_provider_accesses has_many :daily_requests end end elsif defined?(MongoMapper::Document) raise NotImplementedError elsif defined?(DataMapper::Resource) raise NotImplementedError end module Oauth2Provider class Access validates :client_uri, presence: true validates :resource_owner_uri, presence: true # Block the resource owner delegation to a specific client def block! self.blocked = Time.now self.save Token.block_access!(client_uri, resource_owner_uri) Authorization.block_access!(client_uri, resource_owner_uri) end # Unblock the resource owner delegation to a specific client def unblock! self.blocked = nil self.save end # Check if the status is or is not blocked def blocked? !self.blocked.nil? end # Increment the daily accesses def accessed! daily_requests_for(Time.now).increment! end # A daily requests record (there is one per day) # # @params [String] time we want to find the requests record # @return [DailyRequest] requests record def daily_requests_for(time = Time.now) find_or_create_daily_requests_for(time) end # Give back the last days in a friendly format.It is used to # generate graph for statistics def chart_days daily_requests = self.daily_requests.limit(10) days = daily_requests.map(&:created_at) days.map { |d| d.strftime("%b %e") } end # Give the number of accesses for the last days. It is used # to generate graph for statistics def chart_times access_times = self.daily_requests.limit(10) access_times.map(&:times) end private def find_or_create_daily_requests_for(time) daily_requests_for_time = self.daily_requests.find_day(time).first daily_requests_for_time = self.daily_requests.create(created_at: time) unless daily_requests_for_time return daily_requests_for_time end def daily_id(time) time.year + time.month + time.day end end end
true
0ff0ac7c41b8776007ae1855e23e538b83dae897
Ruby
willfowls/prepcourse
/ruby_books/intro_to_ruby/3rd_attempt_at_exercises/61.rb
UTF-8
278
3.34375
3
[]
no_license
# take array and turn it to new array that consists of strings containing one word a = ['white snow', 'winter wonderland', 'melting ice', 'slippery sidewalk', 'salted roads', 'white trees'] a = a.map { |pairs| pairs.split } a = a.flatten p a # no check
true
08a36314daae58059f3606eb3d88b4ad169a93b6
Ruby
WilfredTA/algorithmic_acrobatics
/Dynamic Programming/min_path_sum.rb
UTF-8
2,457
4.28125
4
[]
no_license
#Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. #Note: You can only move either down or right at any point in time. #Example 1: #[[1,3,1], # [1,5,1], # [4,2,1]] #Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum. # 1. Rephrase the problem as a general problem, then assume it is solved and # redefine the solution in terms of the solution to sub problems # 2. Express the solutions of sub-problems with recursion: # A). Parameters and Return value # B). Reduction - How the sub-problems lead up to the general problem* # C). Base Case # D). Use the return value # 3. Optimize with a cache # - Check the cache first before the recursive calls # * This is usually the hardest part. There are certain things to look for in a # problem description to help identify how the reduction should be. If you are # supposed to find a minimum value (such as in this case), then the return value of the # recursive calls will probably be compared and the lesser of the two will be used # USING THE PROCESS # STEP 1 # Assume we have reached the bottom right corner of the grid: which path # is the one that we took to get there? We took the minimum path. Which path is the # minimum path? Well, it is the current value added two the minimum of the path that # terminates one cell above the bottom right, and the path that terminates one cell # to the left of bottom right. # So, min_path(x,y) is the lesser of the two paths that terminate at x-1, y and x, y-1 # The sum of min_path(x,y) is the val of x,y + the sum of those two paths. # STEP 2 # The return value of min_path needs to be a sum # The parameters will be the grid and the x and y value of the current cell def min_path_sum(grid) min_path_sum_helper(grid, grid.length - 1, grid[0].length - 1) end def min_path_sum_helper(grid, rows, cols, memo = {}) if rows == 0 && cols == 0 return grid[rows][cols] end if rows < 0 || cols < 0 return Float::INFINITY end path1 = memo[[rows-1, cols]] || min_path_sum_helper(grid, rows-1, cols, memo) path2 = memo[[rows, cols-1]] || min_path_sum_helper(grid, rows, cols-1, memo) memo[[rows, cols]] = grid[rows][cols] + min(path1, path2) end def min(x, y) if x < y return x else return y end end p min_path_sum([[1,3,1], [1,5,1], [4,2,1]]) # 7
true
574968c9edffc6d47c59535ef8ac7aa208d2b755
Ruby
prashanthrajagopal/SalesTax
/lib/order.rb
UTF-8
1,118
3.421875
3
[]
no_license
require_relative './tax_calculator' require_relative './math' require 'bigdecimal' class Order def initialize(args, quant) @products = args @quantities = quant end def calculate_tax product_tax = [] @products.each do |product| tc = TaxCalculator.new(product) tax_rate = tc.calculate_tax_rate product_tax << (Math.round_with_precision((product.price * tax_rate), BigDecimal('0.05'))).round(2) end product_tax end def item_price_with_tax item_price = [] @products.each_with_index do |product, index| item_price << ((product.price + calculate_tax[index]) * @quantities[index]).round(2) end item_price end def sales_tax_total (calculate_tax.inject(:+)).round(2) end def total (item_price_with_tax.inject(:+)).round(2) end def order_receipt @products.each_with_index do |product, index| puts "#{@quantities[index]} #{product.name} at #{product.price.to_f}\t=>\t#{item_price_with_tax[index].to_f}" end puts "Sales Tax total\t=>\t#{sales_tax_total.to_f}" puts "Order Total\t=>\t#{total.to_f}" end end
true
bcca4623611af2f0259525204212f16204b70aa9
Ruby
lorca/flat_file_benchmark
/gen_data.rb
UTF-8
494
2.859375
3
[]
no_license
# # generate a data file # # do ruby gen_data.rb > input/mydata.csv # user_id=1 for user_id in (1..10000) payments = (rand * 1000).to_i for user_payment_id in (1..payments) payment_id = user_id.to_s + user_payment_id.to_s payment_amount = "%.2f" % (rand * 30); is_card_present = "N" created_at = (rand * 10000000).to_i if payment_id.to_i % 3 == 0 is_card_present = "Y" end puts [user_id, payment_id, payment_amount, is_card_present, created_at].join("\t") end end
true
920300350837676071082ee1254560e08cf5ff9f
Ruby
elbagre/Chess-Project
/pieces/pawn.rb
UTF-8
933
3.625
4
[]
no_license
require 'byebug' require_relative "piece" class Pawn < Piece WHITE_MOVES = [ [-1, 0], [-1, -1], [-1, 1], [-2, 0] ] BLACK_MOVES = [ [1, 0], [1, -1], [1, 1], [2, 0] ] def initialize(position, color, board) super(position, color, board) @color == :white ? @symbol = " ♟ ".colorize(:white) : @symbol = " ♟ " end def moves current_moves.each_with_object([]) do |move, valid_moves| new_pos = position[0] + move[0], position[1] + move[1] next unless valid_move?(new_pos) valid_moves << new_pos end end private def starting_position? if color == :white position[0] == 6 else position[0] == 1 end end def current_moves if starting_position? color_moves else color_moves[0..2] end end def color_moves if color == :white WHITE_MOVES else BLACK_MOVES end end end
true
8bd36c60b9974443c57b4613573be4315fdb3fa4
Ruby
rsoemardja/Codecademy
/Ruby/Learn Ruby/Looping/Loops & Iterators/The 'Until' Loop.rb
UTF-8
218
2.828125
3
[]
no_license
# Problem counter = 1 until counter __ 10 puts counter # Add code to update 'counter' here! end # Solution counter = 1 until counter > 10 puts counter # Add code to update 'counter' here! counter += 1 end
true
e9fc62cb0d6312660a3efdf08152f3344bf76988
Ruby
Filipe-p/OTB-test
/lib/OTB/queue.rb
UTF-8
1,945
3.125
3
[ "MIT" ]
permissive
module OTB class Queue attr_accessor :jobs, :jobs_parsed #usign job:nil for stability & latter flexibity # Idea being you could also have string:nil # then you could initialized with Job objects in the jobs: # or you could initialized with String objects in the string: def initialize(string:nil) @jobs = string @jobs_parsed = OTB::Job.parse(@jobs) unless string.nil? end def sort_sequence case @jobs when '' '' when nil raise JobQueueError.no_input_error else check_self_dependency(@jobs_parsed) check_circular_dependency(@jobs_parsed) sort_jobs_to_sequence(@jobs_parsed) end end private def check_self_dependency(jobs_parsed) jobs_parsed.each do |job, dependency| if job == dependency raise JobQueueError.self_dependency_error end end end def check_circular_dependency(jobs_parsed) hash_jobs_with_depencecies = {} jobs_parsed.each_with_index do |job_dependency, index| [job_dependency].each do |job, dependency| if hash_jobs_with_depencecies.keys.include?(dependency) && hash_jobs_with_depencecies.values.include?(job) raise JobQueueError.circular_dependecy_error end hash_jobs_with_depencecies[job] = dependency unless dependency.empty? end end end def sort_jobs_to_sequence(jobs_parsed) sequence = [] jobs_parsed.each do |job, dependency| if dependency.empty? sequence << job unless sequence.include?(job) elsif sequence.include?(job) index = sequence.find_index(job) sequence.insert(index, dependency) else sequence << dependency unless sequence.include?(dependency) sequence << job unless sequence.include?(job) end end sequence.join(', ') end end end
true
f276b5ee641ea98d28f2779eed2bc8c19efd1b5e
Ruby
Furaha/ugandasms
/app/models/participant.rb
UTF-8
1,289
2.546875
3
[]
no_license
class Participant < ActiveRecord::Base require 'csv' validates :number, presence: true has_many :answers def self.import(file) CSV.foreach(file.path, headers: true) do |row| participant_hash = row.to_hash participant = Participant.where(number: participant_hash["number"]) if participant.count == 1 participant.first.update_attributes(participant_hash) else Participant.create!(participant_hash) end # end if !participant.nil? end # end CSV.foreach end # end self.import(file) def send_message(msg) @twilio_number = ENV['TWILIO_NUMBER'] @client = Twilio::REST::Client.new ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'] message = @client.account.messages.create( :from => @twilio_number, :to => self.number, :body => msg, ) puts message.to end def track_campaign(campaign_id) self.update(current_campaign: campaign_id) end def tracked_campaign if self.current_campaign.nil? return nil else return Campaign.find(self.current_campaign) end end def campaign_is_tracked?(campaign_record_id) if (!self.tracked_campaign.nil? && (self.tracked_campaign.id == campaign_record_id)) true else false end end end
true
7c4b6cf33dbe2d1742d0b57aaefddd55d5ac7429
Ruby
kazunetakahashi/atcoder-ruby
/0208_ARC033/C.rb
UTF-8
99
2.90625
3
[ "MIT" ]
permissive
s = gets.chomp.split("+") x = 0 s.each{|y| if y.include?("0") x += 1 end } puts s.size - x
true
b198358579add741338b7587395490d0af49cdc0
Ruby
RJ-Ponder/RB101
/lesson_6/scratch.rb
UTF-8
76
2.546875
3
[]
no_license
def clear(state = 'clear') system state puts "this is a test" end clear
true
0e44f68b9b96b9ac38c8616a65c77996605a1e7b
Ruby
quetzaluz/codesnippets
/ruby/codeeval/007_prefix_expressions.rb
UTF-8
596
3.578125
4
[]
no_license
OPS = ['+', '/', '*'] def pref(line) s = line.split(' ') r = [] s.reverse.each do |i| if OPS.include?(i) r1 = r.pop() r2 = r.pop() if i == '+' r.push(r1 + r2) elsif i == '*' r.push(r1 * r2) elsif i == '/' r.push(r1.to_f / r2.to_f) end else r.push(i.to_i) end end rf = r[0] ri = r[0].to_i return ri == rf ? ri : rf end File.open(ARGV[0]).each_line do |line| puts(pref(line)) end
true
1e9a56bf038a227c7fd3beaa3f187ae7f82e5351
Ruby
tmaria17/pantry
/test/pantry_test.rb
UTF-8
2,054
3.234375
3
[]
no_license
require './lib/pantry' require './lib/recipe' require 'minitest/autorun' require 'minitest/pride' require 'pry' class PantryTest < Minitest::Test def test_it_exists pantry = Pantry.new assert_instance_of Pantry , pantry end def test_stock_hash pantry = Pantry.new assert_equal({ }, pantry.stock) #assert_equal Hash , pantry.stock.class end def test_stock_check pantry = Pantry.new pantry.restock("Cheese",0) assert_equal 0 , pantry.stock_check("Cheese") end def test_you_can_restock pantry= Pantry.new pantry.restock("Cheese", 10) assert_equal 10, pantry.stock_check("Cheese") pantry.restock("Cheese", 20) assert_equal 30, pantry.stock_check("Cheese") end def test_shopping_list_exists pantry= Pantry.new r = Recipe.new("Cheese Pizza") r.add_ingredient("Cheese", 20) r.add_ingredient("Flour", 20) pantry.add_to_shopping_list(r) assert_equal({"Cheese" => 20,"Flour" => 20} , pantry.shopping_list) end def test_you_can_add_more_to_shopping_list pantry = Pantry.new r = Recipe.new("Cheese Pizza") r.add_ingredient("Cheese", 20) r.add_ingredient("Flour", 20) pantry.add_to_shopping_list(r) r = Recipe.new("Spaghetti") r.add_ingredient("Spaghetti Noodles", 10) r.add_ingredient("Marinara Sauce", 10) r.add_ingredient("Cheese", 5) pantry.add_to_shopping_list(r) assert_equal({"Cheese" => 25, "Flour" => 20, "Spaghetti Noodles" => 10, "Marinara Sauce" => 10}, pantry.shopping_list) end def test_you_can_add_to_cookbook pantry = Pantry.new r1 = Recipe.new("Cheese Pizza") r1.add_ingredient("Cheese", 20) r1.add_ingredient("Flour", 20) r2 = Recipe.new("Pickles") r2.add_ingredient("Brine", 10) r2.add_ingredient("Cucumbers", 30) r3 = Recipe.new("Peanuts") r3.add_ingredient("Raw nuts", 10) r3.add_ingredient("Salt", 10) pantry.add_to_cookbook(r1) pantry.add_to_cookbook(r2) pantry.add_to_cookbook(r3) assert_equal [r1,r2,r3] , pantry.cookbook end end
true
1908d0b26fb9e41c96ba0359a4b8307df52cbf08
Ruby
himaratsu/nokogiri_moviecom
/sample.rb
UTF-8
304
2.703125
3
[]
no_license
# -- coding: utf-8 require "open-uri" require "rubygems" require "nokogiri" # スクレイピングするURL url = "http://www.walmart.com.br/" charset = nil html = open(url) do |f| charset = f.charset f.read end doc = Nokogiri::HTML.parse(html, nil, charset) # タイトルを表示 p doc.title
true
bd05a2f29d35447253b0a73270cf0e31421d5321
Ruby
LinuxGit/Code
/ruby/ProgrammingRuby/block_object.rb
UTF-8
87
2.8125
3
[]
no_license
bo = lambda { |param| puts "You called me with #{param}" } bo.call "ruby" bo.call "51"
true
e52259cf57573ea9d21faecad651fbcb69a1e557
Ruby
n-studio/arena-test
/app/services/fight_service.rb
UTF-8
2,635
3.140625
3
[ "Beerware" ]
permissive
class FightService POINTS_LIMIT = ENV.fetch('POINTS_LIMIT', 10) LIFE_POINTS_FACTOR = ENV.fetch('LIFE_POINTS_FACTOR', 5) MAX_STEPS_COUNT = ENV.fetch('MAX_STEPS_COUNT', 20) FIGHTERS_COUNT_MAX = ENV.fetch('FIGHTERS_COUNT_MAX', 2) attr_reader :fight, :fighters def initialize(fight:) @fight = fight @fighters = fight.fighters @fighters.each(&:init_stats) end def start steps_count = 0 while @fighters[0].remaining_life_points.positive? && @fighters[1].remaining_life_points.positive? create_step steps_count += 1 break if steps_count > MAX_STEPS_COUNT end finish end def finish @fight.update_attribute(:state, "finished") if @fighters[0].remaining_life_points.positive? && @fighters[1].remaining_life_points <= 0 winner_index = 0 loser_index = 1 elsif @fighters[1].remaining_life_points.positive? && @fighters[0].remaining_life_points <= 0 winner_index = 1 loser_index = 0 else return end @fight.fight_attendances.find_by(fighter_id: @fighters[winner_index]).update_column(:winner, true) @fight.fight_attendances.find_by(fighter_id: @fighters[loser_index]).update_column(:loser, true) @fighters[winner_index].increment!(:wins_count) @fighters[loser_index].increment!(:losses_count) end private JANKEN_HANDS = %w[✊ ✋ ✌️].freeze JANKEN_BEATS = { "✊" => "✌️", "✋" => "✊", "✌️" => "✋" }.freeze def create_step fighter1_hand, fighter2_hand = janken_hands_result winner = janken_winner(fighter1_hand, fighter2_hand) fighter1_damage_points = @fighters[0] == winner || winner.nil? ? 0 : @fighters[1].attack_points fighter2_damage_points = @fighters[1] == winner || winner.nil? ? 0 : @fighters[0].attack_points FightStep.create( fight: @fight, hands: [fighter1_hand, fighter2_hand].join(","), damage_points: [fighter1_damage_points, fighter2_damage_points].join(","), remaining_life_points: [@fighters[0].remaining_life_points, @fighters[1].remaining_life_points].join(",") ) update_life_points(fighter1_damage_points, fighter2_damage_points) end def update_life_points(*damage_points) @fighters[0].remaining_life_points -= damage_points[0] @fighters[1].remaining_life_points -= damage_points[1] end def janken_hands_result hand1 = JANKEN_HANDS.sample hand2 = JANKEN_HANDS.sample [hand1, hand2] end def janken_winner(hand1, hand2) if hand1 == hand2 nil elsif JANKEN_BEATS[hand1] == hand2 @fighters[0] else @fighters[1] end end end
true
6f94dd08422cb1e09ac9de2c3f56895ab0fad6d7
Ruby
mihirkelkar/languageprojects
/ruby/code_eval_stack.rb
UTF-8
287
3.234375
3
[]
no_license
#!/usr/bin/ruby fileContent = open(ARGV[0], 'r').readlines fileContent.each do |line| reverse_temp = line.split().reverse join_list = [] for ii in (0..reverse_temp.length - 1) if ii % 2 == 0 join_list << reverse_temp[ii].to_s end end puts join_list.join(" ") end
true
083e838e7fb489567d0aa6c79885e3229eb849c4
Ruby
jrambold/scrabble
/test/player_test.rb
UTF-8
833
2.9375
3
[]
no_license
gem 'minitest' require_relative '../lib/player' require_relative '../lib/scrabble' require 'minitest/autorun' require 'minitest/pride' require 'pry' class PlayerTest < Minitest::Test def setup @player_1 = Player.new(Scrabble.new) end def test_total_score_starts_at_0 assert_equal 0, @player_1.total_score end def test_total_score_increases @player_1.play('bear') assert_equal 6, @player_1.total_score @player_1.play('quality') assert_equal 25, @player_1.total_score @player_1.play('heloooo') assert_equal 25, @player_1.total_score end def test_turns_starts_at_0 assert_equal 0, @player_1.turns end def test_turns_increase_when_playing @player_1.play('bear') @player_1.play('quality') @player_1.play('heloooo') assert_equal 3, @player_1.turns end end
true
7dfdc841d1045afa1b33a81c0b459798cb7d88c3
Ruby
getflywheel/uptimerobot
/lib/uptimerobot/client.rb
UTF-8
2,825
2.5625
3
[ "MIT" ]
permissive
class UptimeRobot::Client ENDPOINT = "https://api.uptimerobot.com/" USER_AGENT = "Ruby UptimeRobot Client #{UptimeRobot::GEM_VERSION}" METHODS = [ :getAccountDetails, :getMonitors, :newMonitor, :editMonitor, :deleteMonitor, :getAlertContacts, :newAlertContact, :deleteAlertContact ] DEFAULT_ADAPTERS = [ Faraday::Adapter::NetHttp, Faraday::Adapter::Test ] OPTIONS = [ :api_key, :raise_no_monitors_error, :skip_unescape_monitor, :debug ] def initialize(options) @options = {} OPTIONS.each do |key| @options[key] = options.delete(key) end raise ArgumentError, ':api_key is required' unless @options[:api_key] options[:url] ||= ENDPOINT @conn = Faraday.new(options) do |faraday| faraday.request :url_encoded faraday.response :json, :content_type => /\bjson$/ faraday.response :raise_error faraday.response :logger, ::Logger.new(STDOUT), bodies: true if @options[:debug] yield(faraday) if block_given? unless DEFAULT_ADAPTERS.any? {|i| faraday.builder.handlers.include?(i) } faraday.adapter Faraday.default_adapter end end @conn.headers[:user_agent] = USER_AGENT end private def method_missing(method_name, *args, &block) unless METHODS.include?(method_name) raise NoMethodError, "undefined method: #{method_name}" end len = args.length params = args.first unless len.zero? or (len == 1 and params.kind_of?(Hash)) raise ArgumentError, "invalid argument: #{args}" end request(method_name, params || {}, &block) end def request(method_name, params = {}) params.update( :api_key => @options[:api_key], :format => 'json', :noJsonCallback => 1 ) response = @conn.post do |req| req.url "/#{UptimeRobot::API_VERSION}/#{method_name}" req.body = URI.encode_www_form(params) yield(req) if block_given? end json = response.body validate_response!(json) if method_name == :getMonitors and not @options[:skip_unescape_monitor] unescape_monitor!(json) end json end def validate_response!(json) if json['stat'] != 'ok' if json['id'] == '212' if @options[:raise_no_monitors_error] raise UptimeRobot::Error.new(json) else json.update( 'total' => '0', 'monitors' => [] ) end else raise UptimeRobot::Error.new(json) end end end def unescape_monitor!(json) json['monitors'].each do |monitor| %w(friendly_name keyword_value http_username http_password).each do |key| value = monitor[key] || '' next if value.empty? monitor[key] = CGI.unescapeHTML(value) end end end end
true
d0fe3014200a17a011d978ad143cf31755b53498
Ruby
donfanning/kodi-dedup
/lib/kodi_dedup/classes/show.rb
UTF-8
362
2.625
3
[ "MIT" ]
permissive
module KodiDedup class Show def initialize(data) @data = data end def episodes @episodes ||= KodiDedup.episodes(tvshowid) end def method_missing(method, *args) @data[method.to_s].presence || super(method, args) end def respond_to_missing?(method, *) @data[method.to_s].presence || super end end end
true
fc9c13911ba95327b55a67eafc1fb47c3c4df3f9
Ruby
drosenfeld87/reinforcing_exercise_tdd
/calculator.rb
UTF-8
561
3.359375
3
[]
no_license
def add (number1, number2) number1 + number2 end # def adds_2_and_2 # assert_equal 4, add(2, 2) # end # # def adds_positive_numbers # assert_equal 8, add(2, 6) # end # subtract takes two parameters and subtracts the second from the first def subtract (number1, number2) number1 - number2 end # sum takes an *array* of numbers and adds them all together # This one is a bit trickier! def sum(n) result = 0 n.each do |number| result = result + number end return result end # def computes_sum # end
true
1dd6943c3cb1e67bd5ff9dac8fd78885aa69c176
Ruby
vsvld/rmagick
/test/Image_attributes.rb
UTF-8
24,020
2.546875
3
[ "MIT" ]
permissive
require 'fileutils' require 'rmagick' require 'minitest/autorun' # TODO # test frozen attributes! # improve test_directory # improve test_montage class Image_Attributes_UT < Minitest::Test def setup @img = Magick::Image.new(100, 100) gc = Magick::Draw.new gc.stroke_width(5) gc.circle(50, 50, 80, 80) gc.draw(@img) @hat = Magick::Image.read(FLOWER_HAT).first @p = Magick::Image.read(IMAGE_WITH_PROFILE).first.color_profile end def test_background_color expect { @img.background_color }.not_to raise_error expect(@img.background_color).to eq('white') expect { @img.background_color = '#dfdfdf' }.not_to raise_error # expect(@img.background_color).to eq("rgb(223,223,223)") background_color = @img.background_color if background_color.length == 13 expect(background_color).to eq('#DFDFDFDFDFDF') else expect(background_color).to eq('#DFDFDFDFDFDFFFFF') end expect { @img.background_color = Magick::Pixel.new(Magick::QuantumRange, Magick::QuantumRange / 2.0, Magick::QuantumRange / 2.0) }.not_to raise_error # expect(@img.background_color).to eq("rgb(100%,49.9992%,49.9992%)") background_color = @img.background_color if background_color.length == 13 expect(background_color).to eq('#FFFF7FFF7FFF') else expect(background_color).to eq('#FFFF7FFF7FFFFFFF') end expect { @img.background_color = 2 }.to raise_error(TypeError) end def test_base_columns expect { @img.base_columns }.not_to raise_error expect(@img.base_columns).to eq(0) expect { @img.base_columns = 1 }.to raise_error(NoMethodError) end def test_base_filename expect { @img.base_filename }.not_to raise_error expect(@img.base_filename).to eq('') expect { @img.base_filename = 'xxx' }.to raise_error(NoMethodError) end def test_base_rows expect { @img.base_rows }.not_to raise_error expect(@img.base_rows).to eq(0) expect { @img.base_rows = 1 }.to raise_error(NoMethodError) end def test_bias expect { @img.bias }.not_to raise_error expect(@img.bias).to eq(0.0) expect(@img.bias).to be_instance_of(Float) expect { @img.bias = 0.1 }.not_to raise_error expect(@img.bias).to be_within(0.1).of(Magick::QuantumRange * 0.1) expect { @img.bias = '10%' }.not_to raise_error expect(@img.bias).to be_within(0.1).of(Magick::QuantumRange * 0.10) expect { @img.bias = [] }.to raise_error(TypeError) expect { @img.bias = 'x' }.to raise_error(ArgumentError) end def test_black_point_compensation expect { @img.black_point_compensation = true }.not_to raise_error assert(@img.black_point_compensation) expect { @img.black_point_compensation = false }.not_to raise_error expect(@img.black_point_compensation).to eq(false) end def test_border_color expect { @img.border_color }.not_to raise_error # expect(@img.border_color).to eq("rgb(223,223,223)") border_color = @img.border_color if border_color.length == 13 expect(border_color).to eq('#DFDFDFDFDFDF') else expect(border_color).to eq('#DFDFDFDFDFDFFFFF') end expect { @img.border_color = 'red' }.not_to raise_error expect(@img.border_color).to eq('red') expect { @img.border_color = Magick::Pixel.new(Magick::QuantumRange, Magick::QuantumRange / 2, Magick::QuantumRange / 2) }.not_to raise_error # expect(@img.border_color).to eq("rgb(100%,49.9992%,49.9992%)") border_color = @img.border_color if border_color.length == 13 expect(border_color).to eq('#FFFF7FFF7FFF') else expect(border_color).to eq('#FFFF7FFF7FFFFFFF') end expect { @img.border_color = 2 }.to raise_error(TypeError) end def test_bounding_box expect { @img.bounding_box }.not_to raise_error box = @img.bounding_box expect(box.width).to eq(87) expect(box.height).to eq(87) expect(box.x).to eq(7) expect(box.y).to eq(7) expect { @img.bounding_box = 2 }.to raise_error(NoMethodError) end def test_chromaticity chrom = @img.chromaticity expect { @img.chromaticity }.not_to raise_error expect(chrom).to be_instance_of(Magick::Chromaticity) expect(chrom.red_primary.x).to eq(0) expect(chrom.red_primary.y).to eq(0) expect(chrom.red_primary.z).to eq(0) expect(chrom.green_primary.x).to eq(0) expect(chrom.green_primary.y).to eq(0) expect(chrom.green_primary.z).to eq(0) expect(chrom.blue_primary.x).to eq(0) expect(chrom.blue_primary.y).to eq(0) expect(chrom.blue_primary.z).to eq(0) expect(chrom.white_point.x).to eq(0) expect(chrom.white_point.y).to eq(0) expect(chrom.white_point.z).to eq(0) expect { @img.chromaticity = chrom }.not_to raise_error expect { @img.chromaticity = 2 }.to raise_error(TypeError) end def test_class_type expect { @img.class_type }.not_to raise_error expect(@img.class_type).to be_instance_of(Magick::ClassType) expect(@img.class_type).to eq(Magick::DirectClass) expect { @img.class_type = Magick::PseudoClass }.not_to raise_error expect(@img.class_type).to eq(Magick::PseudoClass) expect { @img.class_type = 2 }.to raise_error(TypeError) expect do @img.class_type = Magick::PseudoClass @img.class_type = Magick::DirectClass expect(@img.class_type).to eq(Magick::DirectClass) end.not_to raise_error end def test_color_profile expect { @img.color_profile }.not_to raise_error expect(@img.color_profile).to be(nil) expect { @img.color_profile = @p }.not_to raise_error expect(@img.color_profile).to eq(@p) expect { @img.color_profile = 2 }.to raise_error(TypeError) end def test_colors expect { @img.colors }.not_to raise_error expect(@img.colors).to eq(0) img = @img.copy img.class_type = Magick::PseudoClass expect(img.colors).to be_kind_of(Integer) expect { img.colors = 2 }.to raise_error(NoMethodError) end def test_colorspace expect { @img.colorspace }.not_to raise_error expect(@img.colorspace).to be_instance_of(Magick::ColorspaceType) expect(@img.colorspace).to eq(Magick::SRGBColorspace) img = @img.copy Magick::ColorspaceType.values do |colorspace| expect { img.colorspace = colorspace }.not_to raise_error end expect { @img.colorspace = 2 }.to raise_error(TypeError) Magick::ColorspaceType.values.each do |cs| expect { img.colorspace = cs }.not_to raise_error end end def test_columns expect { @img.columns }.not_to raise_error expect(@img.columns).to eq(100) expect { @img.columns = 2 }.to raise_error(NoMethodError) end def test_compose expect { @img.compose }.not_to raise_error expect(@img.compose).to be_instance_of(Magick::CompositeOperator) expect(@img.compose).to eq(Magick::OverCompositeOp) expect { @img.compose = 2 }.to raise_error(TypeError) expect { @img.compose = Magick::UndefinedCompositeOp }.not_to raise_error expect(@img.compose).to eq(Magick::UndefinedCompositeOp) Magick::CompositeOperator.values do |composite| expect { @img.compose = composite }.not_to raise_error end expect { @img.compose = 2 }.to raise_error(TypeError) end def test_compression expect { @img.compression }.not_to raise_error expect(@img.compression).to be_instance_of(Magick::CompressionType) expect(@img.compression).to eq(Magick::UndefinedCompression) expect { @img.compression = Magick::BZipCompression }.not_to raise_error expect(@img.compression).to eq(Magick::BZipCompression) Magick::CompressionType.values do |compression| expect { @img.compression = compression }.not_to raise_error end expect { @img.compression = 2 }.to raise_error(TypeError) end def test_delay expect { @img.delay }.not_to raise_error expect(@img.delay).to eq(0) expect { @img.delay = 10 }.not_to raise_error expect(@img.delay).to eq(10) expect { @img.delay = 'x' }.to raise_error(TypeError) end def test_density expect { @img.density }.not_to raise_error expect { @img.density = '90x90' }.not_to raise_error expect { @img.density = 'x90' }.not_to raise_error expect { @img.density = '90' }.not_to raise_error expect { @img.density = Magick::Geometry.new(@img.columns / 2, @img.rows / 2, 5, 5) }.not_to raise_error expect { @img.density = 2 }.to raise_error(TypeError) end def test_depth expect(@img.depth).to eq(Magick::MAGICKCORE_QUANTUM_DEPTH) expect { @img.depth = 2 }.to raise_error(NoMethodError) end def test_directory expect { @img.directory }.not_to raise_error expect(@img.directory).to be(nil) expect { @img.directory = nil }.to raise_error(NoMethodError) end def test_dispose expect { @img.dispose }.not_to raise_error expect(@img.dispose).to be_instance_of(Magick::DisposeType) expect(@img.dispose).to eq(Magick::UndefinedDispose) expect { @img.dispose = Magick::NoneDispose }.not_to raise_error expect(@img.dispose).to eq(Magick::NoneDispose) Magick::DisposeType.values do |dispose| expect { @img.dispose = dispose }.not_to raise_error end expect { @img.dispose = 2 }.to raise_error(TypeError) end def test_endian expect { @img.endian }.not_to raise_error expect(@img.endian).to be_instance_of(Magick::EndianType) expect(@img.endian).to eq(Magick::UndefinedEndian) expect { @img.endian = Magick::LSBEndian }.not_to raise_error expect(@img.endian).to eq(Magick::LSBEndian) expect { @img.endian = Magick::MSBEndian }.not_to raise_error expect { @img.endian = 2 }.to raise_error(TypeError) end def test_extract_info expect { @img.extract_info }.not_to raise_error expect(@img.extract_info).to be_instance_of(Magick::Rectangle) ext = @img.extract_info expect(ext.x).to eq(0) expect(ext.y).to eq(0) expect(ext.width).to eq(0) expect(ext.height).to eq(0) ext = Magick::Rectangle.new(1, 2, 3, 4) expect { @img.extract_info = ext }.not_to raise_error expect(ext.width).to eq(1) expect(ext.height).to eq(2) expect(ext.x).to eq(3) expect(ext.y).to eq(4) expect { @img.extract_info = 2 }.to raise_error(TypeError) end def test_filename expect { @img.filename }.not_to raise_error expect(@img.filename).to eq('') expect { @img.filename = 'xxx' }.to raise_error(NoMethodError) end def test_filter expect { @img.filter }.not_to raise_error expect(@img.filter).to be_instance_of(Magick::FilterType) expect(@img.filter).to eq(Magick::UndefinedFilter) expect { @img.filter = Magick::PointFilter }.not_to raise_error expect(@img.filter).to eq(Magick::PointFilter) Magick::FilterType.values do |filter| expect { @img.filter = filter }.not_to raise_error end expect { @img.filter = 2 }.to raise_error(TypeError) end def test_format expect { @img.format }.not_to raise_error expect(@img.format).to be(nil) expect { @img.format = 'GIF' }.not_to raise_error expect { @img.format = 'JPG' }.not_to raise_error expect { @img.format = 'TIFF' }.not_to raise_error expect { @img.format = 'MIFF' }.not_to raise_error expect { @img.format = 'MPEG' }.not_to raise_error v = $VERBOSE $VERBOSE = nil expect { @img.format = 'shit' }.to raise_error(ArgumentError) $VERBOSE = v expect { @img.format = 2 }.to raise_error(TypeError) end def test_fuzz expect { @img.fuzz }.not_to raise_error expect(@img.fuzz).to be_instance_of(Float) expect(@img.fuzz).to eq(0.0) expect { @img.fuzz = 50 }.not_to raise_error expect(@img.fuzz).to eq(50.0) expect { @img.fuzz = '50%' }.not_to raise_error expect(@img.fuzz).to be_within(0.1).of(Magick::QuantumRange * 0.50) expect { @img.fuzz = [] }.to raise_error(TypeError) expect { @img.fuzz = 'xxx' }.to raise_error(ArgumentError) end def test_gamma expect { @img.gamma }.not_to raise_error expect(@img.gamma).to be_instance_of(Float) expect(@img.gamma).to eq(0.45454543828964233) expect { @img.gamma = 2.0 }.not_to raise_error expect(@img.gamma).to eq(2.0) expect { @img.gamma = 'x' }.to raise_error(TypeError) end def test_geometry expect { @img.geometry }.not_to raise_error expect(@img.geometry).to be(nil) expect { @img.geometry = nil }.not_to raise_error expect { @img.geometry = '90x90' }.not_to raise_error expect(@img.geometry).to eq('90x90') expect { @img.geometry = Magick::Geometry.new(100, 80) }.not_to raise_error expect(@img.geometry).to eq('100x80') expect { @img.geometry = [] }.to raise_error(TypeError) end def test_gravity expect(@img.gravity).to be_instance_of(Magick::GravityType) Magick::GravityType.values do |gravity| expect { @img.gravity = gravity }.not_to raise_error end expect { @img.gravity = nil }.to raise_error(TypeError) expect { @img.gravity = Magick::PointFilter }.to raise_error(TypeError) end def test_image_type expect(@img.image_type).to be_instance_of(Magick::ImageType) Magick::ImageType.values do |image_type| expect { @img.image_type = image_type }.not_to raise_error end expect { @img.image_type = nil }.to raise_error(TypeError) expect { @img.image_type = Magick::PointFilter }.to raise_error(TypeError) end def test_interlace_type expect { @img.interlace }.not_to raise_error expect(@img.interlace).to be_instance_of(Magick::InterlaceType) expect(@img.interlace).to eq(Magick::NoInterlace) expect { @img.interlace = Magick::LineInterlace }.not_to raise_error expect(@img.interlace).to eq(Magick::LineInterlace) Magick::InterlaceType.values do |interlace| expect { @img.interlace = interlace }.not_to raise_error end expect { @img.interlace = 2 }.to raise_error(TypeError) end def test_iptc_profile expect { @img.iptc_profile }.not_to raise_error expect(@img.iptc_profile).to be(nil) expect { @img.iptc_profile = 'xxx' }.not_to raise_error expect(@img.iptc_profile).to eq('xxx') expect { @img.iptc_profile = 2 }.to raise_error(TypeError) end def test_mean_error expect { @hat.mean_error_per_pixel }.not_to raise_error expect { @hat.normalized_mean_error }.not_to raise_error expect { @hat.normalized_maximum_error }.not_to raise_error expect(@hat.mean_error_per_pixel).to eq(0.0) expect(@hat.normalized_mean_error).to eq(0.0) expect(@hat.normalized_maximum_error).to eq(0.0) hat = @hat.quantize(16, Magick::RGBColorspace, true, 0, true) assert_not_equal(0.0, hat.mean_error_per_pixel) assert_not_equal(0.0, hat.normalized_mean_error) assert_not_equal(0.0, hat.normalized_maximum_error) expect { hat.mean_error_per_pixel = 1 }.to raise_error(NoMethodError) expect { hat.normalized_mean_error = 1 }.to raise_error(NoMethodError) expect { hat.normalized_maximum_error = 1 }.to raise_error(NoMethodError) end def test_mime_type img = @img.copy img.format = 'GIF' expect { img.mime_type }.not_to raise_error expect(img.mime_type).to eq('image/gif') img.format = 'JPG' expect(img.mime_type).to eq('image/jpeg') expect { img.mime_type = 'image/jpeg' }.to raise_error(NoMethodError) end def test_monitor expect { @img.monitor }.to raise_error(NoMethodError) monitor = proc { |name, _q, _s| puts name } expect { @img.monitor = monitor }.not_to raise_error expect { @img.monitor = nil }.not_to raise_error end def test_montage expect { @img.montage }.not_to raise_error expect(@img.montage).to be(nil) end def test_number_colors expect { @hat.number_colors }.not_to raise_error expect(@hat.number_colors).to be_kind_of(Integer) expect { @hat.number_colors = 2 }.to raise_error(NoMethodError) end def test_offset expect { @img.offset }.not_to raise_error expect(@img.offset).to eq(0) expect { @img.offset = 10 }.not_to raise_error expect(@img.offset).to eq(10) expect { @img.offset = 'x' }.to raise_error(TypeError) end def test_orientation expect { @img.orientation }.not_to raise_error expect(@img.orientation).to be_instance_of(Magick::OrientationType) expect(@img.orientation).to eq(Magick::UndefinedOrientation) expect { @img.orientation = Magick::TopLeftOrientation }.not_to raise_error expect(@img.orientation).to eq(Magick::TopLeftOrientation) Magick::OrientationType.values do |orientation| expect { @img.orientation = orientation }.not_to raise_error end expect { @img.orientation = 2 }.to raise_error(TypeError) end def test_page expect { @img.page }.not_to raise_error page = @img.page expect(page.width).to eq(0) expect(page.height).to eq(0) expect(page.x).to eq(0) expect(page.y).to eq(0) page = Magick::Rectangle.new(1, 2, 3, 4) expect { @img.page = page }.not_to raise_error expect(page.width).to eq(1) expect(page.height).to eq(2) expect(page.x).to eq(3) expect(page.y).to eq(4) expect { @img.page = 2 }.to raise_error(TypeError) end def test_pixel_interpolation_method expect { @img.pixel_interpolation_method }.not_to raise_error expect(@img.pixel_interpolation_method).to be_instance_of(Magick::PixelInterpolateMethod) expect(@img.pixel_interpolation_method).to eq(Magick::UndefinedInterpolatePixel) expect { @img.pixel_interpolation_method = Magick::AverageInterpolatePixel }.not_to raise_error expect(@img.pixel_interpolation_method).to eq(Magick::AverageInterpolatePixel) Magick::PixelInterpolateMethod.values do |interpolate_pixel_method| expect { @img.pixel_interpolation_method = interpolate_pixel_method }.not_to raise_error end expect { @img.pixel_interpolation_method = 2 }.to raise_error(TypeError) end def test_quality expect { @hat.quality }.not_to raise_error expect(@hat.quality).to eq(75) expect { @img.quality = 80 }.to raise_error(NoMethodError) end def test_quantum_depth expect { @img.quantum_depth }.not_to raise_error expect(@img.quantum_depth).to eq(Magick::MAGICKCORE_QUANTUM_DEPTH) expect { @img.quantum_depth = 8 }.to raise_error(NoMethodError) end def test_rendering_intent expect { @img.rendering_intent }.not_to raise_error expect(@img.rendering_intent).to be_instance_of(Magick::RenderingIntent) expect(@img.rendering_intent).to eq(Magick::PerceptualIntent) Magick::RenderingIntent.values do |rendering_intent| expect { @img.rendering_intent = rendering_intent }.not_to raise_error end expect { @img.rendering_intent = 2 }.to raise_error(TypeError) end def test_rows expect { @img.rows }.not_to raise_error expect(@img.rows).to eq(100) expect { @img.rows = 2 }.to raise_error(NoMethodError) end def test_scene ilist = Magick::ImageList.new ilist << @img img = @img.copy ilist << img ilist.write('temp.gif') FileUtils.rm('temp.gif') expect { img.scene }.not_to raise_error expect(@img.scene).to eq(0) expect(img.scene).to eq(1) expect { img.scene = 2 }.to raise_error(NoMethodError) end def test_start_loop expect { @img.start_loop }.not_to raise_error assert(!@img.start_loop) expect { @img.start_loop = true }.not_to raise_error assert(@img.start_loop) end def test_ticks_per_second expect { @img.ticks_per_second }.not_to raise_error expect(@img.ticks_per_second).to eq(100) expect { @img.ticks_per_second = 1000 }.not_to raise_error expect(@img.ticks_per_second).to eq(1000) expect { @img.ticks_per_second = 'x' }.to raise_error(TypeError) end def test_total_colors expect { @hat.total_colors }.not_to raise_error expect(@hat.total_colors).to be_kind_of(Integer) expect { @img.total_colors = 2 }.to raise_error(NoMethodError) end def test_units expect { @img.units }.not_to raise_error expect(@img.units).to be_instance_of(Magick::ResolutionType) expect(@img.units).to eq(Magick::UndefinedResolution) expect { @img.units = Magick::PixelsPerInchResolution }.not_to raise_error expect(@img.units).to eq(Magick::PixelsPerInchResolution) Magick::ResolutionType.values do |resolution| expect { @img.units = resolution }.not_to raise_error end expect { @img.units = 2 }.to raise_error(TypeError) end def test_virtual_pixel_method expect { @img.virtual_pixel_method }.not_to raise_error expect(@img.virtual_pixel_method).to eq(Magick::UndefinedVirtualPixelMethod) expect { @img.virtual_pixel_method = Magick::EdgeVirtualPixelMethod }.not_to raise_error expect(@img.virtual_pixel_method).to eq(Magick::EdgeVirtualPixelMethod) Magick::VirtualPixelMethod.values do |virtual_pixel_method| expect { @img.virtual_pixel_method = virtual_pixel_method }.not_to raise_error end expect { @img.virtual_pixel_method = 2 }.to raise_error(TypeError) end def test_x_resolution expect { @img.x_resolution }.not_to raise_error expect { @img.x_resolution = 90 }.not_to raise_error expect(@img.x_resolution).to eq(90.0) expect { @img.x_resolution = 'x' }.to raise_error(TypeError) end def test_y_resolution expect { @img.y_resolution }.not_to raise_error expect { @img.y_resolution = 90 }.not_to raise_error expect(@img.y_resolution).to eq(90.0) expect { @img.y_resolution = 'x' }.to raise_error(TypeError) end def test_frozen @img.freeze expect { @img.background_color = 'xxx' }.to raise_error(FreezeError) expect { @img.border_color = 'xxx' }.to raise_error(FreezeError) rp = Magick::Point.new(1, 1) gp = Magick::Point.new(1, 1) bp = Magick::Point.new(1, 1) wp = Magick::Point.new(1, 1) expect { @img.chromaticity = Magick::Chromaticity.new(rp, gp, bp, wp) }.to raise_error(FreezeError) expect { @img.class_type = Magick::DirectClass }.to raise_error(FreezeError) expect { @img.color_profile = 'xxx' }.to raise_error(FreezeError) expect { @img.colorspace = Magick::RGBColorspace }.to raise_error(FreezeError) expect { @img.compose = Magick::OverCompositeOp }.to raise_error(FreezeError) expect { @img.compression = Magick::RLECompression }.to raise_error(FreezeError) expect { @img.delay = 2 }.to raise_error(FreezeError) expect { @img.density = '72.0x72.0' }.to raise_error(FreezeError) expect { @img.dispose = Magick::NoneDispose }.to raise_error(FreezeError) expect { @img.endian = Magick::MSBEndian }.to raise_error(FreezeError) expect { @img.extract_info = Magick::Rectangle.new(1, 2, 3, 4) }.to raise_error(FreezeError) expect { @img.filter = Magick::PointFilter }.to raise_error(FreezeError) expect { @img.format = 'GIF' }.to raise_error(FreezeError) expect { @img.fuzz = 50.0 }.to raise_error(FreezeError) expect { @img.gamma = 2.0 }.to raise_error(FreezeError) expect { @img.geometry = '100x100' }.to raise_error(FreezeError) expect { @img.interlace = Magick::NoInterlace }.to raise_error(FreezeError) expect { @img.iptc_profile = 'xxx' }.to raise_error(FreezeError) expect { @img.monitor = proc { |name, _q, _s| puts name } }.to raise_error(FreezeError) expect { @img.offset = 100 }.to raise_error(FreezeError) expect { @img.page = Magick::Rectangle.new(1, 2, 3, 4) }.to raise_error(FreezeError) expect { @img.rendering_intent = Magick::SaturationIntent }.to raise_error(FreezeError) expect { @img.start_loop = true }.to raise_error(FreezeError) expect { @img.ticks_per_second = 1000 }.to raise_error(FreezeError) expect { @img.units = Magick::PixelsPerInchResolution }.to raise_error(FreezeError) expect { @img.x_resolution = 72.0 }.to raise_error(FreezeError) expect { @img.y_resolution = 72.0 }.to raise_error(FreezeError) end end # class Image_Attributes_UT if $PROGRAM_NAME == __FILE__ FLOWER_HAT = '../doc/ex/images/Flower_Hat.jpg' Test::Unit::UI::Console::TestRunner.run(ImageAttributesUT) end
true
5271481f57736f880964578b09212163551dea67
Ruby
jpedrosa/luhnybin
/luhn.rb
UTF-8
1,814
3.515625
4
[ "Apache-2.0" ]
permissive
DOUBLE_DIGITS = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] class Luhn def test_it a, start_at, max_len total = 0 double_digit = false i = start_at + max_len - 1 while i >= start_at total += double_digit ? DOUBLE_DIGITS[a[i]] : a[i] double_digit = !double_digit i -= 1 end total % 10 == 0 end def mask s mirror = s.unpack('c*') masked = nil i = 0 digit_count = 0 mask_offset = -1 digits = [] len = mirror.length while i < len c = mirror[i] if c >= 48 and c <= 57 #between 0 and 9 digit_count += 1 digits << c - 48 if digit_count >= 14 the_len = digit_count < 16 ? digit_count : 16 while the_len >= 14 start_at = digit_count - the_len if test_it(digits, start_at, the_len) masked = mirror[0..-1] if not masked mask_len = the_len j = i while mask_len > 0 && j > mask_offset mc = mirror[j] if mc >= 48 and mc <= 57 #between 0 and 9 masked[j] = 88 #X mask_len -= 1 end j -= 1 end mask_offset = i if the_len == 16 end the_len -= 1 end end elsif c != 45 and c != 32 #not - or space if digit_count > 0 digit_count = 0 digits = [] end end i += 1 end masked ? masked.pack('c*') : s end def tap_stdin n_repeats = ARGV[0] ? ARGV[0].to_i : 1 if n_repeats > 1 lines = STDIN.readlines n_repeats.times do lines.each do |s| puts mask(s) end end else STDIN.each do |s| puts mask(s) end end end end
true
70fdb3c42de60c3be22cdef99d04e98f5f1f1ce9
Ruby
CosmicSpagetti/enigma
/lib/enigma.rb
UTF-8
838
2.6875
3
[]
no_license
class Enigma def encrypt(message, key = Key.new, date = Offset.new) shifts = Shifts.new(key, date) { encryption:shifts.shifter(message) , key: shifts.key_instance.key , date: shifts.date_instance.date } end def decrypt(message, key = Key.new, date = Offset.new) shifts = Shifts.new(key, date) { decryption:shifts.deshifter(message) , key: shifts.key_instance.key , date: shifts.date_instance.date } end def crack(message, date = Offset.new) key = 00000 key_format = key.to_s.rjust(5, "0") cracked_message = decrypt(message, key_format, date) until cracked_message[:decryption][-4..-1] == " end" key += 1 key_format = key.to_s.rjust(5, "0") cracked_message = decrypt(message, key_format, date) end decrypt(message, key_format, date) end end
true
f10a761971474e707e59cec621bd5f7b90aaf92b
Ruby
hybitz/tax_jp
/lib/tax_jp/depreciation_rate.rb
UTF-8
1,622
2.796875
3
[ "MIT" ]
permissive
module TaxJp module DepreciationRates end # 減価償却率 class DepreciationRate DB_PATH = File.join(TaxJp::Utils.data_dir, '減価償却率.db') attr_reader :valid_from, :valid_until attr_reader :durable_years attr_reader :fixed_amount_rate attr_reader :rate, :revised_rate, :guaranteed_rate def initialize(row) @valid_from = row[0] @valid_until = row[1] @durable_years = row[2] @fixed_amount_rate = row[3] @rate = row[4] @revised_rate = row[5] @guaranteed_rate = row[6] end def self.find_all_by_date(date) date = TaxJp::Utils.convert_to_date(date) with_database do |db| sql = 'select * from depreciation_rates ' sql << 'where valid_from <= ? and valid_until >= ? ' sql << 'order by durable_years ' ret = [] db.execute(sql, [date, date]) do |row| ret << TaxJp::DepreciationRate.new(row) end ret end end def self.find_by_date_and_durable_years(date, durable_years) date = TaxJp::Utils.convert_to_date(date) with_database do |db| sql = 'select * from depreciation_rates ' sql << 'where valid_from <= ? and valid_until >= ? ' sql << ' and durable_years = ? ' ret = nil db.execute(sql, [date, date, durable_years]) do |row| ret = TaxJp::DepreciationRate.new(row) end ret end end private def self.with_database db = SQLite3::Database.new(DB_PATH) begin yield db ensure db.close end end end end
true
d54abdfd364146693a8ffa7a7510ffb1fb3fe6b0
Ruby
bin3/learnrb
/rpl/tcp_client.rb
UTF-8
184
2.78125
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby -w # coding: utf-8 require 'socket' puts "[TCP Client]" host, port = ARGV TCPSocket.open(host, port) do |s| while line = s.gets puts line.chop end end
true
024aaa3edb6b7bb1c46211cca032bfa1a18cf03b
Ruby
yasmineezequiel/Vanilla_Ruby
/Section_19_Modules_and_Mixins/Mixins_Part_1.rb
UTF-8
1,153
4.40625
4
[]
no_license
# Why mix in modules to classes? # Different classes need similar functionalities. # For example, String and Numeric both need <, <=, >, >=, and == # However, neither class can be represented as subclass of the other. # Duplication of methods across classes violates the DRY principle. # The solution is to use mixins and modules. # Example; class OlympicMedal # Access the comparable ruby module; <, <=, <=>, >, >=, .between? include Comparable MEDAL_VALUES = {'Gold' => 3, 'Silver' => 2, 'Bronze' => 1} attr_reader :type # access the type of the medal # type is a sring and wight an integer def initialize(type, weight) @type = type @weight = weight end def <=>(another) # This method will use the comparable module if MEDAL_VALUES[type] < MEDAL_VALUES[another.type] -1 elsif MEDAL_VALUES[type] == MEDAL_VALUES[another.type] 0 else 1 end end end bronze = OlympicMedal.new("Bronze", 5) silver = OlympicMedal.new("Silver", 10) gold = OlympicMedal.new("Gold", 20) puts bronze > gold # false puts gold > silver # true puts gold == silver # false puts bronze != gold # true
true
cc35a7ec890a9aee669bfdf60ef7fc5794eda268
Ruby
kmac02/phase-0-tracks
/ruby/santa.rb
UTF-8
1,591
4.0625
4
[]
no_license
# santa class class Santa attr_accessor :gender attr_reader :age, :ethnicity def initialize (gender, ethnicity, age) puts "Initializing Santa instance..." @gender = gender @ethnicity = ethnicity @reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] @age = age end def speak puts "Ho, ho, ho! Haaappy holidays!" end def eat_milk_and_cookies (cookie) puts "That was a good #{cookie}!" end def celebrate_birthday (age) @age = age.to_i + 1 end def get_mad_at(reindeer) @reindeer_ranking[-1] = reindeer end end #Driver Code santa = Santa.new("gender fluid", "latinx", 3) santa.eat_milk_and_cookies("chocolate chip") santa.speak reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] #Test setter methods #santa.get_mad_at("Comet") # santa.gender = "male" # santa.celebrate_birthday(35) # create santas with randomly generated genders and ethnicities ## create arrays santas = [] example_genders = ["pangender", "genderless", "hijra", "agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "latinx", "Indian-American", "Mystical Creature (unicorn)", "N/A"] #create age range in array age = *(0..140).to_a # generate santas 10.times do |i| santas << Santa.new(example_genders.sample, example_ethnicities.sample, age.sample) end # test new santas array santas[3].celebrate_birthday(45) p santas[3]
true
863a2a56dc62982f09221542c2e75ff2e11df663
Ruby
soufiane121/ruby-enumerables-cartoon-collections-lab-nyc-web-100719
/cartoon_collections.rb
UTF-8
475
3.484375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves(arg) answer=[] arg.each_with_index do |ele, idx| answer << "#{idx+1} #{ele}" end print answer end def summon_captain_planet(arr) answer=arr.collect { |ele| "#{ele.capitalize}!"} answer end def long_planeteer_calls(arr) arr.any? {|ele| ele.length > 4 } end def find_the_cheese(arr) cheese_types = ["cheddar", "gouda", "camembert"] arr.each do |ele| if cheese_types.include?(ele) return ele end end nil end
true
3c5dae75479fd955c7fca26a588dcf04a0115bae
Ruby
DustinFehlman/CST438
/HangmanTwo/app/controllers/games_controller.rb
UTF-8
3,176
2.921875
3
[]
no_license
class GamesController < ActionController::Base def play if cookies[:sessionID] && !params[:newGame] sessionID = cookies[:sessionID] currentGame = continueGame(sessionID) else currentGame = createGame() end @game = currentGame userGuess = params[:guessed_letter] if(userGuess) takeGuessInput(userGuess) end checkForWinner() saveGame() createUI() end def createUI @wordUI = @game.correctLettersGuessed @guessesLeft = @game.guessCount @hangManImg = "h" + (@game.guessCount - 7).abs.to_s + ".gif" end def saveGame @game.save! end def storeCorrectGuess(guess) @game.guessedLetters.concat(guess) tempArr = @game.correctLettersGuessed.split(' ') tempArr.each_with_index do |item, index| if @game.word[index] == guess tempArr[index] = guess end end @game.correctLettersGuessed = tempArr.join(' ') end def checkForWinner if(@game.correctLettersGuessed.delete(' ') == @game.word) @response = "Goodjob you win!" end end def storeIncorrectGuess(guess) @game.guessedLetters.concat(guess) @game.guessCount -= 1 end def createRandomWord() wordArr = IO.readlines("app/assets/words.txt") return wordArr[Random.rand(wordArr.count - 1)].strip end def createGame sessionID = SecureRandom.uuid cookies[:sessionID] = sessionID word = createRandomWord() newGame = Game.create!(:sessionID => sessionID, :word => word, :guessCount => 6, :guessedLetters => "", :correctLettersGuessed => createBlankScoreArray(word).join(' ')) return newGame end def continueGame(sessionID) savedGame = Game.where("sessionID = ?", sessionID).first if(!savedGame) return createGame() end return savedGame end def createBlankScoreArray(word) return Array.new(word.length, '_') end def takeGuessInput(guess) if guess.length > 1 @response = "Too many letters. One letter per turn." elsif guess.length == 0 || guess == '' if(@game.guessCount == 0) @response = "Incorrect choice. Game over." else @response = "" end else if @game.guessedLetters.include?(guess) @response = "Already guessed #{guess}" elsif @game.word.include?(guess) storeCorrectGuess(guess) @response = "Correct choice!" else storeIncorrectGuess(guess) if(@game.guessCount == 0) @response = "Incorrect choice. Game over." else @response = "Incorrect choice." end end end end end
true
3e8f67812710abac24a35cd0041d93459ab0aeb5
Ruby
Mohammad-Daylaki/prime-ruby-re-coded-000
/prime.rb
UTF-8
132
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(number) if number <=1 return false end numbers=(2..Math.sqrt(number)).to_a numbers.all?{|n| number%n!=0} end
true
6abc4b707afa6968fa8a12bcd2a9341ec9a82163
Ruby
olwend/tic_tac_toe
/spec/player_spec.rb
UTF-8
213
2.6875
3
[]
no_license
require_relative '../lib/player' describe Player do subject { described_class.new} it "has a name" do tom = Player.new("Tom") expect(tom.name).to eq("Tom") end it "takes a turn" do end end
true
f7f9b9d6364e572fa5a406ac4593dd4648f5dd6b
Ruby
kostanzhoglo/rspec-fizzbuzz-v-000
/fizzbuzz.rb
UTF-8
145
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def fizzbuzz(i) if i % 3 == 0 && i % 5 == 0 "FizzBuzz" elsif i % 3 == 0 "Fizz" elsif i % 5 == 0 "Buzz" end end # fizzbuzz(i)
true
3847247d3fc049b16fdb99d424c8ea40718685df
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/gigasecond/9e69741c3c9e488fb8818726c1724047.rb
UTF-8
147
3.234375
3
[]
no_license
class Gigasecond def initialize(birthday) @birthday = birthday.to_time end def date (@birthday + 1_000_000_000).to_date end end
true
e4c540ce3b134d97c090f04c0343d029f9aadd8a
Ruby
jacegu/nervion
/lib/nervion/stream.rb
UTF-8
1,360
2.671875
3
[ "MIT" ]
permissive
require 'eventmachine' require 'nervion/stream_parser' require 'nervion/reconnection_scheduler' module Nervion class Stream < EM::Connection attr_reader :http_error def initialize(*args) @request = args[0] @handler = args[1] end def post_init @scheduler = ReconnectionScheduler.new end def connection_completed start_tls send_data @request end def receive_data(data) @handler << data rescue HttpError => error @http_error = error end def retry @http_error = nil reconnect @request.host, @request.port end def unbind handle_closed_stream unless close_requested? end def http_error_occurred? not http_error.nil? end def close_requested? @close_stream ||= false end def close @close_stream = true close_connection end private def handle_closed_stream if http_error_occurred? handle_http_error_and_retry else handle_network_error_and_retry end end def handle_http_error_and_retry @handler.handle_http_error http_error @scheduler.reconnect_after_http_error_in self end def handle_network_error_and_retry @handler.handle_network_error @scheduler.reconnect_after_network_error_in self end end end
true
1d98892a93e8992bc496309004fcb3b0879cff7c
Ruby
fredericcormier/fingers
/lib/instrument.rb
UTF-8
4,020
3.609375
4
[ "MIT" ]
permissive
require "tones" require "tuning" include Tones include Tuning module Instrument #===Note about tuning # The tuning used here is from the first (highest) string to lowest string # ex for standard guitar (first to last): # Guitar: E, B, G, D, A, E #for touch instruments, with inverted tunings, it's the Chapman Stick® standard that is used (first to last): # Stick baritone: A, E, B, F#, C# / C, G, D, A, E class NoSuchFretError < ArgumentError; end class StringOutOfBounds < ArgumentError; end E__M = { :no_such_fret_error => 'This string cannot play at that fret', :string_out_of_bounds => 'No string at that index' } # a string (or instrument string) is simply a repeating chromatic scale. # note that we copy the chromatic scale in the string array. # a string can cover a range of 3 octaves Max (the chramatic scale length is set to 3 octaves), # which is much more than what a real string can handle # #==== Usage (although you shouldn't use this class directly) # # s = InstrumentDef::String.new('c', 4, 24) # s[0] => C 4 #index 0 is the open string class String < Tones::ChromaticScale attr_reader :notes, :length def initialize(root,octave, length) super(root, octave) @notes = Array.new() @length = length @length.times { |i| @notes << @chromatic_scale[i] } end #return this string's note at fretNumber def [](fretNum) raise NoSuchFretError, E__M[:no_such_fret_error] unless (0..@length-1).include? fretNum @notes[fretNum] end alias note_at_fret [] #Is the note in the range of this string ? def can_play_note?(*args) case args[0] when Tones::Note then #its a Note Object @notes.include?(args[0]) when Object::String then #it's a String if args[1].class == Fixnum @notes.include?(Note.new(args[0], args[1])) end else raise ArgumentError end end def to_a @notes end def each @notes.each { |e| yield e } end def to_s sout ="" @notes.each { |e| sout << e.note.to_s << e.octave.to_s<<" "} sout end # name is inherited from ChromaticScale.name end # An Instrument is an Array of "num_of_strings" strings.(thus an array of array). # We first load the tuning by setting the notes at fret "0" # then we create new Strings("chromatic scale") according to the tuning # # to access notes through the fretboard just do #=== Usage # guitar = Instrument::Fretboard.new(GUITAR, 'my_beloved_guild') # puts guitar[1][3] => "D 4" # #the first array access the string and the second the fret. the array are zero based so in this example we have: # guitar[1] this is the second string (b on guitar) # guitar[1][3] second string third fret (fret 0 is open string) class Fretboard attr_reader :num_of_strings, :strings, :name, :tuning def initialize(tuning,name = "") @num_of_strings = tuning.length @strings = Array.new(0) @tuning = Array.new(0) @name = name @num_of_strings.times { |i| @tuning << tuning[i][0] } @num_of_strings.times { |t| @strings<<Instrument::String.new(tuning[t][0],tuning[t][1],tuning[t][2])} end #access string at index def [](index) raise StringOutOfBounds, E__M[:string_out_of_bounds] unless (0..(@num_of_strings - 1)).member? index @strings[index] end def each @strings.each { |e| yield e } end end end
true
93be1c3d0e0a176eb848004acba88dba77de292a
Ruby
JoyFoodly/joyful_12
/db/seeds.rb
UTF-8
4,096
2.65625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Admin.create_with(password: 'password').find_or_create_by!(email: 'siruguri@gmail.com') Admin.create_with(password: 'password').find_or_create_by!(email: 'hollie@joyfoodly.com') user_attributes = { first_name: 'Tester', last_name: 'Person', password: 'password', created_at: Time.current } user = User.create_with(user_attributes).find_or_create_by!(email: 'test@example.com') user.confirm! test_user = user easy_recipe_attributes = { title: 'Roasted Cauliflower', subtitle: 'Cauliflower recipe 1 - easy', prep_time: '10 min', cook_time: '15 min', serving_size: '4 - 6 people', difficulty: 'easy', instructions: %q{ 1. In a bowl, toss cauliflower florets with 2 tablespoons olive oil, and two teaspoons of salt. We also like to add a teaspoon of a spice, like cumin or curry powder at this point. Toss well. 1. Distribute evenly on a cookie sheet, allowing some space between the florets. 1. Put in the oven. Check at 10 minutes. When the florets start to brown, flip cauliflower over. Continue cooking cauliflower until it is crisp tender and slightly browned all over, about 15-20 minutes. } } spring_foods = [["Avocado", "spring-avocado"], ["Potato", "spring-potato"], ["Strawberry", "spring-strawberry"], ["Artichoke", "spring-artichoke"], ["Peas", "spring-peas"], ["Asparagus", "spring-asparagus"], ["Radishes", "spring-radish"], ["Fennel", "spring-fennel"], ["Green Onion", "spring-green-onion"], ["Spinach", "spring-spinach"], ["greens", "spring-greens"], ["rhubarb", "spring-rhubarb"]] spring_season = Season.find_or_create_by(name: 'Spring') spring_foods.each do |name, slug| food = Food.find_or_create_by(name: name, slug: slug, season: spring_season) food.recipes.find_or_create_by(easy_recipe_attributes.merge(title: "#{spring_season.name} Roasted #{food.name}" )) end # Test user is a Spring user test_user.seasons << spring_season winter_foods = [["Sweet Potato", "winter-sweet-potato"], ["Brussels Sprout", "winter-brussels-sprout"], ["Winter Squash", "winter-winter-squash"], ["Citrus", "winter-citrus"], ["Greens", "winter-greens"], ["Beet", "winter-beets"]] winter_season = Season.find_or_create_by(name: 'Winter') winter_foods.each do |name, slug| food = Food.find_or_create_by(name: name, slug: slug, season: winter_season) food.recipes.find_or_create_by(easy_recipe_attributes.merge(title: "#{winter_season.name} Roasted #{food.name}" )) end foods = ["Fennel", "Avocado", "Potato", "Strawberry", "Spinach", "Artichoke", "Peas", "Asparagus", "Green Onions", "Radish", "mystery", "mystery 2"] ingredients = [['Cauliflower', 'Produce', '1 head', 0], ['Salt', 'Other', '2 tsp', 2], ['Olive Oil', 'Other', '2 tbs', 1]] seasons = %w[Summer Fall].map { |name| Season.find_or_create_by(name: name) } seasons.each do |season| foods.each do |food| food = Food.find_or_create_by(name: food, slug: season.name.downcase + '-' + food.downcase.split.join('-'), season: season) recipe = food.recipes.find_or_create_by(easy_recipe_attributes.merge(title: "#{season.name} Roasted #{food.name}" )) ingredients.each do |ingredient_name, category, quantity, sort_order| ingredient = Ingredient.find_or_create_by!(name: ingredient_name, category: category) recipe.ingredient_list_items.find_or_create_by!(ingredient_id: ingredient.id, quantity: quantity, sort_order: sort_order) end end end ['Gluten Free', 'Dairy Free'].each { |allergy_name| Allergy.find_or_create_by!(name: allergy_name) }
true
ffbc7e214284def5b03f6be40553c6e2f619254b
Ruby
codedymes/ruby-challenges
/numerology.rb
UTF-8
955
3.359375
3
[]
no_license
puts "please enter your birthdate in the following format: MMDDYYYY" birthday = gets results = birthday[0].to_i + birthday[1].to_i + birthday[2].to_i + birthday[3].to_i + birthday[4].to_i + birthday[5].to_i + birthday[6].to_i + birthday[7].to_i results.to_s results = results[0].to_i + results[1].to_i if (results > 9) results = results[0].to_i + results[1].to_i end case results when 1 puts "Your numerology number is #{results}." when 2 puts "Your numerology number is #{results}." when 3 puts "Your numerology number is #{results}." when 4 puts "Your numerology number is #{results}." when 5 puts "Your numerology number is #{results}." when 6 puts "Your numerology number is #{results}." when 7 puts "Your numerology number is #{results}." when 8 puts "Your numerology number is #{results}." when 9 puts "Your numerology number is #{results}." else puts "Your number did not compute, try again" end #elsif puts "Your num is #{results}."
true
8a7d7f8b2d59fb35e12b427372acf5647ab7a078
Ruby
TheLucasMoore/oo-meowing-cat-v-000
/lib/meowing_cat.rb
UTF-8
66
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Cat attr_accessor :name def meow puts "meow!" end end
true
a6b4fed270c77a410ae83d94f5a30721e3b82b72
Ruby
rhivent/ruby_awal
/array.rb
UTF-8
764
4
4
[]
no_license
#array bahasa = ["array",2,"js","css","python"] puts "pertama : " + bahasa.first puts "terakhir : " + bahasa.last #ambil 2 bagian pertama puts "2 bgian pertama : #{bahasa.take(2)}" puts "count array : #{bahasa.count}" puts "length array : #{bahasa.length}" bahasa.push("ruby") #memasukkan data ke dlm array di akhir array bahasa.unshift("c++") #memasukkan data ke dlm array di awal array print bahasa puts "" bahasa.insert(2,"swift") #memasukkan data ke dlm array di posisi tertentu dengan parameter 1 = posisi dan parameter kedua data yg dimasukkan print bahasa puts "" # mengeluarkan nilai yg terakhir dari data array bahasa.pop print bahasa puts "" # mengeluarkan nilai yg pertama dari data array puts "ngeluarin nilai #{bahasa.shift}" print bahasa puts
true
9c7252a52d76b9c8c74aba4353ee188819c21d78
Ruby
phallguy/shamu
/lib/shamu/events/channel_stats.rb
UTF-8
654
2.625
3
[ "MIT" ]
permissive
module Shamu module Events # Indicates that an {EventsService} supports reporting channel activity states. module ChannelStats # Gets stats for the given `channel`. # # #### Stats Included in the results. # # - **name** name of the channel. # - **subscribers_count** the number of subscribers. # - **queue_size** the size of the message queue. # - **dispatching** true if the channel is currently dispatching messages. # # @param [String] name of the channel # @return [Hash] stats. def channel_stats( name ) fail NotImplementedError end end end end
true
7a105eed66b60e90c105d391d8ea0cf7e19d553f
Ruby
takaya-47/take_out_app
/app/models/order_order_detail.rb
UTF-8
1,895
2.5625
3
[]
no_license
class OrderOrderDetail # フォームオブジェクトクラスであるのでライブラリを読み込む include ActiveModel::Model # このクラスで扱う属性を全て定義 attr_accessor :quantity, :total_price, :last_name, :first_name, :last_name_kana, :first_name_kana, :prefecture_id, :address, :phone_number, :visit_day_id, :visit_time_id, :menu_id, :token # バリデーションを記述 with_options presence: true do validates :quantity, numericality: { greater_than: 0, less_than: 101 } validates :total_price validates :address validates :phone_number, format: { with: /\A0[1-9]\d{0,3}[-(]\d{1,4}[-)]\d{4}\z/ } validates :menu_id validates :token end # そもそもリストから選ぶ形式なので0以外についてのみ制約を設ける with_options numericality: { other_than: 0, message: 'を選択してください' } do validates :prefecture_id validates :visit_day_id validates :visit_time_id end # 全角漢字、かな、カナがOK with_options format: { with: /\A[ぁ-んァ-ヶ一-龥々]+\z/ } do validates :last_name validates :first_name end # 全角カナのみOK with_options format: { with: /\A[ァ-ヶ]+\z/ } do validates :last_name_kana validates :first_name_kana end # 以下にデータ保存の処理を記述 def save order = Order.create(menu_id: menu_id) # 先に保存したorderインスタンスのidを使っている! order_detail = OrderDetail.create!(quantity: quantity, total_price: total_price, last_name: last_name, first_name: first_name, last_name_kana: last_name_kana, first_name_kana: first_name_kana, prefecture_id: prefecture_id, address: address, phone_number: phone_number, visit_day_id: visit_day_id, visit_time_id: visit_time_id, order_id: order.id) end end
true
1b12157e1e7b1733542485894b3f9b14d0b13bfd
Ruby
gersonnoboa/TaxiAppAPI
/app/controllers/api/bookings_helper.rb
UTF-8
2,222
2.640625
3
[]
no_license
module Api::BookingsHelper require 'compute_distance_between.rb' def create_booking(user, location) Booking.create(location_id: location.id, status: Booking::AVAILABLE, user_id: user.id) end def push_to_next_driver(driver, booking) driver_list = [] drivers = Driver.where("status = ? ", Driver::ACTIVE).where("id != ?", driver.id) location = Location.find_by(id: booking.location_id) create_drivers_list(drivers, driver_list, location) push_booking_to_drivers(driver_list, booking) end def push_booking_to_drivers(driver_list, booking) driver_list.each do |driver| chan = driver.to_s Pusher.trigger(chan, 'ride', { action: 'new_booking', booking: { start_location: booking.location.pickup_address, destination: booking.location.dropoff_address, id: booking.id }, customer: { first_name: booking.user.first_name, last_name: booking.user.last_name, email: booking.user.email } }) end end def create_drivers_list(drivers, driver_list, location) drivers.each do |driver| if is_nearest_driver(driver, location) then driver_list.push("driver_#{driver.id}") end end end def is_nearest_driver(driver, location) # Nearest on a 3km radius cl = location dl = driver # dl = location # mocked as the driver current location not yet implemented loc1 = [cl.pickup_lat, cl.pickup_long] # loc2 = [dl.pickup_lat, dl.pickup_long] loc2 = [dl.current_location_lat, dl.current_location_long] compute = ComputeDistanceBetween.new(loc1, loc2) #if (compute.get_distance <= 3000.0) then true else false end true end def push_status_to_user(booking, driver) Pusher.trigger("customer_#{booking.user_id}", 'pickup', { message: 'Your taxi is enroute', car_model: driver.car_model, car_color: driver.car_color, plate_number: driver.plate_number }) end def update_status(booking, driver) booking.status = Booking::CLOSED booking.driver_id = driver.id driver.status = Driver::BUSY booking.save && driver.save end end
true
46ee130cbfd5a2830a73de1575f7e230596da23e
Ruby
JOCOghub/ruby-getting-remote-data-lab-onl01-seng-ft-070620
/lib/get_requester.rb
UTF-8
371
2.6875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'open-uri' require 'net/http' require 'json' class GetRequester URL = "http://data.cityofnewyork.us/resource/uvks-tn5n.json" def initialize(url) @url = url end def get_response_body uri = URI.parse(@url) variable = Net::HTTP.get_response(uri) variable.body end def parse_json JSON.parse(get_response_body) end end
true
4526361dd94884300cbcbbe669e64aea156d0c7b
Ruby
bhb/tack
/lib/tack/middleware/parallel.rb
UTF-8
2,295
2.578125
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'forkoff' require 'facter' module Tack module Middleware class Parallel include Middleware::Base def initialize(app, options = {}) super @processes = options.fetch(:processes) { processors } @processes = processors if @processes == 0 @output.puts "Running tests in parallel in #{@processes} processes." end def run_suite(tests) many_results = map(tests) total_results = reduce(many_results) failing_tests = total_results[:failed].map{|result| result[:test]} if !failing_tests.empty? @output.puts "Rerunning #{failing_tests.length} tests (in case they failed due to parallelism)" total_results[:failed].clear new_results = @app.run_suite(failing_tests) final_results = reduce([total_results,new_results]) else final_results = total_results end final_results end private def processors Facter.loadfacts Facter.sp_number_processors.to_i end def map(tests) test_groups = [] tests.each_slice([tests.length.to_f/@processes,1].max) do |group| test_groups << group end results = test_groups.forkoff! :processes => @processes, :strategy => 'file' do |*test_group| if !test_group.first.is_a?(Array) test_group = [test_group] end result = basics(Util::ResultSet.new) # TODO - this is just a hack to see if the tests pass # In reality, we shouldn't silently ignore the fact # that for some reason, parallel mode fails to catch :invalid_test catch(:invalid_test) do result = @app.run_suite(test_group) end result || {} end results.each do |result| raise result if result.is_a?(Exception) end results end def reduce(many_result_sets) merged_result_set = { :passed => [], :failed => [], :pending => [] } [:passed, :failed, :pending].each do |key| many_result_sets.each do |result_set| merged_result_set[key] += result_set[key] end end merged_result_set end end end end
true
688e9211f39aca5543016fddbebfea96115bb550
Ruby
khamilowicz/Jumpstart_store
/app/models/address.rb
UTF-8
473
2.703125
3
[]
no_license
class Address < ActiveRecord::Base attr_accessible :country, :city, :zip_code, :street, :house_nr, :door_nr validates_numericality_of :zip_code, :house_nr, :door_nr, greater_than: 0, only_integer: true, allow_nil: true belongs_to :user def to_s "#{self.country} #{self.zip_code_formed} #{self.city} #{self.street} #{self.house_nr}/#{self.door_nr}" end def zip_code_formed "" + self.zip_code.to_s.first(2) + "-" + self.zip_code.to_s.last(3) end end
true
84a929384b3cc260f652c9f675ec73c2fa28cb9a
Ruby
wusuopu/youdao-dict-rb
/db.rb
UTF-8
3,605
2.84375
3
[]
no_license
#!/usr/bin/env ruby #-*- coding:utf-8 -*- # Copyright (C) 2012 ~ 2013 Deepin, Inc. # 2012 ~ 2013 Long Changjin # # Author: Long Changjin <admin@longchangjin.cn> # Maintainer: Long Changjin <admin@longchangjin.cn> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. module Database require "sqlite3" require "json" FILE_NAME = "word.db" class DBManager def initialize @db = SQLite3::Database.new(FILE_NAME) create_table unless table_exists? @insert_state = @db.prepare "insert into word (keyword, pronounce, voice, trans, web_trans, word_group) values (?, ?, ?, ?, ?, ?)" @select_state = @db.prepare "SELECT * FROM word WHERE keyword=(?);" end def table_exists? table = false @db.execute( "SELECT name FROM sqlite_master WHERE type='table';" ) do |row| if row[0] == "word" then table = true break end end table end def create_table @db.execute(''' CREATE TABLE IF NOT EXISTS "main"."word" ( "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "keyword" varchar(150) NOT NULL, "pronounce" varchar(100), "voice" TEXT, "trans" TEXT, "web_trans" TEXT, "word_group" TEXT ); ''') end def insert(data) if ! data.include? :keyword || data[:keyword] == "" then return nil end keyword = data[:keyword].downcase begin pronounce = data[:pronounce].to_json rescue pronounce = "[]" end begin voice = data[:voice].to_json rescue voice = "[]" end begin trans = data[:trans].to_json rescue trans = "[]" end begin web_trans = data[:web_trans].to_json rescue web_trans = "[]" end begin word_group = data[:word_group].to_json rescue word_group = "[]" end begin @insert_state.execute keyword, pronounce, voice, trans, web_trans, word_group rescue Exception => e p e nil end end def select(word) @select_state.execute word do |result_set| row = result_set.first if ! row then return nil end res = {} res[:keyword] = row[1] begin res[:pronounce] = JSON.parse row[2] rescue res[:pronounce] = [] end begin res[:voice] = JSON.parse row[3] rescue res[:voice] = [] end begin res[:trans] = JSON.parse row[4] rescue res[:trans] = [] end begin res[:web_trans] = JSON.parse row[5] rescue res[:web_trans] = [] end begin res[:word_group] = JSON.parse row[6] rescue res[:word_group] = [] end return res end nil end def close @insert_state.close @select_state.close @db.close end end end
true
80adf16887814e1559dc96b6cddb014e2a166d63
Ruby
npogodina/linked-lists
/lib/linked_list.rb
UTF-8
1,298
3.734375
4
[ "MIT" ]
permissive
require_relative 'node' class LinkedList attr_reader :head def initialize @head = nil end # Time complexity - O(1) # Space complexity - O(1) def add_first(data) first = Node.new(data, head) @head = first end # Time complexity - O(1) # Space complexity - O(1) def get_first return head ? head.data : nil end # Time complexity - O(n) # Space complexity - O(1) def length counter = 0 return counter if head == nil node = head while node counter += 1 node = node.next end return counter end # Time complexity - O(n) # Space complexity - O(1) def add_last(data) if head.nil? add_first(data) return end node = head until node.next.nil? node = node.next end node.next = Node.new(data) end # Time complexity - O(n) # Space complexity - O(1) def get_last node = head until node.next.nil? node = node.next end return node.data end # Time complexity - O(n) # Space complexity - O(1) def get_at_index(index) return nil if head == nil counter = 0 node = head until counter == index || node.next.nil? node = node.next counter += 1 end return counter == index ? node.data : nil end end
true
25182b8f7240c6a4daac68f2104cfb9e1b166978
Ruby
Himuravidal/E8CP1A1
/ejer04.rb
UTF-8
439
3.109375
3
[]
no_license
def show_stock_by_product lines = File.open('archivo.txt', 'r').readlines.each(&:chomp) new_lines = [] lines.each { |line| new_lines.push(line.split(', ').map(&:chomp)) } new_lines.each do |details| name = details.shift sum = get_sum(details) end end def get_sum(details) suma = 0 details.each do |ele| unless ele == 'NR' sum += ele.to_i end end return sum end show_stock_by_product
true
b9008b9e2161c71f8841d4d76ad5c4382737d6f0
Ruby
RTurney/Birthday-app
/app.rb
UTF-8
534
2.953125
3
[]
no_license
# frozen_string_literal: true require 'sinatra' require_relative './lib/birthday_calculator' # Main app class. Inherits from Sinatra base. class Birthday < Sinatra::Base get '/' do erb(:index) end post '/birthday' do @bday_calculator = BirthdayCalculator.new @name = params[:name] @day = params[:day].to_s monthYear = params[:month] @month = monthYear.split('-')[1].to_s if @bday_calculator.calculate_days(@day, @month) == 0 erb(:birthday) else erb(:days_left) end end end
true
133399338118b6d3a3907ef3d03368fcacf095af
Ruby
cielavenir/procon
/yukicoder/3xxx/tyama_yukicoder3100.rb
UTF-8
85
2.9375
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby gets.to_i.times{ n=gets.to_i p (n+~gets.split.map(&:to_i).sum)%-~n }
true
ee095668338af80b696ec60587ca5782897e2bb6
Ruby
ifcwebserver/IFCWebServer-Extensions
/extensions/byclass/IFC.rb
UTF-8
2,109
2.671875
3
[]
no_license
xx = <<-eos class API def getObjectByLineID(id) #doc:<div class='documentaion' >Return an IFC object by its STEP ID </div> end def IFC_CLASS_NAME.nonInverseAttributes #doc:<div class='documentaion' >Return a list of IFC class basic attributes<br> #doc:<b> IFCCOLUMN.nonInverseAttributes</b>: -->>><br>"|globalId |ownerHistory |name |description |objectType |objectPlacement |representation |tag"</div> end def IFCObject.to_xml (obj) #doc:<div class='documentaion' >Serialize any IFC object as XML #doc:<br><u> Example:</u><b> "#61185".to_obj.to_xml</b> -->>><br> #doc:&lt;IFCCOLUMN&gt; #doc:&lt;line_id&gt;61185&lt;/line_id&gt; #doc:&lt;globalId&gt;'0APvzagRfDa8S2CxmCLJFH'&lt;/globalId&gt; #doc:&lt;ownerHistory&gt;#13&lt;/ownerHistory&gt; #doc:&lt;name&gt;'St\S\|tze-001'&lt;/name&gt; #doc:&lt;description&gt;''&lt;/description&gt; #doc:&lt;objectType&gt;$&lt;/objectType&gt; #doc:&lt;objectPlacement&gt;#61239&lt;/objectPlacement&gt; #doc:&lt;representation&gt;#61228&lt;/representation&gt; #doc:&lt;tag&gt;$&lt;/tag&gt; #doc:&lt;/IFCCOLUMN&gt; #doc:</div> end def IFCObject.to_csv(obj) #doc:<div class='documentaion' >Serialize any IFC object as Comma-Separated Values (CSV) </div> end def IFCObject.to_html (obj) #doc:<div class='documentaion' >Serialize any IFC object as row in HTML table</div> end def IFC_CLASS_NAME.list(cols="") #doc:<div class='documentaion' >Return a list of all IFC class instances, the parameter 'cols' can be used to define a set of custom data fields to be reported </div> end def IFCObject.as_link #doc:<div class='documentaion' >Return HTML hyperlink to any IFC object instance </div> end def IFC_CLASS_NAME.where (cond,output) #doc:<div class='documentaion' >Return a hash of user defined output applied on IFCCLASS object's instances which meet the 'cond' expression, 'all' or true can be used to retrive all instances, 'cond' can be any valid Ruby expression applied on each object instance, the 'o' is used as place holder for object instances <br><b>IFCWINDOW.where("all","o.area > 2.00")</b> </div> end end eos
true
ce22665fc23fe3acc939441cd8b3df8f91d86071
Ruby
eggyy1224/101-programming-foundation
/small_problems/medium2/balance.rb
UTF-8
616
3.828125
4
[]
no_license
require 'pry' def balanced?(str) left = 0 right = 0 str.chars.each do |char| if char == '(' left += 1 elsif char == ')' right += 1 return false if left - right == -1 end end right - left == 0 ? true : false end puts balanced?(')Hey!(') puts balanced?('What (is) this?') == true puts balanced?('What is) this?') == false puts balanced?('What (is this?') == false puts balanced?('((What) (is this))?') == true puts balanced?('((What)) (is this))?') == false puts balanced?('Hey!') == true puts balanced?(')Hey!(') == false puts balanced?('What ((is))) up(') == false
true