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
31626807fa9ccc8b71c3b4013f569e411b4a618b
Ruby
mikekauffman/hash-warmup
/02_first_genre.rb
UTF-8
374
3.21875
3
[]
no_license
require_relative 'people' # What is the first genre that each person listed? puts PEOPLE [:favorite_genres] PEOPLE.each do |name, data| puts data[:preferences][:favorite_genres].first end #OR PEOPLE.each do |name, data| puts data[:preferences][:favorite_genres][0] end #OR PEOPLE.values.each do |data| puts data[:preferences][:favorite_genres][0] #or .first end
true
68087544986a521e6bc457fb94318058775b5ce7
Ruby
paulentine/VideoStoreAPI
/test/models/customer_test.rb
UTF-8
2,315
2.515625
3
[]
no_license
require "test_helper" describe Customer do before do @customer = customers(:customer_1) end describe "Validations" do it "must be valid with valid data" do @customer.must_be :valid? end it "will not be valid without name" do @customer.name = nil expect(@customer.valid?).must_equal false end it "will not be valid without registered_at" do @customer.registered_at = nil expect(@customer.valid?).must_equal false end it "will not be valid without postal_code" do @customer.postal_code = nil expect(@customer.valid?).must_equal false end it "will not be valid without phone" do @customer.phone = nil expect(@customer.valid?).must_equal false end it "will not be valid without movies_checked_out_count" do @customer.movies_checked_out_count = nil expect(@customer.valid?).must_equal false end end describe "relations" do before do @cust_with_no_rental = customers(:customer_2) end it "can have 0 rental" do expect(@cust_with_no_rental.rentals.count).must_equal 0 expect(@cust_with_no_rental.rentals).must_equal [] end it "can have 1 or more rentals" do expect(@customer.rentals.count).must_equal 2 expect(@customer.rentals.first).must_equal rentals(:rental_1) expect(@customer.rentals.last).must_equal rentals(:rental_2) new_rental = Rental.new() movie = movies(:movie_2) movie.rentals << new_rental @customer.rentals << new_rental @customer.reload expect(@customer.rentals.count).must_equal 3 expect(@customer.rentals.last).must_equal new_rental end it "can have 0 movie through rentals" do expect(@cust_with_no_rental.movies.count).must_equal 0 expect(@cust_with_no_rental.movies).must_equal [] end it "can have 1 or more movie through rentals" do expect(@customer.movies.count).must_equal 2 expect(@customer.movies.first).must_equal movies(:movie_2) expect(@customer.movies.last).must_equal movies(:movie_1) new_movie = movies(:movie_3) @customer.movies << new_movie @customer.reload expect(@customer.movies.count).must_equal 3 expect(@customer.movies.last).must_equal new_movie end end end
true
0334232ecc12ddb1120f7ae8183ca6000adfb6fe
Ruby
upstill/RecipePower-source
/lib/time_check.rb
UTF-8
193
2.734375
3
[]
no_license
def time_check_log(label) tstart = Time.now result = yield tstop = Time.now rpt = "TIMECHECK #{label}: "+(tstop-tstart).to_s+" sec." logger.debug rpt result end
true
d5264aa99cecc5b619dbd8f64b2b6682135d763c
Ruby
NYDrewReynolds/my_enigma
/test/offset_test.rb
UTF-8
841
2.65625
3
[]
no_license
require 'minitest/autorun' require 'minitest' require 'minitest/pride' require './lib/offset.rb' class OffsetTest < Minitest::Test def setup key = Key.new("41521") date = Date.new("020315") @offset = Offset.new(key, date) end def test_it_exists assert Offset end def test_it_combines_a_values assert_equal 50, @offset.a end def test_it_can_be_wrong_a refute_equal 40, @offset.a end def test_it_combines_b_values assert_equal 17, @offset.b end def test_it_can_be_wrong_b refute_equal 0, @offset.b end def test_it_combines_c_values assert_equal 54, @offset.c end def test_it_can_be_wrong_c refute_equal 49, @offset.c end def test_it_combines_d_values assert_equal 26, @offset.d end def test_it_can_be_wrong_d refute_equal 62, @offset.d end end
true
a3ef0a09f63b220cc0bd5a1a36fccb0ef6684071
Ruby
hack3rvaillant/convert_svg_string_to_gcode_gem
/lib/convert_svg_string_to_gcode/helpers/create_gcode_array_from_svg_commands.rb
UTF-8
1,881
3.1875
3
[]
no_license
require 'convert_svg_string_to_gcode/constants/plotter_config' class CreateGCodeArrayFromSVGCommands def self.perform(commands, options = {step: 0.20}) start_point = nil step=options[:step] gcode_array = commands.map do |c| case c.type when ConversionConstants::MOVE move_to_point(c) when ConversionConstants::LINE_TO draw_to_point(c) when ConversionConstants::CURVE create_gcode_path_from_bezier(c, step) else throw Error end end end def self.move_to_point(new_point) x_value = new_point.p1x y_value = new_point.p1y command = ["G0 X#{x_value} Y#{y_value} #{PlotterConfig::Z_UP}"] return command end def self.draw_to_point(new_point) x_value = new_point.p1x y_value = new_point.p1y command = ["G1 X#{x_value} Y#{y_value} #{PlotterConfig::Z_DOWN}"] return command end def self.create_gcode_path_from_bezier(svg_command, step) p0x = svg_command.p0x p0y = svg_command.p0y cp0x = svg_command.cp0x cp0y = svg_command.cp0y cp1x = svg_command.cp1x cp1y = svg_command.cp1y p1x = svg_command.p1x p1y = svg_command.p1y t = step gcode_array = [] while t<1 do ax = ( (1 - t) * p0x ) + (t * cp0x) ay = ( (1 - t) * p0y ) + (t * cp0y) bx = ( (1 - t) * cp0x ) + (t * cp1x) by = ( (1 - t) * cp0y ) + (t * cp1y) cx = ( (1 - t) * cp1x ) + (t * p1x) cy = ( (1 - t) * cp1y ) + (t * p1y) dx = ( (1 - t) * ax ) + (t * bx) dy = ( (1 - t) * ay ) + (t * by) ex = ( (1 - t) * bx ) + (t * cx) ey = ( (1 - t) * by ) + (t * cy) new_point_x = ( (1 - t) * dx ) + (t * ex) new_point_y = ( (1 - t) * dy ) + (t * ey) gcode_array << "G1 X#{new_point_x} Y#{new_point_y} #{PlotterConfig::Z_DOWN}" t+=step end return gcode_array end end
true
b46e0db34ad6e5f5d792a680ccf195d0f765f9e7
Ruby
scoiatael/parrhasius
/lib/parrhasius/downloaders/fourchan.rb
UTF-8
927
2.703125
3
[]
no_license
# frozen_string_literal: true require 'down' require 'nokogiri' require 'securerandom' module Parrhasius module Downloaders class FourChan # rubocop:todo Style/Documentation include Enumerable def download(link) img_link = link.attributes['href'] return unless img_link [SecureRandom.uuid + ext(img_link.value), Down.download("https:#{img_link.value}").read] end def enumerate_link(link) html = Nokogiri(Down.download(link).read) html.search('a').select { |l| l.children.size == 1 && l.children.first.to_s.match(/.*(jpg|png)$/) } end def initialize(main_page) @main_page = main_page @links = enumerate_link(@main_page) end def ext(link) ".#{link.split('.').last}" end def each(&block) @links.each(&block) end def total @links.size end end end end
true
ed7330d4e49edd5a9da7f625d3365939e9786ba7
Ruby
rafiamafia/dotfiles
/bin/inspect
UTF-8
1,402
3.140625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby class Inspector attr_accessor :argv, :stdin, :stdout def initialize(argv, stdin, stdout) self.argv = argv self.stdin = stdin self.stdout = stdout end def call if argv.any? then inspect_files argv else inspect_stream stdin end end private def inspect_files(filenames) filenames.each do |filename| File.open(filename) { |file| inspect_stream file } end end def inspect_stream(stream) stream.each_line { |line| stdout.puts line.inspect } end end if $0 !~ /rspec/ Inspector.new(ARGV, $stdin, $stdout).call else require 'stringio' describe 'inspect_stream' do def inspect(argv, stdin) stdout = StringIO.new Inspector.new(argv, stdin, stdout).call stdout.string end context 'when given no args' do it 'inspects each line from stdin, and prints it to the output' do inspect([], StringIO.new("a\tb\nc")).should == %("a\\tb\\n"\n"c"\n) end end context 'when given args' do it "treats each argument like a filename, inspecting that file's lines and printing to output" do begin File.write 'testa', 'a' File.write 'testb', 'b' inspect(%w[testa testb], StringIO.new('not seen')).should == %("a"\n"b"\n) ensure File.delete 'testa', 'testb' end end end end end
true
8887991ea79b529a7ea788444f350610928cb049
Ruby
zlhhhhhhh/hw-ruby-intro
/lib/ruby_intro.rb
UTF-8
1,599
3.96875
4
[]
no_license
# When done, submit this entire file to the autograder. # Part 1 def sum arr # YOUR CODE HERE sum = 0; for i in arr sum += i end return sum end def max_2_sum arr # YOUR CODE HERE max_sum = 0; max1 = -Float::INFINITY; max2 = -Float::INFINITY; for i in arr if i >= max1 max2 = max1 max1 = i elsif i<max1 and i >= max2 max2 = i end end if max1 == -Float::INFINITY and max2 ==-Float::INFINITY return max_sum elsif max2 == -Float::INFINITY return max1 else max_sum = max1 + max2 return max_sum end end def sum_to_n? arr, n # YOUR CODE HERE hashmap = Hash.new() for i in arr if hashmap.has_key?(n-i) return true else hashmap[i]= 1 end end return false end # Part 2 def hello(name) return "Hello, "+name; end def starts_with_consonant? s # YOUR CODE HERE if /\A(?=[^aeiou])(?=[a-z])/i.match(s) return true end return false end def binary_multiple_of_4? s # YOUR CODE HERE if /^[0-1]+$/.match(s) if /00\Z/.match(s) or s=="0" return true else return false end else return false end end # Part 3 class BookInStock def initialize(isbn,price) if isbn=="" or price <= 0 raise ArgumentError end @isbn = isbn @price = price end # getter def price @price end def isbn @isbn end # setter def price=(price) @price = price end def isbn=(isbn) @isbn = isbn end # price_as_string func def price_as_string return "$" + format("%.2f",@price) end end
true
0934365315793173926e851a9491842f6a95b9c2
Ruby
henix/shielddns
/regexptrie.rb
UTF-8
1,480
3.421875
3
[]
no_license
require 'stringio' class RegexpTrie # @param strs: Array[String] # @param out: IO def self.build(strs, out = nil) if out build_depth(strs, 0, out) else out = StringIO.new build_depth(strs, 0, out) out.string end end private def self.build_depth(strs, depth, out) size = strs.size if size == 0 return elsif size == 1 t = strs.first if depth < t.length out.write(Regexp.quote(t[depth..-1])) end return end strs.sort_by! { |s| s[depth] or "" } i = strs.find_index { |s| s.length > depth } if i == nil return # not found, exit end has_empty = i > 0 all_same = strs[i][depth] == strs.last[depth] if not all_same or has_empty out.write("(?:") end if all_same out.write(Regexp.quote(strs[i][depth])) build_depth((i > 0 and strs[i...size] or strs), depth + 1, out) else # use [depth] to split strs into sections first = true while i < size start = i ch = strs[i][depth] while i < size and strs[i][depth] == ch i = i + 1 end e = i if first first = false else out.write("|") end out.write(Regexp.quote(ch)) build_depth(strs[start...e], depth + 1, out) end end if not all_same or has_empty out.write(")") end if has_empty out.write("?") end end end
true
1acf155a6b6fb93fb9deb35571a75855b671e7db
Ruby
FayeKeegan/checkers
/empty_square.rb
UTF-8
123
2.6875
3
[]
no_license
class EmptySquare def initialize end def to_s " " end def empty? true end def checker? false end end
true
a6e6bf9d0819d5c924ca63e5be54cfee7c15ad5f
Ruby
Stanis1av/Ruby
/Ruby/Двоичные числа/1.0.0 app.rb
UTF-8
1,082
3.546875
4
[ "MIT" ]
permissive
# def convert_to_binary(n) # ch = n / 2 # ost = n % 2 # result = [] # result << ost # loop do |v| # ost = ch % 2 # ch = ch / 2 # result << ost # break if ch == 0 # end # answer = result.reverse.join.to_i # puts answer # end # convert_to_binary(6) def convert_to_binary(integer) binary = [] while integer > 0 binary << integer % 2 integer /= 2 end binary.reverse.join end # p convert_to_binary(6) def convert_to_binary_recursive(integer) if integer <= 1 integer.to_s else convert_to_binary_recursive(integer / 2) + (integer % 2).to_s end end # p convert_to_binary_recursive(6) n = 2**20 %i(convert_to_binary convert_to_binary_recursive).each do |method| failed = [] t1 = Time.now (0..n).each do |i| binary = self.send(method, i) correct = (binary == i.to_s(2)) failed << i if !correct end t2 = Time.now puts "\n#{method}" puts " - CORRECT: #{failed.empty?}" puts " - FAILED: #{failed}" if failed.any? puts " - #{t2-t1}sec" end
true
a9a4f9059cab40023b4020eab3e906f4cc8987b8
Ruby
fairpay-coop/fairpay-server
/app/models/binbase.rb
UTF-8
1,682
2.671875
3
[]
no_license
class Binbase < ActiveRecord::Base # create_table :binbases do |t| # t.string :bin, index: true # t.string :card_brand # t.string :card_type # t.string :card_category # t.string :country_iso # t.string :org_website # t.string :org_phone # t.references :binbase_org # t.timestamps null: false belongs_to :binbase_org def is_regulated binbase_org.present? && binbase_org.is_regulated end def issuing_org binbase_org&.name end # ask joseph for copy of latest import data file # DEFAULT_DATA_FILE = '../binbase/bins_iso_9_5.csv' DEFAULT_DATA_FILE = 'db/bins.csv' DEFAULT_BIGBANKS_FILE = 'db/bigbanks.txt' def self.purge_imported Binbase.delete_all BinbaseOrg.delete_all end def self.import_data(data_file: DEFAULT_DATA_FILE, bigbanks_file: DEFAULT_BIGBANKS_FILE) big_banks = CSV.readlines(bigbanks_file, col_sep: '|').flatten CSV.foreach(data_file, col_sep: ';') do |row| data = row_to_hash(row) org_name = data.delete(:issuing_org) org = BinbaseOrg.find_by(name: org_name) if org_name && ! org is_regulated = big_banks.include?(org_name) org_data = {name: org_name, country_iso: data[:country_iso], website: data[:org_website], phone: data[:org_phone], is_regulated: is_regulated} puts "new org data: #{org_data}" org = BinbaseOrg.create!(org_data) end data[:binbase_org_id] = org.id if org Binbase.create!(data) end end def self.row_to_hash(r) {bin: r[0], card_brand: r[1], issuing_org: r[2], card_type: r[3], card_category: r[4], country_iso: r[6], org_website: r[9], org_phone: r[10]} end end
true
22b7651d770574fb0f2f406753afcdd070ee90a7
Ruby
ericburleson/LearntoProgram
/LearnToProgram11.rb
UTF-8
3,578
3.109375
3
[]
no_license
#LearnToProgram11.rb #The filename doesn't have to end with ".txt" but since it is valid, why not? filename = 'ListerQuote.txt' test_string = 'I promise that I swear absolutely that' + 'I will never mention gazpacho soup again.' #The 'w' here is for write-access to the file #since we are trying to write to it. File.open filename, 'w' do |f| f.write test_string end read_string = File.read filename puts(read_string == test_string) puts '------' require 'yaml' test_array = ['Give Quiche a Chance', 'Mutants Out!', 'Chameleon Life Forms, No thanks!'] #Here's half the magic test_string = test_array.to_yaml #You see? Kind of like to_s, and in fact it is a string, #but it's a yaml description of test_array filename = 'RimmerTShirts.txt' File.open filename, 'w' do |f| f.write test_string end read_string = File.read filename #And the other half of the magic: read_array = YAML::load read_string puts(read_string == test_string) puts(read_array == test_array ) puts '------' buffy_quote_1 = '\'Kiss rocks\'? Why would anyone want to kiss... Oh, wait, I get it.' buffy_quote_2 = "'Kiss rocks'?\n" + "Why would anyone want to kiss...\n" + "Oh, wait, I get it." puts buffy_quote_1 puts puts(buffy_quote_1 == buffy_quote_2) puts("3...\n2...\n1...\nHAPPY NEW YEAR!") puts('single (\') and double (") quotes') puts("single (') and double (\") quotes") name = 'Luke' zip = 90210 puts "Name = #{name}, Zipcode = #{zip}" puts "#{20 * 10**4 + 1} Leagues Under the Sea, THE REVENGE!" puts '------' #First we define those fancy methods... def yaml_save object, filename File.open filename, 'w' do |f| f.write(object.to_yaml) end end def yaml_load filename yaml_string = File.read filename YAML::load yaml_string end #And now we use these fancy methods test_array = ['Slick Shoes', 'Bully Blinders', 'Pinchers of Peril'] filename = 'DatasGadgets.txt' #We save it yaml_save(test_array, filename) #we load it read_array = yaml_load(filename) puts(read_array == test_array) puts '------' # For Katy, with love #This is where she stores all her pictures before she gets her YAML on and moves them to the server. #Just for my own convenience, I'll go there now #Skipped Katy, since it references files on her computer. #moving to new_shuffle def shuffle sorted_array rec_shuffle(sorted_array, []) end def rec_shuffle sorted_array, shuffled_array if sorted_array.length <= 0 return shuffled_array end shuffled_array = [] unshuffled_array = [] random_element = sorted_array[rand(sorted_array.length)] #repeat process until the array is empty. sorted_array.each_with_index do |test_object, i| if i % 2 == 0 shuffled_array.push(test_object) #Add the element to a new array. else unshuffled_array.push(test_object) #Add the element back in the mix. end end shuffled_array + rec_shuffle(unshuffled_array, shuffled_array) end playlist = ['music/Jazz/Monk--Nutty/track08.ogg', 'music/Jazz/Monk--London_Collection_1/track05.ogg', 'music/Jazz/Monk--Nutty/track13.ogg', 'music/Jazz/Monk--Round_Midnight/track02.ogg', 'music/Jazz/Monk--Round_Midnight/track14.ogg', 'music/Jazz/Monk--Round_Midnight/track15.ogg', 'music/Jazz/Monk--Round_Midnight/track08.ogg', 'music/Rock/FNM--Who_Cares_A_Lot_2/track02.ogg', 'music/Rock/FNM--Who_Cares_A_Lot_2/track08.ogg', 'music/Rock/FNM--Who_Cares_A_Lot_1/track02.ogg', 'music/Rock/FNM--Who_Cares_A_Lot_2/track01.ogg'] puts shuffle(playlist)
true
1211a9afa27718d479ed5f02a5da78ab5569f5c0
Ruby
thilo/coworking-framework
/db/seeds.rb
UTF-8
5,231
2.65625
3
[]
no_license
# encoding: utf-8 # 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) questionaire = { "Accessibility" => ["Is your space open for more than 10 hours per week?", "Is your space open for coworking at the weekends?", "Is your space open to anyone?", "Do your coworkers have their own keys?", "Is it open to people with all professional backgrounds?", "Is the space located in close proximity to its members?", "Is the space open at night (after 9pm)?", "Is there an hourly or half-day rate?", "Is there a daily rate?", "Is there public transport nearby?" ], "Pooling of Resources" => [ "Are (the majority) of the workspaces shared?", "Does the space have at least one communal area?", "Is there a printer, photocopier and scanner at the coworkers’ disposal?", "Is there a secretary, accountant, or technical assistance made available for coworkers?", "Does the space provide a virtual address/postage service or storage service (for materials or digital data)?", "Does the space provide a shared land-line?", "Is the space fitted with a communal workshop (fablab)?", "Does the space provide access to shared production tools (3D printers, sewing machines, musical instruments, photographic equipment, audiovisual production equipment)?", "Does the space have at least one of the following areas: shared shop front, childcare facilities, recording studio or darkroom?", "Is there an event space and relevant amenities, including projectors, whiteboards, etc?" ], "Shared Energies" => [ "Is the space open to everyone?", "Does the space regularly host events that are open to non-members (more than once per week)?", "Do the coworkers have access to an internal social network/intranet?", "Do the space managers organize events designed to introduce coworkers to one another on a regular basis?", "Does the space host member events on a regular basis (more than once per week)?", "Is there a monthly (or less) membership plan?", "On average, does the space host more than 30 coworkers each day?", "Amongst the staff, is there a person whose specific job is to connect members and put them in contact with one another?", "Does the space offer workshops or courses to its members?", "Does the space frequently communicate its members’ projects’ via its own communication channels (at least once per week)?" ], "Proximity" => [ "Is there a dedicated for convivial exchange in the space (café, communal kitchen...)?", "Do coworkers mainly work on flexible or ‘hot-desks’ (rather than fixed workstations)?", "Is the spaces limited to teams of three members or less?", "In the space, do the majority of coworkers share the same open space?", "Do coworkers often eat meals together?", "Does your space hold less than 30 people at a time?", "Does the space have games (fussball or table-tennis table, board games, games console)?", "Within the space, do you often help or attend spontaneous events between coworkers: after-work drinks, games, joint projects... (at least once per week)?", "Do most of the coworkers in your space know the names of at least half of the other coworkers in the community?", "Do you organize members-only events at least twice per month?" ], "Permission" => [ "Are the coworkers involved in the overall governance of the space?", "If the space is an association, are the coworkers members of that association or organization?", "Can members eat and/or drink in the work areas?", "Does the space have an interactive members’ wall?", "Can members prepare meals in the space during the day?", "Do members initiate events?", "Did the coworkers help in arranging the space?", "Is there an internal social network/intranet?", "Are there often social or non-work related gatherings organized in your space?", "Is the space adaptable and flexible (tables moved often, furniture often rearranged...)?" ], "Privacy" => [ "Does the space have a separate meeting room?", "Does the space have several isolated rooms and/or a telephone booth?", "Does the space have silent or quiet areas?", "Does the space have an interactive members’ wall?", "Is minimal membership engagement more than one month?", "Do you have a backup service for coworkers’ digital data?", "Are the majority of workstations private?", "Does the space have lockers or lockable storage areas?", "Is the space under video surveillance?", "Is there an area for repose or rest?", ] } Section.delete_all questionaire.each do |section, questions| new_section = Section.create! name: section questions.map{|question| new_section.questions << Question.new(content: question)} end
true
58b87a0dbd38379baa73fdef53bce44b9c73c032
Ruby
nicky-isaacs/mapquestsearch
/lib/mapquestsearch.rb
UTF-8
1,713
2.84375
3
[ "MIT" ]
permissive
require 'mapquestsearch/version' require 'rest_client' require 'json' require 'rexml/document' class MapQuestSearch CITY = 'city' LAT_LONG = 'lat_long' ALLOWED_FORMATS = [:json, :xml, :html] RETRY_COUNT = 5 @@_default_format = nil #---------------------------- def self.default_format @@_default_format || :json end def self.default_format=(format) raise "Invalid format #{format.to_s}" unless ALLOWED_FORMATS.include?(format) @@_default_format = format end def self.raw(search, format=nil, options={}) format ||= MapQuestSearch.default_format mapquest_exec_search search, format, options end def city_lat_long(term, format, options={}) result = mapquest_exec_search search, format, options result.detect{ |hash| hash[0] == CITY }[lat_long].split(',').map{ |l| l.to_f } end private def self.mapquest_endpoint "http://open.mapquestapi.com/nominatim/v1/search.php" end def self.validate_format(format) raise "Invalid format type: #{format.class.to_s}:#{format.to_s}" unless format.is_a? Symbol raise "Invalid format option: #{format}" unless ALLOWED_FORMATS.include?(format) true end def self.mapquest_exec_search(search, format, options={}) validate_format format options[:format] = format.to_s options[:q] = search begin result = RestClient.get MapQuestSearch.mapquest_endpoint, { params: options } rescue try_count ||= 0 try_count += 1 try_count > RETRY_COUNT ? (return nil) : retry end case format when :json return JSON.parse(result.to_str) when :xml return REXML::Document.new result.to_str else result.to_str end end end
true
8a359e83e2c7bba641735b9a54a8060438f16f51
Ruby
TatsuyaIsamu/Arrays
/test5.rb
UTF-8
768
3.84375
4
[]
no_license
4.8.5 ブロックローカル変数 numbers = [1, 2, 3, 4] sum = 0 numbers.each do |n; sum| sum = 10 sum += n p sum end sum # ブロック外なので sum = 0 になる 4.8.6 繰り返し処理以外でも使用されるブロック sample.rb 参照 4.8.7 do..end と {} の結合度の違い a = [1, 2, 3] a.delete(10) do "NG" end a.delete 10 do "NG" end a.delete 10 { "NG" } # エラー発生 a.delete (10) { "NG" } # {} は前後との結合度が強いので前後の引数を () で区別する必要がある 4.8.8 ブロックを使うメソッドを定義する names = ["田中", "鈴木", "佐藤"] names.map{|name| "#{name}さん"}.join("と") # チェーンメソッド
true
873e050ff93467ea925308d0b0755f5f4bcd7d25
Ruby
cjmurphy93/aA-classwork
/w01/w1d1/references_exercise/destination_city.rb
UTF-8
770
3.453125
3
[]
no_license
def dest_city(paths) # new_path = paths.flatten # new_path.each_with_index do |city, i| # (0...paths.length - 1).each do |j| # if paths[j][0] == city # new_path[i] = "" # end # end # end # new_path.each do |city| # if city != "" # return city # end # end new_path = paths.flatten cityhash = Hash.new(0) new_path.each do |city| cityhash[city] += 1 end cityhash.each do |k, v| if v == 1 paths.each do |sub| if sub[-1] == k return k end end end end end p dest_city([["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]])
true
e03f97901874221520730fda2c40bff2e21b1425
Ruby
jinnujohnson/Exercism_Problems
/ruby/series/series.rb
UTF-8
409
3.765625
4
[]
no_license
class Series def initialize(string) @string = int_conversion(string) end def int_conversion(s) s.chars.to_a.map(&:to_i) end def slices(count) slice = [] if count > @string.length fail ArgumentError.new('Unable To Slice') end i = -1 begin i += 1 j = i + count - 1 slice << @string[i..j] end while j < @string.length - 1 slice end end
true
bd1f3da98e73ae0d3e50971d0bfc7d05c2d8bb0b
Ruby
libdx/twee
/model.rb
UTF-8
1,480
2.84375
3
[]
no_license
#!/usr/bin/env ruby require 'singleton' require 'yaml' module Twee UserConfigDirName = ".twee" UserConfigMainFileName = "config.yml" class Config include Singleton attr_accessor :write_password alias_method :write_password?, :write_password def self.load Config.instance end def initialize super load_system_config load_user_config end def user @users[0] end def users @users end def config_path File.expand_path("~/#{UserConfigDirName}/#{UserConfigMainFileName}") end def load_system_config end def load_user_config path = config_path if File.exist?(path) config = YAML.load_file(path) @users = config[:users] write_password = config[:write_password] else # populate dummy user user = User.new user.username = "elkness" user.password = "*******" @users = [user] end end def write_system_config end def write_user_config path = config_path config = {:users => @users, :write_password => write_password?} File.open(path, 'w') { |out| YAML.dump(config, out) } end end class Store include Singleton def user Config.instance.user end def users Config.instance.users end end class User attr_accessor :username attr_accessor :password attr_accessor :token attr_accessor :messages def initialize yield self if block_given? end end class Message attr_accessor :text def belongs_to_user?(user) end end end
true
8c24a0b45894dd99f14be21691ab01afd45e0a2a
Ruby
startling/sullivan
/spec/sullivan_spec.rb
UTF-8
1,120
2.890625
3
[ "MIT" ]
permissive
require 'sullivan' describe Sullivan do describe ".validation" do it "provides a convenient way to access the built-in validations" do v = Sullivan.validation do hash( string_matching: string_matching(/\Al(ol)+\z/, error: "must be be a laugh"), kind_of: kind_of(Numeric) ) end error = v.validate({}) expect(error[:string_matching]).to eq("must be be a laugh") expect(error[:kind_of]).to eq("must be a kind of Numeric") end it "uses a non-instance-eval version when the block has an arity of 1" do v = Sullivan.validation do |vals| expect(a_method_on_self).to eq("can be called without an error") vals.hash( string_matching: vals.string_matching(/\Al(ol)+\z/, error: "must be be a laugh"), kind_of: vals.kind_of(Numeric) ) end error = v.validate({}) expect(error[:string_matching]).to eq("must be be a laugh") expect(error[:kind_of]).to eq("must be a kind of Numeric") end def a_method_on_self "can be called without an error" end end end
true
87193aae1af9156f5b317a7fd26193403005adac
Ruby
mikoyan/name_checker
/lib/name_checker/twitter_checker.rb
UTF-8
2,153
2.8125
3
[ "MIT" ]
permissive
# NOTE: This is rate limited to 150 requests per hour. # TODO: Add OAuth or some other authentication in order # to get my request limit rate increased. module NameChecker class TwitterChecker include HTTParty include Logging MAX_NAME_LENGTH = 16 base_uri "http://api.twitter.com" @service_name = :twitter def self.check(screen_name, options = {}) # Just return false if the suggestion exceeds the max allowed SN length. if screen_name.length > MAX_NAME_LENGTH return Availability.new(@service_name, false) end # Carry on with the availability checking. options.merge!( query: { screen_name: screen_name } ) res = get("/1/users/show.json", options) status = handle_response(res, screen_name) Availability.new(@service_name, status) end def self.warning_limit 20 end private def self.handle_response(res, screen_name) log_rate_limit(res.headers["x-ratelimit-remaining"]) # Twitter response codes: # INFO: https://dev.twitter.com/docs/error-codes-responses # 403 = Forbidden. Can be for a couple of reasons. case res.code when 200 then false when 403 then parse_403(screen_name, res) # Name is available if the request is not found when 404 then true else log_warning(screen_name, res) end end def self.log_warning(name, res) warning = "#{@service_name.upcase}_FAILURE: Handling #{name}. Response: #{res}" Logging.logger.warn(warning) # Nil return must be explicit because the logging will return true. return nil end def self.log_rate_limit(remaining) return nil if remaining.to_i > warning_limit warning = "RATELIMIT_WARNING: Service #{@service_name}. Remaining requests: #{remaining}" Logging.logger.warn(warning) # Nil return must be explicit because the logging will return true. return nil end def self.parse_403(name, res) return false if res["error"] =~ /suspended/ # Something we hadn't intended happened if we reach this point log_warning(name, res) end end end
true
b2bcdc730a352b36ab495d46c669955a1bdf3b17
Ruby
mwagner19446/wdi_work
/w02/d02/Marco/morning_exercises.rb
UTF-8
1,297
3.828125
4
[]
no_license
class Person def initialize(name) @name = name end def self.learn puts "I'm a class method" puts self end def learn puts "I'm an instance method" puts self end def hello self.learn end def hello_again learn end end pj = Person.new("PJ") #=>=> #<Person:0x007ff03a0ece00 @name="PJ"> pj.learn #=>I'm an instance method #<Person:0x007ff03a0ece00> #=> nil pj.hello #I'm an instance method #<Person:0x007ff03a0ece00> #=> nil pj.hello_again #I'm an instance method #<Person:0x007ff03a0ece00> #=> nil Person.learn #I'm a class method #Person #=> nil #Person.hello #NoMethodError: undefined method `hello' for Person:Class #from (pry):113:in `__pry__' # Person.hello_again #NoMethodError: undefined method `hello_again' for Person:Class #from (pry):114:in `__pry__' randimals = ["porpoise", "camel", "lobster", "kangaroo", "wombat", "chameleon"] plural_animals = randimals.map {|animal| animal + "s"} puts "#{plural_animals}" puts "#{randimals.sort}" puts "#{randimals.sort.reverse}" backward_animals = randimals.map {|animal| animal.reverse} puts "#{backward_animals}" long_named_animals = randimals.sort_by do |animal| x = animal.length end puts "#{long_named_animals}" odd_alhpa_animals = randimals.sort_by {|animal| animal[-1]} puts "#{odd_alhpa_animals}"
true
0f6d9d006226b3c77e3b9bd348c55cd465fe79b4
Ruby
andrewdavidburt/epicodus_squish_underflow
/app/models/question.rb
UTF-8
997
2.65625
3
[]
no_license
class Question < ActiveRecord::Base has_many :answers belongs_to :user validates :title, :presence => true validates :description, :presence => true # def average_rating # if (self.reviews.size > 0) # sum = 0 # self.reviews.each do |review| # sum += review.rating # end # result = (sum/self.reviews.size) # else # result = 0 # end # return result # end # scope :sorted_by, lambda { |sort_option| # # extract the sort direction from the param value. # direction = (sort_option =~ /desc$/) ? 'desc' : 'asc' # case sort_option.to_s # when /^year_/ # order("this.year #{ direction }") # when /^name_/ # order("this.name #{ direction }") # when /^rating/ # order("this.average_rating #{ direction }") # else # raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }") # end # } # # ->(sort_type) { order('updated_at')} # # order('updated_at ') end
true
7ac49658abdf10a0771e790409ba125ea9165a67
Ruby
BRIMIL01/readruby
/spec/readruby/invocation_spec.rb
UTF-8
7,690
2.953125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
describe ReadRuby::Invocation, ".new" do it "requires a Class as the first argument" do lambda do ReadRuby::Invocation.new(String, :[], 'text') end.should_not raise_error lambda do ReadRuby::Invocation.new('string', :[], 'text') end.should raise_error(ArgumentError) end it "requires a Symbol as the second argument" do lambda do ReadRuby::Invocation.new(Array, :size, 'text') end.should_not raise_error lambda do ReadRuby::Invocation.new(File, [], 'text') end.should raise_error(ArgumentError) end it "raises a NoMethodError if the given object doesn't have the given method" do lambda do ReadRuby::Invocation.new(File, :glark, 'text') end.should raise_error(NoMethodError) end it "doesn't raise a NoMethodError if the given object has the given instance method" do lambda do ReadRuby::Invocation.new(File, :path, 'text') end.should_not raise_error(NoMethodError) end it "doesn't raise a NoMethodError if the given object has the given class method" do lambda do ReadRuby::Invocation.new(File, :open, 'text') end.should_not raise_error(NoMethodError) end it "requires a String for the final argument" do lambda do ReadRuby::Invocation.new(File, :size, 'text') end.should_not raise_error lambda do ReadRuby::Invocation.new(File, :open, :size) end.should raise_error(ArgumentError) end it "returns an instance of ReadRuby::Invocation" do ReadRuby::Invocation.new(Array, :size, 'foo').should be_an_instance_of(ReadRuby::Invocation) end end describe ReadRuby::Invocation, "#object" do it "returns a Class" do ReadRuby::Invocation.new(Array, :first, 'text').object.should be_an_instance_of(Class) end it "returns the first argument passed to the constructor" do ReadRuby::Invocation.new(Array, :first, 'text').object.should == Array end end describe ReadRuby::Invocation, "#method" do it "returns a Symbol" do ReadRuby::Invocation.new(Array, :first, 'text').method.should be_an_instance_of(Symbol) end it "returns the second argument passed to the constructor" do ReadRuby::Invocation.new(Array, :first, 'text').method.should == :first end end # TODO it_behaves_like describe ReadRuby::Invocation, "#signature" do it "returns a Signature object" do ReadRuby::Invocation.new( Array, :at, ' (Fixnum index) => Object or NilClass' ).signature.should be_an_instance_of(Signature) end it "returns the correct Signature object" end describe ReadRuby::Invocation, "#description" do it "returns an Array" do ReadRuby::Invocation.new(Array, :first, 'text').description.should be_an_instance_of(Array) end it "returns an Array of Strings" do ReadRuby::Invocation.new( Array, :first, "Line 1\nLine 2" ).description.all? { |line| line.should be_an_instance_of(String) } end it "sets each element to the corresponding line of the description" do ReadRuby::Invocation.new( Array, :first, "Line 1\nLine 2" ).description.should == ['Line 1', 'Line 2'] end it "has @method placeholders replaced with the name of the method" do ReadRuby::Invocation.new( Array, :first, " @method \nLine 2" ).description.should == [' first ', 'Line 2'] end it "has @object placeholders replaced with the name of the object" do ReadRuby::Invocation.new( Array, :first, " @object \nLine 2" ).description.should == [' Array ', 'Line 2'] end it "doesn't return the signature" it "doesn't return examples" end describe ReadRuby::Invocation, "#to_s" do it "returns a String" do ReadRuby::Invocation.new(String, :size, ' () => Fixnum'). to_s.should be_an_instance_of(String) end it "includes the Class name" do ReadRuby::Invocation.new( String, :size, ' () => Fixnum' ).to_s.should =~ /\WString\W/ end it "includes the method name" do ReadRuby::Invocation.new( String, :size, ' () => Fixnum' ).to_s.should =~ /\Wsize\W/ end it "includes the signature" do ReadRuby::Invocation.new( String, :insert, ' (Fixnum index, String other) => String' ).to_s.should =~ /\(Fixnum index, String other\)/ end it "includes the return value" do ReadRuby::Invocation.new( String, :insert, ' (Fixnum index, String other) => String' ).to_s.should =~ / => String/ end it "includes the description" do invoc = ReadRuby::Invocation.new( String, :insert, <<-text) (Fixnum index, String other) => String Inserts _other_ before the character at _index_. text invoc.to_s.should =~ / _other_ before the character / end end describe ReadRuby::Invocation, "#preprocess" do it "has @method placeholders replaced with the name of the method" do invoc = ReadRuby::Invocation.new( Array, :first, " @method \nLine 2" ) invoc.preprocess invoc.description.should == [' first ', 'Line 2'] end it "has @object placeholders replaced with the name of the object" do invoc = ReadRuby::Invocation.new( Array, :first, " @object \nLine 2" ) invoc.preprocess invoc.description.should == [' Array ', 'Line 2'] end it "will replace the same placeholder multiple times per line if necessary" do invoc = ReadRuby::Invocation.new( Array, :first, " @method @method\nLine 2" ) invoc.preprocess invoc.description.should == [' first first', 'Line 2'] end it "works with both kinds of placeholders in the same description" do invoc = ReadRuby::Invocation.new( Array, :first, " @object\#@method \nLine 2" ) invoc.preprocess invoc.description.should == [' Array#first ', 'Line 2'] end it "works with signatures" do invoc = ReadRuby::Invocation.new( Array, :first, " (Fixnum) => @object" ) invoc.preprocess invoc.signature.to_s.should =~ /\(Fixnum\) => Array/ end it "works with examples" do invoc = ReadRuby::Invocation.new( Array, :first, " [1,2,3].@method(2) #=> [1,2]" ) invoc.preprocess invoc.examples.join.to_s.should include('[1,2,3].first(2)') end it "works if there are no placeholders to replace" do invoc = ReadRuby::Invocation.new( Array, :first, "Line 1\nLine 2" ) lambda { invoc.preprocess }.should_not raise_error invoc.description.should == ['Line 1', 'Line 2'] end it "is called automatically by the constructor" do invoc = ReadRuby::Invocation.new( Array, :first, " @object \nLine 2" ) invoc.description.should == [' Array ', 'Line 2'] end end describe ReadRuby::Invocation, "#parse" do before(:all) do @invocation = ReadRuby::Invocation.new( String, :include?, <<-text) (String) => true or false Line 1 'what'.include?('hat') #=> true what = 'Shibboleth' \\ what.include?('leth') #=> true text end it "returns an Array" do @invocation.parse.should be_an_instance_of(Array) end it "coerces the signature into a Signature object" do @invocation.parse.first.should be_an_instance_of(ReadRuby::Signature) end it "returns description lines as String elements" do @invocation.parse[2].should be_an_instance_of(String) end it "coerces example lines into Example objects" do @invocation.parse[4].should be_an_instance_of(ReadRuby::Example) end it "treats lines ending in '\' as part of the next line" do @invocation.parse.last.should be_an_instance_of(ReadRuby::Example) @invocation.parse.last.ok?.should be_true end end
true
51180555cb12ff89c059627c022ee07be4243ff1
Ruby
edvelezg/unb-dw
/mysql_work/connect.rb
UTF-8
2,720
2.890625
3
[]
no_license
#!/usr/bin/ruby -w # simple.rb - simple MySQL script using Ruby MySQL module # update user set Password=PASSWORD('mondrian') WHERE User='ed'; # SELECT book_id, place_id, count(*) from sentence_and_place group by book_id, place_id; # SELECT book_id, t1.place_id, t2.place_name, COUNT(*) FROM sentence_and_place AS t1 INNER JOIN place AS t2 ON t1.place_id = t2.place_id GROUP BY t2.place_id, book_id; require "mysql" var1 = "snake" mtr = [ ["'#{var1}'", "'reptile'"], ["'frog'", "'amphibian'"], ["'tuna'", "'fish'"], ["'racoon'", "'mammal'"] ] arr = [] mtr.each { |e| arr << "(#{e.join(',')})" } table = arr.join(",\n") begin # connect to the MySQL server dbh = Mysql.real_connect("localhost", "ed", "mondrian", "litolap") # get server version string and display it puts "Server version: " + dbh.get_server_info dbh.query("DROP TABLE IF EXISTS sentence") dbh.query("CREATE TABLE sentence ( book_id INT UNSIGNED, sentence_id INT UNSIGNED, sentence VARCHAR(5000) ) ") dbh.query("DROP TABLE IF EXISTS sentence_and_place") dbh.query("CREATE TABLE sentence_and_place ( book_id INT UNSIGNED, sentence_id INT UNSIGNED, place_id INT UNSIGNED, frequency INT UNSIGNED ) ") dbh.query("DROP TABLE IF EXISTS place") dbh.query("CREATE TABLE place ( place_id INT UNSIGNED, place_name VARCHAR(200) ) ") dbh.query("LOAD DATA LOCAL INFILE '/Users/Naix/Tmp/unb-dw/project/XMLtoRel/places.txt' INTO TABLE place") dbh.query("LOAD DATA LOCAL INFILE '/Users/Naix/Tmp/unb-dw/project/XMLtoRel/sentences.txt' INTO TABLE sentence") dbh.query("LOAD DATA LOCAL INFILE '/Users/Naix/Tmp/unb-dw/project/XMLtoRel/sentences_and_places.txt' INTO TABLE sentence_and_place") # dbh.query("INSERT INTO animal (name, category) # VALUES # #{table} # ") # puts "Number of rows inserted: #{dbh.affected_rows}" # issue a retrieval query, perform a fetch loop, print # the row count, and free the result set # res = dbh.query("SELECT name, category FROM animal") # # while row = res.fetch_row do # printf "%s, %s\n", row[0], row[1] # end # puts "Number of rows returned: #{res.num_rows}" # # res.free rescue Mysql::Error => e puts "Error code: #{e.errno}" puts "Error message: #{e.error}" puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate") ensure # disconnect from server dbh.close if dbh end
true
dda3c7f03868d963463f5f9d639f3fc81b2cf5a2
Ruby
saihdavis/array-CRUD-lab-onl01-seng-pt-032320
/lib/array_crud.rb
UTF-8
926
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def create_an_empty_array [] end def create_an_array my_array = ["one", "two", "three", "four"] end def add_element_to_end_of_array(array, element) my_array = ["one", "two", "three", "four"] my_array.push("arrays!") end def add_element_to_start_of_array(array, element) my_array = ["one", "two", "three", "four"] my_array.unshift("wow") end def remove_element_from_end_of_array(array) my_array = ["wow", "two", "three", "arrays!"] my_array.pop end def remove_element_from_start_of_array(array) my_array = ["wow", "two", "three", "arrays!"] my_array.shift end def retrieve_element_from_index(array, index_number) my_array = ["wow", "am", "three", "arrays!"] my_array[1] end def retrieve_first_element_from_array(array) my_array = ["wow", "am", "three", "arrays!"] my_array[0] end def retrieve_last_element_from_array(array) my_array = ["wow", "am", "three", "arrays!"] my_array[-1] end
true
02abe07aab100c9d13c3e3bbf92ffe8540f3c93f
Ruby
PabloK/CLL
/lib/models/ability.rb
UTF-8
3,087
2.796875
3
[]
no_license
#encoding: utf-8 class Ability include DataMapper::Resource property :id, Serial, :key => true property :name, String, :unique => true, :required => true, :messages => { :presence =>"Förmågan kan inte enbart inehålla mellanslag." } # A measurement of how much this ability is embraced property :number_of_inclusions, Integer, :required => true, :default => 1 property :embracement, Float, :required => true, :default => 1.0 # A measurement of how much this ability is rejected property :number_of_complaints, Integer, :required => true, :default => 0 property :ostracisity, Float, :required => true, :default => 0.0 property :fondness, Float, :required => true, :default => 1.0 validates_length_of :name, :max => 48 , :message => "Förmågan får högst innehålla 48 tecken." has n, :areas, :through => Resource has n, :consultant_tracks, :through => Resource has n, :ability_sliders, :through => Resource # Embrace the ability def embrace! if @number_of_inclusions <= 300 number_of_inclusions = @number_of_inclusions + 1 embracement = 10.0*Math.atan((number_of_inclusions.to_f-30.0)/10.0)/(Math::PI/2.0)+10.0 fondness = determine_fondness(embracement,@ostracisity) update!(:number_of_inclusions => number_of_inclusions, :embracement => embracement, :fondness => fondness) end end # Defame the ability def ostracize! if @number_of_complaints <= 300 number_of_complaints = @number_of_complaints + 1 ostracisity = 8.0*Math.atan((number_of_complaints.to_f-30.0)/10.0)/(Math::PI/2.0)+8.0 fondness = determine_fondness(@embracement,ostracisity) update!(:number_of_inclusions => number_of_inclusions, :ostracisity => ostracisity, :fondness => fondness) end end # Embrace or create the ability if it is used def self.use_ability(area ,ability) # It does not check for abilities in areas but just abilites unless Ability.exists(ability) used_ability = Ability.new used_ability.name = ability used_ability.areas << Area.get(area) used_ability.save else used_ability = Ability.first(:name.like => ability) if used_ability used_ability.areas << Area.get(area) used_ability.embrace! end end if used_ability errors = used_ability.errors.map{|error| error} else errors = [] end # TODO used_ability does not always have data return {:ability => used_ability, :errors => errors} end def self.exists(ability) return Ability.count(:name.like => ability.downcase) != 0 end def self.find_abilties(ability) all(:fields => [:name, :fondness], :name.like => '%'+ability.downcase+'%', :order => [:fondness.desc],:limit => 10) end def name=(name) super(name.downcase.split.join(" ")) end # Calculate the fondness of a ability private def determine_fondness(embracement, ostracisity) return embracement - ostracisity end end
true
61c58497769c55580a9680dd5c02a8fa2c81ef25
Ruby
mdheller/rletters
/app/lib/r_letters/analysis/count_articles_by_field.rb
UTF-8
7,838
2.71875
3
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
# frozen_string_literal: true module RLetters module Analysis # Code for counting the number of articles in a dataset, grouped by a field # # @!attribute field # @return [Symbol] the field to group by # @!attribute dataset # @return [Dataset] if set, the dataset to analyze (else the entire # corpus) # @!attribute normalize # @return [Boolean] if true, divide the counts for `dataset` by the # counts for the same field in `normalization_dataset` before returning # @!attribute normalization_dataset # @return [Dataset] dataset to normalize by (or nil for the whole corpus) # @!attribute progress # @return [Proc] if set, a function to call with percentage of completion # (one integer parameter) class CountArticlesByField include Service include Virtus.model(strict: true, required: false, nullify_blank: true) attribute :field, Symbol attribute :dataset, Dataset attribute :normalize, Boolean, default: false attribute :normalization_dataset, VirtusExt::DatasetId attribute :progress, Proc # Count up a dataset (or the corpus) by a field # # This function takes a Solr field, groups the articles of interest by # the values for the given field, and returns the result in a hash. # # @todo This function should support the same kind of work with names # that we have in RLetters::Documents::Author. # # @return [Result] results of analysis def call Result.new( counts: normalize_counts(dataset ? group_dataset : group_corpus), normalize: normalize, normalization_dataset: normalization_dataset ) end private # Walk a dataset manually and group it by field # # @return [Hash<String, Integer>] number of documents in each group def group_dataset ret = {} total = dataset.document_count enum = RLetters::Datasets::DocumentEnumerator.new(dataset: dataset) enum.each_with_index do |doc, i| key = get_field_from_document(doc) next if key.nil? ret[key] ||= 0 ret[key] += 1 progress&.call((i.to_f / total.to_f * 100.0).to_i) end progress&.call(100) ret end # Allow for and clean up particularly weird values of the year field # # @param [String] year the year to clean # @return [String] the cleaned year def clean_year(year) return nil unless year.present? parts = year.split(%r{[-/]}) ret = parts[0] # Issues #108 and #109: make sure to ignore non-numerical year # values when grouping begin Integer(ret) rescue ArgumentError return nil end return ret end # Group the entire corpus by field, using Solr's result grouping # # @return [Hash<String, Integer>] number of documents in each group def group_corpus ret = {} start = 0 num_docs = 0 total_docs = RLetters::Solr::CorpusStats.new.size loop do search_result = RLetters::Solr::Connection.search_raw( q: '*:*', def_type: 'lucene', group: 'true', 'group.field' => field.to_s, fl: 'uid', facet: 'false', start: start.to_s, rows: 100 ) # These conditions would indicate a malformed Solr response break unless search_result.dig('grouped', field.to_s, 'matches') grouped = search_result['grouped'][field.to_s] break if grouped['matches'].zero? groups = grouped['groups'] break unless groups # This indicates that we're out of records break if groups.empty? # Add this batch to the return groups.each do |g| key = g['groupValue'] # Allow for pathological year values key = clean_year(key) if field == :year next if key.nil? val = g['doclist']['numFound'] ret[key] = val # Update the progress meter if progress num_docs += g['doclist']['numFound'] progress.call((num_docs.to_f / total_docs.to_f * 100.0).to_i) end end # Get the next batch of groups start += 100 end progress&.call(100) ret end # Get the value of the field for grouping from a document # # This implements support for strange year values and grouping on the # facet field values. FIXME: This will probably do something very strange # if you try to count on :authors_facet. # # @param [Document] doc the Solr document # @return [String] the field value def get_field_from_document(doc) # Map the 'facet' fields to normal values return doc.journal if field == :journal_facet return doc.authors if field == :authors_facet # Clean up pathological year values return clean_year(doc.year) if field == :year # We're not yet actually faceting on anything other than journal, # author, or year; so this code isn't tested # :nocov: nil # :nocov: end # Fill in zeros for any missing values in the counts # # If field is year, we'll actually fill in the intervening years by # count. Otherwise, we'll just fill in any values that are present in # the normalization set but missing in the counts. # # @param [Hash<String, Numeric>] counts the counts queried # @param [Hash<String, Numeric>] normalization_counts the counts from the # normalization set, nil if we didn't normalize # @return [Hash<String, Numeric>] the counts with intervening values set # to zero def zero_intervening(counts, normalization_counts = nil) normalization_counts ||= {} if field == :year # Find the low and high values for the numerical contents here, if # asked to do so min = 99999 max = -99999 full_set = (counts.keys + normalization_counts.keys).compact full_set.each do |k| num = 0 begin num = Integer(k) rescue ArgumentError next end min = num if num < min max = num if num > max end # Fill in all of the numerically intervening years Range.new(min, max).each do |i| counts[i.to_s] ||= 0.0 end else normalization_counts.keys.compact.each do |k| counts[k] ||= 0.0 end end counts end # Normalize the counts against the normalization set, if it exists # # This function also makes sure that the field values are a contiguous # range with no gaps, filling in zeros if necessary. # # @param [Hash<String, Integer>] counts the counts for the original set # @param [Hash<String, Float>] the normalized counts def normalize_counts(counts) return {} if counts.empty? return zero_intervening(counts) unless normalize norm_counts = CountArticlesByField.call( field: field, dataset: normalization_dataset ).counts ret = counts.each_with_object({}) do |(k, v), out| # Just don't save an entry for any really strange values here if k.present? && norm_counts[k]&.>(0) out[k] = v.to_f / norm_counts[k] end end zero_intervening(ret, norm_counts) end end end end
true
3778b0cdd763ffb1283a7234190973f0d66729d7
Ruby
diegocasmo/guitarlyco
/app/models/article.rb
UTF-8
488
2.515625
3
[]
no_license
class Article < ActiveRecord::Base # Validations validates_presence_of :title, :slug, :video_link, :body validates_uniqueness_of :title # Callbacks before_validation :add_article_slug def add_article_slug return unless self.title.present? self.slug = self.title.parameterize end # Paginates a list of articles def self.get_paginated(page, per_page) page = page || 1 per_page = per_page || 7 self.paginate(page: page, per_page: per_page) end end
true
1c9c0da28e045d9b44a105241b8afac4dcb7da43
Ruby
craigsheen/coloruby
/lib/coloruby.rb
UTF-8
1,340
3.609375
4
[]
no_license
class Coloruby def self.lighten(hex_color, amount=0.3) hex_color = hex_color.gsub('#','') rgb = hex_color.scan(/../).map { |color| color.hex } rgb[0] = [(rgb[0].to_i + 255 * amount).round, 255].min rgb[1] = [(rgb[1].to_i + 255 * amount).round, 255].min rgb[2] = [(rgb[2].to_i + 255 * amount).round, 255].min "#%02x%02x%02x" % rgb end def self.darken(hex_color, amount=0.3) hex_color = hex_color.gsub('#','') rgb = hex_color.scan(/../).map { |color| color.hex } rgb[0] = (rgb[0].to_i * amount).round rgb[1] = (rgb[1].to_i * amount).round rgb[2] = (rgb[2].to_i * amount).round "#%02x%02x%02x" % rgb end def self.hex_to_rgb(hex_color) hex_color = hex_color.gsub('#','') hex_color.scan(/../).map { |color| color.hex } end def self.rgb_to_hex(rgb_color) '#'+rgb_color.map { |color| color < 10 ? "0#{color.to_s(16)}" : color.to_s(16) }.join("") end def self.light_or_dark?(hex, dark_limit=0.5) rgb = hex.match /#(..)(..)(..)/ brightness = Math.sqrt(0.241 * rgb[1].hex**2 + 0.691 * rgb[2].hex**2 + 0.068 * rgb[3].hex**2) / 255 if brightness > dark_limit "light" else "dark" end end def self.dark?(hex) light_or_dark?(hex) == "dark" end def self.light?(hex) light_or_dark?(hex) == "light" end end
true
e80b81c7889aaf3d3c023ebf5ca42a9555932f94
Ruby
walter-petkanych/lessons
/happy1.rb
UTF-8
226
3.828125
4
[]
no_license
puts('enter your name') name = gets() puts('happy birthday ' + name) puts('what year is now?') year = gets() puts('what is the year you are boarned') boarned = gets() age = year.to_i - boarned.to_i puts('you are ' + age.to_s)
true
6d1cc7c9c8ea93d31dab036d0df42cbf66ae0a93
Ruby
Jacura/Ruby-Practice-Project
/Task5/exception_handling.rb
UTF-8
171
3.125
3
[]
no_license
x = gets.chomp.to_i y = gets.chomp.to_i def add(a,b) begin c = a + b rescue Exception => e puts e.message ensure puts c end end add(x,y)
true
769dedb4b654d0d5ec86cb75fb891f9eb561a896
Ruby
ceritium/gosu-in-space
/libs/shot.rb
UTF-8
611
3.15625
3
[]
no_license
class Shot attr_reader :y, :x, :time def initialize(window, x, y, angle) @image = Gosu::Image.new(window, "media/empire_laser.png", false) @vel_x = @vel_y = @angle = 0.0 @x, @y, @angle = x, y, angle @vel_x += Gosu::offset_x(@angle, 17) @vel_y += Gosu::offset_y(@angle, 17) @time = Time.now end def destroy_tie(ties) ties.reject! do |tie| if Gosu::distance(@x, @y, tie.x, tie.y) < 40 true else false end end end def draw @x += @vel_x @y += @vel_y @image.draw_rot(@x, @y, 1, @angle) end end
true
3aa4ffbe8f94409af6a3cac2faa527d224ed88c2
Ruby
toryu1121/puyoaptana
/puyoclass/yokoku.rb
UTF-8
1,467
3.359375
3
[]
no_license
#! ruby -Ku require './matrixx' # require './action' #後でコメントアウト, 消さなきゃaction.rbを実行できない class Yokoku def initialize(yokoku, input_key, puyo, width, roll) @yokoku = yokoku @input_key = input_key @puyo = puyo @width = width @roll = roll #p @yokoku #p @input_key = 6 case @input_key when 1 story01 when 2 story02 when 3 story03 when 4 story04 when 5 story05 when 6 story06 else #p "何も処理しません" end end attr_accessor :yokoku, :puyo, :width def story01 #p "story01:左を押しました" #p "width を-1します" @width-=1 unless @width == 0 end #落下した時の予告空間の変化 def story02 #p "story02:下を押しました" #p "ここでは処理を行いません" end def story03 #p "story03:右を押しました" #p "width を+1します" @width+=1 unless @width == 5 end def story04 #p "story04:左回転します" @roll.unshift(@roll.pop) end def story05 #p "story05:右回転します" @roll.push(@roll.shift) end #1手先を固ぷよに、2手先をゾロぷよに変化 def story06 #p "story06:1手先を固ぷよに、2手先をゾロぷよに変化させます" test = rand(4) + 1 @yokoku[0] = [6, 6] @yokoku[1] = [test, test] end end
true
ab7642f08b474cbfd9a1b2fca6eb5cd39551d3c0
Ruby
jweissman/dragon
/lib/dragon/events/person_encountered_event.rb
UTF-8
347
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Dragon module Events class PersonEncounteredEvent < Event attr_reader :person def initialize(person: nil) @person = person end def describe "You encounter a person: #{person.describe}" end def actions [ converse_with(person), ignore(person) ] end end end end
true
4561a3fcc3af24225e20136bb64bcce55aaea665
Ruby
mois3x/ruby-tsv
/spec/lib/tsv_spec.rb
UTF-8
3,397
2.6875
3
[ "MIT" ]
permissive
require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb') describe TSV do let(:filename) { 'example.tsv' } describe "#parse" do let(:header) { nil } let(:parameters) { { header: header } } context "given a string with content" do let(:content) { IO.read(File.join(File.dirname(__FILE__), '..', 'fixtures', filename)) } subject { TSV.parse(content, parameters) } it "returns Table initialized with given data" do expect(subject).to be_a TSV::Table expect(subject.source).to eq(content) end context "when block is given" do it "passes block to Table" do data = [] TSV.parse(content) do |i| data.push i end headers = %w{first second third} expect(data).to eq [ TSV::Row.new( ['0', '1', '2'], headers ), TSV::Row.new( ['one', 'two', 'three'], headers ), TSV::Row.new( ['weird data', 's@mthin#', 'else'], headers ) ] end end end context "given a opened IO object" do let(:content) { File.open(File.join(File.dirname(__FILE__), '..', 'fixtures', filename), 'r') } subject { TSV.parse(content, parameters) } it "returns Table initialized with given data" do expect(subject).to be_a TSV::Table expect(subject.source).to eq(content) end it "can properly parse file" do data = [] TSV.parse(content).each do |i| data.push i end headers = %w{first second third} expect(data).to eq [ TSV::Row.new( ['0', '1', '2'], headers ), TSV::Row.new( ['one', 'two', 'three'], headers ), TSV::Row.new( ['weird data', 's@mthin#', 'else'], headers ) ] end end end describe "#parse_file" do let(:tsv_path) { File.join(File.dirname(__FILE__), '..', 'fixtures', filename) } subject { TSV.parse_file tsv_path } context "when no block is given" do it "returns Table initialized with File object" do expect(subject).to be_a TSV::Table expect(subject.source).to be_kind_of(File) expect(subject.source.path).to eq(tsv_path) end end context "when block is given" do it "passes block to Table" do data = [] TSV.parse_file(tsv_path) do |i| data.push i end headers = %w{first second third} expect(data).to eq [ TSV::Row.new( ['0', '1', '2'], headers ), TSV::Row.new( ['one', 'two', 'three'], headers ), TSV::Row.new( ['weird data', 's@mthin#', 'else'], headers ) ] end end context "when accessing unavailable files" do subject { lambda { TSV.parse_file(tsv_path).to_a } } context "when file is not found" do let(:tsv_path) { "AManThatWasntThere.tsv" } it "returns FileNotFoundException" do expect(subject).to raise_error(Errno::ENOENT) end end end describe "intermediate file handle" do it "raises IOError on write attempt" do tempfile = Tempfile.new('tsv_test') handle = TSV.parse_file(tempfile.path).source expect{ handle.puts('test string please ignore') }.to raise_error(IOError, 'not opened for writing') end end end end
true
2d473d9734e6d6191b50361e825c069cae5b3d29
Ruby
CodingMBA/ls_101_lesson_3
/easy_2_7.rb
UTF-8
255
2.8125
3
[]
no_license
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) flintstones.push("Dino", "Hoppy") flintstones.push("Dino").push("Hoppy") flintstones.unshift("Dino", "Hoppy") flintstones.unshift("Dino").unshift("Hoppy") flintstones.concat(%w(Dino Hoppy)) p flintstones
true
f5a4b8fb68f4946d83415a807fa7358a92088d92
Ruby
everypolitician-scrapers/uzbekistan-majlis
/scraper.rb
UTF-8
2,446
2.75
3
[]
no_license
#!/bin/env ruby # encoding: utf-8 require 'scraperwiki' require 'nokogiri' require 'pry' require 'set' require 'open-uri/cached' OpenURI::Cache.cache_path = '.cache' class String def tidy self.gsub(/[[:space:]]+/, ' ').strip end end def noko_for(url) Nokogiri::HTML(open(url).read) end def scrape_letters(fmt, lang) url = fmt % lang noko = noko_for(url % lang) noko.css('#alfabetDepsSearch li a/@href').each do |href| link = URI.join url, href scrape_list(link, lang) end end def scrape_list(url, lang) puts url.to_s.cyan noko = noko_for(url) seen = Set.new noko.css('.deputiesList li a[href*="/deputy/"]/@href').each do |href| link = URI.join url, href next if seen.include? link scrape_person(link, lang, { image: href.parent.css('img/@src').text, }) seen << link end end def scrape_person(url, lang, data_i) noko = noko_for(url) add_map = lang == 'uz' ? { region: "Худуд", constituency: "Сайлов округи", party: "Партияга мансублиги", faction: "Фракцияга аъзолиги", } : { region: "Region", constituency: "Constituency", party: "Party", faction: "Faction member", } info_map = lang == 'uz' ? { birth_date: "Туғилган сана", birth_place: "Туғилган жойи", nationality: "Миллати", } : { birth_date: "Date of Birth", birth_place: "Place of Birth", nationality: "Nationality", } info = noko.css('#deputyPersInfo') add = noko.css('#addInfo') info_data = Hash[info_map.map { |field, str| [ field, info.xpath('.//td[text()="%s"]/following-sibling::td' % str).text.tidy ] }] add_data = Hash[add_map.map { |field, str| [ field, add.xpath('.//li[contains(.,"%s:")]' % str).text.split(':',2).last.to_s.tidy ] }] data = { id: url.to_s.split('/').last, name: noko.css('h2 span').text.tidy, term: 5, source: url.to_s, }.merge(data_i).merge(info_data).merge(add_data) data[:image] = URI.join(url, URI.encode(data[:image])).to_s unless data[:image].to_s.empty? data[:birth_date] = data[:birth_date].split('.').reverse.join('-') # puts data[:id] ScraperWiki.save_sqlite([:id, :term], data) end @LANG = ARGV.first || 'uz' scrape_letters('http://www.parliament.gov.uz/%s/structure/deputy/', @LANG) # scrape_letters('http://www.parliament.gov.uz/en/structure/deputy/search1.php?id=+')
true
0e8f570eeef6bc6826f689ef4023d0b087c76ea5
Ruby
nikomc0/debt_calculator_sinatra
/app/helpers/finance_calculations.rb
UTF-8
2,208
2.96875
3
[]
no_license
module FinanceCalculations # Credit Card Minimum Payment is just a simple percentage of the principal. # def minimum_payment # BigDecimal(self.principal) * 0.03 # end def minimum_payment(*args) apr = self.apr principal = self.principal args.map do |x| if x.include?('principal') principal = BigDecimal(x[:principal]) end if x.include?('apr') apr = BigDecimal(x[:apr]) end end # Interest Rate / Number of payments per year X Prinicipal = Interest '%.2f' % BigDecimal(((apr / 100) / 12) * principal) end def monthly_interest(apr) (apr / 100) / 12 end def monthly_payment(monthly_budget, total_accounts, min_payment) usable_budget = monthly_budget / total_accounts if min_payment && min_payment > 0 usable_budget += min_payment end usable_budget end def num_months(monthly_interest, principal, monthly_payment) top = Math.log(1 - (monthly_interest * principal) / (-monthly_payment)) bottom = Math.log(1 + monthly_interest) num_months = top / bottom num_months.ceil end def calculate_pay_schedule @account.num_months(@account[:monthly_payment], @account[:principal], @account[:monthly_payment]) payment = @account[:monthly_payment] month = @account[:month] payments = [] @account[:num_months].times do |i| accrued_interest = ((@account[:apr] / 100) / 365) * 30 * @account[:principal] # updated_balance = @account[:principal] + accrued_interest updated_balance = @account[:principal] upcoming_month = month.next_month month = upcoming_month now = DateTime.now.in_time_zone('Pacific Time (US & Canada)') if payment >= updated_balance payment = updated_balance updated_balance -= payment @account[:principal] = updated_balance payments << {account_id: account.id, payment: payment, created_at: now, updated_at: now, month: upcoming_month, balance: updated_balance} else # updated_balance += accrued_interest updated_balance -= payment @account[:principal] = updated_balance payments << {account_id: account.id, payment: payment, created_at: now, updated_at: now, month: upcoming_month, balance: updated_balance} end end bulk_import(payments) end end
true
7170dd02c2b1cb7f02e7bb580b1fa060eaf54487
Ruby
binamkayastha/WunCur
/src/extlib/wlist/lib/wlist.rb
UTF-8
3,334
2.875
3
[ "MIT" ]
permissive
require 'json' require 'optparse' OPTIONS = {} OPTIONS_PARSER = OptionParser.new do |opts| opts.banner = "Usage: example.rb [options]" opts.on("-v", "--verbose", "Show verbose statements") do |v| OPTIONS[:verbose] = v end opts.on("-i ID", "--id ID", Integer, "Object identifier") do |v| OPTIONS[:id] = v end opts.on("-r REVISION", "--revision REVISION", Integer, "Object identifier") do |v| OPTIONS[:revision] = v end opts.on("-j ID", "--list-id ID", Integer, "Object identifier") do |v| OPTIONS[:list_id] = v end opts.on("-t TITLE", "--title TITLE", "Title for a task") do |v| OPTIONS[:title] = v end opts.on("-u URL", "--url URL", "Webhook URL") do |v| OPTIONS[:url] = v end opts.on("-d CONFIG", "--CONFIG CONFIG", "Configuration") do |v| OPTIONS[:config] = v end opts.on("-p TYPE", "--processor-type TYPE", "Processor Type") do |v| OPTIONS[:processor_type] = v end opts.on("-s", "--[no-]star", "Star status") do |v| OPTIONS[:starred] = v end opts.on("-c", "--[no-]complete", "Completed status") do |v| OPTIONS[:completed] = v end end def parse_options OPTIONS_PARSER.parse! end class String def black; "\033[30m#{self}\033[0m" end def red; "\033[31m#{self}\033[0m" end def green; "\033[32m#{self}\033[0m" end def brown; "\033[33m#{self}\033[0m" end def blue; "\033[34m#{self}\033[0m" end def magenta; "\033[35m#{self}\033[0m" end def cyan; "\033[36m#{self}\033[0m" end def gray; "\033[37m#{self}\033[0m" end def bold; "\033[1m#{self}\033[22m" end def reverse_color; "\033[7m#{self}\033[27m" end end def client_id return ENV['WLIST_CLIENT_ID'] if ENV['WLIST_CLIENT_ID'] puts "Missing $WLIST_CLIENT_ID in environment" puts "Visit https://developer.wunderlist.com/applications and create an app!" exit -1 end def access_token return ENV['WLIST_ACCESS_TOKEN'] if ENV['WLIST_ACCESS_TOKEN'] puts "Missing $WLIST_ACCESS_TOKEN in environment." exit -1 end def access_headers "-H 'Content-Type: application/json' -H 'X-Client-ID: #{client_id}' -H 'X-Access-Token: #{access_token}'" end def v1url(resource) "https://a.wunderlist.com/api/v1/#{resource}" end # NETWORK ACCESS METHODS def curl(url, method="GET", data=nil, headers=access_headers, quiet=false) cmd = "-s #{headers}" cmd << " -d '#{JSON.generate(data)}'" if data != nil cmd << " -X #{method} '#{url}'" if !quiet and OPTIONS[:verbose] puts "curl ".gray.bold + cmd.gray end response = `curl #{cmd}` end def get(path) url = v1url(path) response = curl(url, "GET") JSON.parse(response) end def post(path, data) url = v1url(path) response = curl(url, "POST", data) JSON.parse(response) end def patch(path, data) url = v1url(path) response = curl(url, "PATCH", data) JSON.parse(response) end def delete(path) url = v1url("#{path}") response = curl(url, "DELETE") if response != "" JSON.parse(response) else nil end end # INBOX HELPER def get_inbox_id lists = get("lists") inbox = lists.detect {|i| i['list_type'] == 'inbox' }['id'] if OPTIONS[:verbose] puts "scanned ".gray.bold + "#{lists.size} lists for list_type of inbox".gray puts "inbox id: ".gray.bold + "#{inbox}".gray end inbox end
true
10c7b9459ee4dbfdc81e62f4dabbdec2c4626d63
Ruby
AgileVentures/WebsiteOne
/app/services/markdown_converter.rb
UTF-8
304
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true class MarkdownConverter attr_reader :markdown private :markdown def initialize(markdown) @markdown = markdown end def as_html converted_markdown.html_safe end private def converted_markdown Kramdown::Document.new(markdown).to_html end end
true
1c008717a900357bbf0a965c97df8d0667641959
Ruby
codenameuriel/getting-remote-data-apis-and-iteration-nyc-web-021720
/lib/command_line_interface.rb
UTF-8
372
3.875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def welcome puts "\nWelcome to the Star Wars program...\nYou can search what movies a character appeared." end def get_character_from_user puts "please enter a character name" # use gets to capture the user's input. This method should return that input, downcased. character_name = gets.chomp # .downcase.strip # puts "You selected #{character_name}!" end
true
915400e5f0b141c007d455e658aa0db77a8cbce8
Ruby
Aditya-Chowdhry/examopedia-rails
/app/models/exam.rb
UTF-8
3,584
2.5625
3
[]
no_license
# create_table :exams do |t| # t.string :title # t.string :description # t.integer :section # t.integer :level # t.attachment :image # t.datetime :exam_date # t.date :form_release_date # t.date :form_last_date # t.string :link1_name # t.string :link1 # t.string :link2_name # t.string :link2 # t.string :link3_name # t.string :link3 # t.string :link4_name # t.string :link4 # t.timestamps null: false # class Exam < ActiveRecord::Base #validates :title,:description,:image,:level,:section ,:presence => true has_attached_file :image,styles: {thumb: "150x150>", medium: "700x500>", small: "350x350>"},processors: [:thumbnail, :compression] validates_attachment_content_type :image, :content_type => /\Aimage\/(jpg|jpeg|pjpeg|png|x-png|gif)\z/, :message => 'file type is not allowed (only jpeg/png/gif images)' enum section: [:'Arts', :'Commerce',:'Science'] enum level: [:'Undergraduate',:'Global',:'Postgraduate'] #processors: [:thumbnail, :compression] scope :approved, -> { where(:exam_review => false) } scope :pending, -> { where(:exam_review => true) } scope :newest,-> { order("created_at desc") } # def self.approve # @exams = Exam.approved.newest # return @exams #end #def self.pending # @exams = Exam.approved.newest #return @exams #end #after_save :compress_with_ffmpeg # after_post_process :compress #http://stackoverflow.com/questions/21897725/papercliperrorsmissingrequiredvalidatorerror-with-rails-4 #Starting with Paperclip version 4.0, all attachments are required to include a content_type validation, a file_name validation, or to explicitly state that they're not going to have either. validates_attachment_content_type :image, :content_type => /\Aimage\/(jpg|jpeg|pjpeg|png|x-png|gif)\z/, :message => 'file type is not allowed (only jpeg/png/gif images)' private def compress_with_ffmpeg [:thumb, :medium, :small].each do |type| img_path = self.image.path(type) Paperclip.run("ffmpeg", " -i #{img_path} #{img_path}") end end def compress current_format = File.extname(image.queued_for_write[:original].path) image.queued_for_write.each do |key, file| reg_jpegoptim = /(jpg|jpeg|jfif)/i reg_optipng = /(png|bmp|gif|pnm|tiff)/i logger.info("Processing compression: key: #{key} - file: #{file.path} - ext: #{current_format}") if current_format =~ reg_jpegoptim compress_with_jpegoptim(file) elsif current_format =~ reg_optipng compress_with_optpng(file) else logger.info("File: #{file.path} is not compressed!") end end end def compress_with_jpegoptim(file) current_size = File.size(file.path) Paperclip.run("jpegoptim", "-o --strip-all #{file.path}") compressed_size = File.size(file.path) compressed_ratio = (current_size - compressed_size) / current_size.to_f logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}") logger.debug("JPEG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%") end def compress_with_optpng(file) current_size = File.size(file.path) Paperclip.run("optipng", "-o7 --strip=all #{file.path}") compressed_size = File.size(file.path) compressed_ratio = (current_size - compressed_size) / current_size.to_f logger.debug("#{current_size} - #{compressed_size} - #{compressed_ratio}") logger.debug("PNG family compressed, compressed: #{ '%.2f' % (compressed_ratio * 100) }%") end end
true
9ea604b33e215031ab3d1287422569ba8e8ae512
Ruby
nathanl/.dotfiles
/bin/prune_merged
UTF-8
893
2.8125
3
[]
no_license
#!/usr/bin/env ruby # Ruby script to interactively prune branches that have been merged PERMANENT_BRANCHES = %w[develop main master staging release] current_branch = %x{git rev-parse --abbrev-ref HEAD}.strip unless PERMANENT_BRANCHES.include?(current_branch) puts "To run this, please check out one of #{PERMANENT_BRANCHES.inspect}" exit(1) end merged_branches = %x{git for-each-ref --format='%(refname:short)' refs/heads/* --merged}.lines.map(&:strip) prunable = merged_branches - PERMANENT_BRANCHES prunable = prunable - current_branch.lines if prunable.any? prunable.each do |branch_name| puts "delete merged branch '#{branch_name}' ? [Y/n]" answer = gets if answer.strip == "Y" %x{git branch -d #{branch_name}} else puts "skipping '#{branch_name}'" end puts end else puts "no temporary branch has been merged to '#{current_branch}'" end
true
3347a9a2f9b0606e5000ac4bbf4eb55c92fd7bea
Ruby
delmereccles/periodic
/lib/periodic/parser.rb
UTF-8
2,456
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Periodic module Parser def parse(string, options = { :bias => :seconds}) return Parseable.new(string, options[:bias]).seconds end private class Parseable def initialize(string, bias) @string = string validates_inclusion_of_numeral_in_string @bias = bias extract_time_parts_from_string end def seconds units = { :seconds => 1, :minutes => 60, :hours => 3600, :days => 3600*24, :weeks => 3600*24*7, :months => 3600*24*30, :years => 3600*24*365.25, :decades => 3600*24*365.25*10, :centuries => 3600*24*365.25*100, :millennia => 3600*24*365.25*1000 } seconds = @time_parts.inject(0) { |total, part| total = total + (part[1] * units[part[0]]) } return seconds % 1 == 0 ? seconds.to_i : seconds end private def validates_inclusion_of_numeral_in_string raise ArgumentError, "String contains no numbers", caller unless @string.match(/\d/) end def digital? @string.match(/:/) end def extract_time_parts_from_string @time_parts = Hash.new digital? ? extract_time_parts_from_digital : extract_time_parts_from_text end def extract_time_parts_from_digital units = [:seconds, :minutes, :hours, :days, :weeks, :months, :years, :decades, :centuries, :millennia] @string.split(":").reverse.each_with_index do |part, i| @time_parts[units[i + ((units.index(@bias) >= @string.split(":").size) ? units.index(@bias) - @string.split(":").size + 1 : 0)]] = part.to_f end end def extract_time_parts_from_text normalize_string units = { :s => :seconds, :m => :minutes, :h => :hours, :d => :days, :w => :weeks, :n => :months, :y => :years, :a => :decades, :c => :centuries, :b => :millennia } @string.split(' ').each { |part| @time_parts[part.match(/([a-z])/) ? units[part.match(/([a-z])/)[1].to_sym] : @bias] = (@time_parts[part.match(/([a-z])/) ? units[part.match(/([a-z])/)[1].to_sym] : @bias]||0) + part.to_f } end def normalize_string [/( )/, /(,)/, /(and)/].each{ |m| @string.gsub!(m, '') } @string.gsub!(/(\d)([a-zA-Z]+)/, '\1\2 ') [{:n=>/(mo\w*)/,:b=>/(m\w*l\w*)/,:a=>/(d\w*c\w*)/}, {:m=>/(m\w*)/,:h=>/(h\w*)/,:d=>/(d\w*)/,:w=>/(w\w*)/,:y=>/(y\w*)/,:c=>/(c\w*)/}, {:s=>/(s\w*)/}].each { |set| set.each{ |k,v| @string.gsub!(v, k.to_s) } } end end end end
true
857a5671778247cc6d301fd27fa1b1f7e91dca1b
Ruby
Exzaiden/loomio-sms-gateway-1
/loomioAPI.rb
UTF-8
3,604
3.0625
3
[]
no_license
require_relative 'masterConfig' require 'net/http' require 'rubygems' require 'json' ## # Accesses the API on Loomio's end # class LoomioAPI @uri = URI.parse(MasterConfig.getAPIServer) @http = Net::HTTP.new @uri.host, @uri.port @path = MasterConfig.getAPIPath @handlerURL = MasterConfig.getAPIHandler $stderr.puts "API initialised" class << self # REST GET query, given the api url and api parameters, and possibly URL parameters. # def getResponse(apiURL, apiParams, params = nil) req = Net::HTTP::Get.new(@path + apiURL + '/' + apiParams) req.set_form_data(params) unless params == nil $stderr.puts "sending GET to #{@uri.host + req.path}" return @http.request(req) end # REST POST query, posting the data to the URI with API parameters and data def postRequest(apiURL, apiParams = "", data) req = Net::HTTP::Post.new(@path + apiURL + '/' + apiParams) req.set_form_data(data) $stderr.puts "sending POST to #{@uri.host + req.path} with data #{data.to_s}" return @http.request(req) end # REST DELETE query, given the API path and the uri of the thing to delete and data. # def deleteRequest(apiURL, apiParams, data = nil) req = Net::HTTP::Delete.new(@path + apiURL + '/' + apiParams) req.set_form_data(data) unless data == nil $stderr.puts "sending DELETE to #{@uri.host + req.path} with data #{data.to_s}" return @http.request(req) end # Given a http response, returns an array with the 0th index being the HTTP # status (404, 200, 403) and the rest being hash of JSON from response # def jsonfy(res) if res.is_a?(Net::HTTPNotFound) return [404] elsif res.is_a?(Net::HTTPForbidden) return [403] elsif res.is_a?(Net::HTTPSuccess) parsed = JSON.parse(res.body) return [200, parsed] end return nil end # Gets an array of proposals in JSON format when given a subdomain name. # The first member of the array is status code of whether the request was successful # def getProposalsBySubdomain(subdomain) return jsonfy getResponse("/active_proposals", subdomain) end # Gets a single JSON representation of a proposal given its key. # returns array, whose first element is status code, and second element is a hash representation of the proposal # def getProposalByKey(key) return jsonfy getResponse("/proposals", key) end # Subscribe to a subdomain, given the subdomain name and the phone number which wants # to receive updaterinos. Returns array with status code as 1st element, and hash of unsubscription info as second # def subscribeToSubdomain(subdomain, number) return jsonfy postRequest("/api_group_subscriptions", {:subdomain => subdomain, :tag => number, :path => @handlerURL}) end # Unsubscribe from a subdomain, given the subdomain name and the number who wants to unsub # # def unsubscribeFromSubdomain(subdomain, number) return jsonfy deleteRequest("/api_group_subscriptions", subdomain, {:tag => number, :path => @handlerURL}) end private :getResponse, :postRequest, :deleteRequest, :jsonfy end end ' #testing purposes def test puts LoomioAPI.subscribeToSubdomain("abstainers", "656565").to_s puts LoomioAPI.getProposalsBySubdomain("abstainers").to_s puts LoomioAPI.getProposalByKey("xEtj48Rz").to_s puts LoomioAPI.unsubscribeFromSubdomain("abstainers", "656565").to_s end test '
true
8bc819ff6b9791a627d55821fa9c068cb36a9949
Ruby
Ricardo875/rails-yelp-mvp
/db/seeds.rb
UTF-8
1,161
2.546875
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts 'Cleaning database...' Restaurant.destroy_all puts 'Creating restaurants...' restaurants_attributes = [ { name: 'Joel Robucho', address: 'Ebisu, Tokyo', category: 'french', #rating: 5 }, { name: 'Rigoletto', address: 'Roppongi, Tokyo', category: 'italian', #rating: 4 }, { name: 'Antonio', address: 'Nishi-Azabu, Tokyo', category: 'italian', #rating: 5 }, { name: 'Pink Elephant', address: 'Akasa Mitsuke, Tokyo', category: 'belgian', #rating: 3 }, { name: 'Genki Sushi', address: 'Shibuya, Tokyo', category: 'japanese', #rating: 3 }, ] Restaurant.create!(restaurants_attributes) puts 'Finished!'
true
26ac6af507c5b978e29e5df0a8762de76e6a6b6a
Ruby
jodiealaine/colorizr
/example.rb
UTF-8
525
3.421875
3
[ "MIT" ]
permissive
require 'colorizr' # Should colorize the specified text with the color specified puts "John".red puts "Paul".green puts "George".blue puts "Ringo".yellow puts "John".pink puts "Paul".light_blue puts "George".white puts "Ringo".light_grey puts "John".black # Should only colorize the text with a colorize method called puts "Only #{'John'.red} is red" # Should show a list of color choices avaiable as methods p "example".colors # Should show a list text examples for each of our color choice methods String.sample_colors
true
fcbda4b36182491bfb6b0d828b176289d51d975a
Ruby
Alexander-Zyurkalov/MakePhrases
/lib/snenglish/word_rates.rb
UTF-8
737
2.515625
3
[]
no_license
module SNEnglish class WordRate < SNEnglish::Base @HEADER = [ "number_of","word","part_of_speech","number_of_files","id" ] def add_columns_to_csv(row) if row.count < 5 row.push self.id else row[-1] = self.id end end def set_attrs(rowHash) #"number_of","word","part_of_speech","number_of_files" self.number_of = rowHash["number_of"] self.word = rowHash["word"] self.part_of_speech = rowHash["part_of_speech"] self.number_of_files = rowHash["number_of_files"] true end end end
true
3171bf5155fde1b4d8fa5c4d03fd3763a40a1cee
Ruby
aetheric-typewriter/w2d3
/tdd_test/lib/tdd.rb
UTF-8
2,351
3.890625
4
[]
no_license
require "byebug" def my_uniq(arr) hash = {} arr.each do |ele| hash[ele] = true end hash.keys end def two_sum(arr) results = [] (0...(arr.length)).each do |i| ((i + 1)...(arr.length)).each do |j| results << [i, j] if arr[i] + arr[j] == 0 end end results end def my_transpose(arr) result = [] arr.each_with_index do |subarr, i| temp = [] subarr.each_with_index do |ele, j| temp.push(arr[j][i]) end result.push(temp) end result end def stockpicker(arr) return [] if arr.length < 2 pair = [0, 1] arr.each_with_index do |ele1, i| arr.each_with_index do |ele2, j| in_order = j > i current_difference = arr[j] - arr[i] pair_difference = arr[pair[1]] - arr[pair[0]] higher_difference_then_pair = current_difference > pair_difference pair = [i, j] if in_order && higher_difference_then_pair end end pair end class Hanoi attr_accessor :tower1, :tower2, :tower3, :n def initialize @tower1 = [] @tower2 = [] @tower3 = [] @n = 3 n.downto(1).each do |i| @tower1 << i end end def move(x, y) nums_to_towers = {1 => tower1, 2 => tower2, 3 => tower3 } tower_x = nums_to_towers[x] tower_y = nums_to_towers[y] raise "Out of Rule Error" if tower_x.empty? raise "Out of Rule Error" if tower_x.last > tower_y.last tower_y.push(tower_x.pop) end def won? tower1.empty? && (tower2.empty? || tower3.empty?) end def play until won? print_out begin pos = read_input move(*pos) end end end def print_out puts "Towers of Hanoi" puts "+++++++++++++++" puts puts "tower1: #{tower1} " puts "tower2: #{tower2} " puts "tower3: #{tower3} " puts end def read_input puts "Enter the tower start position and drop position (enter tower x to tower y as 'x,y')" data = gets.chomp pos = data.split(",").map(&:to_i) end end if __FILE__ == $PROGRAM_NAME game = Hanoi.new game.play end
true
6d90f1ba851f2743253b86c056bacaea9412d740
Ruby
jannesbrunner/ruby-workshop
/1_navigator/solve.rb
UTF-8
159
2.671875
3
[]
no_license
require './navigator' directions = File.read('./input.txt') navigator = Navigator.new navigator.follow(directions) puts "The answer is #{navigator.position}"
true
06d50424c17c4052ce908444bbe6c157ea05502e
Ruby
razic/armduino
/arm.rb
UTF-8
1,576
2.625
3
[]
no_license
# require libraries %w[ rubygems osc-ruby serialport ].each { |lib| require lib } # connect to arduino @arduino = SerialPort.new "/dev/tty.usbserial-A800etAZ", 115200 # initial arm position @shoulder, @forearm, @elbow, @claw = 180, 50, 60, 35 # setup osc server so we can listen for messages from the multi-touch on my iphone osc_server = OSC::Server.new "razic.local",8001 # these are the osc patterns and their callbacks # it's callback is triggered when a osc message matching one of our addresses is received osc_addrs = [ ["/1/shoulder_forearm", Proc.new { |m| @shoulder, @forearm = *m.instance_variable_get(:@args); }], ["/1/elbow", Proc.new { |m| @elbow = m.instance_variable_get(:@args)[0]; }], ["/1/claw", Proc.new { |m| @claw = m.instance_variable_get(:@args)[0]; }] ] osc_addrs.each { |a| osc_server.add_method a[0], &a[1] } # run the osc server in a new thread Thread.new { osc_server.run } # start telling the arduino where to move the motors loop do # here are our little packets ["<", 0, @shoulder.to_i, ">"].each { |byte| @arduino.putc byte } if @shoulder.to_i != @last_shoulder ["<", 1, @forearm.to_i, ">"].each { |byte| @arduino.putc byte } if @forearm.to_i != @last_forearm ["<", 2, @elbow.to_i, ">"].each { |byte| @arduino.putc byte } if @elbow.to_i != @last_elbow ["<", 3, @claw.to_i, ">"].each { |byte| @arduino.putc byte } if @claw.to_i != @last_claw @last_shoulder = @shoulder.to_i @last_forearm = @forearm.to_i @last_elbow = @elbow.to_i @last_claw = @claw.to_i puts ".\n" # who needs sleep? sleep 0.02 end
true
e7b219345d533602cafc9be2d65562f096393bb4
Ruby
meyouhealth/flexible_enum
/spec/identity_values_spec.rb
UTF-8
2,103
2.734375
3
[ "MIT" ]
permissive
require 'spec_helper' describe "identity values" do it "retrieves the details for the current value" do register = CashRegister.new register.status = CashRegister::NOT_ACTIVE expect(register.status_details).to eq(my_custom_option: "Nothing to see here", value: 10) end it "retrieves the name for the current value" do register = CashRegister.new register.status = CashRegister::UNKNOWN expect(register.status_name).to eq("unknown") register.status = CashRegister::NOT_ACTIVE expect(register.status_name).to eq("not_active") register.status = nil expect(register.status_name).to be_nil end it "retrieves the human name of the current value" do register = CashRegister.new register.status = CashRegister::UNKNOWN expect(register.human_status).to eq("Unknown") register.status = CashRegister::NOT_ACTIVE expect(register.human_status).to eq("Not active") register.status = nil expect(register.human_status).to be_nil end it "retrieves human names for available options" do expect(CashRegister.human_status(CashRegister::UNKNOWN)).to eq("Unknown") expect(CashRegister.human_status(CashRegister::NOT_ACTIVE)).to eq("Not active") end it "retrieves custom human names when provided" do expect(CashRegister.human_status(CashRegister::ALARM)).to eq("Help I'm being robbed!") end it "retrieves the human name of the current value of namespaced attributes" do opened_register = CashRegister.new.tap {|r| r.drawer_position = CashRegister::DrawerPositions::OPENED } closed_register = CashRegister.new.tap {|r| r.drawer_position = CashRegister::DrawerPositions::CLOSED } expect(opened_register.human_drawer_position).to eq("Opened") expect(closed_register.human_drawer_position).to eq("Closed") end it "retrieves human names for known constants of namespaced attributes" do expect(CashRegister.human_drawer_position(CashRegister::DrawerPositions::OPENED)).to eq("Opened") expect(CashRegister.human_drawer_position(CashRegister::DrawerPositions::CLOSED)).to eq("Closed") end end
true
9d29b10da02e99a317848df56c8201096628fe71
Ruby
pks/nlp_scripts
/first-upper
UTF-8
119
2.765625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'zipf' while line = STDIN.gets line.strip! line[0] = line[0].upcase puts line end
true
6d67117f36ab74a8896664b35d0423b771c940e0
Ruby
yuto0139/bonus-drink
/bonus_drink.rb
UTF-8
277
3.203125
3
[]
no_license
class BonusDrink def self.total_count_for(amount) # 3本未満の場合はamountの値が答え return amount if amount < 3 # 3本以上の場合はamountにおまけの本数を加えた値が答え return amount + (amount - 1) / 2 if amount >= 3 end end
true
50f441a647ce831827bf257e252cb02640206a1e
Ruby
ankit8898/tic-tac-toe
/lib/tic_tac_toe/diagonal.rb
UTF-8
217
2.765625
3
[]
no_license
#Diagonal # # A diagonal in a grid module TicTacToe class Diagonal attr_reader :position,:cells def initialize(opts = {}) @position = opts[:position] @cells = opts[:cells] end end end
true
6f1d9e4da61fbf21b53ddb492e9593c2e883a9b0
Ruby
rkononov/iron_worker_ruby
/test/test_inheritance.rb
UTF-8
386
2.59375
3
[ "BSD-2-Clause" ]
permissive
require_relative 'test_base' class TestInheritance < TestBase def test_who_am_i worker = TestWorker2.new puts "1: " + worker.who_am_i? puts "2: " + worker.who_am_i2? end def test_multi_subs t3 = TestWorker3.new t3.queue t3.wait_until_complete puts "LOG:" log = t3.get_log puts log assert log.include?("super_class_method") end end
true
cb9022e4c9364f382bc37aab7cd9d51d6936e745
Ruby
aizunoinu/RubyLife
/正規表現/test9-1.rb
UTF-8
606
3.703125
4
[]
no_license
#文字列の先頭に対してマッチ処理を行う #行の先頭に対してマッチ処理を実施する。 def check1(str) print "#{str}は ^abc に" if /^abc/ =~ str then print "マッチします\n" else print "マッチしません\n" end end #文字列の先頭に対してマッチ処理を実施する。 def check2(str) print "#{str}は \\Aabc に" if /\Aabc/ =~ str then print "マッチします\n" else print "マッチしません\n" end end check1("abc\ndef") check1("def\nabc") check2("abc\ndef") check2("def\nabc")
true
0282e3f86ec023d6b3ec76bef6b0acc600f8add8
Ruby
franky-og/ruby-objects-belong-to-lab-dumbo-web-82619
/lib/author.rb
UTF-8
127
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Author # def initialize(name) # @name = name # end def name=(new_name) @name = new_name end attr_reader :name end
true
cbc9bacc6c0e7e98de649fd4d90ee7c1014c1a25
Ruby
iEv0lv3/enigma
/lib/modules/shift.rb
UTF-8
1,533
3.453125
3
[]
no_license
require_relative 'character' module Shift include Character def create_shift(new_key, new_date) shift_key = new_key.make_keys(new_key.digits) shift_offset = new_date.create_offset(new_date.date) key_plus_offset(shift_key, shift_offset) end def key_plus_offset(shift_key, shift_offset) shift_offset.zip(shift_key.cycle).map(&:sum) end def apply_shift(indexes, shift, flag) shift_sets = create_shift_sets(indexes) if flag == 'encrypt' add_shift_to_indexes(shift_sets, shift) elsif flag == 'decrypt' remove_shift_from_indexes(shift_sets, shift) end end def create_shift_sets(indexes) shift_sets = [] indexes.each_slice(4) { |set| shift_sets << set } shift_sets end def add_shift_to_indexes(shift_sets, shift) alphabet = create_character_array cipher_set = [] shift_sets.each do |char_set| char_set.each_with_index do |char, index| if char.is_a?(Integer) == false cipher_set.push(char) else cipher_set.push(alphabet.rotate(shift[index])[char]) end end end cipher_set.join end def remove_shift_from_indexes(shift_sets, shift) alphabet = create_character_array cipher_set = [] shift_sets.each do |char_set| char_set.each_with_index do |char, index| if char.is_a?(Integer) == false cipher_set.push(char) else cipher_set.push(alphabet.rotate(-shift[index])[char]) end end end cipher_set.join end end
true
89618ed5cf25d1b46170e36b519e3e26a6b6d99b
Ruby
sethpuckett/gm-treasure
/app/models/treasure_haul.rb
UTF-8
479
3.125
3
[]
no_license
# frozen_string_literal: true class TreasureHaul attr_accessor :cp, :sp, :ep, :gp, :pp def initialize(cp: 0, sp: 0, ep: 0, gp: 0, pp: 0) @cp = cp @sp = sp @ep = ep @gp = gp @pp = pp end def add(type, value) case type when :cp then @cp += value when :sp then @sp += value when :ep then @ep += value when :gp then @gp += value when :pp then @pp += value else raise ArgumentError, "Invalid type '#{type}'" end end end
true
b69ded35f7a174d068fafe802b55a46a4b52e8c2
Ruby
jessiehuff/ttt-with-ai-project-v-000
/lib/game.rb
UTF-8
1,887
4.0625
4
[]
no_license
require 'pry' class Game attr_accessor :board, :player_1, :player_2 WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2] ] def initialize(player_1= Players::Human.new("X"), player_2= Players::Human.new("O"), board = Board.new) @board = board @player_1 = player_1 @player_2 = player_2 end def current_player @board.turn_count.even? ? @player_1 : @player_2 end def over? self.won? || self.draw? end def draw? @board.full? && !won? end def won? #returns false for a draw, returns the correct winning combination in the case of a win #binding.pry WIN_COMBINATIONS.detect do |combo| @board.cells[combo[0]] != " " && @board.cells[combo[0]] == @board.cells[combo[1]] && @board.cells[combo[1]] == @board.cells[combo[2]] end end def winner #returns X when X won, returns O when O won, returns nil when no winnter if winning = won? @winner = board.cells[winning.first] end end def turn #makes valid moves, asks for input again after a failed validation, changes to player 2 after the first turn player = current_player current_move = player.move(@board) if !@board.valid_move?(current_move) turn @board.display else @board.update(current_move, player) @board.display end end def play #asks for players input on a turn of the game, #checks if the game is over after every turn, #plays the first turns of the game, #checks if the game is a draw after every tur #stops playing if someone has won #congratulates the winner #stops playing in a draw, #plays through an entire game while !over? turn end if won? puts "Congratulations #{winner}!" else draw? puts "Cat's Game!" end end end
true
ee11decd0996a7b0c0f48153d2bccc7564cf0992
Ruby
mmichael0413/RomanNumerals
/roman_numerals_spec.rb
UTF-8
1,577
3.5
4
[]
no_license
require 'rspec' require_relative 'roman_numerals' describe RomanNumerals do let(:roman_numerals) { RomanNumerals.new } describe '#run!' do context 'when the user enters a valid number' do it 'should call the answer! method with the result' do allow_any_instance_of(RomanNumerals).to receive(:welcome!).and_return(1999) expect_any_instance_of(RomanNumerals).to receive(:answer!).with('MCMXCIX') .and_return('Your number in Roman numerals is MCMXCIX') roman_numerals.run! end end end describe '#invalid?' do context 'with an integer between 1 and 3000' do it 'should return false' do invalid = roman_numerals.invalid?(50) expect(invalid).to be false end end context 'with a string' do it 'should return true' do invalid = roman_numerals.invalid?('5') expect(invalid).to be true end end context 'with an integer greater than 3000' do it 'should return true' do invalid = roman_numerals.invalid?(3001) expect(invalid).to be true end end end describe '#answer!' do it 'should print a message with the result' do expect(STDOUT).to receive(:puts).with('Your number in Roman numerals is IX') roman_numerals.answer!('IX') end end describe '#welcome!' do it 'should return the integer value of user input' do expect_any_instance_of(RomanNumerals).to receive(:gets).and_return('45') result = roman_numerals.welcome! expect(result).to eq(45) end end end
true
b21bb49aa20eedbc5aaca7fc95be748f8d58e8a5
Ruby
omajul85/well-grounded-rubyist
/self_scope_and_visibility/method_access_rules/protected.rb
UTF-8
438
4.5
4
[]
no_license
class C def initialize(n) @n = n end def compare(c) if c.n > n puts "The other object's n is bigger" else puts "The other object's n is the same or smaller" end end protected attr_reader :n end c1 = C.new(100) c2 = C.new(101) c1.compare(c2) # The object doing the comparing (c1, in the example) has to ask the # other object (c2) to execute its n method. # # Therefore, n can’t be private.
true
c1e6cb9c9d8a668367de11085f8f23186bfb7736
Ruby
Syft-Application/companies-house-api
/lib/companies_house/request.rb
UTF-8
1,631
2.515625
3
[]
no_license
# frozen_string_literal: true require 'net/http' require 'virtus' module CompaniesHouse # This class manages individual requests. # Users of the CompaniesHouse gem should not instantiate this class class Request include Virtus.model attribute :api_endpoint attribute :api_key attribute :query attribute :path def initialize(args) args[:query] = defaults.merge(args[:query] || {}) super(args) @api_key = ::CompaniesHouse.api_key @api_endpoint = ::CompaniesHouse.api_endpoint raise ArgumentError, 'Missing API key' unless api_key raise ArgumentError, 'HTTP is not supported' unless uri.scheme == 'https' end def call response = connection.request req parse(response) end private def defaults { start_index: 0 } end def connection @connection ||= Net::HTTP.new(uri.host, uri.port).tap do |conn| conn.use_ssl = true end end def req obj = Net::HTTP::Get.new(uri) obj.basic_auth api_key, '' obj end def uri uri_inst = URI(api_endpoint) uri_inst = URI.join(uri_inst, path) uri_inst.query = URI.encode_www_form(query) uri_inst end def parse(response) case response.code when '200' JSON[response.body] when '401' raise ::CompaniesHouse::Errors::AuthenticationError, response when '429' raise ::CompaniesHouse::Errors::RateLimitError, response else raise ::CompaniesHouse::Errors::APIError.new('Unknown API response', response) end end end end
true
28aab4056689a65fb3c8227c4b3b7cf0099bce5e
Ruby
walterchabla/phase-0-tracks
/ruby/gps6/my_solution.rb
UTF-8
3,841
4.40625
4
[]
no_license
# Virus Predictor # I worked on this challenge [by myself]. # We spent [2] hours on this challenge. # EXPLANATION OF require_relative #require_relative is having the code from another file being avaliable in this file, using a relative path. #require would work for files that are outside the directory or folder, is like using a load path. require_relative 'state_data' class VirusPredictor #It declares the instence variable and sets the instance variable to the arguments, and its the first thing it runs. def initialize(state_of_origin, population_density, population) @state = state_of_origin @population = population @population_density = population_density end #Its calling private methods def virus_effects predicted_deaths speed_of_spread end private #predictcs number of deaths and prints a string. def predicted_deaths # predicted deaths is solely based on population density number_of_deaths = 0 density_deaths = {'200' => 0.4, '150' => 0.3, '100' => 0.2, '50' => 0.1, '0' => 0.05} density_deaths.each do |density, rate| if @population_density >= density_deaths[density].to_i number_of_deaths = (@population * rate).floor end end print "#{@state} will lose #{number_of_deaths} people in this outbreak" end # it will print a string of how long it will take to spread base on the population density def speed_of_spread #in months # We are still perfecting our formula here. The speed is also affected # by additional factors we haven't added into this functionality. speed = 0.0 density_speed = {'200' => 0.5, '150' => 1, '100' => 1.5, '50' => 2, '0' => 2.5} density_speed.each do |density, rate| if @population_density >= density.to_i speed += rate end end puts " and will spread across the state in #{speed} months.\n\n" end end #======================================================================= # DRIVER CODE # initialize VirusPredictor for each state STATE_DATA.each do |state_name, value| VirusPredictor.new(state_name, STATE_DATA[state_name][:population_density], STATE_DATA[state_name][:population]).virus_effects end alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population]) alabama.virus_effects jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population]) jersey.virus_effects california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population]) california.virus_effects alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population]) alaska.virus_effects #======================================================================= # Reflection Section # The difference between the two different hash syntaxes are that when you use '=>' you can use another hash inside the hash as its value or declare the variable, and when you use the collins you are declaring the key and giving the value, example: key: value. #require_relative is having the code from another file being avaliable in this file in a relative path. require_relative works if your in the same folder or directory, as require would work for files that are outside the directory or folder using a load path that will look all the files. # some ways to iterate through a hash is using #each, #sort and while. # When refactoring virus_effects what stood out about the variables were that they where instance variables and that they were already being initialiaze in the method initialize. # the concepts that I solidify in this challenge were using require_relative and working with class and methods, and how to iterate throught a hash.
true
53c23dff0cb815e1908f3a477161514b412d8be0
Ruby
nkinney/rrobots
/PolarIce/Driver.rb
UTF-8
3,776
3.15625
3
[]
no_license
#The Driver is responsible for turning and moving the tank. class Driver include Rotator MAXIMUM_ROTATION = 10 INITIAL_ROTATION = 0 INITIAL_DESIRED_HEADING = nil INITIAL_DESIRED_POSITION = nil MAXIMUM_SPEED = 8 MAXIMUM_ACCELERATION = 1 INITIAL_ACCELERATION_RATE = 0 INITIAL_DESIRED_SPEED = 0 INITIAL_DESIRED_MAXIMUM_SPEED = 8 def tick @state_machine.tick end def update_state(position, heading, speed) @current_position = position @current_heading = heading @current_speed = speed end def initialize_state_machine driver = self @state_machine = Statemachine.build do context driver state :awaiting_orders do on_entry :awaiting_orders event :tick, :awaiting_orders, :default_tick event :lock, :locked event :stop, :stop end state :stop do on_entry :do_stop event :tick, :wait_for_stop, :default_tick end state :wait_for_stop do on_entry :wait_for_stop event :stopped, :awaiting_orders event :stopping, :stop end state :locked do on_entry :locked event :tick, :locked, :locked_tick event :lock, :locked event :unlock, :awaiting_orders end end end def awaiting_orders log "driver.awaiting_orders\n" @desired_speed = 8 @rotation = 10 end def stop log "driver.stop\n" @state_machine.stop end def do_stop log "driver.do_stop\n" @desired_speed = 0 @desired_target = nil # @state_machine.tick end def wait_for_stop log "driver.wait_for_stop\n" if (@current_speed == 0) stopped else stopping end end def stopped log "driver.stopped\n" @state_machine.stopped polarIce.stopped end def stopping log "driver.stopping\n" @state_machine.stopping end def lock log "driver.lock\n" @state_machine.lock @desired_speed = 0 end def locked log "driver.locked\n" end def locked_tick rotator_tick accelerate if @current_speed != nil && @desired_speed != nil calculate_new_position end def unlock log "driver.unlock\n" @state_machine.unlock end def default_tick rotator_tick move if @current_position != nil && @desired_target != nil accelerate if @current_speed != nil && @desired_speed != nil calculate_new_position end def move @desired_speed = calculate_desired_speed end def calculate_desired_speed Math.sqrt(current_position.distance_to(@desired_target)).floor.clamp(MAXIMUM_SPEED).clamp(@desired_max_speed) end def accelerate @acceleration = calculate_acceleration end def calculate_acceleration (@desired_speed - @current_speed).clamp(MAXIMUM_ACCELERATION) end def calculate_new_position new_speed = @current_speed + @acceleration new_heading = @current_heading + @rotation @new_position = @current_position + Vector[new_heading, new_speed].to_cartesian end def initialize polarIce @polarIce = polarIce @max_rotation = MAXIMUM_ROTATION @acceleration = INITIAL_ACCELERATION_RATE @rotation = INITIAL_ROTATION @desired_heading = INITIAL_DESIRED_HEADING @desired_target = INITIAL_DESIRED_POSITION @desired_speed = INITIAL_DESIRED_SPEED @desired_max_speed = INITIAL_DESIRED_MAXIMUM_SPEED initialize_state_machine end attr_accessor(:current_speed) attr_accessor(:desired_speed) attr_accessor(:desired_max_speed) attr_accessor(:acceleration) attr_accessor(:new_position) attr_accessor(:polarIce) end
true
b5448977c7b7a4cee4914e8fce2367d1dad4e630
Ruby
elzj/ao3_api
/app/archive_search/search/range_parser.rb
UTF-8
3,193
3.28125
3
[]
no_license
# frozen_string_literal: true module Search # Handles user-inputted rangelike data and outputs # actual number and date ranges if possible class RangeParser TIME_REGEX = %r{ ^(?<operand>[<>]*)\s* (?<amount>[\d -]+)\s* (?<period>year|week|month|day|hour)s? (?<ago>\s*ago)?\s*$ }xi NUMBER_REGEX = %r{ ^(?<operand>[<>]*)\s*(?<value>[\d,. -]+)\s*$ }xi def self.string_to_range(str) new(str).parse end attr_reader :text_range def initialize(text_range) @text_range = unescape(text_range.to_s) end def parse if match = text_range.match(TIME_REGEX) parse_time( operand: match[:operand], amount: match[:amount], period: match[:period] ) elsif match = text_range.match(NUMBER_REGEX) parse_numbers( operand: match[:operand], value: match[:value] ) else {} end end # Examples: "<1 week ago", "> 6 months ago", "1-3 hours ago" def parse_time(operand:, amount:, period:) case operand when "<" { gte: time_from_string(amount, period) } when ">" { lte: time_from_string(amount, period) } when "" match = amount.match(/-/) if match { gte: time_from_string(match.pre_match, period), lte: time_from_string(match.post_match, period) } else range_from_string(amount, period) end end end # This is for form fields where you're asking for items with # a certain number of comments, bookmarks, words, etc. # Examples: "> 100", "<10", "1,000 - 10,0000" def parse_numbers(operand:, value:) case operand when "<" { lte: sanitize_integer(value) } when ">" { gte: sanitize_integer(value) } when "" match = value.match(/-/) if match { gte: sanitize_integer(match.pre_match), lte: sanitize_integer(match.post_match) } else { gte: sanitize_integer(value), lte: sanitize_integer(value) } end end end private # helper method to create times from two strings def time_from_string(amount, period) sanitize_date(amount.to_i.send(period).ago) end # Generate a range based on one number # Interval is based on period used, ie 1 month ago = range from beginning to end of month def range_from_string(amount, period) amount = amount.to_i period = period.singularize min = amount.send(period).ago.send("beginning_of_#{period}") max = min.send("end_of_#{period}") min, max = [min, max].map { |date| sanitize_date(date) } { gte: min, lte: max } end def unescape(str) str.gsub("&gt;", ">").gsub("&lt;", "<").downcase end # Convert strings with comma/period separators def sanitize_integer(number) Search::Sanitizer.sanitize_integer(number) end # Keeping date logic in one place def sanitize_date(date) Search::Sanitizer.sanitize_date(date) end end end
true
fdcc7480853a603d69e61c62ab1d719ea10a82da
Ruby
danstutzman/generate-bilingual-sentence-pairs
/OLD/load_spanish.rb
UTF-8
14,859
2.59375
3
[]
no_license
require 'pp' require './models_fast' VOCAB_HEIGHT = 1 SUFFIX_HEIGHT = 1 STEM_HEIGHT = 1 CONJUGATION_HEIGHT = 2 TEMPLATE_HEIGHT = 3 PHRASE_HEIGHT = 4 SENTENCE_HEIGHT = 5 def to_sentence s s[0].upcase + s[1..-1] + '.' end connect_to_db! true new_prompt 'vocab_l1', 'vocab_l2', 'Translate to Spanish:' new_prompt 'vocab_l2', 'vocab_l1', 'Translate to English:' new_prompt 'conjugation_l1', 'conjugation_l2', 'Translate to Spanish:' new_prompt 'conjugation_l2', 'conjugation_l1', 'Translate to English:' new_prompt 'phrase_l1', 'phrase_l2', 'Translate to Spanish:' new_prompt 'phrase_l2', 'phrase_l1', 'Translate to English:' new_prompt 'l2_irregular_infinitive', 'l2_irregular_stem', "What's the irregular stem for:" new_prompt 'l2_irregular_stem', 'l2_irregular_infinitive', "What verb and tense does this irregular stem go to?" new_prompt 'suffix_l2', 'features_l2', "What tense, person, and number does this verb suffix mean?" new_prompt 'features_l2', 'suffix_l2', "What's the suffix for this tense, person, and number?" new_prompt 'l1_vp_template', 'l2_vp_template', 'Translate to Spanish:' new_prompt 'l2_vp_template', 'l1_vp_template', 'Translate to English:' new_prompt 'l1_sentence', 'l2_sentence', 'Translate to Spanish:' new_prompt 'l2_sentence', 'l1_sentence', 'Translate to English:' $nouns_that_are_written = [] $nouns_that_are_persons = [] $nouns_that_need_determiner = {} %q[ 1 el the(m) . . . 1 la the(f) . . . 1 un a(m) . . . 1 una a(f) . . . 1 billete ticket x . x 1 chaqueta jacket . . x 1 algo something x . . 1 alguien someone . x . ].split("\n").reject { |line| line == '' }.each do |line| _, level, vocab_l2, vocab_l1, is_writing, is_person, needs_determiner = line.split(/\s+/) vocab_l1 = new_concept 'vocab_l1', vocab_l1, level, false vocab_l2 = new_concept 'vocab_l2', vocab_l2, level, true arc = new_arc VOCAB_HEIGHT, vocab_l1, vocab_l2, true $nouns_that_are_written.push arc if is_writing == 'x' $nouns_that_are_persons.push arc if is_person == 'x' $nouns_that_need_determiner[vocab_l2.content] = true if needs_determiner == 'x' end %q[ the(m) ticket |el billete the(f) jacket |la chaqueta a(m) ticket |un billete a(f) jacket |una chaqueta ].split("\n").reject { |line| line == '' }.each do |line| phrase_l1, phrase_l2 = line.split('|').map { |field| field.strip } determiner_l1, noun_l1 = phrase_l1.split(' ') determiner_l1 = $concept_by_type_and_content[['vocab_l1', determiner_l1]] noun_l1 = $concept_by_type_and_content[['vocab_l1', noun_l1]] determiner_l1_arc = $arc_by_from_concept_and_to_concept_type[ [determiner_l1, 'vocab_l2']] level = [noun_l1.level, determiner_l1.level].max phrase_l1 = new_concept 'phrase_l1', phrase_l1, level, false phrase_l2 = new_concept 'phrase_l2', phrase_l2, level, true arc = new_arc PHRASE_HEIGHT, phrase_l1, phrase_l2, true noun_l1_arc = $arc_by_from_concept_and_to_concept_type[[noun_l1, 'vocab_l2']] arc.add_part_arcs! [determiner_l1_arc, noun_l1_arc] reverse_arc(arc).add_part_arcs! \ [reverse_arc(determiner_l1_arc), reverse_arc(noun_l1_arc)] end # Definitions of verbs $l1_infinitive_to_l1_past = {} $l2_verbs_ending_with = {} %q[ 1 hablar talk talked 1 comer eat ate 1 vivir live lived 1 andar walk walked 1 ser be were 1 estar be were 1 tener have had 1 hacer do did 1 decir say said 1 ir go went 1 ver see saw 1 dar give gave 1 saber know knew 1 venir come came 1 salir leave left 1 querer want wanted 1 poner put put 1 leer read read 1 parecer appear appeared 1 conocer know knew 1 escribir write wrote ].split("\n").reject { |line| line == '' }.each do |line| _, level, l2, l1, l1_past = line.split(/\s+/) $l1_infinitive_to_l1_past[l1] = l1_past l1 = new_concept 'vocab_l1', l1, level, false l2 = new_concept 'vocab_l2', l2, level, true arc = new_arc VOCAB_HEIGHT, l1, l2, true suffix = '-' + l2.content[-2..-1] $l2_verbs_ending_with[suffix] ||= [] $l2_verbs_ending_with[suffix].push arc end # Special present conjugations %q[ 1 ser pret 1 s soy 1 ser pret 2 s eres 1 ser pres 3 s es 1 ser pres 1 p somos 1 ser pres 3 p son 1 estar pres 1 s estoy 1 estar pres 2 s estás 1 estar pres 3 s está 1 estar pres 3 p están 1 tener pres 1 s tengo 1 hacer pres 1 s hago 1 decir pres 1 s digo 1 decir pret 3 p dijeron 1 ir pres 1 s voy 1 ir pres 2 s vas 1 ir pres 3 s va 1 ir pres 1 p vamos 1 ir pres 3 p van 1 ir pret 1 s fui 1 ir pret 2 s fuiste 1 ir pret 3 s fue 1 ir pret 1 p fuimos 1 ir pret 3 p fueron 1 ver pres 1 s veo 1 dar pres 1 s doy 1 dar pret 1 s di 1 dar pret 2 s diste 1 dar pret 3 s dio 1 dar pret 1 p dimos 1 dar pret 3 p dieron 1 saber pres 1 s sé 1 poner pres 1 s pongo 1 venir pres 1 s vengo 1 salir pres 1 s salgo 1 parecer pres 1 s parezco 1 conocer pres 1 s conozco ].split("\n").reject { |line| line == '' }.each do |line| _, level, infinitive_l2, tense, person, number, conjugation_l2 = line.split(/\s+/) infinitive_l2 = $concept_by_type_and_content[['vocab_l2', infinitive_l2]] infinitive_arc = reverse_arc( $arc_by_from_concept_and_to_concept_type[[infinitive_l2, 'vocab_l1']]) conjugation_l1 = infinitive_arc.from_concept.content if tense == 'pret' conjugation_l1 = $l1_infinitive_to_l1_past.fetch(conjugation_l1) end conjugation_l1 = "#{conjugation_l1}(#{person},#{number})" conjugation_l1 = new_concept 'conjugation_l1', conjugation_l1, level, false conjugation_l2 = new_concept 'conjugation_l2', conjugation_l2, level, true arc = new_arc STEM_HEIGHT, conjugation_l1, conjugation_l2, true # Probably memorized directly without falling back to infinitive #arc.add_part_arcs! [infinitive_arc] #reverse_arc(arc).add_part_arcs! [reverse_arc(infinitive_arc)] end # Stem changers %q[ 1 pres poder pued- 1 pres tener tien- 1 pres querer quier- 1 pres seguir sig- 1 pres encontrar encuentr- 1 pres venir vien- 1 pres pensar piens- 1 pres volver vuelv- 1 pres sentir sient- 1 pres contar cuent- 1 pres empezar empiez- 1 pres decir di- 1 pret andar anduv- 1 pret saber sup- 1 pret querer quis- 1 pret poner pus- 1 pret venir vin- 1 pret decir dij- ].split("\n").reject { |line| line == '' }.each do |line| _, level, tense, l2_infinitive, l2_irregular_stem = line.split(/\s+/) l2_irregular_infinitive = "#{l2_infinitive}(#{tense})" l2_irregular_infinitive = new_concept 'l2_irregular_infinitive', l2_irregular_infinitive, level, true l2_irregular_stem = new_concept 'l2_irregular_stem', l2_irregular_stem, level, true stem_arc = new_arc STEM_HEIGHT, l2_irregular_infinitive, l2_irregular_stem, true if tense == 'pret' %q[ 21 1 s -e 21 2 s -iste 21 3 s -o 21 1 p -imos 21 3 p -ieron ].split("\n").reject { |line2| line2.strip == '' }.each do |line2| _, suffix_level, person, number, suffix = line2.split(/\s+/) features = "(#{tense},#{person},#{number}) for irregular verbs" features = $concept_by_type_and_content[['features_l2', features]] || new_concept('features_l2', features, suffix_level, false) suffix_description = "#{suffix} for irregular verbs" suffix_description = $concept_by_type_and_content[['suffix_l2', suffix]] || new_concept('suffix_l2', suffix_description, suffix_level, true) suffix_arc = new_arc SUFFIX_HEIGHT, features, suffix_description, true l2_infinitive_concept = $concept_by_type_and_content.fetch(['vocab_l2', l2_infinitive]) infinitive_arc = reverse_arc($arc_by_from_concept_and_to_concept_type.fetch( [l2_infinitive_concept, 'vocab_l1'])) conjugation_l1 = $l1_infinitive_to_l1_past.fetch( infinitive_arc.from_concept.content) conjugation_l1 = new_concept 'conjugation_l1', "#{conjugation_l1}(#{person},#{number})", level, false conjugation_l2 = new_concept 'conjugation_l2', l2_irregular_stem.content[0...-1] + suffix[1..-1], level, true conjugation_arc = new_arc CONJUGATION_HEIGHT, conjugation_l1, conjugation_l2, true part_arcs = [infinitive_arc, stem_arc, suffix_arc].compact part_arcs2 = [stem_arc, infinitive_arc, suffix_arc].compact conjugation_arc.add_part_arcs! part_arcs reverse_arc(conjugation_arc).add_part_arcs!( part_arcs2.map { |arc| reverse_arc(arc) }) end end end [[$l2_verbs_ending_with['-ar'], '-ar verb', %q[ 11 pres 1 s -o 12 pres 2 s -as 13 pres 3 s -a 14 pres 1 p -amos 15 pres 3 p -an 21 pret 1 s -é 22 pret 2 s -aste 23 pret 3 s -ó 24 pret 1 p -amos 25 pret 3 p -aron]], [$l2_verbs_ending_with['-er'] + $l2_verbs_ending_with['-ir'], '-er and -ir verbs', %q[ 11 pres 1 s -o 12 pres 2 s -es 13 pres 3 s -e 14 pres 3 p -en 11 pret 1 s -í 12 pret 2 s -iste 13 pret 3 s -ió 11 pret 1 p -imos 13 pret 3 p -ieron]], [$l2_verbs_ending_with['-er'], '-er verb', %q[ 14 pres 1 p -emos]], [$l2_verbs_ending_with['-ir'], '-ir verb', %q[ 14 pres 1 p -imos]], ].each do |infinitive_arcs, verb_type, conjugation_table| for infinitive_arc in infinitive_arcs conjugation_table.split("\n").reject { |line2| line2.strip == '' }.each do |line2| _, suffix_level, tense, person, number, suffix = line2.split(/\s+/) features = "(#{tense},#{person},#{number}) for #{verb_type}" features = $concept_by_type_and_content[['features_l2', features]] || new_concept('features_l2', features, suffix_level, false) suffix_description = "#{suffix} for #{verb_type}" suffix_description = $concept_by_type_and_content[['suffix_l2', suffix]] || new_concept('suffix_l2', suffix_description, suffix_level, true) suffix_arc = new_arc SUFFIX_HEIGHT, features, suffix_description, true conjugation_level = [infinitive_arc.level, suffix_level.to_i].max conjugation_l1 = case tense when 'pres' infinitive_arc.from_concept.content when 'pret' $l1_infinitive_to_l1_past[infinitive_arc.from_concept.content] else raise "Don't know tense #{tense}" end conjugation_l1 = "#{conjugation_l1}(#{person},#{number})" if $concept_by_type_and_content[['conjugation_l1', conjugation_l1]] # don't create conjugation; it was already created else conjugation_l1 = new_concept 'conjugation_l1', conjugation_l1, conjugation_level, false if [tense, person, number] == ['pres', '1', 'p'] # then don't look for an irregular stem possible_l2_irregular_stem = nil else possible_l2_irregular_stem = $concept_by_type_and_content[ ['l2_irregular_infinitive', "#{infinitive_arc.to_concept.content}(#{tense})"]] possible_l2_irregular_stem = $arc_by_from_concept_and_to_concept_type[ [possible_l2_irregular_stem, 'l2_irregular_stem']] end l2_stem = possible_l2_irregular_stem ? possible_l2_irregular_stem.to_concept.content[0...-1] : infinitive_arc.to_concept.content[0...-2] conjugation_l2 = new_concept 'conjugation_l2', l2_stem + suffix[1..-1], conjugation_level, true conjugation_arc = new_arc CONJUGATION_HEIGHT, conjugation_l1, conjugation_l2, true part_arcs = [infinitive_arc, possible_l2_irregular_stem, suffix_arc].compact part_arcs2 = [possible_l2_irregular_stem, infinitive_arc, suffix_arc].compact conjugation_arc.add_part_arcs! part_arcs reverse_arc(conjugation_arc).add_part_arcs!( part_arcs2.map { |arc| reverse_arc(arc) }) end end # next conjugation end # next verb end # next verb type %q[ 1 | leer algo | to read something |x 1 | escribir algo a alguien | to write something to someone |x ].split("\n").reject { |line| line == '' }.each do |line| level, l2_vp_template, l1_vp_template, something_written = line.split('|').map { |part| part.strip } l1_words = l1_vp_template.split(' ') part_arcs = [] l2_words = l2_vp_template.split(' ') l2_verb = $concept_by_type_and_content.fetch(['vocab_l2', l2_words.first]) part_arcs.push reverse_arc( $arc_by_from_concept_and_to_concept_type.fetch([l2_verb, 'vocab_l1'])) for template_word in ['algo', 'alguien'] if l2_words.include? template_word part_arcs.push reverse_arc($arc_by_from_concept_and_to_concept_type.fetch( [$concept_by_type_and_content.fetch(['vocab_l2', template_word]), 'vocab_l1'])) end end l1_vp_template = new_concept 'l1_vp_template', l1_vp_template, level, false l2_vp_template = new_concept 'l2_vp_template', l2_vp_template, level, true arc = new_arc TEMPLATE_HEIGHT, l1_vp_template, l2_vp_template, true arc.add_part_arcs! part_arcs reverse_arc(arc).add_part_arcs! part_arcs.map { |arc| reverse_arc(arc) } %q[ 1 s I 2 s you 3 s he/she 1 p we 3 p they ].split("\n").reject { |line| line.strip == '' }.each do |line| _, person, number, l1_pronoun = line.split(/\s+/) l1_conjugation = "#{l1_words[1]}(#{person},#{number})" l1_conjugation = $concept_by_type_and_content.fetch( ['conjugation_l1', l1_conjugation]) l2_conjugation_arc = $arc_by_from_concept_and_to_concept_type.fetch( [l1_conjugation, 'conjugation_l2']) l2_conjugation = l2_conjugation_arc.to_concept.content if something_written == 'x' for noun_arc in $nouns_that_are_written l1_verb = l1_words[1] l1_verb += 's' if [person, number] == ['3', 's'] l1_noun = noun_arc.from_concept.content l2_noun = noun_arc.to_concept.content if $nouns_that_need_determiner[l2_noun] l1_noun = "a #{l1_noun}" l2_noun = "un/una #{l2_noun}" end l1_sentence = to_sentence([l1_pronoun, l1_verb, l1_noun].join(' ')) l1_sentence = new_concept 'l1_sentence', l1_sentence, 1, false l2_sentence = to_sentence([l2_conjugation, l2_noun].join(' ')) l2_sentence = new_concept 'l2_sentence', l2_sentence, 1, true sentence_arc = new_arc SENTENCE_HEIGHT, l1_sentence, l2_sentence, true sentence_arc.add_part_arcs! [l2_conjugation_arc, noun_arc] reverse_arc(sentence_arc).add_part_arcs! [reverse_arc(l2_conjugation_arc), reverse_arc(noun_arc)] end end end end persist_to_db!
true
adfa701b63ae2a1e702d86adbcb06ecabf2dec51
Ruby
markandrus/Templatron
/util/makeMasthead.rb
UTF-8
619
2.546875
3
[]
no_license
#! /usr/local/bin/ruby require 'rubygems' begin require 'RMagick' include Magick def makeMasthead(title, outputPng) title.strip! text = Draw.new text.font = 'Gotham-Rounded-Light' text.pointsize = 28 text.gravity = SouthWestGravity hdr = Image.new(650, 53) { self.background_color = 'none' } text.annotate(hdr, 0, 0, 0, 0, title) { self.fill = 'white' } hdr.write(outputPng) return true end rescue LoadError puts "WARNING: You do not have RMagick installed. This script will not be able to generate `masthead.png' for the new site." def makeMasthead(title, outputPng) return false end end
true
bc66e38c1da28cff12a94ccfb82bbf6d8c11c033
Ruby
Derikulous/interview_prep
/ruby/max_value.rb
UTF-8
1,304
4.4375
4
[]
no_license
# 4) Your task is to # • write a function that computes the maximum value among the deviations of all the sequences considered above # • print the value the standard output (stdout) # Note that your function will receive the following arguments: # • v # o which is the array of integers # • d # o which is an integer value giving the length of the sequences # Data constraints # • the array will contain up to 100,000 elements # • all the elements in the array are integer numbers in the following range: [1, 231 -1] # • the value of d will not exceed the length of the given array # Efficiency constraints # • your function is expected to print the result in less than 2 seconds # Input Output # v: 6, 9, 4, 7, 4, 1 # d: 3 6 # The sequences of length 3 are: # • 6 9 4 having the median 5 (the minimum value in the sequence is 4 and the maximum is 9) # • 9 4 7 having the median 5 (the minimum value in the sequence is 4 and the maximum is 9) # • 7 4 1 having the median 6 (the minimum value in the sequence is 1 and the maximum is 7) # • The maximum value among all medians is 6 # def find_deviation(v, d) # # Write your code here # # To print results to the standard output you can use puts # # Example puts "Hello world!" # end
true
d0107fa9882c2014ca4c29b1b925fa55cfaf4811
Ruby
mudasobwa/profigure
/lib/profigure.rb
UTF-8
4,339
3.234375
3
[ "MIT" ]
permissive
require 'profigure/version' require 'hash_deep_merge' # @author Alexei Matyushkin # # Module to use as is, to monkeypatch it, or to extend in order to have # nice and easy config files support. # # It’s designed to be as intuitive as possible. # # _Usages:_ # # Say, we have the following `config.yml` file: # # :version : '0.0.1' # :nested : # :sublevel : # :value : 'test' # :url : 'http://example.com' # :configs : # - 'config/test1.yml' # - 'config/test2.yml' # # Then: # # config = (Profigure.load 'config/config.yml').configure do # set :foo, 'bar' # set :fruits, ['orange', 'apple', 'banana'] # end # # puts config.nested.sublevel.value # # ⇒ 'test' # config.nested = { :newvalue => 'test5' } # # ⇒ 'test5' # # _Setting deeply nested values with this syntax is **not yet allowed**._ # # ---- # # The handlers for `YAML` section might be specified with double underscore. # When set, the handler will be called with value to operate it. # # As an example, let’s take a look at the following code: # # module ProfigureExt # extend Profigure # # def self.__configs key, *args # key = [*args] unless (args.empty?) # setter # # @configs ||= ProfigureExt.clone # @configs.clear # # key.each { |inc| @configs.push inc } unless key.nil? # # @configs.to_hash # end # end # # Here the handler is defined for `configs` section. Once found, the section # will be passed to this handler, which apparently loads the content of # included config files. # # *NB* The name alludes both to “pro” vs. “con” and to “pro” vs. “lite”. Enjoy. # module Profigure # Methods to propagate to modules which will `extend Profigure` module ClassMethods # A wrapper for the configuration block # @param block the block to be executed in the context of this module def configure &block instance_eval(&block) end # Getter for values by keys # @param key the key to retrieve the value for # @return the value retrieven def [] key Hash === config[key.to_sym] ? self.clone.push(config[key.to_sym]) : config[key.to_sym] end # Setter for values by keys # @param key the key to set the value for # @return the value set def []= key, value config[key.to_sym] = value end # Clears the underlying hash # @return `self` def clear @config = {} self end # Loads parameters from `stream`, file by `filename` or `hash`. Inits # the underlying hash empty when called without args # @return `self` def push input = nil config.deep_merge! case input when IO then YAML.load_stream(input) when String then YAML.load_file(input) when Hash then input else {} end self end alias_method :load, :push # Saves the properties to a file # @return the result of respective `File.write` operation def store file File.write file, YAML.dump(to_hash) end # @return Read-only copy of the underlying hash def to_hash config.clone end # @return Empty initialized instance def instance @instance ||= self.push end private def set(key, value) config[key.to_sym] = value end def add(key, value) config[key.to_sym] = [*config[key.to_sym]] << value end def config (@config ||= {})[self] ||= Hash.new end def method_missing sym, *args, &cb if sym =~ /(.+)=$/ sym = $1.to_sym method(:"__#{sym}").call(args.first, args) if singleton_methods.include?(:"__#{sym}") self[sym] = args.first else singleton_methods.include?(:"__#{sym}") ? method(:"__#{sym}").call(self[sym]) : self[sym] end end end extend ClassMethods def self.extended other other.extend ClassMethods end end module ProfigureExt extend Profigure def self.__configs key, *args key = [*args] unless (args.empty?) # setter @configs ||= ProfigureExt.clone @configs.clear key.each { |inc| @configs.push inc } unless key.nil? @configs.to_hash end end
true
52fb375bee18bcbb76a9264915a3804188cb5520
Ruby
ymdelgado/ruby-gol
/Player.rb
UTF-8
1,926
3.5
4
[]
no_license
require_relative 'Cell' require_relative 'Grid' class Player attr_accessor :timeinterval attr_accessor :rows, :cols attr_reader :grid attr_accessor :actions def initialize @rows, @cols= 10, 10 @timeinterval= 1 self.menu_actions end def menu_actions system('clear') #STDOUT.flush puts "="*50 puts "Give an action:" puts "="*50 puts "set grid size (def 10,10) --> size>###, ###" puts "set timeinterval (def 1) --> time>number(1..10)" puts "initialize grid --> init" puts "run --> run" puts "clear grid --> clear" puts "exit --> exit or word unrecognized" puts "="*50 if(@grid) @grid.draw end puts "enter command... " @actions = gets.chomp self.proc_actions end def proc_actions if(@actions!="") x= @actions.split('>') case x[0].downcase when "init" @grid= Grid.new(@rows, @cols) self.menu_actions when "size" rc= x[1].split(',') @rows, @cols = rc[0].to_i, rc[1].to_i @grid= Grid.new(@rows, @cols) self.menu_actions when "time" @timeinterval = x[1].to_i self.menu_actions when "clear" @grid.clear self.menu_actions when "run" if(!@grid) @grid= Grid.new(@rows,@cols) end # create a process to contain a thread for # execution of infinite loop and wait for # a key to kill the thread t = Thread.new do i = 0 while true system 'clear' @grid.play puts "\n<enter> to stop >> " sleep(@timeinterval) end end gets t.kill self.menu_actions end end end end
true
51dd053549734ec8da2ac46c57bb5dbe71701e7b
Ruby
sogilis/csv_fast_importer
/rakelib/release.rb
UTF-8
1,392
2.703125
3
[ "MIT" ]
permissive
require './rakelib/repository' require './rakelib/changelog' class Release GEM_NAME = 'csv_fast_importer' VERSION_FILE = 'lib/csv_fast_importer/version.rb' GEMFILE_LOCK = 'Gemfile.lock' def initialize(type) @type = type end def last_version CSVFastImporter::VERSION end def version @version ||= bump(last_version, @type) end def apply! sub_file_content VERSION_FILE, last_version, version sub_file_content GEMFILE_LOCK, "#{GEM_NAME} (#{last_version})", "#{GEM_NAME} (#{version})" end def changelog @changelog ||= Changelog.parse(Repository.log_from("v#{last_version}")) end def git_commit `git add #{VERSION_FILE} #{GEMFILE_LOCK}` `git commit -m 'Chore / Change version to #{version}'` end private def bump(version, bump_type) major, minor, patch = version.split(".").map(&:to_i) if bump_type == 'major' major += 1 minor = 0 patch = 0 elsif bump_type == 'minor' minor += 1 patch = 0 else patch += 1 end [major, minor, patch].join(".") end def sub_file_content(file_path, from, to) current_content = File.read(file_path) modified_content = current_content.sub(from, to) raise "Cannot find regexp #{from} in file #{file_path}" if modified_content == current_content File.open(file_path, "w") { |file| file << modified_content } end end
true
aa4b98e10614680da71e0dd6f429c26f03475474
Ruby
grosscol/auto_toggl
/lib/backfill.rb
UTF-8
1,581
2.65625
3
[]
no_license
require 'togglv8' require 'date' require 'yaml' require 'pry' # Read the config cfg = YAML.load_file('./config/auto_toggl.yml') api_token = cfg["api_token"] default_workspace_id = cfg["default_workspace_id"] proj_id=cfg["default_project_id"] # Have token or die abort("no api_token") unless api_token # Configure the api interface toggl_api = TogglV8::API.new(api_token) user = toggl_api.me(all=true) workspaces = toggl_api.my_workspaces(user) ws_id = default_workspace_id || workspaces.first['id'] # Since, January 1, 2016, to today, check if they're an entry, and create one if not. Date.new(2016,01,01).upto(Date.today) do |dt| puts "Checking for #{dt.iso8601} weekday: #{dt.cwday}" # Check to see if there is an entry for current day. start_date = DateTime.new(dt.year, dt.month, dt.day, 0) end_date = DateTime.new(dt.year, dt.month, dt.day, 23) today_entries = toggl_api.get_time_entries({ start_date: start_date.iso8601, end_date: end_date.iso8601 }) # Make entry unless is a saturday or sunday or entry exists. if today_entries.size < 1 && !dt.saturday? && !dt.sunday? sleep 2 start_time = DateTime.new(dt.year, dt.month, dt.day, 8, 03, 00, "-0400") puts "making entry for #{start_time}" toggl_api.create_time_entry({ 'description' => "Hydra Work", 'wid' => ws_id, 'pid' => proj_id, 'duration' => 26640, 'start' => start_time.iso8601, 'tags' => ['development'], 'created_with' => "Otto T. Oggle" }) else puts "Entry exits or is saturday or is sunday" end end
true
a2cdbfa759eee9d805d90f47902cd2be09283c7d
Ruby
notnotdrew/project-euler-multiples-3-5-web-0715-public
/lib/oo_multiples.rb
UTF-8
341
3.5
4
[]
no_license
class Multiples attr_reader :limit def initialize(limit) @limit = limit end def collect_multiples (1...limit).select { |n| multiple_of?([3, 5], n) } end def sum_multiples collect_multiples.reduce(&:+) end private def multiple_of?(divisors, candidate) divisors.any? { |d| candidate % d == 0 } end end
true
98006b24282b2e4313140efd1e1e3cf744f1e878
Ruby
Dudu197/figurinhas-copa-2018
/app/models/calculate.rb
UTF-8
562
2.8125
3
[]
no_license
class Calculate include ActiveModel::Model attr_accessor :repited_str, :needed_str, :to_send, :to_receive, :calculated def calculate self.to_send = [] self.to_receive = [] my_repited = Repited.pluck(:number) my_needed = Needed.pluck(:number) self.repited_str.split(",").each do |number| self.to_receive << number.to_i if my_needed.include? number.to_i end self.needed_str.split(",").each do |number| self.to_send << number.to_i if my_repited.include? number.to_i end self.calculated = true end end
true
838aff9bc569a7f9179667a11697cdfc89530272
Ruby
Ugats/Ruby-Practice
/chapter07a.rb
UTF-8
283
3.515625
4
[]
no_license
# encoding: utf-8 arr = [] is_Enter = false puts '好きな英単語を入力してください(いくつでも)' while is_Enter == false word = gets.chomp if word == '' is_Enter = true else arr << word end end sort_arr = arr.sort sort_arr.each do |word| puts word end
true
f6452504023dce12a1cd4f25b346aea8391e822d
Ruby
sebastianalamina/MyP_2020-1_Proyecto3
/code/interfaz/TableroInterfaz.rb
UTF-8
685
3.09375
3
[]
no_license
require_relative '../Tablero' require_relative './CasillaInterfaz' # Clase que representa un tablero en la interfaz. class TableroInterfaz attr_reader :casillas # Inicializador de un tablero para la interfaz. def initialize(tablero) # Se asocia un tablero de ajedrez. @tablero = tablero # Se crea un diccionario con todas las casillas del tablero. @casillas = [] # Se agrega cada casilla al diccionario. for col in (1..8) for ren in (1..8) bool = (col+ren) % 2 == 0 color = bool ? 0 : 4095 pieza = tablero.getPieza(col, ren) @casillas.push( CasillaInterfaz.new(col, ren, color, pieza) ) end end end end
true
bf3d6b379b3a99d20d036223d2cdaead851f3bf5
Ruby
souleyman26/nouveau
/exo_05.rb
UTF-8
764
3.828125
4
[]
no_license
puts "On va compter le nombre d'heures de travail à THP" puts "Travail : #{10 * 5 * 11}"#multiplie entre puts "En minutes ça fait : #{10 * 5 * 11 * 60}"# multiplie entre tjrs puts "Et en secondes ?" puts 10 * 5 * 11 * 60 * 60 # c'est un resultat puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?" # boléen puts 3 + 2 < 5 - 7 puts "Ça fait combien 3 + 2 ? #{3 + 2}" #il calcul dans les parenthèse puts "Ça fait combien 5 - 7 ? #{5 - 7}" #il calcul dans la parenthèse soustraction puts "Ok, c'est faux alors !"# puts "C'est drôle ça, faisons-en plus :" puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}" puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}"#boléen puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" #boléen
true
c65ee2c2a3dc5cb34a23d5d3cd26d152447d47b3
Ruby
smunozmo/oop-school-library
/spec/solver_spec.rb
UTF-8
1,471
3.640625
4
[]
no_license
require_relative '../solver' describe 'Solver class' do context 'Runing Solver' do it 'Should the factorial of 5' do solver = Solver.new result = solver.factorial(5) expect(result).to eq 120 end it 'Should resturn 0' do solver = Solver.new result = solver.factorial(0) expect(result).to eq 0 end it 'Should resturn erros' do solver = Solver.new result = solver.factorial(-5) expect(result).to eq 'Math Error' end end context 'Running reverse method' do it 'Should return "olleh"' do solver = Solver.new reverse = solver.reverse('hello') expect(reverse).to eq 'olleh' end it 'Should not return "hello"' do solver = Solver.new reverse = solver.reverse('hello') expect(reverse).not_to eq 'hello' end end context 'Running fizzbuzz method' do it 'Should return fizz' do solver = Solver.new fizzbuzz = solver.fizzbuzz(3) expect(fizzbuzz).to eq 'fizz' end it 'Should return buzz' do solver = Solver.new fizzbuzz = solver.fizzbuzz(5) expect(fizzbuzz).to eq 'buzz' end it 'Should return fizzbuzz' do solver = Solver.new fizzbuzz = solver.fizzbuzz(15) expect(fizzbuzz).to eq 'fizzbuzz' end it 'Should return the number 7 as a string' do solver = Solver.new fizzbuzz = solver.fizzbuzz(7) expect(fizzbuzz).to eq '7' end end end
true
c674bbfc0f5516ee29bb2392fd377c139bd259c7
Ruby
jbfolkerts/tablestakes
/lib/tablestakes.rb
UTF-8
24,035
3.671875
4
[ "MIT" ]
permissive
#!/usr/bin/ruby -w # # Tablestakes is an implementation of a generic table class # which takes input from a tab-delimited file and creates a # generic table data structure that can be manipulated with # methods similar to the way a database table may be manipulated. # # Author:: J.B. Folkerts (mailto:jbf@pentambic.com) # Copyright:: Copyright (c) 2014 J.B. Folkerts # License:: Distributes under the same terms as Ruby # This class is a Ruby representation of a table. All data is captured as # type +String+ by default. Columns are referred to by their +String+ headers # which are assumed to be identified in the first row of the input file. # Output is written by default to tab-delimited files with the first row # serving as the header names. class Table # The headers attribute contains the table headers used to reference # columns in the +Table+. All headers are represented as +String+ types. # attr_reader :headers @headers =[] @table = {} @indices = {} # Structure of @table hash # { :col1 => [1, 2, 3], :col2 => [1, 2, 3] } # Instantiate a +Table+ object using a tab-delimited file # # ==== Attributes # +input+:: OPTIONAL +Array+ of rows or +String+ to identify the name of the tab-delimited file to read # # ==== Examples # cities = Table.new() # empty table # cities = Table.new([ ["City", "State], ["New York", "NY"], ["Dallas", "TX"] ]) # create from Array of rows # cities = Table.new("cities.txt") # read from file # cities = Table.new(capitals) # create from table # def initialize(input=nil) @headers = [] @table = {} @indices = {} if input.respond_to?(:fetch) if input[0].respond_to?(:fetch) #create Table from rows add_rows(input) end elsif input.respond_to?(:upcase) # a string, then read_file read_file(input) elsif input.respond_to?(:headers) @headers = input.headers.dup input.each {|row| add_row(row) } end # else create empty +Table+ end # Defines an iterator for +Table+ which produces rows of data (headers omitted) # for its calling block. # def each if block_given? @table[@headers.first].each_index do |index| nextrow = [] @headers.each do |col| begin nextrow << @table[col][index].clone rescue nextrow << @table[col][index] end end yield nextrow end else self.to_enum(:each) end end # Return a copy of a column from the table, identified by column name. # Returns empty Array if column name not found. # # ==== Attributes # +colname+:: +String+ to identify the name of the column def column(colname) Array(get_col(colname)) end # Return a copy of a row from the table as an +Array+, given an index # (i.e. row number). Returns empty Array if the index is out of bounds. # # ==== Attributes # +index+:: +FixNum+ indicating index of the row. def row(index) Array(get_row(index)) end # Return true if the Table is empty, false otherwise. # def empty? @headers.length == 0 && @table.length == 0 end # Add a column to the Table. Raises ArgumentError if the column name is already taken # or there are not the correct number of values. # # ==== Attributes # +args+:: Array of +String+ to identify the name of the column (see examples) # # ==== Examples # cities.add_column("City", ["New York", "Dallas", "San Franscisco"]) # cities.add_column(["City","New York", "Dallas", "San Franscisco"]) # cities.add_column("City", "New York", "Dallas", "San Franscisco") def add_column(*args) if args.kind_of? Array args.flatten! colname = args.shift column_vals = args end # check arguments raise ArgumentError, "Duplicate Column Name!" if @table.has_key?(colname) unless self.empty? if column_vals.length != @table[@headers.first].length raise ArgumentError, "Number of elements in column does not match existing table" end end append_col(colname, column_vals) end # Add one or more rows to the Table, appending it to the end. Raises ArgumentError if # there are not the correct number of values. The first row becomes the table headers # if currently undefined. # # ==== Attributes # +array_of_rows+:: +Array+ of +Arrays+ to hold the rows values # # ==== Examples # cities.add_rows([ ["New York", "NY"], ["Austin", "TX"] ]) def add_rows(array_of_rows) array_of_rows.each do |r| add_row(r.clone) end return self end # Append one Table object to another. Raises ArgumentError if the header values and order do not # align with the destination Table. Return self if appending an empty table. Return given table if # appending to an empty table. # # ==== Attributes # +a_table+:: +Table+ to be added # # ==== Examples # cities.append(more_cities) def append(a_table) if !a_table.kind_of? Table raise ArgumentError, "Argument to append is not a Table" end if self.empty? return a_table elsif a_table.empty? return self end if a_table.headers != @headers raise ArgumentError, "Argument to append does not have matching headers" end a_table.each do |r| add_row(r.clone) end return self end # Add a row to the Table, appending it to the end. Raises ArgumentError if # there are not the correct number of values. # # ==== Attributes # +row+:: +Array+ to hold the row values # # ==== Examples # cities = Table.new.add_row( ["City", "State"] ) # create new Table with headers # cities.add_row("New York", "NY") # add data row to Table # def add_row(*row) if row.kind_of? Array row = row.flatten end if @headers.empty? @headers = row else unless row.length == @headers.length raise ArgumentError, "Wrong number of fields in Table input" end append_row(row) end return self end alias :<< :add_row # Delete a column from the Table. Raises ArgumentError if the column name does not exist. # # ==== Attributes # +colname+:: +String+ to identify the name of the column # # ==== Examples # cities.del_column("State") # returns table without "State" column def del_column(colname) # check arguments raise ArgumentError, "Column name does not exist!" unless @table.has_key?(colname) @headers.delete(colname) @table.delete(colname) return self end # Delete a row from the Table. Raises ArgumentError if # the row number is not found # # ==== Attributes # +rownum+:: +FixNum+ to hold the row number # # ==== Examples # cities.del_row(3) # deletes row with index 3 (4th row) # cities.del_row(-1) # deletes last row (per Ruby convention) def del_row(rownum) # check arguments if self.empty? || rownum >= @table[@headers.first].length raise ArgumentError, "Row number does not exist!" end @headers.each do |col| @table[col].delete_at(rownum) end return self end # Rename a header value for this +Table+ object. # # ==== Attributes # +orig_name+:: +String+ current header name # +new_name+:: +String+ indicating new header name def rename_header(orig_name, new_name) raise ArgumentError, "Original Column name type invalid" unless orig_name.kind_of? String raise ArgumentError, "New Column name type invalid" unless new_name.kind_of? String raise ArgumentError, "Column Name does not exist!" unless @headers.include? orig_name update_header(orig_name, new_name) return self end # Converts a +Table+ object to a tab-delimited string. # # ==== Attributes # none def to_s result = @headers.join("\t") << "\n" @table[@headers.first].each_index do |index| @headers.each do |col| result << @table[col][index].to_s unless col == @headers.last result << "\t" else result << "\n" end end end result end # Converts a +Table+ object to an array of arrays (each row). The first # entry are the table headers. # # ==== Attributes # none def to_a result = [ Array(@headers) ] @table[@headers.first].each_index do |index| items = [] @headers.each do |col| items << @table[col][index] end result << items end result end # Counts the number of instances of a particular string, given a column name, # and returns an integer >= 0. Returns +nil+ if the column is not found. If # no parameters are given, returns the number of rows in the table. # # ==== Attributes # +colname+:: OPTIONAL +String+ to identify the column to count # +value+:: OPTIONAL +String+ value to count # # ==== Examples # cities.count # returns number of rows in cities Table # cities.size # same as cities.count # cities.length # same as cities.count # cities.count("State", "NY") # returns the number of rows with State == "NY" # def count(colname=nil, value=nil) if colname.nil? || value.nil? if @table.size > 0 @table.each_key {|e| return @table.fetch(e).length } else return 0 end end raise ArgumentError, "Invalid column name" unless @headers.include?(colname) if @table[colname] result = 0 @table[colname].each do |val| val == value.to_s ? result += 1 : nil end result else nil end end alias :size :count alias :length :count # Returns counts of the most frequent values found in a given column in the form of a # Table. Raises ArgumentError if the column is not found. If no limit is given # to the number of values, only the top value will be returned. # # ==== Attributes # +colname+:: +String+ to identify the column to count # +num+:: OPTIONAL +String+ number of values to return # # ==== Examples # cities.top("State") # returns a Table with the most frequent state in the cities Table # cities.top("State", 10) # returns a Table with the 10 most frequent states in the cities Table # def top(colname, num=1) freq = tally(colname).to_a[1..-1].sort_by {|k,v| v }.reverse return Table.new(freq[0..num-1].unshift([colname,"Count"])) end # Returns counts of the least frequent values found in a given column in the form of a # Table. Raises ArgumentError if the column is not found. If no limit is given # to the number of values, only the least frequent value will be returned. # # ==== Attributes # +colname+:: +String+ to identify the column to count # +num+:: OPTIONAL +String+ number of values to return # # ==== Examples # cities.bottom("State") # returns a Table with the least frequent state in the cities Table # cities.bottom("State", 10) # returns a Table with the 10 least frequent states in the cities Table # def bottom(colname, num=1) freq = tally(colname).to_a[1..-1].sort_by {|k,v| v } return Table.new(freq[0..num-1].unshift([colname,"Count"])) end # Count instances in a particular field/column and return a +Table+ of the results. # Raises ArgumentError if the column is not found. # # ==== Attributes # +colname+:: +String+ to identify the column to tally # # ==== Examples # cities.tally("State") # returns each State in the cities Table with number of occurences # def tally(colname) # check arguments raise ArgumentError, "Invalid column name" unless @table.has_key?(colname) result = {} @table[colname].each do |val| result.has_key?(val) ? result[val] += 1 : result[val] = 1 end return Table.new([[colname,"Count"]] + result.to_a) end # Select columns from the table, given one or more column names. Returns an instance # of +Table+ with the results. Raises ArgumentError if any column is not valid. # # ==== Attributes # +columns+:: Variable +String+ arguments to identify the columns to select # # ==== Examples # cities.select("City", "State") # returns a Table of "City" and "State" columns # cities.select(cities.headers) # returns a new Table that is a duplicate of cities # def select(*columns) # check arguments raise ArgumentError, "Invalid column name(s)" unless columns columns.kind_of?(Array) ? columns.flatten! : nil columns.each do |c| raise ArgumentError, "Invalid column name" unless @table.has_key?(c) end result = [] result_headers = [] columns.each { |col| @headers.include?(col) ? result_headers << col : nil } result << result_headers @table[@headers.first].each_index do |index| this_row = [] result_headers.each do |col| this_row << @table[col][index] end result << this_row end result_headers.empty? ? Table.new() : Table.new(result) end alias :get_columns :select # Given a particular condition for a given column field/column, return a subtable # that matches the condition. If no condition is given, a new +Table+ is returned with # all records. # Returns an empty table if the condition is not met or the column is not found. # # ==== Attributes # +colname+:: +String+ to identify the column to tally # +condition+:: OPTIONAL +String+ containing a ruby condition to evaluate # # ==== Examples # cities.where("State", "=='NY'") # returns a Table of cities in New York state # cities.where("State", "=~ /New.*/") # returns a Table of cities in states that start with "New" # cities.where("Population", ".to_i > 1000000") # returns a Table of cities with population over 1 million # def where(colname, condition=nil) # check arguments raise ArgumentError, "Invalid Column Name" unless @headers.include?(colname) result = [] result << @headers self.each do |row| if condition eval(%q["#{row[headers.index(colname)]}"] << "#{condition}") ? result << row : nil else result << row end end result.length > 1 ? Table.new(result) : Table.new() end alias :get_rows :where # Given a second table to join against, and a field/column, return a +Table+ which # contains a join of the two tables. Join only lists the common column once, under # the column name of the first table (if different from the name of thee second). # All columns from both tables are returned. Returns +nil+ if the column is not found. # # ==== Attributes # +table2+:: +Table+ to identify the secondary table in the join # +colname+:: +String+ to identify the column to join on # +col2name+:: OPTIONAL +String+ to identify the column in the second table to join on # # ==== Examples # cities.join(capitals, "City", "Capital") # returns a Table of cities that are also state capitals # capitals.join(cities, "State") # returns a Table of capital cities with populations info from the cities table # def join(table2, colname, col2name=colname) # check arguments raise ArgumentError, "Invalid table!" unless table2.is_a?(Table) raise ArgumentError, "Invalid column name" unless @table.has_key?(colname) raise ArgumentError, "Invalid column name" unless table2.headers.include?(col2name) dedupe_headers(table2, colname) result = [ Array(@headers) + Array(table2.headers) ] @table[colname].each_index do |index| t2_index = table2.column(col2name).find_index(@table[colname][index]) unless t2_index.nil? result << self.row(index) + table2.row(t2_index) end end if result.length == 1 #no rows selected return nil else return Table.new(result) end end # Given a field/column, and a regular expression to match against, and a replacement string, # create a new table which performs a substitute operation on column data. In the case that the # given replacement is a +String+, a direct substitute is performed. In the case that it is a +Hash+ # and the matched text is one of its keys, the corresponding +Hash+ value will be substituted. # # Optionally takes a block containing an operation to perform on all matching data elements # in the given column. Raises ArgumentError if the column is not found. # # ==== Attributes # +colname+:: +String+ to identify the column to substitute on # +match+:: OPTIONAL +String+ or +Regexp+ to match the value in the selected column # +replace+:: OPTIONAL +String+ or +Hash+ to specify the replacement text for the given match value # +&block+:: OPTIONAL block to execute against matching values # # ==== Examples # cities.sub("Population", /(.*?),(.*?)/, '\1\2') # eliminate commas # capitals.sub("State", /NY/, "New York") # replace acronym with full name # capitals.sub("State", /North|South/, {"North" => "South", "South" => "North"}) # Northern states for Southern and vice-versa # capitals.sub("State") { |state| state.downcase } # Lowercase for all values # def sub(colname, match=nil, replace=nil, &block) # check arguments raise ArgumentError, "No regular expression to match against" unless match || block_given? raise ArgumentError, "Invalid column name" unless @table.has_key?(colname) if ! block_given? if ! (String.try_convert(match) || Regexp.try_convert(match)) raise ArgumentError, "Match expression must be String or Regexp" elsif ! (replace.respond_to?(:fetch) || replace.respond_to?(:to_str)) raise ArgumentError, "Replacement must be String or Hash" end end result = Table.new([@headers]) col_index = @headers.index(colname) self.each do |row| if block_given? row[col_index] = block.call row[col_index] else row[col_index] = row[col_index].sub(match, replace) end result.add_row(row) end return result end # alias :sub! :sub # Return Array with the union of elements columns in the given tables, eliminating duplicates. # Raises an ArgumentError if a column is not found. # # ==== Attributes # +table2+:: +Table+ to identify the secondary table in the union # +colname+:: +String+ to identify the column to union # +col2name+:: OPTIONAL +String+ to identify the column in the second table to union # # ==== Examples # cities.union(capitals, "City", "Capital") # returns Array with all cities in both tables # def union(table2, colname, col2name=colname) # check arguments raise ArgumentError, "Invalid table!" unless table2.is_a?(Table) raise ArgumentError, "Invalid column name" unless @table.has_key?(colname) raise ArgumentError, "Invalid column name" unless table2.headers.include?(col2name) return self.column(colname) | table2.column(col2name) end # Return an Array with the intersection of columns from different tables, eliminating duplicates. # Return nil if a column is not found. # # ==== Attributes # +table2+:: +Table+ to identify the secondary table in the intersection # +colname+:: +String+ to identify the column to intersection # +col2name+:: OPTIONAL +String+ to identify the column in the second table to intersection # # ==== Examples # cities.intersect(capitals, "City", "Capital") # returns Array with all capitals that are also in the cities table # def intersect(table2, colname, col2name=colname) # check arguments raise ArgumentError, "Invalid table!" unless table2.is_a?(Table) raise ArgumentError, "Invalid column name" unless @table.has_key?(colname) raise ArgumentError, "Invalid column name" unless table2.headers.include?(col2name) return self.column(colname) & table2.column(col2name) end # Sort the table based on given column. Uses precedence as defined in the # column. By default will sort by the value in the first column. # # ==== Attributes # +args+:: OPTIONAL +String+ to identify the column on which to sort # # ==== Options # datatype => :Fixnum # datatype => :Float # datatype => :Date # # ==== Examples # cities.sort("State") # Re-orders the cities table based on State name # cities.sort { |a,b| b<=>a } # Reverse the order of the cities table # cities.sort("State") { |a,b| b<=>a } # Sort by State in reverse alpha order # def sort(column=nil, &block) col_index = 0 if column.kind_of? String col_index = @headers.index(column) elsif column.kind_of? Fixnum col_index = column end # return empty Table if empty if self.empty? return Table.new() end neworder = [] self.each { |row| neworder << OrderedRow.new(row,col_index) } result = [neworder.shift.data] # take off headers block_given? ? neworder.sort!(&block) : neworder.sort! neworder.each { |row| result << row.data } return Table.new(result) end alias :sort! :sort # Write a representation of the +Table+ object to a file (tab delimited). # # ==== Attributes # +filename+:: +String+ to identify the name of the file to write def write_file(filename) file = File.open(filename, "w") file.print self.to_s end private def read_file(filename) file = File.open(filename, "r") result = [] file.each_line do |line| result << line.chomp.split("\t") end result.each do |row| begin add_row(row) rescue ArgumentError if row.length < @headers.length (@headers.length - row.length).times { row << "" } add_row(row) else $stderr.puts "ArgumentError: #{row.length} fields --> #{row.join(";")}" end end end end def get_row(index) result = [] if index >= @table[@headers.first].length || index < -(@table[@headers.first].length) return result end @headers.each { |col| result << @table[col][index].to_s } return result end def append_row(row) @headers.each do |col| @table[col] = [] unless @table[col] @table[col] << row.shift end end def get_col(colname) # return empty Array if column name not found unless @table.has_key?(colname) Array.new() else Array(@table[colname]) end end def append_col(colname, column_vals) @headers << colname @table[colname] = Array.new(column_vals) return self end def update_header(item, new_item) i = @headers.index(item) @headers[i] = new_item unless i.nil? @table.fetch(item,nil).nil? ? nil : @table[new_item] = @table[item] end def dedupe_headers(table2, colname) # ensure no duplication of header values table2.headers.each do |header| if @headers.include?(header) update_header(header, '_' << header ) if header == colname colname = '_' << colname end end end end end #Table # This class functions as a temporary representation of a row. The OrderedRow # contains information about which column it should be sorted on, so that # Comparable can be implemented. class OrderedRow # Contains data elements of the row @data = [] # Indicates which row element (column) on which to sort @sort_index = 0 # Creates a new OrderedRow. Callers must specify the index of the row # element which will be used for order comparisons. # # ==== Attributes # +my_array+:: An array representing a row from +Table+ # +index+:: A Fixnum value which represents the comparison value # def initialize(my_array, index) @data = my_array @sort_index = index end # Returns the row elements in an +Array+ # # ==== Attributes # none def data return @data end # Implements comparable # # ==== Attributes # +other+:: The row to be compared def <=>(other) self.data[@sort_index] <=> other.data[@sort_index] end end
true
85376a5413918636d89ce42bcd8fc6fe97856bbd
Ruby
OlegPerminov/parser
/product.rb
UTF-8
824
2.65625
3
[]
no_license
require 'mechanize' require 'securerandom' class Product def initialize(product, page) @type = "product" @name = product.at("a[@class='name']").text @group_name = page.at("div[@id='tips']").text.split("/")[2] @icon_name = SecureRandom.uuid + "." + product.at("a[@class='img']")['rel'].split("/")[-1].split(".")[-1] @id = product.at("a[@class='name']")['href'].split("/")[4] icon_url = "http://www.a-yabloko.ru" + product.at("a[@class='img']")['rel'] save_image(icon_url) write_data end def save_image(icon_url) img = Mechanize.new.get(icon_url) img.save("./images/#{@icon_name}") end def write_data line = "#{@type}\t#{@name}\t#{@group_name}\t#{@icon_name}\t#{@id}" File.open("catalog.txt", "a") { |file| file.puts line.delete("\"") } end end
true
55c9e889d80857558690b16947572ef26a390715
Ruby
emmasroberts97/week_2_day_1_lab
/student.rb
UTF-8
557
3.59375
4
[]
no_license
# PART A class Student def initialize(input_student, input_cohort) @student = input_student @cohort = input_cohort end #GETTERS def student_name() return @student end def cohort_name() return @cohort end #SETTERS def set_student_name(new_name) @student = new_name end def set_student_cohort(new_cohort) @cohort = new_cohort end def student_talk if @student == "Emma" return "My name is Emma" end end def say_favourite_language(language) return "I love #{language}" end end
true
7f73ec08889e5bb1ad2c3ac87060ab4cf97b0217
Ruby
johnTheDudeMan/the_odin_project
/ruby_scripts/building_blocks/spec/caesar_cipher_spec.rb
UTF-8
828
3.0625
3
[]
no_license
require_relative '../caesar_cipher' describe "caesar_cipher" do describe "takes string and integer parameter" do let(:dbl) { double } before { expect(dbl).to receive(:caesar_cipher).with(instance_of(String), instance_of(Fixnum)) } it "passes when the args match" do dbl.caesar_cipher("cat", 3) end end it "shifts each letter by a factor" do expect(caesar_cipher("cat", 3)).to eq("fdw") end it "ignores spaces" do expect(caesar_cipher("c a t", 3)).to eq("f d w") end it "maintains case" do expect(caesar_cipher("CaT", 3)).to eq("FdW") end it "wraps around alphabet" do expect(caesar_cipher("xyz", 2)).to eq("zab") end it "ignores numbers" do expect(caesar_cipher("cat5", 3)).to eq("fdw5") end it "accepts negative factors" do expect(caesar_cipher("fdw", -3)).to eq("cat") end end
true
093e8e40624addbd5c28fb65e3e17180b9b6b32c
Ruby
jrodri207/parrot-ruby-online-web-pt-090919
/parrot.rb
UTF-8
53
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def parrot(name = "Squawk!") puts name name end
true
755bc2668bef654ba8fda5f632bb6b3c0a8d9d52
Ruby
masayasviel/algorithmAndDataStructure
/from51to100/ABC93/mainB.rb
UTF-8
213
3.28125
3
[]
no_license
a, b, k = gets.chomp.split(" ").map(&:to_i) ans = [] if b-a+1 < k ans = [*a..b] else a.upto(a+k-1) do |i| ans << i end b.downto(b-k+1) do |i| ans << i end end puts ans.sort.uniq
true
7badf899638a30748ab17bf7025803c4b56e96d5
Ruby
miloprice/leetcode-review
/ruby/038_count_and_say.rb
UTF-8
655
3.84375
4
[]
no_license
# @param {Integer} n # @return {String} # Faster than 53.33% of submissions def count_and_say(n) if n == 1 '1' elsif n > 1 prev_val = count_and_say(n - 1) cur_char = nil cur_count = 0 cur_val = "" prev_val.each_char.each do |new_char| if cur_char && new_char != cur_char cur_val << cur_count.to_s + cur_char cur_char = new_char cur_count = 0 elsif cur_char.nil? cur_char = new_char end cur_count += 1 end cur_val << cur_count.to_s + cur_char cur_val end end
true
d81ca084448fcc749d2e18d5d5f4610e4d84dd65
Ruby
huberb/eulerproblems
/euler36/euler36.rb
UTF-8
395
3.890625
4
[]
no_license
class Integer def to_b 32.times .map{ |i| self >> i & 1 == 1 ? "1" : "0" } .reverse .drop_while{ |b| b != "1" } .join end end def palindrom?(str) (str.length / 2).times.all? do |i| i2 = str.length - i - 1 str[i] == str[i2] end end nums = 1_000_000 .times .select{ |n| palindrom?(n.to_s) and palindrom?(n.to_b) } puts nums.inspect puts nums.sum
true
96ea285f417ab2db76f2ccf331752c5acf6439e9
Ruby
KamilLelonek/ruby-tuples
/spec/tuple_spec.rb
UTF-8
3,419
3.703125
4
[]
no_license
describe Tuple do describe 'Initialization' do context 'initializer' do it 'should instantiate with multiple arguments' do expect { Tuple.new() } .not_to raise_error expect { Tuple.new(1, 2, 3) }.not_to raise_error expect(Tuple.new()) .to be_instance_of Tuple expect(Tuple.new(1, 2, 3)).to be_instance_of Tuple end it 'should instantiate with an array' do expect { Tuple.new([]) } .not_to raise_error expect { Tuple.new([1, 2, 3]) }.not_to raise_error expect(Tuple.new([])) .to be_instance_of Tuple expect(Tuple.new([1, 2, 3])).to be_instance_of Tuple end end it 'should instantiate by method' do expect { Tuple() } .not_to raise_error expect { Tuple(1, 2, 3) }.not_to raise_error expect(Tuple()) .to be_instance_of Tuple expect(Tuple(1, 2, 3)).to be_instance_of Tuple end it 'should instantiate by factory' do expect { Tuple[] } .not_to raise_error expect { Tuple[1, 2, 3] }.not_to raise_error expect(Tuple[]) .to be_instance_of Tuple expect(Tuple[1, 2, 3]).to be_instance_of Tuple end end describe 'Comparison' do it 'should be the same tuples' do expect(Tuple()) .to eq Tuple() expect(Tuple(1)) .to eq Tuple(1) expect(Tuple(1, 2)) .to eq Tuple[1, 2] expect(Tuple(1, 2, 3)).to eq Tuple.new(1, 2, 3) end it 'should be different' do expect(Tuple(1)) .not_to eq Tuple(2) expect(Tuple(1, 2)).not_to eq Tuple(3) end end describe 'Indexing' do let(:tuple) { Tuple(:a, :b, :c) } context 'square brackets' do it 'should access particular elements for positive indexes' do expect(tuple[0]).to eq :a expect(tuple[1]).to eq :b expect(tuple[2]).to eq :c end it 'should access particular elements for negative indexes' do expect(tuple[-1]).to eq :c expect(tuple[-2]).to eq :b expect(tuple[-3]).to eq :a end it 'should return nil for both positive and negative indexes exceeding size' do expect(tuple).to have_exactly(3).items expect(tuple[3]) .to be_nil expect(tuple[-4]).to be_nil end end context 'auxilary methods' do let(:empty_tuple) { Tuple() } let(:one_element_tuple) { Tuple(:an_only_element) } it 'should fetch first and last element when they exist' do expect(tuple.first).to eq :a expect(tuple.last) .to eq :c end it 'should return nil if and only if tuple is empty' do expect(empty_tuple.first).to be_nil expect(empty_tuple.last) .to be_nil end it 'should have the same first and last element for one-length tuple' do expect(one_element_tuple) .to have_exactly(1).item expect(one_element_tuple.first).to eq one_element_tuple.last end it 'should count tuple elements' do expect(empty_tuple.length) .to eq 0 expect(empty_tuple.arity) .to eq 0 expect(one_element_tuple.length).to eq 1 expect(one_element_tuple.arity) .to eq 1 expect(Tuple(1, 2, 3).length) .to eq Tuple(:a, :b, :c).arity end it 'should return reversed tuple' do expect(Tuple(1, 2, 3).invert).to eq Tuple(3, 2, 1) end end end end
true
6468d17715a61d0fce58189fb9a90c9a8a8e5621
Ruby
arfelio/one_way_ticket
/app/repos/repo.rb
UTF-8
571
2.609375
3
[]
no_license
class Repo def initialize(klass, params) @params = params @klass = klass end attr_reader :params, :klass def create klass.to_adapter.create!(params) end def find klass.to_adapter.find_first(params) end def find_by_id klass.to_adapter.get!(params) end def get_collection(args) args.each_pair { | key, value | args.delete(key) if value.blank? } klass.to_adapter.find_all(args) end def search if params[:search].present? get_collection(params[:search]) else get_collection({}) end end end
true
7e2256d3787eb0294f5966fd16beab3371c48225
Ruby
jelenicak/text-split
/lib/page.rb
UTF-8
814
2.953125
3
[]
no_license
require "open-uri" require_relative "exceptions" class Page LOOKS_LIKE_XPATH = /^(\.\/|\/|\.\.|\.$)/ # this regular expression can be found in # Nokogiri::XML::Searchable def self.extract(url, xpath) new(url, xpath) end def initialize(url, xpath) @doc = Nokogiri::HTML(open(url).read) @xpath = xpath end def text (@xpath.nil? || @xpath.empty?) ? content : custom_content end def title @doc.xpath('/html/head/title').text end def content @doc.xpath('//h1 | //p').reduce("") do |text, node| text = text + " " + node.text end end def custom_content if @xpath =~ LOOKS_LIKE_XPATH @doc.xpath(@xpath).reduce("") do |text, node| text = text + " " + node.text end else raise Exceptions::InvalidPath end end end
true
55836dcbec282a07fd3c93b143070d60ddd2961d
Ruby
XRayV5/tribe_marketplace-
/spec/model.spec.rb
UTF-8
4,458
2.828125
3
[]
no_license
require "spec_helper" describe Bundle do describe ".initialize" do it "generates the bundle instance with format of IMG" do expect(Bundle.new("IMG").get_format).to eq "IMG" end it "generates the bundle instance with format of Flac" do expect(Bundle.new("Flac").get_format).to eq "Flac" end it "generates the bundle instance with format of VID" do expect(Bundle.new("VID").get_format).to eq "VID" end it "raises invalid format error when given unsupported format" do expect {Bundle.new("MP4")}.to raise_error(RuntimeError, "Invalid format") end end describe ".get_price_by_bundle" do it "returns correct price for bundle of format IMG" do expect(Bundle.new("IMG").get_price_by_bundle(5)).to eq 450 end it "returns correct price for bundle of format Flac" do expect(Bundle.new("Flac").get_price_by_bundle(3)).to eq 427.50 end it "returns correct price for bundle of format VID" do expect(Bundle.new("VID").get_price_by_bundle(9)).to eq 1530 end end describe "Bundle.new(\"IMG\").cal_qty_per_bundle.get_qty_per_bundle" do before :all do @img_bdl = Bundle.new("IMG") end it "returns correct qty per bundle for an simple order of format IMG" do expect(@img_bdl.cal_qty_per_bundle(5).get_qty_per_bundle).to match_array [["5", 1]] end it "returns correct qty per bundle for even order of format IMG" do expect(@img_bdl.cal_qty_per_bundle(15).get_qty_per_bundle).to match_array [["10", 1], ["5", 1]] end it "returns correct qty per bundle for an varied order of format IMG" do expect(@img_bdl.cal_qty_per_bundle(25).get_qty_per_bundle).to match_array [["10", 2], ["5", 1]] end end describe "Bundle.new(\"Flac.cal_qty_per_bundle\").get_qty_per_bundle" do before :all do @flac_bdl = Bundle.new("Flac") end it "returns correct qty per bundle for an simple order of format Flac" do expect(@flac_bdl.cal_qty_per_bundle(6).get_qty_per_bundle).to match_array [["6", 1]] end it "returns correct qty per bundle for even order of format Flac" do expect(@flac_bdl.cal_qty_per_bundle(15).get_qty_per_bundle).to match_array [["9", 1], ["6", 1]] end it "returns correct qty per bundle for an varied order of format Flac" do expect(@flac_bdl.cal_qty_per_bundle(12).get_qty_per_bundle).to match_array [["9", 1], ["3", 1]] end it "returns correct qty per bundle for an more varied order of format Flac" do expect(@flac_bdl.cal_qty_per_bundle(24).get_qty_per_bundle).to match_array [["9", 2], ["6", 1]] end end describe "Bundle.new(\"Flac.cal_qty_per_bundle\").get_qty_per_bundle" do before :all do @vid_bdl = Bundle.new("VID") end it "returns correct qty per bundle for an simple order of format VID" do expect(@vid_bdl.cal_qty_per_bundle(3).get_qty_per_bundle).to match_array [["3", 1]] end it "returns correct qty per bundle for even order of format VID" do expect(@vid_bdl.cal_qty_per_bundle(8).get_qty_per_bundle).to match_array [["5", 1], ["3", 1]] end it "returns correct qty per bundle for an varied order of format VID" do expect(@vid_bdl.cal_qty_per_bundle(17).get_qty_per_bundle).to match_array [["9", 1], ["5", 1], ["3", 1]] end it "returns correct qty per bundle for an more varied order of format VID" do expect(@vid_bdl.cal_qty_per_bundle(13).get_qty_per_bundle).to match_array [["5", 2], ["3", 1]] end # "Cannot provide a combo deal for given qty" it "raises 'Cannot provide a combo deal for given qty' for invalid order qty" do expect {@vid_bdl.cal_qty_per_bundle(16).get_qty_per_bundle}.to raise_error(RuntimeError, "Cannot provide a combo deal for given qty") end end describe ".cal_price_per_bundle" do it "calculates correct total prices for an simple order of format VID" do expect(Bundle.new("VID").cal_price_per_bundle([["5", 1], ["9", 1]])["5"]).to match_array([1, 900]) end it "calculates correct total prices for an simple order of format Flac" do expect(Bundle.new("Flac").cal_price_per_bundle([["3", 1], ["9", 1]])["9"]).to match_array([1, 1147.5]) end it "calculates correct total prices for an simple order of format IMG" do expect(Bundle.new("IMG").cal_price_per_bundle([["5", 2], ["10", 1]])["10"]).to match_array([1, 800]) end end end
true
6f75b7f843e7301f025b0d6ed1f6d834cc6b6a39
Ruby
Cileos/shiftplan
/app/models/time_period_formatter.rb
UTF-8
2,074
3.203125
3
[]
no_license
# Basically a model-layer decorator module TimePeriodFormatter def self.period_with_zeros(from, to) [time_with_zeros(from), time_with_zeros(to)].compact.join('-') end def self.period_without_zeros(from, to) [time_without_zeros(from), time_without_zeros(to)].compact.join('-') end # show zeros only if neccessary def self.period(from, to) [time(from), time(to)].compact.join('-') end def self.wide_period(from, to) [time(from), time(to)].compact.join(' - ') end def self.time_with_zeros(time) time && time.strftime('%H:%M') end def self.time_without_zeros(time) time && time.hour end def self.time(t) return unless t t.min == 0 ? time_without_zeros(t) : time_with_zeros(t) end def period_with_duration period_with_zeros + ' ' + duration end def duration '(%d:%02dh)' % [ length_in_minutes / 60, length_in_minutes % 60 ] end # may be overridden by OvernightableDecoratorHelper, returning only the length for one part # returns 3.25 for 3 hours and 15 minutes # OPTIMIZE rounding def length_in_hours length_in_minutes / 60 end # completely ignores overnightables, best for summing up def total_length_in_hours length_in_minutes / 60 end def period TimePeriodFormatter.period self_or_prev_day.starts_at, self_or_next_day.ends_at end def wide_period TimePeriodFormatter.wide_period self_or_prev_day.starts_at, self_or_next_day.ends_at end def period_with_zeros TimePeriodFormatter.period_with_zeros self_or_prev_day.starts_at, self_or_next_day.ends_at end private def self_or_prev_day @self_or_prev_day ||= (respond_to?(:previous_day) && previous_day).presence || self end def self_or_next_day @self_or_next_day ||= (respond_to?(:next_day) && next_day).presence || self end def length_in_minutes @length_in_minutes ||= if all_day? (actual_length_in_hours || 0.0) * 60 else ((self_or_next_day.ends_at) - self_or_prev_day.starts_at) / 60 end end end
true
d77971132fba30e3fa4bfcf98f0230edfdadb150
Ruby
MaligneCanyon/programming_foundations
/exercises/easy2_ex6.rb
UTF-8
328
3.515625
4
[]
no_license
# inputs: # - none # outputs: # - odd numbers, each printed on a separate line # reqs: # - print all odd nums btwn 1 and 99 # rules: # - print each num on a sep line # struct: # -numeric # algo: # - from 1 to 99 # - print the num # - incr by 2 1.step(by:2, to:99) { |num| puts num } # (1..99).each { |v| puts v if v.odd? }
true
2e49a2a56531e2e0df6fe3aa25f2373a892c330d
Ruby
Vidreven/rubitcointools
/lib/blocks.rb
UTF-8
2,306
3.09375
3
[ "MIT" ]
permissive
require_relative 'specials' require_relative 'hashes' class Blocks def initialize @sp = Specials.new @h = Hashes.new end def serialize_header(inp) o = @sp.change_endianness(inp[:version]) + @sp.change_endianness(inp[:prevhash]) + @sp.change_endianness(inp[:merkle_root]) + @sp.change_endianness(inp[:timestamp]) + @sp.change_endianness(inp[:bits]) + @sp.change_endianness(inp[:nonce]) o = @sp.changebase(o, 16, 256) h = @sp.changebase(@h.bin_dbl_sha256(o), 256, 16) raise RuntimeError, "Incorrect hash " + h unless @sp.change_endianness(h) == inp[:hash] o end def deserialize_header(inp) h = @sp.changebase(@h.bin_dbl_sha256(inp), 256, 16) inp = @sp.changebase(inp, 256, 16) { version: @sp.change_endianness('0' + inp[0..6]), # a hack to make the length 4 bytes prevhash: @sp.change_endianness(inp[7..70]), merkle_root: @sp.change_endianness(inp[71..134]), timestamp: @sp.change_endianness(inp[135..142]), bits: @sp.change_endianness(inp[143..150]), nonce: @sp.change_endianness(inp[151..-1]), hash: @sp.change_endianness(h) } end # Returns a Merkle path of the transaction to the root? def mk_merkle_proof(header, hashes, index) nodes = hashes.map{|h| @sp.change_endianness(h)} nodes = nodes.map{|h| @sp.changebase(h, 16, 256)} if (nodes.length % 2 == 1) && (nodes.length > 2) nodes << nodes[-1] end layers = [nodes] while nodes.length > 1 newnodes = [] (0..nodes.length-1).step(2) do |i| newnodes << @h.bin_dbl_sha256(nodes[i] + nodes[i+1]) end if (newnodes.length % 2 == 1) && (newnodes.length > 2) newnodes << newnodes[-1] end nodes = newnodes layers << nodes end # Sanity check to make sure merkle root is valid raise RuntimeError, "Invalid root" unless @sp.changebase(nodes[0].reverse, 256, 16) == header[:merkle_root] merkle_siblings = [] (0..layers.length - 1).each{|i| merkle_siblings << layers[i][(index >> i) ^ 1]} merkle_siblings.compact! merkle_siblings = merkle_siblings.map{|s| @sp.changebase(s, 256, 16)} merkle_siblings = merkle_siblings.map{|s| @sp.change_endianness(s)} { hash: hashes[index], siblings: merkle_siblings, header: header } end end
true
e4eef695a9df8fb6f5211458f9e1249a821b7f35
Ruby
BrunoJimenezUrizar/devmemo
/test/unit/dump_test.rb
UTF-8
1,654
2.578125
3
[]
no_license
require 'test_helper' class DumpTest < ActiveSupport::TestCase #### UT_032W ############################################## test "dump_create" do assert Dump.create, "UT_032W: dump should be created" end ########################################################## #### UT_033W ############################################## test "dump_nil" do dump=Dump.new assert !dump.save, "UT_033W: dump nil created!" end ########################################################## #### UT_034W ############################################## test "dump_with_por_nil" do dump=dumps(:one) dump.por_id=nil assert !dump.save, "UT_034W: dump with por nil created!" end ########################################################## #### UT_035W ############################################## test "dump_destroy" do dump=dumps(:one) dump.destroy assert !Dump.find_by_id(1), "UT_035W: dump should be destroyed" end ########################################################## #### UT_036W ############################################## test "dump_delete_on_cascade" do dump=dumps(:one) d_id=dump.id p_id=dump.por_id Por.find(p_id).destroy assert_nil Dump.find_by_id(d_id), "UT_036W: A dump should be destroyed when its PoR did" end ########################################################## #### UT_037W ############################################## test "dump_update" do dump=dumps(:one) dump.description="nombre_nuevo" assert_equal("nombre_nuevo",dump.description ,"UT_037W: dump name should be updated") end ########################################################## end
true
453ecebc13ac3edf40c3cb412cda192b5f60c75e
Ruby
wbailey/data_table
/lib/data_table/row.rb
UTF-8
1,229
2.875
3
[]
no_license
class DataTable def add_row( row, options = { :after => :last } ) raise UndefinedHeader unless valid_header? raise InvalidRow unless row.is_a?( Array ) raise InvalidRowSize unless row.size.eql?( @header.size ) raise InvalidAddOption unless options.is_a?( Hash ) && options.keys.size.eql?( 1 ) order, value = options.to_a.flatten case order when :before, :after raise InvalidRowIndex unless /^(first|last|\d+)$/.match( value.to_s ) case value.to_s when 'first' index = order.eql?( :before ) ? 0 : 1 when 'last' index = order.eql?( :after ) ? -1 : self.size - 1 when /\d+/ index = order.eql?( :before ) ? value : value + 1 end else raise InvalidAddOption end # By default the array will substitute undefined values with nil when the index is out of bounds index = self.size if index > self.size self.insert( index, row ) end def row( index = 0 ) raise UndefinedTable if self.empty? if row = self[index.to_i] row else raise UndefinedRow end end def delete_row( index = 0 ) row( index ) self.delete_at( index.to_i ) end end
true
1c68d62765d45e343b4595ab359eba6abb0baf58
Ruby
proudcloudojt/sample_app
/app/models/micropost.rb
UTF-8
1,217
2.546875
3
[]
no_license
class Micropost < ActiveRecord::Base attr_accessible :content , :recipients USERNAME_REGEX = /@\w+/i belongs_to :user has_many :recipients, :dependent => :destroy has_many :replied_users, :through => :recipients, :source => "user" validates :content, :presence => true, :length => { :maximum => 140 } validates :user_id, :presence => true default_scope :order => 'microposts.created_at DESC' scope :from_users_followed_by, lambda {|user| followed_by(user)} after_save :save_recipients private def self.followed_by(user) followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id) where("user_id IN (#{followed_ids}) OR user_id = :user_id", { :user_id => user}) end def save_recipients return unless reply? people_replied.each do |user| Recipient.create!(:micropost_id => self.id, :user_id => user.id) end end def reply? self.content.match( USERNAME_REGEX ) end def people_replied users = [] self.content.clone.gsub!( USERNAME_REGEX ).each do |username| user = User.find_by_username(username[1..-1]) users << user if user end users end end
true
23e29603122fbe2ccacf9f26fdc4165f046b8275
Ruby
Sifuri/TicTacToe
/gameboard.rb
UTF-8
1,246
3.875
4
[]
no_license
# GameBoard Class class GameBoard attr_accessor :options # Represent a new board with an array of numerical elements for each board space. def initialize @options = [] SPACES.times do |s| options << s end end #Display the current board. def show(new_options = nil) @options = new_options if new_options puts "\t\t\t--#{options[0]}--|--#{options[1]}--|--#{options[2]}--" puts "\t\t\t--#{options[3]}--|--#{options[4]}--|--#{options[5]}--" puts "\t\t\t--#{options[6]}--|--#{options[7]}--|--#{options[8]}--" end # Determine and store all available options def free_moves(options) moves = [] SPACES.times do |s| unless options[s] != s moves << s end end moves end # Verify if the board has a winner, tie, or neither def verify(options) # Check the board to see if there are 'X' or 'O' values in a row SOLUTIONS.each do |s| if options[s[0]] == options[s[1]] and options[s[1]] == options[s[2]] return options[s[0]] end end # If no one has won, check to see if there are any free spaces, if not declare tie unless options.all? {|i| i.is_a? String } return false else "Tie" end end end
true