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
84a8826918ea21f3849d0010de9cb75b38adecf3
Ruby
AJAYJAITWAL/Ruby_programs
/All_small_pro/vowel_orNot.rb
UTF-8
247
4.1875
4
[]
no_license
puts "Enter character " c = gets.chomp() if(c=='a' or c=='i' or c=='o' or c=='u' or c=='e') puts "This is a vowel" elsif(c=='A' or c=='I' or c=='O' or c=='U' or c=='E') puts "This is a vowel" else puts "This is a consonet" end
true
be246cdfa1c7640e4129a72b8418015d003dc9fa
Ruby
a2ikm/authenticate_from_scratch
/app/models/session_storage.rb
UTF-8
205
2.53125
3
[]
no_license
module SessionStorage class <<self def set(key, value, expires_in) Rails.cache.write(key, value, expires_in: expires_in) end def get(key) Rails.cache.read(key) end end end
true
a1d8101a59f42110f999dba1e00e3191c96996e2
Ruby
ndomar/megasoft-13
/Rails/WebsitesPrototypeBuilder/spec/models/comment_spec.rb
UTF-8
795
2.578125
3
[]
no_license
require 'spec_helper.rb' describe Comment do before(:each) do @attr = {:body =>"My Comment",:assigned_part => "1"} end it "should create a new Comment" do Comment.create!(@attr) end it "should require a Comment" do no_body = Comment.new(@attr.merge(:body => "")) no_body.should_not be_valid end it "should require an assigned_part" do no_body = Comment.new(@attr.merge(:assigned_part => "")) no_body.should_not be_valid end it "should have a maximum length of 8000" do chars = (0..9).to_a.concat(('a'..'z').to_a).concat(('A'..'Z').to_a).concat(['|',',','.','!','-']) str = ""; 8001.times {str += chars.sample.to_s} no_body = Comment.new(@attr.merge(:body => str)) no_body.should_not be_valid end end
true
1a38254c1d75ac0408f438b5f436bd01a670a854
Ruby
cola119/CompetitiveProgramming
/AtCoder/BeginnerSelection/ABC086C.rb
UTF-8
240
3.359375
3
[]
no_license
def test n = gets.chomp.to_i t1, x1, y1 = 0, 0, 0 n.times do t2, x2, y2 = gets.chomp.split(" ").map(&:to_i) return "No" if ((x2-x1).abs+(y2-y1).abs-t2-t1) % 2 != 0 || (x2-x1).abs+(y2-y1).abs > t2-t1 end return "Yes" end puts test
true
c36654b3b7b0a178795c022e2c695cef96ffe3bf
Ruby
turuthivic/EBWiki
/app/services/determine_visits_to_cases.rb
UTF-8
790
2.6875
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true # This service object, given a list of URLs and the views for each one, will # return a list of cases the URLs lead to the corresponding views. class DetermineVisitsToCases include Service # The begin..rescue..end block is used to determine if the URL leads to an # article without performing the same query twice (to check if the case # exists and then retrieve the case object. Once Ruby is upgraded to # >= 2.5, the rescue can be performed directly within the each do..end block. def call(visit_info) cases = [] visit_info.each do |(url, views)| begin this_case = Case.friendly.find(url.split('/').last) cases << [this_case, views] rescue ActiveRecord::RecordNotFound end end cases end end
true
9f8346f2d3522b98fae9d7cb4700dad4668c2840
Ruby
sakura2uuu/algorithm
/ruby/acm_icpc_team.rb
UTF-8
1,271
3.296875
3
[]
no_license
# Problem: https://www.hackerrank.com/challenges/acm-icpc-team/problem # Original solution taking too long to run def acmTeam(topic) num_of_attendees = topic.count permutations = (0..(num_of_attendees - 1)).to_a.permutation(2).to_a unique_permutations = permutations.map do |array| array.sort end.uniq result = unique_permutations.map do |person1, person2| (topic[person1].to_i(2) | topic[person2].to_i(2)).to_s(2).scan('1').count end [max = result.max, result.count(max)] end # Solution Referred: https://www.hackerrank.com/rest/contests/master/challenges/acm-icpc-team/hackers/kgyrtkirk/download_solution def acmTeam2(topic) num_of_attendees = topic.count # 1. Convert to binary first topic_converted = topic.map{ |a| a.to_i(2) } # 2. Use json to store result result = {} result.default = 0 # 3. Use for-loop to get the permutations # Example for 4 attendees # person1: (0) , (1), (2) # person2: (1, 2, 3), (2, 3), (3) (0..(num_of_attendees - 2)).each do |person1| ((person1 + 1)..(num_of_attendees - 1)).each do |person2| known_topics = (topic_converted[person1] | topic_converted[person2]).to_s(2).count('1') result[known_topics]+=1 end end [max = result.keys.max, result[max]] end
true
c0264ada243be4f2a2430040d6fe01bd25669d7a
Ruby
briandunn/flatware
/lib/flatware/serialized_exception.rb
UTF-8
672
2.859375
3
[ "MIT" ]
permissive
module Flatware class SerializedException attr_reader :class, :message, :cause attr_accessor :backtrace def initialize(klass, message, backtrace, cause = '') @class = serialized(klass) @message = message @backtrace = backtrace @cause = cause end def self.from(exception) new( exception.class, exception.message, exception.backtrace, exception.cause ) end private def serialized(klass) SerializedClass.new(klass.to_s) end end class SerializedClass attr_reader :name alias to_s name def initialize(name) @name = name end end end
true
a691cbe2cde2b7b7a69843b37b7489f6afe9352d
Ruby
nlangford/Odin
/LearnRuby/02_calculator/calculator.rb
UTF-8
164
3.59375
4
[]
no_license
def add(num1, num2) num1 + num2 end def subtract(num1, num2) num1 - num2 end def sum(arr) total = 0 arr.each {|i| total+=i} return total end
true
92fa3b5d71533495a452649f4f3f2978a1ada7e0
Ruby
kawatoshi/toukei
/kokyaku_jyouhou_touroku.rb
UTF-8
948
2.796875
3
[]
no_license
#!/usr/bin/ruby # -*- coding: utf-8 -*- require './inputkey' include Inputkey open(ARGV[0].chomp, 'r') do |io| kokyaku = Inputkey::Inputkey.new("") kokyaku_kana = Inputkey::Inputkey.new("") kokyaku_ryaku = Inputkey::Inputkey.new("") while line = io.gets ary = line.split(/\t/) k_id = ary[0] kokyaku.set_source(ary[2], ary[1]) kokyaku_kana.set_source(ary[2], ary[3]) kokyaku_ryaku.set_source(ary[4], ary[4]) seikyuusaki_code = ary[6] busyo = ary[7] puts <<"COMMAND1" key #{k_id} <r 3> Enter </r> 700 COMMAND1 kokyaku.kanakan kokyaku.enter kokyaku_kana.kana kokyaku.enter kokyaku_ryaku.kanakan kokyaku.enter puts <<"COMMAND2" <r 15> enter </r> F4 key ↓↓ 100 enter enter F4 key ↓ enter 100 F3 200 key #{seikyuusaki_code} enter enter 300 enter <r 14> enter </r> key #{busyo} enter 300 <r 13> enter </r> F4 100 key ↓ enter 200 <r 10> enter </r> 200 space 300 F12 700 enter 900 COMMAND2 end end
true
ce36f28828c340ea268b243d12727474478e773b
Ruby
craigh44/Ruby_FizzBuzz
/lib/fizzbuzz.rb
UTF-8
371
4.03125
4
[]
no_license
class FizzBuzz def isDivisibleByThree(number) number % 3 == 0 end def isDivisibleByFive(number) number % 5 == 0 end def isDivisibleByFifteen(number) number % 15 == 0 end def say(number) return "FizzBuzz" if isDivisibleByFifteen(number) return "Fizz" if isDivisibleByThree(number) return "Buzz" if isDivisibleByFive(number) return number end end
true
b77fb2e684d2bf016e3ded88ecd3ac0d83b6c814
Ruby
Kimbeaux/Learn-Ruby-Ex-5
/ex5.rb
UTF-8
1,415
4.25
4
[]
no_license
name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'White' hair = 'Brown' puts "Let's talk about %s." % name puts "He's %d inches tall." % height puts "He's %d pounds heavy." % weight puts "Actually that's not too heavy." puts "He's got %s eyes and %s hair." % [eyes, hair] puts "His teeth are usually %s depending on the coffee." % teeth # this line is tricky, try to get it exactly right puts "If I add %d, %d, and %d I get %d." % [age, height, weight, age + height + weight] # Trying more format sequences. puts "2 is %b in binary." % 2 puts "The numeric code for 52 is %c." % 52 # Got a blank for 32 and thought I had a syntax error. ;P puts "Weight in exponential notation is %.3e." % weight # Note: w/o '.3', default precision is 6. puts "Or I can convert weight to floating point, with a precision of 2 places after the decimal point: %.2f." % weight puts "Converting 0.0000345 to exponential form yields %0.3g." % 0.0000345 puts "Height is %.3i." % height puts "16 in octal is %o." % 16 puts "The value of argument inspect of %s is %p." % ['age', age] puts "At least he can't be - %u years old." % age puts "But his age in hex is %x." % age # Converting height to centimeters. puts "%.2f inches is %.2f centimeters." % [height, height * 2.54] # 1 = 2.54 cm/inch puts "%.2f pounds is %.2f kilograms." % [weight, weight / 2.2046] # 1 = pound/2.2046 kg
true
d39c4a76a5effa5c7926a8ead9fc24a1f8571613
Ruby
leoelios/uniara_virtual_parser
/lib/uniara_virtual_parser/services/files.rb
UTF-8
1,575
2.609375
3
[ "MIT" ]
permissive
module UniaraVirtualParser module Services module Files def files(token) response = Client.get_with_token('/alunos/consultas/arquivos/', token) parse_files response.body end private def parse_files(html) doc = Nokogiri::HTML(html) files = [] doc.css('div#conteudo ~ table').each do |table| #todo: create a class for each selector if table.css('b').first.text =~ /ARQUIVOS DISPONIBILIZADOS PELA/ selector = ->(file) { "COORDENAÇÃO" } files << extract_files(table, selector) elsif table.css('tr td')[2].text == "Disciplina" selector = ->(file) { file.parent.parent.css('td:nth-child(2)').text } files << extract_files(table, selector) else selector = ->(file) do tr = file.parent.parent until(tr.css('td:nth-child(2)').text == 'Tamanho') tr = tr.previous_element end tr.css('td:nth-child(1)').text end files << extract_files(table, selector) end end files.flatten.group_by(&:grade) end def extract_files(table, grade_selector = nil) table.css('a').map do |file| link = file.attribute('href').value.match(/abrearq\('(.*)'\)/)[1] grade = if grade_selector grade_selector.call(file) end Models::File.new(name: file.text, link: link, grade: grade) end end end end end
true
378ff44458b8bdc6b837013b04e7f519e85a1a5d
Ruby
phinze/puppet-postgresql
/spec/puppet_spec/files.rb
UTF-8
1,327
2.625
3
[ "ISC" ]
permissive
require 'fileutils' require 'tempfile' # A support module for testing files. module PuppetSpec::Files # This code exists only to support tests that run as root, pretty much. # Once they have finally been eliminated this can all go... --daniel 2011-04-08 #if Puppet.features.posix? then # def self.in_tmp(path) # path =~ /^\/tmp/ or path =~ /^\/var\/folders/ # end #elsif Puppet.features.microsoft_windows? # def self.in_tmp(path) # tempdir = File.expand_path(File.join(Dir::LOCAL_APPDATA, "Temp")) # path =~ /^#{tempdir}/ # end #else # fail "Help! Can't find in_tmp for this platform" #end def self.cleanup $global_tempfiles ||= [] while path = $global_tempfiles.pop do #fail "Not deleting tmpfile #{path} outside regular tmpdir" unless in_tmp(path) begin FileUtils.rm_r path, :secure => true rescue Errno::ENOENT # nothing to do end end end def tmpfile(name) # Generate a temporary file, just for the name... source = Tempfile.new(name) path = source.path source.close! # ...record it for cleanup, $global_tempfiles ||= [] $global_tempfiles << File.expand_path(path) # ...and bam. path end def tmpdir(name) path = tmpfile(name) FileUtils.mkdir_p(path) path end end
true
cf87b74cb75d2dafe202c23118064e4d7a6e0376
Ruby
Matlawton/coder-academy-t1a3
/src/extras_archive/name_controller.rb
UTF-8
970
3.65625
4
[]
no_license
# require "./test2" # THIS FILE IS NOT CURRENTLY BEING USED. class NameController def self.user_name user_name_attempt = 0 while user_name_attempt < 3 puts "Hey, whats your name?" user_name = gets.chomp.capitalize # If the user types in a name then the loop will stop if user_name != "" AgeController.age break # continues the loop until the user types in a name, or until the user_name_attempt is greater than three. else user_name_attempt += 1 if user_name_attempt == 3 puts "\n You are nameless, do you need some suggestions?" user_name = "Shred Lord #00761" else puts "ERROR!! >> Please enter the name of the student:" end end end end end
true
c5f048f88c084223e12b667b25a10216ad87b7b2
Ruby
brainomite/ruby-minesweeper
/board.rb
UTF-8
1,821
3.671875
4
[ "MIT" ]
permissive
require_relative "tile.rb" class Board def initialize() @grid = Array.new(9) { Array.new } @grid.each_with_index do |col, row_idx| 9.times { |col_idx| col << Tile.new([row_idx, col_idx], self)} end bombs = Board.get_ten_random_pos bombs.each do |bomb| x,y = bomb @grid[x][y].make_bomb end end def self.new_random_board grid = Array.new(9) { Array.new } grid.each_with_index do |col, row_idx| 9.times { |col_idx| col << Tile.new([row_idx, col_idx], self)} end bombs = Board.get_ten_random_pos bombs.each do |bomb| x,y = bomb grid[x][y].make_bomb end Board.new(grid) end def self.get_ten_random_pos positions = [] 9.times do |x| 9.times do |y| positions << [x,y] end end positions.shuffle! positions.take(10) end def [](pos) x, y = pos @grid[x][y] end def display puts " " + (0..8).to_a.join(" ") @grid.each_with_index do |row, idx| puts idx.to_s + " " + row.join(' ') end nil end def toggle_flag(pos) x, y = pos @grid[x][y].toggle_flag end def lost? @grid.any? do |row| row.any? do |tile| true if tile.revealed? and tile.is_bomb? end end end def out_of_bounds?(pos) x, y = pos return true if x < 0 || y < 0 || x >= @grid.length || y >= @grid.length false end def reveal(pos) self[pos].reveal end def reveal_all @grid.each do |row| row.each do |tile| tile.reveal end end nil end def won? @grid.all? do |row| row.all? do |tile| if !tile.is_bomb? && tile.revealed? true elsif tile.is_bomb? && !tile.revealed? true else false end end end end end
true
cbf0b6170154c9c9cedff10dc8951d3f02557025
Ruby
FusionBolt/PLP-Experiment
/DataTypes/TypeSystemDemo/type.rb
UTF-8
6,287
2.9375
3
[ "MIT" ]
permissive
require './helper' class Fun attr_accessor :name, :params, :body, :param_type_constrains def initialize(name, params, body, type_constrains = {}) @name, @params, @body, @param_type_constrains = name, params, body, type_constrains end def type_valid?(env = {}) @body.type_valid? full_env env end def type(env = {}) params_type(env).append(return_type(env)) end def type_constrains(env = {}, self_constraint = []) if @param_type_constrains.any? @param_type_constrains else # filter :a in constrain # reduce :a's exposure (@body.type_constrains (full_env env), self_constraint).reduce({}) do |sum, (name, constrain)| sum.merge({name => Set.new(remove_excess_generic_a(constrain))}) end end end def params_type(env = {}) if @param_type_constrains.any? @param_type_constrains[0..-2] else # params type and return type constrains = type_constrains env @params.map do |param| constrains.fetch(param, :a) end end end def return_type(env = {}) if @param_type_constrains.any? @param_type_constrains[-1] else @body.type full_env env end end private def remove_excess_generic_a(constrain) # not only :a if constrain.size != 1 constrain.filter { |v| v != :a } else constrain end end def full_env(env) # TODO:change name=>"" env.merge(@param_type_constrains).merge(@params.announce).merge({@name => ""}) end end class SymbolTable < Hash # record(class) member fun/type -> symbol table # function type [param type1, param type2, return type] # variable type-val def initialize num_op = %i[+ - * /] generic_num_op = generate_op_env(num_op, %i[Num Num Num]) comparable_op = %i[< >] generic_comparable_op = generate_op_env(comparable_op, %i[Ord Ord Bool]) op_env = generic_num_op.merge(generic_comparable_op) new_hash = { :Num => generic_num_op, :Ord => generic_comparable_op} update new_hash.merge op_env end private def generate_op_env(op_array, type_constrains) op_array.reduce({}) do |sum, op| sum.merge({op => Fun.new(op, [], [], type_constrains)}) end end end $symbol_table = SymbolTable.new class Literal attr_accessor :val def initialize(val) @val = val end def type_valid? true end def type(env = {}) s = val.class.to_s.to_sym case s in :TrueClass | :FalseClass :Bool in :Integer :Num else s end end def type_constrains(env = {}, self_constraint = []) {} end end class Expr attr_accessor :expr def initialize(expr) @expr = expr end def type_valid?(env = {}) @expr.type_valid? env end def type(env = {}) @expr.type env end def type_constrains(env = {}, self_constraint = []) @expr.type_constrains env end end class Identifier attr_accessor :name, :val def initialize(name, val = nil) @name, @val = name.to_sym, val end def type_valid?(env = {}) (not val.nil?) || (env.has_key? @name) end def type(env = {}) # val is nil then find env # if env not find, is error if val.nil? if env.has_key? @name env[@name].type else raise RuntimeError, 'val is nil, may be not define in this env' end else @val.type env end end def type_constrains(env = {}, self_constraint = []) merge_constrains( generate_map(@name, type(env)), generate_map(@name, self_constraint)) end private def generate_map(name, constrains) { name => Set.new([constrains].flatten) } end end class If attr_accessor :cond_expr, :then_expr, :else_expr def initialize(cond_expr, then_expr, else_expr) @cond_expr, @then_expr, @else_expr = cond_expr, then_expr, else_expr end def type_valid?(env = {}) @cond_expr.type(env) == :Bool && @then_expr.type(env) == @else_expr.type(env) end # type of If is expr def type(env = {}) @then_expr.type env end def type_constrains(env = {}, self_constraint = []) # TODO:refactor merge_constrains( @cond_expr.type_constrains(env, :Bool), merge_constrains( (@then_expr.type_constrains env, self_constraint), (@else_expr.type_constrains env, self_constraint))) end end class BinOp attr_accessor :op, :left_expr, :right_expr def initialize(op, left_expr, right_expr) @op, @left_expr, @right_expr = op.to_sym, left_expr, right_expr end def type_valid?(env = {}) case [@left_expr.type(env), @left_expr.type(env)] in [:a, :a] | [:a, _] | [_, :a] true in [lt, rt] env[lt][@op].params_type[1] == rt end end def type(env = {}) # forbidden define nest fun # so don't process about when expr is a fun case [@left_expr.type(env), @right_expr.type(env)] in [:a, :a] env[@op] in [:a, t] env[t][@op] in [t, :a] env[t][@op] in [lt, rt] env[lt][@op] end.return_type env end def type_constrains(env = {}, self_constraint = []) op = env[@op] merge_constrains( @left_expr.type_constrains(env, op.params_type[0]), @right_expr.type_constrains(env, op.params_type[1])) end end class Generic def type(env = {}) :a end def type_constrains(env = {}, self_constrains = []) {} end def type_valid?(env = {}) true end end class Param < Array attr_accessor :params def initialize(*params) params.each do |v| append v.to_sym end end def announce reduce({}) do |env, name| env.merge({name => Generic.new}) end end end class FunCall attr_accessor :fun_name, :params def initialize(fun_name, params) @fun_name, @params = fun_name.to_sym, params end def type_valid?(env = {}) return false unless env.has_key? @fun_name # except return val env[@fun_name][0..-2] == params.map(&:type) end def type(env = {}) if env.empty? raise RuntimeError, 'call function not exist' end env[@fun_name][-1] end def type_constrains(env = {}, self_constraint = []) params.reduce({}) do |sum, param| merge_constrains(sum, param.type_constrains(env)) end end end
true
e7343c278380af226d922b43296cdaafe641fb71
Ruby
krestenkrab/hotruby
/modules/vm-test/ruby_test/test/core/FileStat/instance/tc_size.rb
UTF-8
919
2.765625
3
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
######################################################################### # tc_size.rb # # Test case for the FileStat#size and File::Stat#size? instance methods. ######################################################################### require 'test/unit' class TC_FileStat_File_Instance < Test::Unit::TestCase def setup @stat = File::Stat.new(__FILE__) @file = RUBY_PLATFORM.match('mswin') ? 'NUL' : '/dev/null' end def test_size_basic assert_respond_to(@stat, :size) assert_respond_to(@stat, :size?) end def test_size assert_kind_of(Fixnum, @stat.size) assert_equal(true, @stat.size > 0) end def test_size_bool assert_not_nil(@stat.size?) assert_nil(File::Stat.new(@file).size?) end def test_size_expected_errors assert_raises(ArgumentError){ @stat.size?(1) } end def teardown @stat = nil @file = nil end end
true
c37c606d2d4d9b3ebb982815885ff08b60b68c58
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/space-age/7d96ec4b063546b3b59ec9975fb2a364.rb
UTF-8
584
3.53125
4
[]
no_license
class SpaceAge attr_reader :seconds def initialize(seconds) @seconds = seconds end private EARTH_YEARS = { earth: 1.0, mercury: 0.2408467, venus: 0.61519726, mars: 1.8808158, jupiter: 11.862615, saturn: 29.447498, uranus: 84.016846, neptune: 164.79132 } SECONDS_PER_YEAR = 60 * 60 * 24 * 365.25 EARTH_YEARS.each do |planet, years| method_name = "on_#{planet}".to_sym define_method(method_name) do (seconds / (EARTH_YEARS[planet] * SECONDS_PER_YEAR)).round(2) end end end
true
9acdf0a41542c227a8d5487d118b64fec6a19c40
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/800/feature_try/method_source/14953.rb
UTF-8
340
3.1875
3
[]
no_license
def combine_anagrams(words) letter_counts = Hash.new words.each do |word| value = count_letters(word) if letter_counts.has_key?(value) then letter_counts[value].push(word) else letter_counts[value] = [word] end end result = [] letter_counts.each_value { |value| result.push(value) } return result end
true
3c57f87671f9a5ab6ce657637f441c793d112b2f
Ruby
edeutschie/Calculator
/ed.calculator.rb
UTF-8
1,958
5.125
5
[]
no_license
# opening statment print "\nAre you ready to do some math?" # establish array of operators operators = [ "add", "+", "subtract", "-", "multiply", "*", "divide", "/" ] # get user input for operation print "\n\nWhat do you want to do? You can enter add, + , subtract, - , multiply, * , divide, or /.\n\n" operation = gets.chomp.downcase # make sure operational input is not erroneous until operators.include?(operation) print "\nThat's not an option. What do you want to do?\n\n" operation = gets.chomp.downcase end # define methods for the 4 possible operations def add(num_one, num_two) return num_one + num_two end def subtract(num_one, num_two) return num_one - num_two end def multiply(num_one, num_two) return num_one * num_two end def divide(num_one, num_two) if num_one == 0 || num_two == 0 return "0" else return num_one / num_two end end # get user input for two numbers print "\nWhat is your first number?\n\n" num_one = gets.chomp integer_version = num_one.to_i until integer_version.to_s == num_one print "\nThat's not a number. What is your first number?\n\n" num_one = gets.chomp integer_version = num_one.to_i end num_one = integer_version print "\nWhat is your second number?\n\n" num_two = gets.chomp integer_version = num_two.to_i until integer_version.to_s == num_two print "\nThat's not a number. What is your second number?\n\n" num_two = gets.chomp integer_version = num_two.to_i end num_two = integer_version # based on the operation selected, determine the method and do the math. if operation == "add" || operation == "+" solution = add(num_one, num_two) elsif operation == "subtract" || operation == "-" solution = subtract(num_one, num_two) elsif operation == "multiply" || operation == "*" solution = multiply(num_one, num_two) elsif operation == "divide" || operation == "/" solution = divide(num_one, num_two) end # print result print "\nYour answer is: #{solution}\n\n"
true
deb385bb297e95da98a011eded2b9ea012462411
Ruby
trailblazer/representable
/test/skip_test.rb
UTF-8
2,994
2.53125
3
[ "MIT" ]
permissive
require "test_helper" class SkipParseTest < MiniTest::Spec representer! do property :title, skip_parse: ->(options) { options[:user_options][:skip?] and options[:fragment] == "skip me" } property :band, skip_parse: ->(options) { options[:user_options][:skip?] and options[:fragment]["name"].nil? }, class: OpenStruct do property :name end collection :airplays, skip_parse: ->(options) { options[:user_options][:skip?] and options[:fragment]["station"].nil? }, class: OpenStruct do property :station end end let(:song) { OpenStruct.new.extend(representer) } # do parse. it do song.from_hash( { "title" => "Victim Of Fate", "band" => {"name" => "Mute 98"}, "airplays" => [{"station" => "JJJ"}] }, user_options: {skip?: true} ) _(song.title).must_equal "Victim Of Fate" _(song.band.name).must_equal "Mute 98" _(song.airplays[0].station).must_equal "JJJ" end # skip parsing. let(:airplay) { OpenStruct.new(station: "JJJ") } it do song.from_hash( { "title" => "skip me", "band" => {}, "airplays" => [{}, {"station" => "JJJ"}, {}] }, user_options: {skip?: true} ) _(song.title).must_be_nil _(song.band).must_be_nil _(song.airplays).must_equal [airplay] end end class SkipRenderTest < MiniTest::Spec representer! do property :title property :band, skip_render: ->(options) { options[:user_options][:skip?] and options[:input].name == "Rancid" } do property :name end collection :airplays, skip_render: ->(options) { options[:user_options][:skip?] and options[:input].station == "Radio Dreyeckland" } do property :station end end let(:song) { OpenStruct.new(title: "Black Night", band: OpenStruct.new(name: "Time Again")).extend(representer) } let(:skip_song) { OpenStruct.new(title: "Time Bomb", band: OpenStruct.new(name: "Rancid")).extend(representer) } # do render. it { _(song.to_hash(user_options: {skip?: true})).must_equal({"title" => "Black Night", "band" => {"name"=>"Time Again"}}) } # skip. it { _(skip_song.to_hash(user_options: {skip?: true})).must_equal({"title"=>"Time Bomb"}) } # do render all collection items. it do song = OpenStruct.new(airplays: [OpenStruct.new(station: "JJJ"), OpenStruct.new(station: "ABC")]).extend(representer) _(song.to_hash(user_options: {skip?: true})).must_equal({"airplays"=>[{"station"=>"JJJ"}, {"station"=>"ABC"}]}) end # skip middle item. it do song = OpenStruct.new( airplays: [ OpenStruct.new(station: "JJJ"), OpenStruct.new(station: "Radio Dreyeckland"), OpenStruct.new(station: "ABC") ] ).extend(representer) _(song.to_hash(user_options: {skip?: true})).must_equal({"airplays"=>[{"station"=>"JJJ"}, {"station"=>"ABC"}]}) end end
true
a2099dcbcde25ee83b2975f35c946326ad2e7f55
Ruby
emalfano/intro-to-programming
/loops_and_iterators/ex1.rb
UTF-8
115
3.375
3
[]
no_license
x = [1, 2, 3, 4, 5] x.each do |a| a + 1 end # the each expression returns the original array, a + 1 does nothing
true
8fcfa306b093035cdfa18b388740538b2be1d5e4
Ruby
charlesbjohnson/super_happy_interview_time
/rb/lib/leetcode/lc_108.rb
UTF-8
1,037
3.5
4
[ "MIT" ]
permissive
# frozen_string_literal: true module LeetCode # 108. Convert Sorted Array to Binary Search Tree module LC108 TreeNode = Helpers::LeetCode::BinaryTree::TreeNode # Description: # Given an integer array nums where the elements are sorted in ascending order, # convert it to a height-balanced binary search tree. # # A height-balanced binary tree is a binary tree in which the depth of # the two subtrees of every node never differs by more than one. # # Examples: # Input: nums = [-10, -3, 0, 5, 9] # Output: [0, -3, 9, -10, null, 5] # # Input: nums = [1, 3] # Output: [3, 1] # # @param {Array<Integer>} nums # @return {TreeNode} def sorted_array_to_bst(nums) rec = ->(l, r) { return if l > r return TreeNode.new(nums[l]) if l == r m = ((r - l + 1) / 2) + l TreeNode.new( nums[m], rec.call(l, m - 1), rec.call(m + 1, r) ) } rec.call(0, nums.length - 1) end end end
true
6e5aecec64c7b69ace8392a5f0d79f20497f2158
Ruby
bernerdschaefer/svg
/lib/svg/canvas.rb
UTF-8
899
2.84375
3
[]
no_license
module SVG class Canvas < XML::Document include NodeHelpers # @param width the canvas width # @param height the canvas height def initialize(width, height) super() self.root = SVG::Node.new "svg", version: "1.1", xmlns: "http://www.w3.org/2000/svg", width: width, height: height end # Adds the provided node to the root node. # # @param [SVG::Node] node the node to append def <<(node) root << node end # @param property the property to return # @return [String] the value of the property on the root node def [](property) root[property] end # Sets the value of the given property on the root node. # # @param property the property to set # @param value the value to set the property to def []=(property, value) root[property] = value end end end
true
ec92574fed802fa38df98d8a8f283345570f7d01
Ruby
taw/project-euler
/euler_38.rb
UTF-8
284
2.734375
3
[]
no_license
#!/usr/bin/env ruby1.9 rv = [] (1...100_000).each{|k| v = "" (1..9).each{|i| v += (k*i).to_s next if v.size < 9 break if v.size > 9 break if v =~ /0/ if v.split(//).uniq.size == 9 p [v.to_i, k, i] rv << [v.to_i, k, i] end } } p rv p rv.max
true
527a30f805becfb41da55671fc6a300b9e53d01b
Ruby
davidlesches/infuser
/lib/infuser/helpers/hashie.rb
UTF-8
317
2.609375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
module Infuser module Helpers module Hashie def camelize_hash hash hash.each_with_object({}) do |(key, value), h| h[key.to_s.split('_').map { |w| safe_classify(w) }.join] = value end end def safe_classify w w[0] = w[0].upcase; w end end end end
true
27ef7b369edb8535213816a6664227dc3161ca33
Ruby
konomi1/ruby
/compare.rb
UTF-8
130
3.125
3
[]
no_license
total=100 if total<200 puts "合計は200未満です。" end if total>=150 puts"合計は150以上です。" end
true
6d43769f811c3868b5a193fa1abce236d1a2dea1
Ruby
camisoul/atcoder
/ABC/056/A/ruby/test.rb
UTF-8
93
2.796875
3
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true a, b = gets.split puts a == b ? 'H' : 'D'
true
25a3aac7a4f9f1ba78b6ca188a08fc7283f2a259
Ruby
Ninigi/upsalla
/lib/helpers/string_helper.rb
UTF-8
392
2.875
3
[ "MIT" ]
permissive
module Upsalla module StringHelper def snake_case(string) return string.downcase if string.match(/\A[A-Z]+\z/) string. gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2'). gsub(/([a-z])([A-Z])/, '\1_\2'). downcase end def demodulize(string) if i = string.rindex("::") string[(i+2)..-1] else string end end end end
true
9c115b4ab3511022f75330b4f96cf98a081879cd
Ruby
MDes41/exercism
/ruby/prime-factors/prime_factors.rb
UTF-8
537
3.703125
4
[]
no_license
#all working but needs to be cleaned up class PrimeFactors def self.for(number) final = [number] result = [] divisor = 2 loop do break if number == 1 break if result.reduce(:*) == final.first while divisor <= final.first if number % divisor != 0 divisor += 1 elsif number == divisor result << divisor divisor = final.first + 1 else number = number / divisor result << divisor end end end result end end
true
019914c16ed65fecfec77105d91bdf0b9e08b084
Ruby
adynata/EmotionalWeatherReport
/app/models/feel.rb
UTF-8
3,030
2.53125
3
[]
no_license
# == Schema Information # # Table name: feels # # id :integer not null, primary key # feel :string not null # user_id :integer not null # created_at :datetime not null # updated_at :datetime not null # class Feel < ActiveRecord::Base attr_accessor :raw_feelers, :color, :mapped_colors validates :user, :feel, presence: true before_save :mapped_colors, :color belongs_to :user has_many :connections has_many( :friends, through: :connections, source: :users ) # there are 15 categories of feelings! FEELS_CAT_HUES = { "AFRAID"=> "ffcb00", "ANNOYED"=> "ff9966", "ANGRY"=> "ff4c00", "AVERSION"=> "a9ff25", "CONFUSED"=> "cc00ff", "DISCONNECTED"=> "bbdd55", "DISQUIET"=> "3200ff", "EMBARRASSED"=> "ff4433", "FATIGUE"=> "ffcb99", "PAIN"=> "ff0011", "SAD"=> "66ddff", "TENSE"=> "feff99", "VULNERABLE"=> "99ffcc", "YEARNING"=> "7c26ff", "AFFECTIONATE"=> "9865ff", "ENGAGED"=> "df6628", "HOPEFUL"=> "00ffcb", "CONFIDENT"=> "3366ff", "EXCITED"=> "00ffb2", "GRATEFUL"=> "e565ff", "INSPIRED"=> "65cbff", "JOYFUL"=> "65ff98", "EXHILARATED"=> "ff3fff", "PEACEFUL"=> "7fff65", "REFRESHED"=>"9999ff" } def color @color = Feel.mapped_colors[self.feel] end def self.raw_feelers File.readlines("#{Rails.root.to_s}/lib/assets/inventory.txt").map(&:chomp) end def self.feels_tree feels_tree = Hash.new { |h, k| h[k] = {} } feel_class = nil current_feel_category = nil raw_feelers.each do |feel| if feel[0] == "_" feel_class = feel[1..-1] feels_tree[feel_class] = {} elsif !feel.match(/\p{Lower}/) current_feel_category = feel feels_tree[feel_class][current_feel_category] = [] else feel.match(/\p{Lower}/) feels_tree[feel_class][current_feel_category] << feel end end feels_tree end def self.feels_tree_neg self.feels_tree["NEGATIVE"] end def self.feels_tree_pos self.feels_tree["POSITIVE"] end def self.all_feels feels_only = [] raw_feelers.each do |feel| feels_only << feel if feel.match(/\p{Lower}/) end feels_only end def self.mapped_colors colors = feels_tree @mapped_colors = {} FEELS_CAT_HUES.each do |k,v| if colors["POSITIVE"][k] idx = colors["POSITIVE"][k].count feelers = colors["POSITIVE"][k] color = Paleta::Color.new(:hex, v ) palette = Paleta::Palette.generate(:type => :analogous, :from => :color, :size => idx, :color => color) (0...idx).each do |i| @mapped_colors[feelers[i]] = palette[i].hex end else idx = colors["NEGATIVE"][k].count feelers = colors["NEGATIVE"][k] color = Paleta::Color.new(:hex, v) palette = Paleta::Palette.generate(:type => :analogous, :from => :color, :size => idx, :color => color) (0...idx).each do |i| @mapped_colors[feelers[i]] = palette[i].hex end end end @mapped_colors end end
true
9aeba903b93f735230fccfc18f6342d161b10c58
Ruby
YOUSUKE0601/ruby-practice
/ruby_practice1/reizoko.rb
UTF-8
1,217
3.59375
4
[]
no_license
require "./power.rb" # 冷蔵庫モデルA クラス class ReizoukoA # 設定温度を受け取ってインスタンス変数を保持する def initialize(num) @set_temperature = num.to_i @temperature = 25 @foodstuff = [] power(:on) puts "設定温度を #{@set_temperature}に設定しました" puts "現在の温度は #{@temperature}です" puts "#{@foodstuff.size}個の食材があります" end #冷やす機能:1回で-1℃冷える def cool_down @temperature -= 1 if @set_temperature < @temperature puts "内部を冷やして#{@temperature}になりました" end #ドアが開く機能 #内部温度が上昇する。 食材を一覧表示する def open_door @temperature += 3 puts "内部温度が上昇して#{@temperature}になりました" puts "#{@foodstuff.size}個の食材があります" @foodstuff.each do |v| puts v end end #冷蔵庫に食材を入れる def put_in(str) @foodstuff << str end include Power end if __FILE__ == $0 then modelA = ReizoukoA.new(15) modelA.cool_down modelA.put_in("apple") modelA.open_door modelA.power(:off) end
true
244deda55a0548ee4fb958004122442d2b3fd989
Ruby
luismulinari/timestamp-estrito
/timestamp.rb
UTF-8
4,271
2.734375
3
[]
no_license
class Transacao attr_accessor :dados_bloqueados attr_reader :id, :ts, :historia def initialize(historia, ts, id) @historia = historia.chomp("\n") @operations = Array.new @historia.split(' ').each { |a| @operations.push Operacao.new(a[0,1], a[2,1]) } @ts = ts @id = id p "Transacao criada #{@id}, #{@historia}" @dados_bloqueados = Hash.new end def next_operation @operations.first end def finished? @operations.empty? end def execute(dado) op = @operations.first @operations.delete_at(0) if op.type == 'r' then if dado.ts_read < @ts then dado.ts_read = @ts end else dado.current_transaction = @id @dados_bloqueados[dado.value] = dado dado.ts_write = @ts end p "Executada thread: #{@id.to_s}; timestamp: #{@ts}; operacao: #{op.type}; dado: #{dado.value};" end def abort dado op = @operations.first p "Abortada thread: #{@id.to_s};timestamp: #{@ts}; operacao: #{op.type}; dado: #{dado.value};" end def to_s "<Transacao: ID: #{@id};TS #{@ts};HIS #{@historia};OPS: #{@operations.to_s}>" end end class Operacao attr_reader :type, :dado def initialize type, dado @type = type @dado = dado end def to_s "<Operacao: TYPE: #{@type};DADO #{@dado}>" end end class Dado attr_reader :value attr_accessor :ts_read, :ts_write, :current_transaction, :fila_wait def initialize value, ts_read, ts_write @value = value @ts_read = ts_read @ts_write = ts_write @current_transaction = nil @fila_wait = Array.new end end class Scheduler def self.schedule transactions p "//=================================//", "Iniciando scheduling" dados = Hash.new while !transactions.empty? do posicao = rand(transactions.size) t = transactions[posicao] p "Selecionada thread: #{t.id.to_s}, #{t.historia}" if t.finished? then transactions.delete(t.id) t.dados_bloqueados.each { |k, db| db.current_transaction = nil if !db.fila_wait.empty? t_wait = db.fila_wait.pop transactions[t_wait.id] = t_wait end } p "Commiting thread: #{t.id.to_s}" next end operation = t.next_operation if (!dados.key?(operation.dado)) then dados[operation.dado] = Dado.new(operation.dado, 0, 0) end dado_atual = dados[operation.dado] if !dado_atual.current_transaction.nil? && dado_atual.current_transaction != t.id && t.ts > dado_atual.ts_write then dado_atual.fila_wait.insert(0, t) transactions.delete(t.id) p "Incluindo na fila wait #{t.id}, #{operation.type}(#{dado_atual.value})" next end if operation.type == 'r' then if t.ts < dado_atual.ts_write then t.abort dado_atual t.dados_bloqueados.each { |k, db| db.current_transaction = nil if !db.fila_wait.empty? t_wait = dado_atual.fila_wait.pop p 'remove wait' transactions[t_wait.id] = t_wait end } transactions[t.id] = Transacao.new(t.historia, Time.new.to_i, t.id) else t.execute dado_atual end # ts comparison else if ((t.ts < dado_atual.ts_read) || (t.ts < dado_atual.ts_write)) then t.abort dado_atual transactions[t.id] = Transacao.new(t.historia, Time.new.to_i, t.id) t.dados_bloqueados.each { |k, db| db.current_transaction = nil if !db.fila_wait.empty? t_wait = dado_atual.fila_wait.pop p 'remove wait' transactions[t_wait.id] = t_wait end } else t.execute dado_atual end #ts comparison end # operation type end #while p "Escalonamento terminado", "//=================================//" end end @transactions = Hash.new f = File.new(ARGV[0]) f.each_line { |line| p "Lendo transacao: #{line.chomp!}" ts = rand(10) id = f.lineno - 1 @transactions[id] = Transacao.new(line, ts, id) } Scheduler.schedule(@transactions)
true
604b220504226303759d5be5df3047c01ce4cb28
Ruby
kdow/slack-cli
/lib/channel.rb
UTF-8
1,002
2.90625
3
[]
no_license
require_relative "recipient" require 'dotenv' Dotenv.load module SlackCLI class Channel < Recipient attr_reader :topic, :member_count def initialize(slack_id:, name:, topic:, member_count:) super(slack_id: slack_id, name: name) @topic = topic @member_count = member_count end def self.list url = "https://slack.com/api/channels.list" data = { "token": ENV["SLACK_API_TOKEN"], } response = self.get(url, data) channels = [] response["channels"].each do |channel| slack_id = channel["id"] name = channel["name"] topic = channel["topic"]["value"] member_count = channel["num_members"] channel = self.new(slack_id: slack_id, name: name, topic: topic, member_count: member_count) channels << channel end return channels end def details return "Slack ID: #{slack_id}, Name: #{name}, Topic: #{topic}, Member count: #{member_count}" end end end
true
b5a0ac38867f7fddd29cfb45211bfbfb77d4774b
Ruby
lsowen/pentestpackage
/gppdecrypt.rb
UTF-8
525
3.125
3
[]
no_license
require 'rubygems' require 'openssl' require 'base64' encrypted_data = ARGV def decrypt(encrypted_data) padding = "=" * (4 - (encrypted_data.length % 4)) epassword = "#{encrypted_data}#{padding}" decoded = Base64.decode64(epassword) key = "\x4e\x99\x06\xe8\xfc\xb6\x6c\xc9\xfa\xf4\x93\x10\x62\x0f\xfe\xe8\xf4\x96\xe8\x06\xcc\x05\x79\x90\x20\x9b\x09\xa4\x33\xb6\x6c\x1b" aes = OpenSSL::Cipher::Cipher.new("AES-256-CBC") aes.decrypt aes.key = key plaintext = aes.update(decoded) plaintext << aes.final pass = plaintext.unpack('v*').pack('C*') # UNICODE conversion return pass end blah = decrypt(encrypted_data) puts blah
true
02d4a0dbb53f2b8ef2a2dbe0541e2be22b4be5f7
Ruby
tongxm520/ruby-code
/ClassicalProgram/lib/enumerable.rb
UTF-8
3,285
3.6875
4
[]
no_license
#encoding:utf-8 class Undergraduate attr_accessor :student_no, :name, :gender, :birthday, :credit def age Time.now.year-self.birthday.year end def display_full_info puts "#{self.name},#{self.student_no},#{self.gender},#{self.age},#{self.credit}" end def self.max_age(first,*rest) # Assume that the required first argument is the largest max = first # Now loop through each of the optional arguments looking for bigger ones rest.each {|x| max = x if x.age > max.age } # Return the largest one we found "#{max.name}的年龄最大,#{max.age}岁" end def Undergraduate.display(undergraduates) undergraduates.each do |e| e.display_full_info end end end undergraduates =Array.new alice =Undergraduate.new alice.student_no = "0603020215" alice.name = "Alice" alice.gender = "female" alice.birthday = Time.local(1985, 7, 18) alice.credit = 5 undergraduates << alice sam =Undergraduate.new sam.student_no="0603020216" sam.name= "Sam" sam.gender="male" sam.birthday=Time.local(1986, 9, 5) sam.credit=4 undergraduates << sam nash =Undergraduate.new nash.student_no="0603020217" nash.name= "Nash" nash.gender="male" nash.birthday=Time.local(1988, 12, 30) nash.credit=4 undergraduates << nash kitty =Undergraduate.new kitty.student_no="0603020218" kitty.name= "Kitty" kitty.gender="female" kitty.birthday=Time.local(1989, 4, 1) kitty.credit=3 undergraduates << kitty newton =Undergraduate.new newton.student_no="0603020219" newton.name= "牛顿" newton.gender="male" newton.birthday=Time.local(1984, 6, 21) newton.credit=3 undergraduates << newton puts "the age of kitty is #{kitty.age}" duplicates_count =undergraduates.length undergraduates =undergraduates.uniq puts undergraduates.methods.grep(/length/) puts undergraduates.length==duplicates_count-1 puts undergraduates.include?(newton) puts undergraduates.index(nash) names =undergraduates.map {|undergraduate| undergraduate.name} puts names.inspect #total_credit = undergraduates.inject {|sum, undergraduate| sum + undergraduate.credit } #puts total_credit puts (1..10).inject {|sum, n| sum + n} puts [2,5,6].inject(1) {|product, n| product * n } # find the longest word names =undergraduates.collect {|undergraduate| undergraduate.name} longest = names.inject do |memo,word| memo.length > word.length ? memo : word end puts "'#{longest}'的长度为:#{longest.length}" female_undergraduates =undergraduates.select {|undergraduate| undergraduate.gender=="female"} puts "female undergraduates:" Undergraduate.display(female_undergraduates) male_undergraduates =undergraduates.reject {|undergraduate| undergraduate.gender=="female"} puts "male undergraduates:" Undergraduate.display(male_undergraduates) fruit_by_length =%w{ apple pear fig }.sort_by {|word| word.length} puts "fruit_by_length:" puts fruit_by_length undergraduates_by_name = undergraduates.sort_by {|undergraduate|undergraduate.name} Undergraduate.display(undergraduates_by_name) groups = undergraduates.partition { |u| u.gender == "male" } puts "male undergraduates:" Undergraduate.display(groups[0]) puts "female undergraduates:" Undergraduate.display(groups[1]) puts "男毕业生中:#{Undergraduate.max_age(*groups[0])}" #Undergraduate.max_age(groups[0])会出错
true
30a1d00b8c46d080d1b62943caa629378a5a3967
Ruby
carolyny/launchschool
/Backend/101/Exercises/halvsies.rb
UTF-8
409
3.59375
4
[]
no_license
def halvsies(array) array1=[] array2=[] index = 0 loop do array1 << array[index] index+=1 break if index >= array.size/2.0 end loop do break if index >= array.size array2 << array[index] index+=1 end result = [array1,array2] end puts halvsies([1, 2, 3, 4]) == [[1, 2], [3, 4]] puts halvsies([1, 5, 2, 4, 3]) == [[1, 5, 2], [4, 3]] puts halvsies([5]) == [[5], []] puts halvsies([]) == [[], []]
true
c8574d33a70eb895a1801301c3996de1a3dcb63f
Ruby
r-osoriobarra/desafios_array_archivos_27-05-21
/calculo_notas2.rb
UTF-8
351
3.296875
3
[]
no_license
#Desafío 3 - calculo_notas 2 #leer el archivo y transformarlo a array data = (File.open('notas.data').read).split("\n") marks = data.map {|e| e.split(',')} #lógica de nota mayor def nota_mas_alta(array) high_marks = array.map do |i| i.map {|e| e.to_i}.max end return high_marks end nota_mas_alta(marks)
true
ea2e1df9093b6b4ba79aecc51673e5c397b400fd
Ruby
CspenceGroup/LouisianaCalling-api
/app/helpers/program_helper.rb
UTF-8
1,846
2.578125
3
[]
no_license
module ProgramHelper include ApplicationHelper # Get regions query string def regions_query_str(region_ids) region_ids = region_ids.split(',') list_of_regions = convert_regions_to_hash regions = region_ids.map { |region| "'#{list_of_regions[region.to_i]}'" } "region IN (#{regions.join(',')})" end # Get programs durations query string def programs_query_str(program_duration_ids) program_duration_ids = program_duration_ids.split(',') program_durations = Constants::PROGRAM_DURATIONS program_q = ['('] program_duration_ids.each_with_index do |id, index| if index.zero? program_q.push "duration like '%#{program_durations[id.to_i]}%'" else program_q.push "OR duration like '%#{program_durations[id.to_i]}%'" end end program_q.push ')' program_q.join('') end # Get times per week query string def hours_query_str(hour_per_week_ids) hour_per_week_ids = hour_per_week_ids.split(',') hours_per_weeks = Constants::HOURS_PER_WEEK hours_q = ['('] hour_per_week_ids.each_with_index do |id, index| if index.zero? hours_q.push "hours_per_weeks like '%#{hours_per_weeks[id.to_i]}%'" else hours_q.push "OR hours_per_weeks like '%#{hours_per_weeks[id.to_i]}%'" end end hours_q.push ')' hours_q.join('') end # Get time of day query string def times_query_str(time_of_day_ids) time_of_day_ids = time_of_day_ids.split(',') times_of_day = Constants::TIME_OF_DAY times_q = ['('] time_of_day_ids.each_with_index do |id, index| if index.zero? times_q.push "time_of_day like '%#{times_of_day[id.to_i]}%'" else times_q.push "OR time_of_day like '%#{times_of_day[id.to_i]}%'" end end times_q.push ')' times_q.join('') end end
true
9f9715e8678fac69922dc3514150d1cba7623f5f
Ruby
EduardoLecaros/EconomicSim
/Data/PriceBelief.rb
UTF-8
911
3.5625
4
[]
no_license
#PriceBelief.rb require_relative '../Utilities/Extensions' class PriceBelief MIN_SPAN = 2.0 MIN_PRICE = 0.01 attr_reader :min, :max def initialize(min, max) @min = min @max = max end def choose_price @min + rand(@max - @min) end def narrow(narrow_amount) new_min = @min + narrow_amount new_max = @max - narrow_amount new_belief = PriceBelief.new(new_min, new_max) unless new_belief.span < MIN_SPAN @min = new_min @max = new_max end end def expand(expand_amount) new_min = @min - expand_amount @min = new_min unless new_min <= MIN_PRICE @max += expand_amount end def translate(amount) new_min = @min + amount new_max = @max + amount @min = new_min unless new_min <= MIN_PRICE @max = new_max unless new_max <= MIN_PRICE end def span @max - @min end def mean Math.avg(@min, @max) end end
true
d84ce6f6c71d93210d03fa93e47dc2534bbdebbe
Ruby
Liam-Williams/lighthouse
/week1/day3/pop_bottles.rb/pop_bottles.rb
UTF-8
557
3.8125
4
[]
no_license
def total_bottles(money) @bottles = money.to_i / 2 @empty_bottles_to_bottles = @bottles / 2 @caps_to_bottles = (@empty_bottles_to_bottles / 4) + @bottles @empty_bottles_leftover = @bottles % 2 @caps_leftover = @bottles % 4 @total_bottles = @empty_bottles_to_bottles + @caps_to_bottles + @bottles puts "You have a total of #{@total_bottles} bottles of pop. You have #{@empty_bottles_leftover} empty bottles\nand you have #{@caps_leftover} bottles caps left over." end total_bottles(20)
true
3629366ea6b999167916ac7b09b86b0838f4cc6e
Ruby
495-Labs-Projects/ChoreTrackerAPI
/app/controllers/tasks_controller.rb
UTF-8
3,164
2.609375
3
[]
no_license
class TasksController < ApplicationController # This is to tell the gem that this controller is an API swagger_controller :tasks, "Tasks Management" # Each API endpoint index, show, create, etc. has to have one of these descriptions # This one is for the index action. The notes param is optional but helps describe what the index endpoint does swagger_api :index do summary "Fetches all Tasks" notes "This lists all the tasks" end # Show needs a param which is which task id to show. # The param defines that it is in the path, and that it is the Task's ID # The response params here define what type of error responses can be returned back to the user from your API. In this case the error responses are 404 not_found and not_acceptable. swagger_api :show do summary "Shows one Task" param :path, :id, :integer, :required, "Task ID" notes "This lists details of one task" response :not_found end # Create doesn't take in the task id, but rather the required fields for a task (namely first_name and last_name) # Instead of a path param, this uses form params and defines them as required swagger_api :create do summary "Creates a new Task" param :form, :name, :string, :required, "Name" param :form, :points, :integer, :required, "Points" param :form, :active, :boolean, :required, "Active" response :not_acceptable end # Update requires the task id but you can also change the first_name and/or last_name of the task. # Again since it takes in an task id, it can be not found. # Also this will have both path and form params swagger_api :update do summary "Updates an existing Task" param :path, :id, :integer, :required, "Task Id" param :form, :name, :string, :optional, "Name" param :form, :points, :integer, :optional, "Points" param :form, :active, :boolean, :optional, "Active" response :not_found response :not_acceptable end # Lastly destroy is just like the rest and just takes in the param path for task id. swagger_api :destroy do summary "Deletes an existing Task" param :path, :id, :integer, :required, "Task Id" response :not_found end # Controller code before_action :set_task, only: [:show, :update, :destroy] # GET /tasks def index @tasks = Task.all render json: @tasks end # GET /tasks/1 def show render json: @task end # POST /tasks def create @task = Task.new(task_params) if @task.save render json: @task, status: :created, location: @task else render json: @task.errors, status: :unprocessable_entity end end # PATCH/PUT /tasks/1 def update if @task.update(task_params) render json: @task else render json: @task.errors, status: :unprocessable_entity end end # DELETE /tasks/1 def destroy @task.destroy end private # Use callbacks to share common setup or constraints between actions. def set_task @task = Task.find(params[:id]) end # Only allow a trusted parameter "white list" through. def task_params params.permit(:name, :points, :active) end end
true
a5be0f2d6c9c3b4099fc0598c2f5f7161b95a62d
Ruby
tylerball/raw2jpg
/raw2jpg
UTF-8
3,702
2.609375
3
[]
no_license
#!/usr/bin/env ruby require 'open3' require 'optparse' require 'tmpdir' require 'fileutils' require 'shellwords' require 'byebug' if ENV['DEBUG'] options = { formats: ['raf', 'nef', 'cr2'], } opts = OptionParser.new do |opts| opts.banner = "Usage: raw2jpg [options] [directories]" opts.on("-e", "--extensions [FORMATS]", Array, "Extensions to search, comma seperated (default 'raf,nef,cr2')") do |value| options[:formats] = value end opts.on("-v", "--[no-]verbose", "Run verbosely") do |value| options[:verbose] = value end opts.on("-c", "--[no-]cra", "Overwrite jpgs when raw file has Camera Raw adjustments") do |value| options[:cra] = value end opts.on("-f", "--force", "Overwrite existing jpgs") do |value| options[:force] = value end opts.on("-h", "--help", "Prints this help") do puts opts exit end end.parse! class Step def initialize(input, output = nil) @input = input @output = output end end class ConvertWithCRA < Step def do puts "converting to DNG with Camera Raw Adjustments" out, _ = Open3.capture2("/Applications/Adobe DNG Converter.app/Contents/MacOS/Adobe DNG Converter", '--args', '-p2', "-d #{@output}", @input) out end end class ConvertExifTool < Step def do out = '' orientation, _ = Open3.capture2("exiftool -Orientation# \"#{@input}\"") out << orientation orientation.gsub!(/^.*: /, '').gsub!("\n", '') convert, _ = Open3.capture2("exiftool -b -JpgFromRaw \"#{@input}\" > \"#{@output}\"") out << convert write_orientation, _ = Open3.capture2("exiftool -Orientation#=\"#{orientation}\" \"#{@output}\" -overwrite_original_in_place") out << write_orientation out end end class ConvertSips < Step def do out, _ = Open3.capture2("sips -s format jpeg \"#{@input}\" --out \"#{@output}\"") out end end class CleanupDNG < Step def do FileUtils.rm(@input) end end class Processor attr_accessor :file def initialize(file, options) @file = file @options = options end def should_process? return true if @options[:cra] and has_cra? return true if File.exist?(output) and @options[:force] return false if File.exist?(output) true end def process steps = [] if has_cra? steps << ConvertWithCRA.new(@file , Shellwords.escape(File.dirname(base))) steps << ConvertExifTool.new("#{base}.dng", "#{base}.jpg") steps << CleanupDNG.new("#{base}.dng") else steps << ConvertSips.new(@file, "#{base}.jpg") end steps.each do |step| out = step.do puts out if @options[:verbose] end end def output @output ||= "#{base}.jpg" end def has_cra? fname = "#{base}.xmp" @has_cra ||= begin return false unless File.exist?(fname) File.read(fname).include?('crs:ProcessVersion') end end def base @base ||= @file.gsub(File.extname(@file), '') end end if ARGV.empty? puts opts.options.help exit end dirs = ARGV.first.split(',') puts "Finding raw files..." files = dirs.map do |dir| glob = "/**/*.{#{options[:formats].join(',')}}" files = Dir.glob(File.join(dir, glob), File::FNM_CASEFOLD) files.map! do |file| Processor.new(file, options) end.select! do |p| p.should_process? end files end.flatten! if files.empty? puts "No files found." exit end total = files.size puts "#{total} files to process" files.each_with_index do |processor, i| count = i + 1 puts "#{' ' * (total.to_s.size - count.to_s.size)}#{count}/#{total} converting #{processor.file}" processor.process end
true
417b4bc2c36e3157ec0d43342d08f20c0acc9002
Ruby
joyhuangg/my-select-dumbo-web-080618
/lib/my_select.rb
UTF-8
167
3.453125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_select(collection) i = 0 result = [] while i < collection.length if yield collection[i] result.push(collection[i]) end i += 1 end result end
true
1ecb363f1abab5b2090ec1d0325350fcca792515
Ruby
elizabethengelman/lil-blue-feeder
/logger.rb
UTF-8
620
3.015625
3
[]
no_license
require 'serialport' class Logger PORT = '/dev/tty.usbmodem1411' BAUD_RATE = 9600 DATA_BITS = 8 STOP_BITS = 1 PARITY = SerialPort::NONE def start puts "Startinglogger" log_loop end def serial_port SerialPort.new(PORT, BAUD_RATE, DATA_BITS, STOP_BITS, PARITY) end def log_loop while true do while(i = serial_port.gets.chomp) do write_to_file(i) puts i end end end def write_to_file(event) log_entry = "#{Time.now}: #{event}\n" File.open('lil_b_feeder.log', 'a') do |file| file.write(log_entry) end end end Logger.new.start
true
ffaa55f8bf2fb2a42f22b32f5414bd237bd96dc6
Ruby
siwka/target_sum
/lib/quest.rb
UTF-8
3,122
3.078125
3
[]
no_license
require 'calculator' require 'array' class Quest attr_accessor :cli, :calculator, :full_menu, :target, :prices, :values def initialize(cli) @full_menu = {} @prices, @values, @results = Array.new @calculator = Calculator.new @cli = cli end def start cli.exit_with_error_message unless @cli.arguments_any? cli.read_csv_file @target = @cli.read_target cli.announce_bad_target if @target <= 0 # add_options prices vs total, etc @full_menu = @cli.read_menu @prices = @full_menu.values.read_prices.reject_expensive(@target) @values, solvable = @calculator.possible_solution_exist?(@prices, @target) unless @prices.empty? @prices = [] unless solvable @prices.empty? end def run_boring_menu boring_menu = @prices.divisors_of(@target) @results = [] unless boring_menu.nil? || boring_menu[0].empty? boring_menu[1].to_money @results << boring_menu[0].match_with(@full_menu, boring_menu[1]) end end def run_permutation return unless cli.all_choices? limit_entree_qty = [] limit_entree_qty.calculate_limits(@target, @prices) max_qty = Calculator.new numers_range_for_choice = max_qty.adjust_limits(limit_entree_qty, @prices) cli.statistics(@full_menu, @target, numers_range_for_choice) cli.display_machine_thinking perm = (0..numers_range_for_choice).to_a.repeated_permutation(@prices.length).to_a cli.display_nr_of_combinations(perm.count) perm.reject_each_more_than(limit_entree_qty) prices_subsets = perm.check_subsets_for_sum(@prices, @target) @results = prices_subsets.match_prices_with_entrees(@full_menu, @prices) end def run_knapsack # Knapsack algorithm passes tests # knapsack works as expected. This solution would made sense if we use val array as e.g. calories intake. # In this case we'd look for solution of max calorie intake with price limit set by target. # @values = Array.new(@prices.length, 1) # does not support receiving closest total value to target # @prices.shuffle! # run_knapsack results vary on array elements ordered differently knapsack, keepitem = @calculator.knapsack_no_repetition(@target, @prices, @values) result_items = @calculator.retireve_solution_from(keepitem, @target, @prices) selected_prices = result_items.retireve_from(@prices) # puts "\nprices------\n" # print @prices # puts "\ntotal------\n" # print @prices.reduce(:+) # puts "\n========\n" # print result_items # puts "\nselected prices------\n" # print selected_prices # puts "\ntotal------\n" # puts selected_prices.reduce(:+) if selected_prices.reduce(:+) == @target @results = Array.new(selected_prices.length,1).match_with(@full_menu, selected_prices.to_money) else @results = [] end # puts "\n********************\n" # puts @target # print @results # puts "\n********************\n" # @results end def finish if @results.empty? cli.announce_no_combination(@target) else cli.announce_combination(@target, @results) end end end
true
73fff125ce6779eda183d5c2b62d7a3982c03c07
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/1130/source/2106.rb
UTF-8
307
3.234375
3
[]
no_license
def combine_anagrams(words) hash = Hash.new words.each do |word| normalized = word.downcase.chars.sort.join if (hash[normalized] == nil) hash[normalized] = Array.new end hash[normalized]<<word end array = Array.new hash.each_value { |value| array<<value } return array end
true
28a2bdd831f6db6444b9fa9fe033043dd33431fb
Ruby
GianlucaAnsaldi/chitter-challenge
/lib/peep.rb
UTF-8
508
2.984375
3
[]
no_license
require 'pg' require_relative './database_connection' class Peep attr_reader :user_id, :create_time, :body def initialize(user_id:, create_time:, body:) @user_id = user_id @create_time = create_time @body = body end def self.all peeps = DatabaseConnection.query('SELECT * FROM peeps ORDER BY create_time DESC;') peeps.map do |peep| Peep.new( user_id: peep['user_id'], create_time: peep['create_time'], body: peep['body'] ) end end end
true
3f17abb3e62ecae234ba3cb59c76aea0573ad472
Ruby
rickcid/Ruby-Exercises
/RubyExercise10.rb
UTF-8
278
3.625
4
[]
no_license
puts 'RUBY EXERCISES ASSIGNMENT' puts '' puts 'EXERCISE 10' puts '' #Ruby 1.9 method h = {a: 1, b: 2, c: 3, d: 4} puts h h[:e] = 5 puts h puts '' #Ruby 1.8 method new_hash = {:a => '500', :b => '600', :c => '700', :d => '800'} puts new_hash new_hash[:e] = "5" puts new_hash
true
f8fbec4e7dd62d1c89b72871ccd7b7ffa3c7e8ba
Ruby
urbanczykd/rev0
/Bowling/app/models/games/bowling/game.rb
UTF-8
2,126
3.515625
4
[]
no_license
module Games module Bowling class Game < Array class FramsNumberExceeded < StandardError; end class UnknownStructure < StandardError; end class PinNumberExceeded < StandardError; end MAX_FRAMES = 10 MAX_PINS = 10 def initialize push(::Games::Bowling::Frame.new) end def push(value) super(value) if valid?(value) end def knock(value) if last_strike? last.knock(value) if last[:throwns].count < 3 else raise PinNumberExceeded.new("You can't thrown more then 10 pins") if last.calc + value[:knocked] > 10 last.knock(value) end push(::Games::Bowling::Frame.new) if create_new_frame? recalculate_scores end def total map{|frame| frame[:score]}.inject(:+) end private def last_frame? count == MAX_FRAMES end def last_strike? last[:throwns].first == MAX_PINS end def recalculate_scores frames = reject{|frame| frame[:throwns].blank?}.last(3) frames.each_with_index do |frame, index| balls = frames[index..-1].map{|fr| fr[:throwns]}.flatten if frame.strike? || frame.spare? frame[:score] = balls.take(3).inject(:+) end end end def create_new_frame? if (last.thrown == 2) && pins_left? true elsif !pins_left? && size < MAX_FRAMES true else false end end def pins_left? last.calc < MAX_PINS end def valid?(value) raise UnknownStructure.new("Game works only with Frame structure") if !is_frame?(value) true end def is_frame?(value) value.is_a?(::Games::Bowling::Frame) end end end end #game = ::Games::Bowling::Game.new; k = ::Games::Bowling::Thrown.new(3); game.knock(k) #k = ::Games::Bowling::Thrown.new(4); game.knock(k) # the most points that can be scored in a single frame is 30 points (10 for the original strike, plus strikes in the two subsequent frames).
true
f803eec9e15aa0c9f9bc47e15d0e36401af9588d
Ruby
zgfif/rock_scissors_paper
/lib/message.rb
UTF-8
495
3.59375
4
[]
no_license
class Message class << self def win(winner) "The winning move is #{winner.move}" end def tie 'Tie' end def invalid_move 'Error: One of the users wrote invalid move' end def please_wait 'Please wait...' end def name_question(n) "Hey Player #{n}. What's your name?" end def move_question 'Please type your move (rock, scissors or paper): ' end def greeting(name) "Hi. #{name}" end end end
true
1bbd5b5ca4ef47a6dbef3fa834e598449dd6e54c
Ruby
thai321/Notes
/Interview/HR/Implementation/Divisible_Sum_Pairs.rb
UTF-8
537
3.875
4
[]
no_license
# You are given an array of n integers, a0, a1, ... a_n-1 # , and a positive integer, k . # Find and print the number of (i,j) pairs where i < j and a_i + a_j is divisible by k. #!/bin/ruby def divisibleSumPairs(n, k, ar) # Complete this function count = 0; (0...n-1).each do |i| (i+1...n).each do |j| count += 1 if (ar[i] + ar[j]) % k == 0 end end count; end n, k = gets.strip.split(' ') n = n.to_i k = k.to_i ar = gets.strip ar = ar.split(' ').map(&:to_i) result = divisibleSumPairs(n, k, ar) puts result;
true
c387035cc740fdd05ae3131a183a6d49d2892123
Ruby
obi-a/ragios
/lib/ragios/recurring_jobs/scheduler.rb
UTF-8
2,698
2.53125
3
[ "MIT" ]
permissive
module Ragios module RecurringJobs class Scheduler attr_reader :internal_scheduler, :work_pusher, :events_pusher ACTIONS = %w(run_now_and_schedule schedule_and_run_later trigger_work reschedule unschedule).freeze # interval jobs - trigger immediately and then triggers every time the set interval has elasped # every jobs - don't trigger immediately, it triggers first when the set interval has elasped and keep recurring at that interval TYPES = [:every, :interval].freeze def initialize(skip_actor_creation = false) @internal_scheduler = Rufus::Scheduler.new unless skip_actor_creation @work_pusher = Ragios::Monitors::Workers::Pusher.new @events_pusher = Ragios::Events::Pusher.pool(size: 20) end end def perform(options_array) options = JSON.parse(options_array.first, symbolize_names: true) send(options[:perform], options) if ACTIONS.include?(options[:perform]) end def run_now_and_schedule(options) schedule(:interval, options) end def schedule_and_run_later(options) schedule(:every, options) end def reschedule(options) unschedule(options) schedule_and_run_later(options) end def schedule(scheduler_type, options) unless TYPES.include?(scheduler_type) raise ArgumentError.new("Unrecognized scheduler_type #{scheduler_type}") end opts = { tags: options[:monitor_id] } opts[:first] = :now if scheduler_type == :interval job_id = @internal_scheduler.interval options[:interval].to_s, opts do trigger_work(options) end if job_id logger.info("#{self.class.name} scheduled #{scheduler_type} job #{job_id} for monitor_id #{options[:monitor_id]} at interval #{options[:interval]}") end end def trigger_work(options) @work_pusher&.async&.push(options[:monitor_id]) @events_pusher&.async&.log_event( monitor_id: options[:monitor_id], event: {"monitor status" => "triggered"}, state: "triggered", time: Time.now.utc, type: "event", event_type: "monitor.triggered" ) end def unschedule(options) jobs = find(options[:monitor_id]) jobs.each do |job| job.unschedule logger.info("#{self.class.name} unscheduled job: #{job.id} for tags #{job.tags}") end end def find(tag) @internal_scheduler.jobs(tag: tag) end private def logger ::Ragios::Logging.logger end end end end
true
1dcfc3ee939fefca6b92b4748679af811278ea36
Ruby
sekiya93/ProgramTracing
/exam/ruby_code/tt004_comment.rb
UTF-8
338
3.5
4
[]
no_license
# -*- coding: utf-8 -*- # 二進数の加算 # - 配列の添字0から値が入る def tt004(c) i = 0 q = 0 while q != 1 do if c[i] == 1 then c[i] = 0 i = i + 1 else c[i] = 1 q = 1 end printf("%s %d, %s\n", q, i, c.to_s) end p c end tape = [1, 0, 1] tt004(tape) tt004(tape) tt004(tape)
true
6afc208477c7e952b867ac9c3a6385fec1f3cfe9
Ruby
kyleblee/ttt-with-ai-project-v-000
/lib/players/computer.rb
UTF-8
1,538
3.515625
4
[]
no_license
module Players class Computer < Player WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] CORNERS = [0,2,6,8] def move(board=nil) if winning_combo = self.check_mate?(board) # for the winning opp when a row or diagonal is 2/3 occupied by computer (using WIN_COMBINATIONS) final_move = winning_combo.detect do |cell_index| board.valid_move?(cell_index + 1) end final_move += 1 final_move.to_s elsif defense_needed = self.defense(board) #defense for when the opponent is 2/3 in a row or diagonal safety = defense_needed.detect do |cell_index| board.valid_move?(cell_index + 1) end safety += 1 safety.to_s else # for the first or second move of the game, going for corners index = CORNERS.detect do |corner| board.valid_move?(corner + 1) end index += 1 index.to_s end end def check_mate?(board) WIN_COMBINATIONS.detect do |combo| board_combo = combo.collect do |index| board.cells[index] end board_combo.count(self.token) == 2 && board_combo.count(" ") == 1 end end def defense(board) WIN_COMBINATIONS.detect do |combo| board_combo = combo.collect do |index| board.cells[index] end board_combo.count(self.token) == 0 && board_combo.count(" ") == 1 end end end end
true
0e73f634b2eef51aeb725406d4e21e64c6231028
Ruby
MyriaBailey/personal-apps
/task_externalizer.rb
UTF-8
535
4.34375
4
[]
no_license
# Task Externalizer # Sometimes, you need a bit of extra help externalizing what all needs to be done and in what order. # This very short program was written to help sort that in a simple interactive app. def new_task(task) loop do puts "What do you need to do in order to #{task}?" input = gets.chomp if input == "nothing" || input == "done" || input == "next" break else new_task(input) end end end puts "What do you want to get done?" new_task(gets.chomp) puts "Congratulations!!! Good job!!"
true
bd02af7159c303f9d064ca3de20d06831c3ab9af
Ruby
Mattens15/Inline-LASESI
/vendor/bundle/gems/faker-1.8.7/lib/extensions/symbol.rb
UTF-8
139
2.5625
3
[ "MIT", "Apache-2.0" ]
permissive
# For Ruby 1.8 unless :symbol.respond_to?(:downcase) Symbol.class_eval do def downcase to_s.downcase.intern end end end
true
2b6ec75c005cad58674b244b29ce5d32af855379
Ruby
rbembleton/Full-Stack-Blackjack
/app/models/game.rb
UTF-8
2,884
2.921875
3
[]
no_license
# == Schema Information # # Table name: games # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # turn_id :integer default(0) # turn_type :string # status :string default("new") # next_order_num :integer default(0), not null # class Game < ActiveRecord::Base has_many :users has_one :deck, dependent: :destroy has_many :cards, dependent: :destroy has_one :discard_pile, dependent: :destroy has_one :dealer, dependent: :destroy after_create :create_dependencies def hands self.players.map { |player| player.hand } end def players ordered_users + Dealer.where(game_id: self.id) end def ordered_users self.users.order(:order_in_game) end def current_player if turn_type == 'User' return User.find(turn_id) elsif turn_type == 'Dealer' return Dealer.find(turn_id) end nil end def create_dependencies Deck.new_full_deck(self.id) DiscardPile.create!(game_id: self.id) Dealer.create!(game_id: self.id) end def start return if self.users.count == 0 self.reload self.update!(turn_id: self.ordered_users.first.id, turn_type: 'User', status: 'started') d, dp, dlr = self.deck, self.discard_pile, self.dealer self.players.each do |player| h = player.hand || Hand.create!(player_id: player.id, player_type: player.class.to_s) d.deal(2).each.with_index do |card, idx| card.update!({ order: idx, location_id: h.id, location_type: 'Hand', hidden: idx == 0 }) end end self.reload end def make_move(move_type) # return if @current_user.id != self.turn_id case move_type when :hit User.find(self.turn_id).hit_me when :stand next_player end self.reload end def next_player game_players = players.to_a curr_idx = game_players.find_index { |player| player.class.to_s == turn_type && player.id == turn_id } return nil if curr_idx >= game_players.length self.update!(turn_id: players[curr_idx + 1].id, turn_type: players[curr_idx + 1].class.to_s) if self.turn_type == 'Dealer' return finish_game end end def finish_game self.dealer.take_turn self.update!(status: 'finished') self.players.each { |plr| plr.hand.cards.each { |c| c.update!(hidden: false) } } winner end def winner highest_hand, current_winner = 0, nil self.reload self.hands.each do |hand| if hand && !hand.busted? && hand.best_value > highest_hand highest_hand = hand.best_value current_winner = hand.player end end current_winner end def reset self.update!(status: 'cleared') self.deck.reshuffle self.hands.each { |hand| hand.reload if hand } end end
true
e13c4701277f430a2fc641e524e4ba0c4353e0f5
Ruby
mpaulweeks/commander-league
/rb/oracle.rb
UTF-8
1,170
2.84375
3
[]
no_license
require_relative 'store' require_relative 'card_ref' class Oracle attr_reader :card_ref, :multiverse def initialize(card_ref=nil) @card_ref = card_ref || CardRef.new @multiverse = Store.load_multiverse @categories = [ 'Land', 'Creature', 'Enchantment - Aura', 'Enchantment', 'Artifact - Equipment', 'Artifact', 'Planeswalker', 'Sorcery', 'Instant' ] end def determine_category(card_meta) types = card_meta['types'] @categories.each do |category| types.each do |type| if (category.include? '-') && (card_meta.has_key? "subtypes") subtype = card_meta["subtypes"][0] if category == ("%s - %s" % [type, subtype]) return category end elsif category == type return category end end end raise "Found an un-categorizable card! %s" % card_meta end def add_card_meta!(cards) cards.each do |card_name, card| card_meta = self.card_ref.get_card(card_name) card[:category] = determine_category(card_meta) card[:multiverse] = self.multiverse[card_name] end end end
true
05a8f9edb6f034d92985ab6a8eddb898c7b8af54
Ruby
iamadawra/menuize
/features/step_definitions/restaurant_steps.rb
UTF-8
2,243
2.609375
3
[]
no_license
Then /^the restaurant "(.*)" should be editable/ do |restaurant| r = Restaurant.find_by_name(restaurant) r.status.should eq("Collaborative") end Then /^the restaurant "(.*)" should be awaiting approval/ do |restaurant| r = Restaurant.find_by_name(restaurant) r.status.should eq("Pending Approval") end Then /^I should reach the show page for (.*)/ do |restaurant| restaurants_path(Restaurant.find_by_name(restaurant)) end Given /the following restaurants exist/ do |restaurant_table| restaurant_table.hashes.each do |restaurant| Restaurant.create(restaurant) end end Given /^I browse restaurants without logging in/ do visit '/logout' visit '/restaurants' end And (/^"(.*)" should have Close Time equals "(.*)"$/) do |name, time| r = Restaurant.find_by_name(name) timeArr = time.split(" ") num = timeArr[0].to_i num = num + 12 if timeArr[1] == "pm" r.close_time.should eq(num) end Then /^I should see "(.*)" in the row for "(.*)"/ do |value, rowname| has_value_in_row = false all("tr").each do |tr| if tr.has_content?(rowname) && tr.has_content?(value) has_value_in_row = true end end assert has_value_in_row end Then /^I should not see "(.*)" in the row for "(.*)"/ do |value, rowname| has_value_in_row = false all("tr").each do |tr| if tr.has_content?(rowname) && tr.has_content?(value) has_value_in_row = true end end assert !has_value_in_row end When /^I delete "(.*)"/ do |restaurant| click_link "Delete This Restaurant" end Then /there should be "(.*)" menu item boxes/ do |number| x = Integer(number) count = 0 all(".item-field").each do |item_field| count+=1 end assert count == x end When /I hover over and click on remove link/ do links = all(".remove-link") links[0].click end Then /^"(.*)" should appear before "(.*)"/ do |first, second| has_first = false has_second = false passes = false all("tr").each do |tr| has_first = true if tr.has_content?(first) if tr.has_content?(second) has_second = true if (has_first) passes = true else passes = false end break end end assert passes end When /^I reach the restaurant page/ do visit '/restaurants' end
true
a90d3e18c815337a2e424b086fdde3019208bc57
Ruby
mikexstudios/noceracode
/automate_chi/tafel_ait.expt
UTF-8
3,771
2.578125
3
[]
no_license
#!/usr/bin/env ruby require 'logger' #Must be required before automate_chi.rb! #$log_file = File.new('Z:\Labs\noceracode\automate_chi\test.log', 'w') $log_file = File.new('C:\Users\Nocera Group\Dropbox\Electrochemistry\Mike\04-08-2013\02tafel\tafel.log', 'w') $log_file.sync = true #do not buffer $log = Logger.new($log_file) #$log = Logger.new(STDOUT) $log.level = Logger::DEBUG require './automate_chi.rb' #require '../usbnetpower8800/usbnetpower8800.rb' #@stir_plate = USBNetPower8800.new #require '../pH-vwr/pH-vwr.rb' #@pH_meter = PHVWR.new(5) #COM6 def run_ait $log.info '-------------------------------------' begin $log.info 'Running tafel experiment with filename: %s' % @save_filename es = EchemSoftware.new es.setup_amperometric_it_curve(@init_e, @sample_interval, @run_time, 0, 3, @sensitivity) #Another quirk with the software is that iR comp must be called after RDE #it seems or else iR comp won't actually be enabled. es.setup_manual_ir_compensation(@ir_comp) #Thread.new { # @stir_plate.on # sleep(@stir_time) # @stir_plate.off #} es.run(@status_check_interval, @status_max_runtime) es.save_as(@save_filename) #Get pH at final point #begin # m = @pH_meter.measure #rescue Errno::EACCES #problem with opening COM port #end #begin # $log.info 'pH: %f' % m['pH'] # $log.info 'Temp: %f' % m['temp'] #rescue TypeError, NameError # $log.info 'pH meter returned nil' #end rescue RuntimeError $log.error 'RuntimeError: Retrying experiment...' #Getting here means that the software has crashed. So let's try to restart #it again. es.kill $log.info 'Killing program and sleeping for a bit...' sleep(60) #1 minutes to let instrument rest retry ensure if es #when we have errors, es is automatically GC'ed and set to nil. $log.info 'Killing program through ensure...' es.kill es = nil end end $log.info '-------------------------------------' $log.info $log_file.flush #since .sync doesn't work for some reason print '.' end #Experiment variables @stir_time = 6 #sec. @collect_time = 1 #sec #The sensitivity must be specified as 1e-n where n = [1, 12], because that #is what the potentiostat can handle. @sensitivity = 1e-5 #see below @sample_interval = 0.05 #sec @ir_comp = 14.0 #ohm #The following is for our own purposes for defining the potential range and step @potential_range = (0.57..0.68) #V, needs to be from high to low for positive step #@step = (@potential_range.first - @potential_range.last) / 16.0 @step = 0.005 #V #@step = 0.01 #V #We run from high potential to low potential for pass in 1..2 potentials = @potential_range.step(@step).to_a.map {|x| x.round(3)} potentials.reverse! #Go from high to low $log.info('Potentials: %s' % potentials.to_s) #For each potential, we loop through specified rotation velocities. potentials.each_with_index do |p, i| @init_e = p #Dynamic sensitivity mod #@sensitivity = 1e-3 if p <= 1.7 @sensitivity = 1e-4 if p <= 0.68 @sensitivity = 1e-5 if p <= 0.66 @sensitivity = 1e-6 if p <= 0.61 #Anodize first point if pass == 1 and p == 0.68 #@stir_time = 30 * 60 #30 minutes @stir_time = 10 #s else @stir_time = 6 #s end @run_time = @stir_time + @collect_time @status_check_interval = (@run_time + 5) / 2 #sec #When our runtime exceeds the maximum runtime given below, we assume the experi #has crashed and exit from loop. @status_max_runtime = @run_time + 10 #sec p_formatted = '%.3f' % p @save_filename = '%02ip_%s.bin' % [pass, p_formatted.sub('.', '')] run_ait end end #@stir_plate.close
true
2d446461bcff9bca5feda17f24e0ac41dd4520ac
Ruby
muniere/tailor
/Rakefile
UTF-8
5,284
2.6875
3
[]
no_license
require 'open3' # # Constants # VERBOSE = true NOOP = false MAPPINGS = { :bin => { :src => File.join(Dir.pwd, 'bin'), :dst => File.expand_path('~/.bin') }, :bash => { :src => File.join(Dir.pwd, 'completion/tailor.bash'), :dst => File.expand_path('~/.bash_completion.d/tailor') }, :zsh => { :src => File.join(Dir.pwd, 'completion/tailor.zsh'), :dst => File.expand_path('~/.zsh-completions/_tailor') } } LOCK_FILE = File.join(Dir.pwd, 'PREFIX.lock') # # Extended String # class String def red; "\033[31m#{self}\033[0m"; end def green; "\033[32m#{self}\033[0m"; end def yellow; "\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 end # # Helper functions # class Helper # # output info # def self.info(message) STDERR.puts "[INFO] #{message}".cyan if VERBOSE end # # output warn # def self.warn(message) STDERR.puts "[WARN] #{message}".yellow if VERBOSE end # # list files in directory # def self.lsdir(dir) return Dir.entries(dir) - ['.', '..'] end # # make directory recursively # def self.mkdir_p(dir) return self.exec("mkdir -p #{dir}") end # # create symlink forcely # def self.ln_sf(src, dst) return self.exec("ln -sf #{src} #{dst}") end # # copy file # def self.cp(src, dst) return self.exec("cp #{src} #{dst}") end # # remove file # def self.rm(file) return self.exec("rm #{file}") end # # remove file recursively # def self.rm_r(file) return self.exec("rm -r #{file}") end # # create symlink recursively # def self.symlink_r(src: nil, dst: nil) if !File.exists?(src) self.warn("File NOT FOUND: #{src}") return false end if File.symlink?(dst) self.info("File already exists: #{dst}") return true end if !Dir.exists?(dir = File.dirname(dst)) self.mkdir_p(dir) end # file if File.file?(src) return self.ln_sf(src, dst) end # directory if !File.directory?(dst) self.mkdir_p(dst) end success = true self.lsdir(src).each do |conf| success &= self.symlink_r(src: File.join(src, conf), dst: File.join(dst, conf)) end return success end # # copy file recursively # def self.copy_r(src: nil, dst: nil) if !File.exists?(src) self.warn("File NOT FOUND: #{src}") return false end if File.exists?(dst) self.info("File already exists: #{dst}") return true end if !Dir.exists?(dir = File.dirname(dst)) self.mkdir_p(dir) end # file if File.file?(src) return self.cp(src, dst) end # directory if !File.directory?(dst) self.mkdir_p(dst) end success = true self.lsdir(src).each do |conf| success &= self.cp(File.join(src, conf), File.join(dst, conf)) end return success end # # unlink file # def self.unlink_r(src: nil, dst: nil) if !File.exists?(dst) and !File.symlink?(dst) self.info("File already removed: #{dst}") return true end # symlink if File.symlink?(dst) and File.exists?(src) return self.rm(dst) end # file if File.file?(dst) self.info("File is NOT LINK: #{dst}") return false end # directory success = true self.lsdir(src).each do |file| if !File.symlink?(path = File.join(dst, file)) next end success &= self.rm(path) end if self.lsdir(dst).empty? success &= self.rm_r(dst) end return success end # # show status # def self.status_r(src: nil, dst: nil) paths = [] if File.file?(dst) or File.symlink?(dst) # file paths.push(dst) else # directory self.lsdir(src).each do |file| path = File.join(dst, file) if File.exists?(path) or File.symlink?(path) paths.push(path) end end end return self.exec("ls -ldG #{paths.join(' ')}", verbose: true, noop: false) end # # install bundles # def self.bundle return self.exec('bundle install') end # # exec shell command # def self.exec(command, options={}) verbose = !options[:verbose].nil? ? options[:verbose] : VERBOSE noop = !options[:noop].nil? ? options[:noop] : NOOP if verbose STDERR.puts "[EXEC] #{command}".green end return true if noop Process.waitpid(Process.spawn(command)) return $?.success? end end # # Tasks # desc 'install' task :install do if !(prefix = ENV['PREFIX']).nil? MAPPINGS[:bin][:dst] = prefix File.write(LOCK_FILE, prefix) end Helper.bundle MAPPINGS.each do |id, mapping| Helper.symlink_r(mapping) end end desc 'uninstall' task :uninstall do if File.exists?(LOCK_FILE) MAPPINGS[:bin][:dst] = File.read(LOCK_FILE) end MAPPINGS.each do |id, mapping| Helper.unlink_r(mapping) end end desc 'show status' task :status do if File.exists?(LOCK_FILE) MAPPINGS[:bin][:dst] = File.read(LOCK_FILE) end MAPPINGS.each do |id, mapping| Helper.status_r(mapping) end end
true
f2839bc7a034e3a301135a939f824079c074f1ac
Ruby
ismael-i/Mini_jeu
/app_2.rb
UTF-8
2,737
3.609375
4
[]
no_license
require "bundler" Bundler.require require_relative "lib/game" require_relative "lib/player" puts "-" * 49 puts "|Bienvenue sur 'ILS VEULENT TOUS MA POO' ! |" puts "|Le but du jeu est d'être le dernier survivant !|" puts "-" * 49 # Demander à l'utilisateur, son prenom print "Quel est votre prénom?\n" first_name_user = gets.chomp # creer le personnage utilisateur dont le nom est en fonction de l'entree au clavier user = HumanPlayer.new(first_name_user) # creer 2 joueurs, josiane et josé player1 = Player.new("Josiane") player2 = Player.new("José") # mettre les 2 joueurs dans le tableau ennemies ennemies = [player1, player2] # Tant que le point de vie du personnage utilisateur est superieur à 0 et tous ses ennemies sont vivants while user.life_points > 0 && (player1.life_points > 0 || player2.life_points > 0) puts "\nQuelle action veux-tu effectuer ?" print "a - chercher une meilleur arme\ns - chercher à se soigner\n" puts "attaquer un joueur en vue :" print "\n0 - Josiane a #{player1.life_points} points de vie" print "\n1 - José a #{player2.life_points} points de vie" print "\n2 - Attaque des ennemies" print "\n>" # attendre l'utilisateur appuie au clavier pour donner son choix choice = gets.chomp case choice #si a when "a" puts "chercher une meilleur arme\ns - chercher à se soigner" # utilisateur recherche un arme user.search_weapon # affichage de l'etat de l'utilisateur user.show_state when "s" puts "chercher à se soigner" # utilisateur recherche un pack de santé user.search_health_pack # affichage de l'etat de l'utilisateur user.show_state when "0" puts "Josiane a #{player1.life_points} points de vie" # le personnage utilisateur attaque l'ennemie 1 s'il n'est encore mort (user.attacks(player1); player1.show_state) if player1.life_points > 0 # affichage de l'etat de l'ennemie 1 player1.show_state when "1" puts "José a #{player2.life_points} points de vie" # le personnage utilisateur attaque l'ennemie 2 s'il n'est encore mort (user.attacks(player2); player2.show_state) if player2.life_points > 0 # affichage de l'etat de l'ennemie 2 player2.show_state when "2" puts "attaque des ennemies" ennemies.each do |ennemie| # le personnage utilisateur a été attaqué par les 2 ennemies ennemie.attacks(user); user.show_state if user.life_points > 0 end else end end # fin de partie puts "La partie est finie" # si le point de vie de l'utilisateur est inferieur ou égal à 0 alors afficher Loser ! Tu as perdu ! si non BRAVO ! TU AS GAGNE ! (user.life_points <= 0) ? (puts "Loser ! Tu as perdu !") : (puts "BRAVO ! TU AS GAGNE !") binding.pry
true
a6654e6515189e7f4ac5fb8636af400efd13791e
Ruby
epson121/adventofcode
/2016/01.rb
UTF-8
1,072
3.265625
3
[]
no_license
file = File.new("01.txt", "r") while (line = file.gets) moves = line.split(",").map{|e| e.strip} end pos = [0, 0] visited = [] map2 = { "N" => { "L" => [-1, 'W'], "R" => [1, 'E'] }, "S" => { "L" => [1, 'E'], "R" => [-1, 'W'] }, "E" => { "L" => [1, 'N'], "R" => [-1, 'S'] }, "W" => { "L" => [-1, 'S'], "R" => [1, 'N'] } } duplicate = nil facing = "N" moves.each do |move| dir = move[0] len = move[1..move.length].to_i for i in 1..len if facing == "N" or facing == "S" l = [pos[0] + 1 * map2[facing][dir][0], pos[1]] else l = [pos[0], pos[1] + 1 * map2[facing][dir][0]] end if visited.include?(l) if duplicate == nil duplicate = l end end visited << l pos = l end facing = map2[facing][dir][1] end p "Easter bunny is away " + pos.map(&:abs).inject(&:+).to_s p "Distance is " + duplicate.map(&:abs).inject(&:+).to_s
true
aa9f01929f9ccc7c69af2d9370168884339462a6
Ruby
tjpkrp1/tts-class-9-17
/methods/remainder_challenge.rb
UTF-8
662
4.4375
4
[]
no_license
# Welcome to the Remainder Challenge # Divide 2 numbers and return the number and remainder # If either number is NOT an integer, don't aept the number and ask again. # The number 0 is UNACCEPTABLE def get_numbers # ask the user for a number puts "enter a number:" # get that number and save it number = gets.chomp if number.include?(".") puts "Try again, it needs to be an integer" elsif number.to_i == 0 puts "Try again, it needs to be an integer." Def divide_with_remainder(number1, number2) quotient = number1 / number2 remainder = number 1 % number 2 "The answer is #{quotient} remainder #{remainder}." end puts divide_with_remainder(6,4)
true
71b9d5659cb0d41a10ded05a4fd33e5125d8826a
Ruby
JulieBerry/Learn_Ruby
/ex14.rb
UTF-8
2,578
3.796875
4
[]
no_license
# (variable-definition)user_name (equals) (argument-variable).first # defines a variable as user input user_name = ARGV.first user_lastname = ARGV.last # (variable-definition)prompt (equals) (single-quote)>(single-quote) # defines a variable to a symbol prompt = '(+)(+)' # (put-string) (open-string)Hi (octothorpe)(get-variable)user_name(close-variable).(close string) # prints a string calling a user-defined variable puts "Hi #{user_name} #{user_lastname}." # (put-string) (open-string)I'd like to ask you a few questions.(close-string) # prints a string of text puts "I'd like to ask you a few questions." # (put-string) (open-string)Do you like me (octothorpe)(get-variable)user_name(close-variable)? (close string) # prints a string of text calling for user input after a variable prompt puts "Do you like me #{user_name} #{user_lastname}? ", prompt # (variable-definition) (equals) (dollar-sign)(redirect)(user-prompt) # defines a variable a user-defined variable likes = $stdin.gets.chomp # (print-string) (open-string)Where do you live (octothorpe)(get-variable)user_name(close-variable)?(close string), (prompt) # prints a string of text calling for user input after a variable prompt puts "Where do you live #{user_name} #{user_lastname}? ", prompt # (variable-definition) (equals) (dollar-sign)(redirect)(user-input-prompt) # defines a variable a user-defined variable lives = $stdin.gets.chomp # (put-string) (open-string)What kind of computer do you have? (close-string), (user-prompt) # prints a string of text calling for user input after a variable prompt puts "What kind of computer do you have? ", prompt # (variable-definition) (equals) (dollar-sign)(redirect)(user-prompt) # defines a variable as user input computer = $stdin.gets.chomp # prints a multi-line string calling for user-input-variables puts """ Alright, #{user_name} #{user_lastname}, so you said #{likes} about liking me. You live in #{lives}. Not sure where that is. And you have a #{computer}. Nice. """ # QUESTION: Isn't prompt just another variable? Is there something special about the word prompt? puts "\nEXTRA CREDIT 1 - Find out what Zork and Adventure were. Try to find a copy and play it." puts "\nEXTRA CREDIT 2 - Change the prompt variable to something else entirely." puts "\nEXTRA CREDIT 3 - Add another argument and use it in your script, the same way you did in the previous exercise with first, second = ARGV. Make sure you understand how I combined a (triple-quote) style multiline string with the (octothorpe) {} format activator as the last print." # Note: redo #3
true
1e838cf3d83e8a5beb660719b8e1851f07c5fe56
Ruby
GabyML/battleships-2
/spec/ship_locator_spec.rb
UTF-8
1,351
2.921875
3
[]
no_license
require 'ship_locator' describe ShipLocator do let(:ship) { double :ship, length: 3 } let(:board) {double :board, place: nil} subject {ShipLocator.new(board: board)} let(:vertical_ship_hash) do {ship: ship, orientation: :vertical, seed: [0,0]} end let(:horizontal_ship_hash) do {ship: ship, orientation: :horizontal, seed: [0,0]} end let(:off_the_board) do {ship: ship, orientation: :vertical, seed: [9,0]} end it 'can return horizontal ship coordinates' do expect_board_to_receive([[0,0],[0,1],[0,2]]) subject.place_ship(horizontal_ship_hash) end it 'can return vertical ship coordinates' do expect_board_to_receive([[0,0],[1,0],[2,0]]) subject.place_ship(vertical_ship_hash) end it 'will raise error if ship overlaps' do subject.place_ship(horizontal_ship_hash) expect{subject.place_ship(vertical_ship_hash)} .to raise_error 'there is already a ship there' end it 'will raise error if ship falls off the board' do expect{subject.place_ship(off_the_board)} .to raise_error 'that is outside the playable area' end it 'places a ship' do expect_board_to_receive([[0,0],[1,0],[2,0]]) subject.place_ship(vertical_ship_hash) end def expect_board_to_receive(coords) expect(board).to receive(:place).with(hittable: ship, coords: coords) end end
true
83ee4cfa21c6dcbab5edf6e1857ca92d2979d094
Ruby
pmoore/bcw_rails
/config/initializers/constants.rb
UTF-8
409
2.84375
3
[]
no_license
module BcwConstants class Cities WASHINGTON_DC = { :name => 'Washington, DC', :name_short => "DC", :url_slug => 'dc' } ATLANTA = { :name => 'Atlanta', :name_short => "Atlanta", :url_slug => 'atlanta' } ALL_CITIES = [ WASHINGTON_DC, ATLANTA ] def self.find_city_by_url_slug(slug) ALL_CITIES.each do |city| return city if city[:url_slug] == slug end end end end
true
eeab1a4c2007d3bd06967c0942f0a866565a30f4
Ruby
rks/application_support
/test/array_test.rb
UTF-8
2,282
3.140625
3
[]
no_license
require File.dirname(__FILE__) + "/test_helper" require File.dirname(__FILE__) + "/../lib/array.rb" class ArrayTest < Test::Unit::TestCase def test_should_receive_instance_level_monkey_patches injected_methods = %(divided_by) injected_methods.each do |method| assert Array.new.respond_to?(method.to_sym), "Arrays should respond to #{method}" end end module DividedBy class DividedByTest < Test::Unit::TestCase def test_divide_by_zero_returns_self initial = ["a", "b"] assert_equal ["a", "b"], initial.divided_by(0) end def test_divided_by_one_should_return_self initial = ["a", "b"] assert_equal ["a", "b"], initial.divided_by(1) end def test_divides_empty_array initial = [] assert_equal [[], []], initial.divided_by(2) assert_equal [[], [], []], initial.divided_by(3) end def test_divided_by_with_evenly_divisible_array initial = ["a", "b"] expected = [["a"], ["b"]] assert_equal expected, initial.divided_by(2) end def test_divided_by_with_non_evenly_divisible_array initial = ["a"] expected = [["a"], []] assert_equal expected, initial.divided_by(2) end def test_evenly_divisible_array_divided_by_non_even_divisor initial = ["a", "b", "c"] expected = [["a"], ["b"], ["c"]] assert_equal expected, initial.divided_by(3) end def test_non_evenly_divisible_array_divided_by_non_even_divisor initial = ["a", "b"] expected = [["a"], ["b"], []] assert_equal expected, initial.divided_by(3) end def test_single_item_array_divided_by_non_even_divisor initial = ["a"] expected = [["a"], [], []] assert_equal expected, initial.divided_by(3) end def test_long_array_divided_into_even_groups initial = (1..10).to_a expected = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] assert_equal expected, initial.divided_by(2) end def test_long_array_divided_into_non_even_groups initial = (1..10).to_a expected = [(1..4).to_a, (5..8).to_a, (9..10).to_a] assert_equal expected, initial.divided_by(3) end end end end
true
03dc06aa810abe9540ae5cf8ed51dd3956ed6ce1
Ruby
qbektrix/pixmatch
/lib/pixmatch/client/delete.rb
UTF-8
498
2.5625
3
[ "MIT" ]
permissive
module Pixmatch class Client module Delete # Given a list of image filenames, delete the images from the collection. # @param files [Array] Array of file names. def delete(filenames) filenames = [ filenames ] if filenames.is_a?(String) filenames_hash = { } filenames.each { |f| filenames_hash["filenames[#{filenames_hash.size}]"] = f } request(:post, 'rest', { method: :delete }, { payload: filenames_hash }) end end end end
true
1bdb330348a015167fc03c97c5d0fd7269ec50f3
Ruby
ysei/project_euler_solutions
/e010.rb
UTF-8
147
3.140625
3
[]
no_license
#!/usr/bin/env ruby require 'primes' # N = 10 N = 2_000_000 p = Primes.new(N + 100) sum = 0 while p.next_prime < N sum += p.current end p sum
true
97f7b484ba70d3634c4463d61033b2d863253305
Ruby
javonesm89/Sencbl
/lib/cli.rb
UTF-8
1,466
3.265625
3
[]
no_license
require "../Sencbl/environment.rb" require "./lib/scraper" require "./lib/word" class CLI attr_accessor :word_hash, :has_name @@prompt = TTY::Prompt.new def run if !@has_name greet Scraper.collect_dates @has_name = true end @date_options = Scraper.all @chosen_date = @@prompt.select("#{@name}, choose a date for Word of the Day!", @date_options) scrape_and_make_word_object(@chosen_date) display start_over end def greet @name = @@prompt.ask("Welcome to Sencbl! What's your name?\n") do |n| n.required true n.validate /[a-zA-Z]/ end end def scrape_and_make_word_object(chosen_date) word_hash = Scraper.collect_word_object(@chosen_date) @word_of_day = WordPlay.new(word_hash) end def display @word_of_day.display_info @options = %w(Yes?😎 No?😕) sleep(4) more_info = @@prompt.select("Need help?\n", @options) more_info == "Yes?😎" ? @word_of_day.display_examples_and_origin : (puts "Ok! Add #{@word_of_day.word} to your vocabulary and you'll sound super smart!") end def start_over sleep(4) start_game = @@prompt.select("Another word?\n", @options) if start_game == "Yes?😎" self.run else (puts "Check back tomorrow for a new word!") end end end
true
7e003c9898d5a591007d6d25750abdf78b75495c
Ruby
getty104/Ruby_Design_Pattern
/Producer-Consumer.rb
UTF-8
872
3.5
4
[]
no_license
class Bank def initialize @money = 0 @m = Mutex.new @cv = ConditionVariable.new end def add @m.synchronize{ while @money >5000 puts "add wait" @cv.wait(@m) end n = (rand*2000).to_i @money += n puts "add:#{n} :#{@money}" @cv.broadcast } end def use @m.synchronize{ while @money <= 0 puts "use wait" @cv.wait(@m) end n = (rand*(@money)).to_i @money -= n puts "use:#{n} :#{@money}" @cv.broadcast } end end class Parent def initialize(bank) @bank = bank end def add @bank.add end end class Child def initialize(bank) @bank = bank end def use @bank.use end end bank = Bank.new parent = Parent.new(bank) child = Child.new(bank) t1 = Thread.new{ loop do parent.add sleep(rand(2)) end } t2 = Thread.new{ loop do child.use sleep(rand(2)) end } t1.join t2.join
true
6af0584a9104c64237fddeab711c92ab0831f6b7
Ruby
lis2/presentations
/objects-extended/test.rb
UTF-8
70
2.90625
3
[]
no_license
a = 10 Klass = Class.new do |b| a = 20 b = 30 end puts a puts b
true
a39da673e5fe1d3f181e082e776ca1cc809a8d58
Ruby
DartmouthDSC/LinkedNameAuthority
/app/models/concerns/lna/date_helper.rb
UTF-8
1,604
2.90625
3
[]
no_license
module Lna module DateHelper extend ActiveSupport::Concern # Helper to set date values. Converts dates, in Date or String format, to a RDF::Literal. # # @param [String] name of field to be set # @param [String|Date|DateTime|Time|nil] d value of field def date_setter(name, d) case d.class.name when 'RDF::Literal::Date', 'NilClass' value = d when 'String' begin if d.empty? value = nil else value = ::RDF::Literal.new(Date.parse(d)) end rescue raise ArgumentError, "#{name} could not be converted to a date." end when 'Date', 'DateTime', 'Time' value = ::RDF::Literal.new(Date.parse(d.to_s)) else raise ArgumentError, "#{name} cannot be a #{d.class}." end set_value(name, value) end # Convert the date fields in the hash given to a date format that solr can understand. # # @param [Hash] values hash of values # @param [Array<String>] keys list of keys that represent dates # @return [Hash] hash with replacement keys for keys given def self.solr_date(values, keys) # Change keys for dates and convert date string to a solr friendly format. keys.each do |key| if values.key?(key) && (values[key].is_a?(String) || values[key].is_a?(Date)) date = values.delete(key) date = date.to_s if date.is_a?(Date) values[key.to_s.concat('_dtsi').to_sym] = Date.parse(date).strftime('%FT%TZ') end end values end end end
true
0b87a4654850c9259358d6a5e9ef6f637589c8d3
Ruby
pronix/studyfiles
/vendor/plugins/hierarchy/lib/hierarchy.rb
UTF-8
4,946
2.78125
3
[ "MIT" ]
permissive
# @private module Arel # @private module Attributes # @private def self.for_with_psql(column) case column.sql_type when 'ltree' then String else for_without_psql(column) end end unless singleton_class.method_defined?(:for_without_psql) singleton_class.send :alias_method, :for_without_psql, :for singleton_class.send :alias_method, :for, :for_with_psql end end end require 'hierarchy_generator' require 'hierarchy/index_path' require 'hierarchy/node' # Adds a tree structure to a model. This is very similar to @acts_as_nested_set@ # but uses the PostgreSQL-specific @ltree@ feature for schema storage. # # Your model must have a @path@ field of type @ltree@. This field will be a # period-delimited list of IDs of records above this one in the hierarchy. In # addition, you should also consider the following indexes: # # <pre><code> # CREATE INDEX index1 ON table USING gist(path) # CREATE INDEX index2 ON table USING btree(path) # </code></pre> # # replacing @table@ with your table and @index1@/@index2@ with appropriate names # for these indexes. # # @example # class MyModel < ActiveRecord::Base # include Hierarchy # end module Hierarchy extend ActiveSupport::Concern # @private included do |base| base.extend ActiveSupport::Memoizable base.memoize :index_path, :ancestors base.scope :parent_of, ->(obj) { obj.top_level? ? base.where('false') : base.where(id: obj.index_path.last) } base.scope :children_of, ->(obj) { base.where(path: obj.my_path) } base.scope :ancestors_of, ->(obj) { obj.top_level? ? base.where('false') : base.where(id: obj.index_path.to_a) } base.scope :descendants_of, ->(obj) { base.where([ "path <@ ?", obj.my_path ]) } base.scope :siblings_of, ->(obj) { base.where(path: obj.path) } base.scope :priority_order, base.order("NLEVEL(path) ASC") base.scope :top_level, base.where([ "path IS NULL or path = ?", '' ]) base.before_save { |obj| obj.path ||= '' } end module ClassMethods # @overload treeified # @return [Hash<ActiveRecord::Base, Hash<...>>] All models organized # into a tree structure. Returns a hash where each key is a tree root, # and the values are themselves hashes whose keys are the children of the # respective model. def treeified(root=nil, objects=nil) path = root ? root.content.my_path : '' root ||= Node.new(nil) objects ||= order('id ASC').all.sort_by { |o| [ o.index_path, o.id ] } while objects.first and objects.first.path == path child = objects.shift root << Node.new(child) end root.children.each do |child| treeified child, objects end return root end end # Methods added to instances of the class this module is included into. module InstanceMethods # Sets the object above this one in the hierarchy. # # @param [ActiveRecord::Base] parent The parent object. # @raise [ArgumentError] If @parent@ is an unsaved record with no primary key. def parent=(parent) raise ArgumentError, "Parent cannot be a new record" if parent.try(:new_record?) self.path = parent.try(:my_path) end # Returns an array of ancestors above this object. Note that a) this array # is ordered with the most senior ancestor at the beginning of the list, and # b) this is an _array_, not a _relation_. For that reason, you can pass # any additional scope options to the method. # # @param [Hash] options Additional finder options. # @return [Array] The objects above this one in the hierarchy. def ancestors(options={}) return [] if top_level? objects = self.class.ancestors_of(self).scoped(options).group_by(&:id) index_path.map { |id| objects[id].first } end # @return [ActiveRecord::Relation] The objects below this one in the # hierarchy. def descendants self.class.descendants_of self end # @return [ActiveRecord::Base] The object directly above this one in the # hierarchy. def parent top_level? ? nil : self.class.parent_of(self).first end # @return [ActiveRecord::Relation] The objects directly below this one # in the hierarchy. def children self.class.children_of self end # @return [Array] The objects at the same hierarchical level of this one. def siblings self.class.siblings_of(self) - [ self ] end # @return [true, false] Whether or not this object has no parents. def top_level? path.blank? end # @return [true, false] Whether or not this object has no children. Makes a # database call. def bottom_level? children.empty? end # @private def my_path path.blank? ? id.to_s : "#{path}.#{id}" end # @private def index_path IndexPath.from_ltree path.to_s end end end
true
56dc25638cff8fa8ba58f4f1d67184f3e1c481a7
Ruby
LoCodes/my-first-hash-onl01-seng-pt-032320
/my_first_hash.rb
UTF-8
1,590
4.125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Challenge I: Instantiating Hashes # #my_hash # uses the literal constructor to create a hash that contains key/value pairs # use the literal constructor to set the variable, my_hash, equal to a hash with key/value pairs of your choice. def my_hash my_name = {"name" => "Loren"} end # Challenge II: Hash with Data # #shipping_manifest # returns a hash with key/value pairs describing old-timey items # set a variable called `the_manifest`, equal to a hash # fill that hash with key/value pairs that describe the following information: # We have 5 whale bone corsets, 2 porcelain vases and 3 oil paintings def shipping_manifest the_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3} end # Challenge III: Retrieving Data # #retrieval # operates on the shipping_manifest hash to return the value of the 'oil paintings' key # Look up the value of the "oil paintings" key in the shipping_manifest hash below def retrieval shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3} shipping_manifest["oil paintings"] end # Challenge IV: Adding Data # #adding # operates on the shipping_manifest hash to add a key/value pair # add 2 muskets to the shipping_manifest hash below # add 4 gun powder to the shipping_manifest hash below # return the shipping_manifest hash below def adding shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3} shipping_manifest["muskets"] = 2 shipping_manifest["gun powder"] = 4 shipping_manifest end
true
875421a2db97dc9827ee452d91506fca1faa7de0
Ruby
Daiki-Ishida/Pon
/test/helpers/application_helper_test.rb
UTF-8
1,140
2.84375
3
[]
no_license
require 'test_helper' class ApplicationHelperTest < ActionView::TestCase def setup @user = users(:one) @ferret = ferrets(:one) @contract = contracts(:one) end test "display_name returns name with proper suffix" do assert display_name(@user) == "#{@user.name} さん" assert display_name(@ferret) == "#{@ferret.name} くん" end test "display_age returns approximate age or age depending on model" do @user.birth_date = Date.today.prev_year(25).prev_month(5) @ferret.birth_date = Date.today.prev_year(3) assert display_age(@user) == "20代" assert display_age(@ferret) == "3 才" end test "dislplay_address returns within city name" do assert display_address(@user) == "東京都千代田区" assert display_address(@user) == display_address(@ferret) end test "display_gender returns gender in proper word" do assert display_gender(@user) == "女性" assert display_gender(@ferret) == "オス" end test "display_period returns period of contract" do assert display_period(@contract) == "2019年07月28日から2019年07月29日までの1泊2日" end end
true
25efa7819a88f66ca78fe17f28f0edfa4c9e8b2c
Ruby
gerard76/magic_engine
/app/models/player.rb
UTF-8
5,124
2.78125
3
[]
no_license
class Player DEFAULT_HAND_SIZE = 7 STARTING_LIFE = 20 ZONES = %i(graveyard exiled hand library) attr_accessor :name, :game attr_accessor :triggers #zones attr_accessor :deck, *ZONES attr_accessor :life, :overdraw attr_accessor :mulligan_count attr_accessor :poison_counter, :mana_pool attr_accessor :cant_be_attacked def initialize(deck) @deck = deck @mulligan_count = 0 @poison_counter = 0 @mana_pool = ManaPool.new @starting_hand_size = DEFAULT_HAND_SIZE @maximum_hand_size = DEFAULT_HAND_SIZE @life = STARTING_LIFE @cant_be_attacked = false @cards_played_this_turn = [] @triggers = [] end def start_game(game) @game = game ZONES.each do |zone_name| self.send("#{zone_name}=", PlayerZone.new(self, zone_name)) end deck.cards.shuffle.each do |card| # 108.3. The owner of a card in the game is the player who started the game with it in their deck. card.owner = self library.add(card) end draw(@starting_hand_size) end def draw(amount = 1) # 121.4. A player who attempts to draw a card from a library with no cards in it loses the game the next time a player would receive priority. (This is a state-based action) overdraw = library.size < amount return if overdraw cards = library.pop(amount) cards.each { |card| card.move hand } cards end def mulligan mulligan_count += 1 library = (library + hand).shuffle hand = draw(@starting_hand_size) # ai: which cards to return? library.unshift *hand.pop(mulligan_count) end def discard(amount = 1) # TODO: player chose card graveyard << hand.pop end def untap battlefield.each do |card| card.untap card.sick = false end end def can_play?(card) card.playable_zones.include?(card.zone&.name) && mana_pool.can_pay?(card.mana_cost) && card.owner == self && (!card.is_land? || !!!@cards_played_this_turn.detect(&:is_land?)) && ((!card.is_sorcery? && !card.is_instant?) || card.abilities.first.can_pay?) end def declare_attacker(card, target) # TODO # if there is only 1 possible 'target' we could automatically pick that # 506.2. During the combat phase, the active player is the attacking player # creatures that player controls may attack return false unless game.current_state == :declare_attackers return false unless target.is_a?(Player) || target.is_planeswalker? return false if game.active_player != self return false if card.controller != self return false if target.cant_be_attacked card.attack(target) end def declare_blocker(card, target) return false unless game.current_state == :declare_blockers return false if card.controller != self return false if game.active_player == self # active player is attacker not defender # TODO # add cost to block to tally # 509.1e If any of the costs require mana, the defending player then has a chance to activate mana abilities card.block(target) end def end_of_combat battlefield.each(&:end_of_combat) end def play_card(card, **options) # if it turns out options are only used for ':target' I need to simplify # if they are used for something else I need to remove these remarks return false unless can_play?(card) mana_pool.pay_mana(card.mana_cost) card.controller = self if card.is_land? card.move game.battlefield add_triggers_to_stack if triggers.present? else card.options = options game.stack.add card end @cards_played_this_turn << card end def pay_mana(color, amount) mana_pool.pay(color, amount) end def cleanup @cards_played_this_turn = [] end def empty_mana_pool mana_pool.empty end def assign_damage(power) self.life -= power end def battlefield game.battlefield end def dead? # 704.5a If a player has 0 or less life, that player loses the game. return true if life <= 0 # 704.5c If a player has ten or more poison counters, that player loses the game. return true if poison_counter >= 10 return true if overdraw end def add_triggers_to_stack if triggers.size > 1 # 603.3b If multiple abilities have triggered since the last time a player received priority, each player, in APNAP order, puts triggered abilities they control on the stack in any order they choose. # TODO: let player determine order end while trigger = triggers.pop # TODO: if trigger has cost, player needs to pony up # 603.3c If a triggered ability is modal, its controller announces the mode choice when putting the ability on the stack. # TODO: let player determine mode game.stack << trigger end end def cards all_cards = battlefield.cards ZONES.each do |zone_name| all_cards += self.send(zone_name).cards end all_cards end end
true
467ef4646150eace114569fe1d91ee415cf56660
Ruby
yoshi0202/uci
/src/app/app/services/ElectricityServices.rb
UTF-8
445
2.578125
3
[]
no_license
require "ElectricityDTO" class ElectricityServices def create_dto(id) dto = ElectricityDTO.new dto.cost = find(id).cost return dto end def find(id) return ElectricitySupply.find(id) end def create_supply(charge_id, cost) return 0 if charge_id.nil? or UtilityCharge.find_by_id(charge_id).electricity_supply.exists?(id: charge_id) ElectricitySupply.new(utility_charge_id: charge_id, cost: cost).save end end
true
b214ef7e8dd8bc346d2f27d4399b07d0e885c607
Ruby
yhupaul/TwO-O-Player-Math-Game-
/game.rb
UTF-8
728
3.734375
4
[]
no_license
class Game def initialize(name) @name = name @player1 = Player.new('Player1') @player2 = Player.new('Player2') end def start puts "NEW GAME!! Welcome #{@player1.name} and #{player2.name}" turn end def game_status puts "P1: #{@player1.lives}/3 vs P2: #{@player2.lives}/3" end def winner(player) puts "#{player.name} wins with the score of #{player.lives}/3" puts 'GAME-OVER!!' puts 'Good bye!' exit(0) end def score if @player1.is_dead winner(@player2) elsif @player2.is_dead winner(@player1) end end def turn @player1.new_question score @player2.new_question score show_status puts 'NEW-GAME' turn end end
true
1c0877b11bda5d9024ef32c63deab0401523f124
Ruby
tobico/missingno
/spec/missingno_spec.rb
UTF-8
2,731
3.15625
3
[ "MIT" ]
permissive
require 'missingno' require 'spec' #Single class using missingno class SingleClass def_when /^(foo|bar)$/, :test def_when ['one', 'two', 'three'] do @ok = true end attr_accessor :ok end #Subclass of class using missingno class SubClass < SingleClass def_when /^zap$/, :sub_test end #Class with method_missing defined class MMClass def method_missing *args "mmclass method_missing" end def_when 'foo', :missingno end #Subclass of class with method_missing defined class MMSubClass < MMClass def_when /^zap$/, :sub_test end #Mixin module using missingno module MixinMM def_when 'zap', :mm_zap end #Class using missingno with mixin class MixedChain include MixinMM def_when 'foo', :mm_foo end describe 'missingno' do describe 'with a single class' do subject { SingleClass.new } it 'should respond to symbols matching given regexp' do should respond_to(:foo) should respond_to(:bar) should_not respond_to(:zap) end it 'should call nominated method when I call a matching (missing) method' do subject.should_receive(:test) subject.foo end it 'should receive the submatch as an argument to #test' do subject.should_receive(:test).with('foo') subject.foo end it 'should run specified block when matching array element given' do subject.ok = false subject.one subject.ok.should == true subject.ok = false subject.three subject.ok.should == true end end describe 'with a subclass of a class also using missingno' do subject { SubClass.new } it 'should respond to matches from superclass' do should respond_to(:foo) should respond_to(:bar) end it 'should respond to matches from subclass' do should respond_to(:zap) end it 'should call the correct methods when a match found' do subject.should_receive :test subject.foo subject.should_receive :sub_test subject.zap end end describe 'with a class that already has method_missing' do subject { MMClass.new } it 'should call missingno method when I call a matching method' do subject.should_receive :missingno subject.foo end it 'should call original method_missing when I call a non-matching method' do subject.zap.should == "mmclass method_missing" end end describe 'through a mixin' do subject { MixedChain.new } it 'should call method matched in class' do subject.should_receive :mm_foo subject.foo end it 'should call method matched in mixin' do subject.should_receive :mm_zap subject.zap end end end
true
b7a536d4716ae5436690e3db4e8549aa9203abb3
Ruby
jrobertson/sps_chat
/lib/sps_chat.rb
UTF-8
999
2.828125
3
[]
no_license
#!/usr/bin/env ruby # file: sps_chat.rb require 'sps_duplex' class SPSChat < SPSDuplex def initialize(host: 'localhost', port: '8080', \ userid: 'user' + (0..1000).to_a.sample.to_s, room: '', \ interactive: true) @userid = userid super(host: host, port: port, topic: 'chat', sub_topic: '#', pub_topic: userid, interactive: interactive) end def typing(c) @pub.notice ("%s/typing: %s" % [@topic, c]) end # used by the callback routine # def ontopic(topic, msg) typing = false a = topic.split('/') sender = a.pop (sender = a.pop; typing = true) if sender == 'typing' return if sender == @userid typing ? onincoming(sender, msg, true) : onincoming(sender, msg) end def onincoming(sender, msg, typing=false) puts "%s: %s" % [sender, msg] end end if __FILE__ == $0 then chat = SPSChat.new port: 8080 chat.send 'hello' end
true
c7fc0f52b2dd54a4a0d1330fb33a1a8a43effbf2
Ruby
jmeirow/command_post
/lib/command_post/util/string_util.rb
UTF-8
521
2.765625
3
[]
no_license
#require File.expand_path(File.dirname(__FILE__) + '/../../command_post') module CommandPost class StringUtil def self.to_camel_case(field, upcase) string = field.to_s upcase == true ? string.upcase : string.split('_').collect{|x| x.slice(0,1).capitalize + x.slice(1..-1) }.join() end def self.to_label(field, upcase) string = field.to_s upcase == true ? string.upcase : string.split('_').collect{|x| x.slice(0,1).capitalize + x.slice(1..-1) }.join(' ') end end end
true
d9f39d692e5b031a47dbd52faa2b7abc789648d7
Ruby
mattTea/Notes_and_Playground
/ch10_airport.rb
UTF-8
1,005
3.84375
4
[]
no_license
class Airport def initialize @hangar = [] end def land(plane) @hangar.push(plane) puts "plane.index: #{@hangar.index(plane)}" end def take_off(plane) if @hangar.length > 0 if @hangar.include? plane plane_index = @hangar.index(plane) @hangar.delete_at(plane_index) return plane else return "Error: plane not in hangar" end else return "Error: there are no planes to take off" end end def hangar_report if @hangar.length == 1 "There is 1 plane in the hangar" else "There are #{ @hangar.length } planes in the hangar" end end end class Plane def initialize # ... end end # write a Plan class if you can # and get the following code sample running heathrow = Airport.new plane = Plane.new plane_2 = Plane.new heathrow.land(plane) heathrow.land(plane_2) puts heathrow.hangar_report # => "There is 1 plane in the hangar" heathrow.take_off(plane) puts heathrow.hangar_report
true
53a9e0f7674e09b29fd8d26dcd141d5447078ab7
Ruby
craigjbass/naughts-and-crosses
/spec/unit/board_repository_spec.rb
UTF-8
1,230
2.546875
3
[]
no_license
shared_examples 'a board repository' do context 'given no board has been initialised' do it 'should contain no board' do expect(subject.fetch).to eq(nil) end end context 'given a board has been saved' do before { subject.update(this: 'is a fake board') } it 'should contain a board' do expect(subject.fetch).to eq(this: 'is a fake board') end context 'and another new board has been saved' do before { subject.update(this: 'is another fake board') } it 'should contain the newer board' do expect(subject.fetch).to eq(this: 'is another fake board') end end end end describe InMemoryBoardRepository do subject { InMemoryBoardRepository.new } it_behaves_like 'a board repository' end describe SubscribableBoardRepositoryProxy do subject do SubscribableBoardRepositoryProxy.new( InMemoryBoardRepository.new ) end it_behaves_like 'a board repository' context 'given a subscriber has subscribed' do it 'calls the subscriber when update is called' do subscriber_called = false subject.subscribe { subscriber_called = true } subject.update(nil) expect(subscriber_called).to eq(true) end end end
true
e10124cc7faaf7ffdd4aa4901da7cf8c2f5b39d7
Ruby
jan-czekawski/code_wars
/6kyu/calculate_string_notation.rb
UTF-8
1,187
4.375
4
[]
no_license
# Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. # For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. # If the second string isn't a valid rotation of the first string, the method returns -1. # Examples: # "coffee", "eecoff" => 2 # "eecoff", "coffee" => 4 # "moose", "Moose" => -1 # "isn't", "'tisn" => 2 # "Esham", "Esham" => 0 # "dog", "god" => -1 # For Swift, your function should return an Int?. So rather than returning -1 when the second string isn't a valid rotation of the first, return nil. # shiftedDiff("coffee", "eecoff") => 2 # shiftedDiff("eecoff", "coffee") => 4 # shiftedDiff("moose", "Moose") => nil # shiftedDiff("isn't", "'tisn") => 2 # shiftedDiff("Esham", "Esham") => 0 # shiftedDiff("dog", "god") => nil def shifted_diff(first, second) return -1 end Test.assert_equals(shifted_diff("eecoff","coffee"), 4) Test.assert_equals(shifted_diff("Moose","moose"), -1) Test.assert_equals(shifted_diff("isn't","'tisn"), 2)
true
d8b6cbd4a72731baf25fc5b771db5c024a07b6e2
Ruby
LouisSavoie/create-project
/create-project.rb
UTF-8
589
2.53125
3
[]
no_license
require 'octokit' require 'dotenv' # Set up env vars Dotenv.load github_name = ENV['GITHUB_NAME'] github_token = ENV['GITHUB_TOKEN'] # Get project name from the user print "Project Name: " project_name = gets.chomp # Setup Octokit and create GitHub Repo client = Octokit::Client.new(:access_token => "#{github_token}") client.create_repository("#{project_name}") # Run shell script to: Create project dir, git init, add remote, create readme, git add all, initial commit, push to GitHub system( "chmod +x create-local-repo.sh && ./create-local-repo.sh #{project_name} #{github_name}" )
true
74518fa6512571a23f76581b2e2496a557d91679
Ruby
fracus/ruby.exercises
/lib/matem.rb
UTF-8
61
2.734375
3
[]
no_license
class Matem def self.suma(a,b) n=a+b return n end end
true
7c55d2c928c28b99034dc67decd73892a007160e
Ruby
jnmandal/chicago-trains
/app/models/train.rb
UTF-8
1,534
2.875
3
[]
no_license
class Train < ActiveRecord::Base before_validation :strip_whitespace validates :run, uniqueness: true before_save :set_flags def self.import(file) CSV.foreach(file.path, headers: true) do |row| Train.create( line: row.field(0), route: row.field(1), run: row.field(2), operator: row.field(3) ) end end def self.to_csv CSV.generate(headers: %w[TRAIN_LINE, ROUTE_NAME, RUN_NUMBER, OPERATOR_ID], write_headers: true) do |csv| self.all.each do |train| csv << [train.line, train.route, train.run, train.operator] end end end def strip_whitespace self.line = self.line.strip if self.line self.route = self.route.strip if self.route self.run = self.run.strip if self.run self.operator = self.operator.strip if self.operator end def set_flags unless set_line_flag || set_route_flag || set_run_flag self.flag = false self.flag_info = nil end end def set_line_flag unless %w[El Metra Amtrak Trolley].include? self.line self.flag = true self.flag_info = "Check that line data field is correct." true end end def set_route_flag unless self.route.length > 0 self.flag = true self.flag_info = "Check that route data field is correct." true end end def set_run_flag unless %w[E M A T].include? self.run[0] self.flag = true self.flag_info = "Check that run data field is correct." true end end end
true
e5e8c3f13c1d0195ac0bff9a2c129c02112e7d30
Ruby
rocky/rb-trepanning
/processor/command/next.rb
UTF-8
3,122
2.9375
3
[ "BSD-2-Clause" ]
permissive
# -*- coding: utf-8 -*- # Copyright (C) 2010, 2015 Rocky Bernstein <[email protected]> require_relative '../command' class Trepan::Command::NextCommand < Trepan::Command unless defined?(HELP) NAME = File.basename(__FILE__, '.rb') HELP = <<-HELP **#{NAME}**[+|=|-|<|>|!|<>] [*event-name*...] [*count*] Step one statement ignoring steps into function calls at this level. Sometimes this is called "step over". With an integer argument, perform `#{NAME}` that many times. However if an exception occurs at this level, or we *return* or *yield* or the thread changes, we stop regardless of count. A suffix of "+" on the command or an alias to the command forces to move to another line, while a suffix of "-" does the opposite and disables the requiring a move to a new line. If no suffix is given, the debugger setting 'different' determines this behavior. If no suffix is given, the debugger setting *different* determines this behavior. Examples: --------- #{NAME} # #{NAME} 1 event, *any* event #{NAME} 1 # same as above #{NAME}+ # same but force stopping on a new line #{NAME}= # same but force stopping on a new line a new frame added #{NAME}- # same but force stopping on a new line a new frame added #{NAME} 5/5+0 # same as above #{NAME} line # #{NAME} using only line events #{NAME} call # #{NAME} using only call call events #{NAME}<> # #{NAME} using call return events at this level or below See also: --------- `step`, `continue`, `finish`, `set different` HELP ALIASES = %W(n #{NAME}+ #{NAME}- #{NAME}< #{NAME}> #{NAME}<> #{NAME}! n> n< n! n+ n- n<> n=) CATEGORY = 'running' # execution_set = ['Running'] MAX_ARGS = 1 # Need at most this many. FIXME: will be eventually 2 NEED_STACK = true NEED_RUNNING = true SHORT_HELP = 'Step program without entering called functions' end # This method runs the command def run(args) opts = @proc.parse_next_step_suffix(args[0]) if args.size == 1 # Form is: "next" which means "next 1" step_count = 0 else count_str = args[1] opts = { :msg_on_error => "The '#{NAME}' command argument must eval to an integer. Got: %s" % count_str, :min_value => 1 } count = @proc.get_an_int(count_str, opts) return unless count # step 1 is core.step_count = 0 or "stop next event" step_count = count - 1 end @proc.next(step_count, opts) end end if __FILE__ == $0 require_relative '../mock' dbgr, cmd = MockDebugger::setup [%w(n 5), %W(#{cmd.name} 1+2), %w(n foo)].each do |c| dbgr.core.step_count = 0 cmd.proc.leave_cmd_loop = false result = cmd.run(c) puts 'Run result: %s' % result puts 'step_count %d, leave_cmd_loop: %s' % [dbgr.core.step_count, cmd.proc.leave_cmd_loop] end [%w(n), %w(next+), %w(n-)].each do |c| dbgr.core.step_count = 0 cmd.proc.leave_cmd_loop = false result = cmd.run(c) puts cmd.proc.different_pos end end
true
e6162ce43b9d20c01b8ebac75d0af372432868a1
Ruby
bosoxbill/advent-of-code-2020
/day4/day4.rb
UTF-8
1,348
3.09375
3
[]
no_license
class Identification SHORTHAND_TO_ATTRS = { pid: :passport_id, cid: :country_id, byr: :birth_year, iyr: :issue_year, eyr: :expiration_year, hgt: :height, hcl: :hair_color, ecl: :eye_color } VALID_ATTRS = SHORTHAND_TO_ATTRS.values REQUIRED_ATTRS = VALID_ATTRS - [:country_id] attr_accessor *VALID_ATTRS def initialize(opts ={}) clean_opts = opts.slice(VALID_ATTRS) VALID_ATTRS.each do |(attr, value)| send "#{attr}=", value end end def valid? valid_fields = 0 REQUIRED_ATTRS.each do |attr| ivar = instance_variable_get("@#{attr}") return false if ivar.nil? end return true end end def read_input valid_count = 0 identifications = Array.new id = Identification.new File.open('input.txt', 'r') do |f| f.each_line do |line| key_value_pairs = line.split(' ') if key_value_pairs.empty? identifications << id id = Identification.new next end key_value_pairs.each do |kvp| key, value = kvp.split(':') ivar_name = Identification::SHORTHAND_TO_ATTRS[key.to_sym] id.send("#{ivar_name}=", value) end end end identifications << id return identifications end def do_it ids = read_input valid = ids.select(&:valid?) return valid.count end puts do_it()
true
e14bf35767f09e96fa2315a93e4c4928e2010fb9
Ruby
ezkl/dimapa
/lib/diff_methods.rb
UTF-8
4,091
3.09375
3
[ "MIT" ]
permissive
module DiffMethods FIXNUM_MAX = 2**(0.size * 8 - 2) - 1 attr_accessor :diff_timeout def initialize # Number of seconds to map a diff before giving up (0 for infinity). @diff_timeout = 1 end # Find the differences between two texts. Simplifies the problem by # stripping any common prefix or suffix off the texts before editing. def diff_main(text1, text2, checklines = true, deadline = nil) # Set a deadline by which time the diff must be complete. deadline ||= diff_new_deadline # Check for null inputs. raise ArgumentError.new("Null inputs. (diff_main)") unless text1 || text2 # Check for equality (speedup). return (text1.empty? ? [] : [[:equal, text1]]) if text1 == text2 diff_main_compute_diff(text1, text2, checklines, deadline) end def diff_main_compute_diff(text1, text2, checklines, deadline) # Trim off common prefix and suffix (speedup). common_prefix, text1, text2 = diff_trim_common_prefix(text1, text2) common_suffix, text1, text2 = diff_trim_common_suffix(text1, text2) # Compute the diff on the middle block. diffs = diff_compute(text1, text2, checklines, deadline) # Restore the prefix and suffix. diffs.unshift([:equal, common_prefix]) unless common_prefix.nil? diffs.push([:equal, common_suffix]) unless common_suffix.nil? diff_cleanup_merge(diffs) diffs end private :diff_main_compute_diff # Calculate a new deadline using the @diff_timeout configuration value def diff_new_deadline Time.now + (diff_timeout.zero? ? FIXNUM_MAX : diff_timeout) end private :diff_new_deadline # Trim off the common prefix def diff_trim_common_prefix(text1, text2) if (common_length = diff_common_prefix(text1, text2)).nonzero? common_prefix = text1[0...common_length] text1 = text1[common_length..] text2 = text2[common_length..] end [common_prefix, text1, text2] end private :diff_trim_common_prefix # Trim off the common suffix def diff_trim_common_suffix(text1, text2) if (common_length = diff_common_suffix(text1, text2)).nonzero? common_suffix = text1[-common_length..] text1 = text1[0...-common_length] text2 = text2[0...-common_length] end [common_suffix, text1, text2] end private :diff_trim_common_suffix # Find the differences between two texts. Assumes that the texts do not # have any common prefix or suffix. def diff_compute(text1, text2, checklines, deadline) if (diffs = diff_compute_common_cases(text1, text2)) diffs elsif (diffs = diff_compute_half_match(text1, text2, checklines, deadline)) diffs elsif checklines && text1.length > 100 && text2.length > 100 diff_line_mode(text1, text2, deadline) else diff_bisect(text1, text2, deadline) end end def diff_compute_half_match(text1, text2, checklines, deadline) if (hm = diff_half_match(text1, text2)) # A half-match was found, sort out the return data. text1_a, text1_b, text2_a, text2_b, mid_common = hm # Send both pairs off for separate processing. diffs_a = diff_main(text1_a, text2_a, checklines, deadline) diffs_b = diff_main(text1_b, text2_b, checklines, deadline) # Merge the results. diffs_a + [[:equal, mid_common]] + diffs_b end end private :diff_compute_half_match def diff_compute_common_cases(text1, text2) # Just add some text (speedup). return [[:insert, text2]] if text1.empty? # Just delete some text (speedup). return [[:delete, text1]] if text2.empty? short, long = [text1, text2].sort_by(&:length) # Shorter text is inside the longer text (speedup). if (i = long.index(short)) op = text1.length > text2.length ? :delete : :insert [[op, long[0...i]], [:equal, short], [op, long[(i + short.length)..]]] # Single character string. elsif short.length == 1 # After the previous speedup, the character can't be an equality. [[:delete, text1], [:insert, text2]] end end private :diff_compute_common_cases end
true
1d1658c7b999d202683e69222b196dbe9aff6541
Ruby
nikolic/itekako-darts
/spec/models/game_spec.rb
UTF-8
1,399
2.5625
3
[]
no_license
# == Schema Information # # Table name: games # # id :integer not null, primary key # coeficient_id :integer # number_of_players :integer # doubles :boolean # created_at :datetime not null # updated_at :datetime not null # require 'spec_helper' describe Game do before do @coeficient = FactoryGirl.create :coeficient @players = [] 8.times do @players.push FactoryGirl.create :player end @game = Game.start_new true, @players end subject { @game } describe "Check validation" do it { should be_valid } end game_fields = [ :number_of_players, :coeficient_id, :doubles ] describe "Check fields" do game_fields.each do |field| it { should respond_to field} end end describe "Checking game mechanics" do before do # @game.add_players(@players) @game.position_teams [3,2,4,1] end it "should have 8 players" do @game.number_of_players.should eq 8 end it "should have 2 players per team" do 4.times do |i| @game.get_team(i+1).count.should eq 2 end end it "should have correct team order" do @game.team_position(1).should eq 4 @game.team_position(2).should eq 2 @game.team_position(3).should eq 1 @game.team_position(4).should eq 3 end end end
true
26ba156b79f4192de15cad3ecb2c5496bb64ba0e
Ruby
mcdees2010/Movie-Bites
/app/controllers/movielists_controller.rb
UTF-8
501
2.75
3
[]
no_license
class MovielistsController < ApplicationController def index if params[:search] #if a user has searched for a movie sanitized = params[:search].split.map { |i| i.capitalize }.join(' ') #turn what the user searched in capitalized words by each element in an array @movies = Movie.where("title LIKE ?", "%#{sanitized}%") #queries movies searched by the sanitized parameter, finding a similar title else @movies = Movie.all end end end
true
e174236c7808c43a9eef49ccdfaebb7d8a02996a
Ruby
rouge-ruby/rouge
/spec/support/similarity.rb
UTF-8
851
2.515625
3
[ "MIT", "BSD-2-Clause" ]
permissive
module Similarity def self.test(lexer_class) # state_defintions is an InheritableHash, so we use `own_keys` to # exclude states inherited from superclasses state_names = Set.new(lexer_class.state_definitions.own_keys) candidates = Rouge::Lexer.all.select do |x| # we can only compare to RegexLexers which have state_definitions next false unless x < Rouge::RegexLexer # don't compare a lexer to itself or any subclasses next false if x <= lexer_class true end max_score = 1 matches = [] candidates.each do |candidate| score = (state_names & candidate.state_definitions.keys).size if score > max_score max_score = score matches = [candidate] elsif score == max_score matches << candidate end end [max_score, matches] end end
true
b112a8d216b32521ae5532b2a0116a1eb333e0a7
Ruby
ryanmeinzer/ruby-project-alt-guidelines-nyc01-seng-ft-042020
/bin/run-legacy.rb
UTF-8
195
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# require_relative '../config/environment' # puts "Yo, what's your name? Let's shred." # puts "" # puts "" # greeting # starter # play # puts "" # puts "" # puts "Peace!" # puts "" # puts ""
true
20357b10d84ace27f658543bae4a67be1364196d
Ruby
braintree/braintree_ruby
/lib/braintree/resource_collection.rb
UTF-8
1,314
2.9375
3
[ "MIT" ]
permissive
module Braintree class ResourceCollection # :nodoc: include Enumerable attr_reader :ids def initialize(response, &block) # :nodoc: @ids = Util.extract_attribute_as_array(response[:search_results], :ids) @page_size = response[:search_results][:page_size] @paging_block = block end # Yields each item def each(&block) @ids.each_slice(@page_size) do |page_of_ids| resources = @paging_block.call(page_of_ids) resources.each(&block) end end def empty? @ids.empty? end # Returns the first or the first N items in the collection or nil if the collection is empty def first(amount = 1) return nil if @ids.empty? return @paging_block.call([@ids.first]).first if amount == 1 @ids.first(amount).each_slice(@page_size).flat_map do |page_of_ids| @paging_block.call(page_of_ids) end end # Only the maximum size of a resource collection can be determined since the data on the server can change while # fetching blocks of results for iteration. For example, customers can be deleted while iterating, so the number # of results iterated over may be less than the maximum_size. In general, this method should be avoided. def maximum_size @ids.size end end end
true
e137bd088c4277117ad73d1e1828e27efad4af87
Ruby
kristjan/fastmuffin
/app/models/singly.rb
UTF-8
739
2.84375
3
[]
no_license
require 'httparty' class Singly SINGLY_API_BASE = "https://api.singly.com" def initialize(token) @token = token end def checkins(opts) start = Time.now data = HTTParty.get(SINGLY_API_BASE + '/types/checkins', { :query => opts.merge(:access_token => @token) }).parsed_response opts[:fields] ? Singly.expand_fields(data) : data end private def self.expand_fields(data) data.map do |datum| item = {} datum.keys.each do |field| cursor = item pieces = field.split('.') pieces[0...-1].each do |piece| cursor[piece] ||= {} cursor = cursor[piece] end cursor[pieces.last] = datum[field] end item end end end
true
6d5b73af323b7e085c45bc86c285f655cf329ffc
Ruby
maksimoreo/chess_ruby
/lib/chesspieces/king.rb
UTF-8
3,881
3.21875
3
[]
no_license
# frozen_string_literal: true require_relative 'chesspiece' require_relative '../directional_moves' require_relative '../chess_position' # King chess piece class King < ChessPiece def allowed_cells(from, chessboard) # Not using available_cells(from, cb) here, because it also returns unchecked castlings moves = attack_cells(from, chessboard).reject do |cell| # Reject occupied cells next true unless chessboard.can_move_or_take?(cell, color) # Copy chessboard temp_chessboard = chessboard.clone # Perform the move on a temporary chessboard perform_chess_move(ChessMove.new(from, cell), temp_chessboard) # Reject moves that result in check temp_chessboard.check?(color) end castlings = allowed_castlings(chessboard, from, color == :white ? 0 : 7) moves + castlings end def available_cells(from, chessboard) moves = attack_cells(from, chessboard).select do |cell| chessboard.can_move_or_take?(cell, color) end castlings = available_castlings(chessboard, from, color == :white ? 0 : 7) moves + castlings end # King always attacks 8 cells around it (5 if on the edge, 3 if in the corner) def attack_cells(from, _chessboard) (DiagonalMoves.directions + AxisAlignedMoves.directions) .map { |direction| from + direction } .reject(&:nil?) end def move(chess_move, chessboard) # Move King chessboard.reposition(chess_move[:from], chess_move[:to]) # Move Rook if performing a castling row = chess_move[:from].i if chess_move[:from].j == 4 && (row == 0 || row == 7) if chess_move[:to].j == 2 # Queenside chessboard.reposition(ChessPosition.new(row, 0), ChessPosition.new(row, 3)) elsif chess_move[:to].j == 6 # Kingside chessboard.reposition(ChessPosition.new(row, 7), ChessPosition.new(row, 5)) end end # disallow castling chessboard.info[color][:castling][:queenside] = false chessboard.info[color][:castling][:kingside] = false end def perform_chess_move(chess_move, chessboard) # Move King chessboard.reposition(chess_move.from, chess_move.to) # Move Rook if performing a castling row = chess_move.from.i if chess_move.from.j == 4 && (row == 0 || row == 7) if chess_move.to.j == 2 # Queenside chessboard.reposition(ChessPosition.new(row, 0), ChessPosition.new(row, 3)) elsif chess_move.to.j == 6 # Kingside chessboard.reposition(ChessPosition.new(row, 7), ChessPosition.new(row, 5)) end end # disallow castling chessboard.info[color][:castling][:queenside] = false chessboard.info[color][:castling][:kingside] = false end private def available_castlings(chessboard, pos, row) cells = [] check = lambda do |side, rook_column, empty_from, empty_to| pos == ChessPosition.new(row, 4) && # King is on e1 or e8 chessboard.info[color][:castling][side] && # Neither the king nor the chosen rook has previously moved. chessboard[ChessPosition.new(row, rook_column)] == Rook[color] && # There is a rook in the corner (empty_from..empty_to).all? { |n| chessboard.cell_empty?(ChessPosition.new(row, n)) } # There are no pieces between the king and the chosen rook end if pos == ChessPosition.new(row, 4) cells << ChessPosition.new(row, 2) if check.call(:queenside, 0, 1, 3) cells << ChessPosition.new(row, 6) if check.call(:kingside, 7, 5, 6) end cells end def allowed_castlings(chessboard, from, row) available_castlings(chessboard, from, row).select do |move| range = [from.j, move.j].minmax # King's cell, rook's cell and cells between them are not under attack (range[0]..range[1]).none? { |n| chessboard.cell_under_attack?(ChessPosition.new(row, n), ChessPiece.opposite_color(color)) } end end end
true