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
1c56ec8c0a8f7304bd2e011f1ab22ddaa575f981
Ruby
adamhundley/exercism
/ruby/hamming/hamming.rb
UTF-8
425
3.46875
3
[]
no_license
class Hamming attr_reader :zipper VERSION = 1 def self.compute(one, two) raise ArgumentError if one.length != two.length calculate(one,two) end def self.zip_town(one, two) one.chars.zip(two.chars) end def self.calculate(one,two) score = 0 zip_town(one, two).each do |x,y| if x != y score += 1 end end score end end Hamming.compute('GGACTGA', 'GGACTGA')
true
0cb8b738809e1ea2c9478031307454bfc059213c
Ruby
diatmpravin/modbDev
/lib/filter_query.rb
UTF-8
496
2.890625
3
[]
no_license
class FilterQuery # Given a query string, parse it out into an appropriate Hash # structure for Model.search to work properly. def self.parse(query) filter = {:full => query} key = :query query.split("\s").each do |word| filter[key] ||= [] if word =~ /(.*):$/ key = $1.to_sym else filter[key] << word end end filter.each_key do |k| filter[k] = filter[k].join(" ") if filter[k].is_a?(Array) end filter end end
true
095ad6f3e867191615aacd9318f32aa57149d926
Ruby
AlexFrz/Le-scrappeur-fou---THP
/lib/dark_trader.rb
UTF-8
1,586
3.53125
4
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' #1 Première méthode : Déclaration de la page à scrapper def get_page page = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/")) return page end #2 Deuxième méthode : Collecte des abbréviations des noms des monnaies def scrapp_symbols page = get_page symbols = page.css("//tbody//tr//td[@class='cmc-table__cell cmc-table__cell--sortable cmc-table__cell--left cmc-table__cell--sort-by__symbol']//div/text()") symbols_array = [] #/ initialisation d'un array pour les stocker symbols.each do |symbol| #/ on met .text pour les avoir en string après each car each que sur integer symbols_array << symbol.text end return symbols_array end #3 Troisième méthode : Collecte des cours des monnaies def scrapp_prices page = get_page prices = page.xpath("//tbody//tr//td[@class='cmc-table__cell cmc-table__cell--sortable cmc-table__cell--right cmc-table__cell--sort-by__price']//a[@class='cmc-link']//text()") prices_array = [] prices.each do |price| prices_array << price.text[1..-1].to_f end return prices_array end #4 Quatrième méthode : Synchronisation des noms et des cours des monnaies def crypto_master symbols_array = scrapp_symbols #/ on rappelle nos méthodes prices_array = scrapp_prices a = [] #/ on initialise un array pour les stocker symbols_array.each_with_index do |k, v| #/ on associe pour chaque item de symbols_array un item de prices_array a << {k => (prices_array)[v]} #/ on sauvegarde sous forme d'hash dans le tableau end print a return a end crypto_master
true
19bba609d0071601e01bd21517cdb13024bb9008
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/nucleotide-count/986b42c131c244de81f1eb5093ce2d44.rb
UTF-8
455
3.53125
4
[]
no_license
class DNA NUCLEOTIDES = "ATCG" def initialize(string) raise ArgumentError unless good_genes(string) || string.empty? @string = string end def count(nucleotide) raise ArgumentError unless good_genes(nucleotide) @string.count(nucleotide) end def nucleotide_counts Hash[*NUCLEOTIDES.chars.map {|k| [k,count(k)]}.flatten] end private def good_genes(strand) strand =~ Regexp.new("^[#{NUCLEOTIDES}]+") end end
true
cf5d5d06d90cdaffe4d4213d2eb38831d3f5bfb1
Ruby
jaggederest/ragi
/ragi/test.rb
UTF-8
3,922
2.828125
3
[ "BSD-3-Clause" ]
permissive
# # RAGI - Ruby classes for implementing an AGI server for Asterisk # The BSD License for RAGI follows. # # Copyright (c) 2005, SNAPVINE LLC (www.snapvine.com) # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of SNAPVINE nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module RAGI # This class is useful for writing unit tests class TestSocket def initialize(params, messages) @params = params @messages = messages @inParams = true @currentIndex = 0 end def self.Exec(cmd, params) [ "EXEC #{cmd} #{params}", "200 result=0"] end def self.GetData(soundfile, result) ["GET DATA #{soundfile} 2000", "200 result=#{result} (timeout)"] end def self.StreamFile(soundfile, escapeDigits, initialOffset, result, endpos) ["STREAM FILE #{soundfile} \"#{escapeDigits}\" #{initialOffset}", "200 result=#{result} endpos=#{endpos}"] end def self.PlaySound(soundfile) [ "EXEC playback #{soundfile}", "200 result=0"] end def self.SayNumber(number) SayNumberFull(number, " \"*#\"") end def self.SayNumberFull(number, escapeDigits) [ "SAY NUMBER #{number} \"#{escapeDigits}\"", "200 result=0"] end def self.HangUp() [ "HANGUP", "200 result=0"] end def print(msg) if @inParams raise StandardError, "Should not receive commands until parameters are parse" end if (!@messages[@currentIndex]) raise StandardError, "Too many messages received\nMessage =#{msg}= received" end if (msg != @messages[@currentIndex][0]) raise StandardError, "Unexpected message received\nMessage =#{msg}= received\nExpected =#{@messages[@currentIndex][0]}" end end def gets if (@inParams) then if (@currentIndex < @params.length) then key = @params.keys[@currentIndex] val = "#{key}: #{@params[@params.keys[@currentIndex]]}" @currentIndex += 1 else @currentIndex = 0 @inParams = false val = '' end else if (@currentIndex < @messages.length) then val = @messages[@currentIndex][1] @currentIndex += 1 else raise StandardError, "Unexpected messages past end of test case" @currentIndex = 0 val = '\n' end end val end end end
true
702ced8a23bc9caf518f6dca26ae82306a82016a
Ruby
schan1031/AppAcademy-Master
/W2D3/Poker/spec/deck_spec.rb
UTF-8
363
2.734375
3
[]
no_license
require 'rspec' require 'deck' describe Deck do subject(:deck) {Deck.new} describe "#initialize" do it 'initializes a full deck' do expect(deck.deck_list.length).to eq(52) end describe "#shuffle" do it 'shuffles the deck' do temp = deck.deck_list.dup expect(deck.shuffle!).not_to eq(temp) end end end end
true
1690db640fad7e5d112cebad2fcd5ac76728702d
Ruby
danidemi/shop_management
/lib/worksheet.rb
UTF-8
3,814
2.671875
3
[]
no_license
class Worksheets attr_accessor :operators, :time_intervals def build_operator_headers operators = Operator \ .select(:first_name, :last_name) \ .joins(:company) \ .where(:companies => {:id => current_operator.company.id}) operatorHeaders = Array.new operators.each{ |operator| operatorHeaders << {:id => operator.id, :label => operator.first_name + " " + operator.last_name}; } operatorHeaders << {:id => nil, :label => "noop"}; return operatorHeaders end def build_time_rows(a_date) day_start = DateTime.parse(a_date.to_s) day_end = day_start day_start = day_start.advance :hours=>8 day_end = day_end.advance :hours=>18 increment_field = :minutes increment_amount = 30 time_intervals = Array.new while day_start < day_end do interval_start = day_start interval_end = interval_start.advance( increment_field => increment_amount ) time_intervals << {:start => interval_start, :end => interval_end} day_start = interval_end end return time_intervals end def build_meetings_list(a_date) return Meeting.joins(:company).where(:companies => {:id => current_operator.company.id}) end def build_empty_worksheet(operators, intervals) worksheet = Array(operators.count); heads.count.times{ |i| worksheet[i] = Array(intervals.count) } return worksheet end def dododo(a_date) heads = build_operator_headers rows = build_time_rows a_date meets = build_meetings_list a_date worksheet = build_empty_worksheet if(meets && !meets.empty?) meeting_index = 0 heads.count.times{ |operator_index| rows.count.times{ |time_interval_index| operator = heads[operator_index] time_interval = rows[time_interval_index] if(meeting_index < meets.count) meeting = meets[meeting_index] while( meeting && meeting.operator_id == operator[:id] && time_interval[:start] <= meeting.start && time_interval[:end] < meeting.start ) if(!worksheet[operator_index, time_interval_index]){ worksheet[operator_index, time_interval_index] = Array.new } worksheet[operator_index, time_interval_index] << meeting meeting_index++ if(meeting_index < meets.count) meeting = meets[meeting_index] else meeting = nil end end end } } end end def build(a_date) # Retrieve the list of operators @operators = Operator.select(:first_name, :last_name).joins(:company).where(:companies => {:id => current_operator.company.id}) # Compute the list of time intervals day_start = DateTime.parse(a_date.to_s) day_end = day_start day_start = day_start.advance :hours=>8 day_end = day_end.advance :hours=>18 increment_field = :minutes increment_amount = 30 @time_intervals = Array.new while day_start < day_end do interval_start = day_start interval_end = interval_start.advance( increment_field => increment_amount ) @time_intervals << {:start => interval_start, :end => interval_end} day_start = interval_end end @meetings = {} @operators.each do |operator| @time_intervals.each do |interval| meetings = Meeting \ .joins(:company) \ .joins(:operator) \ .where(:companies => {:id => current_operator.company.id}) \ .where(:operators => {:id => operator.id}) \ .where([":start < start AND start < :end", {:start => interval_start, :end => interval_end}]) \ .order(:start) @meetings[interval] = {} @meetings[interval][operator] = meetings; end end return self end def meetings_for(time_interval, operator) @meetings[time_interval][operator] end end
true
4edb59252ea7f908c599ef3f1db28b21d4bbacdb
Ruby
KirkMartinez/cryptopals
/lib/c14_byte_ecb_decrypt_harder.rb
UTF-8
4,829
3.3125
3
[]
no_license
# Challenge 14: byte at a time ECB decryption require_relative 'cbc_encryptor' require_relative 'ecb_encryptor' require_relative 'utilities' KEYSIZE=16 # Oracle encrypts using a consistent, but unknown key with ECB # Oracle encrypts like this: # AES-128-ECB(random-prefix || attacker-controlled || target-bytes, random-key) @key = (1..KEYSIZE).map {rand(256).chr}.join def encryption_oracle(attacker_controlled) rnd = rand(40) random_prefix = (0..rnd).map { rand(255).chr }.join secret = 'Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK' target_bytes = secret.unpack("m0").first plain_text = random_prefix + attacker_controlled + target_bytes padded = CBCEncryptor.pad(plain_text, KEYSIZE) ecb = ECBEncryptor.new(@key) ecb.encrypt(padded) end # Goal: decrypt target-bytes # How? # We can generate two identical blocks that we know it will be duplicated # in sequential blocks of ct if the blocks are block-aligned. # We can't control block-alignment since we don't know the prefix length. # We could determine the prefix len, if it is fixed, by prepending to # our double-block. If it's not fixed we have to make many requests and # filter out the ones that are block-aligned (have repeating sequential ct). # # Ex: suppose block size is 4 # Key: random-prefix chars='R' # target chars (unknown or known)='A..Z' # our pt chars='a..z' # # Byte-aligned: # RRRR abcd abcd ABCD EFGH IJKL # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # Byte-misaligned: # RRRR RRab cdab cdAB CDEF GHIJ KLMN # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # # To shift in the first char of target-bytes (assuming byte alignment), # try all chars in the last byte of block 0 & remove last char of block 1: # RRRR abc? abcA BCDE FGHI JKLM # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # # But now we don't know if we are byte aligned when looping through ? values. # Solution: a third duplicate block to indicate block-alignment: # (Let's assume, for simplicity's sake that the random prefix can be greater # than the block size. Otherwise we'd need to try more padding in front of # out pt so that we will get duplicate ct.) # # RRRR abc? abc? abcA BCDE FGHI JKLM # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # # Next byte is much the same: # RRRR abA? abA? abAB CDEF GHIJ KLM # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # # After reading "ABCD", shift "A" out and compare vs the next unknown byte. # We also need to append the correct # of padding chars to align target-bytes: # RRRR BCD? BCD? aaaA BCDE FGHI JKLM # 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 0123 # # Naming: # block #'s are counted w/r/t our provided text # # This different from the alg in Challenge 12 in two ways: # 1) we need to detect and only work with block-aligned results # 2) we need to identify the ct block matching where our pt starts # Requests an encryption of pt # Asks oracle multiple times until duplicate sequential ct blocks are sequential # Only then does it return # Returns: (ct, pt_start_block) # Input: pt must be even multiple of blocksize to ensure duplicate ct block seen def repeating_block(t) block = -1 (0..t.length/BLOCKSIZE).each do |block_num| if t[block_num*BLOCKSIZE..block_num*BLOCKSIZE+BLOCKSIZE-1] == t[(block_num+1)*BLOCKSIZE..(block_num+1)*BLOCKSIZE+BLOCKSIZE-1] puts block_num block = block_num end end block rescue puts "WARNING: No repeating block found." block end def ask(pt) trial = nil loop do trial = encryption_oracle(pt) break if repeats(trial, BLOCKSIZE) end block = repeating_block(trial) [trial, block] end puts ask('YELLOW SUBMARINE'*2) def decrypt(prefix_count, so_far, block_num) r = 'a'*prefix_count short = encryption_oracle(r)[block_num*16..block_num*16+15] # ciphertext with start of unknown # ^ pulling the right byte, but need to include 15 bytes of of padding... (0..255).each do |ch| if block_num == 0 t = r + so_far + ch.chr # padding + known unknown chars + test char in last position else t = so_far + ch.chr # no padding since we are in scan mode Now end test = encryption_oracle(t)[0..15] if short == test return ch end end nil end def decrypt_block pt_so_far = '' (0..1000).each do |byte| block_num = byte / 16 # Block including char we are identifying if byte < 16 pos_to_insert = 16-byte prefix_count = (pos_to_insert-1) decrypted_char = decrypt(prefix_count, pt_so_far, block_num) pt_so_far += decrypted_char.chr else pt_so_far = pt_so_far[1..15] decrypted_char = decrypt(15-byte%16, pt_so_far, block_num) break unless decrypted_char pt_so_far += decrypted_char.chr end print(decrypted_char.chr) end end # decrypt_block
true
cbc5629aba53a168a146ad6b20b0e3e5abbd2469
Ruby
jns/Aims
/bin/aims_output.rb
UTF-8
5,548
2.703125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'optparse' require 'aims' options = {:step => :all} optParser = OptionParser.new do |opts| opts.banner = "usage: #{File.basename $0} [options] file1 [file2 ...]" opts.on('-s', '--step [N]', 'Output information for relaxation step.', "Specify an integer, 'first', 'last', or 'all'", "Default is 'all'") do |s| case s when /([1-9]+)/ options[:step] = $1.to_i when "first" options[:step] = :first when "last" options[:step] = :last else options[:step] = :all end end opts.on('--debug', 'Debug output') do options[:debug] = true end opts.on('-g', '--geometry', 'Output Geometry for selected relaxation steps') do options[:geometry] = true end opts.on('--geometry-delta', 'Display change from input geometry to final geometry') do options[:geometry_delta] = true end opts.on('-c', '--self-consistency', 'Output self-consistency information') do options[:self_consistency] = true end opts.on('-f', 'Output max force component for each geometry relaxation step') do options[:forces] = true end opts.on('-t', 'Output timings') do options[:timings] = true end end begin optParser.parse!(ARGV) files = ARGV if files.empty? puts optParser.help exit end outputs = files.collect{|f| Aims::OutputParser.parse(f) } int_format = "%-20s %20i" float_format = "%-20s 20.5f" exp_format = "%-20s %20.5e" sciter_format = "%-20s %20i" timings_format = "%-35s %20.5f" energy_format = "%-35s %20.5f" force_format = "%-35s %20.5e" total_sc_iterations = 0 total_relaxations = 0 outputs.each{|output| puts "**************************************************************************" puts "**" puts "** #{output.original_file}" puts "**" puts "**************************************************************************" steps = case options[:step] when Integer stepno = options[:step] if stepno < 0 [output.geometry_steps.last] elsif stepno < output.geometry_steps.size [output.geometry_steps[stepno]] else [output.geometry_steps.last] end when :first [output.geometry_steps.first] when :last [output.geometry_steps.last] else output.geometry_steps end steps.each_with_index{|step, i| total_relaxations += 1 total_sc_iterations += step.sc_iterations.size puts "= Relaxation Step #{step.step_num} =" indent = " " puts indent + sciter_format % ["SC Iterations", step.sc_iterations.size] puts indent + energy_format % ["Total Energy", step.total_energy] puts indent + timings_format % ["Total CPU time", step.total_cpu_time] puts indent + timings_format % ["Total Wall time", step.total_wall_time] if options[:forces] and not step.forces.empty? puts indent + force_format % ["Max Force", step.forces.max{|a,b| a.r <=> b.r}.r] end if options[:timings] puts " Cumulative SC Timings:" step.timings.each{|t| puts " " +timings_format % [t[:description], t[:cpu_time]]} end if options[:self_consistency] indent = " " # Iterate over each sc iteration step.sc_iterations.each_with_index{|sc_iter, iter| # SC Iteration Header puts " == SC Iteration #{iter} ==" # Output convergence criterion puts indent + exp_format % ["Change in total energy", sc_iter.d_etot] puts indent + exp_format % ["Change in sum of eigenvalues", sc_iter.d_eev] puts indent + exp_format % ["Change in charge density", sc_iter.d_rho] # Output timings if requested if options[:timings] if sc_iter.timings sc_iter.timings.each{|t| puts indent + timings_format % [t[:description], t[:cpu_time]] } else puts "No timing data available." end end puts "" } end if options[:geometry] puts step.geometry.format_geometry_in end puts "\n\n" } puts "= Calculation Summary =" unless output.geometry_converged puts "Warning Geometry not converged!" end puts int_format % ["Number of SC Iterations found:", total_sc_iterations] puts int_format % ["Number of Relaxation Steps found:", total_relaxations] puts float_format % ["Total CPU time", output.total_cpu_time] output.computational_steps.each{|cs| puts int_format % [cs[:description], cs[:value]] } if options[:timings] output.timings.each{|t| puts " " +timings_format % [t[:description], t[:cpu_time]]} end # puts timings_format % ["Total Wall time", output.total_wall_time] if options[:geometry_delta] puts "= Change in atomic positions for calculation" puts output.geometry_steps.last.geometry.delta(output.geometry_steps.first.geometry) end } # puts "Total relaxation steps: #{total_relaxations}" # puts "Total sc iterations: #{total_sc_iterations}" rescue puts "" puts "Sorry. There was an error parsing the remainder of the file." if options[:debug] puts $!.message puts $!.backtrace else puts "Rerun with --debug for more info" end puts "" exit end
true
069d6d5bb8b990133b7557d9759f214efb948b01
Ruby
Alias-a/DrivingHistoryAnalyzer
/spec/trip_spec.rb
UTF-8
669
3.265625
3
[]
no_license
require File.dirname(__FILE__) + '/../lib/driving_history_analyzer/trip' require 'date' describe DrivingHistoryAnalyzer::Trip do describe "#to_s" do it "should print all the attributes of the trip object" do time_elapsed = 2220 start_time = Time.new(2018, 11, 16, 9, 3) end_time = Time.new(2018, 11, 16, 9, 40) miles_driven = 101 driver_name = "Spongebob" trip = DrivingHistoryAnalyzer::Trip.new(start_time, end_time, miles_driven, driver_name) expect(trip.to_s).to eq(""+ "Driver: Spongebob,\n"+ "Start Time: 09:03,\n"+ "End Time: 09:40,\n"+ "Miles Driven: 101,\n"+ "Time Elapsed: 2220.0"+ "") end end end
true
56329108288bbf0c3678ae1a29a4c4e8489a983a
Ruby
mariangelds/pitagoras
/app/models/archivo.rb
UTF-8
5,159
2.59375
3
[]
no_license
class Archivo < ActiveRecord::Base has_no_table column :ruta, :string def validar_extension (archivo) nombre = archivo.original_filename $extension = nombre.slice(nombre.rindex("."),nombre.length).downcase if ($extension == ".xls" || $extension ==".xlsx") true else false end end def subirArchivo(archivo , materia) leerExcel(archivo.original_filename) #Con la clave del profesor conoceremos su materia m=materia conexion = GoogleDrive.login(ENV["GMAIL_USERNAME"], ENV["GMAIL_PASSWORD"]) archivo = conexion.spreadsheet_by_title('Materia') if archivo.nil? archivo= conexion.create_spreadsheet('Materia') end numeroHojaTrabajo=0 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title while(!(hojaTrabajo.nil?)and((tituloHojaTrabajo<=>m)!=0)) do numeroHojaTrabajo=numeroHojaTrabajo+1 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] if !(hojaTrabajo.nil?) tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title end end auxiliar=numeroHojaTrabajo if hojaTrabajo.nil? puts 'no existe' archivo.add_worksheet(m,1,1) tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title hojaTrabajo=archivo.worksheets[numeroHojaTrabajo] controlador=0 else hojaTrabajo.delete archivo.add_worksheet(m,1,1) tituloHojaTrabajo=archivo.worksheets[archivo.worksheets.length-1].title hojaTrabajo=archivo.worksheets[archivo.worksheets.length-1] end puts hojaTrabajo.title contador=0 for i in (1.. ($listaValores.length/7)) last_row = 1 + hojaTrabajo.num_rows for j in (1 .. 7) hojaTrabajo[last_row, j] = $listaValores[contador] contador=contador+1 end end hojaTrabajo.save end def leerExcel (archivo) $listaValores=[] if ($extension!= ".xls") oo = Roo::Excel.new("#{Rails.root}/public/archivos/"+archivo) end if ($extension!=".xlsx") oo = Roo::Excel.new("#{Rails.root}/public/archivos/"+archivo) end oo.default_sheet = oo.sheets.first contador=0 valor='' for i in (1 .. oo.last_row) for j in (1 .. oo.last_column) $listaValores[contador]= oo.cell(i,j) puts $listaValores[contador] contador=contador+1 end end end def leerNotasDeMiMateria (materia) $listaAlumnos=[] conexion = GoogleDrive.login(ENV["GMAIL_USERNAME"], ENV["GMAIL_PASSWORD"]) archivo = conexion.spreadsheet_by_title('Materia') numeroHojaTrabajo=0 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title while(!(hojaTrabajo.nil?))do if (archivo.worksheets[numeroHojaTrabajo].title == materia) cantidadAlumno=0 for i in (2 .. hojaTrabajo.num_rows) $listaAlumnos[cantidadAlumno]=[hojaTrabajo[i, 1],hojaTrabajo[i, 2],hojaTrabajo[i, 3],hojaTrabajo[i, 4],hojaTrabajo[i, 5],hojaTrabajo[i, 6],hojaTrabajo[i, 7]] cantidadAlumno=cantidadAlumno+1 end break end numeroHojaTrabajo=numeroHojaTrabajo+1 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] end end def validarCedula(cedula) listaMaterias=[] conexion = GoogleDrive.login(ENV["GMAIL_USERNAME"], ENV["GMAIL_PASSWORD"]) archivo = conexion.spreadsheet_by_title('Materia') numeroHojaTrabajo=0 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title while(!(hojaTrabajo.nil?))do for i in (2 .. hojaTrabajo.num_rows) if(hojaTrabajo[i, 3]==cedula) return true end end numeroHojaTrabajo=numeroHojaTrabajo+1 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] end return false end def leerNotasCedula (cedula) $listaMaterias=[] conexion = GoogleDrive.login(ENV["GMAIL_USERNAME"], ENV["GMAIL_PASSWORD"]) archivo = conexion.spreadsheet_by_title('Materia') numeroHojaTrabajo=0 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] tituloHojaTrabajo=archivo.worksheets[numeroHojaTrabajo].title cantidadMateria=0 while(!(hojaTrabajo.nil?))do for i in (2 .. hojaTrabajo.num_rows) if(hojaTrabajo[i, 3]== cedula) $listaMaterias[cantidadMateria]=[archivo.worksheets[numeroHojaTrabajo].title,hojaTrabajo[i, 4],hojaTrabajo[i, 5],hojaTrabajo[i, 6],hojaTrabajo[i, 7]] cantidadMateria=cantidadMateria+1 break end end numeroHojaTrabajo=numeroHojaTrabajo+1 hojaTrabajo = archivo.worksheets[numeroHojaTrabajo] end end end
true
778055fc399e7914ca4a5f5f0bcf988e02ee2af2
Ruby
rvna/black_thursday
/lib/item_analyst.rb
UTF-8
532
3.21875
3
[]
no_license
require_relative '../lib/statistics' class ItemAnalyst attr_reader :all_items include Statistics def initialize(all_items) @all_items = all_items end def item_prices all_items.map do |item| item.unit_price end end def average_price_standard_deviation standard_deviation(item_prices).round(2) end def golden_items avg = mean(item_prices) std_dev = average_price_standard_deviation all_items.find_all do |item| item.unit_price > (avg + (std_dev * 2)) end end end
true
bb0181ca2fce6831a2107d52cab8ee76d30dadf0
Ruby
xldenis/ruby
/test/parser/success/expression/begin.rb
UTF-8
368
2.90625
3
[]
no_license
begin 1 end begin 1 ensure 2 end begin ensure end begin rescue rescue end begin else ensure end begin 1 ; ensure 2 end begin 1 ensure 2 end begin 1 rescue 2 end begin 1 else 2 end begin rescue def a ; end 2 end begin rescue 'A' => e end begin rescue :a => e end begin rescue 2, 4, 5 end begin rescue 2, 4, 5 => a end begin rescue ensure end
true
69e8353360b687234d25b0617b19e683cfcad819
Ruby
awagner85/tealeaf_book
/array.rb
UTF-8
58
3.234375
3
[]
no_license
x = [1,2,3] y = [] x.each do |i| y << i + 2 end p x p y
true
1b2a35f21715b16f005b7f55a87898fdaf0e2575
Ruby
emilyjspencer/ruby-practice1
/odd_numbers_below_100.rb
UTF-8
146
3.78125
4
[]
no_license
#Print only odd numbers under 100 to the console number = 0 while number < 100 do if number.odd? puts number end number += 1 end
true
8c95c9e92cbf59cf42b4ccbd92c51bf10657b699
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/a2145fda6a8843c08358cb3e27da16e0.rb
UTF-8
414
3.875
4
[]
no_license
class Bob def hey(message) silence(message) || shouting(message) || question(message) || "Whatever." end private def silence(message) return nil unless message.strip.empty? "Fine. Be that way!" end def shouting(message) return nil unless message.upcase == message "Woah, chill out!" end def question(message) return nil unless message.end_with?("?") "Sure." end end
true
e845b9f61d5df8438fa5f144107eed521703c0f8
Ruby
sjchakrav/ruby_interview_exercises
/reversestring.rb
UTF-8
151
3.34375
3
[]
no_license
s = "1234567890" rs = "" i = 1 while i <= s.length rs << s[i*(-1)] i+=1 end puts "The original string: '#{s}'" puts "The reversed string: '#{rs}'"
true
e1b4d5b377f77e37199e94948728326441a79354
Ruby
CodeCoreYVR/debugging-lab
/db/seeds.rb
UTF-8
444
2.625
3
[]
no_license
QUESTIONS_TO_CREATE = 250 def create_answer Answer.create(body: Faker::Pokemon.name) end QUESTIONS_TO_CREATE.times do Question.create title: Faker::StarWars.quote, body: Faker::Hipster.paragraph, view_count: rand(100) end Question.all.each do |question| rand(2..4).times do question.answers << create_answer end end puts Cowsay.say "Created #{QUESTIONS_TO_CREATE} questions"
true
42d958c7ee0b249dd12e0c4bb7008e644f7dd87d
Ruby
EricaJCasePhD/ride-share-two
/driver.rb
UTF-8
779
2.734375
3
[]
no_license
require 'pry' require 'csv' require_relative 'record_magic.rb' module Rideshare class Driver extend RecordMagic attr_reader :id, :vin, :name def initialize(args) @id= args[:driver_id] @vin = args[:vin] @name = args[:name] end private def proof_data raise ArgumentError.new("Warning: bad VIN: #{args[:vin]}; Driver #{args[:driver_id]} data not included ") if args[:vin].length != 17 raise ArgumentError.new("Warning: Bad driver ID: must be a number, but was reported as #{args[:driver_id]} data not included ") unless (args[:driver_id].is_a? Integer) && (args[:driver_id] > 0 ) raise ArgumentError.new("Warning: Driver name not reported") unless (args[:name].is_a? String) && (args.length > 0) end end end
true
d30dd98a0984f2ef69d90b77ff809250c64ed8a4
Ruby
ChristyTropila/SuperheroRuby
/app/models/superhero.rb
UTF-8
1,570
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Superhero < ActiveRecord::Base #macro that connects our ruby models to the db #a superhero belongs to a superpower and an organization belongs_to :superpower belongs_to :organization has_many :user_superheros has_many :users, through: :user_superheros #CRUD METHODS #return a hash of all heros with name id key value pairs def self.all_names Superhero.all.map do |hero| {hero.name => hero.id} # binding.pry end end #this method interpolates the name of supehero and its associated superpowers and organizations. #accounts for possiblity of superheros having yet to be assigned a superpower or organization def self.all_names_and_descrip results=Superhero.all.reload.map do |hero| if !hero.superpower && !hero.organization "~~NAME: #{hero.name} \n" elsif !hero.superpower "~~NAME: #{hero.name}\n~~ORGANIZATION: #{hero.organization.name}--#{hero.organization.description} \n" elsif !hero.organization "~~NAME: #{hero.name}\n~~SUPERPOWER: #{hero.superpower.name}--#{hero.superpower.description} \n" else "~~NAME: #{hero.name}\n~~SUPERPOWER: #{hero.superpower.name}--#{hero.superpower.description}\n~~ORGANIZATION: #{hero.organization.name}--#{hero.organization.description} \n" end end end end
true
8f1e85f82c0b07c1681e14f89f2bc8a75338bb5a
Ruby
davidcelis/snap
/lib/cinch/plugins/ping.rb
UTF-8
331
2.546875
3
[]
no_license
require 'cinch' module Cinch module Plugins class Ping include Cinch::Plugin match /ping/ # An easy check to see if the bot is responding to basic commands. # # <davidcelis> !ping # <snap> davidcelis: Pong! def execute(m) m.reply "Pong!", true end end end end
true
0cf8179114cf3251a90eed792cccb482ce6f7317
Ruby
Clem-svg/TheGossipProjectSinatra
/lib/gossip.rb
UTF-8
1,073
3.21875
3
[]
no_license
require 'csv' require 'sinatra' class Gossip attr_accessor :author, :content def initialize(author,content) @author = author @content = content end # Sauvegarde chaque gossip dans un fichier csv, n'écrase pas les lignes ayant déjà du contenu def save CSV.open("./db/gossip.csv", "ab") do |csv| csv << [@author, @content] end end def self.all all_gossips = [] CSV.read("./db/gossip.csv").each do |csv_line| gossip = Gossip.new(csv_line[0], csv_line[1]) all_gossips << gossip end return all_gossips end def self.find(id) all_gossips = self.all x = id.to_i x = x - 1 puts all_gossips[x].author puts all_gossips[x].content return all_gossips[x] end def self.update(id, new_author, new_content) all_gossips = self.all all_gossips[id + 1].author = new_author all_gossips[id + 1].content = new_content CSV.open("./db/gossip.csv", "w") do |csv| all_gossips.each do |gossip| csv << [gossip.author, gossip.content] end end end end
true
c979abc40c441aa323b0b73504bddaf850131f65
Ruby
dougjohnston/yearbook-planner
/test/unit/yearbook/yearbook_method_test.rb
UTF-8
1,034
2.796875
3
[]
no_license
require 'minitest_helper' class YearbookMethodTest < UnitTest # years test "returns a the yearbook years" do yearbook = FactoryGirl.build(:yearbook, :starting_year => 2013, :ending_year => 2014) assert_equal '2013-2014', yearbook.years end # title test "returns a nice title" do yearbook = FactoryGirl.build(:yearbook, :starting_year => 2013, :ending_year => 2014, :theme => "Survivors") assert_equal '2013-2014 &ndash; Survivors', yearbook.title end # current! test "makes a yearbook current" do one = FactoryGirl.create(:yearbook) two = FactoryGirl.create(:old_yearbook, :school => one.school) assert_same one.school, two.school two.current! refute one.reload.current? assert two.reload.current? end test "only affects current school" do one = FactoryGirl.create(:yearbook) two = FactoryGirl.create(:old_yearbook) refute_same one.school, two.school one.current! && two.current! assert one.reload.current? assert two.reload.current? end end
true
ab18ef66b011d894017e1f29c5c6a3c76371708a
Ruby
felkh/image_blur
/image_blur_3.rb
UTF-8
1,340
3.875
4
[]
no_license
class Image def initialize(array) @image = array end def output_image @image.each do |row| puts row.join end end def get_ones ones = [] @image.each_with_index do |img_array, img_array_index| img_array.each_with_index do |img_array_item, img_array_item_index| if img_array_item == 1 ones << [img_array_index, img_array_item_index] end end end ones end def blur(distance) ones = get_ones @image.each_with_index do |img_array, img_array_index| img_array.each_with_index do |img_array_item, img_array_item_index| ones.each do |x_row_num, y_col_num| if manhattan_distance(img_array_item_index, img_array_index, y_col_num, x_row_num) <= distance @image[img_array_index][img_array_item_index] = 1 end end end end end def manhattan_distance(x1, y1, x2, y2) horizontal_distance = (x2 - x1).abs vertical_distance = (y2 - y1).abs horizontal_distance + vertical_distance end end image = Image.new([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0] ]) image.blur(3) image.output_image
true
802d2e73a2b978e021cc1863500c002e759f6db0
Ruby
hooopo/direct_web_spider
/downloader/normal_downloader.rb
UTF-8
672
2.59375
3
[]
no_license
# encoding: utf-8 require 'open-uri' require 'timeout' module Spider class NormalDownloader < Downloader def initialize(items) @items = items end def run @items.each do |item| begin html = open(item.url).read rescue Timeout::Error, Errno::ECONNREFUSED logger.error("#{item.class} #{item.kind} #{item.url} HTTP Connection Error.") else item = Encoding.set_utf8_html(item, html) if !Utils.valid_html?(item.html) logger.error("#{item.class} #{item.kind} #{item.url} Bad HTML.") else yield(item) end end end end end end
true
d78f8f7653dfee7006299f09944e8e2a1518cd48
Ruby
mmthatch12/ruby-proj-1
/MathHelper.rb
UTF-8
157
3.34375
3
[]
no_license
module MathHelpers def double(num) num *2 end end class Savings include MathHelpers end my_savings = Savings.new my_savings.double(500)
true
6e9a796ed1ec25dfa8f8b68e01ad73fa81c747e1
Ruby
kamilkowalski/timetable-parsers
/lib/timetabler.rb
UTF-8
876
2.859375
3
[]
no_license
require 'nokogiri' require 'open-uri' class Timetabler def initialize(parser=nil) @lines = [] @routes = [] @stops = [] @times = [] @parser = parser if !@parser.nil? use_parser @parser end end def parsers Dir.entries(File.join(File.dirname(__FILE__), "parsers")).select{|f| !["..", "."].include?(f)} end def fetch(parser=nil) if @parser.nil? and parser.nil? raise "Parser not specified" elsif @parser.nil? and !parser.nil? use_parser parser end fetch_all end def use_parser(parser) if parsers.include? parser require File.join(File.dirname(__FILE__), "parsers", parser, "parser") subinitialize else raise "Unknown parser: " + parser.to_s end return self end end class Timetabler::Line < Hash end class Timetabler::Route < Hash end class Timetabler::Stop < Hash end class Timetabler::Time < Hash end
true
6ddba65b0f63d326937ba292aec391d758c33ed0
Ruby
icvlahovic/meal-choice-prework
/meal_choice.rb
UTF-8
54
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def meal_choice(diet = "meat") return "#{diet}" end
true
99282d725006cce2f3ea343bfd19cc94187bd550
Ruby
Auggum/Meta_Filter
/csv.rb
UTF-8
930
2.71875
3
[]
no_license
require 'csv' def output_update(r_desc, r_id) puts "UPDATE pp SET pp.meta_description = \"#{r_desc}\" WHERE pp.id = #{r_id};" end CSV.foreach('/home/augo/Documents/RubyTests/finalchange.csv') do |row| row_description = row[2] row_id = row[0] row_meta_description = row[1] if (!row_description.nil? && row_meta_description.nil?) row_description.gsub!('<p>', '') row_description.gsub!('</p>', '') row_description.gsub!('<strong>', '') row_description.gsub!('</strong>', '') row_description.gsub!('<br />', '') html_links = %w(1296 1297 1298 1299 1300 1346) if (!html_links.include? (row_id)) if (row_description.length >= 160) period = (0..160).find_all {|i| row_description[i, 1] == '.'} output_update(row_description[0..period.last], row_id) unless period.empty? else output_update(row_description[0..160], row_id) end end end end
true
01b3181c1fc20f81bf4d141b561a45a1c425671f
Ruby
brianw921/W2D2
/BrianRamChess/Board.rb
UTF-8
2,221
3.734375
4
[]
no_license
require_relative "null_piece" require_relative "Piece" require_relative "RBQ" require "byebug" class NoPieceError < StandardError def m2 puts "ther's no piece in this position" end end class CannotMoveError < StandardError def m1 puts "you can't move the piece or the piece can't make that move" end end class Board attr_reader :rows def initialize # debugger @rows = Array.new(8) {Array.new(8)} # @sentinel = NullPiece.new self.populate end def populate # we currently didnot assign what piece we only set up the piece and the board # debugger (0...8).each do |i| @rows[0][i] = Piece.new(self,:white,[0,i]) @rows[1][i] = Piece.new(self,:white,[1,i]) @rows[6][i] = Piece.new(self,:black,[6,i]) @rows[7][i] = Piece.new(self,:black,[7,i]) end (2..5).each do |i| (0..7).each do |j| @rows[i][j] = NullPiece.instance end end end def [](pos) row, col = pos @rows[row][col] end def []=(pos,val) row, col = pos @rows[row][col] = val end def move_piece(start_pos,end_pos) # we have to use self[pos] here because we have already defined a method to put instances in the rows at given position if valid_pos?(start_pos) #issue = THIS teleports the piece, doesn't define what move they can make #debugger self[start_pos], self[end_pos] = self[end_pos], self[start_pos] #pry(main)> b.move_piece([0,0],[4,4])=> [null_piece, piece] end end def valid_pos?(pos) x , y = pos #debugger if self[pos].is_a?(NullPiece) return false # puts "try again" # raise NoPieceError end if !(x >= 0 && x < 8 && y < 8 && y >=0) # check whether or not the position is out of the chess board. # raise CannotMoveError return false # puts "cannot move" end true end def add_piece(piece,pos) end def checkmate?(color) #if king color have no possible moves. Checkmate to that color, declare other color winner end def in_check?(color) end def find_king(color) end def pieces end def dup end def move_piece!(color,start_pos,end_pos) end private attr_accessor :sentinel end
true
1b6db66d3390ff47f672b3f063a828fbb4dc97c3
Ruby
OwenKLenz/ruby_small_problems
/medium_2/unlucky_days.rb
UTF-8
1,737
4.375
4
[]
no_license
# Write a method that returns the number of Friday the 13ths in the year given by an argument. You may assume that the year is greater than 1752 (when the United Kingdom adopted the modern Gregorian Calendar) and that it will remain in use for the foreseeable future. # Examples: # Input: an integer (the year) # Ouput: an integer (number of Friday the 13ths) # Considerations: # none # Data structures: # An array of months? Range? # Algorithm: # count the number of months (1-12) for which the 13th is a friday # Count (convert month range to an array) with a block # Block: # create a new date object on the argument year, current iteration month and day of 13 # check if that date is a friday require 'date' def friday_13th(year) (1..12).to_a.count { |month| Date.new(year, month, 13).friday? } end # # Brute force: # def friday_13th(year) # date = Date.new(year) # days_in_year = date.leap? ? 366 : 365 # counter = 0 # days_in_year.times do # counter += 1 if date.friday? && date.day == 13 # date += 1 # end # counter # end p friday_13th(2015) == 3 p friday_13th(1986) == 1 p friday_13th(2019) == 2 def most_friday_13ths date = Date.new lookup_table = {} until date.year == Date.today.year do lookup_table[date.year] = friday_13th(date.year) date += 365 end lookup_table end # Further Exploration: def five_friday_count(year) five_friday_months = 0 date = Date.new(year) (1..12).each do |current_month| fridays = 0 until date.month != current_month date += 1 fridays += 1 if date.friday? end five_friday_months += 1 if fridays == 5 end five_friday_months end p five_friday_count(2019) == 4 p five_friday_count(2004) == 5
true
f9af824ca113d1e8032e0e333541f03b844701f6
Ruby
jenlindner/Seurrat
/image.rb
UTF-8
3,115
3.96875
4
[]
no_license
#i would love to be able to synch this between javascript and ruby over a socket connection. #chow about ruby has the read data ready, does it execute a callback to the js function to write? #does the write function have a pre-hook saying check this flag to call read function's data? #i could use node callbacks to coordinate the read-write flow, #but do i have to then do it all in javascript? #maybe it's a ruby service? exposing the read data? require 'RMagick' include Magick class ImageReader attr_accessor :current_rgb, :intense_pixel def get_color_of_most_intense_pixel(image,x,y,height,width) current_rgb = 765 intense_pixel = "" pixels = image.get_pixels(x,y,height,width) pixels.each do |p| #no. i want color of darkest pixel, which would be lowest values of rgb, each. but for now let's just #add them and use lowest. rgb = p.red + p.green + p.blue if (rgb < current_rgb) # current_intensity = p.intensity # puts "current intensity = #{current_intensity}" intense_pixel = p end end # puts "rgb(#{intense_pixel.red},#{intense_pixel.green},#{intense_pixel.blue})" # puts "r#{intense_pixel.red} g#{intense_pixel.green} b#{intense_pixel.blue}" #want to return a string with rgb "rgb(#{intense_pixel.red},#{intense_pixel.green},#{intense_pixel.blue})" end def foo "foo" end #so a row is ten pixels high. so i want to call this get_most every ten pixels for 300. need to be able to pass #in the x value def read_row(image, y_value) colors_of_row = [] row = 300 marker = 0 while marker < row if marker % 10 == 0 #at this point, i'd want to call a method with the color value this method returns #to use it to write pixel color somewhere else # puts get_color_of_most_intense_pixel(image,200,100,10,10) #ah - you need to increment your y value, to move along the row. # puts "marker = #{marker}" colors_of_row << get_color_of_most_intense_pixel(image,marker,y_value,10,10) #think i want to store this in an array. and then pass the array. #jump ahead to next square 10 pixels to the right marker += 9 end marker+=1 end # puts "marker = #{marker}" # puts "colors of row is: #{colors_of_row}" colors_of_row end def read_number_of_rows(number, image) #so lets say i want to read 20 rows, 10 pixels high counter = 0 set_of_rows = [] while counter < number y_value = counter * 10 puts "y_value is #{y_value}" set_of_rows << read_row(image,y_value) counter += 1 end puts set_of_rows[0][7] set_of_rows end end image = ImageList.new('public/images/distance.jpg') i = ImageReader.new # i.read_row(image,0) i.read_number_of_rows(20, image) # i.read_number_of_rows(10,image) #what i want to do first is get the rgb of a given pixel, then figure out #the dominant/darkest pixel of a given 10*10 square, then expose that somehow #so that i can use javascript to get it and color second image with.
true
6b809da5c0f1ee367425eb267299762a95e09a78
Ruby
scfcode/My-Scripts
/flickr_download.rb
UTF-8
4,792
2.5625
3
[]
no_license
#!/usr/bin/ruby # # == Synopsis # # flickr_download: batch downloader for photos stored on Flickr # # == Usage # # flickr_download -u NAME -i ID [OPTION] ... # # flickr_download -u NAME -t TITLE [OPTION] ... # # -h, --help # this usage message # # -i, --photoset-id # target photoset id # # -t, --photoset-title # target photoset title # # -u, --username # photos owner username (required argument) # # -c, --stdout # do not download photos, only dump their static URLs on stdout # Copyright (C) 2006 Stefano Zacchiroli # # This program is free software, you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # Created: Mon, 25 Sep 2006 17:30:44 +0200 zack # Last-Modified: Mon, 25 Sep 2006 17:44:40 +0200 zack require 'net/http' require 'optparse' require 'rdoc/usage' require 'uri' $LOAD_PATH << File.join(ENV['HOME'], 'lib/ruby') require 'flickr' # mixin for checking and possibly obtaining an authentication token from flickr module Authorizer DEFAULT_TOKEN_CACHE_FILE = File.join(ENV['HOME'], '.flickr_auth') API_KEY = 'bd58d18427f40e82d7b2f0dbf6f2dc7a' SHARED_SECRET = 'b87f58d931a16d4f' # check if a auth token is present, if not generate a frob and interactively # wait for the user to authorize the current application. As a side-effect # set the instance variable @flickr to a new Flickr instance def get_auth_token(cache_file = DEFAULT_TOKEN_CACHE_FILE) @flickr = Flickr.new(cache_file, API_KEY, SHARED_SECRET) unless @flickr unless @flickr.auth.token @flickr.auth.getFrob url = @flickr.auth.login_link puts "You must visit #{url} to authorize flickr_download.\n" + "Press enter when you have done so. " + "This is the only time you will have to do this." gets @flickr.auth.getToken @flickr.auth.cache_token end end end class Downloader include Authorizer def initialize(username, pred, download=true) @username = username # name of the photoset owner @set_predicate = pred # photoset predicate @download = download # should we download? (or only print urls ...) get_auth_token end def go user = @flickr.people.findByUsername @username set = (@flickr.photosets.getList user).find &@set_predicate fail "can't find a matching set" unless set if @download threads = [] each_url(set) {|url| threads << Thread.new(url) {|url_text| url = URI.parse(url_text) puts "starting download of #{url_text} ..." res = Net::HTTP.get_response url File.open(File.basename(url.path), "w") {|f| f << res.body } } } puts 'waiting for all downloads to complete ...' threads.each {|thread| thread.join } puts 'all done.' else each_url(set) {|url| puts url} end end private def each_url(set) @flickr.photosets.getInfo set puts "will download #{set.photos.length}" \ + " photo#{set.photos.length > 1 ? 's' : ''}(s)" if @download set.photos.each {|photo| @flickr.photos.getInfo photo best_size = find_best_size photo.sizes yield best_size.source } end def find_best_size(sizes) sorted_best_first = sizes.sort_by {|tag, _| case tag when :Original; 1 when :Large; 2 when :Medium; 3 when :Small; 4 when :Square; 5 when :Thumbnail; 6 end } # first element returned is now a pair: <best size tag, best size> sorted_best_first[0][1] end end def parse_cmdline options = { :photoset_id => nil, :photoset_title => nil, :download => true, :username => nil, } cmdline = GetoptLong.new( ['--help', '-h', GetoptLong::NO_ARGUMENT], ['--photoset-id', '-i', GetoptLong::REQUIRED_ARGUMENT], ['--photoset-title', '-t', GetoptLong::REQUIRED_ARGUMENT], ['--username', '-u', GetoptLong::REQUIRED_ARGUMENT], ['--stdout', '-c', GetoptLong::NO_ARGUMENT] ) cmdline.each do |opt, arg| case opt when '--help' ; RDoc::usage when '--photoset-id' ; options[:photoset_id] = arg when '--photoset-title' ; options[:photoset_title] = arg when '--stdout' ; options[:download] = false when '--username' ; options[:username] = arg end end RDoc::usage unless options[:username] RDoc::usage unless options[:photoset_id] or options[:photoset_title] RDoc::usage if options[:photoset_id] and options[:photoset_title] options end options = parse_cmdline if options.has_key? :photoset_id pred = lambda {|set| set.id == options[:photoset_id]} elsif options.has_key? :photoset_title pred = lambda {|set| set.title == options[:photoset_title]} end (Downloader.new(options[:username], pred, options[:download])).go
true
dc9409ead39b9982d4fbe216a7096a38b01a2763
Ruby
PhilippaElliott/lesson_4
/loops20.rb
UTF-8
83
3
3
[]
no_license
def greeting while number_of_greetings puts 'Hello!' end number_of_greetings = 2
true
37859c045ef1ba64aa4635ff7d412404dc4b6ddb
Ruby
geluso/roguebike
/lib/actors/player.rb
UTF-8
2,358
2.9375
3
[]
no_license
class Player < Actor attr_accessor :xx, :yy, :facing, :speed attr_accessor :hp, :fuel, :fuel_capacity attr_accessor :sensor_range attr_accessor :inventory def initialize(xx: 0, yy: 0) @xx = xx @yy = yy @facing = :EAST @speed = 1 @hits = 0 @hp = 10 @fuel = DEFAULT_FUEL_CAPACITY @fuel_capacity = DEFAULT_FUEL_CAPACITY @sensor_range = DEFAULT_SENSOR_RANGE @inventory = Inventory.new end def symbol Geo.symbol(@facing) end def color Ncurses.COLOR_PAIR(2) end def slow_down @speed -= 1 if @speed < 0 @speed = 0 end end def speed_up @speed += 1 if @speed > 10 @speed = 10 end end def collide(obstacle) @hits += 1 end def damage @hp - @hits end def fire transform = Transform.new(xx: @xx, yy: @yy, facing: @facing) Projectile.new(transform) end def fire_mega t1 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_left(@facing) ) t2 = Transform.new( xx: @xx, yy: @yy, facing: @facing ) t3 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(@facing) ) p1 = Projectile.new(t1) p2 = Projectile.new(t2) p3 = Projectile.new(t3) [p1, p2, p3] end def fire_ultra t1 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(@facing) ) t2 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(Geo.turn_right(@facing)) ) t3 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(Geo.turn_right(Geo.turn_right(@facing))) ) t4 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(@facing)))) ) t5 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(@facing))))) ) t6 = Transform.new( xx: @xx, yy: @yy, facing: Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(Geo.turn_right(@facing)))))) ) p1 = Projectile.new(t1) p2 = Projectile.new(t2) p3 = Projectile.new(t3) p4 = Projectile.new(t4) p5 = Projectile.new(t5) p6 = Projectile.new(t6) [p1, p2, p3, p4, p5, p6] end def to_s "#{self.symbol} #{@xx} #{@yy}" end end
true
946ab026b54e9810471e9f580488198b0c14785a
Ruby
myronmarston/reports_as_sparkline
/lib/simplabs/reports_as_sparkline/reporting_period.rb
UTF-8
2,902
2.671875
3
[ "MIT" ]
permissive
module Simplabs #:nodoc: module ReportsAsSparkline #:nodoc: class ReportingPeriod #:nodoc: attr_reader :date_time, :grouping def initialize(grouping, date_time = nil) @grouping = grouping @date_time = parse_date_time(date_time || DateTime.now) end def self.first(grouping, limit, end_date = nil) self.new(grouping, end_date).offset(-limit) end def self.from_db_string(grouping, db_string) parts = grouping.date_parts_from_db_string(db_string) result = case grouping.identifier when :hour self.new(grouping, DateTime.new(parts[0], parts[1], parts[2], parts[3], 0, 0)) when :day self.new(grouping, Date.new(parts[0], parts[1], parts[2])) when :week self.new(grouping, Date.commercial(parts[0], parts[1], 1)) when :month self.new(grouping, Date.new(parts[0], parts[1], 1)) end result end def next self.offset(1) end def previous self.offset(-1) end def offset(offset) self.class.new(@grouping, @date_time + offset.send(@grouping.identifier)) end def ==(other) if other.class == Simplabs::ReportsAsSparkline::ReportingPeriod return @date_time.to_s == other.date_time.to_s && @grouping.identifier.to_s == other.grouping.identifier.to_s end false end def <(other) if other.class == Simplabs::ReportsAsSparkline::ReportingPeriod return @date_time < other.date_time end raise ArgumentError.new("Can only compare instances of #{Simplabs::ReportsAsSparkline::ReportingPeriod.klass}") end def last_date_time case @grouping.identifier when :hour DateTime.new(@date_time.year, @date_time.month, @date_time.day, @date_time.hour, 59, 59) when :day DateTime.new(@date_time.year, @date_time.month, @date_time.day, 23, 59, 59) when :week date_time = (@date_time - @date_time.wday.days) + 7.days Date.new(date_time.year, date_time.month, date_time.day) when :month Date.new(@date_time.year, @date_time.month, (Date.new(@date_time.year, 12, 31) << (12 - @date_time.month)).day) end end private def parse_date_time(date_time) case @grouping.identifier when :hour DateTime.new(date_time.year, date_time.month, date_time.day, date_time.hour) when :day date_time.to_date when :week date_time = (date_time - date_time.wday.days) + 1.day Date.new(date_time.year, date_time.month, date_time.day) when :month Date.new(date_time.year, date_time.month, 1) end end end end end
true
854e379d3e28d394f08f82e640d5e635d0e6218b
Ruby
tehut/BankAccounts
/lib/savingsaccount.rb
UTF-8
582
3.25
3
[]
no_license
require_relative 'account.rb' module Bank class SavingsAccount < Account def initialize(id = "", balance = 10, date_opened = "" ) super(id, balance, date_opened) raise ArgumentError.new("balance must be >= 10") if balance < 10 end def withdraw(amount) total_withdrawl = amount + 2 super(total_withdrawl, 10) #end return @balance end def add_interest(rate) if rate > 0 then @balance = balance * (1 + (rate/100)) else puts "Rate must be greater than 0" end return @balance end end end
true
f708b3a435d6d421c8dca774aa58b109916d2f5e
Ruby
Ad00M87/fink
/db/seeds.rb
UTF-8
834
2.78125
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) names = ['2','3','4','5','6','7','8','9','10','Jack','Queen','King','Ace'] suits = ['Clubs','Spades','Hearts','Diamonds'] names.each_with_index do |value, i| image = suits.each do |suit| if suit === 'Clubs' || suit === 'Spades' color = 'Black' else color = 'Red' end Card.create( name: value, value: i + 2, suit: suit, color: color, image: "#{value.downcase}_of_#{suit.downcase}.png" ) end end
true
3df3538ea5ff383fdfe8b932ffb3834f699582ec
Ruby
emikojima/oxford-comma-v-000
/lib/oxford_comma.rb
UTF-8
188
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) new_array = [] if array.count <= 2 array.join(" and ") else new_array << array.pop return "#{array.join(", ")}, and #{new_array.join}" end end
true
751d6944bb5241b6b649fe5d6274ca6b6e488e55
Ruby
njpa/launchschool-course-100
/09_exercises/ex_17.rb
UTF-8
1,003
4.5
4
[]
no_license
# EXERCISE 17 # =========== # What will the following program output? hash1 = {shoes: "nike", "hat" => "adidas", :hoodie => true} hash2 = {"hat" => "adidas", :shoes => "nike", hoodie: true} if hash1 == hash2 puts "These hashes are the same!" else puts "These hashes are not the same!" end # Since... # (1) the data types of the keys of both hashes match; # (2) the symbols and strings used as keys in both hashes match; and # (3) the values # assiged to each key match in both hashes, # the expression `hash1 == hash2` will evaluate to `true`. # The program will therefore output "These hashes are the same!". # SIDENOTE: # When evaluating the equality of two hashes, Ruby will not make a distinction # in the syntax (i.e. old notation vs. new notation) that is used. In fact, # inputting `{foo: "bar"}` in `irb` will evaluate to `{:foo => "bar"}`. # It is worth noting that the above statement will only hold true so long # as the data types used as keys are equal in both hashes.
true
b79bf1380d81177476b1058097986e12fd907bb6
Ruby
sheena-gygax/DemoDayApp
/CA_examples/shopping_cart.rb
UTF-8
895
3.625
4
[]
no_license
class Item def initialize(name, price) @name = name @price = price end def name @name end def price @price end def name=(product) @name = product end def price=(price) @price = product end end class Cart def initialize @cart = [] end def add(item, quantity) item_hash = Hash.new item_hash[:item] = item item_hash[:quantity] = quantity @cart << item_hash end def total total = 0 @cart.each do |item_hash| item = item_hash[:item] price = item.price quantity = item_hash[:quantity] total = total + price * quantity end return total end end ipad = Item.new("iPad 2", 499) imac = Item.new("iMac 27", 1699) macbook = Item.new("MacBook Air 13", 1299) cart = Cart.new cart.add(ipad, 2) cart.add(imac, 1) cart.add(macbook, 1) puts cart.total
true
3972823a08b34f5feaad22644a386bc9dd90c4fa
Ruby
Cloudxtreme/logtrend
/lib/logtrend.rb
UTF-8
5,238
2.890625
3
[]
no_license
require 'rubygems' require 'eventmachine' require 'eventmachine-tail' require 'rrd' require 'logger' require 'erb' # A Ruby module that uses RRD (http://www.mrtg.org/rrdtool/) to generate graphs for trending data from log files. # # logtrend tails a log file and matches lines one by one, sending matched counters to RRD as appropriate. module LogTrend class Base # This sets the directory where graphs should be stored. attr_accessor :graphs_dir # This sets the directory where your RRD files will rest. attr_accessor :rrd_dir # This sets the logger to use. Must be something that behaves like a Logger object. attr_accessor :logger # This sets the HTML file template for the generated index.html file. # The String here will pass through ERB, with self being set as the binding. # # The default generates a simple HTML file that loads one IMG tag per graph. attr_accessor :template # Defines the amount of time between each updates, given in seconds. Default value is 60 seconds. # # From the rrdcreate(2) manual page: # # Specifies the base interval in seconds with which data will be fed into the RRD. # # # @see http://www.mrtg.org/rrdtool/doc/rrdcreate.en.html attr_accessor :step # Defines the amount of time between updates that will mark a value unknown. # # From the rrdcreate(2) manual page: # # heartbeat defines the maximum number of seconds that may pass between two updates of this data source before the value of the data source is assumed to be *UNKNOWN*. # # @see http://www.mrtg.org/rrdtool/doc/rrdcreate.en.html attr_accessor :heartbeat def initialize(options={}) set_defaults options.each do |key, val| send("#{key}=", val) end end def add_trend(name, &block) raise ArgumentError, "D'oh! No block." unless block_given? @trends[name] = block end def add_graph(name, &block) raise ArgumentError, "D'oh! No block." unless block_given? graph = Graph.new(name) yield graph @graphs << graph end # # This is the preferred entry point. def self.run(logfile, options={}, &block) throw "D'oh! No block." unless block_given? l = Base.new(options) yield l l.run logfile end def run(logfile) counters = reset_counters EventMachine.run do EventMachine::add_periodic_timer(step) do @logger.debug "#{Time.now} #{counters.inspect}" counters.each {|name, value| update_rrd(name, value)} @graphs.each {|graph| build_graph(graph)} build_page counters = reset_counters end EventMachine::file_tail(logfile) do |filetail, line| @trends.each do |name, block| counters[name] += 1 if block.call(line) end @logger.debug counters.inspect end end end private def reset_counters counters = {} @trends.keys.each do |k| counters[k] = 0 end counters end def update_rrd(name, value) file_name = File.join(@rrd_dir,"#{name}.rrd") rrd = RRD::Base.new(file_name) if !File.file?(file_name) rrd.create :start => Time.now - 10.seconds, :step => step do datasource "#{name}_count", :type => :gauge, :heartbeat => heartbeat, :min => 0, :max => :unlimited archive :average, :every => 5.minutes, :during => 1.year end end rrd.update Time.now, value end def build_graph(graph) rrd_dir = @rrd_dir RRD.graph File.join(@graphs_dir,"#{graph.name}.png"), :title => graph.name, :width => 800, :height => 250, :color => ["FONT#000000", "BACK#FFFFFF"] do graph.points.each do |point| if point.style == :line line File.join(rrd_dir,"#{point.name}.rrd"), "#{point.name}_count" => :average, :color => point.color, :label => point.name.to_s elsif point.style == :area area File.join(rrd_dir,"#{point.name}.rrd"), "#{point.name}_count" => :average, :color => point.color, :label => point.name.to_s end end end end def build_page file_name = File.join(@graphs_dir,'index.html') File.open(file_name, "w") do |f| f << @template.result(binding) end end def set_defaults @graphs_dir = '.' @rrd_dir = '.' @trends = {} @graphs = [] @logger = Logger.new(STDERR) @logger.level = ($DEBUG and Logger::DEBUG or Logger::WARN) @step = 1.minute @heartbeat = 5.minutes @template = ERB.new <<-EOF <html> <head> <title>logtrend</title> </head> <body> <% @graphs.each do |graph| %> <img src='<%=graph.name%>.png' /> <% end %> </body> </html> EOF end private :set_defaults end class Graph attr_reader :points attr_reader :name def initialize(name) @name = name @points = [] end def add_point(style,name,color) @points << GraphPoint.new(style, name, color) end end GraphPoint = Struct.new(:style, :name, :color) end
true
cc2e45241516badb0b97f02292ef1e166bd2844f
Ruby
chrisjohncarter123/oxford-comma-onl01-seng-pt-021020
/lib/oxford_comma.rb
UTF-8
442
3.46875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) if(array.length == 2) return "#{array[0]} and #{array[1]}" end result = "" array.each_with_index do |word, index| remaining = array.length - index if(index == 0 && remaining == 1) result = word elsif(index > 0 && remaining > 1) result += ", #{word}" elsif(remaining == 1) result += ", and #{word}" else result += "#{word}" end end result end
true
1cf491ddacb272059150538c18574a5cb9e0f02f
Ruby
kgardnr/tealeaf
/Tealeaf_Intro/9_MoreStuff/1.rb
UTF-8
223
2.65625
3
[]
no_license
def lab_exists?(string) if /lab/.match(string) p string else p "No match" end end lab_exists?("laboratory") lab_exists?("experiment") lab_exists?("Pans Labrynth") lab_exists?("elaborate") lab_exists?("polar bear")
true
810cc59fe8264901acf2dddc2079f5bae2f6ed15
Ruby
kevin-a-nelson/dwarf_fortress_raw_sparcer
/test.rb
UTF-8
823
2.921875
3
[]
no_license
require_relative 'DFRawParcerUtil' class DFRawParser < DFRawParcerUtil attr_reader :json, :file_length, :file, :file_lines def initialize(file_name) @file = File.read(file_name) @file_lines = @file.split("\n") @file_length = @file_lines.length @json = init_json end def init_json(line_num = 0) line = @file_lines[line_num] return init_json(line_num + 1) if empty_line?(line) return init_json(line_num + 1) unless attribute?(line) parsed_line = parse_line(line) key = parsed_line[:key].to_sym value = parsed_line[:value].to_sym return { "#{key}": value.to_s } if line_num == @file_length - 1 json = {} json[key] = { "#{value}": init_json(line_num + 1) } json end end body_default = DFRawParser.new('raw/objects/body_default.txt') p body_default.json
true
c293bfa186d5b37ec4be1347c84ce877c135c2ab
Ruby
norbert/movieapp
/app/models/poster_finder.rb
UTF-8
755
2.78125
3
[]
no_license
module PosterFinder def self.medium_width() 185 end def self.small_width() 92 end def self.call movie tmdb_config = Tmdb.configuration tmdb_images = Tmdb.poster_images movie.tmdb_id # sort by language ("en" and nil first) then average rating tmdb_images.sort! { |a, b| if a.language == b.language a.average_rating <=> b.average_rating else a.language == 'en' || (a.language.nil? && b.language != 'en') ? 1 : -1 end } tmdb_images.reverse! tmdb_images.map do |image| Poster.new \ tmdb_config.poster_url(medium_width * 2, image.file_path), tmdb_config.poster_url(small_width * 2, image.file_path) end end Poster = Struct.new(:medium_url, :small_url) end
true
24a27c93f5a2ecc5127445a6610eb6bae39740e2
Ruby
David-Kirsch/MovieApp
/app/models/Model1.rb
UTF-8
1,923
3.140625
3
[]
no_license
#class for Model1 goes here #Feel free to change the name of the class class MovieGoer @@all = [] attr_accessor :name, :selected_movie attr_reader :mgr, :producer def initialize(name, mgr = false, producer = false) @name = name @mgr = mgr @producer = producer save end def save @@all << self end def self.all @@all end def movies_at_theater(theater) theater.now_playing.map do |movie| movie.name.upcase end.sort end def all_movies Theater.all.map do |movie| movie.now_playing.map do |movie_name| movie_name.name.upcase end end.flatten.uniq.sort end def see_a_movie(title, theater) if(movies_at_theater(theater).include?(title.upcase)) @selected_movie = Movie.all.select do |movie| movie.name.upcase == title.upcase end theater.buy_movie_ticket(self, @selected_movie[0]) else puts "Sorry, #{title.upcase} is not playing at #{theater.name}." end end def view_ticket_stubs all_movies = Theater.all.map do |location| location.tickets_sold.select do |sold| sold[:person] == self end end.flatten puts "Ticket Stub" puts "_____________________________________________".blue.bold puts " " list = all_movies.map do |stub| ticket_info = "PURCHASE DATE: #{stub[:time]}," ticket_info += " CUSTOMER: #{stub[:person].name }," ticket_info += " PRICE: #{stub[:cost].to_s}," ticket_info += " MOVIE: #{stub[:movie].name }," ticket_info += " THEATER: #{stub[:theater]}" end.sort {|a,b| b<=>a} puts list puts "______________________________________________".blue.bold end end
true
6fd15e71043d1561c1f366ecfc9cbb9c4e20292f
Ruby
martincalvert/html_toc
/lib/htmlfile.rb
UTF-8
1,438
3.34375
3
[]
no_license
#HtmlFile class takes a name of a file, checks to see if it .htm or .html extesion then performs actions on the file before closing it and returning true for success or false for a error #Martin Calvert (sdla) #martin@martin-calvert.com #Martin-Calvert class HtmlFile attr_accessor :file_name,:line_number @comment_lines={} @lines=[] def self.extensions return [".htm",".html"] end def initialize(htmlfile_name) @lines=[] @comment_lines={} if HtmlFile.extensions.include?(File.extname(htmlfile_name)) @file_name=htmlfile_name handle_file else return false end end def handle_file line_number=0 update_file=false file=File.open(@file_name,'r+') temp=File.open('temp.txt','w') file.each do |line| if line.include?('<!-- Table Of Contents') update_file=true elsif line.include?('-->')&&update_file update_file=false elsif !update_file temp.puts line end end temp.close temp=File.open('temp.txt','r+') temp.each do |line| line_number+=1 if line.include?('<!--'&&'-->') comment_line=line.delete('<!--'&&'-->') comment_line.delete!('!') comment_line.strip @comment_lines.merge!(line_number=>comment_line) end @lines << line end file.rewind file.puts '<!-- Table Of Contents' @comment_lines.each do |k,v| file.puts "Line - #{k+@comment_lines.size+2} #{v}" end file.puts '-->' @lines.each do |val| file.puts val end file.close end end
true
f7205031b2d2ce18e54bc661ee5219a85cae67d0
Ruby
ciprianna/Ruby
/CP_Book_Practice.rb
UTF-8
16,237
4.625
5
[]
no_license
#Ruby Practice #puts = print puts 1.0 + 2.0 puts 2.0 * 3.0 puts 5.0 - 8.0 puts 9.0 / 2.0 puts 5 * (12-8) + -15 puts 98 + (59872 / (13 * 8)) * -51 #Hours in a year puts 365 * 24 #Number of seconds in a decade puts ((60 * 24) * 365) * 10 #My age puts (((60.0*60.0)*24.0) * 365.0) * 26.5 #Author's age (given in seconds to begin with) puts 1025000000 / (60 * 60 * 24 * 365) #Difference in age now vs age at time the book was written puts 32 - (800000000 / (60 * 60 *24 * 365)) #Author's age at the time the book was written puts 32 - 7 #Print strings puts 'Hello World!' puts " " #Empty strings puts 'Good-bye.' puts 'I like ' + 'apple pie.' #Don't forget the space so the words don't directly join #prints blink 4 times puts 'blink ' * 4 # \ escapes the apostrophe so it prints it as part of the string puts 'You\'re swell!' # \ also escapes itself puts 'backslash at the end of a string: \\' puts 'up\\down' puts 'up\down' #Variables must start with a lower case letter in Ruby my_string = '...you can say that again...' puts my_string puts my_string name = 'Anya Christina Emmanuella Jenkins Harris' puts 'My name is ' + name + '.' puts "Wow! " + name puts "is a really long name!" #Can reassign variables if they've been used, but replaces value composer = 'Mozart' puts composer + ' was "da bomb" in his day.' composer = 'Beethoven' puts 'But I prefer ' + composer + ', personally.' #Variables can also be numbers/equations with stored results my_own_var = 'Just another ' + 'string.' puts my_own_var my_own_var = 5 * (1 + 2) puts my_own_var #Variables cannot point to other variables #Converting object types var1 = 2 var2 = '5' # .to_s converts the number to a string puts var1.to_s + var2 #Output is '25' # .to_i converts the string to an integer puts var1 + var2.to_i #Output is 7 # .to_f converts the object to a float puts '15'.to_f #Output is 15.0 puts '99.999'.to_f #Output remains the same puts '99.999'.to_i #Output is 99 puts '5 is my favorite number!'.to_i #Output is 5 puts 'Who asked you about 5 or whatever?'.to_i #Output is 0 because it begins with a letter puts 'Your momma did.'.to_f #Output is 0.00 puts 'stringy'.to_s #Output is 'stringy' puts 3.to_i #Output is 3 #Interactive Programs puts 'Hello there, and what\'s your name?' #gets retrieves a string that the user types in. Get String. name = gets.chomp #the .chomp cuts off the "Enter" after the user types in a string puts 'Your name is ' + name + '? What a lovely name!' puts 'Pleased to meet you, ' + name + '. :)' #Practice puts 'What is your first name?' firstname = gets.chomp puts 'What is your middle name?' middlename = gets.chomp puts 'What is your last name?' lastname = gets.chomp puts 'Hello, ' + firstname + ' ' + middlename + ' ' + lastname + '!' puts 'What is your favorite number?' favnum = gets.chomp.to_i #Add the chomp and the .to_i at the end of the variable so it's stored there. newnum = favnum + 1 #Must add the .to_s at the end here because it is "putting a string (puts)" # and the variables are integers above puts 'Well, ' + favnum.to_s + ' is your favorite number, but ' + newnum.to_s + ' is a bigger and better favorite number.' #String play varrev = 'stop' puts varrev.reverse #Reverses the string, output would be pots puts varrev.length.to_s #Gets the length of characters and must make it a string when used in puts puts varrev.upcase #Makes the string upper case puts varrev.downcase #Makes the string lower case puts varrev.swapcase #Swaps the given case of the string puts varrev.capitalize #Capitalizes only the first character #Practice wholename = firstname + ' ' + middlename + ' ' + lastname #With spaces included as characters wholenamechar = firstname + middlename + lastname #No spaces puts 'Your whole name is ' + wholenamechar.length.to_s + ' letters long!' #Visual formatting line_width = 50 puts ('Old Mother Hubbard'.center(line_width)) puts ('Sat in her cupboard'.center(line_width)) puts ('Eating her curds and whey,'.center(line_width)) puts ('When along came a spider'.center(line_width)) puts ('Who sat down beside her'.center(line_width)) puts ('And scared her poor shoe dog away.'.center(line_width)) #Centers the string along the previously defined line_width str = '-->text<--' puts (str.ljust(line_width)) #Left justified puts (str.center(line_width)) #Centered puts (str.rjust(line_width)) #Right justified puts (str.ljust(line_width / 2) + str.rjust(line_width / 2)) #Divides the total line_width and #puts one on each side, left and right justified #Practice puts 'What do you WANT?' employee = gets.chomp puts 'WHADDYA MEAN "' + employee.upcase + '"?!? YOU\'RE FIRED!!' #Table of contents puts ('Table of Contents'.center(50)) puts ('Chapter 1: Getting Started'.ljust(30) + 'Page 1'.rjust(20)) puts ('Chapter 2: Numbers'.ljust(30) + 'Page 9'.rjust(20)) puts ('Chapter 3: Letters'.ljust(30) + 'Page 13'.rjust(20)) #Comparisons puts 1 > 2 #Returns false puts 1 < 2 #Returns true #Can also use >= <= == and != #Comparisons only directly compare the first character in a string and will read the numbers # in order and capital letters are before all lower case letters. #Branching / if else puts 'Hello, what\'s your name?' name = gets.chomp puts 'Hello, ' + name + '.' if name == 'Jade' puts 'What a lovely name!' end puts 'Hello, what\'s your name?' name = gets.chomp puts 'Hello, ' + name + '.' if name == 'Jade' puts 'What a lovely name!' elsif name == 'Kitty' #Gives same result for the two specified names puts 'What a lovely name!' end #Does the same thing as the above code, with an OR statement puts 'Hello, what\'s your name?' name = gets.chomp puts 'Hello, ' + name + '.' if name == 'Jade' || name == 'Kitty' puts 'What a lovely name!' end # || is OR, && is AND, ! is NOT puts 'I am a fortune-teller. Tell me your name.' name = gets.chomp if name == 'Jade' puts 'I see great things in your future.' else puts 'Your future is...oh my! Look at the time!' puts 'I really have to go, sorry!' end #Loops while true input = gets.chomp puts input if input == 'bye' break #breaks the while loop end end puts 'Come again soon!' #Practice while true puts 'What would you like to ask C to do?' request = gets.chomp puts 'You say, "C, please ' + request + '"' puts 'C\'s response:' puts '"C ' + request + '."' puts '"Papa ' + request + ', too."' puts '"Mama ' + request + ', too."' puts '"Ruby ' + request + ', too."' puts '"Nono ' + request + ', too."' puts '"Emma ' + request + ', too."' puts if request == 'stop' break end end #99 Bottles bottles = 99 while true puts bottles.to_s + ' bottles of beer on the wall.' puts bottles.to_s + ' bottles of beer.' puts 'Take one down, pass it around.' bottles = bottles - 1 puts bottles.to_s + ' bottles of beer on the wall.' puts ' ' if bottles == 1 puts bottles.to_s + ' bottle of beer on the wall.' puts bottles.to_s + ' bottle of beer.' puts 'Take one down, pass it around.' bottles = bottles - 1 puts bottles.to_s + ' bottle of beer on the wall.' end if bottles == 0 break end end #Deaf granny puts 'What did you say there, youngin\'?' grancount = 0 while true granresp = gets.chomp if granresp == granresp.upcase puts 'NO, NOT SINCE 1938!' elsif puts 'HUH?! SPEAK UP, SONNY!' end if granresp == 'BYE'.chomp grancount = grancount +1 else grancount = 0 end if grancount >= 3 puts 'BYE, SONNY!' break end end #Arrars start at 0 array = [] array[0] = 'Hi' #language example languages = ['English', 'Norwegian', 'Ruby'] languages.each do |lang| # .each tells Ruby to look at every object in the array; it's an iterator #Then do tells Ruby to manipulate the array object by object, which is called a new variable |lang| #Then can use lang to refer to looking at the objects separately. puts 'I love ' + lang + '!' puts 'Don\'t you?' end puts 'And let\'s hear it for Java!' puts '<crickets chirp in the distance>' #Repeater example 3.times do #Tells it to print three times. puts 'Hip-hip-hooray!' end #Foods foods = ['artichoke', 'brioche', 'caramel'] puts foods puts puts foods.to_s #smashes all of the objects in the array together in a single string puts puts foods.join(', ') #joins all the objects together, separated by commas puts puts foods.join(' :) ') + ' 8) ' #joins all of the objects together, separated by smileys and added a smiley at the end #push pop #push adds an object to the end of an array #pop removes the last object from the array and tells you what it was #They both CHANGE the array #last just tells you what the last object was #example favorites = [] favorites.push 'raindrops on roses' favorites.push 'whiskers on kittens' puts favorites[0] #Gives the first object puts favorites.last #Gives the last object puts favorites.length #Gives the length puts favorites.pop #Tells you the last object and removes it. puts favorites #Lists the array; only one object left now. puts favorites.length #Gives the length #Practice #Sort a list sortlist = [] puts 'Give me a list of words:' while true join = gets.chomp sortlist.push join if join == '' break end end puts 'Here\'s your list in alphabetical order:' puts sortlist.sort #sorts your list #table of contents #First time puts ('Table of Contents'.center(50)) puts ('Chapter 1: Getting Started'.ljust(30) + 'Page 1'.rjust(20)) puts ('Chapter 2: Numbers'.ljust(30) + 'Page 9'.rjust(20)) puts ('Chapter 3: Letters'.ljust(30) + 'Page 13'.rjust(20)) #Now title = 'Table of Contents' chapters = [['Getting Started', 1],['Numbers', 9], ['Letters', 13]] puts title.center(50) puts chap_num = 1 chapters.each do |chap| name = chap[0] page = chap[1] beginning = 'Chapter ' + chap_num.to_s + ': ' + name ending = 'Page ' + page.to_s puts beginning.ljust(30) + ending.rjust(20) chap_num = chap_num + 1 end #Some arguments/methods take parameters to define how it's done def say_moo number_of_moos #Defines a function that takes two parameters "say_moo" and "number_of_moos" puts 'mooooooo.....' * number_of_moos end #So this is how you would use the function say_moo 3 #Another example def double_this num #There are two parameters that need to be defined by these variables num_times_2 = num * 2 #They are called local variables because they're defined in the function puts num.to_s + ' doubled is ' + num_times_2.to_s #Those are num and num_times_2 end double_this 44 #Prints 44 doubled is 88 #Function/Method practice def ask question while true puts question reply = gets.chomp.downcase if (reply == 'yes' || reply == 'no') if reply == 'yes' answer = true else answer = false end break else puts 'Please answer "yes" or "no".' end end answer end puts 'Hello, and thank you for taking the time' puts 'to help me with my experiment.' puts 'Please answer a few questions' puts 'with either a "yes" or a "no".' puts ask 'Do you like eating tacos?' #Asks for a response, but it isn't stored ask 'Do you like eating burritos?' #this one isn't stored either wets_bed = ask 'Do you wet the bed?' #This one is stored because it's the one we care about ask 'Do you like eating chimichangas?' ask 'Do you like eating sopapillas?' puts 'Just a few more questions...' ask 'Do you like drinking horchata?' ask 'Do you like eating flautas?' puts puts 'DEBRIEFING:' puts 'Thank you for taking this survey.' puts 'It was an experiment about bed-wetting,' puts 'and the questions about Mexican food' puts 'were to throw you off.' puts puts wets_bed #Recalls the variable of interest #Rewrite def ask question while true puts question reply = gets.chomp.downcase if (reply == 'yes' || reply == 'no') if reply == 'yes' return true else return false end else puts 'Please answer "yes" or "no".' end end end puts 'Hello, and thank you for taking the time' puts 'to help me with my experiment.' puts 'Please answer a few questions' puts 'with either a "yes" or a "no".' puts ask 'Do you like eating tacos?' #Asks for a response, but it isn't stored ask 'Do you like eating burritos?' #this one isn't stored either wets_bed = ask 'Do you wet the bed?' #This one is stored because it's the one we care about ask 'Do you like eating chimichangas?' ask 'Do you like eating sopapillas?' puts 'Just a few more questions...' ask 'Do you like drinking horchata?' ask 'Do you like eating flautas?' puts puts 'DEBRIEFING:' puts 'Thank you for taking this survey.' puts 'It was an experiment about bed-wetting,' puts 'and the questions about Mexican food' puts 'were to throw you off.' puts puts wets_bed #Recalls the variable of interest #Old Roman Numerals def old_roman_numeral num roman = ' ' roman = roman + 'M' * (num / 1000) #Starts with the greatest number possible, # and captures what could be left over roman = roman + 'D' * (num % 1000 / 500) #Defines the leftovers as the new var and takes the # remainders again for the next lowest Roman Numeral roman = roman + 'C' * (num % 500 / 100) roman = roman + 'L' * (num % 100 / 50) roman = roman + 'X' * (num % 50 / 10) roman = roman + 'V' * (num % 10 / 5) roman = roman + 'I' * (num % 5 / 1) roman #Final result after dividing by all the Roman Letters end puts old_roman_numeral 350 #Num count problem in steps #First step - Count by 1 num = 0 while true puts num num = num + 1 if num > 100 break end end #Second step - Count by 2 num = 0 while true counter = 2 puts num num = num + counter if num > 100 break end end #Step 3 - Count by a submitted number num = 0 puts 'Please pick a positive integer:' counter = gets.chomp.to_i while true puts num num = num + counter if num > 100 break end end #Step 4 - Count by a submitted number, but have the program check the range num = 0 puts 'Please pick a positive integer:' counter = gets.chomp.to_i while true if (counter < 1 || counter > 100) puts 'Sorry, that number doesn\'t work!' break end puts num num = num + counter if num > 100 break end end #Long (multi-line) comments =begin all comment text on each of these lines =end # .to_a turns object into an array # can choose to split an object by lines, bytes, char #example poem.lines.to_a #This takes a poem, splits it by lines, and puts the lines as objects in an array #Adding an ! to the end of a method tells the method to impact just the object instead of making a copy # using .include? " " allows you to search a string to see if it includes whatever is placed in the quotes # A "hash" is the same thing as a dictionary # {} creates a hash #Example books = {} #empty books["Gravity's Rainbow"] = :splendid #Added a key to the hash called "gravity's rainbow" and related it to another word, as a symbol # the word "splendid" is a symbol because it has a : in front of it #Useful because they save space in the computer's memory if you need to keep reusing the word #Now we can just type books["Gravity's Rainbow"] and it will show us the review of the book - splendid books.keys #lists all the keys listed Dir.entries "/" #Lists everything in the top directory/root Dir["/*.txt"] #Only searches for text files in the root File.open("/Home/file.txt", "a") do |f| #Opens a file in Home dir called "file.txt" #then the file is appended with "a" to do something |f|, which is to append the file with added text # Will show ... to prompt you to keep typing #After that, type end on a fresh line to finish appending the open document Cat #What's added end print File.read("/Home/file.txt") #Reads the file File.mtime("/Home/file.txt") #Gives a time and date of the last time the file was changed #Could add .hour after the file in parenthesis to get how many hours ago the file was changed File.foreach #opens a file and hands each line of the file to the block .split(': ') #Breaks a string into an array by removing the piece you pass it in the parenthesis .strip #Removes spaces around a variable #Single-quotes tell Ruby to ignore any called variables within them #Double-quotes will call variables using #{} # Calling variables using #{} or %{} - %{} will give you a raw value, not a string
true
4abffe10495b0a096e2c4de69539cdf2e9aef3fb
Ruby
JPlante9117/oo-cash-register-online-web-ft-100719
/lib/cash_register.rb
UTF-8
939
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CashRegister attr_accessor :total, :discount, :cart def initialize(discount=0) @cart = Array.new @total = 0 @discount = discount end def add_item(title, price, quantity = 1) i = 0 @price = price * quantity @title = title #title, price, adds to total #accepts optional quantity #includes previous total while i < quantity @cart << title @total += price i += 1 end end def apply_discount if @discount == 20 @total = @total - (total * (@discount/100.00)) return "After the discount, the total comes to $#{@total.to_i}." else return "There is no discount to apply." end end def items @cart end def void_last_transaction #select the last thing added to the transaction #remove it from the list and remove it from the total @total -= @price end end
true
31e0f91e680dffec1b9d5c5ddfb3bb3b0e6bbefd
Ruby
MattRice12/internal-learning
/classes/user.rb
UTF-8
328
3.515625
4
[]
no_license
class User attr_reader :first_name, :last_name attr_accessor :age def initialize(first_name, last_name, age) @first_name = first_name @last_name = last_name @age = age end def full_name first_name + " " + last_name end def personal_description "#{full_name} is #{age} years old." end end
true
7f503384207f2022e030da8347f3c1f13da6cc7b
Ruby
95mao/furima-34801
/spec/models/buy_address_spec.rb
UTF-8
3,551
2.703125
3
[]
no_license
require 'rails_helper' RSpec.describe BuyAddress, type: :model do # RSpec.describe 「 factorybotのクラス名 」, type: :model before do item = FactoryBot.create(:item) user = FactoryBot.create(:user) # FactoryBotで作ったitemとuserのデータを@buy_addressで紐付けするため @buy_address = FactoryBot.build(:buy_address, user_id: user.id, item_id: item.id) # ()の中はfactorybotのクラスで決めたfactoryのこと(2行目)) sleep(1) # sleep(秒数) ()中の時間をかけて処理をしてくれる end describe "購入情報登録" do context '登録できるとき' do it '全ての情報が正常であれば登録できる'do expect(@buy_address).to be_valid end it '建物名が空でも登録できる'do @buy_address.building_name = '' expect(@buy_address).to be_valid end end context '登録できないとき' do it 'user_idが空では登録できない' do @buy_address.user_id = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("User can't be blank") end it 'item_idが空では登録できない' do @buy_address.item_id = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Item can't be blank") end it 'postal_codeが空では登録できない' do @buy_address.postal_code = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Postal code can't be blank") end it 'start_idが空では登録できない' do @buy_address.start_id = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Start can't be blank") end it 'cityが空では登録できない' do @buy_address.city = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("City can't be blank") end it 'house_numberが空では登録できない' do @buy_address.house_number = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("House number can't be blank") end it 'telが空では登録できない' do @buy_address.tel = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Tel can't be blank") end it 'postal_codeが-なしでは登録できない' do @buy_address.postal_code = '1234567' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Postal code is invalid") end it 'start_idが0では登録できない' do @buy_address.start_id = 0 @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Start must be other than 0") end it 'telが12桁以上では登録できない' do @buy_address.tel = '111111111111' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Tel is too long (maximum is 11 characters)") end it 'tokenが空では登録できない' do @buy_address.token = '' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Token can't be blank") end it 'telが数字でないと登録できない' do @buy_address.tel = 'a0901234567' @buy_address.valid? expect(@buy_address.errors.full_messages).to include("Tel is invalid") end end end end
true
7be0d56be3b371e40038edf8a8738da1e8017589
Ruby
unepwcmc/parcc
/lib/modules/importers/turnover.rb
UTF-8
1,255
2.578125
3
[]
no_license
class Importers::Turnover < Importers::Base extend Memoist STATS = [:median, :upper, :lower] def self.import instance = new instance.import end def import files.each { |file| populate_values file } end def populate_values file_path split_filename = File.basename(file_path, '.csv').split turnover_defaults = { taxonomic_class_id: taxon_class_id_from_name(split_filename.first), year: split_filename[3] } csv_reader(file_path).each do |record| create_record(turnover_defaults, record) end end def create_record defaults, record stats = record.to_hash.slice(*STATS) pa_id = {protected_area_id: pa_id_from_wdpa_id(record[:wdpaid])} SpeciesTurnover.create defaults.merge(stats).merge(pa_id) end memoize def files Dir['lib/data/turnover/*'] end memoize def pa_id_from_wdpa_id wdpa_id db.select_value( "SELECT id from protected_areas where wdpa_id = #{wdpa_id.to_i}" ).instance_eval { to_i unless nil? } end memoize def taxon_class_id_from_name name db.select_value( "SELECT id from taxonomic_classes where name = '#{name}'" ).instance_eval { to_i unless nil? } end define_method(:db) { ActiveRecord::Base.connection } end
true
919d69d7544dcc199010da65dc1fdf7df5dc22f9
Ruby
olotintemitope/andela_ruby
/numbers.rb
UTF-8
259
3.640625
4
[]
no_license
class Numbers def initialize(array) if array.kind_of? (Array) @numbers = array end end def numbers @numbers end def sum_up sum = 0 @numbers.each { |num| sum+=num } sum end end
true
42eb0484ee0917440cfc1488bac02ad012f4379c
Ruby
brentluna/knights_travails
/knightpath.rb
UTF-8
1,517
3.484375
3
[]
no_license
require_relative 'poly_tree_node' class KnightPathFinder DELTAS = [[-2, 1], [-2, -1], [-1, 2], [-1, -2], [2, 1], [2, -1], [1, -2], [1, 2]] def initialize(start_pos) @start_pos = start_pos @visited_positions = [@start_pos] @tree = build_move_tree end def self.valid_moves(pos) valid_moves = [] DELTAS.each do |delta| row, col = pos.first + delta.first, pos.last + delta.last valid_moves << [row, col] if [row, col].all? { |pos| pos.between?(0, 7) } end valid_moves end def build_move_tree root = PolyTreeNode.new(@start_pos) queue = [root] until queue.empty? curr_node = queue.shift moves = new_move_positions(curr_node.value) moves.each do |move| node = PolyTreeNode.new(move) node.parent = curr_node queue << node end end root end def find_path(end_pos) return trace_path_back(@tree) if @tree.value == end_pos @tree.children.each do |child| result = child.dfs(end_pos) return trace_path_back(result) unless result.nil? end nil end def trace_path_back(node) path = [node] until path.last.parent.nil? path << path.last.parent end path = path.map { |node| node.value } @visited_positions = [@start_pos] path.reverse end def new_move_positions(pos) moves = KnightPathFinder.valid_moves(pos) moves = moves.reject { |move| @visited_positions.include?(move) } @visited_positions.push(*moves) moves end end
true
65a348c4da07c1a98eb7a917d00d4ed076a97677
Ruby
richrace/search-properties
/spec/models/parse_search_string_spec.rb
UTF-8
3,984
2.921875
3
[]
no_license
require 'spec_helper' describe ParseSearchString do before(:all) do @parser = ParseSearchString.new end describe "#find_bedrooms" do it "will detect string with 'bedroom'" do search_string = "1 bedroom house" @parser.find_bedrooms(search_string).should eq 1 end it "will detect string with 'bedrooms'" do search_string = "2 bedrooms house" @parser.find_bedrooms(search_string).should eq 2 end it "will detect string with 'bed'" do search_string = "1 bed house" @parser.find_bedrooms(search_string).should eq 1 end it "will detect string with 'beds'" do search_string = "2 beds house" @parser.find_bedrooms(search_string).should eq 2 end it "won't fail when no number of bedrooms supplied" do search_string = "bedroom house" @parser.find_bedrooms(search_string).should eq 0 end it "will get the number of bedrooms if something is before the bedroom info" do search_string = "house 1 bedroom" @parser.find_bedrooms(search_string).should eq 1 end it "doesn't care about case uses 'BEdRoom'" do search_string = "house 1 BEdRoom" @parser.find_bedrooms(search_string).should eq 1 end it "will detect string with written number 'one'" do search_string = "one bed house" @parser.find_bedrooms(search_string).should eq 1 end it "will detect string with written number 'two'" do search_string = "two bed house" @parser.find_bedrooms(search_string).should eq 2 end it "will detect string with lots of whitespace between '1 bed'" do search_string = "1 bed house" @parser.find_bedrooms(search_string).should eq 1 end end describe "#find_property_type" do it "will detect string with 'flat'" do search_string = "1 bedroom flat" @parser.find_property_type(search_string).should eq "flat" end it "will detect string with 'house'" do search_string = "1 bedroom house" @parser.find_property_type(search_string).should eq "house" end it "will detect string with 'flats'" do search_string = "1 bedroom flats" @parser.find_property_type(search_string).should eq "flat" end it "will detect string with 'houses'" do search_string = "1 bedroom houses" @parser.find_property_type(search_string).should eq "house" end it "will ignore case 'HouSe'" do search_string = "1 bedroom HouSe" @parser.find_property_type(search_string).should eq "house" end it "will ignore case FlaTs" do search_string = "1 bedroom FlaTs" @parser.find_property_type(search_string).should eq "flat" end end describe "#find_location" do it "will find just location at the end" do search_string = "1 bedroom flat london" @parser.find_location(search_string).should eq "london" end it "will find location when at the beginning" do search_string = "london 1 bedroom flat" @parser.find_location(search_string).should eq "london" end it "will find location when in the middle" do search_string = "1 bedroom london flat" @parser.find_location(search_string).should eq "london" end it "will find location when location is more than one word" do search_string = "1 bed flat north london" @parser.find_location(search_string).should eq "north london" end it "is not case sensitive" do search_string = "1 bed flat North LONDON" @parser.find_location(search_string).should eq "north london" end end describe "#parse_search_string" do it "will get a hash of search parameters" do expected_hash = {:bedroom_count => 1, :property_type => "flat", :location => "north london"} search_string = "1 bed flat north london" @parser.parse_search_string(search_string).should eq expected_hash end end end
true
13ed60026854336c62a1155482e5e3f37672e81d
Ruby
ryanfb/ruby-opencv
/test/test_cvline.rb
UTF-8
1,023
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
#!/usr/bin/env ruby # -*- mode: ruby; coding: utf-8-unix -*- require 'test/unit' require 'opencv' require File.expand_path(File.dirname(__FILE__)) + '/helper' include OpenCV # Tests for OpenCV::CvLine class TestCvLine < OpenCVTestCase def setup @line = CvLine.new end def test_initialize assert_not_nil(@line) assert_equal(CvLine, @line.class) end def test_rho @line.rho = 0.0 assert_in_delta(0.0, @line.rho, 0.001) @line.rho = 3.14 assert_in_delta(3.14, @line.rho, 0.001) end def test_theta @line.theta = 0.0 assert_in_delta(0.0, @line.theta, 0.001) @line.theta = 3.14 assert_in_delta(3.14, @line.theta, 0.001) end def test_aref_aset @line[0] = 0.0 @line[1] = 0.0 assert_in_delta(0.0, @line[0], 0.001) assert_in_delta(0.0, @line[1], 0.001) @line[0] = 3.14 @line[1] = 2.71 assert_in_delta(3.14, @line[0], 0.001) assert_in_delta(2.71, @line[1], 0.001) assert_raise(IndexError) { @line[2] = 1 } end end
true
febd9803df646629c9e0ec3230b670ec4bdedabd
Ruby
segunadeleye/ruby_track
/Ex14/bin/main.rb
UTF-8
133
3.234375
3
[]
no_license
require_relative "../lib/string" string = "An apple a day keeps the doctor away" puts "'#{string}' reversed to '#{string.reverse}'"
true
20c350c6572284fbc65fb54fbbf56ea867f1437b
Ruby
AlexStoll/RB101
/lesson_2/pseudo2.rb
UTF-8
1,254
4.71875
5
[]
no_license
# 1. a method that returns the sum of two integers # Define the two integers before the method definition, maybe get them from the user. # Create the method which takes int1 and adds it to int2, making sure it's doing integer addition. # START # PRINT request for two integers # SET int1 = GET first value # SET int2 = GET second value # Define method to # PRINT return of int1 + int2 # END # 2. a method that takes an array of strings, and returns a string that is all those strings concatenated # Create an array of strings # Define a method to return each value of the array and list them in one string # START # SET strings = an array of strings # SET length = number of strings in the array # SET counter = 0 # WHILE counter <= length # add each string to big_string # PRINT big_string # END # 3. a method that takes an array of integers, and returns a new array with every other element # Use the index of the array to add every other number to a new array # So when the index is odd, add that value to the new array. # START # SET others = an empty array # SET count = 0 # WHILE count <= size of the input array # IF index is odd # add the corresponding value to the empty array # ELSE # next # END # count += 1 # END
true
0df15640d4a5d4652b7489cbb1973ea40960732e
Ruby
jeff-chen/codon-autocorrelation-calculate
/root_distance_translator.rb
UTF-8
142
2.625
3
[]
no_license
require 'translator' class RootDistanceTranslator < Translator def distance(pos1, pos2) Math.sqrt(((pos2 - pos1).abs)+1).to_f end end
true
1d95ac4309e63b4f9f8cb6d25b681b03f1ad46cc
Ruby
kimihito/whitehall
/db/data_migration/20130812130035_migrate_document_series_join_data.rb
UTF-8
1,296
2.734375
3
[]
no_license
require "benchmark" # Takes the existing data that joins document series to editions and creates # the corresponding joins to link series directly with documents instead. time = Benchmark.measure do # results will contain an array of hashes mapping document series to document ids in the form: # { 'document_series_id' => 123, 'id' => '456'} where id is the document id. query = EditionDocumentSeries.joins(edition: :document) .where("editions.state != 'deleted'") .select(['document_series_id', 'documents.id']) .order('editions.publication_date DESC') results = ActiveRecord::Base.connection.select_all(query) # We are only interested in unique combinations of document to series mappings unique_results = results.uniq unique_series_count = results.map {|r| r['document_series_id'] }.uniq.count puts "Found #{unique_results.count} documents across #{unique_series_count} document series" puts "Creating new joins between document series and documents" unique_results.each do |row| DocumentSeriesMembership.where(document_series_id: row['document_series_id'], document_id: row['id']).first_or_create! print '.' end end puts "\nAll done. Total time taken:" puts time
true
394917d75b490f51df337352e9b491b466270970
Ruby
Rinthm/phase-0
/week-4/leap-years/my_solution.rb
UTF-8
312
3.265625
3
[ "MIT" ]
permissive
# Leap Years # I worked on this challenge with: Jerrie Evans. # Your Solution Below def leap_year?(year) if year % 4 == 0 && year % 100 != 0 return true elsif year % 400 == 0 return true elsif year % 4 == 0 && year % 100 == 0 && year % 400 != 0 return false else year % 4 != 0 return false end end
true
20e65d01298c3a4decb6cdd162ec8fa609f0be1b
Ruby
matthiashaefeli/Practice-Problems
/src/solution_ruby.rb
UTF-8
4,567
3.921875
4
[]
no_license
require "pry" class Solution def reverse(string) array = [] string.split('').each do |letter| array.unshift(letter) end return array.join('') end def factorial(n) result = 1 while n > 0 result = result * n n -= 1 end return result end def longest_word(sentence) result = sentence.split(' ').sort_by {|word| word.length} result[-1] end def sum_nums(num) result = 0 until num == 0 result += num num-=1 end return result end def time_conversion(minutes) # Time.at(minutes).utc.strftime("%M:%S") hh, mm = minutes.divmod(60) if mm < 10 m = "0" + mm.to_s else m = mm.to_s end return hh.to_s + ":" + m end def count_vowels(string) result = 0 vowel = ['a','e','i','o','u','A', 'E', 'I', 'O', 'U'] string.split('').each do |letter| if vowel.include?(letter) result += 1 end end return result end def palindrome?(string) if string == string.reverse return true else false end end def nearby_az(string) array = string.split('') index = 0 while index < array.length if array[index] == 'a' if array[index+1] == 'z' || array[index+2] == 'z' || array[index+3] == 'z' return true else index += 1 end else index += 1 end end return false end def two_sum(nums) i = 0 while i < nums.length i2 = i + 1 while i2 < nums.length if nums[i] + nums[i2] == 0 return [i, i2] end i2 += 1 end i += 1 end return nil end def is_power_of_two?(num) if num < 1 return false end while true if num == 1 return true elsif num % 2 == 0 num = num / 2 else return false end end end def third_greatest(nums) result = nums.sort.uniq return result[-3] end def most_common_letter(string) result = [0, 1] i = 0 while i < string.length if result[1] < string.count(string[i]) result[0] = string[i] result[1] = string.count(string[i]) i += 1 else i += 1 end return result end end def dasherize_number(num) string_number = num.to_s result_string = "" i = 0 while i < string_number.length number = string_number[i].to_i if i > 0 prev_number = string_number[i-1].to_i if prev_number%2 == 1 || number%2 == 1 result_string += "-" end end result_string += string_number[i] i += 1 end return result_string end def capitalize_words(string) string_array = string.split(' ') string_array.map! do |word| word.capitalize end result = string_array.join(' ') return result end def scramble_string(string, positions) string_array = [] positions.each do |number| string_array << string[number] end return string_array.join('') end def is_prime?(number) if number <= 1 return false end idx = 2 while idx < number if number % idx == 0 return false end idx += 1 end return true end def nth_prime(n) prime_array = [] i = 1 while prime_array.length < n if is_prime?(i) prime_array << i i += 1 else i += 1 end end return prime_array[-1] end def longest_palindrome(string) index = 0 index2 = -1 result = "" while index < string.length if palindrome?(string[index..index2]) if result.length < string[index..index2].length result = string[index..index2] end end if string[index+1] == string[index2] index2 = -1 index += 1 else index2 -= 1 end end return result end def greatest_common_factor(number1, number2) index = number1 while index > 0 if (number2%index == 0) && (number1%index == 0) return index else index -= 1 end end end def caesar_cipher(number, string) alphabet = ("a".."z").to_a result_string = "" string.split("").each do |letter| index_letter = alphabet.index(letter) new_index = index_letter + number if new_index > alphabet.length dif_index = new_index - alphabet.length result_string << alphabet[dif_index] else result_string << alphabet[new_index] end end return result_string end def num_repeats(string) string_array = string.split("") new_array = string_array.select{ |letter| string_array.count(letter) > 1} return new_array.uniq.count end end
true
c6344cc500391505b86ee2d36481043cb6d6b5b9
Ruby
kianinyvr/AR_stores_and_employees
/exercises/exercise_4.rb
UTF-8
804
2.984375
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' puts "Exercise 4" puts "----------" Store.create(name: "Surrey", annual_revenue: 224000, mens_apparel: false, womens_apparel: true) Store.create(name: "Whistler", annual_revenue: 1900000, mens_apparel: true, womens_apparel: false) Store.create(name: "Yaletown", annual_revenue: 430000, mens_apparel: true, womens_apparel: true) @mens_store = Store.where(mens_apparel: true) pp @mens_store @mens_store.each do |item| pp "Name: #{item.name}" pp "Revenue: #{item.annual_revenue}" end @womens_store = Store.where(womens_apparel: true).where('annual_revenue < 1000000', true ) @womens_store.each do |item| pp "Name: #{item.name}" pp "Revenue: #{item.annual_revenue}" end
true
879b215433a770b7fca5fa34df190a94d2cb3645
Ruby
anishkhithani/hangman
/hangman_test.rb
UTF-8
1,637
3.578125
4
[]
no_license
require 'test/unit' require_relative 'Hangman' class TestHangman < Test::Unit::TestCase def setup @game = Hangman.new @game.word = "booger" @game.board = @game.draw_board(@game.word) end def test_for_initialize_method assert_equal(8,@game.chances) assert_equal([],@game.guesses) assert_equal("______",@game.board) end def test_for_wordhas_check_tosee_ifword_has_letter_and_false assert_equal(true,@game.word_has?("o")) assert_equal(false,@game.word_has?("h")) end def test_for_putting_correct_letter_on_board @game.put_letter_on_board("b") assert_equal("b_____",@game.board) end def test_for_wrong_letter @game.wrong_letter("p") assert_equal(7,@game.chances) assert_equal(["p"],@game.guesses) end def test_valid_guess_trueandfalse assert_equal(true,@game.valid_guess?("b")) assert_equal(false,@game.valid_guess?("booger")) end # def test_if_raise_is_outputed_from_invalid_guess # assert_raise("Invalid Guess") {@game.guess("booger")} # end def test_win_for_true @game.guess("b") @game.guess("o") @game.guess("g") @game.guess("e") @game.guess("r") assert_equal(true,@game.win?) end def test_for_lose @game.guess("1") @game.guess("2") @game.guess("3") @game.guess("4") @game.guess("5") @game.guess("6") @game.guess("7") @game.guess("8") puts @game.chances assert_equal(0,@game.chances) end end
true
c3c72a6883500ae970ae3349107cc9e53d4e075f
Ruby
AndyGauge/prayer-lexer
/app.rb
UTF-8
735
2.625
3
[]
no_license
require 'sinatra' require './lib/importer.rb' require 'net/http' require 'uri' require 'json' set :bind, '0.0.0.0' get '/' do '<h1>Lex:</h1> <h2>Prayer-lexer recommends verses based on context of prayers</h2> <p>Send a post request to this same route to compute the verse appropriate for the content of the request</p> <form action="/" method="post"><input type=text name="prayer"><input type="submit"></form>' end post '/' do return "bad request" if params.nil? request = params.values.reduce.nil? ? params.keys.reduce : params.values.reduce response = JSON.parse(Net::HTTP.get_response(URI.parse(URI.escape("http://bible-api.com/#{Importer.lex request}"))).body) "#{response["reference"]} #{response["text"]}" end
true
9616a2e34d79ff793ba9e1257767dff5e2e4e18e
Ruby
alexignat/learn_ruby
/02_calculator/calculator.rb
UTF-8
186
3.609375
4
[]
no_license
def add(x, y) x + y end def subtract(x, y) x - y end def sum(sum_this) sum_this.inject(0) { |sum, x| sum + x } sum_this.reduce(0) { |sum, x| sum + x } sum_this.reduce(:+) end
true
b9456cdc4e1ffb5be4e0dd8c0b08e3208775abc3
Ruby
ganmacs/playground
/ruby/thr/c.rb
UTF-8
309
3.09375
3
[]
no_license
SIZE = 10 def countup counter = 0 open('count.txt', 'r') { |f| counter = f.read.to_i + 1 } open('count.txt', 'w') { |f| f.write counter } end open('count.txt', 'w') do |f| f.write 0 end m = Mutex.new Array.new(SIZE).map { Thread.start { m.synchronize { countup } } }.each(&:join)
true
4ca4c9bb7aa842e4e05469b10dddf2f971352c16
Ruby
ahrk-izo/Ruby_object_program1
/03/judge.rb
UTF-8
3,339
3.953125
4
[]
no_license
# coding: utf-8 #-------------------- # ジャンケンの審判を表すクラス #-------------------- class Judge # 定数定義(大文字で始まる)他クラスの定数を参照 STONE = Player::STONE SCISSORS = Player::SCISSORS PAPER = Player::PAPER def initialize(name = "tmp") # javaでいうコンスタントかな # インスタンス変数(インスタンスごとに持つ変数) @name = name # 名前 end # 審判確認出力 def getName return @name end # ジャンケンを開始する def startJanken(player1, player2) # 各プレイヤーのインスタンスを受け取る puts "【ジャンケン開始】" # forを使い複数回行う for cnt in 1..3 puts "#{cnt} 回戦目" winner = judgeJanken(player1, player2) # 勝った方のオブジェクトが返る if winner != nil print winner.getName, "さんが勝ちました\n" # 勝ったプレイヤーへ結果を伝える winner.notifyResult(true) else print "引き分けです\n" end end # ジャンケンの終了を宣言 puts "【ジャンケン終了】" # 最終的な勝者の判定 finalWinner = judgeFinalWinner(player1, player2) if finalWinner != nil print "最終勝者は", finalWinner.getName, "さんです" print "[", finalWinner.getWinCount, "勝]", "\n" else print "引き分けでした\n" end end # 「ジャンケン・ポン」と声をかけ、 # プレイヤーの手を見て、どちらが勝ちか判定する def judgeJanken(player1, player2) winner = nil # プレイヤー1の手を出す player1hand = player1.showHand # プレイヤー2の手を出す player2hand = player2.showHand # それぞれの手を表示する printHand(player1hand) print "[", player1.getName, "]" print " vs " printHand(player2hand) print "[", player2.getName, "]" print "\n" # プレイヤー1が勝つ場合 if (player1hand == STONE && player2hand == SCISSORS) || (player1hand == SCISSORS && player2hand == PAPER) || (player1hand == PAPER && player2hand == STONE) winner = player1 # プレイヤー2が勝つ場合 elsif (player2hand == STONE && player1hand == SCISSORS) || (player2hand == SCISSORS && player1hand == PAPER) || (player2hand == PAPER && player1hand == STONE) winner = player2 else # どちらでもない場合は引き分け(nullを返す) end return winner end # 最終的な勝者を判定する def judgeFinalWinner(player1, player2) winner = nil # player1の勝ち数を聞く player1WinCount = player1.getWinCount # player2の勝ち数を聞く player2WinCount = player2.getWinCount if player1WinCount > player2WinCount # プレイヤー1の勝ち winner = player1 elsif player1WinCount < player2WinCount # プレイヤー2の勝ち winner = player2 end # どちらでもない場合はnullを返す return winner end # ジャンケンの手を表示する def printHand(hand) case hand when STONE print "グー" when SCISSORS print "チョキ" when PAPER print "パー" else end end end
true
cb83a4578368352111840398ee279bccf446966b
Ruby
toddmohney/ennui
/spec/lib/ennui_spec.rb
UTF-8
1,426
2.625
3
[ "MIT" ]
permissive
require 'spec_helper' require 'pry' require 'ennui' include Ennui class EnnuiTest include Ennui end describe Ennui do let(:ennui_test) { EnnuiTest.new } describe "#sometimes?" do it "is true about %50 of the time" do score = truthiness_score(1000, Proc.new { sometimes? }) score.should be_within(0.10).of(0.50) end end describe "#sometimes" do it "calls sometimes?" do Ennui.should_receive(:sometimes?) Ennui.sometimes end context "when sometimes? is true" do before do Ennui.stub(:sometimes?) { true } end it "yields to the block" do expect { |block| Ennui.sometimes(&block) }.to yield_control end end context "when sometimes? is false" do before do Ennui.stub(:sometimes?) { false } end it "does not yield to the block" do expect { |block| Ennui.sometimes(&block) }.not_to yield_control end end end describe "#who_cares?" do it "is true about %25 of the time" do score = truthiness_score(1000, Proc.new { who_cares? }) score.should be_within(0.10).of(0.25) end end describe "#whatever" do it "is an alias for sometimes" do Ennui.should_receive(:sometimes) Ennui.whatever end end describe "#maybe" do it "is an alias for sometimes" do Ennui.should_receive(:sometimes) Ennui.maybe end end end
true
2baf8b3dee839fc0dd19c3fdd2c43f6cbc8b5cac
Ruby
rails/activeresource
/test/cases/reflection_test.rb
UTF-8
2,408
2.515625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "abstract_unit" require "fixtures/person" require "fixtures/customer" class ReflectionTest < ActiveSupport::TestCase def test_correct_class_attributes object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {}) assert_equal :people, object.name assert_equal :test, object.macro assert_equal({}, object.options) end def test_correct_class_name_matching_without_class_name object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, {}) assert_equal Person, object.klass end def test_correct_class_name_matching_as_string object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "Person") assert_equal Person, object.klass end def test_correct_class_name_matching_as_symbol object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: :person) assert_equal Person, object.klass end def test_correct_class_name_matching_as_class object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: Person) assert_equal Person, object.klass end def test_correct_class_name_matching_as_string_with_namespace object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "external/person") assert_equal External::Person, object.klass end def test_correct_class_name_matching_as_plural_string_with_namespace object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, class_name: "external/profile_data") assert_equal External::ProfileData, object.klass end def test_foreign_key_method_with_no_foreign_key_option object = ActiveResource::Reflection::AssociationReflection.new(:test, :person, {}) assert_equal "person_id", object.foreign_key end def test_foreign_key_method_with_with_foreign_key_option object = ActiveResource::Reflection::AssociationReflection.new(:test, :people, foreign_key: "client_id") assert_equal "client_id", object.foreign_key end def test_creation_of_reflection Person.reflections = {} object = Person.create_reflection(:test, :people, {}) assert_equal ActiveResource::Reflection::AssociationReflection, object.class assert_equal 1, Person.reflections.count assert_equal Person, Person.reflections[:people].klass end end
true
85ebb77e762765d904f46b0126f7aef5065b21c3
Ruby
davluangu/buzzfeed-titanic
/app.rb
UTF-8
1,094
2.546875
3
[]
no_license
require 'sinatra' require 'uri' require 'net/http' require 'json' get '/' do erb :form end post "/submit" do name = "#{params['lastname']}, #{params['title']} #{params['firstname']}" params["name"] = name params.delete("firstname") params.delete("lastname") params.delete("title") params["sibsp"] = params["sibsp"].to_i params["parch"] = params["parch"].to_i params["age"] = params["age"].to_i params["sibsp"] = params["sibsp"] + 1 if params["spouse"] == "yes" params.delete("spouse") params["fare"] = 60 params["cabin"] = "B5" params["home.dest"] = "Chicago, IL" params["ticket"] = 42 uri = URI.parse("http://syberia-titanic-demo.elasticbeanstalk.com/score") req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'}) req.body = params.to_json res = Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end score = JSON.parse(res.body)["score"].to_f score_formula = 1/(1 + (2.71828 ** -score)) * 2 - 1 "<b><font size='+3'>Chance of survival: #{(score_formula * 100).to_s[0..5]}%</font></b>" end
true
e011173afd683ca69ae96f6dbe58483036a1c5b8
Ruby
srishtinath/ruby-oo-relationships-practice-auto-shop-exercise-nyc01-seng-ft-042020
/app/models/mechanic.rb
UTF-8
739
3.53125
4
[]
no_license
class Mechanic attr_reader :name, :specialty @@all = [] def initialize(name, specialty) @name = name @specialty = specialty Mechanic.all << self end def self.all @@all end def cars Car.all.select { |car_obj| car_obj.mechanic == self} end def car_owners cars.map { |car_obj| car_obj.owner} end def car_owners_names cars.map { |car_obj| car_obj.owner.name} end end # - `Mechanic.all` Get a list of all mechanics # - `Mechanic#cars` Get a list of all cars that a mechanic services # - `Mechanic#car_owners` Get a list of all the car owners that go to a specific mechanic # - `Mechanic#car_owners_names` Get a list of the names of all car owners who go to a specific mechanic
true
8a5dff04652d1d40c8a8873111a9f58dbc8b5208
Ruby
AteroConfigs/learnstat
/lib/bar_graph_builder.rb
UTF-8
2,665
2.90625
3
[ "MIT" ]
permissive
require 'rvg/rvg' include Magick class BarGraphBuilder RVG::dpi = 72 @@title_styles = { :text_anchor => 'middle', :font_size => 30, :font_family => 'georgia', :fill=> '#CCC' } @@label_styles = { :font_size => 20, :font_family => 'verdana', :fill => '#CCC' } @@axis_styles = { :stroke_width => 2, :stroke => '#CCC' } @@padding = 25 def initialize(distribution, title = 'Bar Graph', size = '800x600') @distribution = distribution @title = title @width, @height = size.split( 'x' ).collect {|x| x.to_i } @bar_width = (650 - (@distribution.size + 1) * @@padding) / @distribution.size end def render rvg = RVG.new(@width, @height).viewbox(0,0,800,600) do |canvas| canvas.background_image = Magick::Image.new(800, 600, GradientFill.new(0, 0, 800, 0, '#000', '#9b2f47')) canvas.text(400, 30) do |title| title.tspan(@title).styles( @@title_styles ) end canvas.g do |axes| axes.line(100, 50, 100, 500).styles( @@axis_styles ) axes.line(100, 500, 750, 500).styles( @@axis_styles ) axes.line( 95, 50, 105, 50).styles( @@axis_styles ) axes.line( 95, 165, 105, 165).styles( @@axis_styles ) axes.line( 95, 275, 105, 275).styles( @@axis_styles ) axes.line( 95, 385, 105, 385).styles( @@axis_styles ) end canvas.text(80, 60) {|label| label.tspan( '100%' ).styles( @@label_styles.merge( :text_anchor => 'end' ) ) } canvas.text(80, 170) {|label| label.tspan( '75%' ).styles( @@label_styles.merge( :text_anchor => 'end' ) ) } canvas.text(80, 280) {|label| label.tspan( '50%' ).styles( @@label_styles.merge( :text_anchor => 'end' ) ) } canvas.text(80, 390) {|label| label.tspan( '25%' ).styles( @@label_styles.merge( :text_anchor => 'end' ) ) } canvas.text(80, 500) {|label| label.tspan( '0%' ).styles( @@label_styles.merge( :text_anchor => 'end' ) ) } @distribution.each_with_index do |bar, index| frequency = bar[:frequency] color = bar[:color] label = bar[:label] || (index+65).chr bar_style = { :stroke => color, :fill => color } bar_height = 450 * frequency bar_x = 100 + @@padding + (@@padding + @bar_width)*index bar_y = 500 - 450 * frequency - 2 canvas.g {|bars| bars.rect( @bar_width, bar_height, bar_x, bar_y ).styles( bar_style ) } label_x = bar_x + @bar_width / 2 label_y = 525 canvas.text(label_x, label_y) {|bar_label| bar_label.tspan( label ).styles( @@label_styles.merge( :text_anchor => 'middle' ) ) } end end image = rvg.draw image.format = 'png' image.to_blob end end
true
ec6cb0159094c1c61bc73d002bc5422925c497bf
Ruby
zagoranov/bb-schedule
/app/helpers/application_helper.rb
UTF-8
701
2.734375
3
[]
no_license
module ApplicationHelper def day_distance(dt) n = (Time.now.to_date - dt.to_date).to_i if dt.wday == 2 && I18n.locale == :ru zz = "o" else zz = "" end case n when 0 rt = t(:today) when 1 rt = t(:yesterday) when 2..6 rt = t(:at) + zz + " " + week_day(dt.wday) else rt = n.to_s + " " + t(:days_ago) end return rt end def week_day(dd) case dd when 0 tr = t(:sunday) when 1 tr = t(:monday) when 2 tr = t(:tuesday) when 3 tr = t(:wednesday) when 4 tr = t(:thursday) when 5 tr = t(:friday) else tr = t(:saturday) end return tr end end
true
7f6ab7666d775d23f8fb5892548225888804fa55
Ruby
rishab231/calcentral
/app/models/canvas_lti/webcast_eligible_courses.rb
UTF-8
3,223
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer", "ECL-2.0" ]
permissive
module CanvasLti class WebcastEligibleCourses include ClassLogger def initialize(sis_term_ids, options = {}) @sis_term_ids = sis_term_ids @options = options end def fetch courses_by_term = fetch_term_to_course_sections_hash extract_webcast_eligible_courses courses_by_term end private def fetch_term_to_course_sections_hash courses_by_term = {} @sis_term_ids.each do |term_id| canvas_sections = Canvas::Report::Sections.new(@options).get_csv term_id if canvas_sections course_id_to_csv = canvas_sections.group_by { |row| row['canvas_course_id'] } course_id_to_csv.each do |canvas_course_id, csv_rows| if canvas_course_id sis_section_ids = csv_rows.collect { |row| row['section_id'] } sis_section_ids.delete_if { |section| section.blank? } sis_section_ids.each do |sis_section_id| section = Canvas::Terms.sis_section_id_to_ccn_and_term sis_section_id unless section.nil? || section[:ccn].nil? key = { term_yr: section[:term_yr], term_cd: section[:term_cd] } courses_by_term[key] ||= {} courses_by_term[key][canvas_course_id] ||= Set.new courses_by_term[key][canvas_course_id] << section end end end end else logger.error "No Canvas sections found where term_id = #{term_id}" end end courses_by_term end def extract_webcast_eligible_courses(courses_by_term) eligible_courses = {} sign_up_eligible = Webcast::SignUpEligible.new(@options).get courses_by_term.each do |key, courses| ccn_set = extract_ccn_set courses term_yr = key[:term_yr] term_cd = key[:term_cd] recordings_per_ccn = Webcast::CourseMedia.new(term_yr, term_cd, ccn_set, @options).get_feed sign_up_eligible_ccn_set = sign_up_eligible[Berkeley::TermCodes.to_slug(term_yr, term_cd)] courses.each do |canvas_course_id, sections| sections.each do |section| ccn = section[:ccn].to_s.to_i if ccn > 0 has_recordings = recordings_per_ccn.has_key?(ccn) && recordings_per_ccn[ccn][:videos].present? logger.warn "#{term_yr}-#{term_cd}-#{ccn} has recordings (canvas_course_id = #{canvas_course_id})" if has_recordings is_webcast_eligible = !has_recordings && !sign_up_eligible_ccn_set.nil? && sign_up_eligible_ccn_set.include?(ccn) if has_recordings || is_webcast_eligible section[:has_webcast_recordings] = has_recordings section[:is_webcast_eligible] = is_webcast_eligible eligible_courses[canvas_course_id] ||= Set.new eligible_courses[canvas_course_id] << section end end end end end eligible_courses end def extract_ccn_set(courses) ccn_set = Set.new courses.values.each do |course| course.map { |section| section[:ccn] }.each { |ccn| ccn_set << ccn.to_i } end ccn_set end end end
true
4b0f8edb7db952c63e5d85b9709d746f3dc43844
Ruby
marcelgalang/ruby-collaborating-objects-lab-v-000
/lib/mp3_importer.rb
UTF-8
481
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MP3Importer attr_accessor :path, :files def initialize(path) @path= path @files= [] end def files @files= [] Dir.foreach(path) do|track| if track =~ (/[.mp3]{4}/) @files<< track end end @files end def import @files.map do |file| binding.pry Song.new_by_filename(file) end end # works def import self.files.each do |file| Song.new_by_filename(file) end end end
true
153ef5a0c31a86e28872340d9ffeac412fca5689
Ruby
xiejiangzhi/regexp-examples
/lib/regexp-examples/parser.rb
UTF-8
2,551
2.96875
3
[ "MIT" ]
permissive
require_relative 'parser_helpers/parse_group_helper' require_relative 'parser_helpers/parse_after_backslash_group_helper' require_relative 'parser_helpers/parse_multi_group_helper' require_relative 'parser_helpers/parse_repeater_helper' require_relative 'parser_helpers/charset_negation_helper' # :nodoc: module RegexpExamples IllegalSyntaxError = Class.new(StandardError) # A Regexp parser, used to build a structured collection of objects that represents # the regular expression. # This object can then be used to generate strings that match the regular expression. class Parser include ParseGroupHelper include ParseAfterBackslashGroupHelper include ParseMultiGroupHelper include ParseRepeaterHelper include CharsetNegationHelper attr_reader :regexp_string def initialize(regexp_string, regexp_options) @regexp_string = regexp_string @ignorecase = !(regexp_options & Regexp::IGNORECASE).zero? @multiline = !(regexp_options & Regexp::MULTILINE).zero? @extended = !(regexp_options & Regexp::EXTENDED).zero? @num_groups = 0 @current_position = 0 end def parse repeaters = [PlaceHolderGroup.new] until end_of_regexp group = parse_group(repeaters) return [group] if group.is_a? OrGroup @current_position += 1 repeaters << parse_repeater(group) end repeaters end private def parse_group(repeaters) case next_char when '(' parse_multi_group when '[' parse_char_group when '.' parse_dot_group when '|' parse_or_group(repeaters) when '\\' parse_after_backslash_group when '^' parse_caret when '$' parse_dollar when /[#\s]/ parse_extended_whitespace else parse_single_char_group(next_char) end end def parse_repeater(group) case next_char when '*' parse_star_repeater(group) when '+' parse_plus_repeater(group) when '?' parse_question_mark_repeater(group) when '{' parse_range_repeater(group) else parse_one_time_repeater(group) end end def parse_one_time_repeater(group) OneTimeRepeater.new(group) end def rest_of_string regexp_string[@current_position..-1] end def next_char regexp_string[@current_position] end def end_of_regexp next_char == ')' || @current_position >= regexp_string.length end end end
true
3c9d85a4aebc8cda06fb3f14c2d3c7a4cde2de0e
Ruby
tshepomcode/ceaser_cipher
/ceaser_cipher.rb
UTF-8
1,895
4.34375
4
[]
no_license
require 'pry' def ceaser_cipher(string, num) cipher_arr = [] # provide a-z and A-Z arrays arr_az_AZ = ("a".."z").to_a + ("A".."Z").to_a #strip string to character array string_arr = string.split("") # for each element of string, check string exists in a-z, A-Z string_arr.each.with_index do |letter, index| # puts "check if exists in a-z" # puts "#{letter}: [#{index}]" if arr_az_AZ.include?(letter) # puts "We found \"#{letter}\" at position #{arr_az_AZ.index(letter)} in a-z and A-Z" # add the shift to locate the shifted character char_pos = arr_az_AZ.index(letter) #p "char_pos = #{char_pos}" if (char_pos >= 0 && char_pos <= 25) # puts "The letter #{letter} is in small caps" char_new_pos = char_pos + num if char_new_pos > 25 char_new_pos = (char_new_pos - 25) # puts "new position is #{char_new_pos} which is letter #{arr_az_AZ[char_new_pos]}" cipher_arr[index] = arr_az_AZ[char_new_pos] else # puts "New position is #{char_new_pos} which is letter #{arr_az_AZ[char_new_pos]}" cipher_arr[index] = arr_az_AZ[char_new_pos] end elsif (char_pos >= 26 && char_pos <= 51) # puts "The letter #{letter} is in caps" char_new_pos = char_pos + num if char_new_pos > 51 char_new_pos = (char_new_pos - 51) + 25 # puts "new position is #{char_new_pos} which is letter #{arr_az_AZ[char_new_pos]}" cipher_arr[index] = arr_az_AZ[char_new_pos] else # puts "New position is #{char_new_pos} which is letter #{arr_az_AZ[char_new_pos]}" cipher_arr[index] = arr_az_AZ[char_new_pos] end end else #puts "Not a letter: #{letter}" cipher_arr << letter end end string_cipher = cipher_arr.join puts string_cipher end ceaser_cipher("What a string!", 5) # Definetly can shorten this code but I'm new to ruby ;-)
true
77354b584b9143443de964bed3bf44b9c392df59
Ruby
mvassaramo/OO-mini-project-london-web-071618
/tools/console.rb
UTF-8
1,433
2.59375
3
[]
no_license
require 'pry' require_relative '../config/environment.rb' soup_recipe = Recipe.new("soup") pasta_recipe = Recipe.new("pasta") bread_recipe = Recipe.new("bread") sandwich_recipe = Recipe.new("sandwich") lasagne_recipe = Recipe.new("lasagne") cake_recipe = Recipe.new("cake") salad_recipe = Recipe.new("salad") casey = User.new("casey") maduri = User.new("maduri") walnut = Ingredient.new("walnut") cheese = Ingredient.new("cheese") wheat = Ingredient.new("wheat") lettuce = Ingredient.new("lettuce") gluten = Ingredient.new("gluten") milk = Ingredient.new("milk") chocolate = Ingredient.new("chocolate") flour = Ingredient.new("flour") nut_allergy = Allergen.new("nut_allergy", casey, walnut) wheat_allergy = Allergen.new("wheat_allergy", maduri, wheat) gluten_allergy = Allergen.new("gluten_allergy", maduri, gluten) soup_recipecard = RecipeCard.new("soup_recipecard", casey, soup_recipe, 7, "23/10/2018") salad_recipecard = RecipeCard.new("salad_recipecard", casey, salad_recipe, 3, "12/03/2018") cake_recipecard = RecipeCard.new("cake_recipecard", casey, cake_recipe, 4, "10/09/2018") lasagne_recipecard = RecipeCard.new("lasange_recipecard", casey, lasagne_recipe, 10, "19/07/2014") lettuce_ingredient = RecipeIngredient.new("soup_recipe_ingredient", lettuce, soup_recipe) walnut_ingredient = RecipeIngredient.new("soup_recipe_ingredient", walnut, soup_recipe) ingredients_array = ["salt","pepper","salsa"] binding.pry
true
ce7d06a9a7f731149f59f4862e068bb62dbc39db
Ruby
DeveloperAlan/WDI_SYD_7_Work
/w01/d01/chris/strings.rb
UTF-8
345
3.359375
3
[]
no_license
puts "What is your first name?" first=gets.strip puts"Your first name is #{first}" puts "What is your last name?" last=gets.strip puts "Your last name is #{last}" puts "Your full name is #{first} #{last}" fullname="#{first} #{last}" puts "what is your address?" address= gets.strip puts "Your name is #{fullname} and you live at #{address}"
true
f94e6c6f42a8d9f426de8cf0d65a94a56b00914c
Ruby
sylwiavargas/Thrive-CLI
/db/seeds.rb
UTF-8
7,616
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
Directory.destroy_all Tip.destroy_all User.destroy_all Tip.create( name: "Golden Rule", category: "Ruby", title: "Use pry, don’t cry.", content: "Although pry may seem a little counter-intuitive (you may think: why would I stop my process to use pry?!?), it will save you a lot of trouble if you pry often.", how_to: "Remember to try pry outside a method and INSIDE as well if it does not work.", url: "https://tinyurl.com/y5cffgd5", user_created: "false" ) Tip.create( name: "Errors", category: "Ruby", title: "Errors are your friends.", url: "https://ruby-doc.org/core-2.2.0/Exception.html", content: "An error is nothing more than Ruby's version of open communication and constructive feedback. It tells you where it hurts!", how_to: "Do not freak out when you see the error. Just read it. And then again. Then check the file name and the line number, like here: ruby_tips.rb:9. Check the error type, like here: (NameError). Check both in your code and if that does not help - Google!", user_created: "false" ) Tip.create( name: "A variable has no name", category: "Ruby", title: "Name your variables and name them right.", content: "Simple as that: if you name your variables right, debugging and refactoring will be easy-peasy.", how_to: "Be descriptive (but not overly) so that your future self will know exactly where to look for what.\n By the way, remember that class variables have two @ signs in their name (@@), while instance variables just have one (@).", url: "https://tinyurl.com/y6ludg3o", user_created: "false" ) Tip.create( name: "And you, what is your datatype?", category: "Ruby", title: "Make sure you know what datatype your variables (and arguments) are.", content: "Imagine debugging for an hour just to later learn that the variable you passed in a method as an argument is a string, not an array.", how_to: "Call a variable with .class method (for instance: puppies_array.class) - this will tell you everything.", user_created: "false" ) # Tip.create( # name: "Hash me outside", # category: "Ruby", # title: "Don't iterate over hashes. What for? Just split them into arrays 🙄.", # user_created: "false" # ) Tip.create( name: "Floating around", category: "Ruby", title: "Remember to float when you do math.", content: "If you are getting errors on your equations, try to float the integer.", how_to: ".to_f is the method!", url: "http://ruby.bastardsbook.com/chapters/numbers/", user_created: "false" ) Tip.create( name: "Single Source of Truth", category: "Ruby", title: "I will tell the truth, the whole truth and nothing but the truth.", content: "When designing your domain in OO Ruby, make sure that every piece of data is saved JUST ONCE in ONE place.\n Other places may use this data but it should live only in one place. Otherwise you will spend hours debugging.", how_to: "Use a whiteboard A LOT, mark all the relations and try to challenge your assumptions.", url: "https://tinyurl.com/y4wb2dc7", user_created: "false" ) Tip.create( name: "Select vs map vs find vs each", category: "Ruby", title: "There is a method in this madness.", content: "Sometimes it may be difficult to choose which of the Fantastic Four methods (map, select, find, each) to use.", how_to: "1. Are you trying to choose a few elements out of an array? Select or map may be your best choice (see next steps).\n 1a. Do you have any kind of comparison (e.g. name == XYZ)? If so, you want to use select.\n 1b. If not or if you want to get a specific part of each given instance (e.g. show only names), then map.\n 2. Are you looking for the first thing that fulfills some condition? Go with find.\n 3. If any of the above satisfies you, if you are not getting the result you want to or if you are just lazy, resort to each (though remember that it shows poor character)", url: "https://tinyurl.com/y3ywcuob", user_created: "false" ) def wellness_tips html = open("https://ggia.berkeley.edu/") doc = Nokogiri::HTML(html) tips = doc.search(".article__content") #selects 12 tips links = doc.search(".article__actions") tips.map.with_index do |tip, index| new_tip = Tip.create() #create a new Tip instance new_tip.name = tip.css('h4').text new_tip.content = tip.css('p').text new_tip.category = "Wellness" new_tip.user_created = false new_tip.save! end first_name = tips.first.css('h4').text first_new_tip = Tip.where('name = ?', first_name).first first_number = first_new_tip.id-1 links.map.with_index(first_number) do |link, index| iterated_new_tip = Tip.where('id = ?', first_number+=1) iterated_new_tip[0].update(url: link.css('a').attr('href').text) end Tip.destroy_all(name: "") end Tip.create( name: "Getting job interviews in tech.", category: "Career", title: "I spent 3 months applying to jobs after a coding bootcamp. Here’s what I learned.", content: "A less-talked about part of the bootcamper's journey is what happens after you graduate — when you're searching for that six-figure developer position.", url: "https://tinyurl.com/y85k467h", user_created: "false" ) Tip.create( name: "Getting a job in 4 months.", category: "Career", title: "How to Get Your First Developer Job in 4 Months.", content: "I got my first developer job after 4 months of learning web development. It was lot of hard work but this is how I did it.", url: "https://tinyurl.com/y685wgfv", user_created: "false" ) Tip.create( name: "Coding challenges for the future.", category: "Career", title: "Your new hobby.", url: "https://codewars.com", user_created: "false" ) Tip.create( name: "Women in Tech", category: "Career", title: "Women in Tech: Software Engineer Career Advice.", content: "Is it really a man’s world when it comes to software engineering? Glancing around a Java uni lecture or checking out the engineering department at an old school software house might feel like you’ve just stepped into a secret men’s club.", url: "https://tinyurl.com/y433md22", user_created: "false" ) Tip.create( name: "Barriers to getting a job after a coding bootcamp.", category: "Career", title: "Women in Tech: Software Engineer Career Advice.", content: "What about that 22% bootcamp graduates who don’t have jobs?", url: "https://tinyurl.com/yy554hgy", user_created: "false" ) Tip.create( name: "How to get a job after a coding bootcamp.", category: "Career", title: "How to get a job after a coding bootcamp.", content: "Getting a tech job after a coding bootcamp is very possible, but not necessarily pain-free.", url: "https://tinyurl.com/y4qyhkev", user_created: "false" ) Tip.create( name: "Lessons I learned the first year after completing a coding bootcamp.", category: "Career", title: "Lessons I learned the first year after completing a coding bootcamp.", content: "the resources that have helped me become a better programmer since.", url: "https://tinyurl.com/y56go9ps", user_created: "false" ) # def ruby_tips # html = open("https://launchschool.com/books/ruby/read/arrays") # doc = Nokogiri::HTML(html) # tips = doc.css("h3") # binding.pry # # tips.map.with_index do |tip, index| # counter = 0 # new_tip = Tip.create() #create a new Tip instance # new_tip.name = tip.css('h3').text # # new_tip.content = tip.css('p').text # new_tip.category = "Ruby" # new_tip.save! # end # end # # ruby_tips # RubyTips.scraping_method_for_name.each do |tip| # tip.create(name: name, category: "Ruby") # end
true
d5a66af0b54587e525707fadcb23f86e982c35e3
Ruby
cunctat0r/my_codewars
/4 kyu/Fluent calculator/calc.rb
UTF-8
572
3.046875
3
[ "MIT" ]
permissive
class Calc OPERATIONS = { plus: '.+', minus: '.-', times: '.*', divided_by: './' }.freeze DIGITS = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, zero: 0 }.freeze def initialize @command = '' self end def method_missing(name) item = name.id2name.to_sym @command += OPERATIONS[item] if OPERATIONS[item] @command += DIGITS[item].to_s if DIGITS[item] return eval(@command) if @command =~ /^\d.*\d$/ self end end
true
2279a80f363c5f7ec4a6741b5174ff522e494a39
Ruby
Karis-T/RB139
/exercises_challenges/easy1/beer_song.rb
UTF-8
739
3.96875
4
[]
no_license
class BeerSong def self.verse(num) return verse_zero if num.zero? "#{num} bottle#{num == 1 ? nil : "s"} of beer on the wall, #{num} bottle#{num == 1 ? nil : "s"} of beer.\n" \ "Take #{num == 1 ? "it" : "one"} down and pass it around, #{num - 1 == 0 ? "no more" : num - 1} bottle#{num == 2 ? nil : "s"} of beer on the wall.\n" end def self.verse_zero "No more bottles of beer on the wall, no more bottles of beer.\n" \ "Go to the store and buy some more, 99 bottles of beer on the wall.\n" end def self.verses(num1, num2) rev_arr = (num2..num1).to_a.reverse rev_arr.map{|num| verse(num)}.join("\n") end def self.lyrics verses(99, 0) end end #puts BeerSong.lyrics
true
5a9ded715e6ac9db3b9f63ac88a54c7d8e9b3139
Ruby
jackychen6825/AA_Classwork
/W5/D3/ORM/reply.rb
UTF-8
1,592
3.0625
3
[]
no_license
require_relative 'user' require_relative 'question' require_relative 'questions_database' class Reply attr_reader :id, :parent_id, :question_id def self.find_by_user_id(user_id) data = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE user_id = ? SQL data.map { |reply| Reply.new(reply) } end def self.find_by_question_id(question_id) parent_replies = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM replies WHERE question_id = ? SQL parent_replies.map { |reply| Reply.new(reply) } end def initialize(reply_cols) @id = reply_cols['id'] @question_id = reply_cols['question_id'] @parent_id = reply_cols['parent_id'] @user_id = reply_cols['user_id'] @body = reply_cols['body'] end def child_replies data = QuestionsDatabase.instance.execute(<<-SQL, self.id) SELECT * FROM replies WHERE parent_id = ? SQL data.map { |reply| Reply.new(reply) } end def parent_reply data = QuestionsDatabase.instance.execute(<<-SQL, self.parent_id) SELECT * FROM replies WHERE id = ? SQL Reply.new(data.first) end def question data = QuestionsDatabase.instance.execute(<<-SQL, self.question_id) SELECT * FROM questions WHERE id = ? SQL Question.new(data.first) end def author data = QuestionsDatabase.instance.execute(<<-SQL, @user_id) SELECT * FROM users WHERE id = ? SQL User.new(data.first) end end
true
cb214df936d4a088d61713c77bbf94030883e997
Ruby
Jessicahh7/TTS-Code
/Ruby/loops.rb
UTF-8
221
3.484375
3
[]
no_license
how_many = 10 how_many.times do puts "Beetlejuice" end # can use this way also how_many = 10 how_many.time {puts "Beetlejuice"} # .times only works with integers # can use this also 10.times {puts "Bettlejuice"}
true
ce9b81b845e49a76a86845890c37bf89d346cb46
Ruby
blairanderson/totallycleaner
/_plugins/bannerbear.rb
UTF-8
2,386
2.65625
3
[ "MIT" ]
permissive
require 'openssl' require 'date' require 'fileutils' require 'active_support' require 'active_support/core_ext' BANNERBEAR_SIGNED_URL = "https://on-demand.bannerbear.com/signedurl/qamMwPXe2vwe2KjLgQ/image.jpg" BANNERBEAR_TAGGED_URL = "https://on-demand.bannerbear.com/taggedurl/OvKJl40B6pQkno2NDV/image.jpg" module Jekyll module BannerbearFilter def bannerbear_tag(image_url, avatar_url, author_name, date, title) #api_key: your project API key - keep this safe and non-public #base: this signed url base # photo, avatar, name, date, title options = [ "avatar---image_url~~#{CGI.escape(avatar_url)}", "name---text~~#{CGI.escape(author_name)}", "date---text~~#{CGI.escape(date)}", "title---text~~#{CGI.escape(title)}" ] options.push("photo---image_url~~#{CGI.escape(image_url)}") if image_url.present? modifications = options.join(",") #query: the query string of modifications you want to generate return BANNERBEAR_TAGGED_URL + "?modifications=[#{modifications}]" end def bannerbear_url(image_url, avatar_url, author_name, date, title) #api_key: your project API key - keep this safe and non-public api_key = ENV["BANNERBEAR_KEY"] if api_key.nil? || api_key.empty? puts "ENV['BANNERBEAR_KEY'] is blank. returning image_url" return image_url end #base: this signed url base # photo, avatar, name, date, title options = [ {"name" => "photo","image_url" => image_url}, {"name" => "avatar","image_url" => avatar_url}, {"name" => "name","text" => author_name}, {"name" => "date","text" => date}, {"name" => "title","text" => title} ] #query: the query string of modifications you want to generate query = "?#{options.to_query("m")}" #query: the query string of modifications you want to generate # query = "?m[][name]=backround&m[][image_url]=#{image_url}&m[][name]=pre_title&m[][text]=#{CGI.escape(pre_title)}&m[][name]=title&m[][text]=#{CGI.escape(title)}" #calculate the signature signature = OpenSSL::HMAC.hexdigest("SHA256", api_key, BANNERBEAR_SIGNED_URL+query) #append the signature return BANNERBEAR_SIGNED_URL + query + "&s=" + signature end end end Liquid::Template.register_filter(Jekyll::BannerbearFilter)
true
c46305cd069da1d82785e01d340031079c954f48
Ruby
jdcarey128/sweater-weather
/spec/requests/api/v1/user_registration_spec.rb
UTF-8
4,005
2.59375
3
[]
no_license
require 'rails_helper' RSpec.describe 'User Registration' do # See rails helper for defined_headers, parse_json, and define_body(*) describe 'with valid and unique credentials' do it 'responds with the created user\'s email and unique api_key' do email = 'whatever@example.com' password = 'password' body = define_body(email, password, password) post '/api/v1/users', headers: defined_headers, params: body.to_json expect(response.status).to eq 201 response_body = parse_json result = response_body[:data] attributes = result[:attributes] expect(response_body).to have_key(:data) expect(result[:type]).to eq('users') expect(result[:id]).to be_a(String) expect(result[:attributes]).to be_a(Hash) expect(attributes).to have_key(:email) expect(attributes[:email]).to eq(email) expect(attributes).to have_key(:api_key) end end describe 'error handling with invalid credentials' do it 'returns error if email is taken' do user = create(:user) # With the same email body = define_body(user.email, user.password, user.password) post '/api/v1/users', headers: defined_headers, params: body.to_json expect(response.status).to eq 400 response_body = parse_json expect(response_body[:error]).to eq 400 expect(response_body[:message]).to eq('Email has already been taken') # With alternate case email body = define_body(user.email.upcase, user.password, user.password) post '/api/v1/users', headers: defined_headers, params: body.to_json expect(response.status).to eq 400 response_body = parse_json expect(response_body[:error]).to eq 400 expect(response_body[:message]).to eq('Email has already been taken') end it 'returns an error if password fields do not match' do email = 'whatever@example.com' password = 'password' password2 = 'password2' body = define_body(email, password, password2) post '/api/v1/users', headers: defined_headers, params: body.to_json expect(response.status).to eq 400 response_body = parse_json expect(response_body[:error]).to eq 400 expect(response_body[:message]).to eq('Password confirmation doesn\'t match Password') end it 'returns an error if there is a missing field' do email = '' password = 'password' body = define_body(email, password, password) post '/api/v1/users', headers: defined_headers, params: body.to_json expect(response.status).to eq 400 response_body = parse_json expect(response_body[:error]).to eq 400 expect(response_body[:message]).to eq('Email can\'t be blank') end it 'returns an error if the request body is missing' do email = 'whatever@example.com' password = 'password' # Missing body post '/api/v1/users', headers: defined_headers expect(response.status).to eq 400 response_body = parse_json expect(response_body[:message]).to eq('Missing Email, Password, Password Confirmation in request body') # Missing email in body body = define_body(nil, password, password) post '/api/v1/users', headers: defined_headers, params: body.to_json response_body = parse_json expect(response_body[:message]).to eq('Missing Email in request body') # Missing password in body body = define_body(email, nil, password) post '/api/v1/users', headers: defined_headers, params: body.to_json response_body = parse_json expect(response_body[:message]).to eq('Missing Password in request body') # Missing password confirmation in body body = define_body(email, password, nil) post '/api/v1/users', headers: defined_headers, params: body.to_json response_body = parse_json expect(response_body[:message]).to eq('Missing Password Confirmation in request body') end end end
true
491071a48d29d486ed12ef5e7ff0b8f60631929b
Ruby
mattladany/advent-of-code
/2019/12-01/fuel_calculator.rb
UTF-8
280
3.375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby total_fuel = 0 file = File.open("mass-input", "r") file.each_line { |mass| current_mass = mass.to_i loop do current_mass = current_mass / 3 - 2 break if current_mass <= 0 total_fuel += current_mass end } puts total_fuel
true
ab70a722d5d80c3be60d43baa77d6f22e786372f
Ruby
Rustam-ki/ruby-projects
/3/train.rb
UTF-8
1,179
3.421875
3
[]
no_license
# frozen_string_literal: true class Train attr_reader :number, :type, :route attr_accessor :station, :speed, :count def initialize(number, type, count) @number = number @type = type @count = count @speed = 0 end def raise_speed(speed) self.speed += speed end def raise_back(_speed_back) self.speed -= speed end def stop self.speed = 0 end def add_carriage self.count += 1 if self.speed.zero? end def delete_carriage self.count -= 1 if self.speed.zero? end def route=(route) @route = route self.station = self.route.stations.first end def next_station route.stations[route.stations.index(station) + 1] end def previous_station route.stations[route.stations.index(station) - 1] if route.stations[route.stations.index(station)] != 0 end def move_previous_station if route.stations[route.stations.index(station)] != 0 self.station = route.stations[route.stations.index(station) - 1] end end def move_next_station if route.stations[route.stations.index(station) + 1] self.station = route.stations[route.stations.index(station) + 1] end end end
true
da70d8a03864e5c5109822646fdea70fa5e7f046
Ruby
sw-contact/LS
/small_problems/easy3/xor.rb
UTF-8
236
3.125
3
[]
no_license
def xor?(bool1, bool2) return true if (bool1 && !bool2) return true if (bool2 && !bool1) false end p xor?(5.even?, 4.even?) == true p xor?(5.odd?, 4.odd?) == true p xor?(5.odd?, 4.even?) == false p xor?(5.even?, 4.odd?) == false
true
3fad29395f76fb5b1d8211ce75106479ecf3972e
Ruby
ypylypenko/algorithmable
/lib/algorithmable/graphs/traversals/depth_first.rb
UTF-8
1,042
2.859375
3
[ "MIT" ]
permissive
module Algorithmable module Graphs module Traversals class DepthFirst include Algorithmable::Graphs::Traversals::Errors def initialize(graph, source) @visited = [] @edge_to = [] @source = source traverse graph, source end def visited?(vertex) @visited[vertex] end def path_to(vertex) fail UnvisitedVertexError, vertex unless visited?(vertex) path = [] finish = vertex while finish != @source path.push finish finish = @edge_to[finish] end path.push @source path end private def traverse(graph, vertex) @visited[vertex] = true graph.adjacency(vertex).each do |neighbour_vertex| unless visited? neighbour_vertex @edge_to[neighbour_vertex] = vertex traverse graph, neighbour_vertex end end end end end end end
true
5c39028158936510e26dffa4bca48d900acde430
Ruby
afleones/box2share
/app/workflows/creates_paid_plan.rb
UTF-8
882
2.546875
3
[]
no_license
class CreatesPaidPlan attr_accessor :remote_id, :name, :price_cents, :interval, :interval_count, :space_allowed, :plan def initialize(remote_id:, name:, price_cents:, interval:, interval_count:, space_allowed:) @remote_id = remote_id @name = name @price_cents = price_cents @interval = interval @interval_count = interval_count @space_allowed = space_allowed end def run remote_plan = Stripe::Plan.create( id: remote_id, amount: price_cents, currency: "eur", interval: interval, interval_count: interval_count, product: "box2share", nickname: name) self.plan = Plan.create( remote_id: remote_plan.id, name: name, price_cents: price_cents, interval: interval, interval_count: interval_count, space_allowed: space_allowed, status: :active, type: 'PaidPlan') end end
true
b4cdc6e38c87814e188ff3ea65ae8b6ae13b5124
Ruby
nguyenthuan155632/jmap-api
/app/controllers/inquiry_controller.rb
UTF-8
2,013
2.65625
3
[]
no_license
class InquiryController < ApplicationController def create # res_hash = chk_value(params) # unless res_hash[:is_success] then # if res_hash[:failed_code] == 0 then # output = create_json(code: 102, message: "パラメータの値が不正です。") # render :json => output # return # end # end # jsonのパーツとなるinfoハッシュを作成 begin info = insert_data(params) # info = { # status: 0, # message: params[:emailaddress], # msg: params[:content] # } rescue => err output = create_json(code: 501, message: err.to_s)#"DB処理に失敗しました。") render :json => output return end # jsonの元になるハッシュを作成し、出力して終了 output = create_json(info: info) render :json => output return end ##chk_value private def chk_value(vals) unless vals[:emailaddress] then res_hash = { is_success: false, failed_code: 1 } return res_hash end if vals[:emailaddress] == '' then res_hash = { is_success: false, failed_code: 1 } return res_hash end unless vals[:content] then res_hash = { is_success: false, failed_code: 1 } return res_hash end if vals[:content] == '' then res_hash = { is_success: false, failed_code: 1 } return res_hash end end private def insert_data(vals) inq = Inquiry.new inq.emailaddress = vals[:emailaddress] inq.content = vals[:content] if inq.save! info = { status: 0, message: 'saved.' } return info end end private def create_json(args = {}) args = { code: 0, message: '取得しました。', info: {} }.merge(args) output = { response: args } return output end end
true
bbf3256f696ec2084a7d1d25dfb2a4ada9cb2d02
Ruby
harryuan65/RubyOnStimulants
/app/controllers/excel_controller.rb
UTF-8
5,908
2.515625
3
[]
no_license
class ExcelController < ApplicationController def index @uploads = [] Dir.new(Global::CSV_UPLOAD_PATH).each do |file| if file.end_with?(".csv") @uploads.push(file) end end @uploads= @uploads.sort_by{|str| str.split('_')[0].to_i} @exports=[] check_exports Dir.new(Global::CSV_EXPORT_PATH).each do |file| if file.end_with?(".csv") @exports.push(file) end end @exports = @exports.sort_by{|str| str.split('_')[0].to_i} end def upload uploaded_io = params[:csv_file] @uploads = [] Dir.new(Global::CSV_UPLOAD_PATH).each do |file| if file.end_with?(".csv") @uploads.push(file) end end begin File.open(Rails.root.join(Global::CSV_UPLOAD_PATH, @uploads.size.to_s+"_"+uploaded_io.original_filename.gsub(' ','_')), 'wb') do |file| file.write(uploaded_io.read) end puts("Uploaded "+uploaded_io.original_filename) redirect_to action:'index' rescue=>exception puts(exception) end end def show_csv begin @file_name = params[:file_io] @file_path = get_full_csv_path @file_name @hash_arr = read_hash_from @file_name, false @longest_hash = @hash_arr.max_by(&:length) # @hash_arr = @hash_arr.delete_if{|hash| hash[:country]=="Papua New Guinea" } 這是array of hash 可以用 @hash_arr = @hash_arr.delete_if{|hash| hash["country"]=="Papua New Guinea"} rescue=>exception flash[:alert] = exception.to_s render 'shared/result',locals:{status:false, message:"抱歉,把下面的貼給我",error: exception.to_s} end end def processed_csv # begin @file_name = params[:file_io] @hash_arr = read_hash_from @file_name, false @africa = africa_arr @matched = filter_af @hash_arr @longest_hash = @matched.max_by(&:length) @missing = find_missing @matched @matched = fill_empty @matched @matched = @matched.sort_by{|hash| hash["country_code"]} # rescue=>exception # flash[:alert] = exception.to_s # render 'shared/result',locals:{status:false, message:"抱歉,把下面的貼給我",error: exception.to_s} # end end def export_filter_africa # begin @file_name = params[:file_io] @hash_arr = read_hash_from @file_name, false @africa = africa_arr @matched = filter_af @hash_arr @longest_hash = @matched.max_by(&:length) @matched = fill_empty @matched @matched = @matched.sort_by{|hash| hash["country_code"]} filename = export_africa @matched, params[:file_io] flash[:notice] = "成功輸出了 #{filename}" redirect_to action:'index' # rescue=>exception # return render 'shared/result',locals:{status:false, message:"抱歉他怪怪的,把下面的貼給我",error: exception.to_s} # end end def filter_af hash_arr final_arr = [] hash_arr.each do |hash| africa_arr().each do |countryItem| if /#{countryItem[0]}/.match(hash["country"]) hash["country_code"] = countryItem[1] new_hash = {:no=>countryItem[2]}.merge(hash) final_arr.push(new_hash) break end end end final_arr = final_arr.delete_if{|hash| hash["country"]=="Papua New Guinea" } return final_arr end def find_missing hash_arr recording = Hash.new missing = [] africa_arr().each do |pair| recording["#{pair[1]}"] = false end hash_arr.each do |hash| recording["#{hash["country_code"]}"]=true end africa_hashes = africa_arr().map{ |e| [e[0],e[1]] }.to_h.invert recording.each do |k,v| if !v missing.push(africa_hashes["#{k}"].gsub('.*',' ')) end end # puts '============================' # puts missing # puts '============================' return missing.sort end def fill_empty hash_arr current_codes = hash_arr.map{|hash| hash["country_code"]} africa_arr().each do |e| if current_codes.exclude?(e[1]) hash = {"no"=>e[2], "country"=>e[0].gsub('.*',' '), "country_code"=>e[1],"empty"=>"這個資料沒有這個國家"} hash_arr.push(hash) puts hash end end return hash_arr end def africa_arr [ ["Angola","AGO",1], ["Burundi","BDI",2], ["Benin","BEN",3], ["Burkina.*Faso","BFA",4], ["Botswana","BWA",5], ["Central.*African.*Republic","CAF",6], ["Ivoire","CIV",7], ["Cameroon","CMR",8], [".*Congo.*Dem.*","COD",9], ["Congo","COG",10], ["Comoros","COM",11], ["Cape.*Verde","CPV",12], ["Djibouti","DJI",13], ["Algeria","DZA",14], ["Egypt","EGY",15], ["Eritrea","ERI",16], ["Ethiopia","ETH",17], ["Gabon","GAB",18], ["Ghana","GHA",19], ["Guinea","GIN",20], ["Gambia","GMB",21], ["Guinea.*Bissau","GNB",22], ["Equatorial.*Guinea","GNQ",23], ["Kenya","KEN",24], ["Liberia","LBR",25], ["Libya","LBY",26], ["Lesotho","LSO",27], ["Morocco","MAR",28], ["Madagascar","MDG",28], ["Mali","MLI",30], ["Mozambique","MOZ",31], ["Mauritania","MRT",32], ["Mauritius","MUS",33], ["Malawi","MWI",34], ["Namibia","NAM",35], ["Niger","NER",36], ["Nigeria","NGA",37], ["Rwanda","RWA",38], ["Sudan","SDN",39], ["Senegal","SEN",40], ["Sierra.*Leone","SLE",41], ["Somalia","SOM",42], ["South.*Sudan","SSD",43], [".*Sao.*Tome.*Principe.*","STP",44], ["Swaziland","SWZ",45], ["Eswatini","SWZ",45], ["Seychelles","SYC",46], ["Chad","TCD",47], ["Togo","TGO",48], ["Tunisia","TUN",49], ["Tanzania","TZA",50], ["Uganda","UGA",51], ["South.*Africa","ZAF",52], ["Zambia","ZMB",53], ["Zimbabwe","ZWE",54] ].sort_by{|element| element[0].length}.reverse end end
true
d1e247d7077676731848ebff3de155928e20a855
Ruby
yurak/fanta
/app/helpers/tours_helper.rb
UTF-8
359
2.890625
3
[]
no_license
module ToursHelper def time_to_deadline(time_hash) return '' if time_hash.blank? time_str = '' time_str += "#{time_hash[:days]}d " if time_hash[:days]&.positive? time_str += "#{time_hash[:hours]}h " if time_hash[:hours]&.positive? time_str += "#{time_hash[:minutes]}m " if time_hash[:minutes]&.positive? "#{time_str}left" end end
true
e827e29a9c5defe6490422bacfd6ba0956837dfc
Ruby
ryanjjosh/Ruby
/team.rb
UTF-8
450
3.796875
4
[]
no_license
#team.rb class Team include Enumerable # LOTS of functionality attr_accessor :name, :players def initialize (name) @name = name @players = [] end def add_players (*players) # splat @players += players end def to_s "#{@name} Team: #{@players.join(",")}" end def each @players.each { |player| yield player } end end #groundhogs = Team.new("The Groundhogs") #groundhogs.add_players("Jeremy", " Jordan", " Jamal") #puts groundhogs
true
a70fecc69b2f8e83c3b82a6d503b5cb34afbc15f
Ruby
baezanat/Launch_School_bootcamp
/RB_100/Introduction_to_Programming/loops_and_iterators/conditional_loop.rb
UTF-8
53
2.6875
3
[]
no_license
i = 0 loop do i += 2 puts i if i == 10 break end end
true
be611874bc7469dead53ac4217a95594f9eef21b
Ruby
lachie/oang_orig
/app/models/party.rb
UTF-8
465
2.578125
3
[]
no_license
class Party < ActiveRecord::Base has_many :members named_scope :named, lambda {|name| {:conditions => ['lower(name) = lower(?)',name]} } before_validation :strip_name def self.import!(party_name) @parties ||= {} party_name.downcase! if party = @parties[party_name] party else @parties[party_name] = create!(:name => party_name) end end protected def strip_name self.name = name.gsub(/\s+party/i,'') end end
true
4ff28ed1aab26ee7d38d85947304c30dc6055e97
Ruby
K-Sato1995/ruby_dojo
/Object/methods.rb
UTF-8
494
3.0625
3
[]
no_license
# Methods a = 'string' ## methods puts '============ALL=============' puts a.methods # % * + to_c unicode_normalize unicode_normalize! .......etc ## private_methods puts '============PRIVATE=============' puts a.private_methods ## protected_methods puts '============PROTECTED=============' puts a.protected_methods ## public_methods puts '==============PUBLIC==============' puts a.public_methods ## singleton_methods puts '==============SINGLETON=============' puts a.singleton_methods
true