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
fa772d6fb6768cbc7c007c738d2af1c4548520cf
Ruby
kivanio/brcobranca
/lib/brcobranca/remessa/cnab400/banrisul.rb
UTF-8
9,828
2.53125
3
[ "BSD-3-Clause", "MIT" ]
permissive
# frozen_string_literal: true module Brcobranca module Remessa module Cnab400 class Banrisul < Brcobranca::Remessa::Cnab400::Base attr_accessor :convenio validates_presence_of :agencia, :convenio, :sequencial_remessa, message: 'não pode estar em branco.' validates_length_of :agencia, maximum: 4, message: 'deve ter 4 dígitos.' validates_length_of :sequencial_remessa, maximum: 7, message: 'deve ter 7 dígitos.' validates_length_of :convenio, maximum: 13, message: 'deve ter 13 dígitos.' validates_length_of :carteira, maximum: 1, message: 'deve ter 1 dígito.' def agencia=(valor) @agencia = valor.to_s.rjust(4, '0') if valor end def convenio=(valor) @convenio = valor.to_s.rjust(13, '0') if valor end def sequencial_remessa=(valor) @sequencial_remessa = valor.to_s.rjust(7, '0') if valor end def info_conta codigo_cedente.ljust(20, ' ') end def cod_banco '041' end def nome_banco 'BANRISUL'.ljust(15, ' ') end def complemento ''.rjust(294, ' ') end def codigo_cedente convenio end def digito_nosso_numero(nosso_numero) nosso_numero.duplo_digito end # Header do arquivo remessa # # @return [String] # def monta_header # CAMPO TAMANHO VALOR # tipo do registro [1] 0 # operacao [1] 1 # literal remessa [7] REMESSA # brancos [16] # info. conta [20] # empresa mae [30] # cod. banco [3] # nome banco [15] # data geracao [6] formato DDMMAA # complemento registro [294] # num. sequencial [6] 000001 "01REMESSA #{info_conta}#{empresa_mae.format_size(30)}#{cod_banco}#{nome_banco}#{data_geracao}#{complemento}000001" end def monta_detalhe(pagamento, sequencial) raise Brcobranca::RemessaInvalida, pagamento if pagamento.invalid? detalhe = '1' # identificação do registro 9[01] 001 a 001 detalhe += ''.rjust(16, ' ') # brancos 9[16] 002 a 017 detalhe << codigo_cedente.rjust(13, ' ') # código do cedente X[13] 018 a 030 detalhe << ''.rjust(7, ' ') # brancos X[07] 031 a 037 detalhe << pagamento.documento_ou_numero.to_s.ljust(25, ' ') # num. controle X[25] 038 a 062 detalhe << pagamento.nosso_numero.to_s.rjust(8, '0') # identificação do título (nosso número) 9[08] 063 a 070 detalhe << digito_nosso_numero(pagamento.nosso_numero) # dígitos de conferência do nosso número (dv) 9[02] 071 a 072 detalhe << ''.rjust(32, ' ') # mensagem no bloqueto X[32] 073 a 104 detalhe << ''.rjust(3, ' ') # brancos X[03] 105 a 107 detalhe << carteira # carteira 9[01] 108 a 108 detalhe << pagamento.identificacao_ocorrencia # identificacao ocorrencia 9[02] 109 a 110 detalhe << pagamento.documento_ou_numero.to_s.ljust(10, ' ') # numero do documento alfanum. X[10] 111 a 120 detalhe << pagamento.data_vencimento.strftime('%d%m%y') # data de vencimento 9[06] 121 a 126 detalhe << pagamento.formata_valor # valor do titulo 9[13] 127 a 139 detalhe << cod_banco # banco encarregado 9[03] 140 a 142 detalhe << ''.rjust(5, ' ') # agencia depositaria (brancos) 9[05] 143 a 147 detalhe << '08' # especie do titulo 9[02] 148 a 149 detalhe << 'N' # identificacao (sempre N) X[01] 150 a 150 detalhe << pagamento.data_emissao.strftime('%d%m%y') # data de emissao 9[06] 151 a 156 detalhe << codigo_primeira_instrucao(pagamento) # 1a instrucao 9[02] 157 a 158 detalhe << pagamento.cod_segunda_instrucao # 2a instrucao 9[02] 159 a 160 detalhe << tipo_mora(pagamento) # tipo de mora (diária ou mensal) 9[13] 161 a 161 detalhe << formata_valor_mora(12, pagamento) # mora 9[13] 162 a 173 detalhe << pagamento.formata_data_desconto # data desconto 9[06] 174 a 179 detalhe << pagamento.formata_valor_desconto # valor desconto 9[13] 180 a 192 detalhe << pagamento.formata_valor_iof # valor iof 9[13] 193 a 205 detalhe << pagamento.formata_valor_abatimento # valor abatimento 9[13] 206 a 218 detalhe << pagamento.identificacao_sacado # identificacao do pagador 9[02] 219 a 220 detalhe << pagamento.documento_sacado.to_s.rjust(14, '0') # cpf/cnpj do pagador 9[14] 221 a 234 detalhe << pagamento.nome_sacado.format_size(35) # nome do pagador 9[35] 235 a 269 detalhe << ''.rjust(5, ' ') # brancos 9[05] 270 a 274 detalhe << pagamento.endereco_sacado.format_size(40) # endereco do pagador X[40] 275 a 314 detalhe << ''.rjust(7, ' ') # brancos X[07] 315 a 321 detalhe << formata_percentual_multa(pagamento) # percentual multa X[02] 322 a 324 detalhe << '00' # num.dias para a multa após o vencimento 9[02] 325 a 326 detalhe << pagamento.cep_sacado # cep do pagador 9[08] 327 a 334 detalhe << pagamento.cidade_sacado.format_size(15) # cidade do pagador 9[15] 335 a 349 detalhe << pagamento.uf_sacado # uf do pagador 9[02] 350 a 351 detalhe << '0000' # taxa ao dia para pag. antecipado 9[04] 352 a 355 detalhe << ' ' # branco 9[01] 356 a 356 detalhe << ''.rjust(13, '0') # valor para cálc. do desconto 9[13] 357 a 369 detalhe << pagamento.dias_protesto.to_s.rjust(2, '0') # dias para protesto 9[02] 370 a 371 detalhe << ''.rjust(23, ' ') # brancos X[23] 370 a 394 detalhe << sequencial.to_s.rjust(6, '0') # numero do registro do arquivo 9[06] 395 a 400 detalhe end def monta_trailer(sequencial) trailer = '9' trailer += ''.rjust(26, ' ') # brancos X[26] 002 a 027 trailer << valor_titulos_carteira(13) # total geral/valores dos títulos 9[13] 028 a 040 trailer << ''.rjust(354, ' ') # brancos X[354] 041 a 394 trailer << sequencial.to_s.rjust(6, '0') # sequencial 9[06] 395 a 400 trailer end private def codigo_primeira_instrucao(pagamento) return '18' if pagamento.percentual_multa.to_f > 0.00 pagamento.cod_primeira_instrucao end def tipo_mora(pagamento) return ' ' if pagamento.tipo_mora == '3' pagamento.tipo_mora end def formata_percentual_multa(pagamento) raise ValorInvalido, 'Deve ser um Float' unless /\./.match?(pagamento.percentual_multa.to_s) format('%.1f', pagamento.percentual_multa).delete('.').rjust(3, '0') end def formata_valor_mora(tamanho, pagamento) return ''.rjust(tamanho, ' ') if pagamento.tipo_mora == '3' pagamento.formata_valor_mora(tamanho) end end end end end
true
7fe2bfd6f3877c7666b070946d58fbe3fef25484
Ruby
gllluch/speller
/lib/speller.rb
UTF-8
654
2.6875
3
[]
no_license
require_relative 'speller\HTTPClient' require_relative 'speller\spell' require 'JSON' module Speller URL = 'http://speller.yandex.net/services/spellservice.json/checkText?text=' def self.do text @text = text @respons = HTTPClient.new.get(URL, text) Spell.new(@text, @respons) end end text = 'Преветствую тебя, пустынный уголок, Приют спокойствия, трудов и вдахновенья, Где льется дней моих нивидимый поток На лоне счатья и зобвенья. ' respons = Speller.do text puts respons, respons.show_mistakes
true
d6b2fdbb4e4efcdd9f89ed30300925d64c834400
Ruby
bonzouti/Ruby
/exo_09.rb
UTF-8
173
3.328125
3
[]
no_license
puts "Quel votre prénom ?" print ">" user_name = gets.chomp puts "Quel est votre nom ?" print ">" familly_name = gets.chomp puts " Bonjour, #{user_name},#{familly_name }!"
true
3787f5606700d72e77ff520753bb4d2428fac91a
Ruby
brandoshmando/OOP
/people.rb
UTF-8
710
4.34375
4
[]
no_license
class Person def initialize(name) @name = name end def greeting puts "Hello, my name is #{@name}!" end end class Student < Person def learn puts "I get it!" end end class Instructor < Person def teach puts "Everything in Ruby is an object!" end end instructor = Instructor.new("Chris") instructor.greeting instructor.teach instructor.learn student = Student.new("Cristina") student.greeting student.learn student.teach # These last two calls do not work because methods being called on each of the objects # are not local to the classes they are called on. You are able to call methods # from the person class because both the Instructor and Student classes inherit # from Person.
true
20bbbe1b2ab61b5f9f3f78254853647d7c59413b
Ruby
ManageIQ/manageiq-smartstate
/lib/metadata/util/event_log_filter.rb
UTF-8
2,102
2.75
3
[ "Apache-2.0" ]
permissive
module EventLogFilter def self.prepare_filter!(filter) raise ArgumentError, "filter must be a Hash" unless filter.kind_of?(Hash) filter[:rec_count] = 0 if filter[:rec_count].nil? filter[:num_days] = 0 if filter[:num_days].nil? filter[:generated] = (Time.now.utc - filter[:num_days] * 86400).iso8601 unless filter[:num_days] == 0 filter[:level] = filter[:level].to_s.strip.downcase filter[:level] = filter[:level].empty? ? :warn : filter[:level].to_sym filter[:level] = :warn unless [:error, :warn, :info].include?(filter[:level]) [:message, :source].each do |k| filter[k].strip! unless filter[k].nil? filter[k] = nil if filter[k] == '' unless filter[k].nil? first = filter[k][0, 1] last = filter[k][-1, 1] filter[k] = if first == '"' && last == '"' # Double quotes surrounding provide exact match Regexp.new("^\\s*#{Regexp.escape(filter[k][1..-2])}\\s*$", Regexp::IGNORECASE) elsif first == '/' && last == '/' # Forward slashes surrounding provide regex match Regexp.new(filter[k][1..-2], Regexp::IGNORECASE) else # Neither surrouding provides substring match Regexp.new(Regexp.escape(filter[k]), Regexp::IGNORECASE) end end end filter end def self.filter_by_level?(level, filter) case filter[:level] when :info then false when :warn then !['warn', 'error'].include?(level.to_s) when :error then 'error' != level.to_s else false end end def self.filter_by_generated?(generated, filter) filter[:generated] && generated < filter[:generated] end def self.filter_by_source?(source, filter) filter[:source] && source !~ filter[:source] end def self.filter_by_message?(message, filter) filter[:message] && message !~ filter[:message] end def self.filter_by_rec_count?(rec_count, filter) filter[:rec_count] > 0 && rec_count >= filter[:rec_count] end end
true
d17c155057640b8c7be93af95cc6166a23b8f8c6
Ruby
DCR430/programming-univbasics-4-crud-lab-nyc01-seng-ft-051120
/lib/array_crud.rb
UTF-8
833
3.65625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def create_an_empty_array array=[] end def create_an_array array=["oliver","gloria","daniel","platty"] end def add_element_to_end_of_array(array, element) array << ("arrays!") end def add_element_to_start_of_array(array, element) array.unshift ("wow") end def remove_element_from_end_of_array(array) arrays_array = array.pop end def remove_element_from_start_of_array(array) arrays_array = array.shift end def retrieve_element_from_index(array, index_number) array=["am","gloria","daniel"] array [0] end def retrieve_first_element_from_array(array) array=["wow","gloria","daniel"] array [0] end def retrieve_last_element_from_array(array) array=["wow","gloria","arrays!"] array [2] end def update_element_from_index(array, index_number, element) array=["wow","gloria","arrays!"] array[2] = "totally" end
true
75c6cd0af55e7893472d1b3914bbccd631143574
Ruby
waffle-iron/mysore_city_bus
/scrap.rb
UTF-8
956
2.65625
3
[]
no_license
require 'net/http' require 'open-uri' require 'nokogiri' require 'pry' require 'json' require 'active_support/all' require 'active_support/core_ext/hash/conversions' # uri = URI.parse('http://mitra.ksrtc.in/MysoreMBus/rtemap.jsp') # uri = fetch("http://www.somewebsite.com/hahaha/") uri = "http://mitra.ksrtc.in/MysoreMBus/rtemap.jsp" # a=Net::HTTP.get(uri) bus_details = Nokogiri::HTML(open(uri)) # p "no of buses #{bus_details.css('#country option').count}" bus_list = [] bus_details.css('#country option').each do |bus| bus_list << bus.children.text p bus.children.text end route_hash = {} bus_list.each do |bus| bus_stops = [] uri = "http://mitra.ksrtc.in/MysoreMBus/rtemap.jsp?count="+bus out = Nokogiri::HTML(open(uri)).css("td").children.each do |bus_stop| bus_stops << bus_stop.text end route_hash[bus]=bus_stops.reject { |c| c.empty? } p "route --> #{route_hash[bus]}" end File.open("file.txt","w") do |f| f.write(route_hash) end
true
b2d493b5c9fd97a2a394f0481fea0c496d5fb4a3
Ruby
Jstuff36/InterviewPractice
/AppAcademySkypeInterviewRuby/is_prime?.rb
UTF-8
212
3.5
4
[]
no_license
def is_prime?(num) return false if num < 2 #only numbers greater than 1 can be prime return true if num == 2 #only even prime (2...num).each do |i| return false if num % i == 0 end true end p is_prime?(4)
true
86f1c314cfaccb54605a9dd8fe95a6cf809a0adc
Ruby
taylorthurlow/rubygame
/entities/tile_collider.rb
UTF-8
1,078
3.078125
3
[]
no_license
class TileCollider < Collider attr_accessor :tile def initialize(x, y, width, height, tile = nil) super(width, height) @x = x @y = y @tile = tile end def pos_x box[0] end def pos_y box[1] end def center [@tile.pos_x + @x + @width / 2, @tile.pos_y + @y + @height / 2] end def box [ @tile.pos_x + @x, @tile.pos_y + @y, # top left @tile.pos_x + @x + @width, @tile.pos_y + @y, # top right @tile.pos_x + @x + @width, @tile.pos_y + @y + @height, # bottom right @tile.pos_x + @x, @tile.pos_y + @y + @height, # bottom left ] end def draw_bounding_box Utils.draw_box(@tile.pos_x + @x, @tile.pos_y + @y, @width, @height, 0xB0_FF00FF) Utils.draw_box(center[0] - 1, center[1] - 1, 2, 2, 0xFF_00FF00) end def to_s "#{super} - #{@tile.name}" end def self.new_from_json(collider) TileCollider.new(collider["x"], collider["y"], collider["width"], collider["height"]) end end
true
023653300c60f195811a04b133d184c7f59bacf9
Ruby
kaxla/portfolio
/test/features/posts/edit_post_test.rb
UTF-8
2,377
2.53125
3
[ "MIT" ]
permissive
require "test_helper" feature "Edit a Post" do #--------------INDEX PAGE------------------ scenario "editor can edit a post from index page" do sign_in(:editor) visit posts_path page.find("tbody tr:last").click_on "Edit" fill_in "Body", with: posts(:unpublished).body click_button "Update Post" page.text.must_include posts(:published).title page.text.must_include posts(:unpublished).body end scenario "author can edit a post from index page" do sign_in(:author) visit posts_path page.find("tbody tr:last").click_on "Edit" fill_in "Body", with: posts(:unpublished).body click_button "Update Post" page.text.must_include posts(:published).title page.text.must_include posts(:unpublished).body end scenario "user can't edit a post from index page" do sign_in(:user) visit posts_path page.text.wont_include "Edit" end scenario "not signed in can't edit a post from index page" do visit posts_path page.text.wont_include "Edit" end #---------------SHOW PAGE----------------- # scenario "editor can edit something from show page" do # # Given an existing post with an edit link # sign_in(:editor) # visit post_path(posts(:one)) # # When I fill form and submit edits # click_on "Edit" # fill_in "Body", with: posts(:two).body # click_button "Update Post" # # Then The post should update and show confirmation # page.text.must_include posts(:one).title # page.text.must_include posts(:two).body # end # scenario "an author can edit something from an existing post from show page" do # # Given an existing post with an edit link # sign_in(:author) # visit post_path(posts(:one)) # # When I fill form and submit edits # click_on "Edit" # fill_in "Body", with: posts(:two).body # click_button "Update Post" # # Then The post should update and show confirmation # page.text.must_include posts(:one).title # page.text.must_include posts(:two).body # end # scenario "a user can't edit posts from show page" do # # Given a signed in user # sign_in(:user) # # When they visit a specific post # visit post_path(posts(:one)) # # I can't see an edit link # page.text.wont_include "Edit" # end # scenario "not signed in can't edit post from show page" do # end end
true
67e826b0ae7c5312bb972ef20a0ab8714d6ebf48
Ruby
estherkimyunjung/ruby-oo-fundamentals-instance-variables-lab-hou01-seng-ft-042020
/lib/dog.rb
UTF-8
163
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Dog def name=(dog_name) @this_dogs_name = dog_name end def name @this_dogs_name end end lassis = Dog.new lassis.name = "Lassie" lassis.name
true
e21b9db267131df8db1b74821b3f48ba523f085f
Ruby
madking55/LS-IntroToProgrammingWithRuby
/Basics/3.rb
UTF-8
110
3.078125
3
[]
no_license
movies = {First: 1975, Second: 2014, Third: 2005} puts movies[:First] puts movies[:Second] puts movies[:Third]
true
c416475f66a586a1fd40d25ab932d9ae8156b946
Ruby
benatkin/hurl
/app/helpers/pretty_printing.rb
UTF-8
1,586
2.671875
3
[ "MIT" ]
permissive
module Hurl module Helpers # Pretty printing of content types for the response div. module PrettyPrinting def pretty_print(type, content) type = type.to_s if type =~ /json|javascript/ pretty_print_json(content) elsif type == 'js' pretty_print_js(content) elsif type.include? 'xml' pretty_print_xml(content) elsif type.include? 'html' colorize :html => content else content.inspect end end def pretty_print_json(content) json = Yajl::Parser.parse(content) pretty_print_js Yajl::Encoder.new(:pretty => true).encode(json) end def pretty_print_js(content) colorize :js => content end def pretty_print_xml(content) out = StringIO.new doc = REXML::Document.new(content) doc.write(out, 2) colorize :xml => out.string end def pretty_print_headers(content) lines = content.split("\n").map do |line| if line =~ /^(.+?):(.+)$/ "<span class='nt'>#{$1}</span>:<span class='s'>#{$2}</span>" else "<span class='nf'>#{line}</span>" end end "<div class='highlight'><pre>#{lines.join}</pre></div>" end # accepts an array of request headers and formats them def pretty_print_requests(requests = [], fields = []) headers = requests.map do |request| pretty_print_headers request end headers.join + fields.join('&') end end end end
true
434685198caf845eb55f6ffca43ef0670d122d4c
Ruby
dayatroman79/raaws
/spec/request_spec.rb
UTF-8
3,350
2.53125
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + '/spec_helper.rb' describe RAAWS::Request do describe "PARAMS workflow" do before(:each) { @request = RAAWS::Request.new } it "adds new values to params" do @request.params = {:title => "Modern Times"} @request.params[:title].should == "Modern Times" end it "updates params" do @request.params = {:author => "Charlie Chaplin"} @request.params = {:author => "Buster Keaton"} @request.params[:author].should == "Buster Keaton" end it "adds a timestamp to params" do @request.add_timestamp_to_params({:title => "Kid"})[:timestamp]. should match(Regexp.new(Time.now.year.to_s)) end it "camelizes params keys" do @request.camelize_params({:access_key => "chaplin", :title => "Kid"}). should == {"AccessKey" => "chaplin", "Title" => "Kid"} end it "encodes params values" do @request.encode_params({ :timestamp => "2009-09-22T12:05:39+02:00", :title => "Modern Times" }).should == { :title=>"Modern%20Times", :timestamp=>"2009-09-22T12%3A05%3A39%2B02%3A00" } end it "sorts params byte wise (not alphabetically) for signature" do #%w(AWS Z Author ).sort_by { |s| s.downcase }.should == %w(Author AWS Z) @request.sort_params({"ZZ" => "bla", "AWS" => "123", "Author" => "chap" }). should == [["Author", "chap"], ["AWS", "123"], ["ZZ", "bla"]] end end describe "URLString workflow" do before(:each) do @request = RAAWS::Request.new @params = [["author", "chaplin"], ["title", "kid"]] end it "creates an url string from params" do @request.params_to_string(@params).should == "author=chaplin&title=kid" end it "creates the signature string from params" do @request.string_for_signature("author=chaplin&title=kid"). should == "GET\nwebservices.amazon.com\n/onca/xml\nauthor=chaplin&title=kid" end it "creates the signature" do str_sign = @request.string_for_signature("author=chaplin&title=kid") @request.signature(str_sign).should == "luIKHpS4nH7oJH7qthiFqFn+b1bgqSZ2biRNEXC5sd8=" end it "encodes properly the signature" do @request.url_encode("luIKHpS4nH7oJH7qthiFqFn+b1bgqSZ2biRNEXC5sd8="). should == "luIKHpS4nH7oJH7qthiFqFn%2Bb1bgqSZ2biRNEXC5sd8%3D" end end describe "URI" do before(:each) do @request = RAAWS::Request.new({:title => "Modern Times"}) end it "has a preset of params on initialisation" do pending @request.params.should == {} end it "processes params" do pending @request.process_params.should be_a(Hash) @request.process_params.should == "" end #just to check it works give it should == "" to see it "processes url string" do pending @request.process_url_string.should == "" end it "has the final url address" do @request.params= { :operation => "ItemSearch", :search_index => "DVD", :response_group => "Small"} @request.uri.should == "" end it "gets an xml file from amazon" do @request.params= {:search_index => "DVD", :operation => "ItemSearch", :response_group => "Small"} @request.get.read.should == "" end end end
true
41a0271059fcd1ae4cb69029767989815ffb5931
Ruby
quentin6440/QS2J3_dossier
/lib/01_pyramids.rb
UTF-8
580
3.65625
4
[]
no_license
def ask_storeys puts "Yo ! Like pyramids huh, How many storeys you want bru ? Only odd numbers accepted" print ">" str_nb = gets.chomp.to_i if str_nb%2 !=0 return str_nb else puts "Un nombre impair on te dit !!" end end def wtf_pyramid (str_nb) str_h = str_nb / 2 puts "Here for you mate :" str_h.times {|counter| puts " "*(str_h-counter) + "#"*(counter*2+1)} str_h.times {|counter| puts " "*counter + "#" * (2 * (str_h-counter)-1)} end def perform str_nb = ask_storeys wtf_pyramid (str_nb) end perform
true
957faa4f72f02bfe6538aa8a0823aae1dfaccd0a
Ruby
qbl/insinyur-online-replit-lab
/ruby-series/episode-2/dynamic_fizz_buzz.rb
UTF-8
670
3.734375
4
[]
no_license
# 1.upto(100) do |i| # if (i % 3 == 0 && i % 4 == 0 && i % 5 == 0) # puts 'FizzSussBuzz' # elsif (i % 3 == 0 && i % 4 == 0) # puts 'FizzSuss' # elsif (i % 4 == 0 && i % 5 == 0) # puts 'SussBuzz' # elsif (i % 3 == 0) # puts 'Fizz' # elsif (i % 4 == 0) # puts 'Suss' # elsif (i % 5 == 0) # puts 'Buzz' # else # puts i # end # end def dynamic_fizz_buzz(range, rules) range.each do |i| result = '' rules.each do |(text, divisor)| result << text if (i % divisor == 0) end puts result == '' ? i : result end end dynamic_fizz_buzz( (1..100), [ ['Fizz', 3], ['Suss', 4], ['Buzz', 5] ] )
true
22b7b651204b2b80306f43ee98039b214e753a98
Ruby
SFEley/acts_as_icontact
/lib/acts_as_icontact/readonly.rb
UTF-8
649
2.71875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
module ActsAsIcontact # Overrides methods to make a resource class read-only. Replaces property assignments and save methods with exceptions. module ReadOnly # Properties of this class are read-only. def method_missing(method, *params) raise ActsAsIcontact::ReadOnlyError, "#{self.class.readable_name} is read-only!" if method.to_s =~ /(.*)=$/ super end # Replace save methods with an exception def cannot_save(*arguments) raise ActsAsIcontact::ReadOnlyError, "Contact History is read-only!" end alias_method :save, :cannot_save alias_method :save!, :cannot_save end end
true
2a3ee76309dbfcc8f4541e1d57e8e4f97e923e61
Ruby
anpaez/devops-bootcamp-backend-app
/app/controllers/api/v1/ping_controller.rb
UTF-8
805
2.625
3
[]
no_license
require 'net/http' class Api::V1::PingController < ApplicationController # GET Ping def index @name = params[:name] @time = params[:time].to_i puts "Me ha llamado #{@name}, cuenta atrás: #{@time}" if @time > 0 @time -= 1 @uri = URI('http://localhost:3000/api/v1/ping?name='+@name+'&time='[email protected]_s) puts Net::HTTP.get(@uri) end render json: { nombre: @name, time: @time, message: "Success", }, status: 200 end def show @name = params[:id] puts "Me ha llamado #{@name}" end # POST Ping def create puts "Esto es una prueba" render string: "Esto también es una prueba" end end
true
b559dfea51bb38c1619a735b015c50e6e6b8f44a
Ruby
Automatic365/enigma
/lib/key.rb
UTF-8
118
2.765625
3
[]
no_license
require "pry" class Key attr_reader :key def initialize(key = nil) @key = rand(10000..99999).to_s end end
true
99d3ce589b5b1511916fc2f3942c3512b7627465
Ruby
BJSummerfield/Projecteuler
/problem19.rb
UTF-8
1,373
3.515625
4
[]
no_license
year = 1900 months = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] week_day = [ 1, 2, 3, 4, 5, 6, 7 ] @sundays = [] def sunday_check(year, months, week_day) date = set_start(year, months, week_day) parse_years(date, year, months, week_day) puts @sundays puts @sundays.length end def parse_years(date, year, months, week_day) while date["y"] <= 2000 date['m'] = 0 parse_months(date,months, week_day) date['y'] += 1 end end def parse_months(date, months, week_day) while date["m"] <= 11 parse_days(date, months, week_day) date["m"] += 1 end end def parse_days(date, months, week_day) leap = check_leap_year(date,months,week_day) date["d"] = 1 while date["d"] <= (months[date['m']] + leap) if date['w'] > week_day.last date['w'] = week_day.first end check_sunday(date) date['w'] += 1 date["d"] += 1 end end def check_leap_year(date,months,week_day) if date['y'] % 4 == 0 && date['m'] == 1 return 1 else return 0 end end def check_sunday(date) if date["d"] == 1 && date["w"] == 1 && date['y'] >= 1901 n = "Sunday, #{date['m'] + 1}/#{date['d']}/#{date['y']}" @sundays << n end end def set_start(year, months, week_day) date = {"d" => 1, "w" => 2, "m" => 1, "y" => year} return date end sunday_check(year, months, week_day)
true
6a2d2153bd354a7e2357fb1966aa86c22da4610a
Ruby
omardelarosa/ruby_euler_lab
/002_even_fibonacci/even_fib_george.rb
UTF-8
1,073
3.96875
4
[]
no_license
require './../lib/mathy.rb' def fib_george(max) #initializers i = 2 n = 0 n_minus_1 = 1 n_minus_2 = 0 # n = n_minus_1 + n_minus_2 while i < max # bubble = [n-2, n-1, n] #set current value to the sum of the two previous n = n_minus_1 + n_minus_2 #shift values and move our 'bubble' n_minus_2 = n_minus_1 #next shift n_minus_1 = n #increment i and go to next number i+=1 end #now returns n n end # def add(n1,n2) # if n1 == 0 # n2 # else # n1-=1 # n2+=1 # add(n1,n2) # end # end list = [] #accumulator as a list # (1..100).each do |num| # fib_num = fib_george(num) # if fib_num && is_n_multiple_of_x(fib_num,2) # list.push(fib_num) # end # end fib_num = 0 num = 0 while fib_num < 4000000 fib_num = fib_george(num) if fib_num && is_n_multiple_of_x(fib_num,2) list.push(fib_num) end num+=1 end puts list.reduce(:+) #i need to make list of the first n fibonaccis
true
ee1446715ccfaa6125db53f80b6ce35ec03d1007
Ruby
shadabahmed/leetcode-problems
/0110-balanced-binary-tree.rb
UTF-8
698
3.8125
4
[]
no_license
# Definition for a binary tree node. class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left, @right = nil, nil end end # @param {TreeNode} root # @return {Boolean} def is_balanced(root) max_depth(root) >= 0 end def max_depth(root) return 0 if root.nil? left_depth = max_depth(root.left) right_depth = max_depth(root.right) if left_depth.negative? || right_depth.negative? || (left_depth - right_depth).abs > 1 -1 else 1 + [left_depth, right_depth].max end end root = TreeNode.new(4) root.left = TreeNode.new(2) root.right = TreeNode.new(5) root.left.left = TreeNode.new(1) root.left.right = TreeNode.new(3) p is_balanced(root)
true
d336e6c638401da1dbac781bd33e3c9af0a8ce67
Ruby
kaudyac/backend_mod_1_prework
/ex34.rb
UTF-8
2,712
4.625
5
[]
no_license
animals = ['bear', 'ruby', 'peacock', 'kangaroo', 'whale', 'platypus'] # 1. puts 'The second animal is at 1 and is a ruby.' puts 'The animal at 1 is the second animal and is a ruby.' puts animals[1] # 2. puts 'The third animal is at 2 and is a peacock.' puts 'The animal at 2 is the third animal and is a peacock.' puts animals[2] # 3. puts 'The first animal is at 0 and is a bear.' puts 'The animal at 0 is first and is a bear.' puts animals[0] # 4. puts 'The animal at 3 is fourth and is a kangaroo.' puts 'The fourth animal is at 3 and is a kangaroo.' puts animals[3] # 5. puts 'The fifth animal is at 4 and is a whale.' puts 'The animal at 4 is the fifth animal and is a whale.' puts animals[4] # 6. puts 'The animal at 2 is third and is a peacock.' puts 'The third animal is at 2 and is a peacock.' puts animals[2] # 7. puts 'The sixth animal is at 5 is a platypus.' puts 'The animal at 5 is sixth and is a platypus.' puts animals[5] # 8. puts 'The animal at 4 is fifth and is a whale.' puts 'The fifth animal is at 4 and is a whale.' puts animals[4] puts '-' * 10 # Study Drills # We know that Jan 1, 2010 is really in 2010 and not 2009 because, if we place all # days of the year into an array, like days_of_a_year = [1..365], with January 1 # in the "0th" position in the array, it is not possible to put Jan 1 as the 366th day of the # previous year. # Write your own array and index. trout = ['brook', 'rainbow', 'cutthroat', 'brown', 'lake', 'tiger', 'cutbow'] puts 'The first fish is at 0 and is a brook trout.' puts 'The fish at 0 is first and is a brook trout.' puts trout[0] puts 'The fourth trout is at 3 and is a brown trout.' puts 'The trout at 3 is fourth and is a brown trout.' puts trout[3] puts 'The trout at 5 is sixth and is a tiger trout.' puts 'The sixth trout is at 5 and is a tiger trout.' puts trout[5] puts 'The trout at 6 is seventh and is a cutbow trout.' puts 'The seventh trout is at 6 and is a cutbow trout.' puts trout[6] puts 'The trout at 2 is third and is a cutthroat trout.' puts 'The third trout is at 2 and is a cutthroat trout.' puts trout[2] puts 'The trout at 1 is second and is a rainbow trout.' puts 'The second trout is at 1 and is a rainbow trout.' puts trout[1] puts 'The trout at 4 is fifth and is a lake trout.' puts 'The fifth trout is at 4 and is a lake trout.' puts trout[4] puts '-' * 10 books = ['Eric!', 'Sourcery', 'Thud!'] puts 'The first book is at 0 and is Eric!' puts 'The book at 0 is first and is Eric!' puts books[0] puts 'The second book is at 1 and is Sourcery.' puts 'The book at 1 is second and is Sourcery.' puts books[1] puts 'The third book is at 2 and is Thud!' puts 'The book at 2 is third and is Thud!' puts books[2]
true
9409ac1ff1a5b8f7f14b1298a6136df98c576ca4
Ruby
chadbrewbaker/brewlib
/graph.rb
UTF-8
3,636
2.875
3
[]
no_license
require 'pp' class Graph attr_reader :verts, :rep attr_accessor :no_edge_val #Must have these methods defined in child classes #graph.edge(i,j) #graph.set_edge(i,j,value) #graph.set_dir_edge(i,j,value) #graph.reorder(permutation) #graph.resize(i) def edge?(i,j) if(edge(i,j) != @no_edge_val) return true end return false end def print_adj_mat for i in 0...@verts for j in 0...@verts print "#{edge(i,j)}," end print "\n" end end def print_neato puts 'graph dasGraph { ' for i in 0...@verts for j in i...@verts if(edge(i,j) != @no_edge_val) puts("v#{i} -- v#{j}; ") end end end puts ' } ' end def print_dreadnaught print "n=#{@verts} g\n" for i in 0...@verts for j in (i+1)...@verts if(edge(i,j) != @no_edge_val) print "#{j} " end end print ";\n" end print "x\no\n" end def print_brew print "#{@verts}\n" for i in 0...@verts for j in (i+1)...@verts if(edge(i,j) != @no_edge_val) print "#{i} #{j}\n" end end end print "-1" end def print_dimacs edge_count=0 for i in 0...@verts for j in (i+1)...@verts if(edge(i,j) != @no_edge_val) edge_count+=1 end end end print "p edge #{@verts} #{edge_count}\n" for i in 0...@verts for j in (i+1)...@verts if(edge(i,j) != @no_edge_val) print "e #{i+1} #{j+1}\n" end end end end end #class OutOfCoreDenseGraph # def initialize # @temp_dir ="/tmp/" # end #end #Writing to disk for huge sparse graphs #class OutOfCoreSparseGraph #end # An interface for a graph distributed over a MPI network # Keeps a local cache of changes/requests so it doesn't have to do as many queries # Also supports batch queries #class DistributedGraph # #end class SparseGraph < Graph def initialize (size) @rep=Array.new(size) @rep.fill{ |i| Array.new } @verts=size @no_edge_val=0 end def edge(i,j) @rep[i].each{ |cur| if(cur[0]==j) return cur[1] end } return @no_edge_val end def set_dir_edge(i,j,value) edge_set=false @rep[i].each_index{ |k| if(@rep[i][k][0]==j) @rep[i][k][1]=value edge_set=true break end } if(!edge_set) @rep[i].push([j,value]) end end def set_edge(i,j,value) set_dir_edge(i,j,value) set_dir_edge(j,i,value) end def resize(new_size) copy_num = [new_size, @verts].min new_graph=SparseGraph.new(new_size) for i in 0...copy_num for j in 0...copy_num val= self.edge(i,j) if(val != @no_edge_value) new_graph.set_dir_edge(i,j,val) end end end @verts=new_size @rep=new_graph.rep end def reorder(perm) new_graph=DenseGraph.new(@verts) for i in 0...(@verts-1) for j in 0...(@verts-1) val=self.edge(perm[i],perm[j]) if(val !=@no_edge_value) new_graph.set_dir_edge(i,j,val) end end end end end class DenseGraph < Graph def initialize(size) @rep=Array.new(size) @rep.fill{ |i| Array.new(size).fill{|j| 0} } @verts=size @no_edge_val = 0 end def edge(i,j) return @rep[i][j] end def set_edge(i,j,value) @rep[i][j]=value @rep[j][i]=value end def set_dir_edge(i,j,value) @rep[i][j]=value end def reorder(perm) newGraph= @rep @rep.each_index{|i| @rep[i].each_index{|j| newGraph[i][j]= self.edge(perm[i],perm[j]) } } @rep=newGraph end def resize(size) new_rep=Array.new(size) new_rep.fill{ |i| Array.new(size).fill{|j| 0} } copy_count=[size,@verts].min for i in 0...copy_count for j in 0...copy_count new_rep[i][j] = @rep[i][j] end end @rep=new_rep @verts=size end end
true
624cccabbff37660eb631abb208c8184a4297e93
Ruby
emk/rdf-agraph
/lib/rdf/allegro_graph/parser.rb
UTF-8
951
2.703125
3
[ "Unlicense" ]
permissive
module RDF::AllegroGraph # A module containg the URL parser of AllegroGraph objects such as : # - servers # - catalogs # - repositories module Parser # Parse a full URI and extract the server/catalog and the repository ID. # # The parsing uses the default AllegroGraph URI schema : # http://server:port/catalogs/catalog_name/repositories/repository_name # This function can be overwritten to parse a custom URI schema system. # # @param [String] uri the uri the parse # @return [Array] def parse_uri(url) hash = {} url = URI.parse(url) path = Pathname.new(url.path) hash[:id] = path.basename.to_s path = path.parent.parent url.path = path.to_s if path.parent.basename.to_s == 'catalogs' hash[:catalog] = Catalog.new(url.to_s) else hash[:server] = Server.new(url.to_s) end hash end module_function :parse_uri end end
true
f295b460cb21e80366b871e7b50adb543f4fbc21
Ruby
brycematsuda/ytcms-lite
/test/models/season_test.rb
UTF-8
1,665
2.640625
3
[]
no_license
require 'test_helper' class SeasonTest < ActiveSupport::TestCase test "season name must not be empty" do season = Season.new assert season.invalid? assert season.errors[:name].any? end test "season permalink must not be empty" do season = Season.new(:name => "No permalink!") assert season.invalid? assert season.errors[:permalink].any? end test "season permalink must be unique" do season = Season.new(:name => "Not A Unique Season", :permalink => seasons(:not_unique).permalink) assert season.invalid? assert season.errors[:permalink].any? end test "season name length must be greater than or equal to 5" do season = Season.new(:name => "K", :permalink => "shortname") assert season.invalid? assert_equal ["is too short (minimum is 5 characters)"], season.errors[:name] end test "season name length must be less than or equal to 100" do season = Season.new(:name => seasons(:long).name, :permalink => "toolong") assert season.invalid? assert_equal ["has already been taken", "is too long (maximum is 100 characters)"], season.errors[:name] end test "season permalink length must be greater than or equal to 5" do season = Season.new(:name => "Short Link", :permalink => "s") assert season.invalid? assert_equal ["is too short (minimum is 5 characters)"], season.errors[:permalink] end test "season permalink length must be less than or equal to 100" do season = Season.new(:name => "Long Name", :permalink => seasons(:long).name) assert season.invalid? assert_equal ["is too long (maximum is 20 characters)"], season.errors[:permalink] end end
true
226680a132eedac5edbd8a910eac2a9bdf7b88fc
Ruby
EDalSanto/LaunchSchool
/courses/test_prep/fake_array.rb
UTF-8
296
3.71875
4
[]
no_license
class FakeArray def initialize(array) @elements = array end def []=(index, element) @elements[index] = element end def [](index) @elements[index] end end array = FakeArray.new([]) array[0] = 23 array.[]=(1, 42) #puts "0th element: #{array[0]} 1st element: #{array[1]}"
true
b78c2dc3e3e122b42296c67651f94c8c4a0dc75a
Ruby
jstirk/ludum-dare-28
/src/yogo/structure/iron_mine.rb
UTF-8
579
2.734375
3
[]
no_license
require 'yogo/structure/base' module YOGO module Structure class IronMine < Base def self.name "Iron Mine" end def self.description "+5 iron" end def self.setup_cost 33 end def self.running_cost 10 end def self.valid_tile?(tile) tile.resource == :iron end def self.produces { :iron => 5 } end def causes { :air_pollution => 0.01 * @production, :water_pollution => 0.1 * @production } end end end end
true
ea04b4579a9ae5984a3d2f6ed2fb9f3c57266ade
Ruby
AJFaraday/slow_time_strategy
/app/models/walker.rb
UTF-8
935
3.09375
3
[ "MIT" ]
permissive
class Walker < Token attr_accessor :health def initialize(x, y, owner, grid = nil) super(x, y, owner, grid) @health = 1 end def calculate_movement target_x, target_y = next_step initial_health = @health if @grid.in_range?(target_x, target_y) -> do target = @grid.token_at(target_x, target_y) if target if target.owner == self.owner if target.is_a?(Walker) target.heal(initial_health) @grid.remove_token(x, y, true) end else self.fight(@grid.token_at(target_x, target_y), initial_health, true) end else @grid.move_token(@x, @y, target_x, target_y) end end end end def heal(amount) @health += amount if @health >= 10 @grid.remove_token(x, y) @owner.tokens.delete(self) @grid.add_token(x, y, City, owner) end end end
true
b2acef2b2112231958452fa2f9cf9ee327dd8687
Ruby
StephenAjayi/epicodus_to_do
/spec/lister_spec.rb
UTF-8
774
2.84375
3
[]
no_license
require('rspec') require('lister') describe(Task) do before() do Task.clear() end describe('#description') do it('returns the description of a task') do test_task = Task.new("wash the car") expect(test_task.description()).to(eq("wash the car")) end end describe('#save') do it('saves a description in an array') do test_task = Task.new("mow the lawn") test_task.save() expect(Task.all()).to(eq([test_task])) end end describe('.all') do it('is empty at first') do expect(Task.all()).to(eq([])) end end describe('.clear') do it('empties out all of the saved tasks') do Task.new("mow the lawn").save() Task.clear() expect(Task.all()).to(eq([])) end end end
true
4e725a8005408de6f95570c0be9bd572a0cc3ff0
Ruby
armagh-dev/armagh
/lib/armagh/utils/interruptible_sleep.rb
UTF-8
1,223
2.828125
3
[ "Apache-2.0" ]
permissive
# Copyright 2018 Noragh Analytics, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. # # See the License for the specific language governing permissions and # limitations under the License. # module Armagh module Utils class InterruptibleSleep # A sleep that is able to be interrupted. # # @example Sleep for 10 seconds unless the runner is terminated # sleep(10) { runner.terminated? } # # @param sleep_time [Numeric] the time to sleep # @yield the condition that is checked for interrupt (if true, interrupt) def self.interruptible_sleep(sleep_time) whole = sleep_time.to_i partial = sleep_time - whole whole.times do break if yield sleep 1 end sleep partial unless yield end nil end end end
true
4ffadfdcb03a240c8f3d954ac796c3f938a65b12
Ruby
leblanc119/omnicalc_params
/app/controllers/calculations_controller.rb
UTF-8
2,484
2.703125
3
[]
no_license
class CalculationsController < ApplicationController def flex_square # params = {"the_number"=>"17"} @user_number = params["the_number"].to_f @squared_number = @user_number**2 render("calculations/flex_square.html.erb") end def flex_square_root # params = {"the_number"=>"17"} @user_number = params["the_number"].to_f @square_root_number = @user_number**(1/2.0) render("calculations/flex_square_root.html.erb") end def flex_payment @apr = params["the_number1"].to_f/100.0 @years = params["the_number2"].to_i @principal = params["the_number3"].to_f monthly_rate=(@apr/100)/12 num_payments=@years*12 @monthly_payment = ((monthly_rate)/(1-(1+monthly_rate)**(num_payments*-1)))*@principal render("calculations/flex_payment.html.erb") end def square_form render("calculations/square_form.html.erb") end def square @user_number = params["number_square"].to_f @squared_number = @user_number**2.0 render("calculations/square.html.erb") end def square_root_form render("calculations/square_root_form.html.erb") end def square_root @user_number = params["number_square_root"].to_f @square_root_number = @user_number**(1/2.0) render("calculations/square_root.html.erb") end def payment_form render("calculations/payment_form.html.erb") end def payment monthly_rate=(params["user_apr"].to_f/100)/12 num_payments=params["user_years"].to_f*12 @monthly_payment = ((monthly_rate)/(1-(1+monthly_rate)**(num_payments*-1)))*params["user_pv"].to_f render("calculations/payment.html.erb") end def word_count_form render("calculations/word_count_form.html.erb") end def word_count @text = params["user_text"] @special_word = params["special_word"] @sum=0 @[email protected](/[^a-z0-9\s]/i, "") @word=@special_word.gsub(/[^a-z0-9\s]/i, "") @text2.split.each do |special_count| if @word.upcase == special_count.upcase @sum=@sum+1 end end @word_count = @text.split.count @char_count_spaces = @text.length @char_count_nospace = @text.gsub(" ","").length @occurrences = @sum render("calculations/word_count.html.erb") end def random_form render("calculations/random_form.html.erb") end def random max=params["user_max"].to_f min=params["user_min"].to_f @random=rand(max-min)+min render("calculations/random.html.erb") end end
true
c7e319e280f668a1f7df5d8f443645c2627ec7bd
Ruby
rohitreddyjd/oraview
/tools/send.rb
UTF-8
314
2.703125
3
[]
no_license
#!/usr/bin/env ruby # encoding :utf-8 require "bunny" #Connect to RabbitMQ server conn = Bunny.new conn.start #Create a channel ch = conn.create_channel #declare a queue q = ch.queue("hello") ch.default_exchange.publish("Hello World!", :routing_key => q.name) puts " [x] Sent 'Hello World!'" conn.close
true
1626f16c9c145bc3ec2390fdf3cfa88ad05ed8d8
Ruby
robobluebird/simple_maps
/middlewares/ws.rb
UTF-8
1,054
2.515625
3
[ "MIT" ]
permissive
require 'faye/websocket' require 'json' module Rack class Lint def call(env = nil) @app.call(env) end end end class Rack::Lint::HijackWrapper def to_int @io.to_i end end class Ws def initialize(app) @app = app @clients = [] end def call(env) if Faye::WebSocket.websocket?(env) ws = Faye::WebSocket.new env ws.on :open do |event| p [:open, ws.object_id] @clients << ws end ws.on :message do |event| data = JSON.parse event.data, symbolize_names: true if data[:location_id] && data[:map_id] location = Location.find data[:location_id] map = location.maps.find data[:map_id] data = { location: location, map: map } @clients.each { |client| client.send data.to_json } end end ws.on :close do |event| p [:close, ws.object_id, event.code, event.reason] @clients.delete(ws) ws = nil end ws.rack_response else @app.call(env) end end end
true
7a195a2509fd792f2d90c36486ee8e46a7bacaab
Ruby
Emanao/school-domain-v-000
/lib/school.rb
UTF-8
393
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# code here class School def initialize(name) @name=name @roster={} end def roster @roster end def add_student(student, grade) @roster[grade] = [] if [email protected]?(grade) @roster[grade]<<student end def grade(grade) @roster[grade] end def sort @roster.collect do|grade, student_array| student_array.sort! end @roster end end
true
a2072e0b72431db0375c7764dfd151ba82dfb974
Ruby
justinyiwang/ICS-Course
/ch13/die.rb
UTF-8
367
3.484375
3
[]
no_license
class Die def initialize # I'll just roll the die, though we could do something else # if we wanted to, such as setting the die to have 6 showing. roll end def roll @number_showing = 1 + rand(6) end def showing @number_showing end def cheat num if !num.between?(1,6) roll else @number_showing = num end end end
true
09fad2e6e33fa88578424cad7e99c2f955958a66
Ruby
dallashall/what-if-game
/WhatIf/app/models/team.rb
UTF-8
1,375
2.828125
3
[]
no_license
class Team < ApplicationRecord has_many :questions has_many :answers, through: :questions has_many :users after_initialize :set_team_code! def set_team_code! self.code ||= generate_team_code end def team_code SecureRandom::urlsafe_base64(3).upcase end def generate_team_code code = team_code while Team.find_by(code: code) code = team_code end code end def questions_hash hsh = {} self.questions.each do |question| hsh[question.user_id] = question end hsh end def shuffled_questions hsh = {} user_ids = self.questions.map(&:user_id) shuffled_ids = user_ids.rotate qs = questions_hash user_ids.each_with_index do |id, idx| hsh[id] = qs[shuffled_ids[idx]] end hsh end def answers_hash hsh = {} self.answers.each do |answer| hsh[answer.user_id] = answer end hsh end def shuffled_answers hsh = {} user_ids = self.answers.map(&:user_id) shuffled_ids = user_ids.rotate qs = answers_hash user_ids.each_with_index do |id, idx| hsh[id] = qs[shuffled_ids[idx]] end hsh end def arrangement arr = [] shuffled_questions.each do |id, question| a = {} a[id] = question.answer q = {} q[id] = question arr.push(a) arr.push(q) end arr.rotate end end
true
9358c5a72a4ea578f909cccb488c696a61a38937
Ruby
highnotes/eardrums
/app/models/level.rb
UTF-8
602
2.625
3
[]
no_license
class Level < ActiveRecord::Base validates_presence_of :name validates_presence_of :description validates_presence_of :index validates_numericality_of :index, only_integer: true validates_uniqueness_of :index has_many :courses def self.beginner_levels Level.where(index: [1,2,3,4]).collect {|l| l.id } end def self.intermediate_levels Level.where(index: [5,6,7]).collect {|l| l.id } end def self.advanced_levels Level.where(index: [8,9,10]).collect {|l| l.id } end def self.special_levels Level.where(index: -1).collect {|l| l.id } end end
true
7b4346253a19219cee6203d067abe2317348c6ef
Ruby
catks/djin
/lib/djin/root_cli_parser.rb
UTF-8
1,506
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Djin ## This class is responsible to handle options that must be evaluated # before the load of tasks in djin file(eg: djin.yml) class RootCliParser class << self def parse!(args = ARGV) options = {} # TODO: Find a better way to handle -f/--file option, # throw, catch and delete in ARGV are necessary # to only remove the -f/--file option # and bypass everything else to Dry::CLI catch(:root_cli_exit) do parser(options).parse(args) end remove_file_args!(args) options end private def parser(options) OptionParser.new do |opts| opts.on('-f FILE', '--file FILE') do |v| options[:files] ||= [] options[:files] << v end opts.on('-v', '--version') do throw :root_cli_exit end opts.on('-h', '--help') do throw :root_cli_exit end opts.on('--all') do throw :root_cli_exit end end end def remove_file_args!(args) file_option = ['-f', '--file'] args_indexes_to_remove = args.each_with_index.map do |value, index| index if (file_option.include?(args[index - 1]) && index.positive?) || file_option.include?(value) end.compact args_indexes_to_remove.reverse.each { |index| args.delete_at(index) } end end end end
true
9b821762bced34466787369e4e347f2c1e90ab8e
Ruby
lupinthe14th/codewars
/lib/html_special_chars.rb
UTF-8
117
2.71875
3
[ "MIT" ]
permissive
def html_special_chars(str) str.gsub(/<|>|"|&/, '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', '&' => '&amp;') end
true
e417a468994dec4129c4cb544f466740fc06d0bb
Ruby
Vizzuality/trase
/app/services/api/v3/refresh_dependencies.rb
UTF-8
4,133
2.515625
3
[ "MIT" ]
permissive
module Api module V3 class RefreshDependencies include Singleton def initialize query =<<~SQL SELECT table_name, column_name, dependent_name, dependent_type FROM maintenance.refresh_dependencies SQL begin result = Api::V3::YellowTable.connection.execute query rescue result = [] end @data = result.map do |r| class_with_dependents = class_with_dependents(r) next unless class_with_dependents && class_with_dependents < Api::V3::YellowTable dependent_class = dependent_class(r) next unless dependent_class && ( dependent_class.included_modules.include?(Api::V3::Readonly::MaterialisedView) || dependent_class.included_modules.include?(Api::V3::Readonly::MaterialisedTable) || dependent_class == Api::V3::Readonly::Attribute ) { table_name: r["table_name"], column_name: r["column_name"], class_with_dependents: class_with_dependents, dependent_class: dependent_class } end.compact print end def print @data.group_by { |rd| rd[:class_with_dependents] }.each do |class_with_dependents, data1| Rails.logger.debug class_with_dependents.to_s data1.group_by { |rd| rd[:dependent_class] }.each do |dependent_class, data2| Rails.logger.debug " " + dependent_class.to_s + ": " + data2.map { |rd| rd[:column_name] }.to_s end end end def grouped_by_dependent_class(table_name = nil) data = @data if table_name data = data.select{ |rd| rd[:table_name] == table_name } end data.group_by { |rd| rd[:dependent_class] } end def classes_with_dependents @data.map { |rd| rd[:class_with_dependents] }.uniq end def dependent_classes(klass = nil) data = @data if klass data = @data.select{ |rd| rd[:class_with_dependents] == klass } end data.map { |rd| rd[:dependent_class] }.uniq end private def class_with_dependents(refresh_dependents_record) table_name = refresh_dependents_record["table_name"] class_namespace = if table_name == "attributes" Api::V3::Readonly else Api::V3 end class_camelised = case table_name when "nodes_with_flows_per_year" "NodeWithFlowsPerYear" when "nodes_with_flows_or_geo_v" "NodeWithFlowsOrGeo" else table_name.classify end begin class_namespace.const_get(class_camelised) rescue NameError Rails.logger.error("Unrecognised table: #{table_name}") nil end end def dependent_class(refresh_dependents_record) dependent_name = refresh_dependents_record["dependent_name"] dependent_underscorised = case refresh_dependents_record["dependent_type"] when "m" dependent_name.sub(/_mv$/, "") when "v" dependent_name.sub(/_v$/, "") end class_namespace = if dependent_underscorised =~ /^dashboards_/ dependent_underscorised = dependent_underscorised.sub(/^dashboards_/, "") Api::V3::Readonly::Dashboards else Api::V3::Readonly end dependent_camelised = case dependent_underscorised when "nodes_with_flows" "NodeWithFlows" when "nodes_with_flows_or_geo" "NodeWithFlowsOrGeo" when "node_stats" "NodeStats" else dependent_underscorised.classify end begin class_namespace.const_get(dependent_camelised) rescue NameError Rails.logger.error("Unrecognised dependent: #{dependent_name}") nil end end end end end
true
c5abe5fc93901f2064272af0b3578872afd860bd
Ruby
peter-leonov-dh/screen-diff
/rgb.rb
UTF-8
1,224
3.015625
3
[]
no_license
#!/usr/bin/env ruby require 'rmagick' def img_to_rgb file_src, io_dst img = Magick::Image.read(file_src).first w = img.columns h = img.rows io_dst.puts "RGB" io_dst.puts "#{w} #{h}" h.times do |y| # x, y, columns, rows -> array io_dst.puts img.export_pixels(0, y, w, 1, 'RGB').join(' ') end end def rgb_to_img io_src, file_dst format = io_src.readline.chomp raise 'wrong format' unless format == 'RGB' _, w, h = /^(\d+) (\d+)/.match(io_src.readline).to_a raise 'wrong format' unless w && h w = w.to_i h = h.to_i img = Magick::Image.new(w, h) h.times do |y| pixels = io_src.readline.split(' ').map(&:to_i) # x, y, columns, rows, format, array img.import_pixels(0, y, w, 1, 'RGB', pixels) end img.write(file_dst) end # CLI case ARGV.shift when 'img-to-rgb' raise 'rgb img-to-rgb: two args needed: src.img dst.rgb' unless ARGV.length == 2 img_to_rgb ARGV[0], ARGV[1] == '-' ? STDOUT : File.open(ARGV[1], 'w') when 'rgb-to-img' raise 'rgb rgb-to-img: two args needed: src.rgb dst.img' unless ARGV.length == 2 rgb_to_img ARGV[0] == '-' ? STDIN : File.open(ARGV[0], 'r'), ARGV[1] else raise 'usage: rgb dump source.img - | process | rgb load - dest.img' end
true
b30a6a8b7ed997b6fb1d282bbb8dc3a2f53b15f9
Ruby
LuizFernandoCabral/DevSoft2014-01
/aula03/ex3.3.rb
UTF-8
266
3.3125
3
[]
no_license
def ordena(array) return array if array.size <= 1 pivot = array[0] return ordena(array.select { |y| y < pivot }) + array.select { |y| y == pivot } + ordena(array.select { |y| y > pivot }) end a=[20,0,50,30,34,33,35,22,1] print ordena(a)
true
a7871aa6564fe986823123d10578c0475341700d
Ruby
amadeusM/Ruby-Projects
/app_academy_select_exercise.rb
UTF-8
207
3.515625
4
[]
no_license
# This method returns a list of perfect squares smaller than num. def perfect_squares(num) array = [] i = 1 while i*i < num array << i i += 1 end array.map{|i| i*i} end
true
0271abb15151df4271ff14cd896afbac4bb8d49d
Ruby
Marvinsky/pollApp
/db/seeds.rb
UTF-8
1,175
2.546875
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) user = User.create(email:"[email protected]", uid: "32dfa4328uoja", provider:"facebook") poll = MyPoll.create(title:"Programming language you prefer", description:"We want to know what programming languages are the most used.", expires_at: DateTime.now + 1.year,user:user) question = Question.create(description: "Do you like the performance of your language programming?", my_poll:poll) answer = Answer.create(description: "a)",question:question) user2 = User.create(email:"[email protected]", uid: "32dfwerew28uoja", provider:"twitter") poll2 = MyPoll.create(title:"Universal History", description:"What year america was discover?", expires_at: DateTime.now + 1.year,user:user2) question2 = Question.create(description: "Where did the spanish arrived first?", my_poll:poll2) answer2 = Answer.create(description: "b)",question:question2)
true
101de55d67863e8b4c492966dbb115be1a613f31
Ruby
Adzz/challenges
/spec/list_recursion/all_challenges_spec.rb
UTF-8
9,090
3.34375
3
[ "MIT" ]
permissive
require 'list_recursion' require 'spec_helper' RSpec.describe 'list recursion' do # This gives the tests a method named `nil_node`, # whose value is what's in the block. # It is different from normal methods in that # it only runs the code the first time, # so that successive invocations of `nil_node` from within a test # will return the same node (this resets for each test). let(:nil_node) { NilNode.new } describe 'NilNode' do it 'always has data of nil' do assert_equal nil, nil_node.data end it 'does not have a data=' do # respond_to? is inherited, you don't have to make it assert_equal false, nil_node.respond_to?(:data=) end it 'links to itself' do assert_equal nil_node, nil_node.link end it 'does not have a link=' do assert_equal false, nil_node.respond_to?(:link=) end it 'has a length of 0' do assert_equal 0, nil_node.length end it 'has a min of nil' do assert_equal nil, nil_node.min end it 'has a max of nil' do assert_equal nil, nil_node.max end specify '#first returns nil' do assert_equal nil, nil_node.first end specify '#last returns nil' do assert_equal nil, nil_node.last end it 'is empty' do assert_equal true, nil_node.empty? end it 'returns true when asked if it is nil?' do assert_equal true, nil_node.nil? end describe '#[] returns nil' do example('at 0') { assert_equal nil, nil_node[0] } example('at 1') { assert_equal nil, nil_node[1] } example('at 100') { assert_equal nil, nil_node[100] } end describe 'insertion' do context 'at 0' do it 'returns a normal node' do assert_equal NormalNode, nil_node.insert(0, 'abc').class end specify 'with the inserted data' do assert_equal 'abc', nil_node.insert(0, 'abc').data end specify 'whose link is a nilnode' do assert_equal nil_node, nil_node.insert(0, 'abc').link end end context 'at 1' do it 'returns a normal node' do assert_equal NormalNode, nil_node.insert(1, 'abc').class end specify 'with data of nil' do assert_equal nil, nil_node.insert(1, 'abc').data end specify 'whose link is the same as inserting at 0' do link = nil_node.insert(1, 'abc').link assert_equal NormalNode, link.class assert_equal 'abc' , link.data assert_equal nil_node , link.link end end context 'at 3' do it 'returns a normal node' do assert_equal NormalNode, nil_node.insert(3, 'O.o').class end specify 'with data of nil' do assert_equal nil, nil_node.insert(3, 'O.o').data end specify 'whose link is the same as inserting at 2' do result = nil_node.insert(3, 'O.o') assert_equal nil , result.data assert_equal nil , result.link.data assert_equal nil , result.link.link.data assert_equal 'O.o' , result.link.link.link.data end end end end describe 'NormalNode' do let(:node_b) { NormalNode.new('b', nil_node) } let(:node_ab) { NormalNode.new('a', node_b) } let(:node_cb) { NormalNode.new('c', node_b) } it 'has data of whatever it was initialized with' do assert_equal 'b', node_b.data assert_equal 'a', node_ab.data assert_equal 'c', node_cb.data end it 'does not have a data=' do assert_equal false, node_b.respond_to?(:data=) end it 'has a link is whatever it was initialized with' do assert_equal node_b, node_ab.link assert_equal nil_node, node_ab.link.link end it 'does not have a link=' do assert_equal false, node_ab.respond_to?(:link=) end describe 'has a length of 1 more than its link\'s length' do example 'one deep' do assert_equal 1, node_b.length end example 'two deep' do assert_equal 2, node_ab.length end end describe 'min' do it 'returns its data when its link is a NilNode' do assert_equal 'b', node_b.min end it 'returns its data when its data is less than its links data' do assert_equal 'a', node_ab.min end it 'returns its links data when its links data is less than its data' do assert_equal 'b', node_cb.min end it 'does not depend on its link\'s data for verifying correctness' do node = NormalNode.new('a', NormalNode.new(nil, nil_node)) expect { node.min }.to raise_error ArgumentError, /nil/ end end describe 'max' do it 'returns its data when its link is a NilNode' do assert_equal 'b', node_b.max end it 'returns its data when its data is greater than its links data' do assert_equal 'b', node_ab.max end it 'returns its links data when its links data is greater than its data' do assert_equal 'c', node_cb.max end it 'does not depend on its link\'s data for verifying correctness' do node = NormalNode.new('a', NormalNode.new(nil, nil_node)) expect { node.min }.to raise_error ArgumentError, /nil/ end end specify '#first returns its data' do assert_equal 'b', node_b.first assert_equal 'a', node_ab.first assert_equal 'c', node_cb.first end describe '#last' do it 'returns its data when its link is a nil node' do assert_equal 'b', node_b.last end it 'returns its link\'s data when its link is not a nil node' do assert_equal 'b', node_ab.last end it 'even if its link\'s data is nil' do node = NormalNode.new('a', NormalNode.new(nil, nil_node)) assert_equal nil, node.last end end describe '#empty?' do it('is not empty') { assert_equal false, node_b.empty? } specify 'even if its data is nil' do assert_equal false, NormalNode.new(nil, nil_node).empty? end end describe '#nil?' do it 'returns false when asked if it is nil?' do assert_equal false, node_b.nil? end specify 'even if its data is nil' do assert_equal false, NormalNode.new(nil, nil_node).nil? end end describe '#[]' do specify 'when asked for the data at index 0, it returns its own data' do assert_equal 'b', node_b[0] assert_equal 'a', node_ab[0] assert_equal 'c', node_cb[0] end specify 'otherwise it returns its link\'s result for one index lower' do assert_equal 'b', node_ab[1] assert_equal 'b', node_cb[1] end example 'a more challenging example' do node5 = NormalNode.new('p', nil_node) node4 = NormalNode.new('i', node5) node3 = NormalNode.new('h', node4) node2 = NormalNode.new('l', node3) node1 = NormalNode.new('k', node2) assert_equal 'k', node1[0] assert_equal 'l', node1[1] assert_equal 'h', node1[2] assert_equal 'i', node1[3] assert_equal 'p', node1[4] assert_equal nil, node1[5] assert_equal 'l', node2[0] assert_equal 'h', node2[1] assert_equal 'i', node2[2] assert_equal 'p', node2[3] assert_equal nil, node2[4] end end describe 'insertion' do context 'at index 0' do it 'returns a new normal node' do assert_equal NormalNode, node_ab.insert(0, 'x').class end specify 'the returned node has the data' do assert_equal 'x', node_ab.insert(0, 'x').data end specify 'and the returned node\'s link is the node we called insert on' do assert_equal node_ab, node_ab.insert(0, 'x').link end specify 'the node we called insert on is not modified' do node_ab.insert(0, 'x') assert_equal 'a', node_ab.data assert_equal node_b, node_ab.link assert_equal 'b', node_b.data assert_equal nil_node, node_b.link end end context 'otherwise' do it 'returns a normal node' do assert_equal NormalNode, node_ab.insert(1, 'x').class end specify 'the returned node has the current node\'s data' do inserted = node_ab.insert(1, 'x') assert_equal 'a', inserted[0] end specify 'the returned node\'s link includes the inserted item at the correct position' do inserted = node_ab.insert(1, 'x') assert_equal 'a', inserted[0] assert_equal 'x', inserted[1] assert_equal 'b', inserted[2] assert_equal nil, inserted[3] end specify 'it does not modifty the node we called the insert on' do _inserted = node_ab.insert(1, 'x') assert_equal 'a', node_ab[0] # note we assert against ab, not the result assert_equal 'b', node_ab[1] assert_equal nil, node_ab[2] end end end end end
true
3188909dd46dc53ee892440ac12056b0cfa6bc9f
Ruby
kaize/deadline_camp
/lib/member_collection_convertor.rb
UTF-8
1,632
2.53125
3
[]
no_license
class MemberCollectionConvertor def initialize(*args) custom_options = args.extract_options! @new_options = default_options.merge custom_options.symbolize_keys @collection = args[0] end def to_xls(options = {}) merged_options = options.merge @new_options if @collection.first.present? model = @collection.first.class merged_options[:headers] = merged_options[:columns].map {|column| model.human_attribute_name(column)} end @collection.to_xls merged_options end def to_json(options = {}) @collection.to_json(options) end private def default_options {:columns => [ :id, :state, :email, :first_name, :last_name, :patronymic, :phone, :skype, :jabber, :icq, :institute, :start_year, :start_month, :finish_year, :finish_month, :department, :profession, :degree, :gpa, :web, :camp_time, :camp_life, :camp_fee, :camp_notebook, :camp_training, :hobby, :sport, :group, :how_hear_about_as, :twitter, :facebook, :vkontakte, :city, :birthday, :schoolyear_count, :s_jobs, :s_additional_educations, :s_achievements, :s_langs, :s_skill_databases, :s_skill_ides, :s_skill_operation_systems, :s_skill_others, :s_skill_program_langs, :s_others, :s_preferences, :how_hear_about_as ]} end end
true
1f7ec2af66f14042dfc5a8cc16ad15676354a82e
Ruby
hailinzeng/simple_crm
/lib/crypt.rb
UTF-8
1,232
2.609375
3
[ "MIT" ]
permissive
require 'openssl' unless defined?(::OpenSSL::Cipher::Cipher) module SimpleCrm module Admin ## # Common utility methods used within the admin application. # module Utils ## # This Util it's used for encrypt/decrypt password. # We want password decryptable because generally for our sites we have: password_lost. # We prefer send original password instead reset them. # module Crypt ## # Decrypts the current string using the current key specified. # def decrypt(password) cipher = build_cipher(:decrypt, password) cipher.update(self.unpack('m')[0]) + cipher.final end ## # Encrypts the current string using the current key and algorithm specified. # def encrypt(password) cipher = build_cipher(:encrypt, password) [cipher.update(self) + cipher.final].pack('m').chomp end private def build_cipher(type, password) cipher = OpenSSL::Cipher::Cipher.new("DES-EDE3-CBC").send(type) cipher.pkcs5_keyivgen(password) cipher end end end end end String.send(:include, SimpleCrm::Admin::Utils::Crypt)
true
ad1aa1df001d54398061a0201dd940715b52adcf
Ruby
coreyhellwege/Ruby-Fundamentals
/week3/day12.rb
UTF-8
547
4.375
4
[]
no_license
# Ternary # will puts either the first or second string dependant on whether what's before the ? is true or false puts true ? "it is true" : "it is false" x = 10 < 5 ? "it is true" : "it is false" def method1 return "elephants" end def method2 return "hello world" end # instead of writing this: # if false # puts "it is true" # else # puts "it is false" # end b = 10 > 5 ? method1() : method2() puts x puts b val = 10 > 2 result = val ? true : false age = 22 "#{age >= 18 ? "enter" : "no entry"}" puts g
true
decd05b2894cac1f3b5c2983bb1771058ab5f29a
Ruby
kmcphillips/vocabulizer.com
/test/unit/term_test.rb
UTF-8
5,401
2.828125
3
[]
no_license
require 'test_helper' class TermTest < ActiveSupport::TestCase def valid_term FactoryGirl.create(:term) end def valid_term_with_details term = FactoryGirl.create(:term) term.details << FactoryGirl.create(:term_detail) term end test "#populate_details should just return false if there are already some details" do term = valid_term_with_details term.expects(:populate_from_wordnik).never term.expects(:populate_from_urban_dictionary).never assert !term.populate_details end test "#populate_details should build the details from Wordnik and Urban" do term = valid_term term.expects(:populate_from_wordnik).once term.expects(:populate_from_urban_dictionary).once assert term.populate_details end test "#populate_details! should delete all and call #populate_details" do term = valid_term_with_details assert term.details.size > 0 term.expects(:populate_details).once term.populate_details! assert term.details.size == 0 end test "class #base_value should not change anything if it's already a simple word" do assert_equal "cake", Term.base_value("cake") end test "class #base_value should scrub and set the base value on create" do assert_equal "tree", Term.base_value(" TREES...") end test "#set_base_value should set the base value if it is not set" do Term.expects(:base_value).with("pie").returns("delicious") term = FactoryGirl.create(:term, value: "pie", base_value: nil) assert_equal "delicious", term.base_value end test "#set_base_value should not change anything if it is already set" do term = FactoryGirl.create(:term, value: "pie", base_value: "delicious") assert_equal "delicious", term.base_value end test "#set_base_value should return true since it is a callback, just to be safe" do assert valid_term.send(:set_base_value) end def mock_wordnik_result [ { "citations" => [ {"cite" => "cite 1a"}, {"cite" => "cite 1b"} ], "text" => "text 1", "attributionText" => "text 1 attribution" }, { "citations" => [ {"cite" => "cite 2a"}, {"cite" => "cite 2b"} ], "text" => "text 2", "attributionText" => "text 2 attribution" }, ] end test "#populate_from_wordnik should test the call to the service" do Wordnik.word.expects(:get_top_example).raises(ClientError, "No top example found") Wordnik.word.expects(:get_definitions).with("pie", limit: 7, useCanonical: 'true').returns(mock_wordnik_result) term = FactoryGirl.create(:term) term.send(:populate_from_wordnik) assert_equal 2, term.details.size end test "#populate_from_wordnik should set the expected data" do Wordnik.word.expects(:get_top_example).raises(ClientError, "No top example found") Wordnik.word.expects(:get_definitions).with("pie", limit: 7, useCanonical: 'true').returns(mock_wordnik_result) term = FactoryGirl.create(:term) term.send(:populate_from_wordnik) detail = term.details.where(definition: "text 1").first assert_not_nil detail assert_equal "Wordnik / text 1 attribution", detail.source assert_equal "cite 1a \ncite 1b", detail.example end test "#populate_from_wordnik should set the top example if it finds one" do Wordnik.word.expects(:get_definitions).with("pie", limit: 7, useCanonical: 'true').returns(mock_wordnik_result) Wordnik.word.expects(:get_top_example).returns("text" => "top example", "title" => "top attribution") term = FactoryGirl.create(:term) term.send(:populate_from_wordnik) detail = term.details.where(top: true).first assert_not_nil detail assert_equal "Wordnik / top attribution", detail.source assert_equal "top example", detail.example end def mock_urban_result stub(entries: [ stub(definition: "a", example: "example a"), stub(definition: "b", example: "example b"), stub(definition: "c", example: nil), stub(definition: "d", example: nil) ]) end test "#populate_from_urban_dictionary should test the call to the service" do UrbanDictionary.expects(:define).with("pie").returns(mock_urban_result) term = FactoryGirl.create(:term) term.send(:populate_from_urban_dictionary) assert_equal 3, term.details.size end test "#populate_from_urban_dictionary should limit to the number passed in" do UrbanDictionary.expects(:define).with("pie").returns(mock_urban_result) term = FactoryGirl.create(:term) term.send(:populate_from_urban_dictionary, 2) assert_equal 2, term.details.size end test "#populate_from_urban_dictionary should pass if no entries are found" do UrbanDictionary.expects(:define).with("pie").returns(nil) term = FactoryGirl.create(:term) term.send(:populate_from_urban_dictionary) assert_equal 0, term.details.size end test "#populate_from_urban_dictionary should pull in the expected fields" do UrbanDictionary.expects(:define).with("pie").returns(mock_urban_result) term = FactoryGirl.create(:term) term.send(:populate_from_urban_dictionary) detail = term.details.where(definition: "a").first assert_not_nil detail assert_equal "example a", detail.example assert_equal "Urban Dictionary", detail.source assert detail.urban end end
true
52702fe3d22682e2361210bd97df4f08ef31dbef
Ruby
huffman442/Projects
/UnitConverter/unit_converter.rb
UTF-8
975
3.796875
4
[ "MIT" ]
permissive
class Mass def intake puts "Would you to convert to l)bs or to k)g?" l_or_k = gets.chomp puts "How much mass would you like to convert?" mass = gets.chomp if l_or_k == "l" metric_to_english(mass) elsif l_or_k == "k" english_to_metric(mass) end end def metric_to_english(mass) mass = mass.to_f * 2.20462 puts mass end def english_to_metric(mass) mass = mass.to_f / 2.20462 puts mass end end class Temperature def intake end def celcius_to_fahrenheit end class Currency end puts "Would you like to convert m)ass, t)emperature, c)urrency, or v)olume?" chosen_conversion = gets.chomp if chosen_conversion == "m" m = Mass.new m.intake() elsif chosen_conversion == "t" elsif chosen_conversion == "c" elsif chosen_conversion == "v" else puts "You haven't entered a valid choice please try again." end
true
bbedefc1c84d2f39110fa5cc2fdd20a56304e4af
Ruby
pcrunn/learning-ruby
/classes/person/Person_Test.rb
UTF-8
134
3.484375
3
[]
no_license
require './Person' alex = Person.new("Alexander", "P", 14) alex.welcome if alex.getAge < 15 puts "Wow, such a young developer." end
true
6094e14be4092522b8ed37bc515e13b719d8f875
Ruby
madelinecr/xkcd_scraper
/xkcd_scraper.rb
UTF-8
728
2.71875
3
[]
no_license
#!/usr/bin/env ruby require 'open-uri' require 'nokogiri' @uri = "http://www.xkcd.com/" @comics = Array.new doc = Nokogiri::HTML(open("#{@uri}/archive")) doc.xpath('//div[@id="middleContainer"]/a').each do |link| @comics << URI(link['href']) end @comics.each do |link| doc = Nokogiri::HTML(open("#{@uri}#{link}")) doc.xpath('//div[@id="comic"]').each do |image| image.children.each do |child| if child.node_name == 'img' uri = URI(child['src']) Net::HTTP.start(uri.host) do |http| resp = http.get(uri.path) open(File.basename(uri.path), "wb") do |file| file.write(resp.body) end end puts "Grabbing #{uri}" end end end end
true
099bce7ec442522c91341b570713c31acac07538
Ruby
bebbs/takeaway-challenge
/lib/order_interface.rb
UTF-8
1,728
3.78125
4
[]
no_license
require_relative 'phone' class OrderInterface include Phone def initialize(restaurant) @order = Order.new(restaurant) @menu = order.menu option_menu end attr_reader :order, :menu def option_menu loop do print_options_list handle(input) end end def input print "Input: " STDIN.gets.chomp end def print_options_list puts '1. View the menu' puts '2. Order a dish' puts '3. View order' puts '4. Confirm your order' puts '5. Quit' end def handle(option) case option when '1' then display_menu when '2' then add_to_order when '3' then view_order when '4' then confirm_order when '5' then exit else puts 'Sorry, that input is not recognised.' end end def display_menu display(:menu_header) display(:bar) menu.dishes.each {|dish| puts "#{dish.name}: £#{dish.price}"} display(:bar) end def add_to_order display(:bar) puts 'Which dish would you like to order?' print 'Enter the dish name: ' name_input = STDIN.gets.chomp print 'Quantity: ' quantity_input = STDIN.gets.chomp order.add_item(name_input, quantity_input.to_i) display(:bar) end def view_order puts 'Your order:' display(:bar) order.customer_order.each {|dish| puts "#{dish.name}: #{dish.price}"} display(:bar) end def confirm_order view_order send_text display(:confirmed) exit end def display(option) case option when :confirmed then puts 'Order confirmed!' when :menu_header then puts 'Dish: | Price: ' when :bar then puts '--------------------' end end end interface = OrderInterface.new('indian')
true
96924793d76c88c4c2accec3d922bb4ba5252a6d
Ruby
kaspth/activemodel-aggregator
/lib/active_model/aggregator/aggregation.rb
UTF-8
994
2.515625
3
[ "MIT" ]
permissive
require 'set' module ActiveModel module Aggregation extend ActiveSupport::Concern class_methods do def aggregate(name, required: nil) unless aggregates.include? name aggregates << name define_accessors(name, model_class_for(name)) validate_required_attributes(name, required) end end private def model_class_for(name) name.to_s.singularize.camelize.constantize end def aggregator_method(method_name) define_method method_name do aggregates.map { |a| send(a) }.all?(&method_name) end end def validate_required_attributes(prefix, required) if required validates_presence_of Array(required).map { |r| "#{prefix}_#{r}" } end end def aggregates @aggregates ||= Set.new end end private def aggregates self.class.send(:aggregates) end end end
true
2a375dbb50c86e015f7ec24860a28fed992fdbfb
Ruby
codystair/lc_book
/two_sum.rb
UTF-8
496
3.625
4
[]
no_license
# Brute Force # def two_sum(nums, target) # (0...nums.size).each do |i| # ((i + 1)...nums.size).each do |j| # if nums[i] + nums[j] == target # return [i + 1, j + 1] # end # end # end # end def two_sum(nums, target) map = {} (0...nums.size).each do |i| current_value = nums[i] if map[target - current_value] return [map[target - current_value] + 1, i + 1] else map[current_value] = i end end end p two_sum([4, 5, 7, 6, 9], 14)
true
bf084ea1ad4a6c3777a9419020560621fc2a9b3f
Ruby
teekenl/dailycodechallenge
/arithmeticTree.rb
UTF-8
369
3.828125
4
[]
no_license
class Node attr_accessor :val, :left, :right end def solve_arithmetic(node) return node.val.to_f if is_numeric?(node.val) return eval("#{solve_arithmetic(node.left)} #{node.val} #{solve_arithmetic(node.right)}") end def is_numeric?(string) true if Float(string) rescue false end # node = [*, +, +, 3, 4, 5, 6] # solve_arithemtic(node) => (3 + 4 ) * (5 + 6)
true
e83f90824c04f0fc56c8d30ec04f14b8853afe0d
Ruby
brentd/nstance
/lib/nstance/drivers/docker_api/excon/socket_hijack.rb
UTF-8
1,214
2.53125
3
[ "MIT" ]
permissive
module Nstance module Drivers module DockerAPI module Excon # This middleware allows us to hijack a HTTP request's socket so we can # read and write to it directly. class SocketHijack < ::Excon::Middleware::Base def response_call(datum) return @stack.response_call(datum) unless datum[:hijack] # Trick Excon's response parser into not attempting to read the # response body, or it would block forever. datum[:method] = "CONNECT" res = @stack.response_call(datum) # Set the raw Socket object on the response so we can access it. socket = datum[:connection].send(:socket) raw_socket = socket.instance_variable_get(:@socket) datum[:response][:socket] = raw_socket # Don't allow Excon to close or reuse this socket. The responsibility # of closing the socket is now on the caller. datum[:connection].send(:sockets).delete_if { |k,v| v == socket } if Proc === datum[:hijack] datum[:hijack].call(raw_socket) end res end end end end end end
true
6434c8c91e42b16de700101470778a39a01c4f48
Ruby
xeviknal/iot-control-plane
/user.rb
UTF-8
481
2.9375
3
[ "Apache-2.0" ]
permissive
class User attr_accessor :id, :rides_count, :first_ride_at, :last_ride_at, :current_ride_start_at, :current_ride_end_at def initialize(id) self.id = id self.rides_count = 0 end def start_ride self.first_ride_at = Time.now unless self.first_ride_at? self.last_ride_at = Time.now self.current_ride_start_at = Time.now self.rides_count = self.rides_count + 1 end def finish_ride self.current_ride_end_at = Time.now self.locked end end
true
045e7d068cbccaeb3c82d05d61cec511aa0aad9a
Ruby
octonion/volleyball-m
/ncaa_pbp/scrapers_tsv/ncaa_play_by_play.rb
UTF-8
3,189
2.546875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'csv' require 'mechanize' require 'nokogiri' require 'open-uri' require 'cgi' base_sleep = 0 sleep_increment = 3 retries = 4 agent = Mechanize.new{ |agent| agent.history.max_size=0 } agent.user_agent = 'Mozilla/5.0' base = "http://stats.ncaa.org/game/play_by_play" periods = CSV.open("tsv/ncaa_games_periods.tsv","w") notes = CSV.open("tsv/ncaa_games_notes.tsv","w") info = CSV.open("tsv/ncaa_games_info.tsv","w") officials = CSV.open("tsv/ncaa_games_officials.tsv","w") pbp = CSV.open("tsv/ncaa_games_play_by_play.tsv","w") files =[periods,notes,info,officials,pbp] data = [] ids = [] CSV.open("tsv/ncaa_team_schedules.tsv","r",{:col_sep => "\t", :headers => true}).each do |game| if not(game[19]==nil) game_id = game[19] ids << game_id.to_i end end ids.sort!.uniq! n = ids.size found = 0 ids.each_with_index do |game_id,i| url = "#{base}/#{game_id}" sleep_time = base_sleep print "Sleep #{sleep_time} ... " sleep sleep_time tries = 0 begin page = Nokogiri::HTML(open(url)) rescue sleep_time += sleep_increment print "sleep #{sleep_time} ... " sleep sleep_time tries += 1 if (tries > retries) next else retry end end found += 1 print "#{game_id} : #{i+1}/#{n}; found #{found}/#{n}\n" page.css("table").each_with_index do |table,i| if (i>3) if (i%2==0) next else file_id = 4 period = i/2 - 1 end else file_id = i end table.css("tr").each_with_index do |row,j| if (file_id==4) r = [game_id,period,j] else r = [game_id,j] end row.xpath("td").each_with_index do |d,k| l = d.text.delete("^\u{0000}-\u{007F}").strip r += [l] end if (r.size < 7) next else if (r[2].is_a? Integer) and (r[2]>0) rr = r[0..3] sa = r[4].split(',',2) if not(sa==[]) if (sa[0]==r[4]) last=nil else last = sa[0].strip end if (sa[1]==nil) sb = sa[0].split(' ',2) else sb = sa[1].split(' ',2) end first = sb[0].strip if sb[0] event = sb[1].strip if sb[1] rr += [last,first,event] else rr += [nil,nil,nil] end sa = r[5].split('-',2) rr += [sa[0].strip,sa[1].strip] sa = r[6].split(',',2) if not(sa==[]) if (sa[0]==r[6]) last=nil else last = sa[0].strip end if (sa[1]==nil) sb = sa[0].split(' ',2) else sb = sa[1].split(' ',2) end first = sb[0].strip if sb[0] event = sb[1].strip if sb[1] rr += [last,first,event] else rr += [nil,nil,nil] end files[file_id] << rr else next end end end end files.each do |file| file.flush end end files.each do |file| file.close end
true
35b9c47e8bfec204015a6c1740e6ef2295a8bfa9
Ruby
ahorner/advent-of-code
/spec/2016/09_spec.rb
UTF-8
1,077
2.640625
3
[]
no_license
require "spec_helper" RSpec.describe "Day 9: Explosives in Cyberspace" do let(:runner) { Runner.new("2016/09") } describe "Part One" do it "computes decompressed string lengths" do expect(runner.execute!("ADVENT", part: 1)).to eq(6) expect(runner.execute!("A(1x5)BC", part: 1)).to eq(7) expect(runner.execute!("(3x3)XYZ", part: 1)).to eq(9) expect(runner.execute!("A(2x2)BCD(2x2)EFG", part: 1)).to eq(11) expect(runner.execute!("(6x1)(1x3)A", part: 1)).to eq(6) expect(runner.execute!("X(8x2)(3x3)ABCY", part: 1)).to eq(18) end end describe "Part Two" do it "computes recursively decompressed string lengths" do expect(runner.execute!("ADVENT", part: 2)).to eq(6) expect(runner.execute!("(3x3)XYZ", part: 2)).to eq(9) expect(runner.execute!("X(8x2)(3x3)ABCY", part: 2)).to eq(20) expect(runner.execute!("(27x12)(20x12)(13x14)(7x10)(1x12)A", part: 2)).to eq(241_920) expect(runner.execute!("(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN", part: 2)).to eq(445) end end end
true
5f71751df07567d7f6f6c1f9daae5ebcc399451b
Ruby
alisonlutz28/tts_programs
/rails/quizapp/app/helpers/application_helper.rb
UTF-8
386
2.640625
3
[]
no_license
module ApplicationHelper def check_answer(answer) citylist = ["Atlanta", "Asheville", "Charlotte", "Raleigh"] correct = false citylist.each do |c| if answer == c correct = true end end return correct end def check_for_dup(answer,database) is_dup = false database.each do |d| if answer == d.name is_dup = true end end return is_dup end end
true
a5054e5e29d99164d8367b6810af0a87b0b7c4c3
Ruby
twill14/launchschool-OOP-Lessons
/OOP-Lesson-3-Excercises/variable_scopre.rb
UTF-8
1,279
3.8125
4
[]
no_license
# class Person # def initialize(n) # @name = n # end # def get_name # @name # end # end # bob = Person.new('bob') # bob.get_name # class Person # @@total_peeps = 0 # def self.total_peeps # @@total_peeps # end # def intitialize # @@total_peeps += 1 # end # def total_peeps # @@total_peeps # end # end # Person.total_peeps # Person.new # Person.new # Person.total_peeps # bob = Person.new # bob.total_peeps # joe = Person.new # joe.total_peeps # Person.total_peeps # class Person # TITLES = ['Mr', 'Mrs', 'Ms', 'Dr'] # attr_reader :name # def self.TITLES # TITLES.join(', ') # end # def initialize(n) # @name = "#{TITLES.sample} #{n}" # end # end # Person.TITLES # bob = Person.new('bob') # bob.name # module Swim # def enable_swimming # @can_swim = true # end # end # class Dog # include Swim # def swim # "swimming" if @can_swim # end # end # teddy = Dog.new # teddy.swim # class Dog # LEGS = 4 # end # class Cat # def legs # Dog::LEGS # end # end # class Vehicle # WHEELS = 4 # end # class Car < Vehicle # def self.wheels # WHEELS # end # def wheels # WHEELS # end # end # Car.wheels # a_car = Car.new # a_car.wheels
true
91e05e4249276ba7164c23eea790bfbad96d87b8
Ruby
Lyanov/lb7
/Part2/lr7_2.rb
UTF-8
295
3.359375
3
[]
no_license
# Word class class Word def initialize(arg) @word = arg end def length @word.length end def str @word end end # Word2 class class Word2 < Word def initialize(arg) @word = arg @length = @word.length end attr_reader :length def str @word end end
true
dbb1a437393a5b61d639ccd2e60492f7f3d207ad
Ruby
solyarisoftware/blomming_api
/examples/endpoints/buy/items_search.rb
UTF-8
818
2.796875
3
[ "MIT" ]
permissive
#!/bin/env ruby # encoding: utf-8 require 'blomming_api' if ARGV[0].nil? || ARGV[1].nil? puts " goal: test endpoint: items_search" puts " usage: #{$0} <config_file.yml> <keyword>" puts "example: ruby #{$0} $CONFIG \"ambient music FLAC\"" exit end config_file, keyword = ARGV c = BlommingApi::Client.new config_file puts "searching items for keyword: \"#{keyword}\"" all_items = c.all_pages (:stdout) { |page, per_page| c.items_search( keyword, {page: page, per_page: per_page} ) } puts "#{all_items.size} items found for keyword: #{keyword}:" if all_items.any? all_items.each_with_index { |item, index| puts "#{index+1}: title: #{item["title"]}, id: #{item["id"]}, shop: #{item["shop"]["id"]}" } puts "No items found for keyword: #{keyword}" unless all_items.any?
true
bd4ec9ffb1049ffabb9e23cfe3c836f72bfc39da
Ruby
akxcv/qonfig
/lib/qonfig/command_set.rb
UTF-8
1,357
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Qonfig # @api private # @since 0.1.0 class CommandSet # @return [Array<Qonfig::Commands::Base>] # # @api private # @since 0.1.0 attr_reader :commands # @api private # @since 0.1.0 def initialize @commands = [] @access_lock = Mutex.new end # @param command [Qonfig::Commands::Base] # @return [void] # # @api private # @since 0.1.0 def add_command(command) thread_safe { commands << command } end alias_method :<<, :add_command # @param block [Proc] # @return [Enumerable] # # @api private # @since 0.1.0 def each(&block) thread_safe { block_given? ? commands.each(&block) : commands.each } end # @param command_set [Qonfig::CommandSet] # @return [void] # # @api private # @since 0.1.0 def concat(command_set) thread_safe { commands.concat(command_set.commands) } end # @return [Qonfig::CommandSet] # # @api private # @since 0.2.0 def dup thread_safe do self.class.new.tap { |duplicate| duplicate.concat(self) } end end private # @param block [Proc] # @return [Object] # # @api private # @since 0.2.0 def thread_safe(&block) @access_lock.synchronize(&block) end end end
true
f4318a09f034e0f0e8feb53cc8f0e970a4de25e8
Ruby
JT1989/ruby-exercises
/exercises/find_even.rb
UTF-8
2,035
4.53125
5
[ "MIT" ]
permissive
# Method name: find_even # Inputs: An array of integers # Returns: An array of all the even integers appearing from the input array # If NO even integers are found, return an empty array # Prints: Nothing # For example, # # find_even([1,2,3,4,5,6]) == [2,4,6] # find_even([10,10,10,11,11,11]) == [10,10,10] def find_even(array) array.select { |number| number.even? } #http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-select end # Note #1 # There are two common ways to determine whether a number is even in Ruby # 1. if num.even? ... # 2. if num % 2 == 0 ... # # The "%" is called the "modulo operator". # http://en.wikipedia.org/wiki/Modulo_operation # # It returns the remainder after we divide the left-hand side by the # right-hand side. That means "num % 2" is the remainder after we divide # "num" by 2. If that remainder is 0 then num is even, i.e., num is a multiple # of 2. # Note #2 # If you want to append something to an existing array, use Array#push # http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-push # # It works like this: # # array = [1,2,3] # array.push("apple") # array == [1,2,3,"apple"] if __FILE__ == $0 # Here are some sanity checks written in "plain English". # See if you can translate them into Ruby. Your checks should look like # # p find_even(input) == ...expected return value... # If the input is the empty array, # find_even should return the empty array p find_even([]) == [] p find_even([1,2,3,4,5,6]) == [2,4,6] # If the input array contains all EVEN numbers, # find_even should return the input array p find_even([2,4,6,8,10]) == [2,4,6,8,10] p find_even([10,10,10,11,11,11]) == [10,10,10] # If the input array contains all ODD numbers, # find_even should return the empty array p find_even([1,3,9,13,21,1]) == [] # If an even number appears N times in the input array, # it should appear N times in the the array that find_even returns p find_even([-2,-4,-6,-8,-10]) == [-2,-4,-6,-8,-10] end
true
a8f1a13bde21bbdef0b8051c7e6ab0737efcf27f
Ruby
IuliiaKot/Checkers
/piece.rb
UTF-8
2,549
3.59375
4
[]
no_license
class Piece LEGAL_MOVE = [[-1, 1],[-1, -1],[1, 1],[1, -1]] attr_accessor :board, :pos, :color def initialize(board, color, pos, king = false) @board = board @color = color @pos = pos @king = king end def perform_slide(to_pos) current_x = pos[0] current_y = pos[1] return false unless legal_move?(to_pos) if (to_pos[0] - current_x).abs == 1 && (to_pos[1] - current_y).abs == 1 return true if board[to_pos].nil? end false end def perform_jump(to_pos) current_x = pos[0] current_y = pos[1] return false unless legal_move?(to_pos) return false unless check_next_square?(to_pos) if (to_pos[0] - current_x).abs == 2 && (to_pos[1] - current_y).abs == 2 return true if board[to_pos].nil? end false end def legal_move?(to_pos) board.valid_move(to_pos) end def check_next_square?(to_pos) if direction(to_pos) == :right && diff(to_pos) == :up next_x, next_y = pos[0] - 1, pos[1] + 1 elsif direction(to_pos) == :left && diff(to_pos) == :up next_x, next_y = pos[0] -1, pos[1] - 1 elsif direction(to_pos) == :right && diff(to_pos) == :down next_x, next_y = pos[0] + 1, pos[1] + 1 elsif direction(to_pos) == :left && diff(to_pos) == :down next_x, next_y = pos[0] + 1, pos[1] - 1 end return false if board[[next_x, next_y]].nil? return false if board[[next_x, next_y]].color == color return true end def direction(to_pos) x = pos[1] if x > to_pos[1] return :left else return :right end end def diff(to_pos) if pos[0] > to_pos[0] return :up else return :down end end def valid_move if perform_jump(to_pos) return true elsif perform_jump(to_pos) return ture else return false end end def move(to_pos) current_pos = pos p "current_pos #{current_pos}" p to_pos if valid_move(to_pos) current_pos = to_pos else raise "Invalid move" end end def perform_moves!(move_sequence) if move_sequence.length == 0 if !perform_slide(move_sequence) perform_jump(move_sequence) end end move_sequence.each do |square| move(square) end end def valid_mov_seq?(move_sequence) move_sequaence.each do |square| next if check_next_square?(square) return true end return false end def perform_move(move_sequence) if valid_mov_seq?(move_sequence) perform_moves!(move_sequence) end end
true
0b27629eafe61618a8c2a6e7407005f45d6e14ec
Ruby
yiivan/Quiz-1
/Q10.rb
UTF-8
392
3.375
3
[]
no_license
module HelperMethods def testing(class_name) puts "Yeah! This works for #{class_name}!" end end class MyInclude include HelperMethods end class MyExtend extend HelperMethods end #These will work: inc = MyInclude.new inc.testing("MyInclude") MyExtend.testing("MyExtend") # These will not work: # MyInclude.testing("MyInclude") # # inc = MyExtend.new # inc.testing("MyExtend")
true
f2d4b7bb8735c107249c43574f247a85fde0c8ec
Ruby
EmilZacharczuk/Week_01_weekend_homework
/pet_shop.rb
UTF-8
2,264
3.4375
3
[]
no_license
def pet_shop_name(shop) return shop[:name] end def total_cash(shop) return shop[:admin][:total_cash] end def add_or_remove_cash(shop, amount) return shop[:admin][:total_cash] += amount return shop[:admin][:total_cash] -= amount end def pets_sold(shop) return shop[:admin][:pets_sold] end def increase_pets_sold(shop, number_of_pets) return shop[:admin][:pets_sold] += number_of_pets end def stock_count(shop) # count = shop[:pets].length # return count # # or count = 0 for pet in shop[:pets] count += 1 end return count end def pets_by_breed(shop, breed_name) pets = [] for pet in shop[:pets] if pet[:breed] == breed_name pets.push(pet) end end return pets end def find_pet_by_name(shop, pet_name) for pet in shop[:pets] if pet[:name] == pet_name return pet end end return nil end def remove_pet_by_name(shop, pet_name) for pet in shop[:pets] if pet[:name] == pet_name shop[:pets].delete(pet) end end end def add_pet_to_stock(shop, pet_name) shop[:pets].push(pet_name) count = 0 for pet in shop[:pets] count += 1 end return count end def customer_cash(customer) return customer[:cash] end def remove_customer_cash(customer, amount) return customer[:cash] -= amount end def customer_pet_count(customer) return customer[:pets].count end def add_pet_to_customer(customer, pet) customer[:pets].push(pet) return customer_pet_count(customer) end def customer_can_afford_pet(customers, new_pet) if customers[:cash] <= new_pet[:price] return false else return true end end def sell_pet_to_customer(shop, pet, customer) if pet == nil customer_pet_count(customer) pets_sold(shop) customer_cash(customer) total_cash(shop) else add_pet_to_customer(customer, pet) increase_pets_sold(shop, 1) amount = customer[:pets][0] customer[:cash] -= amount[:price] customer_cash(customer) amount = customer[:pets][0] shop[:admin][:total_cash] += amount[:price] total_cash(shop) end new_pet = pet # if customer_can_afford_pet(customer, pet) == false # customer_pet_count(customer) # pets_sold(shop) # customer_cash(customer) # total_cash(shop) # end end
true
7a8cfb33bcf90b96af5312a8263db9b978b459ff
Ruby
zmoazeni/sqew
/spec/support/jobs.rb
UTF-8
330
2.578125
3
[ "MIT" ]
permissive
class TestJob @testing = 0 class << self def perform(arg) @testing = arg end def testing @testing end def reset @testing = 0 end end end class FailJob def self.perform(*) raise "failed in FailJob" end end class SlowJob def self.perform(secs) sleep secs end end
true
d28b6bef2906096676e156fef92bdd9bb56a462b
Ruby
fraser/pivotal-db
/lib/pivotal_db/cli.rb
UTF-8
1,678
2.609375
3
[]
no_license
require 'thor' module PivotalDb class CLI < Thor desc "stats", "stats" def stats tracker = Tracker.new(Settings[Settings[:project]]) puts "Projects: #{Project.all.count}" puts "Stories: #{Story.all.count}" puts "Notes: #{Note.all.count}" end desc "pull", "pull all stories from Pivotal Tracker (this may take a while)" def pull begin Tracker.new(Settings[Settings[:project]]).pull rescue DataMapper::SaveFailureError => e p e.resource.errors end end desc "random", "return a random incomplete story for review" def random tracker = Tracker.new(Settings[Settings[:project]]) puts puts tracker.random puts end desc "search", "search for the given term in the stories" method_option :includedone, :type => :boolean, :desc => "include done (finished, delivered, accepted) stories" def search(term) tracker = Tracker.new(Settings[Settings[:project]]) states = ["unscheduled", "unstarted", "started", "rejected"] if options.includedone? states += ["finished", "delivered", "accepted"] end found = tracker.search(term, states) puts "#{found.count} Results" found.each do |story| puts puts story.to_s(:brief) puts end end desc "show", "show a particular story by ID or URL" def show(story_id) tracker = Tracker.new(Settings[Settings[:project]]) story_id = story_id.gsub(/.*\//, "") story = Story.get(story_id) if story puts story.to_s(:detailed) else puts "No story found" end end end end
true
83fcc89c46fa09f25353422a9276f3d2c8a7cc77
Ruby
counterbeing/mars-rover-challenge
/specs/plateau_spec.rb
UTF-8
713
3.375
3
[]
no_license
require './classes/plateau.rb' describe Plateau do let(:plateau) { Plateau.new("5 5") } it "can be initialized" do expect(plateau.x).to eq(5) expect(plateau.y).to eq(5) end describe "checks for solid ground" do it "returns false when the point is not on the plateau" do ground = plateau.check_for_solid_ground(6,6) expect(ground).to be_falsey end it "returns true when the point is on the edge of the plateau" do ground = plateau.check_for_solid_ground(5,5) expect(ground).to be_truthy end it "returns true when the point is on the plateau" do ground = plateau.check_for_solid_ground(4,4) expect(ground).to be_truthy end end end
true
badabaf310df4620ced49ad223a7f68ec293e5ef
Ruby
icbd/focus_actor
/spec/user.rb
UTF-8
350
2.90625
3
[ "MIT" ]
permissive
require_relative '../lib/focus_actor/async' require_relative '../lib/focus_actor/future' class User include FocusActor::Async include FocusActor::Future attr_reader :name, :age def initialize(name) @name = name @age = 0 end def grow(cost = 0.1) sleep cost @age += 1 end end CASE_TIMES = 5 COST_TIME = 0.01 # second
true
0bdc9fadcbc10a83d35ce45fe9391685f32f7b23
Ruby
arunthampi/rdiff_match_patch
/spec/match/include_spec.rb
UTF-8
613
2.53125
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + '/../spec_helper.rb' describe "Including the RDiffMatchPatch module as part of a class" do before(:each) do class String include RDiffMatchPatch::Match end end it "should add fuzzy_match as an instance method of that class" do String.new.methods.include?('fuzzy_match').should == true String.methods.include?('fuzzy_match').should == false end it "should be able to fuzzy match a string correctly" do String.match_balance = 0.75 "I am the very model of a modern major general.".fuzzy_match(" that berry ", 5).should == 4 end end
true
5766e489becd56c8cef05e0ddbf1eb31f45c5e01
Ruby
Josephtsessions/mixtapes
/models/song.rb
UTF-8
379
2.609375
3
[]
no_license
require_relative './application_model' class Song < ApplicationModel attr_reader :id, :artist, :title def initialize(attributes) @id = attributes["id"] @artist = attributes["artist"] @title = attributes["title"] end def to_json(options = {}) {id: id, artist: artist, title: title} end protected def self.json_key "songs" end end
true
f3a7d2f50c480033bad4d927139f66b5fc4f9ffc
Ruby
code4tots/aa
/sql/UrlShortener/app/models/shortened_url.rb
UTF-8
1,262
2.59375
3
[]
no_license
class ShortenedUrl < ActiveRecord::Base validates :long_url, presence: true, uniqueness: true validates :short_url, presence: true, uniqueness: true validates :submitter_id, presence: true belongs_to(:submitter, foreign_key: :submitter_id, class_name: 'User') has_many(:visits, foreign_key: :shortened_url_id, class_name: 'Visit') has_many(:visitors, -> { distinct }, through: :visits, source: :visitor, class_name: 'User') def self.random_code # According to the docs, urlsafe_base64(n) creates a string # of rougly 4/3 * n. So I suppose it is reasonable to let n = 16, # and then just cut out the first 16 characters. while true code = SecureRandom.urlsafe_base64(16)[0...16] break unless exists?(short_url: code) end code end def self.create_for_user_and_long_url!(user, long_url) create!(submitter_id: user.id, long_url: long_url, short_url: random_code) end def num_clicks Visit.where(shortened_url_id: id).count end # Number of unique visitors who have clicked def num_uniques visitors.count end # Recently unique visitors def num_recent_uniques visitors.where("visits.created_at > ?", 10.minutes.ago).count end end
true
702d8ffc44cb9f024b782a996002b4d99624b9d8
Ruby
axenictech/ruby-programming
/purva/foreach/for.rb
UTF-8
36
2.765625
3
[]
no_license
a=[1,2,3,4,5] for i in a puts i end
true
b587ed123d40036cbb5e8d4f9efad6259447ee23
Ruby
sinatra/sinatra
/test/result_test.rb
UTF-8
2,085
2.734375
3
[ "MIT" ]
permissive
require_relative 'test_helper' class ThirdPartyError < RuntimeError def http_status; 400 end end class ResultTest < Minitest::Test it "sets response.body when result is a String" do mock_app { get('/') { 'Hello World' } } get '/' assert ok? assert_equal 'Hello World', body end it "sets response.body when result is an Array of Strings" do mock_app { get('/') { ['Hello', 'World'] } } get '/' assert ok? assert_equal 'HelloWorld', body end it "sets response.body when result responds to #each" do mock_app do get('/') do res = lambda { 'Hello World' } def res.each ; yield call ; end return res end end get '/' assert ok? assert_equal 'Hello World', body end it "sets response.body to [] when result is nil" do mock_app { get( '/') { nil } } get '/' assert ok? assert_equal '', body end it "sets status, headers, and body when result is a Rack response tuple" do mock_app { get('/') { [203, {'Content-Type' => 'foo/bar'}, 'Hello World'] } } get '/' assert_equal 203, status assert_equal 'foo/bar', response['Content-Type'] assert_equal 'Hello World', body end it "sets status and body when result is a two-tuple" do mock_app { get('/') { [409, 'formula of'] } } get '/' assert_equal 409, status assert_equal 'formula of', body end it "raises a ArgumentError when result is a non two or three tuple Array" do mock_app { get('/') { [409, 'formula of', 'something else', 'even more'] } } assert_raises(ArgumentError) { get '/' } end it "sets status when result is a Integer status code" do mock_app { get('/') { 205 } } get '/' assert_equal 205, status assert_equal '', body end it "sets status to 500 when raised error is not Sinatra::Error" do mock_app do set :raise_errors, false get('/') { raise ThirdPartyError } end get '/' assert_equal 500, status assert_equal '<h1>Internal Server Error</h1>', body end end
true
14c87c40e4cfcb195d6731be52df9b59a5c28769
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/1130/source/6769.rb
UTF-8
398
4.03125
4
[]
no_license
#Part 3: anagrams def combine_anagrams(words) results = Hash.new{|h, k| h[k] = []} words.each do |word| results[word.downcase.chars.sort(&:casecmp).join] << word end return results.values.sort end puts combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']).to_s puts combine_anagrams(['a', 'A']).to_s puts combine_anagrams(['Hello', 'hello']).to_s
true
f45c85617de23166d249c3099fcb0026703eccf0
Ruby
chaoshades/rmvx-ebjb-core
/src/User Controls/UCIcon.rb
UTF-8
2,999
2.765625
3
[ "MIT" ]
permissive
#============================================================================== # ** UCIcon #------------------------------------------------------------------------------ # Represents an Icon user control on a window #============================================================================== class UCIcon < UserControl #////////////////////////////////////////////////////////////////////////// # * Attributes #////////////////////////////////////////////////////////////////////////// # Image control to draw the icon attr_reader :cIcon # Icon index attr_accessor :iconIndex #////////////////////////////////////////////////////////////////////////// # * Properties #////////////////////////////////////////////////////////////////////////// #-------------------------------------------------------------------------- # * Set of the user control visibility #-------------------------------------------------------------------------- def visible=(visible) @visible = visible @cIcon.visible = visible end #-------------------------------------------------------------------------- # * Set of the user control activity #-------------------------------------------------------------------------- def active=(active) @active = active @cIcon.active = active end #////////////////////////////////////////////////////////////////////////// # * Constructors #////////////////////////////////////////////////////////////////////////// #-------------------------------------------------------------------------- # * Object Initialization # window : window in which the user control will be drawn # rect : rectangle to position the Image control # iconIndex : index of the Icon to draw # align : icon image alignment # opacity : icon image opacity # valign : icon image vertical alignment # active : control activity # visible : control visibility #-------------------------------------------------------------------------- def initialize(window, rect, iconIndex, align=0, opacity=255, valign=0, active=true, visible=true) super(active, visible) self.iconIndex = iconIndex @cIcon = CImage.new(window, rect, nil, nil, align, opacity, valign, active, visible) end #////////////////////////////////////////////////////////////////////////// # * Public Methods #////////////////////////////////////////////////////////////////////////// #-------------------------------------------------------------------------- # * Draw the icon on the window #-------------------------------------------------------------------------- def draw() if self.iconIndex != nil bitmap = Cache.system("IconSet") @cIcon.img_bitmap = bitmap @cIcon.src_rect = Rect.new(self.iconIndex % 16 * 24, self.iconIndex / 16 * 24, 24, 24) @cIcon.draw() end end end
true
8df3c8fdd910d93bed3a9da2d9e31dcb41e5a90e
Ruby
mrlhumphreys/just_shogi
/test/just_shogi/square_test.rb
UTF-8
1,799
2.96875
3
[ "MIT" ]
permissive
require 'minitest/autorun' require 'minitest/spec' require 'just_shogi/square' require 'just_shogi/pieces/fuhyou' describe JustShogi::Square do describe '#initialize' do it 'initializes the attributes' do square = JustShogi::Square.new(id: '55', x: 4, y: 4, piece: { id: 1, player_number: 2, type: 'fuhyou' }) assert_instance_of JustShogi::Fuhyou, square.piece end end describe '#promotion_zone' do describe 'when player 1' do describe 'and in lower ranks' do it 'returns true' do square = JustShogi::Square.new(id: '53', x: 4, y: 2, piece: nil) player_number = 1 assert square.promotion_zone(player_number) end end describe 'and it upper ranks' do it 'returns false' do square = JustShogi::Square.new(id: '54', x: 4, y: 3, piece: nil) player_number = 1 refute square.promotion_zone(player_number) end end end describe 'when player 2' do describe 'and in lower ranks' do it 'returns true' do square = JustShogi::Square.new(id: '57', x: 4, y: 6, piece: nil) player_number = 2 assert square.promotion_zone(player_number) end end describe 'and in upper ranks' do it 'returns true' do square = JustShogi::Square.new(id: '56', x: 4, y: 5, piece: nil) player_number = 2 refute square.promotion_zone(player_number) end end end describe 'when invalid player' do it 'raises error' do square = JustShogi::Square.new(id: '56', x: 4, y: 5, piece: nil) player_number = 3 assert_raises(ArgumentError) do square.promotion_zone(player_number) end end end end end
true
4add3795bf86e433a1e105443c3b451d3074c3c0
Ruby
D3nX/space_race
/rectangle.rb
UTF-8
650
3.203125
3
[]
no_license
class Rectangle attr_accessor :x, :y, :width, :height def initialize(x, y, width, height) @x = x @y = y @width = width @height = height end def draw Gosu.draw_rect( @x, @y, @width, @height, Color::WHITE, 500 ) end def collides?(rectangle) if !rectangle.is_a? Rectangle then raise "Error : This is not a rectangle !" end if rectangle.x + rectangle.width < @x or rectangle.x > @x + @width or rectangle.y + rectangle.height < @y or rectangle.y > @y + @height then return false end return true end end
true
1a2cee5c301c78e071c2e437c9d82917d4d3c75a
Ruby
weyewe/goguard
/app/models/lead.rb
UTF-8
2,117
2.90625
3
[]
no_license
require 'telegram/bot' class Lead < ActiveRecord::Base validate :phone_must_be_present , :valid_selected_product def phone_must_be_present if not phone_number.present? self.errors.add(:phone_number, "Nomor telpon harus ada") return self end end def valid_selected_product if not selected_product.present? self.errors.add(:selected_product, "Selected product harus dipilih") return self end if not ["1" , "2", "3"].include?( selected_product.to_s ) self.errors.add(:selected_product, "Salah selected product") return self end end def self.create_object( params ) new_object = self.new new_object.name = params[:name] new_object.email = params[:email] new_object.selected_product = params[:selected_product] new_object.phone_number = params[:phone_number] new_object.age = params[:age] new_object.address = params[:address] new_object.booking_date = params[:booking_date] new_object.selected_product = params[:selected_product] if new_object.save token = Rails.application.secrets.telebot_token chat_id = Rails.application.secrets.chat_group_id Telegram::Bot::Client.run(token) do |bot| msg = "" msg << "OrderID: #{new_object.id}" + "\n\n" msg << "Nama: " + new_object.name + "\n" msg << "No Telp: " + new_object.phone_number + "\n" msg << "Umur: " + new_object.age.to_s + "\n" msg << "Alamat: " + new_object.address + "\n" msg << "\n\nProduct: " if params[:selected_product].to_i == 1 msg << "Private bodyguard" + "\n" elsif params[:selected_product].to_i == 2 msg << "Driver" + "\n" elsif params[:selected_product].to_i == 3 msg << "Private bodyguard + Driver" + "\n" end msg << "Tgl Booking: " + new_object.booking_date + "\n" bot.api.send_message(chat_id: chat_id, text: msg ) end end return new_object end end
true
25600230c0b88cf8f9e7c0db2f386f42cc127d0f
Ruby
Dm1trySt/viselitsa
/viselitsa.rb
UTF-8
1,200
2.59375
3
[]
no_license
#(c) goodprogrammer.ru # Проверяем на какой ОС работаем, если windows - задаем кодировки if (Gem.win_platform?) Encoding.default_external = Encoding.find(Encoding.locale_charmap) Encoding.default_internal = __ENCODING__ [STDIN, STDOUT].each do io.set_encoding(Encoding.default_external, Encoding.default_internal) end end # Подключаем библиотеку unicode_utils. Предварительно её надо установить, набрав # в консоли: # gem install unicode_utils require_relative 'game.rb' require_relative 'result_printer.rb' require_relative 'word_reader.rb' current_path = File.dirname(__FILE__ ) puts "Игра виселица, v3" printer = ResultPrinter.new reader = WordReader.new # Считывает слово из командной строки # при вызове vilelitsa.rb slovo = reader.read_from_file(current_path + "/data/words.txt") game = Game.new(slovo) while game.status == 0 do # Вывод статуса игры printer.print_status(game) # Просим у пользователя новую букву game.ask_next_letter end printer.print_status(game)
true
2ceb3de07970250b0fa392cca455b2a6066ef9b9
Ruby
Soulou/aoc-2020
/20201204/main-1.rb
UTF-8
1,409
2.984375
3
[]
no_license
#!/usr/bin/env ruby # byr (Birth Year) # iyr (Issue Year) # eyr (Expiration Year) # hgt (Height) # hcl (Hair Color) # ecl (Eye Color) # pid (Passport ID) # cid (Country ID) validations = { "byr" => lambda do |v| v && v.to_i >= 1920 && v.to_i <= 2002 end, "iyr" => lambda do |v| v && v.to_i >= 2010 && v.to_i <= 2020 end, "eyr" => lambda do |v| v && v.to_i >= 2020 && v.to_i <= 2030 end, "hgt" => lambda do |v| next false if !v format = v.match(/^\d{3}cm$/) || v.match(/^\d{2}in$/) next false if !format if v.include?("cm") v.to_i >= 150 && v.to_i <= 193 else v.to_i >= 59 && v.to_i <= 76 end end, "hcl" => lambda do |v| v && v.match(/^#[a-f0-9]{6}$/) end, "ecl" => lambda do |v| v && %w(amb blu brn gry grn hzl oth).include?(v) end, "pid" => lambda do |v| v && v.match(/^\d{9}$/) end, "cid" => lambda do |v| true end, } input = File.read("input").split("\n") passports = [] passport = {} # Parsing input data input.each do |line| if line == "" passports.push(passport) passport = {} end line.split(" ").map{|field| field.split(":")}.each do |field| passport[field[0]] = field[1] end end passports.push(passport) # Validating passwords valid_passports = passports.select do |passport| validations.keys.inject(true) do |acc, key| acc = acc &valid = validations[key].call(passport[key]) end end puts valid_passports.length
true
add21249561c74f9ce20853aa5a4a18184c92b59
Ruby
HunterMeyer/Servitron
/lib/status_transition.rb
UTF-8
526
2.578125
3
[]
no_license
module StatusTransition module Status ACTIVE = 'Active'.freeze DISABLED = 'Disabled'.freeze ERASED = 'Erased'.freeze end def self.settings_for(*statuses) return settings unless statuses.present? settings.select { |status, _| statuses.include? status } end def self.settings { active: { value: Status::ACTIVE, toggle: :activate }, disabled: { value: Status::DISABLED, toggle: :disable }, erased: { value: Status::ERASED, toggle: :erase } } end end
true
884d385d7269006f61c00a58e6a272e7b6390b4e
Ruby
rsamp/app-academy-exercises-and-projects
/Week 1/Minesweeper/tile.rb
UTF-8
1,474
3.5625
4
[]
no_license
require 'byebug' require_relative 'board' class Tile attr_reader :pos, :board attr_accessor :value, :revealed POTENTIAL_NEIGHBORS_DIFF = [[0,1], [0,-1], [-1,0], [1,0], [1,1], [1,-1], [-1,1], [-1,-1]] def initialize(board, pos) @value = nil @revealed = false @board = board @pos = pos end def reveal # debugger puts "You blew up. Try again" if value == :bomb # puts "Already revealed" if revealed self.revealed = true if neighbor_bomb_count > 0 @value = neighbor_bomb_count else @value = "_" neighbors.each { |neighbor| neighbor.reveal unless neighbor.revealed} end end def within_bounds?(pos) (0..8).include?(pos[0]) && (0..8).include?(pos[1]) end def neighbor_bomb_count bomb_count = 0 neighbors.each { |neighbor| bomb_count += 1 if neighbor.value == :bomb } bomb_count end def check_neighbors potential_neighbors.select { |neighbor| within_bounds?(neighbor) } end def neighbors neighbors = [] check_neighbors.each do |neighbor| neighbors << board[neighbor] end neighbors end def potential_neighbors POTENTIAL_NEIGHBORS_DIFF.map { |diff| [self.pos[0] + diff[0], self.pos[1] + diff[1]]} end def inspect end end
true
87235e74d1a529ae88aa569d1197291ef387ee47
Ruby
Andrewsh86/exercism
/ruby/sieve/sieve.rb
UTF-8
326
3.484375
3
[]
no_license
class Sieve def initialize num @num = num end def primes return [] if @num < 2 list = (2..@num).to_a prime_arr = [] until list.empty? do prime_arr << list.shift list.map! do |x| (x % prime_arr.last).zero? ? nil : x end list.compact! end prime_arr end end
true
77ace3902abede2c0f6980a051a4f962093a3505
Ruby
flying-sphinx/plextail
/lib/plextail/line.rb
UTF-8
1,266
2.828125
3
[ "MIT" ]
permissive
# encoding: utf-8 class Plextail::Line DEFAULTS = { :version => '<134>1', :hostname => `hostname`.strip, :message_id => '- -' } attr_accessor :file, :raw, :token, :version, :timestamp, :hostname, :process_id, :message_id, :message def initialize(file, raw, &block) @file, @raw = file, raw @version = DEFAULTS[:version] @timestamp = current_timestamp @hostname = DEFAULTS[:hostname] @message_id = DEFAULTS[:message_id] @message = raw.dup block.call self if block_given? end def to_s unless valid? raise Plextail::InvalidLineError, "Missing #{missing_parts.join(', ')}" end string = parts.join(' ') "#{string.bytes.to_a.length} #{string}" end def valid? parts.all? { |part| part && part.length > 0 } end private def current_timestamp time = Time.now fraction = (".%06i" % time.usec)[0, 7] "#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}+00:00" end def missing_parts [ :version, :timestamp, :hostname, :token, :process_id, :message_id, :message ].select { |part| send(part).nil? || send(part).length == 0 } end def parts [version, timestamp, hostname, token, process_id, message_id, message] end end
true
ab4e3883f888fce5719c590bf7e45ff1b1555cfb
Ruby
taw/rlisp
/tests/test_tokenizer.rb
UTF-8
2,057
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require "minitest/autorun" require 'rlisp' class Test_Tokenizer < Minitest::Test def test_tokenizer code = '2.3 4 , ,@ ` ( ) [ ] foo bar x-y u19 #t #f bah "foo" "bar #{ 3 }" "#{1}" [] []= "#{a} #{b} #{c}"' rg = RLispGrammar.new(code) assert_equal([:expr, 2.3, 1, 0], rg.get_token) assert_equal([:expr, 4, 1, 4], rg.get_token) assert_equal([:unquote, nil, 1, 6], rg.get_token) assert_equal([:"unquote-splicing", nil, 1, 8], rg.get_token) assert_equal([:quasiquote, nil, 1, 11], rg.get_token) assert_equal([:open, nil, 1, 13], rg.get_token) assert_equal([:close, nil, 1, 15], rg.get_token) assert_equal([:sqopen, nil, 1, 17], rg.get_token) assert_equal([:sqclose, nil, 1, 19], rg.get_token) assert_equal([:expr, :foo, 1, 21], rg.get_token) assert_equal([:expr, :bar, 1, 25], rg.get_token) assert_equal([:expr, :"x-y", 1, 29], rg.get_token) assert_equal([:expr, :u19, 1, 33], rg.get_token) assert_equal([:expr, :true, 1, 37], rg.get_token) assert_equal([:expr, :false, 1, 40], rg.get_token) assert_equal([:expr, :bah, 1, 43], rg.get_token) assert_equal([:expr, "foo", 1, 47], rg.get_token) assert_equal([:istr_beg, "bar ", 1, 53], rg.get_token) assert_equal([:expr, 3, 1, 61], rg.get_token) assert_equal([:istr_end, "", 1, 63], rg.get_token) assert_equal([:istr_beg, "", 1, 66], rg.get_token) assert_equal([:expr, 1, 1, 69], rg.get_token) assert_equal([:istr_end, "", 1, 70], rg.get_token) assert_equal([:expr, :"[]", 1, 73], rg.get_token) assert_equal([:expr, :"[]=", 1, 76], rg.get_token) assert_equal([:istr_beg, "", 1, 80], rg.get_token) assert_equal([:expr, :a, 1, 83], rg.get_token) assert_equal([:istr_mid, " ", 1, 84], rg.get_token) assert_equal([:expr, :b, 1, 88], rg.get_token) assert_equal([:istr_mid, " ", 1, 89], rg.get_token) assert_equal([:expr, :c, 1, 93], rg.get_token) assert_equal([:istr_end, "", 1, 94], rg.get_token) assert_equal([:eof, nil, 1, 96], rg.get_token) end end
true
058ee31fee426d50c577b2814dd16373357d6c18
Ruby
AtmaVichara/ruby_blockchain
/lib/transaction.rb
UTF-8
893
3.203125
3
[]
no_license
require 'digest' class Transaction attr_reader :from, :to, :amount def initialize(from, to, amount, priv_key) @from = from # is a public key @to = to # is a public key @amount = amount @signature = PKI.sign(message, priv_key) # provide the signature to verify that you are who you are with your private key end def is_valid_signature? return true if genesis_transaction? # genesis_transaction is always true PKI.valid_signature?(message, @signature, from) # checking to see if key's match with signature's keys with message keys, and finally the from public key end def genesis_transaction? from.nil? end def message Digest::SHA256.hexdigest([@from, @to, @amount].join) # the message is the transaction data, and must be joined to keep data as small as possible for encryption since it is slow end def to_s message end end
true
efb5c7e416d59414d3922cf7ed6b2c291b44d6d4
Ruby
ianfleeton/zmey
/lib/ip_address.rb
UTF-8
612
3.109375
3
[ "MIT" ]
permissive
# frozen_string_literal: true class IPAddress attr_reader :value def initialize(value) @value = value end def to_s @value end # Returns a new IP Address that has been anonymized by setting the latter # portion to zero. def anonymize ipv4 = (m = value.match(/\d+\.\d+\.\d+\.\d+$/)) ? m[0] : "" ipv6 = value.gsub(ipv4, "") ipv6 += ":" if ipv4.present? && ipv6.present? ipv4 = ipv4.gsub(/\.\d+$/, ".0") ipv6 = ipv6.gsub(/:(\d|[a-f])*:(\d|[a-f])*:(\d|[a-f])*:(\d|[a-f])*:(\d|[a-f])*$/, "::") IPAddress.new([ipv6, ipv4].keep_if { |ip| ip.present? }.join) end end
true
342477406b81635a5df2999516c2c86151cc037f
Ruby
ranle/itunes_search
/lib/itunes_search/client.rb
UTF-8
859
2.59375
3
[ "MIT" ]
permissive
module ItunesSearch class Client MAX_TRIES = 5 def initialize(proxies = nil, username = nil, password = nil) @proxies = proxies @username = username @password = password end def get_html(url) response = nil tries = 0 begin if @proxies proxy = "http://#{@proxies.sample}" options = {} options[:proxy_http_basic_authentication] = [proxy, @username, @password] options[:ssl_verify_mode] = OpenSSL::SSL::VERIFY_NONE end obj = open(url, options) response = obj.read() Rails.logger.info('ItunesSearch get_html Success!') rescue => ex ex.backtrace.join("\n") if tries < MAX_TRIES tries += 1 retry else raise ex end end response end end end
true
e3d601c82bc9ce6abcb1670d94e4b822f6c4fc39
Ruby
nrice95/aA-homeworks
/W2D5/lru_cache.rb
UTF-8
615
3.484375
3
[]
no_license
class LRUCache attr_reader :size attr_accessor :cache def initialize(size) @size = size @cache = [] end def count # returns number of elements currently in cache self.cache.count end def add(el) idx = self.cache.index(el) unless idx.nil? self.cache.delete_at(idx) end self.cache << el self.cache.shift if count > self.size end def show # shows the items in the cache, with the LRU item first print self.cache puts self.cache end private # helper methods go here! end
true
4a09c14e25867397ba1de91c00340073e7cd0ad3
Ruby
lorrocha/senshi-sim
/lib/gameplay.rb
UTF-8
460
3.265625
3
[]
no_license
class Gameplay attr_accessor :usa def initialize(player) @usa = player @place = Locations.new end def randomizer rand(11) end def all_stats @usa.all_stats end def stat_check(stat, goal) @usa.send(stat.to_sym) + randomizer >= goal end def update_stat(stat, num) val = @usa.send("#{stat}") + num @usa.send("#{stat}=", val) end def goto(place) @place.send(place.to_sym).each do |key, val| update_stat(key, val) end end end
true
9ff8a3d56b0ecd552da957853cd4765cf3134525
Ruby
Rsaphra/badges-and-schedules-nyc-web-051319
/conference_badges.rb
UTF-8
701
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def badge_maker(name) "Hello, my name is #{name}." end def room_maker(name, counter) "Hello, #{name}! You'll be assigned to room #{counter}!" end def assign_rooms(names) room_list = [] counter = 1 names.each do |name| room_list.push(room_maker(name, counter)) counter += 1 end return room_list end def batch_badge_creator(names) badge_array = [] names.each do |name| badge_array.push(badge_maker(name)) end return badge_array end def printer(attendees) room_list = assign_rooms(attendees) badge_list = batch_badge_creator(attendees) room_list.each do |room| puts room end badge_list.each do |badge| puts badge end end
true
49c3dab9101064d0e5974beaadf06e53e7746329
Ruby
shostakovich/Todo-Void
/features/step-definitions/status_changes_steps.rb
UTF-8
1,195
2.546875
3
[ "MIT" ]
permissive
When /^I provide the option "(.*?)" plus the hash of a todo$/ do |option| TodoVoid.new([option, "cab959"]).execute end When /^I provide the opion "(.*?)" plus the partial hash of a todo$/ do |option| TodoVoid.new([option, "ca"]).execute end When /I provide the option "(.*?)" and a conflicting partial hash/ do |option| @output = TodoVoid.new([option, "18"]).execute end When /^I provide the option "(.*?)" and a non\-existent hash$/ do |option| @output = TodoVoid.new([option, "foobar"]).execute end Then "this todo should be deleted" do output = TodoVoid.new.execute output.should_not =~ /cab959/ end Then "this todo should be marked finished" do output = TodoVoid.new.execute output.should =~ /\e\[30mcab959 todo1/ end Then "this todo should be marked current" do output = TodoVoid.new.execute output.should =~ /\e\[32mcab959/ end Then "I should be notified about a conflict" do @output.should =~ /Conflicting part of an id provided please be more specific/ end Then /^I should be notified about the erronious hash$/ do @output.should =~ /There is no todo with matching id/ end Then "I should see the list of alternatives" do @output.should =~ /todo3/ end
true
586b5511b3449f61ac399269e2db4c0df60634e1
Ruby
mlyubarskyy/leetcode
/350_intersection_of_two_array2.rb
UTF-8
321
3.296875
3
[]
no_license
# @param {Integer[]} nums1 # @param {Integer[]} nums2 # @return {Integer[]} def intersect(nums1, nums2) map = {} (0...nums1.size).each do |i| map[nums1[i]] ||= 0 map[nums1[i]] += 1 end res = [] nums2.each do |el| if map[el] && map[el] > 0 res << el map[el] -= 1 end end res end
true
cbc7a12c089730c2eee58a1d331d1a8eba933f25
Ruby
sanzstv/tcbot
/twitterbot.rb
UTF-8
1,083
2.515625
3
[]
no_license
#!/usr/bin/env ruby require 'Twitter' require_relative 'queries' require_relative 'cache' #` this bot (still in progress) is meant to monitor crime/mystery related topics on The Twitter # caccepts optional list of queries as command line argument in the format: # ruby twitterbot.rb "query 1" "query 2" ... # if no arguments are provided, file will default to list of queries specified in 'queries.rb' config = { consumer_key: ENV['TWITTER_CKEY'], consumer_secret: ENV['TWITTER_CSECRET'], access_token: ENV['TWITTER_ACCESSTOKEN'], access_token_secret: ENV['TWITTER_AT_SECRET'] } client = Twitter::REST::Client.new(config) #TEST MSG search_params = { result_type: "recent", count: "1", lang: "en" } queries = [] if ARGV.length > 0 ARGV.each do |query| queries.push(query) end else queries= TCBotSearch.keyphrases end queries.each do |query| client.search(query, search_params).take(3).each do |tweet| #don't want to retweet multiple times if tweet.retweeted_status? == false client.retweet tweet end end end
true