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
0ece8c46c2f9ba68023f518840343914161b5d7f
Ruby
feigningfigure/WDI_NYC_Apr14_String
/w01/d05/Jane_Shin/animal_shelter/classes/client.rb
UTF-8
527
3.8125
4
[]
no_license
class Client attr_accessor :name, :age, :pets def initialize(client_name, client_age) @name = client_name @age = client_age @pets = Hash.new #make hash, change errthing else end def pet_count @pets.length end def display_pets @pets.each {|pet, pet_attr| puts pet} end def give_away_pet(pet_name) if @pets.include?(pet_name) @pets.delete(pet_name) end end def accept_pet(name, owner) @pets[name] = owner end def to_s "#{@name} is a #{@age} year old with #{@pets.length} pets" end end
true
dc787ec0cc51cfa4824ac6fc57fe42a80399faa2
Ruby
TyMazey/enigma
/lib/key_generator.rb
UTF-8
217
3.234375
3
[]
no_license
class KeyGenerator def initialize @numbers = (0..9) end def randomizer rand(@numbers).to_s end def self.create(length) key = new length.times.collect {|num| key.randomizer}.join end end
true
2f1315204f46b446d2530fdbb53630fb7b54906a
Ruby
AdrianTuckwell/cinema
/models/ticket.rb
UTF-8
1,435
3.296875
3
[]
no_license
require_relative("../db/sql_runner") class Ticket attr_reader :id, :customer_id, :film_id def initialize( options ) @id = options['id'].to_i @customer_id = options['customer_id'].to_i @film_id = options['film_id'].to_i end # ----- Save Ticket ---------------------- def save() sql = "INSERT INTO tickets (customer_id, film_id) VALUES (#{ @customer_id }, #{ @film_id }) RETURNING *" ticket = SqlRunner.run(sql).first @id = ticket['id'].to_i end #------------ Edit ticket --------------------- def update sql = "UPDATE tickets SET customer_id = '#{@customer_id}', film_id = '#{@film_id}' WHERE id = #{@id};" SqlRunner.run(sql) return nil end #------------ Delete ticket by id ---------------- def self.delete(id) sql = "DELETE FROM tickets WHERE id = #{id}" SqlRunner.run(sql) end #------------ Delete all tickets ------------------ def self.delete_all() sql = "DELETE FROM tickets" SqlRunner.run(sql) end #------------ Read all tickets ------------------ def self.all() sql = "SELECT * FROM tickets" return Ticket.map_items(sql) end def self.map_items(sql) tickets = SqlRunner.run( sql ) result = tickets.map { |ticket| Ticket.new( ticket ) } return result end def self.map_item(sql) result = Ticket.map_items(sql) return result.first end end #--- Ticket class end ------------------
true
e684012ece3195d67855baacb5adf707c21d414c
Ruby
elliottwilliams/XcodeMove
/lib/xcmv.rb
UTF-8
2,237
2.71875
3
[]
no_license
# frozen_string_literal: true require 'xcodeproj' require_relative 'xcmv/file' require_relative 'xcmv/header_visibility' require_relative 'xcmv/group_membership' require_relative 'xcmv/project_cache' require_relative 'xcmv/version' # Moves files on disk and between Xcode projects. module XcodeMove class InputError < RuntimeError end class << self # Moves from one `Pathname` to another def mv(src, dst, options) src_file = src.directory? ? Group.new(src) : File.new(src) dst_file = dst.directory? ? src_file.with_dirname(dst) : src_file.class.new(dst) puts("#{src_file.path} => #{dst_file.path}") project_mv(src_file, dst_file, options) disk_mv(src_file, dst_file, options) save(src_file, dst_file) end private # Prepare the project file(s) for the move def project_mv(src_file, dst_file, options) if src_file.path.directory? # Process all children first children = src_file.path.children.map { |c| c.directory? ? Group.new(c) : File.new(c) } children.each do |src_child| dst_child = src_child.with_dirname(dst_file.path) project_mv(src_child, dst_child, options) end else # Remove old destination file reference if it exists dst_file.remove_from_project if dst_file.pbx_file # Add new destination file reference to the new xcodeproj dst_file.create_file_reference dst_file.add_to_targets(options[:targets], options[:headers]) end # Remove original directory/file from xcodeproj if src_file.pbx_file src_file.remove_from_project else warn("⚠️ Warning: #{src_file.path.basename} not found in #{src_file.project.path.basename}, moving anyway...") end end # Move the src_file to the dst_file on disk def disk_mv(src_file, dst_file, options) mover = options[:git] ? 'git mv' : 'mv' command = "#{mover} '#{src_file.path}' '#{dst_file.path}'" system(command) || raise(InputError, "#{command} failed") end # Save the src_file and dst_file project files to disk def save(src_file, dst_file) src_file.save_and_close dst_file.save_and_close end end end
true
a9e6c4cc5a8027c3d83f78aee721e223782122bb
Ruby
blh0021/screen_driver
/lib/driver/mouse.rb
UTF-8
992
2.875
3
[]
no_license
module ScreenDriver class Mouse def mouse_move(x, y) mouse = Robot.new mouse.mouseMove(x, y) end def left_click(x, y) mouse = Robot.new mouse.mouseMove(x,y) mouse.mousePress(InputEvent::BUTTON1_MASK); mouse.mouseRelease(InputEvent::BUTTON1_MASK); #Java 7+ Only #mouse.mousePress(InputEvent::BUTTON1_DOWN_MASK); #mouse.mouseRelease(InputEvent::BUTTON1_DOWN_MASK); end def double_click(x, y) mouse = Robot.new mouse.mouseMove(x, y) mouse.mousePress(InputEvent::BUTTON1_MASK); mouse.mouseRelease(InputEvent::BUTTON1_MASK); mouse.mousePress(InputEvent::BUTTON1_MASK); mouse.mouseRelease(InputEvent::BUTTON1_MASK); #Java 7+ Only #mouse.mousePress(InputEvent::BUTTON1_DOWN_MASK); #mouse.mouseRelease(InputEvent::BUTTON1_DOWN_MASK); #mouse.mousePress(InputEvent::BUTTON1_DOWN_MASK); #mouse.mouseRelease(InputEvent::BUTTON1_DOWN_MASK); end end end
true
3fb79fa9d38d672ad6ed06564780a69c5afae36c
Ruby
ivhq/thisdata-ruby
/test/this_data/event_test.rb
UTF-8
1,219
2.515625
3
[ "MIT" ]
permissive
require_relative "../test_helper.rb" class ThisData::EventTest < ThisData::UnitTest test "can get all events" do response = { total: 10, results: [ {id: "1", overall_score: 0.5, user: {id: 112233}}, {id: "2", overall_score: 0.1, user: {id: 445566}} ] } expected_path = URI.encode("https://api.thisdata.com/v1/events?api_key=#{ThisData.configuration.api_key}") FakeWeb.register_uri(:get, expected_path, status: 200, body: response.to_json, content_type: "application/json") events = ThisData::Event.all assert_equal 2, events.length assert_equal "1", events.first.id assert_equal 445566, events.last.user.id end test "can filter events" do expected_query= { api_key: ThisData.configuration.api_key, user_id: 112233, limit: 25, foo: "bar" } response = {total: 0, results: []} expected_path = URI.encode("https://api.thisdata.com/v1/events?#{URI.encode_www_form(expected_query)}") FakeWeb.register_uri(:get, expected_path, status: 200, body: response.to_json, content_type: "application/json") ThisData::Event.all( user_id: 112233, limit: 25, foo: "bar" ) end end
true
a60521e67d4ced1b37f81e57068af248ab9e3ea8
Ruby
marcusfgardiner/ruby-refresher
/lib/questions.rb
UTF-8
14,388
4.4375
4
[]
no_license
# keep only the elements that start with an a def select_elements_starting_with_a(array) array.select {|i| i[0] == "a"} end # keep only the elements that start with a vowel def select_elements_starting_with_vowel(array) array.select {|i| i[0] == "a" || i[0] =="e" || i[0] == "i" || i[0] == "o" || i[0] == "u"} end # remove instances of nil (but NOT false) from an array def remove_nils_from_array(array) array.select {|i| i != nil} end # remove instances of nil AND false from an array def remove_nils_and_false_from_array(array) array.select {|i| i != nil && i != false } end # don't reverse the array, but reverse every word inside it. e.g. # ['dog', 'monkey'] becomes ['god', 'yeknom'] def reverse_every_element_in_array(array) new_array = Array.new array.each {|element| new_array << element.reverse } new_array end # given an array of student names, like ['Bob', 'Dave', 'Clive'] # give every possible pairing - in this case: # [['Bob', 'Clive'], ['Bob', 'Dave'], ['Clive', 'Dave']] # make sure you don't have the same pairing twice, def every_possible_pairing_of_students(array) # 1 - 1st with 2nd, 3rd ... final i = 1 current_student = 0 max = array.size new_array = [] array.each {|student| # 3 - final does nothing while i < max new_array << [student,array[i]] i += 1 end # 2 - 2nd with 3rd, 4th ... final current_student += 1 i = 1 + current_student } new_array end # discard the first 3 elements of an array, # e.g. [1, 2, 3, 4, 5, 6] becomes [4, 5, 6] def all_elements_except_first_3(array) array[3..-1] end # add an element to the beginning of an array def add_element_to_beginning_of_array(array, element) array.unshift(element) end # sort an array of words by their last letter, e.g. # ['sky', 'puma', 'maker'] becomes ['puma', 'maker', 'sky'] def array_sort_by_last_letter_of_word(array) new_array = Array.new array.each {|element| new_array << element.reverse } new_array.sort! new_array2 = Array.new new_array.each {|element| new_array2 << element.reverse } new_array2 end # cut strings in half, and return the first half, e.g. # 'banana' becomes 'ban'. If the string is an odd number of letters # round up - so 'apple' becomes 'app' def get_first_half_of_string(string) # Find string length # half string length # if odd, add one string_length = string.size string_length += 1 if string_length.odd? half_string_length = string_length/2 string[0..(half_string_length-1)] #return string up to half end # turn a positive integer into a negative integer. A negative integer # stays negative def make_numbers_negative(number) new_number = number if number < 0 new_number = -number if number > 0 new_number end # turn an array of numbers into two arrays of numbers, one an array of # even numbers, the other an array of odd numbers # even numbers come first # so [1, 2, 3, 4, 5, 6] becomes [[2, 4, 6], [1, 3, 5]] def separate_array_into_even_and_odd_numbers(array) #Find out if each element even or odd # if even, put into one array # if odd, put into other array # combine arrays even_array = Array.new odd_array = Array.new final_array = Array.new array.each{|number| if number.odd? odd_array << number else even_array << number end } final_array = [even_array,odd_array] end # count the numbers of elements in an element which are palindromes # a palindrome is a word that's the same backwards as forward # e.g. 'bob'. So in the array ['bob', 'radar', 'eat'], there # are 2 palindromes (bob and radar), so the method should return 2 def number_of_elements_that_are_palindromes(array) # reverse the element # check if reversed element is same as previous element # add one to the count if yes count = 0 array.each {|element| count += 1 if element == element.reverse } count end # return the shortest word in an array def shortest_word_in_array(array) # check each element of array # if the shortest, update the shortest word shortest_word = array[0] array.each {|word| shortest_word = word if shortest_word.size>word.size } shortest_word end # return the longest word in an array def longest_word_in_array(array) longest_word = array[0] array.each {|word| longest_word = word if longest_word.size<word.size } longest_word end # add up all the numbers in an array, so [1, 3, 5, 6] # returns 15 def total_of_array(array) # iterate through array # have a sum variable keeping track # add to sum variable each time sum = 0 array.each {|x| sum += x } sum end # turn an array into itself repeated twice. So [1, 2, 3] # becomes [1, 2, 3, 1, 2, 3] def double_array(array) array*2 end # convert a symbol into a string def turn_symbol_into_string(symbol) symbol.to_s end # get the average from an array, rounded to the nearest integer # so [10, 15, 25] should return 17 def average_of_array(array) sum = 0 array.each {|x| sum += x } (sum.round(2) / array.size).round end # get all the elements in an array, up until the first element # which is greater than five. e.g. # [1, 3, 5, 4, 1, 2, 6, 2, 1, 3, 7] # becomes [1, 3, 5, 4, 1, 2] def get_elements_until_greater_than_five(array) # go through array putting into new array # if greater than 5, stop new_array = [] array.each {|x| break if x > 5 new_array << x } new_array end # turn an array (with an even number of elements) into a hash, by # pairing up elements. e.g. ['a', 'b', 'c', 'd'] becomes # {'a' => 'b', 'c' => 'd'} def convert_array_to_a_hash(array) # work out how many key value pairs #loop through adding keys and values hash=Hash.new number_of_keys = (array.size) number_of_keys.times {|i| next if i.odd? hash[array[i]] = array[i+1] } hash end # get all the letters used in an array of words and return # it as a array of letters, in alphabetical order # . e.g. the array ['cat', 'dog', 'fish'] becomes # ['a', 'c', 'd', 'f', 'g', 'h', 'i', 'o', 's', 't'] def get_all_letters_in_array_of_words(array) #go through each word new_array = [] array.each {|word| new_array << word.split(//) } new_array.flatten.sort #separate each letter and add to new array of letters - .split(//) #take all letters and sort for alphabet end # swap the keys and values in a hash. e.g. # {'a' => 'b', 'c' => 'd'} becomes # {'b' => 'a', 'd' => 'c'} def swap_keys_and_values_in_a_hash(hash) hash.invert end # in a hash where the keys and values are all numbers # add all the keys and all the values together, e.g. # {1 => 1, 2 => 2} becomes 6 def add_together_keys_and_values(hash) #Extract all keys and values #Sum all items new_array = [] new_array << hash.keys new_array << hash.values new_array = new_array.flatten sum = 0 new_array.each {|x| sum += x } sum end # take out all the capital letters from a string # so 'Hello JohnDoe' becomes 'ello ohnoe' def remove_capital_letters_from_string(string) #iterate through letter by letter and see if caps = what it was before new_string = "" string.split("").each {|letter| new_string << " " if letter == " " if letter != letter.capitalize new_string << letter end } new_string #if yes, don't put the letter into a new string # if not a capital, do put the letter in a new string #final value is the string end #----------------------------------------------------- Did this on Mac - need to pull the updates in # round up a float up and convert it to an Integer, # so 3.214 becomes 4 def round_up_number(float) end # round down a float up and convert it to an Integer, # so 9.52 becomes 9 def round_down_number(float) end # take a date and format it like dd/mm/yyyy, so Halloween 2013 # becomes 31/10/2013 def format_date_nicely(date) end # get the domain name *without* the .com part, from an email address # so alex@makersacademy.com becomes makersacademy def get_domain_name_from_email_address(email) end # capitalize the first letter in each word of a string, # except 'a', 'and' and 'the' # *unless* they come at the start of the start of the string, e.g. # 'the lion the witch and the wardrobe' becomes # 'The Lion the Witch and the Wardrobe' def titleize_a_string(string) end #-----------------------------------------------------Did this on Mac - need to pull the updates in # return true if a string contains any special characters # where 'special character' means anything apart from the letters # a-z (uppercase and lower) or numbers def check_a_string_for_special_characters(string) true_or_false = false # collect all non-special characters chars = [] chars = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a + (0..9).to_a + ["0","1","2","3","4","5","6","7","8","9"] chars << " " # check each part of string to see if any special characters string.split("").each {|character| if !chars.include?(character) true_or_false = true else next end } true_or_false end # get the upper limit of a range. e.g. for the range 1..20, you # should return 20 def get_upper_limit_of(range) range.max end # should return true for a 3 dot range like 1...20, false for a # normal 2 dot range def is_a_3_dot_range?(range) range.to_s.include?("...") end # get the square root of a number def square_root_of(number) Math.sqrt(number) end # count the number of words in a file def word_count_a_file(file_path) word_count = 0 f = File.open(file_path, "r") f.each_line {|line| word_count += line.to_s.split.size } word_count end # --- tougher ones --- # call an arbitrary method from a string. so if I # called call_method_from_string('foobar') # the method foobar should be invoked def call_method_from_string(str_method) send(str_method) end # return true if the date is a uk bank holiday for 2014 # the list of bank holidays is here: # https://www.gov.uk/bank-holidays def is_a_2014_bank_holiday?(date) # e.g. year, month, day # date format: Time.local(1976, 8, 3) y = 2014 # store array of bank holiday dates array = [Time.local(y,12,25),Time.local(y,12,26),Time.local(y,8,25),Time.local(y,5,26),Time.local(y,5,5),Time.local(y,4,21),Time.local(y,4,18),Time.local(y,1,1)] # check if date can be found in array array.each {|bank_hol_date| return true if bank_hol_date == date } false # if yes - return true # if no - return false end # given your birthday this year, this method tells you # the next year when your birthday will fall on a friday # e.g. january 1st, will next be a friday in 2016 # return the day as a capitalized string like 'Friday' def your_birthday_is_on_a_friday_in_the_year(birthday) # Key: tells you the YEAR where birthday will be on a Fri # each year = moves up 2 days loop { if birthday.friday? == true return birthday.year end # key -> don't need to account for day of week change in addition, only 1 year onwards - the .friday? will work out what day of the week it is birthday = birthday + (365*24*60*60) } end # in a file, total the number of times words of different lengths # appear. So in a file with the text "the cat sat on the blue mat" # I have 5 words which are 3 letters long, 1 which is 2 letters long # and 1 that is 4 letters long. Return it as a hash in the format # word_length => count, e.g. {2 => 1, 3 => 5, 4 => 1} def count_words_of_each_length_in_a_file(file_path) # take each word, get the size and store it word_size_array = Array.new f = File.read(file_path) f.split.each {|word| word_size_array << word.gsub(/[.,]/,"").size } # count the frequency of each number #store in a hash # give hash default value of 0 to avoid nil class issue, that way, for each key, counting up by 1 hash = Hash.new(0) word_size_array.each {|x| hash[x] += 1 } hash end # implement fizzbuzz without modulo, i.e. the % method # go from 1 to 100 # (there's no RSpec test for this one) def fizzbuzz_without_modulo please enter a number puts "Please enter a whole number, no decimals" input = gets.chomp.to_i ######################### Uncomment this to TEST ALL 1-100 #100.times do |i| # input = i ######################################### #Work around: if #.0/# - #/# > 0 #if multiple of 3 or 5, fizzbuzz if (input/3.0) - (input/3) == 0 && (input/5.0) - (input/5) == 0 puts "fizzbuzz" #if multiple of 3, fizz elsif (input/3.0) - (input/3) == 0 puts "fizz" #if multiple of 5, buzz elsif (input/5.0) - (input/5) == 0 puts "buzz" else puts input.to_s end ######################################### # end end # Uncommented this to test fizzbuzz: ##### fizzbuzz_without_modulo # print the lyrics of the song 99 bottles of beer on the wall # http://www.99-bottles-of-beer.net/lyrics.html # make sure you use the singular when you have one bottle of # beer on the wall, and print 'no more bottles of beer on the wall' # at the end. # (there's no RSpec test for this one) def ninety_nine_bottles_of_beer #99 bottles of beer on the wall, 99 bottles of beer. #Take one down and pass it around, 98 bottles of beer on the wall. number_of_bottles = 99 while number_of_bottles > 1 puts "#{number_of_bottles} bottles of beer on the wall, #{number_of_bottles} bottles of beer" puts "Take one down and pass it around, #{number_of_bottles - 1} bottles of beer on the wall." number_of_bottles -= 1 end ################################# puts "1 bottle of beer on the wall, 1 bottle of beer" puts "Take one down and pass it around, no more bottles of beer on the wall." ################################# puts "No more bottles of beer on the wall, no more bottles of beer." puts "Go to the store and buy some more, 99 bottles of beer on the wall." end ninety_nine_bottles_of_beer
true
2cf71e73d42ddc842e6ccd6ccc8c888ffe3f463d
Ruby
Sproodigy/goods_cards
/training_ruby/books_on_ruby.rb
UTF-8
4,396
3.453125
3
[]
no_license
require 'active_support/all' require 'csv' # def name # while true # names = [] # print 'Name:' # response = gets # case response # when /^[a-zA-Z]/ # names << response # puts response # when /^[0-9]/, /^$/ # puts 'Jerk' # when /[q]/ # puts names # return true # end # end # end # def name # while true # print 'Name: ' # name = gets.chomp # names = [] # count = names << name # array = Array.new(count.count) # puts array # end # end # name class Sequence include Enumerable def initialize(from, to, by) @from, @to, @by = from, to, by end module Sequences def self.fromtoby(from, to, by) x = from while x <= to yield x x += by end end end def each x = @from while x <= @to yield x x += @by end end def length return 0 if @from > @to Integer ((@to-@from)/@by) + 1 end def[](index) retutn nil if index < 0 v = @from + index*@by if v <= @to v else nil end end def *(factor) Sequence.new(@from*factor, @to*factor, @by*factor) end def +(offset) Sequence.new(@from+offset, @to+offset, @by) end # s = Sequence.new(1, 10, 2) # s.each { |x| p x } # print s[s.length-1] # t = (s+1)*2 # p t # Sequences.fromtoby(1, 20, 2) { |x| p x} end # class User # @@users_count = 0 # # def initialize(login, password, email) # @id = @@users_count += 1 # @login = login # @password = password # @email = email # end # # def user_data # @user_data ||= # { # id: @id, # login: @login, # password: @password, # email: @email # } # end # # def just # puts 'Just an inscription' # end # # def self.users_count # @@users_count # end # # end # user = User.new('John', '123', 'sample@mail.ru') # user = User.new('Smith', '456', 'another@mail.ru') # user.just # User.just # puts user.user_data # p = Array.new( ( print "Введите размерность массива: " ; gets.to_i ) ){ |i| # print "Введите #{i}-й элемент массива: " ; gets.to_f } # puts p # # Dragon.new('Jilly') # Dragon.new('Wally') # Dragon.new('Flippy') # Dragon.count class Ranged def by(start, step) start = self.begin if exclude_end? while start < self.end yield start start += step end else while start <= self.end yield start start += step end end end # (0..40).by(10) do |d| # p d # end end def doSelfImportantly (proct) puts 'Everybody just HOLD ON! I have something to do...' proct.call puts 'Ok everyone, I\'m done. Go on with what you were doing.' end sayHello = Proc.new do puts 'hello' end sayGoodbye = Proc.new do puts 'goodbye' end def maybeDo someProc if rand(2) == 0 someProc.call end end def twiceDo someProc someProc.call someProc.call end wink = Proc.new do puts '<wink>' end glance = Proc.new do while rand(4) == 3 puts '<glance>' end end def doUntilFalse firstInput, someProc input = firstInput output = firstInput while output input = output output = someProc.call input end input end buildArrayOfSquares = Proc.new do |array| lastNumber = array.last if lastNumber <= 0 false else array.pop # Take off the last number... array.push lastNumber*lastNumber # ...and replace it with its square... array.push lastNumber-1 # ...followed by the next smaller number. end end alwaysFalse = Proc.new do |justIgnoreMe| false end # puts doUntilFalse([5], buildArrayOfSquares).inspect def compose proc1, proc2 Proc.new do |x| proc2.call(proc1.call(x)) end end squareIt = Proc.new do |x| x * x end doubleIt = Proc.new do |x| x + x end doubleThenSquare = compose doubleIt, squareIt squareThenDouble = compose squareIt, doubleIt # puts doubleThenSquare.call(5) # puts squareThenDouble.call(5) # @@sides = 6 class Polygon def self.sides @@sides end def self.angles @angles end @@sides = 8 @angles = 7 puts @angles.to_s + ' Angles' end class Triangle < Polygon # puts @@sides.to_s + ' Sides ' end
true
6816d701b0e0b8c34e4d422c02cbcdd40258113d
Ruby
FernandaFranco/book-intro-programming
/loops_iterators/exercise_2.rb
UTF-8
124
3.171875
3
[]
no_license
question = "DO YOU LOVE ME? REALLY?? DO YOU???" answer = 0 while answer != "STOP" puts question answer = gets.chomp end
true
1b21e5fdf8787dc4d403847dddefbd8ae9dd3b4a
Ruby
Mikeermz/test_latam
/Finland.rb
UTF-8
239
2.75
3
[]
no_license
require_relative 'Sale.rb' class Finland < Sale def initialize(producto, precio, fecha, latitud, longitud, ciudad, tipo_pago, nombre) super(producto,precio,fecha,latitud,longitud,ciudad,tipo_pago,nombre) @pais = "Finland" end end
true
9d328067dae1c9b50c363416aeba751d8b8602a5
Ruby
firecracker/cloud_search
/spec/cloud_search/document_spec.rb
UTF-8
10,018
2.65625
3
[ "MIT" ]
permissive
# encoding: utf-8 require "spec_helper" describe CloudSearch::Document do it "has a 'id' attribute" do expect(described_class.new(:id => 123).id).to eq("123") end it "has a 'type' attribute" do expect(described_class.new(:type => "add").type).to eq("add") end it "has a 'version' attribute" do expect(described_class.new(:version => 1234).version).to eq(1234) end it "has a 'lang' attribute" do expect(described_class.new(:lang => "en").lang).to eq("en") end it "has a 'fields' attribute" do expect(described_class.new(:fields => {:foo => "bar"}).fields).to eq(:foo => "bar") end it "clears errors between validations" do document = described_class.new :id => nil expect(document).to_not be_valid document.id = "123" document.valid? expect(document.errors[:id]).to be_nil end context "id validation" do it "is invalid without an id" do document = described_class.new document.valid? expect(document.errors[:id]).to eq(["can't be blank"]) end %w(- ? A & * ç à @ % $ ! = +).each do |char| it "is invalid containing #{char}" do document = described_class.new :id => "1#{char}2" document.valid? expect(document.errors[:id]).to eq(["is invalid"]) end end it "is invalid starting with an '_'" do document = described_class.new :id => "_abc" document.valid? expect(document.errors[:id]).to eq(["is invalid"]) end it "is invalid with a string containing only spaces" do document = described_class.new :id => " " document.valid? expect(document.errors[:id]).to eq(["can't be blank"]) end it "is valid with a valid id" do document = described_class.new :id => "507c54a44a42c408f4000001" document.valid? expect(document.errors[:id]).to be_nil end it "is valid with integers" do document = described_class.new :id => 123 document.valid? expect(document.errors[:id]).to be_nil end it "is valid with single-digit integers" do document = described_class.new :id => 1 document.valid? expect(document.errors[:id]).to be_nil end it "is valid with single-character strings" do document = described_class.new :id => "a" document.valid? expect(document.errors[:id]).to be_nil end it "converts integers to strings" do expect(described_class.new(:id => 123).id).to eq("123") end end context "version validation" do it "is invalid with a non numeric value" do document = described_class.new :version => "123a3545656" document.valid? expect(document.errors[:version]).to eq(["is invalid"]) end it "is invalid with a nil value" do document = described_class.new :version => nil document.valid? expect(document.errors[:version]).to eq(["can't be blank"]) end it "converts strings to integers" do expect(described_class.new(:version => "123").version).to eq(123) end it "does not convert strings to integers if they contain non numerical characters" do expect(described_class.new(:version => "123abc567").version).to eq("123abc567") end it "is invalid if value is greater than CloudSearch::Document::MAX_VERSION" do document = described_class.new :version => 4294967296 document.valid? expect(document.errors[:version]).to eq(["must be less than 4294967296"]) end it "is valid with integers greater than zero and less or equal to CloudSearch::Document::MAX_VERSION" do document = described_class.new :version => 4294967295 document.valid? expect(document.errors[:version]).to be_nil end end context "type validation" do it "is valid if type is 'add'" do document = described_class.new :type => "add" document.valid? expect(document.errors[:type]).to be_nil end it "is valid if type is 'delete'" do document = described_class.new :type => "delete" document.valid? expect(document.errors[:type]).to be_nil end it "is invalid if type is anything else" do document = described_class.new :type => "wrong" document.valid? expect(document.errors[:type]).to eq(["is invalid"]) end it "is invalid if type is nil" do document = described_class.new :type => nil document.valid? expect(document.errors[:type]).to eq(["can't be blank"]) end it "is invalid if type is a blank string" do document = described_class.new :type => " " document.valid? expect(document.errors[:type]).to eq(["can't be blank"]) end end context "lang validation" do context "when type is 'add'" do it "is invalid if lang is nil" do document = described_class.new :lang => nil, :type => "add" document.valid? expect(document.errors[:lang]).to eql(["can't be blank"]) end it "is invalid if lang contains digits" do document = described_class.new :lang => "a1", :type => "add" document.valid? expect(document.errors[:lang]).to eql(["is invalid"]) end it "is invalid if lang contains more than 2 characters" do document = described_class.new :lang => "abc", :type => "add" document.valid? expect(document.errors[:lang]).to eql(["is invalid"]) end it "is invalid if lang contains upper case characters" do document = described_class.new :lang => "Ab", :type => "add" document.valid? expect(document.errors[:lang]).to eql(["is invalid"]) end it "is valid if lang contains 2 lower case characters" do document = described_class.new :lang => "en", :type => "add" document.valid? expect(document.errors[:lang]).to be_nil end end context "when type is 'delete'" do it "is optional" do document = described_class.new :type => "delete" document.valid? expect(document.errors[:lang]).to be_nil end end end context "fields validation" do context "when type is 'add'" do it "is invalid if fields is nil" do document = described_class.new :fields => nil, :type => "add" document.valid? expect(document.errors[:fields]).to eql(["can't be empty"]) end it "is invalid if fields is not a hash" do document = described_class.new :fields => [], :type => "add" document.valid? expect(document.errors[:fields]).to eql(["must be an instance of Hash"]) end it "is valid with a Hash" do document = described_class.new :fields => {}, :type => "add" document.valid? expect(document.errors[:fields]).to be_nil end end context "when type is 'delete'" do it "is optional" do document = described_class.new :type => "delete" document.valid? expect(document.errors[:fields]).to be_nil end end end context "#as_json" do let(:attributes) { { :type => type, :id => "123abc", :version => 123456, :lang => "pt", :fields => {:foo => "bar"} } } let(:document) { described_class.new attributes } let(:as_json) { document.as_json } context "when 'type' is 'add'" do let(:type) { "add" } it "includes the 'type' attribute" do expect(as_json[:type]).to eq("add") end it "includes the 'id' attribute" do expect(as_json[:id]).to eq("123abc") end it "includes the 'version' attribute" do expect(as_json[:version]).to eq(123456) end it "includes the 'lang' attribute" do expect(as_json[:lang]).to eq("pt") end it "includes the 'fields' attribute" do expect(as_json[:fields]).to eq(:foo => "bar") end end context "when 'type' is 'delete'" do let(:type) { "delete" } it "includes the 'type' attribute" do expect(as_json[:type]).to eq("delete") end it "includes the 'id' attribute" do expect(as_json[:id]).to eq("123abc") end it "includes the 'version' attribute" do expect(as_json[:version]).to eq(123456) end it "does not include the 'lang' attribute" do expect(as_json[:lang]).to be_nil end it "does not include the 'fields' attribute" do expect(as_json[:fields]).to be_nil end end end context "#to_json" do let(:attributes) { { :type => type, :id => "123abc", :version => 123456, :lang => "pt", :fields => {:foo => "bar"} } } let(:parsed_json) { JSON.parse(described_class.new(attributes).to_json) } context "when 'type' is 'add'" do let(:type) { "add" } it "includes the 'type' attribute" do expect(parsed_json["type"]).to eq("add") end it "includes the 'id' attribute" do expect(parsed_json["id"]).to eq("123abc") end it "includes the 'version' attribute" do expect(parsed_json["version"]).to eq(123456) end it "includes the 'lang' attribute" do expect(parsed_json["lang"]).to eq("pt") end it "includes the 'fields' attribute" do expect(parsed_json["fields"]).to eq("foo" => "bar") end end context "when 'type' is 'delete'" do let(:type) { "delete" } it "includes the 'type' attribute" do expect(parsed_json["type"]).to eq("delete") end it "includes the 'id' attribute" do expect(parsed_json["id"]).to eq("123abc") end it "includes the 'version' attribute" do expect(parsed_json["version"]).to eq(123456) end it "does not include the 'lang' attribute" do expect(parsed_json["lang"]).to be_nil end it "does not include the 'fields' attribute" do expect(parsed_json["fields"]).to be_nil end end end end
true
b7c158cb3b73d9078c125c18ef97ca674609bd3f
Ruby
bilalnaeem/template-engine
/db/seeds.rb
UTF-8
631
2.625
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) puts "Seeding Hamburgers" Hamburger.create name: "Test Hamburger", description: "Some Test Description", price: 25, rating: 5 Hamburger.create name: "Test Hamburger 101", description: "Some Test Description 101", price: 50, rating: 8 puts "Done with Seeding Hamburgers !!!"
true
f02e472d7a43faa9615df45fe994d2b43547683f
Ruby
comfyguy/lessons
/tests/a.rb
UTF-8
122
3.328125
3
[]
no_license
class Animal attr_accessor :name def initialize self.name = 'Murzik' end end pet = Animal.new puts pet.name
true
91ab421de83f8dc90e81301d7e010b177161ba29
Ruby
googleapis/google-cloud-ruby
/google-cloud-pubsub/samples/pubsub_publish_custom_attributes.rb
UTF-8
1,314
2.546875
3
[ "Apache-2.0" ]
permissive
# Copyright 2023 Google, 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. require "google/cloud/pubsub" def publish_message_async_with_custom_attributes topic_id: # [START pubsub_publish_custom_attributes] # topic_id = "your-topic-id" pubsub = Google::Cloud::Pubsub.new topic = pubsub.topic topic_id # Add two attributes, origin and username, to the message topic.publish_async "This is a test message.", origin: "ruby-sample", username: "gcp" do |result| raise "Failed to publish the message." unless result.succeeded? puts "Message with custom attributes published asynchronously." end # Stop the async_publisher to send all queued messages immediately. topic.async_publisher.stop.wait! # [END pubsub_publish_custom_attributes] end
true
777c186465d740ace8295b5d29a1d112ac13fb0f
Ruby
codesicario/Exercises-Launch-School
/sum_or_product_of_int.rb
UTF-8
547
4.25
4
[]
no_license
def product_or_sum puts "Please enter an integer greater than 0:" integer = gets.chomp.to_i puts "Enter 's' to compute the sum, 'p' to compute the product." user_input = gets.chomp if user_input == 's' sum = (1..integer).inject(:+) puts "The sum of the integers between 1 and #{integer} is: #{sum}" elsif user_input == 'p' product = (1..integer).inject(:*) puts "The product of the integers between 1 and #{integer} is: #{product}" else puts "Invaid input. Please enter a 'p' or 's'" end end product_or_sum
true
a717af42fe85a1f37f0af4e344b75a9613f98be8
Ruby
camillavk/Rock-Paper-Scissors
/spec/game_spec.rb
UTF-8
487
2.546875
3
[]
no_license
require_relative '../app/game' describe Game do let (:game) {Game.new} let (:player) {double :player} let (:opponent) {double :opponent} let (:rock) {double :rock} it "should have five choices" do expect(game.choices).to be_kind_of(Array) end it "can add a player" do game.add_player(player) expect(game.player1).to eq(player) end it "can have a second player" do game.add_player(player) game.add_player(opponent) expect(game.player2).to eq(opponent) end end
true
43fc9f1fbea7522377fb4b25c5c22d21ab7211a4
Ruby
InnoZ/RubyCars
/app/models/runner.rb
UTF-8
758
2.890625
3
[]
no_license
class Runner include RubyCarsLog def initialize(scraper) @scraper = scraper end def run log_start scrape ensure log_finish end private attr_reader :scraper def scrape scraper.run rescue => e rescue_message(e) end def rescue_message(e) RubyCarsLog.logger.error([ common_log_args, "error=#{e.class}", "message=#{e.message}", ].join(' ')) end def log_start @start_time = Time.now.to_f RubyCarsLog.logger.info "#{common_log_args} event=start" end def log_finish RubyCarsLog.logger.info [ "#{common_log_args} event=finish", RubyCarsLog.duration_since(@start_time), ].join(' ') end def common_log_args "class=#{scraper.class}" end end
true
df192c5d2b9fc0552f462376d73a3da4dd5cb475
Ruby
djberg96/berger_spec
/test/core/Float/instance/test_floor.rb
UTF-8
1,529
3.328125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Artistic-2.0" ]
permissive
###################################################################### # test_floor.rb # # Test case for the Float#floor instance method. ###################################################################### require 'test/helper' require 'test/unit' class Test_Float_Floor_InstanceMethod < Test::Unit::TestCase def setup @float_pos = 1.07 @float_neg = -0.93 end test "floor basic functionality" do assert_respond_to(@float_pos, :floor) assert_nothing_raised{ @float_pos.floor } assert_kind_of(Integer, @float_pos.floor) end test "floor with no arguments returns expected value for postive floats" do assert_equal(1, @float_pos.floor) assert_equal(1, (1.0).floor) assert_equal(0, (0.0).floor) end test "floor with no arguments returns expected value for negative floats" do assert_equal(-1, @float_neg.floor) end test "floor with arguments returns the expected value" do assert_equal(0.5, 0.555.floor(1)) assert_equal(0.55, 0.555.floor(2)) assert_equal(0.555, 0.555.floor(3)) assert_equal(0.555, 0.555.floor(99)) end test "arguments to floor must be numeric" do assert_raise(TypeError){ 0.555.floor("test") } assert_raise(TypeError){ 0.555.floor(true) } assert_raise(TypeError){ 0.555.floor(false) } assert_raise(TypeError){ 0.555.floor(nil) } end test "floor method only accepts one argument" do assert_raise(ArgumentError){ @float_pos.floor(1,2) } end def teardown @float_pos = nil @float_neg = nil end end
true
20a5e9555c53f8c7c63b54328aad8532a705a783
Ruby
johnlarkin1/ror-intro
/lesson2_assignment2/module2_lesson2_formative.rb
UTF-8
715
3.921875
4
[]
no_license
### This is the old sample code that I'll be working with # Grab 23 random elements between 0 and 10000 arr = (1..10000).to_a.sample(23) p arr # This selects only elements that when divided by 3 have a 0 remainder. p arr.select { |element| element % 3 == 0} # Write a single chain of command to find all numbers that # are from an array of numbers 1..10000 inclusive # are divisible by 3 # are not less than 5000 # sorted in reverse order hw_arr = (1..10000).to_a.select { |element| element % 3 == 0} .reject { |element| element < 5000} .sort.reverse # puts "Final array looks like: #{hw_arr}" # puts "Final array length: #{hw_arr.length}" p hw_arr
true
1aaee53c4b77aab12fc2be18ddf621ee2487d71b
Ruby
BranLiang/assignment_rspec_viking
/spec/viking_spec.rb
UTF-8
4,667
3.15625
3
[]
no_license
# Your code here require 'viking.rb' require 'pry-byebug' describe Viking do let(:viking){ Viking.new } let(:oleg){ Viking.new("Oleg") } let(:bran){ Viking.new("Bran") } before do allow($stdout).to receive(:puts) end describe '#initialize' do it 'set up with a name' do new_viking = Viking.new("Bran") expect(new_viking.name).to eq("Bran") end it 'set up with a particular healthy' do new_viking = Viking.new("Bran", 101) expect(new_viking.health).to eq(101) end it 'can not over written the health value' do expect{ viking.health = 120 }.to raise_error(NoMethodError) end it 'has no weapon when initialized' do expect(viking.weapon).to be_nil end end describe '#pick_up_weapon' do it 'can pick up viking weapon' do axe = instance_double("Weapon", :name) allow(axe).to receive(:is_a?).with(Weapon).and_return(true) viking.pick_up_weapon(axe) expect(viking.weapon).to eq(axe) end it 'sets a weapon as the viking weapon' do b = Bow.new viking.pick_up_weapon(b) expect(viking.weapon).to equal(b) end it 'can not pick none viking weapon' do none_viking_weapon = double allow(none_viking_weapon).to receive(:is_a?).with(Weapon).and_return(false) expect{ viking.pick_up_weapon(none_viking_weapon) }.to raise_error("Can't pick up that thing") end it 'replace the old weapon' do arrow = instance_double("Weapon") axe = instance_double("Weapon") allow(arrow).to receive(:is_a?).with(Weapon).and_return(true) allow(axe).to receive(:is_a?).with(Weapon).and_return(true) viking.pick_up_weapon(arrow) expect(viking.weapon).to eq(arrow) viking.pick_up_weapon(axe) expect(viking.weapon).to eq(axe) end end describe '#drop_weapon' do it 'leave the viking weaponless' do axe = instance_double("Weapon") allow(axe).to receive(:is_a?).with(Weapon).and_return(true) viking.pick_up_weapon(axe) expect(viking.weapon).to eq(axe) viking.drop_weapon expect(viking.weapon).to be_nil end end describe '#receive_attack' do it 'reduce the viking health by the specified amount' do expect(viking.health).to eq(100) viking.receive_attack(10) expect(viking.health).to eq(90) end it 'calls the take_damage method' do allow(viking).to receive(:take_damage).and_return(90) expect(viking).to receive(:take_damage) viking.receive_attack(10) end end describe '#attack' do it 'cause the recipients health to drop' do expect(oleg.health).to eq(100) bran.attack(oleg) expect(oleg.health).to be < 100 end it 'call the take_damage method' do allow(oleg).to receive(:take_damage).and_return(2.5) expect(oleg).to receive(:take_damage) bran.attack(oleg) end it 'call method damage_with_fists when attack without weapon' do # expect(bran.weapon).to be_nil allow(bran).to receive(:damage_with_fists).and_return(10) expect(bran).to receive(:damage_with_fists) bran.attack(oleg) end it 'with no weapon deals Fists multiplier times strength damage' do viking.drop_weapon fists_multiplier = Fists.new.use expected_damage = viking.strength * fists_multiplier expect(oleg).to receive(:receive_attack).with(expected_damage) bran.attack(oleg) end context 'when attacking with a weapon' do it 'runs #damage_with_weapon' do a = Axe.new bran.pick_up_weapon(a) allow(bran).to receive(:damage_with_weapon).and_return(77) expect(bran).to receive(:damage_with_weapon) bran.attack(oleg) end it 'deals damage equal to vikings strength times weapon multiplier' do a = Axe.new axe_multiplier = a.use viking.pick_up_weapon(a) expected_damage = axe_multiplier * viking.strength expect(oleg).to receive(:receive_attack).with(expected_damage) viking.attack(oleg) end end context 'when using an empty Bow' do let(:empty_bow){ Bow.new(0) } it 'uses #damage_with_fists instead' do bran.pick_up_weapon(empty_bow) allow(bran).to receive(:damage_with_fists).and_return(2.5) expect(bran).to receive(:damage_with_fists) bran.attack(oleg) end end it 'raises an error if it kills a Viking' do dying_viking = Viking.new("Beowulf", 1) allow(viking).to receive(:damage_dealt).and_return(100) expect{ viking.attack(dying_viking) }.to raise_error("Beowulf has Died...") end end end
true
b51a5cf1e78495633b6dd8ad92ae9aeed55e1a5e
Ruby
StevenACZ/ruby-basics-2-StevenACZ
/06caesar/caesar.rb
UTF-8
1,065
4.125
4
[]
no_license
# Ask the user for the key and plaintext # Create the ciphertext. You will need to iterate over each character of plaintext. # On each character check if is an alphabetic letter. If you have a list of the alphabetic letters # you cancheck if the character is included in that list. If not, it goes directly to the ciphertext # You can also use that alphabetic list to find the letter that is some position after it. # Do not forget that you should preserve the case of the original letter. # Append the new letter to the ciphertext. # Finally print the ciphertext to the screen. class String def letter? /[A-Za-z]/.match?(self) end end key = 0 ciphertext = "" loop do print("Key: ") key = gets.to_i key.positive? && break end print("plaintext: ") plaintext = gets.strip.to_s abc = [*"a".."z", *"A".."Z"] plaintext.split("").each do |l| current = l.letter? ? abc[(abc.find_index(l).to_i + key) % 52] : l ciphertext += (current == current.upcase) && (l == l.upcase) ? current.upcase : current.downcase end puts("ciphertext: #{ciphertext}")
true
aae634da89bba53eb2087ec094b12b7511af5f37
Ruby
Luis846/Ruby-Practice
/student.rb
UTF-8
342
3.6875
4
[]
no_license
class Student attr_accessor :first_name, :last_name, :primary_phone_number def introduction(target) puts "Hi, #{target}, I'm #{first_name}" end def favorite_number 7 end end Luis = Student.new Luis.first_name = "Luis" Luis.last_name = "Rivera" puts "Luis's favorite number is #{Luis.favorite_number}."
true
54690e4a196bf626baa7225e1c9cc41d527fe3a4
Ruby
ruby-rdf/spira
/spec/rdf_types_spec.rb
UTF-8
5,121
2.625
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
require "spec_helper" # These classes are to test finding based on RDF::RDFS.type class Cars < RDF::Vocabulary('http://example.org/cars/') property :car property :van property :car1 property :van property :station_wagon property :unrelated_type end describe 'models with a defined rdf type' do subject {RDF::Repository.load(fixture('types.nt'))} let(:car1) {Car.for Cars.car1} let(:car2) {Car.for Cars.car2} before :all do class ::Car < Spira::Base type Cars.car property :name, predicate: RDF::RDFS.label end class ::Van < Spira::Base type Cars.van property :name, predicate: RDF::RDFS.label end class ::Wagon < Spira::Base property :name, predicate: RDF::RDFS.label end class ::MultiCar < Spira::Base type Cars.car type Cars.van end end before {Spira.repository = subject} context "when declaring types" do it "should raise an error when declaring a non-uri type" do expect { class ::XYZ < Spira::Base type 'a string, for example' end }.to raise_error TypeError end it "should provide a class method which returns the type" do expect(Car).to respond_to :type end it "should return the correct type" do expect(Car.type).to eql Cars.car end it "should return nil if no type is declared" do expect(Wagon.type).to eql nil end end context "When finding by types" do it "should find 1 car" do expect(Car.count).to eql 1 end it "should find 3 vans" do expect(Van.count).to eql 3 end end context "when creating" do subject {Car.for RDF::URI.new('http://example.org/cars/newcar')} its(:type) {is_expected.to eql Car.type} it "should not include a type statement on dump" do # NB: declaring an object with a type does not get the type statement in the DB # until the object is persisted! expect(subject).not_to have_statement(predicate: RDF.type, object: Car.type) end it "should not be able to assign type" do expect { Car.for(RDF::URI.new('http://example.org/cars/newcar2'), type: Cars.van) }.to raise_error NoMethodError end end context "when loading" do it "should have a type" do expect(car1.type).to eql Car.type end it "should have a type when loading a resource without one in the data store" do expect(car2.type).to eql Car.type end end context "when saving" do it "should save a type for resources which don't have one in the data store" do car2.save! expect(subject.query({subject: Cars.car2, predicate: RDF.type, object: Cars.car}).count).to eql 1 end it "should save a type for newly-created resources which in the data store" do car3 = Car.for(Cars.car3) car3.save! expect(subject.query({subject: Cars.car3, predicate: RDF.type, object: Cars.car}).count).to eql 1 end end context "When getting/setting" do before :each do expect(car1).not_to be_nil end it "should allow setting other properties" do car1.name = "prius" car1.save! expect(car1.type).to eql Cars.car expect(car1.name).to eql "prius" end it "should raise an exception when trying to change the type" do expect {car1.type = Cars.van}.to raise_error(NoMethodError) end it "should maintain all triples related to this object on save" do original_triples = subject.query({subject: Cars.car1}) car1.name = 'testing123' car1.save! expect(subject.query({subject: Cars.car1}).count).to eql original_triples.size end end context "when counting" do it "should count all projected types" do expect { Car.for(Cars.one).save! Van.for(Cars.two).save! }.to change(MultiCar, :count).by(2) end it "should provide a count method for resources with types" do expect(Car.count).to eql 1 end it "should increase the count when items are saved" do Car.for(Cars.toyota).save! expect(Car.count).to eql 2 end it "should decrease the count when items are destroyed" do expect { car1.destroy }.to change(Car, :count).from(1).to(0) end it "should raise a Spira::NoTypeError to call #count for models without types" do expect { Wagon.count }.to raise_error Spira::NoTypeError end end context "when enumerating" do it "should provide an each method for resources with types" do expect(Van.each.to_a.size).to eql 3 end it "should raise a Spira::NoTypeError to call #each for models without types" do expect { Wagon.each }.to raise_error Spira::NoTypeError end it "should return an enumerator if no block is given" do expect(Van.each).to be_a Enumerator end it "should execute a block if one is given" do vans = [] Van.each do |resource| vans << resource end [Cars.van1, Cars.van2, Cars.van3].each do |uri| expect(vans.any? { |van| van.uri == uri }).to be_truthy end end end end
true
65de148c04f4395379c2f1745d14ff6aecbec6d0
Ruby
adrianpike/paranoia
/paranoia.rb
UTF-8
2,062
2.890625
3
[]
no_license
require 'formatador' require 'openssl' require 'ostruct' class ParseError < StandardError; end class Cert < OpenStruct def self.initialize_from_string(string) name = nil; sig = nil string.each_line do |line| if line.match(/"alis"<.+>=(?:0x[0-9A-F]+\W+)?"(.*)"$/) then name = $1 end if line.match(/"hpky"<.*>=(0x[0-9A-F]+)/) then sig = $1 end end if name and sig then self.new(name: name, sig: sig) else # We throw exceptions here because we'd rather report as a bug and fix it # than continue in an undefined state - and possibly miss a sketchy cert. raise ParseError, "Incomplete signature given in cert: \"#{string}\"" end end end class Keychain attr_accessor :certs, :parsed, :digest, :path def initialize(path = '/System/Library/Keychains/SystemRootCertificates.keychain') self.certs = [] self.path = path self.parsed = false self.digest = OpenSSL::Digest::SHA256.new end def cert_data `security dump-keychain #{path}` end def parse buffer = '' cert_data.each_line do |line| if line.match(/^keychain:/) and buffer.length > 0 then cert = Cert.initialize_from_string(buffer) digest << cert.name digest << cert.sig certs << cert buffer = '' end buffer += line end parsed = true end def cert_hashes parse unless parsed certs.collect do |cert| {name: cert.name, signature: cert.sig} end end end os_data = `sw_vers` os, version, build_version = os_data.split("\n").collect do |line| line.split(':').last.strip end system_keychain = Keychain.new Formatador.display_line "[green] ** System Keychain ** [/]" Formatador.display_compact_table(system_keychain.cert_hashes) Formatador.display_line "[red]#{"=" * 80}[/]" Formatador.display_line "#{os} #{version} [green]#{build_version}[/]" Formatador.display_line "Your System Keychain digest is: [green]#{system_keychain.digest}[/]" Formatador.display_line "[red]#{"=" * 80}[/]"
true
8a900c7dd66ddac0076d1a73491ab6b82fa3c7ce
Ruby
demileee/roll-of-the-die
/permutations.rb
UTF-8
132
3.296875
3
[]
no_license
dice = [1, 2, 3, 4, 5, 6] dice2 = [1, 2, 3, 4, 5, 6] dice.each do |die| dice2.each do |die2| puts "#{die} #{die2}" end end
true
16e38c14ff9b2c182aaef4c9f6790f33d6742173
Ruby
eclipse2ant/e_keisan
/lib/unit.rb
UTF-8
1,388
3.171875
3
[]
no_license
#!/usr/local/jruby/bin/jruby # encoding: utf-8 ############################################################################# ### 単位の編集(@@u2fの編集)は、unit_file.rb で行ってください ############## ############################################################################# require 'apath' require 'unit_file' class Unit include Apath def initialize(qty) @rep = qty end def to_g(shokuhin = nil) if @rep =~ /^(\D*)(\d+)([\/.])(\d+)(\D*)$/ if $3 == '/' @amount =$2.to_f / $4.to_f else @amount = "#{$2}.#{$4}".to_f end # p @amount if $5 == 'g' return @amount else @amount*to_gram("#{$1}##{$5}", shokuhin) end elsif @rep =~ /^(\D*)(\d+)(\D*)$/ @amount = $2.to_f if $3 == 'g' return @amount else return @amount*to_gram("#{$1}##{$3}", shokuhin) end elsif @rep =~ /^(\D+)$/ return to_gram("#{$1}", shokuhin) else raise "単位のパターンが一致しません" end end def to_gram(unit, shokuhin) # p unit # p shokuhin if @@u2f[unit] == nil raise "#{unit} に対応するファイルが見つかりません\n" end File.foreach(apath("lib/units/#{@@u2f[unit]}")) do |line| s, gram = line.chomp.split(',') # p s if s == shokuhin return gram.to_f end end raise "単位 #{unit} に対応する #{shokuhin} がありません\n" end end
true
2745ca3ece7c4dcd846d1028d90e3ae4fa2aafd6
Ruby
tdd/tweep
/lib/tweep/account.rb
UTF-8
1,491
2.640625
3
[ "MIT-0", "MIT" ]
permissive
#! /usr/bin/env ruby # encoding: utf-8 # # (c) 2011 Christophe Porteneuve require 'tweep/config' require 'rubygems' require 'twitter' module Tweep class Account @@registry = {} def self.each(&block) @@registry.values.each(&block) end def self.find(nick) @@registry[nick] end def initialize(yml, index) return unless load_config(yml, index) @index = index @@registry[@config.nick] = self end def retweet!(status_id) Tweep.info "#{@config.nick} retweets #{status_id.inspect}" execute :retweet, status_id end def run! return unless @config.has_tweets? && @config.now_is_a_good_time? tweet! end private def execute(call, *args) Twitter.configure do |config| @config.auth.each do |k, v| config.send("#{k}=", v) end end Twitter.send(call, *args) end def load_config(file, index) return unless File.file?(file) && File.readable_real?(file) @config = Config.new(file, index) @config.has_auth? end def tweet! status, idx = @config.next_tweet return if status.blank? Tweep.info "#{@config.nick} tweets: #{status}" st = execute(:update, status) @index.tweeted! @config.nick, idx @config.retweeters.each do |retweeter, _| if @config.should_get_retweeted_by?(retweeter) self.class.find(retweeter).try(:retweet!, st.id) end end end end end
true
519e017a62e9d2abd07b847363d08f2b5a3e8b2f
Ruby
Harxy/battleships
/lib/board.rb
UTF-8
137
2.921875
3
[]
no_license
class Board attr_accessor :board def initialize @board = [] end def boat_location boat, x, y board << boat end end
true
1de744e076a76cc3ab8150d903ba69b51a6ef5cf
Ruby
samiylo/job
/lib/job_posting/scraper.rb
UTF-8
3,632
3.046875
3
[]
no_license
class JobObjects class Job @@all = [] attr_accessor :name, :company, :location, :url def initialize(name, company, location = nil, url) @name = name @company = company @location = location @url = url @@all << self end def self.all @@all.each do |listing| puts "Position Title: #{listing.name}" puts "Company: #{listing.company}" # puts " Location not disclosed" # puts "Location: #{listing.location}" if listing.location == "" puts " Location not disclosed" else puts "Location: #{listing.location}" end puts "==================================================" end end def self.search(job_name) @@all.each do |listing| if job_name == listing.name puts "Position Title: #{listing.name}" puts "Company: #{listing.company}" # puts " Location not disclosed" # puts "Location: #{listing.location}" if listing.location == "" puts " Location not disclosed" else puts "Location: #{listing.location}" end puts "==================================================" puts "DESCRIPTION" puts "==================================================" self.description(job_name) end end end def self.description(job_name) @@all.each do |listing| if job_name == listing.name url = listing.url raw_html = HTTParty.get(url) parsed_page = Nokogiri::HTML(raw_html) description = parsed_page.css('div#jobDescriptionText').text.strip puts "==================================================" puts description # binding.pry end end end def self.random rand_num = rand(10) job = @@all[rand_num] puts "#{job.name}" puts "#{job.company}" puts "#{job.location}" end end # Start scraper logic def scraper all = [] url = "https://www.indeed.com/l-Kingwood,-TX-jobs.html" raw_html = HTTParty.get(url) parsed_page = Nokogiri::HTML(raw_html) job_cards = parsed_page.css('div.jobsearch-SerpJobCard') #15 JOBS page = 1 per_page = job_cards.count #Counts the number of jobs on a page last_page = 1 while page <= last_page job_cards.each do |job_listing| name = job_listing.css('h2.title').text.strip company = job_listing.css('span.company').text.strip location = job_listing.css('div.location').text url = "https://www.indeed.com/" + job_listing.css('a')[0].attributes['href'].value Job.new(name, company, location, url) end page += 1 end # binding.pry end end
true
58451b4fc082dcb6452b43b029b8eebdb82b20dc
Ruby
afiore/extraloop
/lib/extraloop/extractor_base.rb
UTF-8
1,396
2.984375
3
[]
no_license
module ExtraLoop # Pseudo Abstract class from which all extractors inherit. # This should not be called directly # class ExtractorBase module Exceptions class WrongArgumentError < StandardError; end class ExtractorParseError < StandardError; end end attr_reader :field_name # # Public: Initialises a Data extractor. # # Parameters: # field_name - The machine readable field name # environment - The object within which the extractor callback will be run (using run). # selector: - The css3 selector to be used to match a specific portion of a document (optional). # callback - A block of code to which the extracted node/attribute will be passed (optional). # attribute: - A node attribute. If provided, the attribute value will be returned (optional). # # Returns itself # def initialize(field_name, environment, *args) @field_name = field_name @environment = environment @selector = args.find { |arg| arg.is_a?(String)} args.delete(@selector) if @selector @attribute = args.find { |arg| arg.is_a?(String) || arg.is_a?(Symbol) } @callback = args.find { |arg| arg.respond_to?(:call) } self end def parse(input) raise Exceptions::ExtractorParseError.new "input parameter must be a string" unless input.is_a?(String) end end end
true
34eaf401e22ab81e9861f6bced815be49849fb2a
Ruby
hkumar1993/coding_assessments
/2017_12_16/spec/between_two_sets_spec.rb
UTF-8
792
3.125
3
[]
no_license
require 'between_two_sets' describe 'lcm' do it 'returns the lowest common multiple' do expect(lcm([2,4])).to eq(4) expect(lcm([5,6])).to eq(30) expect(lcm([3,6,9])).to eq(18) end end describe 'gcf' do it 'returns the greatest common factor' do expect(gcf([2,4])).to eq(2) expect(gcf([15,20])).to eq(5) end end describe '#getTotalX' do context 'Set A and Set B are sets of integers where' do context 'All elements in A are a factor of x, and x is a factor of all elements in B' do it 'returns total number of possible X values given A and B' do expect(getTotalX([2,4],[16, 32, 96])).to eq(3) expect(getTotalX([3,9, 6],[36, 72])).to eq(2) end end end end
true
551fd72512cbba2356298979df9b833b35dcc744
Ruby
zfvit/learning_ruby
/OO/methods.rb
UTF-8
1,178
3.890625
4
[]
no_license
class Methods $global = 1234 @instanceName = "Instance field!!!" @@class_field = "Like a static field" attr_accessor :instanceName def initialize(arg) @instanceName = arg @instanceName.capitalize! #changeInstanceName!("changed") $global = 5678 {:oneeeee=>1}.each_pair {|key,value| puts $global } end def returnTwoData (arg) if arg == "raise" raise "Raised ..." end return 1, 2 end def self.staticMethod puts @@class_field end def changeInstanceName! (arg) @instanceName = arg end alias renameMe! changeInstanceName! end puts "Playing with Methods ..." m = Methods.new("instance one") puts m.returnTwoData("don\'t raise") puts m.returnTwoData("go go go") #m.changeInstanceName!("new Name") m.renameMe!("aliased") puts m.instanceName "abcde" .tap {|x| x.reverse!} .tap {|x| puts "string: #{x.inspect}"} .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"} .map { |x| x*x } .tap {|x| puts "squares: #{x.inspect}"}
true
23d2f4c1e9c53597efaba989f2fd41d277a3d857
Ruby
unhcr/axis
/app/models/population.rb
UTF-8
1,065
2.59375
3
[]
no_license
class Population < ActiveRecord::Base attr_accessible :ppg_code, :value, :year, :element_id, :element_type, :ppg_id def self.models_optimized(ids = {}, limit = nil, where = nil, offset = nil) conditions = '' conditions = "element_id IN ('#{ids.values.flatten.join("','")}')" if ids sql = "select array_to_json(array_agg(row_to_json(t))) from ( select #{self.table_name}.ppg_id, #{self.table_name}.value, #{self.table_name}.element_type, #{self.table_name}.element_id, #{self.table_name}.year from #{self.table_name} where #{conditions} ) t " sql += " LIMIT #{sanitize(limit)}" unless limit.nil? sql += " OFFSET #{sanitize(offset)}" unless offset.nil? ActiveRecord::Base.connection.execute(sql) end def to_jbuilder(options = {}) Jbuilder.new do |json| json.extract! self, :ppg_id, :ppg_code, :element_id, :element_type, :year, :value end end def as_json(options = {}) to_jbuilder(options).attributes! end end
true
4bafdb37e00282c0e8fb13aeefd6f02a617386c9
Ruby
jasonlong/geo_pattern
/lib/geo_pattern/structure_generators/octagons_generator.rb
UTF-8
1,126
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module GeoPattern module StructureGenerators class OctagonsGenerator < BaseGenerator private attr_reader :square_size, :tile def after_initialize @square_size = map(hex_val(0, 1), 0, 15, 10, 60) @tile = build_octogon_shape(square_size) self.height = self.width = square_size * 6 end def generate_structure i = 0 6.times do |y| 6.times do |x| val = hex_val(i, 1) opacity = opacity(val) fill = fill_color(val) svg.polyline(tile, "fill" => fill, "fill-opacity" => opacity, "stroke" => stroke_color, "stroke-opacity" => stroke_opacity, "transform" => "translate(#{x * square_size}, #{y * square_size})") i += 1 end end svg end def build_octogon_shape(square_size) s = square_size c = s * 0.33 "#{c},0,#{s - c},0,#{s},#{c},#{s},#{s - c},#{s - c},#{s},#{c},#{s},0,#{s - c},0,#{c},#{c},0" end end end end
true
36282079abb348ebe593868c649d63e2d090688c
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/6cb42db4546e4fdfa7d36aa7c9c79e9f.rb
UTF-8
485
3.640625
4
[]
no_license
class Hamming def self.compute(strand1, strand2) distance = 0 strandA = strand_to_array(strand1) strandB = strand_to_array(strand2) size = use_shorter_strand(strandA, strandB) strandA.take(size).each_with_index { |char, index| distance += 1 if char != strandB[index] } distance end def self.use_shorter_strand(strand1, strand2) [strand1.size, strand2.size].min end def self.strand_to_array(strand) strand.split('') end end
true
554063a368810cbc45ce5264dbf16f8eca223ea8
Ruby
LilyMarcela/Ruby-excercises
/testruby.rb
UTF-8
238
4
4
[]
no_license
def fizz_buzz (num) if num % 3==0 && num % 5 == 0 puts "fizz_buzz" elsif num % 3 == 0 puts "fizz" elsif num % 5 == 0 puts "buzz" else puts "#{num}" end end fizz_buzz(3) fizz_buzz(5) fizz_buzz(15) fizz_buzz(20)
true
a7231861ed5f05b640f4b63832e86aa1cbaab255
Ruby
Nanosim-LIG/boast
/lib/BOAST/Language/HighLevelOperators.rb
UTF-8
4,861
2.703125
3
[ "BSD-2-Clause" ]
permissive
module BOAST class HighLevelOperator < Operator include Intrinsics include Arithmetic include Inspectable end class Sqrt < HighLevelOperator extend Functor attr_reader :operand attr_reader :return_type def initialize(a) @operand = a @return_type = a.to_var unless @return_type.type.kind_of?(Real) then @return_type = Variable::new(:sqrt_type, Real, :vector_length => @return_type.type.vector_length) end end def convert_operand(op) return "#{Operator.convert(op, @return_type.type)}" end private :convert_operand def type return @return_type.type end def to_var sqrt_instruction = nil rsqrt_instruction = nil begin sqrt_instruction = intrinsics(:SQRT,@return_type.type) rescue end unless sqrt_instruction then begin rsqrt_instruction = intrinsics(:RSQRT,@return_type.type) rescue end end if [FORTRAN, CL].include?(lang) then return @return_type.copy( "sqrt( #{@operand} )", DISCARD_OPTIONS ) elsif lang == CUDA or lang == HIP or ( sqrt_instruction.nil? and rsqrt_instruction.nil? ) then raise IntrinsicsError, "Vector square root unsupported on ARM architecture!" if architecture == ARM and @return_type.type.vector_length > 1 if @return_type.type.size <= 4 then return @return_type.copy( "sqrtf( #{@operand} )", DISCARD_OPTIONS ) else return @return_type.copy( "sqrt( #{@operand} )", DISCARD_OPTIONS ) end end op = convert_operand(@operand.to_var) if sqrt_instruction then return @return_type.copy( "#{sqrt_instruction}( #{op} )", DISCARD_OPTIONS ) else return (op * @return_type.copy("#{rsqrt_instruction}( #{op} )", DISCARD_OPTIONS)).to_var end end def to_s return to_var.to_s end def pr s="" s << indent s << to_s s << ";" if CLANGS.include?( lang ) output.puts s return self end end class TrigonometricOperator < HighLevelOperator attr_reader :operand attr_reader :return_type def initialize(a) @operand = a @return_type = a.to_var unless @return_type.type.kind_of?(Real) then @return_type = Variable::new(:trig_type, Real, :vector_length => @return_type.type.vector_length) end end def convert_operand(op) return "#{Operator.convert(op, @return_type.type)}" end private :convert_operand def type return @return_type.type end def to_var instruction = nil begin instruction = intrinsics(get_intrinsic_symbol,@return_type.type) rescue end if [FORTRAN, CL].include?(lang) then return @return_type.copy( "#{get_name[lang]}( #{@operand} )", DISCARD_OPTIONS ) elsif lang == CUDA or lang == HIP or instruction.nil? then raise IntrinsicsError, "Vector #{get_name[lang]} root unsupported on ARM architecture!" if architecture == ARM and @return_type.type.vector_length > 1 if @return_type.type.size <= 4 then return @return_type.copy( "#{get_name[lang]}f( #{@operand} )", DISCARD_OPTIONS ) else return @return_type.copy( "#{get_name[lang]}( #{@operand} )", DISCARD_OPTIONS ) end end op = convert_operand(@operand.to_var) return @return_type.copy( "#{instruction}( #{op} )", DISCARD_OPTIONS ) end def to_s return to_var.to_s end def pr s="" s << indent s << to_s s << ";" if CLANGS.include?( lang ) output.puts s return self end end def self.generic_trigonometric_operator_generator( name ) eval <<EOF class #{name.capitalize} < TrigonometricOperator extend Functor def get_intrinsic_symbol return :#{name.upcase} end def get_name return { C => "#{name}", CUDA => "#{name}", HIP => "#{name}", CL => "#{name}", FORTRAN => "#{name}" } end end EOF end generic_trigonometric_operator_generator( "sin" ) generic_trigonometric_operator_generator( "cos" ) generic_trigonometric_operator_generator( "tan" ) generic_trigonometric_operator_generator( "sinh" ) generic_trigonometric_operator_generator( "cosh" ) generic_trigonometric_operator_generator( "tanh" ) generic_trigonometric_operator_generator( "asin" ) generic_trigonometric_operator_generator( "acos" ) generic_trigonometric_operator_generator( "atan" ) generic_trigonometric_operator_generator( "asinh" ) generic_trigonometric_operator_generator( "acosh" ) generic_trigonometric_operator_generator( "atanh" ) generic_trigonometric_operator_generator( "exp" ) generic_trigonometric_operator_generator( "log" ) generic_trigonometric_operator_generator( "log10" ) end
true
939651b8261a1a52e9ef249a4c35573e700f9ed9
Ruby
fstovarr/UNaTHESIS_IS2
/app/controllers/file_controller.rb
UTF-8
2,266
2.5625
3
[]
no_license
require 'digest/md5' require 'fileutils' require 'json' # FileController class FileController < ApplicationController skip_before_action :verify_authenticity_token def initialize super User.user_type_ids.slice 'student' end def load_post file_name = Time.now.strftime('%Y%m%d_%H%M%S') + '.pdf' thesis_project = ThesisProject.update params[:id], :document => create_path(@current_user.id, file_name), :description => params[:project_description] #thesis_project_user = ThesisProjectUser.new user: @current_user, #thesis_project: thesis_project, thesis_project_roles_id: "author" #tutors_juries = JSON.parse params[:tutors_juries] users = [] #tutors_juries.each do | user | # unless User.find_by(email: user["email"]) # users << User.create({ name: user["name"], surname: user["surname"], # country: user["country"], institution: user["institution"], dni: user["dni"], # email: user["email"], password: "12345678", password_confirmation: "12345678", # user_type_id: "jury_tutor"}) # end #end if thesis_project.save file_path = process_file params[:file], file_name else raise 'Thesis project user not valid' end rescue => error users.each do | user | user.destroy end if Rails.env.production? render json: { error: "Bad request" }, status: :unauthorized else render json: { error: error }, status: :unauthorized end end private def create_path(user_id, file_name) "files/#{Digest::MD5.hexdigest(user_id.to_s)}/#{file_name}" end def process_file(file, name) create_file_folder_of_user(@current_user.id) return move_file_to_user_folder(@current_user.id, file.path, name) end def create_file_folder_of_user(user_id) directory = 'files' FileUtils.mkdir_p directory unless File.exist?(directory) id_md5 = Digest::MD5.hexdigest(user_id.to_s) directory = directory + '/' + id_md5 FileUtils.mkdir_p directory unless File.exist?(directory) end def move_file_to_user_folder(user_id, file_path, file_name) destiny_dir = create_path user_id, file_name FileUtils.mv(file_path, destiny_dir) return destiny_dir end end
true
138a490bbba1a1358f42b9220d6e1ec2d7937cae
Ruby
nielspetersen/smar_T
/lib/algorithm/tour_generation.rb
UTF-8
2,970
2.9375
3
[]
no_license
require 'algorithm/variants/savingsplusplus' require 'algorithm/variants/mthreetp' module Algorithm class TourGeneration def self.generate_tours(company, order_type_filter = {}) # clear all tours with status equal to generated Tour.where(status: StatusEnum::GENERATED).destroy_all orders, drivers = preprocess(company.orders(order_type_filter), company.available_drivers) # only start tour generation when orders and available driver exist if orders.any? && drivers.any? mthreetp_classic = Variants::MThreeTP.new(company, AlgorithmEnum::M3PDP) mthreetp_classic.run(orders, drivers) mthreetp_delta = Variants::MThreeTP.new(company, AlgorithmEnum::M3PDPDELTA) mthreetp_delta.run(orders, drivers) savingsplusplus = Variants::SavingsPlusPlus.new(company) savingsplusplus.run(orders, drivers) compare_and_destroy_tours() end end def self.preprocess(all_orders, drivers) orders = preprocess_orders(all_orders) return orders, drivers end def self.preprocess_orders(all_orders) active_orders = all_orders.where(status: OrderStatusEnum::ACTIVE) orders = [] active_orders.each do |order| if !order.start_time || order.start_time.try(:today?) orders.push(order) end end orders.sort_by! { |order| [order.start_time ? 0 : 1, order.start_time] } orders end def self.compare_and_destroy_tours() tours_duration = Array.new([AlgorithmEnum::M3PDP, AlgorithmEnum::M3PDPDELTA, AlgorithmEnum::SAVINGSPP].length) m3pdp_tours = Tour.where(status: StatusEnum::GENERATED, algorithm: AlgorithmEnum::M3PDP) m3pdp_delta_tours = Tour.where(status: StatusEnum::GENERATED, algorithm: AlgorithmEnum::M3PDPDELTA) saving_tours = Tour.where(status: StatusEnum::GENERATED, algorithm: AlgorithmEnum::SAVINGSPP) tours_duration[AlgorithmEnum::M3PDP] = m3pdp_tours.inject(0){ |sum, x| sum + x.duration } tours_duration[AlgorithmEnum::M3PDPDELTA] = m3pdp_delta_tours.inject(0){ |sum, x| sum + x.duration} tours_duration[AlgorithmEnum::SAVINGSPP] = saving_tours.inject(0){ |sum, x| sum + x.duration } best_algorithm_index = tours_duration.each_with_index.min[1] # index of the min value in array # change status of selected tour combination to approved and from orders to assigned Tour.where(status: StatusEnum::GENERATED).where(algorithm: best_algorithm_index).each do |tour| tour.update_attributes(status: StatusEnum::APPROVED) tour.order_tours.each do |order_tour| if ['delivery', 'pickup', 'service'].include? order_tour.kind order_tour.order.update_attributes(status: OrderStatusEnum::ASSIGNED) end end end # delete inefficient tour combinations Tour.where(status: StatusEnum::GENERATED).where.not(algorithm: best_algorithm_index).destroy_all end end end
true
7d67bafe86d25c839b1dfd0b3698644fb6af92c0
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/robot-name/21476d679fe44df0b94680825506504b.rb
UTF-8
387
3.296875
3
[]
no_license
class Robot attr_accessor :name def initialize self.name = Robot.create_new_name end def reset self.name = Robot.create_new_name end private def self.create_new_name letter = possible_letters.sample(2).join digits = "%03d" % rand(1000) return letter + digits end def self.possible_letters ('a'..'z').to_a.concat(('A'..'Z').to_a) end end
true
157987d17e4cff1ff1453a707ba265f3ad9cc702
Ruby
dylanconnolly/messenger_api
/app/models/conversation.rb
UTF-8
1,280
2.71875
3
[]
no_license
class Conversation < ApplicationRecord has_many :user_conversations has_many :users, through: :user_conversations has_many :messages validates_length_of :users, maximum: 2 def self.find_or_create_conversation(sender, recipient) response = find_conversation(sender.id, recipient.id) return response if response conversation = Conversation.create conversation.users.push(sender, recipient) return conversation end def self.find_conversation(sender_id, recipient_id) joins(:user_conversations). group(:id). where("user_id IN (#{sender_id}, #{recipient_id})"). having("COUNT(*) = 2")[0] end def get_recent_messages(user_id, days_ago = nil) if (!days_ago) messages.where(user: user_id).limit(100).order('created_at DESC') else number_of_days = days_ago.to_i > 30 ? 30 : days_ago.to_i messages.where("user_id = #{user_id} AND created_at > '#{timestamp_days_ago(number_of_days)}'"). order('created_at DESC') end end private def timestamp_days_ago(number_of_days_ago) Time.zone.now.change(hour: 0) - number_of_days_ago.day end end
true
766179fb9948ec1a930de61f6e349c57bec94a47
Ruby
syundo0730/deresta-cnn
/src/downloader/note_image_downloader.rb
UTF-8
1,893
2.90625
3
[]
no_license
require 'cgi' require 'json' page_source = open("../../data/scraped_data/index.html", &:read) class NoteImageDownloader def getImageData(page_source) list_data = page_source.scan(%r!<tr class=\"type-(.+?)\">.*?<td>(.+?)</td><td.*?>(.*?)</td><td.*?><a href=\"(.+?)".*?>.*?</a></td><td.*?><a href=\"(.+?)\".*?>.*?</a></td><td.*?"><a href=\"(.+?)\".*?>.*?</a></td><td.*?><a href=\"(.+?)\".*?>.*?</a></td><td.*?></td></tr>!) return list_data.reject{|item| # Listの整列用ライブラリのせいで楽譜情報でないものが混ざってくるので除去する item[1].match(/^<a class/) }.map{|item| # 属性 (cool, passion, cute, all) type = item[0] # 楽曲タイトル title = CGI.unescapeHTML(item[1]) bpm = item[2] # 難易度名 level_names = ['debut', 'regular', 'pro', 'master'] { :type => type, :title => title, :bpm => bpm, :resources => item[3,5].zip(level_names).map {|uri, level_name| img_pos = uri.sub(/\/view/, 'pattern') file_name = "#{type}_#{img_pos.gsub(/\//, '_')}_#{level_name}" { :note_src_path => "https://deresute.info/#{img_pos}.png?v=1.1.2", :file_name => file_name, :level => level_name } } } } end def downloadImage(image_data, root_dir) image_data.map{|item| item[:resources].map{|resouce| src = resouce[:note_src_path] file_name = "#{root_dir}/#{resouce[:file_name]}.png" `wget #{src} -O #{file_name}` } } end def saveAsJson(image_data, path) File.open(path, "w"){|file| json = JSON.pretty_generate(image_data) file.puts(json) } end end noteImageDownloader = NoteImageDownloader.new() image_data = noteImageDownloader.getImageData(page_source) noteImageDownloader.downloadImage(image_data, '../../data/scraped_data/note_image') noteImageDownloader.saveAsJson(image_data, '../../data/scraped_data/video_list.json')
true
435192232a55164e408ec3131f63c45c36762b32
Ruby
elersong/light-blogger
/app/controllers/articles_controller.rb
UTF-8
3,294
2.921875
3
[]
no_license
class ArticlesController < ApplicationController include ArticlesHelper before_filter :require_login, only: [:new, :create, :edit, :update, :destroy] def index # We're going to need the @articles var to hold an array of all articles because the index # page is simply a listing of all the instances of this class. In the view, we cycle through # this array and output the data to the screen. @articles = Article.all end def show # When the user clicks on the link for a specific article, the id field of that object is placed # into a route url, which means it can be accessed by the params method. We can use that to query # the Article table, and .find() the correct @article to be displayed by the view. @article = Article.find(params[:id]) @comment = Comment.new @comment.article_id = @article.id end def new # Since there is no information being pulled FROM the model, this action doesn't need to make any # model calls. All information will be pulled from the browser and inserted into the database. # However, the form_for(model_name) needs a model_name as an instance variable, and if we don't # initialize that variable here, it will raise an error. @article = Article.new end def create # Rails seems to use the create() action instead of the new() action in order to insert data into the # database. We'll use the "fail" hack to see the exact structure of the params hash in order to build # the create method. Uncomment the following line to observe params[] structure. # fail # Now, we use the strong parameters helper method we wrote in articles_helper.rb to sanitize to # beef up security for data from form submission. @article = Article.new(article_params) @article.author = current_user @article.save flash.notice = "Article '#{@article.title}' was created." # Instead of creating a new view template, we'll simply redirect to the show page for this article # after it has been successfully created. redirect_to article_path(@article) end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path flash.notice = "Article '#{@article.title}' was deleted." end def edit # Obviously, the controller will need to know which article to include in the view, so we look it up # based on its :id and then save that object into an instance variable @article. @article = Article.find(params[:id]) end def update # Think of this as very similar to the create() action, except we don't assign a new :id to an object. We # instead look up an old :id row and change the contents using the article_params() from the ArticlesHelper class. @article = Article.find(params[:id]) unless @article.author @article.author = current_user end @article.update(article_params) # no need to .save() the changes # We also need to update the show.html.erb view to include the flash notification... # NO WE DON'T. Rookie mistake. Add it to the application layout so that it shows up sitewide. flash.notice = "Article '#{@article.title}' was updated." redirect_to article_path(@article) end end
true
c5b0b120cdf57bdf351e836b94c444dc37fb263a
Ruby
cwhwang1986/Algorithm
/Easy/ugly_number.rb
UTF-8
732
4.40625
4
[]
no_license
=begin Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. Note that 1 is typically treated as an ugly number. 6 = 2 * 3 8 = 2 * 2 * 2 14 = 2 * 7 10 = 2 * 5 12 = 2 * 2 * 3 28 = 2 * 2 * 7 100 = 5 * 5 * 2 * 2 =end def is_ugly(num, stop=false) return true if [1,2,3,5].index(num) != nil return false if num == 0 while !stop do if num%2 == 0 num /= 2 elsif num% 3 == 0 num /= 3 elsif num% 5 == 0 num /= 5 else stop = true end end return num == 1 end # p is_ugly(6) p is_ugly(8) p is_ugly(14) p is_ugly(10) p is_ugly(22)
true
2826dacf3edfdf93b978bef20e592f81f4d7cef9
Ruby
ben-biddington/rsettings
/lib/rsettings/core/setting.rb
UTF-8
315
3.296875
3
[ "MIT" ]
permissive
class Setting def truthy?; @truthy; end def initialize(text="") @text = text @truthy = (text||"").downcase.match /(yes|no|on|off)/ end def missing?; @text.nil?; end def to_s; @text.to_s; end def true? match = (@text||"").downcase.match(/(yes|on)/) false == match.nil? end end
true
7ce1cce7524d0eb2dfc23ce2df057dafa4e9533b
Ruby
cielavenir/paiza_solutions
/learning/speedrun190424/d4.rb
UTF-8
109
2.75
3
[]
no_license
#!/usr/bin/ruby gets;puts$<.map{|e| {'forward'=>'Sunny','reverse'=>'Rainy','sideways'=>'Cloudy'}[e.chomp] }
true
c3a93d81e04c2dcaf1b754cb538dc7f606a188b1
Ruby
jaywilburn/tickets
/lib/json_web_token.rb
UTF-8
461
2.59375
3
[]
no_license
require 'json_web_token_decoded' class JsonWebToken def self.encode(payload) JWT.encode(payload, Rails.application.secrets.secret_key_base) end def self.decode(token) payload = JWT.decode(token, Rails.application.secrets.secret_key_base, nil)[0] JsonWebTokenDecoded.new(payload) rescue nil # It will raise an error if it is not a token that was generated with our secret key or if the user changes the contents of the payload end end
true
f50f8dd075a83bff5c7f6bcd1e2e6eaced9f4c6e
Ruby
mwynholds/challenges
/euler/Level2/problem64.rb
UTF-8
1,409
3.1875
3
[]
no_license
require '../helper' require '../continued_fraction' require 'bigdecimal' class Problem64 def initialize end def first(n) a = Math.sqrt(n).floor b = 1 c = a [ a, b, c ] end def rest(n, b, c) x = b y = c z = n - c**2 b1 = z / x a1 = 0 c1 = y loop do a1 += 1 c1 -= b1 break if (c1-b1)**2 > n end c1 = -c1 [ a1, b1, c1 ] end def fill(n, sequence) (1..400).each do (_, b, c) = sequence.last sequence << rest(n, b, c) end end def len(array, str) array_len = 0 str_len = 0 array.each do |n| array_len += 1 str_len += n.to_s.length break if str_len == str.length end array_len end def solve odd = [] (2..10000).each do |n| next if n.square? sequence = [ first(n) ] loop do fill n, sequence array = sequence.map { |(a, _, _, _)| a }[1..-1] str = array.join '' pattern = str.match(/^(\d+?)\1{40}\d*$/) if pattern print '.' if n % 10 == 0 length = len array, pattern[1] #puts "#{n} - #{pattern[1]} (#{length}) - #{str}" #puts "#{n} - #{pattern[1]} (#{length})" odd << n if length % 2 == 1 break end end end puts "TOTAL - #{odd.length}" end def test end end Problem64.new.test puts Problem64.new.solve
true
9e45b49fa476e974dbf4f0b3004eb2c00a829ef8
Ruby
alf-tool/alf-core
/lib/alf/adapter.rb
UTF-8
3,355
3.015625
3
[ "MIT" ]
permissive
module Alf class Adapter class << self include Support::Registry # Register an adapter class under a specific name. # # Registered class must implement a recognizes? method that takes an array of # arguments; it must returns true if an adapter instance can be built using those # arguments, false otherwise. # # Example: # # Adapter.register(:sqlite, MySQLiteAdapterClass) # Adapter.sqlite(...) # MySQLiteAdapterClass.new(...) # Adapter.autodetect(...) # => MySQLiteAdapterClass.new(...) # # @see also autodetect and recognizes? # @param [Symbol] name name of the connection kind # @param [Class] clazz class that implemented the connection def register(name, clazz) super([name, clazz], Adapter) end # Auto-detect the connection class to use for specific arguments. # # This method returns an instance of the first registered Connection class that returns # true to an invocation of recognizes?(args). It raises an ArgumentError if no such # class can be found. # # @param [Object] conn_spec a connection specification # @return [Class] the first registered class that recognizes `conn_spec` # @raise [ArgumentError] when no registered class recognizes the arguments def autodetect(conn_spec) name, clazz = registered.find{|nc| nc.last.recognizes?(conn_spec) } unless clazz raise ArgumentError, "No adapter for `#{conn_spec.inspect}`" end clazz end # Builds an adapter instance through the autodetection adapter mechanism. # # @param [Hash] conn_spec a connection specification # @param [Module] schema a module for scope definition # @return [Adapter] an adapter instance def factor(conn_spec) return conn_spec if conn_spec.is_a?(Adapter) autodetect(conn_spec).new(conn_spec) end # Returns true if _args_ can be used for get an adapter instance, false otherwise. # # When returning true, an immediate invocation of new(*args) should succeed. While # runtime exception are admitted (no such connection, for example), argument errors # should not occur (missing argument, wrong typing, etc.). # # Please be specific in the implementation of this extension point, as registered # adapters for a chain and each of them should have a chance of being selected. # # @param [Array] args arguments for the Adapter constructor # @return [Boolean] true if an adapter may be built using `args`, # false otherwise. def recognizes?(args) false end end # class << self # The connection specification attr_reader :conn_spec # Creates an adapter instance. # # @param [Object] conn_spec a connection specification. def initialize(conn_spec) @conn_spec = conn_spec end # Returns a low-level connection on this adapter def connection Connection.new(conn_spec) end # Yields the block with a connection and closes it afterwards def connect c = connection yield(c) ensure c.close if c end end # class Adapter end # module Alf require_relative 'adapter/connection'
true
658610f1e093762036d3705109f61c19f8b48885
Ruby
AndresgilMVP/Practica-de-archivos
/exercise4.rb
UTF-8
584
2.953125
3
[]
no_license
# #Copia el contendio de file_to_copy.txt en un nuevo archivo que se llame notes.txt # (Es probable que este archivo aun no exista en tu directorio). # No se debe alterar el contenido original de file_to_copy.txt # y ten mucho cuidado de cerrar correctamente ambos archivos. archivo_original = "file_to_copy.txt" archivo_copia = "new_file.txt" archivo_original_abierto = open(archivo_original) archivo_original_leido = archivo_original_abierto.read archivo_original_abierto.close abrir_copia = open(archivo_copia, "w+") abrir_copia.write(archivo_original_leido) abrir_copia.close
true
94fe6d0d5d2c94ea1b7ead3c0d196994317797cd
Ruby
kreyes12/ruby-objects-has-many-lab-london-web-071618
/lib/artist.rb
UTF-8
424
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_accessor :name, :songs @@all = [] def initialize(name=nil) @songs = [] @name = name end def self.all @@all end def add_song(new_song) new_song.artist = self @songs << new_song end def add_song_by_name(name) song = Song.new(name) song.artist = self @songs << song end def song_count songs = @songs songs.length end end
true
2c05a908207fc58864c6749e0b8175be77f7e8e2
Ruby
hrigu/rails_3_1_sandbox
/spec/lib/mastermind/master/evaluator_spec.rb
UTF-8
2,520
2.921875
3
[]
no_license
require "spec_helper" require File.expand_path(Rails.root) + '/lib/mastermind/master/computer_master' describe "Evaluator can evaluate guesses" do context "The code has four different colors" do before(:all) do @code = :r, :b, :g, :y @evaluator = Evaluator.new end context "and the guess is exactly the same code" do before(:each) do @result = @evaluator.evaluate(@code, @code) end it "the result should has four blacks and zero white" do @result[0].should == 4 @result[1].should == 0 end end context "and the guess has two members that has the correct color and are on the right place" do before(:each) do guess = :r, :b, :p, :l @result = @evaluator.evaluate(@code, guess) end it "the result should has two blacks and zero white" do @result[0].should == 2 @result[1].should == 0 end end context "and the guess has one member with the correct color but on the wrong place" do before(:each) do guess = :p, :r, :o, :l @result = @evaluator.evaluate( @code, guess ) end it "the result should has zero blacks and one white" do @result[0].should == 0 @result[1].should == 1 end end context "and the guess has two members with the correct color: One on the correct place" do before(:each) do guess = :r, :r, :o, :l @result = @evaluator.evaluate(@code, guess) end it "the result should have zero blacks and one white" do @result[0].should == 1 @result[1].should == 0 end end end context "The code has two member with the same color" do before(:all) do @code = :r, :b, :b, :y @evaluator = Evaluator.new end context "and the guess has only one member with this color, but on the wrong place" do before(:each) do guess = :g, :g, :o, :b @result = @evaluator.evaluate(@code, guess) end it "the result should have zero blacks and one white" do @result[0].should == 0 @result[1].should == 1 end end context "and the guess has only two member with this color, but on the wrong place" do before(:each) do guess = :b, :g, :o, :b @result = @evaluator.evaluate(@code, guess) end it "the result should have zero blacks and one white" do @result[0].should == 0 @result[1].should == 2 end end end end
true
efcaf24c3372d69f21889bca68e39ee361adfee8
Ruby
danbriechle/Enigma
/lib/key.rb
UTF-8
254
2.96875
3
[]
no_license
require 'SecureRandom' require 'pry' class Key attr_reader :first_shift def initialize @first_shift = number_generator end def number_generator number = SecureRandom.random_number(99999).to_s.ljust(5, "0").to_i number end end
true
f54d507f6a296332ff85711a131ad656ecc93f03
Ruby
seejee/sqlite-pure-ruby
/lib/pure-sqlite/database_record.rb
UTF-8
965
3.140625
3
[]
no_license
module PureSQLite class DatabaseRecord attr_reader :entries def initialize(stream) @header_index = Structures::VariableLengthInteger.new(stream) @entries = read_entries(stream) end def header_index_length @header_index.length end def total_header_bytes @header_index.value end def [](index) entries[index] end private def read_entries(stream) data = get_entries(stream) populate_values(stream, data) data end def populate_values(stream, data) data.each do |entry| entry.populate_value(stream) end end def get_entries(stream) bytes_remaining = total_header_bytes - header_index_length entries = [] until(bytes_remaining == 0) entry = Structures::DatabaseRecordEntry.new(stream) entries << entry bytes_remaining -= entry.header_length end entries end end end
true
670e886103663c2d5a1e0880b28ca9464a19162f
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/5939903581e04a07ac6dffe6374e7a9c.rb
UTF-8
109
3.25
3
[]
no_license
class Hamming def self.compute(a, b) a.split("").zip(b.split "").count { |x| x[0] != x[1] } end end
true
746cf0cbdfafa4f564a4b2d305d20877ed67b032
Ruby
filip373/design-patterns
/09_decorator/documents_app.rb
UTF-8
696
2.953125
3
[]
no_license
require_relative "./plaintext_document" require_relative "./encrypted_document" require_relative "./compressed_document" require_relative "./notified_document" puts("Writing a plaintext document...") plaintext_doc = PlaintextDocument.new("my_book.txt") plaintext_doc.write("First chapter") puts("Compressing the document...") compressed_doc = CompressedDocument.new(plaintext_doc) compressed_doc.write("Second chapter") puts("Encrypting the document...") encrypted_doc = EncryptedDocument.new(compressed_doc, 12) encrypted_doc.write("Third chapter") puts("Notificaions about the document...") notified_doc = NotifiedDocument.new(plaintext_doc, "Twitter") notified_doc.write("Fourth chapter")
true
32a0be829b3620391dce24602e41a29f9d7b817f
Ruby
remiodufuye/programming-univbasics-nds-nested-arrays-iteration-lab-dc-web-102819
/lib/iteration.rb
UTF-8
1,482
3.78125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def join_ingredients(src) # Given an Array of 2-element Arrays ( [ [food1, food2], [food3, # food4]....[foodN, foodM]]): # # Build a new Array that contains strings where each pair of foods is # inserted into this template: # # "I love (inner array element 0) and (inner array element 1) on my pizza"" # As such, there should be a new String for each inner array, or pair new_array = [] row_index = 0 while row_index < src.length do new_array.push("I love #{src[row_index][0]} and #{src[row_index][1]} on my pizza") row_index+=1 end new_array end # ingredients = [["pepperoni", "sausage"], ["green olives", "green peppers"], ["onions", "pineapple"]] # join_ingredient(ingredients) # ["I love pepperoni and sausage on my pizza", "I love green olives and green olives on my pizza", "I love onions and pineapple on my pizza"] def find_greater_pair(src) # src will be an array of [ [number1, number2], ... [numberN, numberM] ] # Produce a new Array that contains the larger number of each of the pairs # that are in the inner Arrays index = 0 new_array = [] while index < src.length do new_array.push(src[index].max) index += 1 end new_array end def total_even_pairs(src) total = 0 i = 0 while i < src.length do if (src[i][0] % 2 == 0) && (src[i][1] % 2 == 0) total += src[i][0] + src[i][1] end i += 1 end total end
true
31e9128c92166efa92ac7b837e779661403db562
Ruby
peterneely/e2e-sample
/features/step_definitions/#XSELL04_Quantity_steps.rb
UTF-8
2,738
2.609375
3
[]
no_license
Given(/^an online customer added a product to their shopping bag$/) do pending end Then(/^they should be able to increment the quantity by (\d+) with each click$/) do |arg| pending end And(/^the quantity in the shopping bag summary should increment with each click$/) do pending end And(/^the price in the product summary should increment with each click$/) do pending end And(/^the subtotal in the shopping bag summary should increment with each click$/) do pending end And(/^the FRIES promotion should be shown with each click if a matching promotion is available$/) do pending end And(/^the FRIES promotion should be hidden with each click if a matching promotion is not available$/) do pending end Then(/^they should be able to decrement the quantity by (\d+) with each click$/) do |arg| pending end And(/^the quantity in the shopping bag summary should decrement with each click$/) do pending end And(/^the price in the product summary should decrement with each click$/) do pending end And(/^the subtotal in the shopping bag summary should decrement with each click$/) do pending end And(/^the quantity in the product summary is 99$/) do pending end Then(/^the increment control should be disabled$/) do pending end And(/^the quantity in the product summary is 1$/) do pending end Then(/^the decrement control should be disabled$/) do pending end Then(/^they should be able to enter a quantity from (\d+) to (\d+), inclusive$/) do |arg1, arg2| pending end And(/^the quantity in the shopping bag summary should update with each keypress$/) do pending end And(/^the price in the product summary should update with each keypress$/) do pending end And(/^the subtotal in the shopping bag summary should update with each keypress$/) do pending end And(/^the FRIES promotion should be shown with each keypress if a matching promotion is available$/) do pending end And(/^the FRIES promotion should be hidden with each keypress if a matching promotion is not available$/) do pending end When(/^they try to enter an (.*)$/) do |invalid_quantity| pending end Then(/^the quantity in the product summary should change to (.*)$/) do |value| pending end And(/^the quantity in the shopping bag summary should change to (.*)$/) do |value| pending end And(/^the price in the product summary should update$/) do pending end And(/^the subtotal in the shopping bag summary should update$/) do pending end And(/^the FRIES promotion should be shown if a matching promotion is available$/) do pending end And(/^the FRIES promotion should be hidden if a matching promotion is not available$/) do pending end And(/^customer should see an error message$/) do pending end
true
3f58797eaee1e10c3bf1b45aa8058582dc7b4bff
Ruby
great084/draque_like
/character.rb
UTF-8
454
3.796875
4
[]
no_license
class Character attr_reader :name, :offense, :defense attr_accessor :hp def initialize(name:, hp:, offense:, defense:) @name = name @hp = hp @offense = offense @defense = defense end def attack(opponent) puts "#{@name}の攻撃!!" damage = @offense - opponent.defense / 2 puts "#{opponent.name}に#{damage} のダメージを与えた!!" opponent.hp = damage > opponent.hp ? 0 : opponent.hp - damage end end
true
8cdfe54d7c18c5b063f36805051f8f9b97f395bf
Ruby
mgoldfi1/oo-banking-v-000
/lib/transfer.rb
UTF-8
760
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Transfer attr_reader :sender, :receiver attr_accessor :status, :amount def initialize(sender,receiver,amount) @sender = sender @receiver = receiver @amount = amount @status = "pending" end def valid? sender.valid? && receiver.valid? end def execute_transaction if self.valid? == false || self.amount > sender.balance self.status = "rejected" "Transaction rejected. Please check your account balance." elsif self.status == "pending" sender.balance -= self.amount receiver.balance += self.amount self.status = "complete" end end def reverse_transfer if self.status == "complete" sender.balance += self.amount receiver.balance -= self.amount self.status = "reversed" end end end
true
f7f3745866d54ecb768f7e2009d9cdde1ed1948c
Ruby
Rhoxio/RPG
/Game/Testing/class_testing.rb
UTF-8
103
2.921875
3
[]
no_license
class Person class << Person def species "Homo Sapien" end end end p Person.species
true
e1d1f83cbf3aa8b083c9ef169aa0a39ae7d501f1
Ruby
Mew-Traveler/Time_Traveler
/lib/Time_Traveler/rentInfo.rb
UTF-8
1,232
2.625
3
[ "MIT" ]
permissive
require_relative 'airbnb_api' module Airbnb class RentInfo attr_reader :location attr_reader :infos def initialize(rooms,info) @infos = rooms.map { |item| rooms = room(item) } # searchVal(info) end def infos @infos end def self.find(location:) @search_info = {api:ENV['AIRBNB_API'],locate:location} rooms_data = AirbnbApi.rooms_info(location) new(rooms_data,@search_info) end private def room(item) #item = item['listing'] room_id = item['listing']['id'] room = { id: room_id, name: item['listing']['name'], # need to get price from airbnbAPI # Basic Sample Request: # https://api.airbnb.com/v2/listings/5116458?client_id=3092nxybyb0otqw18e8nh5nty&_format=v1_legacy_for_p3 address: item['listing']['public_address'], airbnb_link: "https://www.airbnb.com.tw/rooms/" + room_id.to_s, roomImg: item['listing']['picture_url'], bed: item['listing']['beds'], roomRank: item['listing']['star_rating'] } end def searchVal(oriSearch) @location = oriSearch['locate'] @airbnbapi = oriSearch['api'] end end end
true
feda04eb6bb896bbd6e68f897e2a7a5bb8656b36
Ruby
Hilbert-lang/dydx
/lib/dydx/function.rb
UTF-8
624
2.890625
3
[ "MIT" ]
permissive
module Dydx class Function attr_accessor :algebra, :vars def initialize(*vars) @vars = vars end def <=(algebra) @algebra = algebra self end def evalue(nums) subst_hash = Hash[*[@vars, nums].transpose.flatten] begin @algebra.subst(subst_hash).to_f rescue ArgumentError eval(@algebra.subst(subst_hash).to_s) end end def differentiate(sym = :x) @algebra.differentiate(sym) end alias_method :d, :differentiate def to_s algebra.to_s end def ==(function) to_s == function.to_s end end end
true
cf49ce2a8f44f37ef81a8094bdcf99b8c0833006
Ruby
jwilkins/coderay
/etc/check-diffs.rb
UTF-8
484
2.5625
3
[ "MIT" ]
permissive
DIFF_PART = / ^ ([\d,]+c[\d,]+) \n # change ( (?: < .* \n )+ ) # old ---\n ( (?: > .* \n )+ ) # new /x class String def undiff! gsub!(/^./, '') end end for diff in Dir['*.debug.diff'] puts diff diff = File.read diff diff.scan(/#{DIFF_PART}|(.+)/o) do |change, old, new, error| raise error if error old.undiff! new.undiff! new.gsub!('inline_delimiter', 'delimiter') unless new == old raise "\n>>>\n#{new}\n<<<#{old}\n" end end end
true
11d98d602d3f14c7fc3b84ef3c0a134733691829
Ruby
KerryAlsace/ruby-challenges
/case.rb
UTF-8
229
3.078125
3
[]
no_license
weather='cold' case weather when 'sunny' puts "Wear sunblock!" when 'rainy' puts "Bring an umbrella!" when 'cold' puts "Wear a jacket!" when 'snowy' puts "Wear snow shoes!" else puts "Take a gamble, wear whatever you want!" end
true
e128ab2074311c70dfa58c2161ac4e3f9437aba5
Ruby
amkhrjee/mb-geometry
/lib/mb/geometry.rb
UTF-8
9,720
3.53125
4
[ "BSD-2-Clause" ]
permissive
require 'matrix' require 'mb-math' require 'mb-util' require_relative 'geometry/version' module MB # Inefficient algorithms for some basic geometric operations. module Geometry class << self # Finds the line intersection, if any, between two lines given coordinates # in the form used by rubyvor (either [a, b, c] or [:l, a, b, c], using # the formula ax + by = c). Returns an array of [x, y] if a single # intersection exists. Returns nil if the lines are coincident or there is # no intersection. def line_intersection(line1, line2) a, b, c = line1 d, e, f = line2 denom = (b * d - a * e).to_f # Detect coincident and parallel lines return nil if denom == 0 x = (b * f - c * e) / denom y = (c * d - a * f) / denom [x, y] end # Returns an array of [x, y] if the two segments (given by arrays of [x1, # y1, x2, y2]) intersect. Returns nil if the segments are parallel or do # not intersect. def segment_intersection(seg1, seg2) x1, y1, x2, y2 = seg1 x3, y3, x4, y4 = seg2 line1 = segment_to_line(*seg1) line2 = segment_to_line(*seg2) xmin = [[x1, x2].min, [x3, x4].min].max xmax = [[x1, x2].max, [x3, x4].max].min ymin = [[y1, y2].min, [y3, y4].min].max ymax = [[y1, y2].max, [y3, y4].max].min x, y = line_intersection(line1, line2) return nil unless x && y if x >= xmin && x <= xmax && y >= ymin && y <= ymax return [x, y] end nil end # Generates an arbitrary segment for the given line a * x + b * y = c. # Possibly useful for working with vertical or horizontal lines via the dot # product. Returns [x1, y1, x2, y2]. def line_to_segment(a, b, c) raise 'Invalid line (a or b must be nonzero)' if a == 0 && b == 0 if a == 0 y = c.to_f / b [0.0, y, 1.0, y] elsif b == 0 x = c.to_f / a [x, 0.0, x, 1.0] else [0.0, c.to_f / b, 1.0, (c - a).to_f / b] end end # Finds the general form of a line intersecting the given points. Returns # [a, b, c] where a * x + b * y = c. def segment_to_line(x1, y1, x2, y2) raise 'Need two distinct points to define a segment' if x1 == x2 && y1 == y2 # Vertical/horizontal/oblique lines if y1 == y2 [0.0, 1.0, y1] elsif x1 == x2 [1.0, 0.0, x1] else [y1 - y2, x2 - x1, x2 * y1 - x1 * y2] end end # Returns the area of a 2D polygon with the given +vertices+ in order of # connection, each of which must be a 2D coordinate (an array of two # numbers). If vertices are given clockwise, the area will be negative. # # Uses the formula from http://mathworld.wolfram.com/PolygonArea.html def polygon_area(vertices) raise "A polygon must have 3 or more vertices, not #{vertices.length}" unless vertices.length >= 3 area = 0 # Rely on Ruby's circular array indexing for negative indices vertices.size.times do |idx| x2, y2 = vertices[idx] x1, y1 = vertices[idx - 1] area += x1 * y2 - x2 * y1 end return area * 0.5 end # Dot product of two vectors (x1, y1) and (x2, y2). # # Using Ruby's Vector class (from require 'matrix') is probably a better # option, when possible. def dot(x1, y1, x2, y2) x1 * x2 + y1 * y2 end # Computes a bounding box for the given 2D +points+ (an array of # two-element arrays), returned as [xmin, ymin, xmax, ymax]. If +expand+ # is given and greater than 0.0, then the bounding box dimensions will be # multiplied by (1.0 + +expand+). def bounding_box(points, expand = nil) raise ArgumentError, 'No points were given' if points.empty? xmin = Float::INFINITY ymin = Float::INFINITY xmax = -Float::INFINITY ymax = -Float::INFINITY points.each do |x, y| xmin = x if xmin > x ymin = y if ymin > y xmax = x if xmax < x ymax = y if ymax < y end if expand && expand > 0.0 extra_width = 0.5 * expand * (xmax - xmin) extra_height = 0.5 * expand * (ymax - ymin) xmin -= extra_width xmax += extra_width ymin -= extra_height ymax += extra_height end [xmin, ymin, xmax, ymax] end # Clips a segment to a bounding box. Returns the clipped segment as an # array with [x1, y1, x2, y2]. # # TODO: Delete this if it is never used and no tests are written. def clip_segment(segment, box) xmin, ymin, xmax, ymax = box x1, y1, x2, y2 = segment new_segment = [] if x1 >= xmin && x1 <= xmax && y1 >= ymin && y1 <= ymax new_segment += [x1, y1] end if x2 >= xmin && x2 <= xmax && y2 >= ymin && y2 <= ymax new_segment += [x2, y2] end return new_segment if new_segment.size == 4 bounds = { top: [xmin, ymax, xmax, ymax], left: [xmin, ymin, xmin, ymax], bottom: [xmin, ymin, xmax, ymin], right: [xmax, ymin, xmax, ymax], } bounds.each do |edge, edge_seg| if intersection = segment_intersection(segment, edge_seg) puts "Segment intersects with #{edge}" new_segment += intersection puts "New segment is #{new_segment.inspect}" return new_segment if new_segment.size == 4 end end raise 'No segment could be formed' end # Returns the distance from the line described by a*x + b*y = c to the # point (x, y). # # Based on the formula from # http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html def distance_to_line(a, b, c, x, y) # Using -c instead of +c due to moving C across the equals sign (a * x + b * y - c).abs.to_f / Math.sqrt(a * a + b * b) end # Returns a line that is the perpendicular bisector of the given segment as # [a, b, c], where a * x + b * y = c. # # Based on the derivation from https://math.stackexchange.com/a/2079662 def perpendicular_bisector(x1, y1, x2, y2) [ x2 - x1, y2 - y1, 0.5 * (x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1) ] end # Returns the circumcenter of the triangle defined by the given three # points as [x, y]. Returns nil if the points are collinear. # # The circumcenter of a polygon is the center of the circle that passes # through all the points of the polygon. See also #circumcircle. def circumcenter(x1, y1, x2, y2, x3, y3) b1 = perpendicular_bisector(x1, y1, x2, y2) b2 = perpendicular_bisector(x2, y2, x3, y3) x, y = line_intersection(b1, b2) return nil if x.nil? || y.nil? [x, y] end # Returns the circumcircle of the triangle defined by the given three # points as [x, y, rsquared]. Returns nil if the points are collinear. def circumcircle(x1, y1, x2, y2, x3, y3) x, y = circumcenter(x1, y1, x2, y2, x3, y3) return nil if x.nil? || y.nil? dx = x - x1 dy = y - y1 rsquared = dx * dx + dy * dy [x, y, rsquared] end # Returns the average of all of the given points. Each point should have # the same number of dimensions. Returns nil if no points were given. def centroid(points) return nil if points.empty? sum = points.reduce([0] * points.first.size) { |acc, point| acc.size.times do |i| acc[i] += point[i] end acc } sum.map { |v| v.to_f / points.size } end # Returns a Matrix that will rotate augmented 2D vectors by +:radians+ # around the point (+:xcenter+, +:ycenter+). def rotation_matrix(radians:, xcenter: 0, ycenter: 0) pre_translate = Matrix[ [1, 0, -xcenter], [0, 1, -ycenter], [0, 0, 1] ] r = radians.rotation rotation = Matrix[[*r.row(0), 0], [*r.row(1), 0], [0, 0, 1]] post_translate = Matrix[ [1, 0, xcenter], [0, 1, ycenter], [0, 0, 1] ] post_translate * rotation * pre_translate end # Returns a Matrix that will scale 2D vectors by +:xscale+/+:yscale+ # (each defaults to copying the other, but at least one must be # specified) centered around the point (+:xcenter+, +:ycenter+). # Multiply with an augmented Vector to apply the transformation. # # Example: # v = Vector[2, 2, 1] # Third/augmented element (w) must be 1 # m = MB::Geometry.scale_matrix(xscale: 3, yscale: 2, xcenter: 1, ycenter: 1) # m * v # # => Vector[4, 3, 1] # x, y, w def scale_matrix(xscale:, yscale: nil, xcenter: 0, ycenter: 0) raise "Specify at least one of :xscale and :yscale" if !(xscale || yscale) xscale ||= yscale yscale ||= xscale Matrix[ [xscale, 0, -xcenter * (xscale - 1)], [0, yscale, -ycenter * (yscale - 1)], [0, 0, 1] ] end end end Geo = Geometry end require_relative 'geometry/generators' require_relative 'geometry/delaunay' require_relative 'geometry/voronoi' require_relative 'geometry/voronoi_animator' require_relative 'geometry/correction'
true
d62d0bac934e54894365d7250b08faed3a3cc0d5
Ruby
am-kantox/see_as_vee
/lib/see_as_vee/producers/hashes.rb
UTF-8
3,180
2.75
3
[ "MIT" ]
permissive
module SeeAsVee module Producers class Hashes INTERNAL_PARAMS = %i|ungroup delimiter|.freeze NORMALIZER = ->(symbol, hash) { hash.map { |k, v| [k.public_send(symbol ? :to_sym : :to_s), v] }.to_h }.freeze HUMANIZER = lambda do |hash| hash.map do |k, v| [k.respond_to?(:humanize) ? k.humanize : k.to_s.sub(/\A_+/, '').tr('_', ' ').downcase, v] end.to_h end.freeze def initialize *args, **params @hashes = [] @params = params add(*args) end def add *args @keys, @joined = [nil] * 2 @hashes += degroup(args.flatten.select(&Hash.method(:===)), @params[:ungroup], @params[:delimiter] || ',') normalize!(false) end def normalize symbol = true # to_s otherwise @hashes.map(&NORMALIZER.curry[symbol]) end def normalize! symbol = true # to_s otherwise @hashes.map!(&NORMALIZER.curry[symbol]) self end def humanize @hashes.map(&HUMANIZER) end def humanize! @hashes.map!(&HUMANIZER) self end def join return @joined if @joined @joined = @hashes.map { |hash| keys.zip([nil] * keys.size).to_h.merge hash } end def keys @keys ||= @hashes.map(&:keys).reduce(&:|) end def to_sheet SeeAsVee::Sheet.new(humanize!.join.map(&:values).unshift(keys)) end private def degroup hashes, columns, delimiter return hashes if (columns = [*columns]).empty? hashes.tap do |hs| hs.each do |hash| columns.each do |column| case c = hash.delete(column) when Array then c when String then c.split(delimiter) else [c.inspect] end.each.with_index(1) do |value, idx| hash["#{column}_#{idx}"] = value end end end end end class << self def join *args, normalize: :human Hashes.new(*args).join.tap do |result| case normalize when :humanize, :human, :pretty then result.map!(&HUMANIZER) when :string, :str, :to_s then result.map!(&NORMALIZER.curry[false]) when :symbol, :sym, :to_sym then result.map!(&NORMALIZER.curry[true]) end end end def csv *args, **params constructor_params, params = split_params(**params) result, = Hashes.new(*args, **constructor_params).to_sheet.produce csv: true, xlsx: false, **params result end def xlsx *args, **params constructor_params, params = split_params(**params) _, result = Hashes.new(*args, **constructor_params).to_sheet.produce csv: false, xlsx: true, **params result end # **NB** this method is NOT idempotent! def split_params **params [ INTERNAL_PARAMS.each_with_object({}) do |param, acc| acc[param] = params.delete(param) end.reject { |_, v| v.nil? }, params ] end end end end end
true
07ba9b19755c6d834410daf74d6ae882fc7d2bbc
Ruby
nkoehring/towerdefence
/classes/game.rb
UTF-8
6,183
3.125
3
[ "ISC" ]
permissive
module TowerDefence class Game include EventHandler::HasEventHandler include TowerDefence def initialize() Configuration.setup make_screen make_clock make_event_hooks # basics Grid.setup @screen.size @grid_highlighter = Grid::GridHighlighter.new @the_path = Grid::GridPath.new @enemies = Sprites::Group.new @towers = Sprites::Group.new @hud = Hud.new # gameplay @restock_enemies = 0 @round = 0 @round_timer = 0 @ticks = 0 @lives = Configuration.rounds[:lives] - 1 @bounty = Configuration.enemy[:bounty] @tower_price = Configuration.tower[:price] @money = Configuration.rounds[:money] # gameplay works as following: # round_timer will be resetted at first and the game loop does: # update_timer # -> next_round! # ---> reset_timer # ---> create_enemy_wave # -----> restock_enemies! reset_timer end # The "main loop". Repeat the #step method # over and over and over until the user quits. def go catch(:quit) do loop do step end end end private def game_over! @game_over = true @enemies.clear @towers.clear @screen.fill :black @hud.draw_score @screen end def tower_upgrade event if @money >= event.price @money -= event.price event.tower.upgrade! else puts "Insufficien money (#{@money}/#{event.price})." end end def count_survivors if @lives > 0 @lives += (@lives * Configuration.rounds[:lives_round_multiplier]) end end def enemy_defeated event @money += @bounty @enemies.delete event.dead end def enemy_missed event if @lives > 0 @lives -= 1 else game_over! end end def next_round! @round += 1 @bounty += (@bounty * Configuration.enemy[:bounty_round_multiplier]).ceil count_survivors reset_timer create_enemy_wave end def reset_timer @round_timer = Configuration.rounds[:secs] mul = Configuration.rounds[:secs_round_multiplier] (@round-1).times { |r| @round_timer += (@round_timer*mul).ceil } end def update_timer @ticks += 1 if @ticks % 30 == 0 and @enemies.length == 0 # around every second @round_timer -= 1 next_round! if @round_timer == 0 end end def restock_enemies! # calculate hitpoints for this round hp = Configuration.enemy[:hitpoints] mul = Configuration.enemy[:hitpoints_round_multiplier] @round.times {|r| hp += (hp*mul).ceil } if @clock.lifetime() % 20 < 3 @enemies << Enemy.new( @event_handler, hp ) @restock_enemies -= 1 end end def create_enemy_wave if @enemies.empty? @restock_enemies = Configuration.rounds[:enemies] mul = Configuration.rounds[:enemies_round_multiplier] @round.times {|r| @restock_enemies += (@restock_enemies*mul).ceil } puts " >>> A NEW ENEMY WAVE COMES! (#{@restock_enemies}) <<< " restock_enemies! end end # Checks for collision with other towers or the path def nice_place_for_tower? ghost @towers.collide_sprite(ghost).empty? and @the_path.collide_sprite(ghost).empty? end # Create a tower at the click position def create_tower event if @money >= @tower_price ghost = GhostTower.new( Grid.screenp_to_elementp(event.pos) ) if nice_place_for_tower?(ghost) @money -= @tower_price tower = Tower.new(@event_handler, Grid.screenp_to_elementp(event.pos), @enemies) @towers << tower end end end # Catch the mouse_moved event to set the grid highlighter # below the mouse pointer and check for collision with # towers and the path def mouse_moved event pos = Grid.screenp_to_elementp(event.pos) @grid_highlighter.rect.center = pos if nice_place_for_tower? @grid_highlighter @grid_highlighter.green! else @grid_highlighter.red! end end # Create a new Clock to manage the game framerate # so it doesn't use 100% of the CPU def make_clock @clock = Clock.new() @clock.target_framerate = 30 @clock.calibrate end # Set up the event hooks to perform actions in # response to certain events. def make_event_hooks @event_handler = GlobalEventHandler.new @clock hooks = { MouseMoveTrigger.new( :none ) => :mouse_moved, InstanceOfTrigger.new(InvadingEvent) => :enemy_missed, InstanceOfTrigger.new(DeadEvent) => :enemy_defeated, InstanceOfTrigger.new(UpgradeEvent) => :tower_upgrade, :mouse_left => :create_tower, :escape => :quit, :q => :quit, QuitRequested => :quit } make_magic_hooks( hooks ) end # Create the Rubygame window. def make_screen @screen = Screen.new(Configuration.screen[:size], 32, [HWSURFACE, DOUBLEBUF]) @screen.title = "Towerdefence!" end # Quit the game def quit puts "Quitting!" throw :quit end # Do everything needed for one frame. def step if @game_over game_over! @event_handler.update else # background for playing field and hud @screen.fill :black @screen.fill [50,50,50], Rect.new(Configuration.screen[:hud_rect]) @event_handler.update @hud.update @clock.framerate.ceil, @round, @enemies.length, @money, @lives+1, @round_timer update_timer restock_enemies! if @restock_enemies > 0 @the_path.draw @screen # Draw the enemy path. @enemies.draw @screen # Draw the enemies. @towers.draw @screen # Draw all set towers. @grid_highlighter.draw @screen # Draw the nifty semi-transparent highlighter below the mouse. @hud.draw @screen # draw the HUD end @screen.update() # Refresh the screen. end end end
true
af5e96a234ec0dca1c067fddb45a609d23401326
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz109_sols/solutions/Mark Harris/number_spiral.rb
UTF-8
1,128
3.71875
4
[ "MIT" ]
permissive
class NumberSpiral include Enumerable def initialize(dimension) @n = dimension @even = dimension % 2 @maxSize = (@n**2 - 1).to_s.length end def each @line=0 (0..@n-1).map { yield nextLine } @line=0 end private def nextLine result = spiral(@n, @line) @line+=1 result.map{ |x| x.to_s.center(@maxSize) }.join(" ") end def spiral(n, l) if (n==1) 0 elsif (n % 2 ==0) #Even if (l == 0) # Top row, just return it. (n**2 - n)..(n**2-1) else # Same as the square of size (n-1) at line (l-1) with this square's number in front. ([(n**2 - n - l)] << spiral(n-1,l-1)).flatten end else #Odd if (l==(n-1)) # Bottom row, just return it a = Array.new (n**2-1).downto(n**2-n) { |x| a << x} a else #Same as the square of size (n-1) at line l with this square's number at the end. (spiral(n-1,l).to_a << [(n ** 2 - 2*n + 1 + l)]).flatten end end end end spiral = NumberSpiral.new((ARGV[0] || 9).to_i) spiral.each {|x| puts x }
true
b7a8195875dda42e18bc68e6430874b832fde8ea
Ruby
laithshadeed/hacker-rank
/zombie-cluster/s.rb
UTF-8
1,128
3.296875
3
[]
no_license
#!/usr/bin/env ruby def search_dfs_recursive(z, visited, i) for j in 0..z.length-1 unless visited[j] visited[i] = true search_dfs_recursive(z, visited, j) if z[i][j] == 1 end end end def search_dfs_iterative(z, visited, i) stack = [i] while !stack.empty? j = stack.pop unless visited[j] visited[j] = true for k in 0..z.length-1 stack.push(k) if z[j][k] == 1 end end end end def search_bfs(z, visited, i) queue = [i] while !queue.empty? j = queue.shift unless visited[j] visited[j] = true for k in 0..z.length-1 queue.push(k) if z[j][k] == 1 end end end end def clusters_count(z) count = 0 visited = [] for i in 0..z.length-1 unless visited[i] search_dfs_recursive(z, visited, i) #search_dfs_iterative(z, visited, i) #search_bfs(z, visited, i) count +=1 end end count end zombies = [] gets # Ignore the first line while line = gets do zombies << line.strip.split('').map{ |x| x.to_i } end open ENV['OUTPUT_PATH'], 'w' do |f| f << "#{clusters_count(zombies)}\n" end
true
b2fea5098d2dd7c57cbb13193a9e842deea49dfb
Ruby
larskanis/pkcs11
/lib/pkcs11/session.rb
UTF-8
30,330
2.953125
3
[ "MIT" ]
permissive
require 'pkcs11/helper' module PKCS11 # Cryptoki requires that an application open one or more sessions with a token to gain # access to the token's objects and functions. A session provides a logical connection # between the application and the token. A session can be a read/write (R/W) session or a # read-only (R/O) session (default). class Session include Helper # @private def initialize(pkcs11, session) # :nodoc: @pk, @sess = pkcs11, session end # The session handle. # @return [Integer] def to_int @sess end alias to_i to_int # @private def inspect # :nodoc: "#<#{self.class} #{@sess.inspect}>" end # Logs a user into a token. # @param [Integer, Symbol] user_type is the user type CKU_*; # @param [String] pin is the user's PIN. # @return [PKCS11::Session] # # When the user type is either CKU_SO or CKU_USER, if the call succeeds, each of the # application's sessions will enter either the "R/W SO Functions" state, the "R/W User # Functions" state, or the "R/O User Functions" state. If the user type is # CKU_CONTEXT_SPECIFIC , the behavior of C_Login depends on the context in which # it is called. Improper use of this user type will raise # CKR_OPERATION_NOT_INITIALIZED. def C_Login(user_type, pin) @pk.C_Login(@sess, string_to_handle('CKU_', user_type), pin) self end alias login C_Login # Logs a user out from a token. # # Depending on the current user type, if the call succeeds, each of the application's # sessions will enter either the "R/W Public Session" state or the "R/O Public Session" # state. # @return [PKCS11::Session] def C_Logout() @pk.C_Logout(@sess) self end alias logout C_Logout # Closes the session between an application and a token. # @return [PKCS11::Session] def C_CloseSession() @pk.C_CloseSession(@sess) self end alias close C_CloseSession # Obtains information about a session. # @return [CK_SESSION_INFO] def C_GetSessionInfo() @pk.C_GetSessionInfo(@sess) end alias info C_GetSessionInfo # Initializes a search for token and session objects that match a # template. # # See {Session#find_objects} for convenience. # @param [Hash] find_template points to a search template that # specifies the attribute values to match # The matching criterion is an exact byte-for-byte match with all attributes in the # template. Use empty Hash to find all objects. # @return [PKCS11::Session] def C_FindObjectsInit(find_template={}) @pk.C_FindObjectsInit(@sess, to_attributes(find_template)) self end # Continues a search for token and session objects that match a template, # obtaining additional object handles. # # See {Session#find_objects} for convenience # @return [Array<PKCS11::Object>] Returns an array of Object instances. def C_FindObjects(max_count) objs = @pk.C_FindObjects(@sess, max_count) objs.map{|obj| Object.new @pk, @sess, obj } end # Terminates a search for token and session objects. # # See {Session#find_objects} for convenience # @return [PKCS11::Session] def C_FindObjectsFinal @pk.C_FindObjectsFinal(@sess) self end # Convenience method for the {Session#C_FindObjectsInit}, {Session#C_FindObjects}, {Session#C_FindObjectsFinal} cycle. # # * If called with block, it iterates over all found objects. # * If called without block, it returns with an array of all found Object instances. # @return [Array<PKCS11::Object>] # # @example prints subject of all certificates stored in the token: # session.find_objects(CLASS: PKCS11::CKO_CERTIFICATE) do |obj| # p OpenSSL::X509::Name.new(obj[:SUBJECT]) # end def find_objects(template={}) all_objs = [] unless block_given? C_FindObjectsInit(template) begin loop do objs = C_FindObjects(20) break if objs.empty? if block_given? objs.each{|obj| yield obj } else all_objs += objs end end ensure C_FindObjectsFinal() end return all_objs end # Creates a new Object based on given template. # # If {Session#C_CreateObject} is used to create a key object, the key object will have its # CKA_LOCAL attribute set to false. If that key object is a secret or private key # then the new key will have the CKA_ALWAYS_SENSITIVE attribute set to # false, and the CKA_NEVER_EXTRACTABLE attribute set to false. # # Only session objects can be created during a read-only session. Only public objects can # be created unless the normal user is logged in. # # @param [Hash] template Attributes of the object to create. # @return [PKCS11::Object] the newly created object # @example Creating a 112 bit DES key from plaintext # secret_key = session.create_object( # CLASS: PKCS11::CKO_SECRET_KEY, KEY_TYPE: PKCS11::CKK_DES2, # ENCRYPT: true, WRAP: true, DECRYPT: true, UNWRAP: true, # VALUE: '0123456789abcdef', LABEL: 'test_secret_key') def C_CreateObject(template={}) handle = @pk.C_CreateObject(@sess, to_attributes(template)) Object.new @pk, @sess, handle end alias create_object C_CreateObject # Initializes the normal user's PIN. This standard # allows PIN values to contain any valid UTF8 character, but the token may impose subset # restrictions. # # @param [String] pin # @return [PKCS11::Session] def C_InitPIN(pin) @pk.C_InitPIN(@sess, pin) self end alias init_pin C_InitPIN # Modifies the PIN of the user that is currently logged in, or the CKU_USER # PIN if the session is not logged in. # # @param [String] old_pin # @param [String] new_pin # @return [PKCS11::Session] def C_SetPIN(old_pin, new_pin) @pk.C_SetPIN(@sess, old_pin, new_pin) self end alias set_pin C_SetPIN class Cipher # @private def initialize(update_block) # :nodoc: @update_block = update_block end # Process a data part with the encryption operation. # @param [String] data data to be processed # @return [String] output data def update(data) @update_block.call(data) end alias << update end class DigestCipher < Cipher # @private def initialize(update_block, digest_key_block) # :nodoc: super(update_block) @digest_key_block = digest_key_block end alias digest_update update # Continues a multiple-part message-digesting operation by digesting the # value of a secret key. # @param [PKCS11::Object] key key to be processed # @return [String] output data def digest_key(key) @digest_key_block.call(key) end end def common_crypt( init, update, final, single, mechanism, key, data=nil) # :nodoc: send(init, mechanism, key) if block_given? raise "data not nil, but block given" if data yield Cipher.new(proc{|data_| send(update, data_) }) send(final) else send(single, data) end end private :common_crypt def common_verify( init, update, final, single, mechanism, key, signature, data=nil ) # :nodoc: send(init, mechanism, key) if block_given? raise "data not nil, but block given" if data yield Cipher.new(proc{|data_| send(update, data_) }) send(final, signature) else send(single, data, signature) end end private :common_verify # Initializes an encryption operation. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism the encryption mechanism # @param [PKCS11::Object] key the object handle of the encryption key. # @return [PKCS11::Session] # # See {Session#encrypt} for convenience # # The CKA_ENCRYPT attribute of the encryption key, which indicates whether the key # supports encryption, must be true. # # After calling {Session#C_EncryptInit}, the application can either call {Session#C_Encrypt} to encrypt data # in a single part; or call {Session#C_EncryptUpdate} zero or more times, followed by # {Session#C_EncryptFinal}, to encrypt data in multiple parts. The encryption operation is active # until the application uses a call to {Session#C_Encrypt} or {Session#C_EncryptFinal} to actually obtain the # final piece of ciphertext. To process additional data (in single or multiple parts), the # application must call {Session#C_EncryptInit} again. def C_EncryptInit(mechanism, key) @pk.C_EncryptInit(@sess, to_mechanism(mechanism), key) self end # Encrypts single-part data. # # See {Session#encrypt} for convenience # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_Encrypt(data, out_size=nil) @pk.C_Encrypt(@sess, data, out_size) end # Continues a multiple-part encryption operation, processing another # data part. # # See {Session#encrypt} for convenience # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_EncryptUpdate(data, out_size=nil) @pk.C_EncryptUpdate(@sess, data, out_size) end # Finishes a multiple-part encryption operation. # # See {Session#encrypt} for convenience # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_EncryptFinal(out_size=nil) @pk.C_EncryptFinal(@sess, out_size) end # Convenience method for the {Session#C_EncryptInit}, {Session#C_EncryptUpdate}, {Session#C_EncryptFinal} call flow. # # If no block is given, the single part operation {Session#C_EncryptInit}, {Session#C_Encrypt} is called. # If a block is given, the multi part operation ({Session#C_EncryptInit}, {Session#C_EncryptUpdate}, {Session#C_EncryptFinal}) # is used. The given block is called once with a cipher object. There can be any number of # {Cipher#update} calls within the block, each giving the encryption result of this part as String. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key used key # @param [String] data data to encrypt # @yield [PKCS11::Session::Cipher] Cipher object for processing data parts # @return [String] the final part of the encryption operation. # # @example for using single part operation # iv = "12345678" # cryptogram = session.encrypt( {DES_CBC_PAD: iv}, key, "block 1block 2" ) # # @example for using multi part operation # iv = "12345678" # cryptogram = '' # cryptogram << session.encrypt( {DES_CBC_PAD: iv}, key ) do |cipher| # cryptogram << cipher.update("block 1") # cryptogram << cipher.update("block 2") # end # # @example Calculating a key check value to a secret key # key_kcv = session.encrypt( :DES3_ECB, key, "\0"*8) def encrypt(mechanism, key, data=nil, &block) common_crypt(:C_EncryptInit, :C_EncryptUpdate, :C_EncryptFinal, :C_Encrypt, mechanism, key, data, &block) end # Initializes a decryption operation. # # See {Session#decrypt} for convenience and {Session#C_EncryptInit} for description. def C_DecryptInit(mechanism, key) @pk.C_DecryptInit(@sess, to_mechanism(mechanism), key) end # Decrypts encrypted data in a single part. # # See {Session#decrypt} for convenience. # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_Decrypt(data, out_size=nil) @pk.C_Decrypt(@sess, data, out_size) end # Continues a multiple-part decryption operation, processing another # encrypted data part. # # See {Session#decrypt} for convenience. # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_DecryptUpdate(data, out_size=nil) @pk.C_DecryptUpdate(@sess, data, out_size) end # Finishes a multiple-part decryption operation. # # See {Session#decrypt} for convenience. # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_DecryptFinal(out_size=nil) @pk.C_DecryptFinal(@sess, out_size) end # Convenience method for the {Session#C_DecryptInit}, {Session#C_DecryptUpdate}, {Session#C_DecryptFinal} call flow. # # @see Session#encrypt # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key used key # @param [String] data data to decrypt # @yield [PKCS11::Session::Cipher] Cipher object for processing data parts # @return [String] the final part of the encryption operation. # @example Decrypt data previously encrypted with a RSA pulic key # plaintext2 = session.decrypt( :RSA_PKCS, rsa_priv_key, cryptogram) def decrypt(mechanism, key, data=nil, &block) common_crypt(:C_DecryptInit, :C_DecryptUpdate, :C_DecryptFinal, :C_Decrypt, mechanism, key, data, &block) end # Initializes a message-digesting operation. # # See {Session#digest} for convenience. # @return [PKCS11::Session] def C_DigestInit(mechanism) @pk.C_DigestInit(@sess, to_mechanism(mechanism)) self end # Digests data in a single part. # # See {Session#digest} for convenience. # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_Digest(data, out_size=nil) @pk.C_Digest(@sess, data, out_size) end # Continues a multiple-part message-digesting operation, processing # another data part. # # See {Session#digest} for convenience. # @return [PKCS11::Session] def C_DigestUpdate(data) @pk.C_DigestUpdate(@sess, data) self end # Continues a multiple-part message-digesting operation by digesting the # value of a secret key. # # See {Session#digest} for convenience. # # The message-digesting operation must have been initialized with {Session#C_DigestInit}. Calls to # this function and {Session#C_DigestUpdate} may be interspersed any number of times in any # order. # @return [PKCS11::Session] def C_DigestKey(key) @pk.C_DigestKey(@sess, key) self end # Finishes a multiple-part message-digesting operation, returning the # message digest as String. # # See {Session#digest} for convenience. # @param [Integer, nil] out_size The buffer size for output data provided to the # library. If nil, size is determined automatically. # @return [String] def C_DigestFinal(out_size=nil) @pk.C_DigestFinal(@sess, out_size) end # Convenience method for the {Session#C_DigestInit}, {Session#C_DigestUpdate}, {Session#C_DigestKey}, # {Session#C_DigestFinal} call flow. # # @example # digest_string = session.digest( :SHA_1 ) do |cipher| # cipher.update("key prefix") # cipher.digest_key(some_key) # end # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [String] data data to digest # @yield [PKCS11::Session::DigestCipher] Cipher object for processing data parts # @return [String] final message digest # @see Session#encrypt def digest(mechanism, data=nil, &block) C_DigestInit(mechanism) if block_given? raise "data not nil, but block given" if data yield DigestCipher.new(proc{|data_| C_DigestUpdate(data_) }, proc{|key_| C_DigestKey(key_) }) C_DigestFinal() else C_Digest(data) end end # Initializes a signature operation, where the signature is an appendix to the # data. # # See {Session#sign} for convenience. # @return [PKCS11::Session] def C_SignInit(mechanism, key) @pk.C_SignInit(@sess, to_mechanism(mechanism), key) self end # Signs data in a single part, where the signature is an appendix to the data. # # See {Session#sign} for convenience. # @return [String] message signature def C_Sign(data, out_size=nil) @pk.C_Sign(@sess, data, out_size) end # Continues a multiple-part signature operation, processing another data # part. # # See {Session#sign} for convenience. # @return [PKCS11::Session] def C_SignUpdate(data) @pk.C_SignUpdate(@sess, data) self end # Finishes a multiple-part signature operation, returning the signature. # # See {Session#sign} for convenience. # @return [String] message signature def C_SignFinal(out_size=nil) @pk.C_SignFinal(@sess, out_size) end # Convenience method for the {Session#C_SignInit}, {Session#C_SignUpdate}, {Session#C_SignFinal} call flow. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key used key # @param [String] data data to sign # @yield [PKCS11::Session::Cipher] Cipher object for processing data parts # @return [String] signature # @see Session#encrypt # @example Sign a text by a RSA private key # signature = session.sign( :SHA1_RSA_PKCS, rsa_priv_key, "important text") def sign(mechanism, key, data=nil, &block) common_crypt(:C_SignInit, :C_SignUpdate, :C_SignFinal, :C_Sign, mechanism, key, data, &block) end # Initializes a verification operation, where the signature is an appendix to # the data. # # See {Session#verify} for convenience. def C_VerifyInit(mechanism, key) @pk.C_VerifyInit(@sess, to_mechanism(mechanism), key) end # Verifies a signature in a single-part operation, where the signature is an # appendix to the data. # # See {Session#verify} for convenience. def C_Verify(data, out_size=nil) @pk.C_Verify(@sess, data, out_size) end # Continues a multiple-part verification operation, processing another # data part. # # See {Session#verify} for convenience. def C_VerifyUpdate(data) @pk.C_VerifyUpdate(@sess, data) end # Finishes a multiple-part verification operation, checking the signature. # # See {Session#verify} for convenience. # @return [Boolean] <tt>true</tt> for valid signature. def C_VerifyFinal(out_size=nil) @pk.C_VerifyFinal(@sess, out_size) end # Convenience method for the {Session#C_VerifyInit}, {Session#C_VerifyUpdate}, {Session#C_VerifyFinal} call flow. # # @see Session#encrypt # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key used key # @param [String] signature signature # @param [String] data data to verify against signature # @yield [PKCS11::Session::Cipher] Cipher object for processing data parts # @return [Boolean] <tt>true</tt> for valid signature. # @example # raise("wrong signature") unless session.verify(:SHA1_RSA_PKCS, rsa_pub_key, signature, plaintext) def verify(mechanism, key, signature, data=nil, &block) common_verify(:C_VerifyInit, :C_VerifyUpdate, :C_VerifyFinal, :C_Verify, mechanism, key, signature, data, &block) end # Initializes a signature operation, where the data can be recovered # from the signature # # See {Session#sign_recover} for convenience. def C_SignRecoverInit(mechanism, key) @pk.C_SignRecoverInit(@sess, to_mechanism(mechanism), key) self end # Signs data in a single operation, where the data can be recovered from # the signature. # # See {Session#sign_recover} for convenience. def C_SignRecover(data, out_size=nil) @pk.C_SignRecover(@sess, data, out_size) end # Convenience method for the {Session#C_SignRecoverInit}, {Session#C_SignRecover} call flow. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key signature key # @param [String] data data to be recovered # @return [String] signature # @see Session#verify_recover def sign_recover(mechanism, key, data) C_SignRecoverInit(mechanism, key) C_SignRecover(data) end # Initializes a signature verification operation, where the data can be recovered # from the signature # # See {Session#verify_recover} for convenience. def C_VerifyRecoverInit(mechanism, key) @pk.C_VerifyRecoverInit(@sess, to_mechanism(mechanism), key) end # Verifies a signature in a single-part operation, where the data is # recovered from the signature. # # See {Session#verify_recover} for convenience. def C_VerifyRecover(signature, out_size=nil) @pk.C_VerifyRecover(@sess, signature, out_size=nil) end # Convenience method for the {Session#C_VerifyRecoverInit}, {Session#C_VerifyRecover} call flow. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] key verification key # @return [String] recovered data # @see Session#sign_recover def verify_recover(mechanism, key, signature) C_VerifyRecoverInit(mechanism, key) C_VerifyRecover(signature) end # Continues multiple-part digest and encryption operations, # processing another data part. # # Digest and encryption operations must both be active (they must have been initialized # with {Session#C_DigestInit} and {Session#C_EncryptInit}, respectively). This function may be called any # number of times in succession, and may be interspersed with {Session#C_DigestUpdate}, # {Session#C_DigestKey}, and {Session#C_EncryptUpdate} calls. def C_DigestEncryptUpdate(data, out_size=nil) @pk.C_DigestEncryptUpdate(@sess, data, out_size) end # Continues a multiple-part combined decryption and digest # operation, processing another data part. # # Decryption and digesting operations must both be active (they must have been initialized # with {Session#C_DecryptInit} and {Session#C_DigestInit}, respectively). This function may be called any # number of times in succession, and may be interspersed with {Session#C_DecryptUpdate}, # {Session#C_DigestUpdate}, and {Session#C_DigestKey} calls. def C_DecryptDigestUpdate(data, out_size=nil) @pk.C_DecryptDigestUpdate(@sess, data, out_size) end # Continues a multiple-part combined signature and encryption # operation, processing another data part. # # Signature and encryption operations must both be active (they must have been initialized # with {Session#C_SignInit} and {Session#C_EncryptInit}, respectively). This function may be called any # number of times in succession, and may be interspersed with {Session#C_SignUpdate} and # {Session#C_EncryptUpdate} calls. def C_SignEncryptUpdate(data, out_size=nil) @pk.C_SignEncryptUpdate(@sess, data, out_size) end # Continues a multiple-part combined decryption and # verification operation, processing another data part. # # Decryption and signature operations must both be active (they must have been initialized # with {Session#C_DecryptInit} and {Session#C_VerifyInit}, respectively). This function may be called any # number of times in succession, and may be interspersed with {Session#C_DecryptUpdate} and # {Session#C_VerifyUpdate} calls. def C_DecryptVerifyUpdate(data, out_size=nil) @pk.C_DecryptVerifyUpdate(@sess, data, out_size) end # Generates a secret key Object or set of domain parameters, creating a new # Object. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [Hash] template Attributes of the key to create. # @return [PKCS11::Object] key Object of the new created key. # @example generate 112 bit DES key # key = session.generate_key(:DES2_KEY_GEN, # {ENCRYPT: true, WRAP: true, DECRYPT: true, UNWRAP: true}) def C_GenerateKey(mechanism, template={}) obj = @pk.C_GenerateKey(@sess, to_mechanism(mechanism), to_attributes(template)) Object.new @pk, @sess, obj end alias generate_key C_GenerateKey # Generates a public/private key pair, creating new key Object instances. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [Hash] pubkey_template Attributes of the public key to create. # @param [Hash] privkey_template Attributes of the private key to create. # @return [Array<PKCS11::Object>] an two-items array of new created public and private key Object. # @example # pub_key, priv_key = session.generate_key_pair(:RSA_PKCS_KEY_PAIR_GEN, # {ENCRYPT: true, VERIFY: true, WRAP: true, MODULUS_BITS: 768, PUBLIC_EXPONENT: 3}, # {SUBJECT: 'test', ID: "ID", DECRYPT: true, SIGN: true, UNWRAP: true}) def C_GenerateKeyPair(mechanism, pubkey_template={}, privkey_template={}) objs = @pk.C_GenerateKeyPair(@sess, to_mechanism(mechanism), to_attributes(pubkey_template), to_attributes(privkey_template)) objs.map{|obj| Object.new @pk, @sess, obj } end alias generate_key_pair C_GenerateKeyPair # Wraps (i.e., encrypts) a private or secret key. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] wrapping_key wrapping key # @param [PKCS11::Object] wrapped_key key to wrap # @return [String] the encrypted binary data. # @see Session#C_UnwrapKey # @example Wrapping a secret key # wrapped_key_value = session.wrap_key(:DES3_ECB, secret_key, secret_key) # @example Wrapping a private key # wrapped_key_value = session.wrap_key({DES3_CBC_PAD: "\0"*8}, secret_key, rsa_priv_key) def C_WrapKey(mechanism, wrapping_key, wrapped_key, out_size=nil) @pk.C_WrapKey(@sess, to_mechanism(mechanism), wrapping_key, wrapped_key, out_size) end alias wrap_key C_WrapKey # Unwraps (i.e. decrypts) a wrapped key, creating a new private key or # secret key object. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] wrapping_key wrapping key # @param [String] wrapped_key key data of the wrapped key # @return [PKCS11::Object] key object of the new created key. # @see Session#C_WrapKey # @example # unwrapped_key = session.unwrap_key(:DES3_ECB, secret_key, wrapped_key_value, # CLASS: CKO_SECRET_KEY, KEY_TYPE: CKK_DES2, ENCRYPT: true, DECRYPT: true) def C_UnwrapKey(mechanism, wrapping_key, wrapped_key, template={}) obj = @pk.C_UnwrapKey(@sess, to_mechanism(mechanism), wrapping_key, wrapped_key, to_attributes(template)) Object.new @pk, @sess, obj end alias unwrap_key C_UnwrapKey # Derives a key from a base key, creating a new key object. # # @param [Hash, Symbol, Integer, PKCS11::CK_MECHANISM] mechanism used mechanism # @param [PKCS11::Object] base_key key to derive # @param [Hash] template Attributes of the object to create. # @return [PKCS11::Object] key object of the new created key. # @example Derive a AES key by XORing with some derivation data # deriv_data = "\0"*16 # new_key = session.derive_key( {CKM_XOR_BASE_AND_DATA => {pData: deriv_data}}, secret_key, # CLASS: CKO_SECRET_KEY, KEY_TYPE: CKK_AES, VALUE_LEN: 16, ENCRYPT: true ) def C_DeriveKey(mechanism, base_key, template={}) obj = @pk.C_DeriveKey(@sess, to_mechanism(mechanism), base_key, to_attributes(template)) Object.new @pk, @sess, obj end alias derive_key C_DeriveKey # Mixes additional seed material into the token's random number # generator. # @param [String] entropy data # @return [PKCS11::Session] def C_SeedRandom(data) @pk.C_SeedRandom(@sess, data) self end alias seed_random C_SeedRandom # Generates random or pseudo-random data. # # @param [Integer] out_size # @return [String] random or pseudo-random binary data of <tt>out_size</tt> bytes. def C_GenerateRandom(out_size) @pk.C_GenerateRandom(@sess, out_size) end alias generate_random C_GenerateRandom # Obtains a copy of the cryptographic operations state of a session, # encoded as a string of bytes. # @return [String] # @see Session#C_SetOperationState def C_GetOperationState @pk.C_GetOperationState(@sess) end alias get_operation_state C_GetOperationState # Restores the cryptographic operations state of a session from a # string of bytes obtained with {Session#C_GetOperationState}. # # @param [String] state previously stored session state # @param [PKCS11::Object] encryption key for sessions stored without keys # @param [PKCS11::Object] authentication key for sessions stored without keys # @return [PKCS11::Session] def C_SetOperationState(state, enc_key=nil, auth_key=nil) @pk.C_SetOperationState(@sess, state, enc_key||0, auth_key||0) self end alias set_operation_state C_SetOperationState end end
true
725162cce40ce02d7123f227ab88248cb7cd3d61
Ruby
eilw/Makers-wkend-challenges
/wk1-airport-challenge/lib/weather.rb
UTF-8
111
2.59375
3
[]
no_license
class Weather STORM_PERCENTAGE = 15 def stormy? true if rand(1..100) <= STORM_PERCENTAGE end end
true
94d05a985907aebd1ae72af162689e734ec6c822
Ruby
YuukiMAEDA/AtCoder
/Ruby/ABC/A/9x9.rb
UTF-8
54
2.75
3
[]
no_license
a,b=gets.split.map(&:to_i) puts a<10 && b<10 ? a*b:-1
true
84156836796193d524343ca00da10b2cac08bb1e
Ruby
azhou31/Ruby-Fundamentals-OOP
/exercise.rb
UTF-8
625
4.28125
4
[]
no_license
a = ["Matz","Guido","Dojo","Choi","John"] b = [5,6,9,3,1,2,4,7,8,10] puts a[0] puts a[1] puts b.class puts b.shuffle.join("-") puts a.to_s puts a.shuffle puts a.fetch(2) #returns "Dojo" puts b.delete(4) #deletes 4 puts b.delete_at(4) #deletes 1 puts a.reverse # ["John,"Choi","Dojo","Guido","Matz"] puts a.length #length is 5 puts b.sort #sorts in ascending order [1,2,3,4,5,6,7,8,9,10] puts b.slice(4) #returns 1 puts a.shuffle #returns random shuffled array puts b.join #returns array with no spaces puts a.insert(3,'Google') #returns array with "Google" after the 3rd index puts b.values_at(2,4,1) #9, 1, 6
true
898b5548d2f5daa07c47a1b19d8237c9704a5a4e
Ruby
gambaroff/ruby_sandbox
/code_challenges/top_three_words.rb
UTF-8
837
3.75
4
[ "Apache-2.0" ]
permissive
text = "Count Lev Nikolayevich Tolstoy, also known as Leo Tolstoy, was a Russian writer who primarily wrote novels and short stories. Tolstoy was a master of realistic fiction and is widely considered one of the world's greatest novelists." #My solution. def top_3_words(text) words_to_string = text.downcase.scan(/[\w']+/) hash_top_words = Hash.new(0) for same_word in words_to_string hash_top_words[same_word] +=1 unless same_word =~ /^\W+$/ end sorted = hash_top_words.sort_by {|k,v| v}.reverse.first(3) top_keys = [] for item in sorted top_keys.push(item[0]) end top_keys end top_keys = sorted.each{|k| k[0]} #Great method doing same thing, but not mine. def top_3_words(text) count = Hash.new { 0 } text.scan(/\w+'*\w*/) { |word| count[word.downcase] += 1 } count.map{|k,v| [-v,k]}.sort.first(3).map(&:last) end
true
4839f93ceebc9948a987357bf15d3e0847799a07
Ruby
snikch/vending-machine
/lib/vend/resource_collection.rb
UTF-8
2,000
2.640625
3
[ "MIT" ]
permissive
module Vend class ResourceCollection attr_accessor :parameters, :store include Vend::Finders include Enumerable def initialize(store, klass, records = nil) @store = store @klass = klass @records = records end ## # Check for a collection method # defined on the resource def method_missing symbol, *args if @klass.collection_methods[symbol] instance_exec *args, &@klass.collection_methods[symbol] else super end end def create(attributes = {}) build(attributes).tap(&:save) end def create!(attributes = {}) build(attributes).tap(&:save!) end def build(attributes) @klass.new(attributes.merge store: @store) end def << record (@records || []) << record end def to_a records.to_a end def each records.each do |attributes| yield build(attributes) end end private def http_response @_http_response ||= @store.get( path: @klass.collection_path, parameters: @parameters, status: 200 ) end def remote_records # Is there pagination info? pagination = http_response.data["pagination"] if pagination # Get all pages data = [] page = 1 pages = pagination["pages"] while page <= pages http_response.data.delete("pagination") data.concat(http_response.data.first.last) @_http_response = nil page += 1 (@parameters ||= {})[:page] = page end @parameters.delete(:page) data else http_response.data.first.last end end def records # Data comes back with a root element, so get the first response's value # { products: [ {}, {}, ..] }.first.last == [ {}, {}, ... ] @records ||= remote_records end def clear @records = nil @_http_response = nil end end end
true
2fa487be82b192a48ec7bffe8020d63e1ff7fdb7
Ruby
akoltun/tree_struct
/lib/tree_struct/array.rb
UTF-8
260
2.640625
3
[ "MIT" ]
permissive
require 'typed_array' class TreeStruct class Array < TypedArray def create self << (item = create_item) item end def to_hash self.map(&:to_hash) end private def create_item item_class.new end end end
true
ccdb3765538aa67b173f62b6faed5f3e9cd164c1
Ruby
noam-io/host
/lib/noam_server/ear.rb
UTF-8
1,701
2.59375
3
[ "BSD-3-Clause" ]
permissive
#Copyright (c) 2014, IDEO require 'em/pure_ruby' require 'noam/messages' module NoamServer module EarHandler attr_accessor :callback_delegate def unbind callback_delegate.terminate end end class Ear attr_accessor :host, :port, :incoming_connection def initialize(host, port, incoming_connection) self.host = host self.port = port self.incoming_connection = incoming_connection make_new_outgoing_connection end def send_data(data) if outgoing_connection send_formatted_data(data) elsif connection_pending # drop data else make_new_outgoing_connection(data) end end def terminate safely_close(incoming_connection) safely_close(outgoing_connection) self.incoming_connection = nil self.outgoing_connection = nil end private attr_accessor :data_to_send, :connection_pending, :outgoing_connection def make_new_outgoing_connection(data = nil) self.connection_pending = true EventMachine::connect(host, port, EarHandler) do |connection| self.outgoing_connection = connection outgoing_connection.callback_delegate = self self.connection_pending = false send_formatted_data(data) if data end end def send_formatted_data(data) outgoing_connection.send_data("%06d%s" % [data.bytesize, data]) end def safely_close(connection) connection.close_connection_after_writing if connection rescue RuntimeError => e stack_trace = e.backtrace.join("\n == ") NoamLogging.debug(self, "Error: #{e.to_s}\n Stack Trace:\n == #{stack_trace}") end end end
true
97afb03bbeff5281b6b60e9b8489e4450a778df2
Ruby
FergusLemon/battle
/lib/game.rb
UTF-8
883
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class Game attr_reader :attacker, :defender @@games = [] def initialize(player_1 = Player.new, player_2 = Player.new) @players = [player_1, player_2] @attacker = @players.first @defender = @players.last @winner = nil @@games << self end def self.games @@games.dup end def players @players.dup end def player_1 @players.first end def player_2 @players.last end def winner over? ? set_winner : @winner end def attack(player) raise 'You cannot attack, this game is over.' if over? player.incur_damage switch_turns end def over? player_on_zero? end private def switch_turns @attacker, @defender = @defender, @attacker end def player_on_zero? @players.any? { |p| p.hit_points == 0 } end def set_winner @players.reject { |p| p.hit_points == 0 }.first end end
true
f84b3a857df347acd7912278b38a535940a3ebcc
Ruby
NQuinn27/AdventOfCode
/Day5/day5_p2.rb
UTF-8
458
3.5625
4
[]
no_license
def has_repeats(s) for i in 0..s.length-2 pair = s[i,2] remaining = s[i+2..-1] if remaining.include? pair then return true; end end return false end def has_repeats_with_gap(s) for i in 0..s.length-2 if s[i] == s[i+2] return true end end return false end count = 0 File.readlines('input.txt').each do |line| next unless has_repeats(line) next unless has_repeats_with_gap(line) count += 1 end puts count
true
8a0704eaf8b61d2a3cec772427b63f7a76c1c98f
Ruby
beck03076/happy_shop
/app/values/money_formatter.rb
UTF-8
573
3.40625
3
[]
no_license
# value object for formatting money class MoneyFormatter # new object # # @param money [Money] def initialize(money) @money = money.to_money end # formats to a string # # @return [String] def format "#{amount} #{currency}" end # to get the currency object of money # # @return [Money::Currency] def currency money.currency end # get the amount part of money # # @return [String] def amount money.format(symbol: false) end private attr_reader :money def usd? money.currency.iso_code == 'USD' end end
true
c6e30d991e08057295ce3135d6573a4a1c0ad4cc
Ruby
SquiggerJJohnson/cursebot
/curse.rb
UTF-8
630
2.703125
3
[]
no_license
require 'cinch' require 'obscenity' curse_words = Psych.load_file(Obscenity::Config.new.blacklist) bot = Cinch::Bot.new do configure do |c| c.server = "irc.rizon.net" c.channels = ["#8chan"] c.nick = "CurseBot" c.user = "CurseBot" c.realname = "CurseBot" end on :message, /.+/ do |m| curse_probability = rand(20).to_i puts "I rolled #{curse_probability}" if curse_probability == 1 m.reply "#{m.user.nick}: #{curse_words[rand(curse_words.count).to_i]}" end end on :kick do |m| bot.join m.channel end on :remove do |m| bot.join m.channel end end bot.start
true
7f7e74bff8a89e3f760a2b7140521cdd443d71ab
Ruby
ilyadzyuba/mendeleev
/mendeleev.rb
UTF-8
502
3.578125
4
[]
no_license
require 'json' file = File.read('elements.json') data_hash = JSON.parse(file) puts "У нас всего элементов: #{data_hash.keys.size}" puts data_hash.keys puts "О каком элементе хотите узнать?" element = gets.chomp if data_hash.has_key?(element) puts "Первооткрывателем этого элемента считается: #{data_hash[element]}" else puts "Извините, про такой элемент мы ещё не знаем." end
true
3d04f25089c9fa755ca425218607718e46e7b170
Ruby
mettledrum/gPhone
/g_phone.rb
UTF-8
2,063
2.625
3
[]
no_license
require 'sinatra' require 'rubygems' require 'twilio-ruby' require 'httparty' require 'active_support' require 'active_support/core_ext' get '/' do @@body = params[:Body] redirect to('/g_weather') end get '/g_weather' do # google geocoordinates API weather_search = @@body.gsub(" ", "+") google_api_response = HTTParty.get("https://maps.googleapis.com/maps/api/geocode/json?address=#{weather_search}") if google_api_response['status'] != "OK" @@error_msg = "Google request didn't work." redirect to('/not_right') end # forecast_io API city_lat = google_api_response["results"][0]["geometry"]["location"]["lat"] city_lng = google_api_response["results"][0]["geometry"]["location"]["lng"] forecast_io_response = HTTParty.get("https://api.forecast.io/forecast/#{ENV['FORECAST_IO_KEY']}/#{city_lat},#{city_lng}") if not forecast_io_response['error'].nil? @@error_msg = "Forecast.io request didn't work." redirect to('/not_right') end # all okay from APIs, get the weather info today_summary = forecast_io_response["daily"]["data"][0]["summary"] current_temp = forecast_io_response["currently"]["apparentTemperature"].round today_max = forecast_io_response["daily"]["data"][0]["apparentTemperatureMax"].round today_min = forecast_io_response["daily"]["data"][0]["apparentTemperatureMin"].round today_max_time = Time.at(forecast_io_response["daily"]["data"][0]["apparentTemperatureMaxTime"]).in_time_zone("America/Denver").strftime("%-l %p %Z") today_min_time = Time.at(forecast_io_response["daily"]["data"][0]["apparentTemperatureMinTime"]).in_time_zone("America/Denver").strftime("%-l %p %Z") # send weather text back message = "\n#{@@body}: #{today_summary}\nHigh of #{today_max}˚F at #{today_max_time}.\nLow of #{today_min}˚F at #{today_min_time}.\nNow: #{current_temp}˚F." twiml = Twilio::TwiML::Response.new do |r| r.Message message end twiml.text end # send error msg get '/not_right' do twiml = Twilio::TwiML::Response.new do |r| r.Message @@error_msg end twiml.text end
true
3d90b35e2d0d3e5171acadbc31b2584cd549428f
Ruby
epistrephein/italiansubs
/lib/italiansubs.rb
UTF-8
4,980
2.546875
3
[ "MIT" ]
permissive
require 'faraday' require 'faraday_middleware' require 'json' module ItalianSubs VERSION = '0.1.1'.freeze API_KEY = '6f53c6a55288ff82591c881eda98cd8f'.freeze API_BASEURL = 'https://api.italiansubs.net/api/rest'.freeze USER_AGENT = 'italiansubs-rubygem'.freeze class RequestError < StandardError; end class APIError < StandardError; end class API attr_accessor :authcode def initialize(username = nil, password = nil) return self if username.nil? || password.nil? login!(username, password) sleep 1 end # SHOWS # list of shows def shows res = call( 'shows', {} ) res.body['Itasa_Rest2_Server_Shows']['direct']['shows'].values end # show details def show(show_id) res = call( "shows/#{show_id}", {} ) res.body['Itasa_Rest2_Server_Shows']['single']['show'] end # next episodes def next_episodes res = call( 'shows/nextepisodes', {} ) res.body['Itasa_Rest2_Server_Shows']['nextepisodes']['shows'].values end # show search def search_show(query, page = 1) res = call( 'shows/search', 'q' => query, 'page' => page ) count = res.body['Itasa_Rest2_Server_Shows']['search']['count'].to_i return [] if count.zero? res.body['Itasa_Rest2_Server_Shows']['search']['shows'].values end # SUBTITLES # show subs def subtitles(show_id, version, page = 1) res = call( 'subtitles', 'show_id' => show_id, 'version' => version, 'page' => page ) res.body['Itasa_Rest2_Server_Subtitles']['direct']['subtitles'].values end # subs detail def subtitle(sub_id) res = call( "subtitles/#{sub_id}", {} ) res.body['Itasa_Rest2_Server_Subtitles']['single']['subtitle'] end # subs search def search_subtitle(query, show_id = nil, version = nil, page = 1) res = call( 'subtitles/search', 'q' => query, 'show_id' => show_id, 'version' => version, 'page' => page ) count = res.body['Itasa_Rest2_Server_Subtitles']['search']['count'].to_i return [] if count.zero? res.body['Itasa_Rest2_Server_Subtitles']['search']['subtitles'].values end # USER # user login def login!(username, password) res = call( 'users/login', 'username' => username, 'password' => password ) @authcode = res.body['Itasa_Rest2_Server_Users']['login']['user']['authcode'] end # user profile def user_profile raise APIError, 'not logged in' if @authcode.nil? res = call( 'users', 'authcode' => @authcode ) res.body['Itasa_Rest2_Server_Users']['direct']['user'] end # MYITASA # list myItasa shows def myitasa_shows raise APIError, 'not logged in' if @authcode.nil? res = call( 'myitasa/shows', 'authcode' => @authcode ) res.body['Itasa_Rest2_Server_Myitasa']['shows']['shows'].values end # show last myItasa subtitles def myitasa_last_subtitles(page = nil) raise APIError, 'not logged in' if @authcode.nil? res = call( 'myitasa/lastsubtitles', 'authcode' => @authcode, 'page' => page ) res.body['Itasa_Rest2_Server_Myitasa']['lastsubtitles']['subtitles'].values end # add a show to myItasa def myitasa_add_show(show_id, version) raise APIError, 'not logged in' if @authcode.nil? res = call( 'myitasa/addShowToPref', 'authcode' => @authcode, 'show_id' => show_id, 'version' => version ) res.body['Itasa_Rest2_Server_Myitasa']['addShowToPref']['shows'].values end # remove a show from myItasa def myitasa_remove_show(show_id, version) raise APIError, 'not logged in' if @authcode.nil? res = call( 'myitasa/removeShowFromPref', 'authcode' => @authcode, 'show_id' => show_id, 'version' => version ) res.body['Itasa_Rest2_Server_Myitasa']['removeShowFromPref']['shows'].values end private def call(url, params) res = request.get do |req| req.url url req.params.merge!(params) req.params['format'] = 'json' req.params['apikey'] = API_KEY req.headers['User-Agent'] = USER_AGENT end raise RequestError, res.reason_phrase unless res.success? unless res.body.keys.any? { |k| k =~ /^Itasa_Rest2_Server/ } raise APIError, res.body['root']['error']['message'] end res end # setup faraday request def request Faraday.new(url: API_BASEURL) do |faraday| faraday.adapter Faraday.default_adapter faraday.request :url_encoded faraday.response :json end end end end
true
1ccb5ca69d0c4acfb80cfbbaee6e2d6c04e3050c
Ruby
jjarre10/homework4
/spec/movies_controller_spec.rb
UTF-8
3,750
2.765625
3
[]
no_license
require 'spec_helper' describe MoviesController, :type => :controller do describe 'edit page for appropriate Movie' do it 'When I go to the edit page for the Movie, it should be loaded' do movie = mock('Movie') Movie.should_receive(:find).with('1').and_return(mock) get :edit, {:id => '1'} response.should be_success end it 'Updates when requested' do #Replaced editing the director field by itself I think movie = mock('Movie', :title => 'Star Wars', :director => 'Steven Spielberg') #mock it movie.stub(:update_attributes!) Movie.stub(:find).and_return(movie) #return what's in movie right now movie.should_receive(:update_attributes!) #saying it should get the method to update post :update, {:id => '1', :movie => mock('Movie')} end end describe 'Creating/Deleting Movies' do #Make create/delete in its own describe it 'When I create a new Movie' do movie = mock('Movie') movie.stub!(:title) Movie.should_receive(:create!).and_return(movie) post :create, {:movie => movie} response.should redirect_to(movies_path) #Redirecting b/c that's what happens when you create a new movie end it 'When I destroy a movie' do #We're doing the destroy here movie = mock('Movie', :title => "Star Wars") #Mock a movie w/ title Star Wars Movie.should_receive(:find).with('1').and_return(movie) #find the movie movie.should_receive(:destroy) #should get the method destroy post :destroy, {:id => '1'} #call destroy where ID is 1 end end describe 'Looking at movie info' do it 'Should find movies with same director' do compare = mock('Movie', :director => "Steven Spielberg") #make a movie with this director similar = [mock('Movie'), mock('Movie')] #make two new movies Movie.should_receive(:find).with('1').and_return(compare) #Use find with ID 1 and return the mock Movie.should_receive(:find_all_by_director).with(compare.director).and_return(similar) #Line above will use find_all_by_director and will return compareTo, the mocks of it. get :similar, {:id => '1'} end end describe 'Filter/sort movies' do it 'Sort by release date' do get :index, {:sort => 'release_date'} response.should redirect_to(movies_path(:sort => 'release_date')) end it 'Sort by titles' do get :index, {:sort => 'title'} #get the index, call sort response.should redirect_to(movies_path(:sort => 'title')) #redirect after calling sort end it 'Filters based on ratings' do get :index, {:ratings => {:G => 1} } #get the index, if ratings is G it's 1 response.should redirect_to(movies_path(:ratings => { :G => 1})) #response should redirect to movies path with G where it's 1 end end end #This ends the entire class =begin describe MoviesController, :type => :controller do describe 'adding director for an existing movie' it 'when I go to the edit page for Alien, it 'And I fill in "Director" with "Ridley Scott" it 'And I press update Movie Info' it 'Then the director for "Alien" Should be "Ridley Scott" desctibe 'Find a movie with same director' it 'When I am on the details page of "Star Wars"' it 'When I follow "Find Movies With Same Director" response.should it 'And I should see "THX-1138"' it 'But I should not see "Blade Runner" describe 'What the program does when we don't know the director' it 'When I am on the details page for the movie "Alien"' it Then I should not see "Ridley Scott" it when I follow "Fing Movies With Same direcor"' it "Then I should be on the homepage" it "And I should see "'Alien' Has no director info" =end
true
aa8b7953a13082f44806fc5c17919d3ed82ab855
Ruby
arvicco/win_gui
/spec/win_gui/convenience_spec.rb
UTF-8
2,231
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "spec_helper.rb" describe WinGui, 'Convenience methods' do before(:each) { @win = launch_test_app.main_window } after(:each) { close_test_app } describe '#dialog' do it 'returns top-level dialog window with given title if no block attached' do with_dialog(:save) do dialog_window = dialog(title: DIALOG_TITLE, timeout: 0.1) dialog_window.should_not == nil dialog_window.should be_a Window dialog_window.text.should == DIALOG_TITLE end end it 'yields found dialog window to block if block is attached' do with_dialog(:save) do dialog(title: DIALOG_TITLE) do |dialog_window| dialog_window.should_not == nil dialog_window.should be_a Window dialog_window.text.should == DIALOG_TITLE end end end it 'returns nil if there is no dialog with given title' do with_dialog(:save) do dialog(title: IMPOSSIBLE, timeout: 0.1).should == nil end end it 'yields nil to attached block if no dialog found' do with_dialog(:save) do dialog(title: IMPOSSIBLE, timeout: 0.1) do |dialog_window| dialog_window.should == nil end end end it 'considers all arguments optional' do with_dialog(:save) do use { dialog_window = dialog() } end end end # describe dialog describe 'convenience input methods on top of Windows API' do describe '#keystroke' do spec { use { keystroke(vkey = 30, char = 'Z') } } it 'emulates combinations of keys pressed (Ctrl+Alt+P+M, etc)' do keystroke(VK_CONTROL, 'A') keystroke(VK_SPACE) textarea = @win.child(class: TEXTAREA_CLASS) textarea.text.should.should == ' ' keystroke('1', '2', 'A', 'B'.ord) textarea.text.should.should == ' 12ab' end end # describe '#keystroke' describe '#type_in' do it 'types text message into the window holding the focus' do text = '1234 abcdefg' type_in(text) textarea = @win.child(class: TEXTAREA_CLASS) textarea.text.should =~ Regexp.new(text) end end # describe '#type_in' end # Input methods end # Convenience methods
true
f9fd37200ac0ae0bf4be4726b7533fd13a865df1
Ruby
mobius-network/mobius-client-ruby
/lib/mobius/client/blockchain/key_pair_factory.rb
UTF-8
1,453
3
3
[ "MIT" ]
permissive
# Transforms given value into Stellar::Keypair object. module Mobius::Client::Blockchain::KeyPairFactory class << self # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity # Generates Stellar::Keypair from subject, use Stellar::Client.to_keypair as shortcut. # @param subject [String||Stellar::Account||Stellar::PublicKey||Stellar::SignerKey||Stellar::Keypair] subject. # @return [Stellar::Keypair] Stellar::Keypair instance. def produce(subject) case subject when String from_string(subject) when Stellar::Account subject.keypair when Stellar::PublicKey from_public_key(subject) when Stellar::SignerKey from_secret_key(subject) when Stellar::KeyPair subject else raise Mobius::Client::Error::UnknownKeyPairType, "Unknown KeyPair type: #{subject.class.name}" end rescue ArgumentError => e raise Mobius::Client::Error::UnknownKeyPairType, "Unknown KeyPair type: #{e.message}" end # rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity private def from_string(subject) subject[0] == "S" ? Stellar::KeyPair.from_seed(subject) : Stellar::KeyPair.from_address(subject) end def from_public_key(subject) Stellar::KeyPair.from_public_key(subject.value) end def from_secret_key(subject) Stellar::KeyPair.from_raw_seed(subject.value) end end end
true
ee328b22847428f0269196bcac2c1c83ca50ba5f
Ruby
briecoyle/sinatra-cool-store-2
/app/models/cart.rb
UTF-8
155
2.578125
3
[]
no_license
class Cart < ActiveRecord::Base belongs_to :user has_many :items def total self.items.inject(0) { |total, item| total += item.price } end end
true
32c9538108c55ed90b451ba489bd53bc9a8782ca
Ruby
leehopper/black_thursday
/spec/invoice_repository_spec.rb
UTF-8
3,854
2.53125
3
[]
no_license
require_relative 'spec_helper' require_relative '../lib/invoice_repository' RSpec.describe InvoiceRepository do before :each do @repo = InvoiceRepository.new('./spec/fixtures/mock_invoices.csv') end it 'exists' do expect(@repo).to be_an_instance_of(InvoiceRepository) end it 'can create invoice instances' do @repo.all.each do |invoice| expect(invoice).to be_an_instance_of(Invoice) end end it 'can find an invoice by id' do expect(@repo.find_by_id(1).merchant_id).to eq(11111) expect(@repo.find_by_id(200)).to eq(nil) expect(@repo.find_by_id(3).merchant_id).to eq(33333) end it 'can find all invoices by customer id' do merchant_id = [] @repo.find_all_by_customer_id(7).each do |invoice| merchant_id << invoice.merchant_id end expect(merchant_id).to eq([12334861, 12334208, 12335417, 12336821]) expect(@repo.find_all_by_customer_id(200)).to eq([]) end it 'can find all invoices by merchant id' do invoice_id = [] @repo.find_all_by_merchant_id(77777).each do |invoice| invoice_id << invoice.id end expect(invoice_id).to eq([7]) expect(@repo.find_all_by_merchant_id(200)).to eq([]) end it 'find_all_by_ids_by_merchant_id' do expect(@repo.find_all_by_ids_by_merchant_id(77777)).to eq([7]) expect(@repo.find_all_by_ids_by_merchant_id(200)).to eq([]) end it 'can find all invoices by status' do invoice_id = [] @repo.find_all_by_status(:returned).each do |invoice| invoice_id << invoice.id end expect(invoice_id).to eq([25, 37, 49]) expect(@repo.find_all_by_status(:sent)).to eq([]) end it 'creates the next highest invoice id' do expect(@repo.next_highest_id).to eq(51) end it 'can create a new invoice' do attributes = { :customer_id => 2, :merchant_id => 104, :status => "pending" } @repo.create(attributes) expect(@repo.all.length).to eq(51) expect(@repo.find_by_id(51).customer_id).to eq(2) expect(@repo.find_by_id(51).merchant_id).to eq(104) expect(@repo.find_by_id(51).status).to eq(:pending) end it 'can only update status and nothing else' do attributes_1 = {status: :shipped} @repo.update(1, attributes_1) expect(@repo.find_by_id(1).status).to eq(:shipped) attributes_2 = { id: 50, customer_id: 22, merchant_id: 200, created_at: Time.now } end it 'can delete the invoice by id' do @repo.delete(2) expect(@repo.all.length).to eq(49) expect(@repo.find_by_id(2)).to eq(nil) end it 'can match invoice id to merchant id' do expect(@repo.invoice_id_by_merchant_id[44444]).to eq([4]) end it 'can find id by date' do @repo.find_invoice_by_date(Time.parse('2009-02-07')).each do |invoice| expect(invoice.created_at).to eq(Time.parse('2009-02-07')) end end it 'shows invoices grouped by merchant' do invoice_count = [] @repo.group_invoices_by_merchant.each do |merchant, invoice| invoice_count << invoice.length end expect(invoice_count[0]).to eq(1) end it 'returns invoice count per merchants' do expect(@repo.invoices_per_merchant[5]).to eq(1) end it 'returns the number of merchants'do expect(@repo.number_of_merchants).to eq(48) end it 'returns total number of invoices' do expect(@repo.total_invoices).to eq(50) end it 'groups invoices by created date' do expect(@repo.group_invoices_by_created_date.length).to eq(7) end it 'returns array of invoice per day' do expect(@repo.invoices_per_day.length).to eq(7) end it 'returns invoice count per day created' do expect(@repo.invoices_by_created_date.keys.first.class).to eq(String) end it 'returns total invoice per status' do expect(@repo.invoice_status_total(:pending)).to eq(17) end end
true
924084ce9d98ae9f5b91fb96e86fd906d3ab7027
Ruby
FrancescaRodricks/fractions
/fraction_spec.rb
UTF-8
1,250
3.3125
3
[]
no_license
# Author : Francesca Rodricks # Date Created: 24/09/2017 # Date Modified: 26/09/2017 # Problem Statement: Adding fractions/rational numbers # Fraction Class Spec require 'rspec' require_relative "#{__dir__}/fraction" RSpec.describe Fraction, type: :class do # 1/2 3/4 5/6 7/8 # add fraction to an integer # add fraction to decimal # add two fractions let(:numerator) { 1 } let(:denominator) { 2 } subject do described_class.new({ numerator: numerator, denominator: denominator }) end describe '#initialize' do it 'creates an instance of numerator' do expect(subject.numerator).to eq(numerator) end it 'creates an instance of denominator' do expect(subject.denominator).to eq(denominator) end end describe '#addition' do let(:result_i_care) { Rational(3,4) } let(:rational_number) { Number.to_rational(1,4) } it 'adds two rational numbers' do expect(subject.addition(rational_number)).to eq(result_i_care) end context 'when denominator is 0' do let(:denominator) { 0 } let(:result_i_care) { Rational(5,4) } it 'set default denominator to 1' do expect(subject.addition(rational_number)).to eq(result_i_care) end end end end
true
18d9a73d11aeca6b9fd49c2743e53c915209a00f
Ruby
SathishAchilles/ParkingLot
/lib/parking_lot.rb
UTF-8
1,013
3.171875
3
[]
no_license
require_relative 'parking_slot' #Implements the parking lot class ParkingLot def initialize @slots = [] end def slots @slots end def slots=(no_of_slots) begin no_of_slots = no_of_slots.to_i raise ArgumentError unless no_of_slots.is_a?(Integer) (ParkingLayout::ENTRY_POINT...no_of_slots).each{|slot| @slots << ParkingSlot.new(slot+ParkingLayout::INCREASING_STEP) } rescue ArgumentError => e e.backtrace @slots = [] rescue Exception => e e.backtrace @slots = [] end end def available_slots @slots.select{|slot| slot.available } end def allocate_slot(vehicle) available_slots.sort_by(&:number).first.allocate(vehicle) rescue nil end def allocated_slots @slots.select{|slot| !slot.available } end def deallocate_slot(number) slot = allocated_slots.find{|slot| slot.number == number } return false unless slot slot.deallocate end def full? available_slots.empty? end end
true
2677ab865d59332296c71e1163a20af7fb252085
Ruby
psychedel/qwester
/lib/random_string.rb
UTF-8
544
3.140625
3
[ "MIT" ]
permissive
class RandomString < String def initialize(length = 40) super(new_random_string(length)) end private def new_random_string(length = 40) string = "" string += random_string until string.length >= length return string[0, length] end def random_string string_pairs = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ).scan(/.{2}/) random_strings = string_pairs.collect{|s| s[0,1].crypt(s)} random_string = random_strings.join return random_string.gsub(/[^A-Za-z0-9]/, "") end end
true
35a7cb412cac00d9e9c1ed1c9091702e00459884
Ruby
badal/jacman-selectors
/lib/jacman/selectors/table.rb
UTF-8
1,544
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env ruby # encoding: utf-8 # File: table.rb # Created: 11/12/2015 # # (c) Michel Demazure <michel@demazure.com> module JacintheManagement module Selectors # specific class for Qt widget class Table # @param [Array<String>] list answer from MySQL # @return [Table] new instance def self.from_sql(list) contents = list.map do |line| line.chomp.split("\t") end labels = contents.shift new(labels, contents) end attr_reader :labels, :rows # @param [Array<String>] labels label row # @param [Array<Array<String>>] rows list of rows def initialize(labels = [], rows = [[]]) @labels = labels @rows = rows end # @return [Integer] number of rows def row_count @rows.size end # @return [Integer] number of columns def column_count @labels.size end # @return [Array] list of tiers_id for routing def tiers_list return [] unless @labels.first == 'tiers_id' @rows.map(&:first) end # @param [String] csv_separator separator for csv files # @return [String] formatted output def output_content(csv_separator) ([@labels] + @rows).map do |line| line.join(csv_separator) end.join("\n") end # @param [Array<Array<String>>] rows new set of rows # @return [Table] new Table with same labels and given rows def fix_rows(rows) self.class.new(@labels, rows) end end end end
true
cc3fb78b8482619b0054a8bf13fcb83a9f8f663b
Ruby
JasonTavarez/ruby-puppy-nyc-web-091619
/lib/dog.rb
UTF-8
590
3.734375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Dog # attr_reader :name attr_accessor :name @@all = [] def initialize(name) @name = name save end def self.all @@all end def self.clear_all #clear array @@all of all Dog instances @@all.clear end def self.print_all #print each name of dog to the terminal @@all.each do |each_dog| puts each_dog.name end #p name is "Dog" end def save #@@all << # dog instance to array @@all << self end end #binding.pry
true
06a445103df7de9ec7dba1128de3b6c48a7dbac5
Ruby
franlocus/knight_travails.rb
/main.rb
UTF-8
463
4
4
[]
no_license
# frozen_string_literal: true require_relative 'knight' require_relative 'board' board = Board.new puts board.knight_moves([0,0],[3,3]) puts board.knight_moves([0,0],[1,2]) puts board.knight_moves([0,0],[7,7]) # You made it in 2 moves! Here's your path: # [0, 0] # [1, 2] # [3, 3] # You made it in 1 moves! Here's your path: # [0, 0] # [1, 2] # You made it in 6 moves! Here's your path: # [0, 0] # [1, 2] # [2, 4] # [3, 6] # [5, 7] # [6, 5] # [7, 7]
true
9a3641466c5551cffb1269728753e695dbb7ef75
Ruby
Hykios42/THP_Scrapping_d09
/lib/crypto_currencies.rb
UTF-8
442
2.984375
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' def crypto_scrapper page = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/")) currencies = [] page.xpath('//span//a').each do |crypto| currencies << crypto.text end values = [] page.xpath('//a[@class="price"]').each do |value| values << value.text end hash = currencies.zip(values).to_h end puts crypto_scrapper
true
a780286162f4c609cdc73f8901582852723856e6
Ruby
krlawrence/SVG
/generators/slope.rb
UTF-8
88
2.8125
3
[ "Apache-2.0" ]
permissive
45.step(89,1) do |a| puts "Angle=#{a} , Slope=#{Math.tan( a*Math::PI / 180 )}" end
true
3c7d9b15dc95280e58e628a4a06f9d5d59996e34
Ruby
usuyama/sam_simulator
/read.rb
UTF-8
961
3.125
3
[]
no_license
# -*- coding: utf-8 -*- class Read attr_accessor :seq, :base_qualities, :cigar, :pos, :chr def initialize(seq, quality, cigar, pos, chr) @seq = seq @base_qualities = quality @cigar = cigar @pos = pos @chr = chr end def inspect "#{@pos}, cigar: #{@cigar}\n#{@seq}\n#{@base_qualities}" end end class ReadPair attr_accessor :first, :second, :id def initialize(first, second) @first = first @second = second end def to_str pos = @first.pos pair_pos = @second.pos ins = pair_pos - pos + @second.seq.length out = "#{@id}\t99\t#{@first.chr}\t#{pos}\t60\t#{@first.cigar}\t=\t#{pair_pos}\t#{ins}\t#{@first.seq}\t#{@first.base_qualities}\n" out += "#{@id}\t147\t#{@second.chr}\t#{pair_pos}\t60\t#{@second.cigar}\t=\t#{pos}\t#{-ins}\t#{@second.seq}\t#{@second.base_qualities}" return out end def inspect out = @first.inspect + "\n" out += @second.inspect return out end end
true
4b575334d0bf723d273aa020047ce8ab7de5e8a4
Ruby
Deimos620/octopus
/app/models/blog_author.rb
UTF-8
759
2.609375
3
[]
no_license
class BlogAuthor < ActiveRecord::Base extend FriendlyId friendly_id :slug, use: :slugged has_many :blog_posts belongs_to :user before_save { self.first_name = first_name.capitalize if self.first_name? } before_save { self.last_name = last_name.capitalize if self.last_name?} validates :slug, uniqueness: {message: "Oops! You've already used this first name! Try adding a dash and a last name."} def name if self.first_name.present? first_name + " " + last_name rescue first_name + "" rescue "" + last_name rescue "BlogAuthor" else self.user.name end end before_save :set_slug, if: :new_record? def set_slug if self.slug.blank? self.slug = self.name.downcase end end end
true