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
a779618d3c24e47c1231c836c30227e4809ee642
Ruby
KevinKra/Enigma
/lib/Enigma.rb
UTF-8
924
3.296875
3
[]
no_license
require 'time' require_relative "../lib/utils/helpers.rb" require_relative "../lib/Encrypt.rb" class Enigma include Helpers attr_reader :key, :date def initialize @key = gen_key @date = todays_date @encrypt = Encrypt.new end private def gen_key rand.to_s[2..6] end def todays_date Time.now.strftime("%d%m%y") end public def encrypt(message, key = nil, date = nil) # encrypt the message date = todays_date if date == nil key = gen_key if key == nil { encryption: @encrypt.handle_encryption(true, message, key, date), key: key, date: date } end def decrypt(message, key, date = nil) # decrypt the message date = todays_date if date == nil # is it smart to handle the date like this for decryption? { encryption: @encrypt.handle_encryption(false, message, key, date), key: key, date: date } end end
true
80a434c8779e30ecaa8181b27caf50d29c2690fb
Ruby
brunogarciagonzalez/sinatra-mvc-lab-dc-web-031218
/models/piglatinizer.rb
UTF-8
1,364
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class PigLatinizer attr_reader :text # def initialize(text) # @text = text # end def piglatinize(word) text_array = word.split(" ") final_words = text_array.collect do |word| word_array = word.split("") if consonants_array.include?(word_array.first) && consonants_array.include?(word_array[1]) && consonants_array.include?(word_array[2]) first_letter = word_array.shift second_letter = word_array.shift third_letter = word_array.shift word_array.push(first_letter).push(second_letter).push(third_letter) word_array.join + "ay" elsif consonants_array.include?(word_array.first) && consonants_array.include?(word_array[1]) first_letter = word_array.shift second_letter = word_array.shift word_array.push(first_letter).push(second_letter) word_array.join + "ay" elsif consonants_array.include?(word_array.first) first_letter = word_array.shift word_array.push(first_letter) word_array.join + "ay" elsif vowels_array.include?(word_array.first) word_array.join + "way" end end final_words.join(" ") end private def consonants_array consonants_array = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ".split("") end def vowels_array vowels_array = "aeiouAEIOU".split("") end end
true
c06de0282e1eb681e56aafbd254608be66df376b
Ruby
Pistos/rdbi-driver-sqlite3
/lib/rdbi/driver/sqlite3.rb
UTF-8
4,613
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'rdbi' require 'epoxy' require 'methlab' require 'sqlite3' class RDBI::Driver::SQLite3 < RDBI::Driver def initialize(*args) super(Database, *args) end end class RDBI::Driver::SQLite3 < RDBI::Driver class Database < RDBI::Database extend MethLab attr_accessor :handle def initialize(*args) super self.database_name = @connect_args[:database] sqlite3_connect end def reconnect super sqlite3_connect end def disconnect super @handle.close end def transaction(&block) raise RDBI::TransactionError, "already in a transaction" if in_transaction? @handle.transaction super end def new_statement(query) sth = Statement.new(query, self) return sth end def preprocess_query(query, *binds) mutex.synchronize { @last_query = query } hashes, binds = binds.partition { |x| x.kind_of?(Hash) } total_hash = hashes.inject({}) { |x, y| x.merge(y) } ep = Epoxy.new(query) ep.quote(total_hash) { |x| ::SQLite3::Database.quote((total_hash[x] || binds[x]).to_s) } end def schema sch = { } execute("SELECT name, type FROM sqlite_master WHERE type='table' or type='view'").fetch(:all).each do |row| table_name_sym, table_name, table_type_sym = row[0].to_sym, row[0], row[1].to_sym sch[table_name_sym] = table_schema(table_name, table_type_sym) end return sch end def table_schema(table_name, type = nil) # overloaded for performance sch = RDBI::Schema.new([], [], type) sch.tables << table_name.to_sym unless sch.type sch.type = execute("select type from sqlite_master where (type='table' or type='view') and name=?", table_name.to_s).fetch(:first)[0].to_sym rescue nil return nil unless sch.type end @handle.table_info(table_name) do |hash| col = RDBI::Column.new col.name = hash['name'].to_sym col.type = hash['type'].to_sym col.ruby_type = hash['type'].to_sym col.nullable = !(hash['notnull'] == "0") sch.columns << col end return sch end inline(:ping) { 0 } def rollback raise RDBI::TransactionError, "not in a transaction during rollback" unless in_transaction? @handle.rollback super() end def commit raise RDBI::TransactionError, "not in a transaction during commit" unless in_transaction? @handle.commit super() end protected def sqlite3_connect @handle = ::SQLite3::Database.new(database_name) @handle.type_translation = false # XXX RDBI should handle this. end end class Statement < RDBI::Statement extend MethLab attr_accessor :handle def initialize(query, dbh) super ep = Epoxy.new(query) @index_map = ep.indexed_binds # sanitizes the query of named binds so we can use SQLite3's native # binder with our extended syntax. @index_map makes a reappearance in # new_execution(). query = ep.quote(@index_map.compact.inject({}) { |x,y| x.merge({ y => nil }) }) { '?' } @handle = check_exception { dbh.handle.prepare(query) } @input_type_map = RDBI::Type.create_type_hash(RDBI::Type::In) @output_type_map = RDBI::Type.create_type_hash(RDBI::Type::Out) end def new_execution(*binds) # XXX is there a patron saint of being too clever? I don't like this # code. hashes, binds = binds.partition { |x| x.kind_of?(Hash) } hash = hashes.inject({}) { |x, y| x.merge(y) } hash.keys.each do |key| if index = @index_map.index(key) binds.insert(index, hash[key]) end end # but this code is still ok. rs = check_exception { @handle.execute(*binds) } ary = rs.to_a # FIXME type management columns = rs.columns.zip(rs.types) columns.collect! do |col| newcol = RDBI::Column.new newcol.name = col[0].to_sym newcol.type = col[1] newcol.ruby_type = col[1].to_sym newcol end this_schema = RDBI::Schema.new this_schema.columns = columns return ary, this_schema, @output_type_map end def finish @handle.close rescue nil super end protected def check_exception(&block) begin yield rescue ArgumentError => e if dbh.handle.closed? raise RDBI::DisconnectedError, "database is disconnected" else raise e end end end end end
true
a1ae676c9f1ba710152a199b0b70d24e740fe689
Ruby
davecozz/pi-sprinkler-api
/src/sprinkler.rb
UTF-8
2,078
3.0625
3
[]
no_license
require 'json' module Sprinkler @active_sprinklers = ['s0', 's1', 's2', 's3'] @gpio_bin = '/usr/local/bin/gpio' @coil_time = 0.3 #length of time in sec to energize the valve coils @pin_offset = 4 #physical offset between on and off gpio pins @status_file = '/dev/shm/sprinkler_status.json' def self.active_sprinklers() @active_sprinklers end def self.get_status(sprinkler) _init_file() s_status = JSON.parse(File.read(@status_file)) if s_status.length > 0 if s_status.has_key?(sprinkler) return s_status[sprinkler] else return false end else return false end end def self.get_status_all() _init_file() status_all = {} @active_sprinklers.each do |s| status_all[s] = get_status(s) end return status_all end def self.on(sprinkler) spk_num = sprinkler[1..-1] #trim first character _reset(spk_num) system("#{@gpio_bin} write #{spk_num} 0") sleep( @coil_time ) system("#{@gpio_bin} write #{spk_num} 1") _set_status(sprinkler, true) end def self.off(sprinkler) spk_num = sprinkler[1..-1] #trim first character spk_off = spk_num.to_i + @pin_offset _reset(spk_off) system("#{@gpio_bin} write #{spk_off} 0") sleep(@coil_time) system("#{@gpio_bin} write #{spk_off} 1") _set_status(sprinkler, false) end def self.timer(sprinkler, min) sec = min.to_i * 60 on(sprinkler) _set_status(sprinkler, true) sleep(sec) off(sprinkler) _set_status(sprinkler, false) end ## private methods def self._reset(pin) system("#{@gpio_bin} mode #{pin} output") sleep(1) end def self._init_file() unless File.file?(@status_file) File.write(@status_file, '{}') end end def self._set_status(sprinkler, status) _init_file() s_status = JSON.parse(File.read(@status_file)) s_status.merge!({sprinkler => status}) File.write(@status_file, s_status.to_json) end class << self private :_reset private :_init_file private :_set_status end end
true
91ada56b03da528d9dd264504bd5c4dfc831dcb0
Ruby
InfinityG/ig-coin-api
/api/services/transaction_service.rb
UTF-8
2,237
2.65625
3
[]
no_license
require './api/gateway/ripple_rest_gateway' require './api/utils/hash_generator' require './api/models/transaction' class TransactionService def execute_deposit(user, amount) ripple_gateway = RippleRestGateway.new client_resource_id = HashGenerator.new.generate_uuid payment = ripple_gateway.prepare_deposit user[:id].to_s, amount status_url = ripple_gateway.create_deposit(client_resource_id, payment) sleep 5 #TODO: break this out into a separate process confirmation_result = ripple_gateway.confirm_transaction "#{RIPPLE_REST_URI}#{status_url}" save_transaction user, confirmation_result, client_resource_id, 'deposit' end def execute_withdrawal(user, amount) ripple_gateway = RippleRestGateway.new client_resource_id = HashGenerator.new.generate_uuid payment = ripple_gateway.prepare_withdrawal user[:id].to_s, amount status_url = ripple_gateway.create_withdrawal(client_resource_id, payment) sleep 5 confirmation_result = ripple_gateway.confirm_transaction "#{RIPPLE_REST_URI}#{status_url}" save_transaction user, confirmation_result, client_resource_id, 'withdrawal' end def get_transactions(user_id) Transaction.all(:user_id => user_id) end def get_transaction_by_id(user_id, transaction_id) Transaction.all(:id => transaction_id, :user_id => user_id).first end private def save_transaction(user, confirmation_result, resource_id, type) transaction = Transaction.new(:user_id => user.id, :resource_id => resource_id, :ledger_id => confirmation_result[:ledger_id], :ledger_hash => confirmation_result[:ledger_hash], :ledger_timestamp => confirmation_result[:ledger_timestamp], :amount => confirmation_result[:amount], :currency => confirmation_result[:currency], :type => type, :status => confirmation_result[:status]) if transaction.save transaction else transaction.errors.each do |e| puts e end raise 'Error saving transaction!' end end end
true
2c98c5f03e0c44e9a5d20bed5c85c503fb158348
Ruby
pigasksky/Brotorift
/src/lib/compiler.rb
UTF-8
8,122
2.5625
3
[]
no_license
require_relative 'parser' require_relative 'compiler_error' require_relative 'runtime' class String def char_case if self == self.upcase return :upper else return :lower end end end class Compiler attr_reader :errors, :runtime def initialize @errors = [] @message_base_id = 0 @message_id = 0 end def compile filename @runtime = self.compile_file filename end def compile_file filename content = File.read filename, encoding: 'utf-8' tokens = Lexer::lex content, filename begin ast = Parser::parse tokens rescue RLTK::NotInLanguage => e add_error UnexpectedTokenError.new e.current return end runtime = Runtime.new filename self.compile_ast runtime, ast runtime end def compile_ast runtime, ast @runtime = runtime ast.each do |decl| begin case decl when IncludeDecl compile_include decl when EnumDecl compile_enum decl when NodeDecl compile_node decl when StructDecl compile_struct decl when DirectionDecl compile_direction decl when SequenceDecl compile_sequence decl end rescue CompilerError => e @errors.push e end end end def compile_include include_ast filename = include_ast.filename + '.b' if not File.exists? filename add_error IncludeFileNotFoundError.new filename, include_ast.position return end include_runtime = self.compile_file filename @runtime.add_include include_runtime end def compile_enum enum_ast self.check_case 'enum', :upper, enum_ast self.check_type_unique enum_ast enum_def = EnumTypeDef.new enum_ast enum_ast.elements.each do |element_ast| self.check_case 'enum element', :upper, element_ast self.check_unique 'enum element', enum_def.elements[element_ast.name], element_ast element_def = EnumElementDef.new element_ast enum_def.add_element element_def end @runtime.add_enum enum_def end def compile_node node_ast self.check_case 'node', :upper, node_ast self.check_case 'node_nick', :upper, node_ast self.check_unique 'node', @runtime.nodes[node_ast.name], node_ast self.check_unique 'node', @runtime.nodes[node_ast.nickname], node_ast node_def = NodeDef.new node_ast @runtime.add_node node_def end def compile_struct struct_ast self.check_case 'struct', :upper, struct_ast self.check_type_unique struct_ast struct_def = StructTypeDef.new struct_ast struct_ast.members.each do |member_ast| self.check_case 'struct member', :lower, member_ast self.check_unique 'struct member', struct_def.get_member(member_ast.name), member_ast member_type_def = self.get_member_type @runtime.nodes.values, member_ast.type member_def = MemberDef.new member_ast, member_type_def struct_def.add_member member_def end @runtime.add_struct struct_def end def compile_direction direction_ast client = @runtime.nodes[direction_ast.client] if client == nil add_error NodeNotFoundError.new direction_ast, direction_ast.client return end server = @runtime.nodes[direction_ast.server] if server == nil add_error NodeNotFoundError.new direction_ast, direction_ast.server return end if client == server add_error ClientServerSameError.new direction_ast return end @message_base_id += 1000 @message_id = 0 old_direction = @runtime.get_direction client, direction_ast.direction, server self.check_unique 'direction', old_direction, direction_ast direction_def = DirectionDef.new direction_ast, client, server direction_ast.messages.each do |message_ast| self.check_case 'message', :upper, message_ast self.check_unique 'message', direction_def.messages[message_ast.name], message_ast direction_def.add_message self.compile_message direction_def, message_ast end @runtime.add_direction direction_def end def compile_message direction_def, message_ast @message_id += 1 message_def = MessageDef.new message_ast, @message_base_id + @message_id message_ast.members.each do |member_ast| self.check_case 'message member', :lower, member_ast self.check_unique 'message member', message_def.get_member(member_ast.name), member_ast nodes_to_check = [direction_def.client, direction_def.server] member_type_def = self.get_member_type nodes_to_check, member_ast.type member_def = MemberDef.new member_ast, member_type_def message_def.add_member member_def end message_def end def compile_sequence sequence_ast self.check_case 'sequence', :upper, sequence_ast self.check_unique 'sequence', @runtime.get_sequence(sequence_ast.name), sequence_ast sequence_def = SequenceDef.new sequence_ast sequence_ast.steps.each do |step_ast| sequence_def.add_step self.compile_step step_ast end @runtime.add_sequence sequence_def end def compile_step step_ast client = @runtime.nodes[step_ast.client] if client == nil add_error NodeNotFoundError.new step_ast, step_ast.client return nil end server = @runtime.nodes[step_ast.server] if server == nil add_error NodeNotFoundError.new step_ast, step_ast.server return nil end if client == server add_error ClientServerSameError.new step_ast return nil end direction_def = @runtime.get_direction client, step_ast.direction, server if direction_def == nil add_error DirectionNotFoundError.new step_ast, client, step_ast.direction, server return nil end message_def = direction_def.messages[step_ast.message] if message_def == nil add_error MessageNotFoundError.new step_ast, direction_def return nil end StepDef.new step_ast, direction_def, message_def end def get_member_type nodes_to_check, member_type_ast type_def, runtime = self.get_type member_type_ast, true return nil if type_def == nil params = [] case type_def.name when 'List' self.check_type_param_count member_type_ast, 1 params.push self.get_member_type nodes_to_check, member_type_ast.params[0] when 'Set' self.check_type_param_count member_type_ast, 1 params.push self.get_member_type nodes_to_check, member_type_ast.params[0] when 'Map' self.check_type_param_count member_type_ast, 2 params.push self.get_member_type nodes_to_check, member_type_ast.params[0] params.push self.get_member_type nodes_to_check, member_type_ast.params[1] else self.check_type_param_count member_type_ast, 0 end member_type_def = TypeInstanceDef.new member_type_ast, type_def, params, runtime self.check_type_nodes member_type_ast, member_type_def member_type_def end def check_type_nodes member_type_ast, member_type_def return if @runtime == member_type_def.runtime @runtime.nodes.each do |n| external_node = member_type_def.runtime.nodes.find { |node| n.name == node.name } if external_node == nil add_error CorrespondingNodeNotFoundError.new member_type_def, n.name return end if external_node.language != n.language add_error NodeLanguageMismatchError.new member_type_def, n, external_node return end end end def get_type ast, raise_error return nil if ast == nil type_def, runtime = @runtime.get_type ast.name return type_def, runtime if type_def != nil add_error TypeNotFoundError.new ast, ast.name if raise_error return type_def, runtime end def check_case type, initial_case, ast if type == 'node_nick' and initial_case != ast.nickname[0].char_case add_error InitialCaseError.new type, initial_case, ast elsif initial_case != ast.name[0].char_case add_error InitialCaseError.new type, initial_case, ast end end def check_type_unique ast type_def, _ = self.get_type ast, false return if type_def == nil if type_def.is_a? BuiltinTypeDef add_error BuiltinNameConflictError.new ast else self.check_unique 'type', type_def, ast end end def check_unique type, old_def, new_ast return if old_def == nil add_error DuplicateDefError.new type, old_def.name, old_def.ast, new_ast end def check_type_param_count ast, expected_count add_error TypeParamCountMismatchError.new ast, expected_count if ast.params.length != expected_count end def add_error error @errors.push error end end
true
b5426adeaf55c012524484a017a4a0006c9eeaf7
Ruby
stonesaw/AtCoder
/2019-11-09_1.rb
UTF-8
99
3.5625
4
[]
no_license
n = gets.chomp.to_i if(n % 2 == 0) print(n % 2 - 1) elsif(n % 2 == 1) print(n - 1) / 2 end
true
07e45e356cf3d06acfa48b79f153fa0b69882e74
Ruby
kernelsmith/workbook
/test/test_readers_csv_reader.rb
UTF-8
4,725
2.84375
3
[ "MIT", "GPL-3.0-only", "LGPL-2.0-or-later", "GPL-2.0-only", "Ruby" ]
permissive
# frozen_string_literal: true require File.join(File.dirname(__FILE__), "helper") module Readers class TestCsvWriter < Minitest::Test def test_open w = Workbook::Book.new w.import File.join(File.dirname(__FILE__), "artifacts/simple_csv.csv") # reads # a,b,c,d # 1,2,3,4 # 5,3,2,1 # "asdf",123,12,2001-02-02 # assert_equal([:a, :b, :c, :d], w.sheet.table.header.to_symbols) assert_equal(3, w.sheet.table[2][:b].value) assert_equal("asdf", w.sheet.table[3][:a].value) assert_equal(Date.new(2001, 2, 2), w.sheet.table[3][:d].value) end def test_excel_csv_open w = Workbook::Book.new w.import File.join(File.dirname(__FILE__), "artifacts/simple_excel_csv.csv") # reads # a;b;c # 1-1-2001;23;1 # asdf;23;asd # 23;asdf;sadf # 12;23;12-02-2011 12:23 # 12 asadf; 6/12 ovk getekend teru...; 6/12 # y w.sheet.table assert_equal([:a, :b, :c], w.sheet.table.header.to_symbols) assert_equal(23, w.sheet.table[2][:b].value) assert_equal("sadf", w.sheet.table[3][:c].value) assert_equal(Date.new(2001, 1, 1), w.sheet.table[1][:a].value) assert_equal(DateTime.new(2011, 2, 12, 12, 23), w.sheet.table[4][:c].value) assert_equal("6/12 ovk getekend terugontv.+>acq ter tekening. 13/12 ovk getekend terugontv.+>Fred ter tekening.", w.sheet.table[5][:b].value) assert_equal("6/12", w.sheet.table[5][:c].value) end def test_excel_standardized_open w = Workbook::Book.new w.import File.join(File.dirname(__FILE__), "artifacts/excel_different_types.csv") # reads # a,b,c,d # 2012-02-22,2014-12-27,2012-11-23,2012-11-12T04:20:00+00:00 # c,222.0,,0027-12-14T05:21:00+00:00 # 2012-01-22T11:00:00+00:00,42000.0,"goh, idd",ls assert_equal([:a, :b, :c, :d], w.sheet.table.header.to_symbols) assert_equal(Date.new(2012, 2, 22), w.sheet.table[1][:a].value) assert_equal("c", w.sheet.table[2][:a].value) assert_equal(DateTime.new(2012, 1, 22, 11), w.sheet.table[3][:a].value) assert_equal(42000, w.sheet.table[3][:b].value) assert_nil(w.sheet.table[2][:c].value) end def test_class_read_string s = File.read File.join(File.dirname(__FILE__), "artifacts/simple_csv.csv") w = Workbook::Book.read(s, :csv) # reads # a,b,c,d # 1,2,3,4 # 5,3,2,1 # "asdf",123,12,2001-02-02 # assert_equal([:a, :b, :c, :d], w.sheet.table.header.to_symbols) assert_equal(3, w.sheet.table[2][:b].value) assert_equal("asdf", w.sheet.table[3][:a].value) assert_equal(Date.new(2001, 2, 2), w.sheet.table[3][:d].value) end def test_instance_read_string w = Workbook::Book.new s = File.read File.join(File.dirname(__FILE__), "artifacts/simple_csv.csv") w.read(s, :csv) # reads # a,b,c,d # 1,2,3,4 # 5,3,2,1 # "asdf",123,12,2001-02-02 # assert_equal([:a, :b, :c, :d], w.sheet.table.header.to_symbols) assert_equal(3, w.sheet.table[2][:b].value) assert_equal("asdf", w.sheet.table[3][:a].value) assert_equal(Date.new(2001, 2, 2), w.sheet.table[3][:d].value) end def test_instance_read_stringio w = Workbook::Book.new sio = StringIO.new(File.read(File.join(File.dirname(__FILE__), "artifacts/simple_csv.csv"))) w.read(sio, :csv) # reads # a,b,c,d # 1,2,3,4 # 5,3,2,1 # "asdf",123,12,2001-02-02 # assert_equal([:a, :b, :c, :d], w.sheet.table.header.to_symbols) assert_equal(3, w.sheet.table[2][:b].value) assert_equal("asdf", w.sheet.table[3][:a].value) assert_equal(Date.new(2001, 2, 2), w.sheet.table[3][:d].value) end def test_from_string w = Workbook::Book.read("2013-03-19,JV,211,032,1,DBG A,,13,0147,\n", :csv, {converters: []}) assert_equal("2013-03-19,JV,211,032,1,DBG A,,13,0147,\n", w.sheet.table.to_csv) end def test_semi_colon_separated_csv w = Workbook::Book.open(File.join(File.dirname(__FILE__), "artifacts/semicolonseparated_in_csv.csv")) assert_equal("artikel,aantal,bedrag,reservering,aanmaaktijd_reservering,gastnummer,titel,voorletters,tussenvoegsels,naam,straat,huisnummer,postcode,woonplaats,email,tel_land,tel_net,tel_abon\nVriend - € 50,1,50.0,123,2016-10-27,7891,asdf,A.,,asdf,asdf ,55,1234 LM,AMSTERDAM,a@example.com,43,,123123\nVriend - € 35,1,35.0,123,2016-11-02,5676,Dasdfr,B.,,asdf,asdf asdf,12,1234 NN,UTRECHT,b@example.com,31,60,123123\n", w.sheet.table.to_csv) end end end
true
fa7ae59e408f15e5cedb119b73531b21f0c65690
Ruby
sgvincentho/introrubycourse
/more_exercises_6.rb
UTF-8
244
3.953125
4
[]
no_license
# more_exercises_6.rb arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Append arr.push(11) #puts arr # prepend arr.unshift(0) #puts arr #------------------------ #Get rid of 11 arr.pop #puts arr # Append 3 arr << 3 #puts arr puts arr.uniq
true
e4ce2a9916aecd3842fd24730565a2de435eb38f
Ruby
picatz/slipstream
/lib/slipstream.rb
UTF-8
1,246
2.890625
3
[ "MIT" ]
permissive
require 'securerandom' require 'slipstream/version' module Slipstream def self.create(**options) Stream.new(options) end class Stream attr_accessor :buffer_size attr_accessor :clean def initialize(**options) if options[:id].nil? @id = SecureRandom.uuid else @id = options[:id] end if options[:buffer_size].nil? @buffer_size = 1 else @buffer_size = options[:buffer_size] end @clean = true if options[:clean] @reader, @writer = IO.pipe end def read(clean: clean?) buffer = "" buffer << @reader.read_nonblock(@buffer_size) while buffer[-1] != "\n" if @clean return buffer.strip else return buffer end rescue IO::EAGAINWaitReadable return nil rescue IOError return false end def id @id end def write(mesg) @writer.puts mesg return true rescue IOError return false end def clean! @clean = true end def clean? return true if @clean false end def unclean! @clean = false end def close! @writer.close @reader.close return true end end end
true
349c76bd474f5eaec5807636051515cf0bbd1cc7
Ruby
RedHatInsights/sources-api
/lib/go_encryption.rb
UTF-8
610
2.5625
3
[ "Apache-2.0" ]
permissive
class GoEncryption def self.encrypt(pass) # clowder can throw error messages - so we filter them out %x[sources-encrypt-compat -encrypt #{pass} | grep -v Clowder].strip.tap do |str| raise "error encrypting string: #{str}" if $?.to_i != 0 raise "bad encryption!" if str.blank? end end def self.decrypt(pass) # clowder can throw error messages - so we filter them out %x[sources-encrypt-compat -decrypt #{pass} | grep -v Clowder].strip.tap do |str| raise "error encrypting string: #{str}" if $?.to_i != 0 raise "bad encryption!" if str.blank? end end end
true
87265d3dfe7c552b1aa71be6995b66538dccaa44
Ruby
eggmantv/ruby_advanced
/04/03_block.rb
UTF-8
200
4.09375
4
[]
no_license
# yield with parameter def hello name puts 'hello method start' result = "hello " + name yield(result) puts 'hello method end' end hello('world') { |x| puts "i am in block, i got #{x}" }
true
803eecf3152c62beccea30d80da81f219fa1ad31
Ruby
jackychen6825/AA_Classwork
/W4/D2/Chess/piece.rb
UTF-8
516
3.421875
3
[]
no_license
class Piece attr_reader :color, :board, :pos def initialize(color, board, pos) @color = color @board = board @pos = pos end def valid_moves v_moves = [] (0...8).each do |row| (0...8).each do |col| pos = [row, col] # if board[pos].color != color || board[pos].empty? if board[pos].nil? || board[pos].color != color v_moves << pos end end end v_moves end def empty? false end def inspect color end end
true
16843d2df8c64b0ff4346b7142797e55740eeb6f
Ruby
celsian/BEWDiful_Students
/05_Classes_Objects/exercises/coa_05_classes.rb
UTF-8
1,242
4.40625
4
[]
no_license
#Class 5 Code Along jimmy = {} jimmy[:name] = "Jimmy Mcbordermier" jimmy[:major] = "Math" jimmy[:course] = "Dr. Dre" jimmy[:grade] = "C" robert = {} robert[:name] = "Robert Ross" robert[:major] = "CS" robert[:course] = "Objects" robert[:grade] = "A" def grade_status(student) if student[:grade] == "F" "failed" elsif student[:grade] <= "D" "passed" end end puts grade_status(jimmy) #Need to make our own object so we can run methods on it. object.passing? (ret t/f) #Solution? Class & Objects (obviously) class Student attr_accessor :name, :major, :course, :grade #This is a class method # def passing? # if grade == "F" # false # else # true # end # end def passing_status "#{name} is studying #{major} and he #{pass? ? "is" : "is not"} passing and #{cheater? ? "is" : "is not"} a cheater." end def cheater? if name == "Jeff" true else false end end end class Grade attr_accessor :grade def pass? if grade == "F" false else true end end end #Robert is the object. robert = Student.new robert.name = "Robert" robert.major = "CS" robert.course = "Robotics" robert.grade = Grade.new robert.grade.grade = "A" puts robert.cheater? puts robert.grade.pass? #Fix this # puts robert.passing_status
true
6dc5225b68922fc1a08d7656245bd82976f6e861
Ruby
jenkliu/j-cart
/app/models/product.rb
UTF-8
340
2.75
3
[]
no_license
class Product < ActiveRecord::Base has_many :items validates_presence_of :name, :price, :qty_in_stock attr_accessible :brand, :info, :name, :price, :qty_in_stock, :items # check if product has at least [qty] in stock def has_in_stock(qty) if self.qty_in_stock >= qty return true else return false end end end
true
c3ce3972bb3e69db546e1c7c1ffc60864b22250d
Ruby
nilfs/workflow_engine_study
/src/file_target.rb
UTF-8
159
2.734375
3
[]
no_license
require_relative 'target' class FileTarget < Target attr_reader :path def initialize(path) @path = path end def exist? File.exist?(path) end end
true
b95bfe9341cc31ee7aa800f61d847c222ee426f3
Ruby
kozinvl/RacingCars
/spec/position_spec.rb
UTF-8
502
3
3
[]
no_license
require 'rspec' require_relative '../position' describe Position do before :each do @position = Position.new(10, 1) end it 'should be equal x var in initialize' do expect(@position.x).to eq 10 end it 'should be equal y var in initialize' do expect(@position.y).to eq 1 end it 'should be instance of class' do expect(@position).to be_an_instance_of Position end it 'should not be equal instances' do expect(@position).not_to eq Position.new 10, 10 end end
true
0fc5d4c12958c1010f09490ced39b3cae3334778
Ruby
rosiljunior1588/exemplo_mobile
/features/elements/exemplo_elements.rb
UTF-8
571
2.59375
3
[]
no_license
## Módulo configurado para mapear todos os elementos da tela, cada tela deve se criar uma classe screen e elements. ## O Exemplo de utilizar elements deve ser aplicado quando o aplicativo é hibrido, ou seja, o mapeamento de elementos será da mesma forma tanto para iOS como para Android. module Elementos_Tela_Exemplo def elementos_tela_exemplo { tela_login: 'id_tela_login', login: 'id_login', senha: 'id_senha', texto_mensagem: 'id_mensagem', botao_y: 'id_botao_y' } end end
true
0cad1e4eb2588a1ed69348836c3164660b21c954
Ruby
DianaLuciaRinconBl/Ruby-book-exercises
/ruby_basic_ex/input/lsprint2.rb
UTF-8
1,466
4.28125
4
[]
no_license
# Modify this program so it repeats itself after each input/print iteration, # asking for a new number each time through. The program should keep running # until the user enters q or Q. number = nil loop do puts "How many output lines do you want? Enter a number greater than 3 " number = gets.chomp.downcase break if number == "q" if number.to_i >=3 number.to_i.times do puts "Launch School is the best!" end else puts "Invalid number, please try again!" end end # LaunchSchool solution: # # loop do # input_string = nil # number_of_lines = nil # # loop do # puts '>> How many output lines do you want? ' \ # 'Enter a number >= 3 (Q to Quit):' # # input_string = gets.chomp.downcase # break if input_string == 'q' # # number_of_lines = input_string.to_i # break if number_of_lines >= 3 # # puts ">> That's not enough lines." # end # # break if input_string == 'q' =>Our inner loop is followed by a second break #if input_string == 'q' to break out of the outer loop # if the user quit. This is necessary since a break # inside a loop always exits the innermost containing # loop, so the break in the inner loop can't exit the outer loop. # # while number_of_lines > 0 # puts 'Launch School is the best!' # number_of_lines -= 1 # end end
true
4a8b478c24dabb4b4f869ff63f1e2db4795900b1
Ruby
343334/pokemon-webhook
/lib/plugin-twitter.rb
UTF-8
2,199
2.6875
3
[]
no_license
require 'twitter' class Notifier class Twitter def initialize begin @client = ::Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] config.access_token = ENV['TWITTER_ACCESS_TOKEN'] config.access_token_secret = ENV['TWITTER_ACCESS_SECRET'] end @delayqueue = {} Thread.new do loop do begin if @delayqueue.length > 0 @delayqueue.keys.each do |key| if key < Time.now.to_i self.send_delayed(@delayqueue[key]['message'],@delayqueue[key]['options']) @delayqueue.delete key end end end sleep 0.01 rescue => e puts "Error running Twitter Delay Thread" puts e.inspect puts e.backtrace end end end puts '[Notifier::Twitter] Loaded Twitter Notifier' rescue => e puts '[Notifier::Twitter] Error loading Twitter Notifier!' puts e.inspect puts e.backtrace end end def send(message='No Message Specified',options={}) source = options['source'] if @delayqueue.length < 25 @delayqueue[options['disappear']-900] = { 'message' => message, 'options' => options } puts "[#{source.upcase}][Notifier::Twitter] Queued Message for #{options['disappear']-900} - Current Time: #{Time.now.to_i}" else puts "[Notifier::Twitter] Queue Full - Ignoring notifications until queue frees up" end end def send_delayed(message='No Message Specified',options={}) source = options['source'] city = options['attachments']['mapcity'] begin @client.update("#{city}: #{message} - #{options['attachments']['mapurl']}") puts "[#{source.upcase}][Notifier::Twitter] Message Sent" rescue => e puts e.inspect puts e.backtrace puts "[#{source.upcase}][Notifier::Twitter] Error sending message to Twitter Bot" end end def is_notifier? return true end end end
true
1efc8de88affb32c5e4e648ae31bbb5993d75fb9
Ruby
eeichinger/cuke4duke-junit
/junit-runner-jruby/src/main/resources-jruby/META-INF/jruby.gem.home/gems/gherkin-2.4.0-java/lib/gherkin/formatter/json_formatter.rb
UTF-8
2,149
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'json' require 'gherkin/formatter/model' require 'gherkin/native' require 'base64' module Gherkin module Formatter class JSONFormatter native_impl('gherkin') include Base64 attr_reader :gherkin_object # Creates a new instance that writes the resulting JSON to +io+. # If +io+ is nil, the JSON will not be written, but instead a Ruby # object can be retrieved with #gherkin_object def initialize(io) @io = io end def uri(uri) # We're ignoring the uri - we don't want it as part of the JSON # (The pretty formatter uses it just for visual niceness - comments) end def feature(feature) @gherkin_object = feature.to_hash end def steps(steps) end def background(background) feature_elements << background.to_hash end def scenario(scenario) feature_elements << scenario.to_hash end def scenario_outline(scenario_outline) feature_elements << scenario_outline.to_hash end def examples(examples) all_examples << examples.to_hash end def step(step) current_steps << step.to_hash end def match(match) last_step['match'] = match.to_hash end def result(result) last_step['result'] = result.to_hash end def embedding(mime_type, data) embeddings << {'mime_type' => mime_type, 'data' => encode64s(data)} end def eof @io.write(@gherkin_object.to_json) if @io end private def feature_elements @gherkin_object['elements'] ||= [] end def feature_element feature_elements[-1] end def all_examples feature_element['examples'] ||= [] end def current_steps feature_element['steps'] ||= [] end def last_step current_steps[-1] end def embeddings last_step['embeddings'] ||= [] end def encode64s(data) # Strip newlines Base64.encode64(data).gsub(/\n/, '') end end end end
true
104fea99b0886e23aad7896da4d1b7203b120ffa
Ruby
ruby-processing/The-Nature-of-Code-for-JRubyArt
/chp05_physicslibraries/toxiclibs/simple_cluster/node.rb
UTF-8
756
2.953125
3
[ "MIT" ]
permissive
# The Nature of Code # <http://www.shiffman.net/teaching/nature> # Spring 2010 # Toxiclibs example: http://toxiclibs.org/ # Force directed graph # Heavily based on: http://code.google.com/p/fidgen/ # Notice how we are using inheritance here! # We could have just stored a reference to a VerletParticle object # inside the Node class, but inheritance is a nice alternative class Node < Physics::VerletParticle2D extend Forwardable def_delegators(:@app, :fill, :stroke, :stroke_weight, :ellipse) def initialize(app:, location:) super(location) @app = app end # All we're doing really is adding a :display function to a VerletParticle def display fill(0, 150) stroke(0) stroke_weight(2) ellipse(x, y, 16, 16) end end
true
a083d951341812e2d73ce07477258d295a198294
Ruby
kaleforsale/using_httpwatch
/sitespider.rb
UTF-8
4,732
2.515625
3
[]
no_license
require 'win32ole' # used to drive HttpWatch require 'watir' # the WATIR framework require 'yaml' class Sitespider attr_accessor :url, :totalTime, :receivedBytes, :compressionSavings, :roundTrips, :numberErrors def initialize(url) @url=url puts @url if @url.empty? exit end end def start_test # Create HttpWatch control = WIN32OLE.new('HttpWatch.Controller') httpWatchVer = control.Version if httpWatchVer[0...1] == "4" or httpWatchVer[0...1] == "5" puts "\nERROR: You are running HttpWatch #{httpWatchVer}. This sample requires HttpWatch 6.0 or later. Press Enter to exit..."; $stdout.flush gets end #end of if statement # Use WATIR to start IE ie = Watir::Browser.new :ie #ie.logger.level = Logger::ERROR # Attach HttpWatch to IE plugin = control.ie.Attach(ie.ie) # Start Recording HTTP traffic plugin.Clear() plugin.Log.EnableFilter(false) plugin.Record() # go to the site ie.goto(@url) #stop recording http data in HttpWatch plugin.Stop() #display summary statistics summary = plugin.Log.Entries.Summary @totalTime = summary.Time @receivedBytes = summary.BytesReceived @compressionSavings = summary.CompressionSavedBytes @roundTrips = summary.RoundTrips @numberErrors = summary.Errors.Count #close down ie plugin.Container.Quit() end ######################## def create_graph(file_name) currentTime = Time.now monthDayYear = currentTime.strftime("%b-%d-%Y") hourMinute = currentTime.strftime("%I:%M%p") dateTimes = [] if File.exists?("#{file_name}.times.yaml") dateTimes = YAML.load_file("#{file_name}.times.yaml") end File.open("#{file_name}.times.yaml", 'w') do |out| dateTimes << hourMinute YAML.dump dateTimes, out end responses = [] if File.exists?("#{file_name}.responsetimes.yaml") responses = YAML.load_file("#{file_name}.responsetimes.yaml") end File.open("#{file_name}.responsetimes.yaml", 'w') do |out| responses << @totalTime YAML.dump responses, out end categoryString = "categories:[" dateTimes.each do |testTime| categoryString= categoryString + "'#{testTime}'," end categoryString = categoryString + "]" puts categoryString responseTimes = "data: [" responses.each do |response| responseTimes = responseTimes + "#{response}," end responseTimes = responseTimes + "]" puts responseTimes #categoryString = "categories: ['', '10:10pm', '10:10pm', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] #data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] #only works for paid software #printf "Time for dns lookups: %d\n", timingsummary.DNSLookup $ #create html using jquery highcharts library newfile = File.new("#{file_name}.browsing.html", 'w') newfile.puts("<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script>") newfile.puts("<script src=\"http://code.highcharts.com/highcharts.js\"></script>") newfile.puts("<div id=\"container\"></div>") newfile.puts("<script>$(function () { $('#container').highcharts({ title: { text: 'HTTP Synthetic Transactions for #{@url}'}, chart: { }, yAxis:{ title: {text: 'Seconds'}, gridLineWidth: 1, labels:{ formatter: function() { return this.value + ' sec'; } }, }, xAxis: { title: {text: 'Time'}, #{categoryString} }, series: [{ name: '#{@url}', #{responseTimes} }] }); });</script>" ); newfile.close =begin puts "Current Month: #{monthDayYear}" puts "Current Time: #{hourMinute}" printf "Total time to load page (secs): %.3f\n", visit_site.totalTime printf "Number of bytes received on network: %d\n", visit_site.receivedBytes printf "HTTP compression saving (bytes): %d\n", visit_site.compressionSavings printf "Number of round trips: %d\n", visit_site.roundTrips printf "Number of errors: %d\n", visit_site.numberErrors =end end end
true
223967ed20db5ccc0f49a7593425e2e4089b35ae
Ruby
cris07/ruby
/intermedio/proc.rb
UTF-8
504
3.828125
4
[]
no_license
#Clase Proc sumar = Proc.new {|x,y| puts "La suma es #{x+y}"} restar = Proc.new do |x,y| puts "La resta es #{x-y}" end multiplicar = Proc.new {|x,y|puts "#{x*y}"} def calcu x,y,proc puts "Hagamos una operacion matemática con procs" proc.call x,y end calcu 1,2, sumar calcu 1,2, restar def metodo x,y,proc1, proc2, proc3=0 puts "OPeraciones matematicas" proc1.call x,y proc2.call x,y if(proc3 != 0) proc3.call x,y end end metodo 5,6,sumar,multiplicar, restar
true
378b6b6eab3595dc699f222bc36cb544e0d49922
Ruby
analisistem/mongoid_nested_set
/spec/matchers/nestedset_pos.rb
UTF-8
1,120
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Mongoid::Acts::NestedSet module Matchers def have_nestedset_pos(lft, rgt, options = {}) NestedSetPosition.new(lft, rgt, options) end class NestedSetPosition def initialize(lft, rgt, options) @lft = lft @rgt = rgt @options = options end def matches?(node) @node = node !!( node.respond_to?('left') && node.respond_to?('right') && node.left == @lft && node.right == @rgt ) end def description "have position {left: #{@lft}, right: #{@rgt}}" end def failure_message_for_should sprintf("expected nested set position: {left: %2s, right: %2s}\n" + " got: {left: %2s, right: %2s}", @lft, @rgt, @node.respond_to?('left') ? @node.left : '?', @node.respond_to?('right') ? @node.right : '?' ) end def failure_message_for_should_not sprintf("expected nested set to not have position: {left: %2s, right: %2s}", @lft, @rgt) end end end end
true
87f5469ade0337ab4c8d9faaaa0c065464903cff
Ruby
morganp/verilog
/lib/verilog/file_list.rb
UTF-8
2,568
3.09375
3
[]
no_license
module Verilog class FileList attr_reader :files ## Expected usage # Use FileList to create an array of files included in design # FileList is then used to create a Path, which loads the files into memory # FileList and Path are separated in case you want a file list with out actually having to open the files def initialize( a_filelist='' ) @files = [] unless ( a_filelist == '') parse_list!( a_filelist ) end end ## Unsure of the name for this # open : it does open the file but not like other open calls # load : opens file and loads content, load! does not imply what it modifies # parse_list is descriptive but not what it modifies def parse_list( filelist ) temp_files = [] ## Splat (*) filelist into Array if single string [*filelist].each do |item| abort( "FileList parse_list item not found : #{item}") unless ::File.exist?( item ) ::IO.readlines( item ).each do |line| ## Remove // or # comments line = strip_comments( line ) ## Expand Environment variables in strings line = expand_envvars( line ) ## -incdir, include the entire contents of listed directory if line.match(/^\s*-incdir\s+(\S+)\s*/) temp_files << incdir($1) ## Recurse on -f (file.f including other files.f) elsif line.match(/^\s*-f\s+(\S+)\s*/) temp_files << parse_list($1) ## Ignore Whitespace elsif line.match(/^\s$/) next ## Append file list line to list of files else temp_files << line.strip end end end ## Recursion embeds arrays, return flat file list return temp_files.flatten end def parse_list!( filelist ) files.push( *parse_list( filelist ) ) end def to_path new_path = Path.new self.files.each do |f| new_path.load_file( f ) end return new_path end private def incdir( in_string ) ## returns array of files and links inc_list = [] Dir.glob( ::File.join(in_string, '*') ).select do |item| if ::File.file?( item ) or ::File.symlink?( item ) inc_list << item end end return inc_list end def expand_envvars( in_string ) return in_string.gsub(/\$(\w+)/) { ENV[$1] } end def strip_comments( in_string ) return in_string.gsub(/(\/\/|#).*$/, '') end end end
true
f1442d06cd6efb76eb5106b8133c91163200d964
Ruby
natikgadzhi/requalations
/spec/requalations/vector/vector_spec.rb
UTF-8
2,786
3.296875
3
[ "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') # # Specifying additional methods in the Vector class # describe Vector do # Before each spec sentence before(:each) do # create a vector @vector = Vector.elements( [4,10,29,2,5,1] ) @column_vector = Vector.elements( [ [1], [2], [29], [5], [10] ]) @column_for_abs = Vector.elements( [ [1], [-9], [8] ]) end ## Class methods describe "class methods" do # #blank # A method to create an empty vector (elements == zeros ) # Usage: # Vector.blank(4) => Vector with 4 zeroes as elements # it "should have #blank method on class" do Vector.should respond_to(:blank) Vector.blank(4).to_a.should == [0,0,0,0] end it "should have #range method to build from range!" do Vector.should respond_to(:range) Vector.range(0...5).to_a.should == [0,1,2,3,4] end end ## Instance methods ## MAX and MIN values in vector describe "Max and min methods and friends" do # Some specs are related to new #max, #min, #max_index, #min_index methods # It should have #max! it "should have #max method" do @vector.max.should == 29.0 end it "should have #min method" do @vector.min.should == 1.0 end it "should get max_index properly" do @vector.max_index.should == 2 end it "should get min_index properly" do @vector.min_index.should == 5 end it "should find max in column_vector" do @column_vector.max.should == 29 end it "should get max_index in column_vector" do @column_vector.max_index.should == 2 end # After some time i've created max_value_and_index methods, they work just the same way. it "should get max_value_and_index correctly" do value, index = @column_vector.max_value_and_index value.should == 29.0 index.should == 2 end it "should get absolute_max element correctly" do value, index = @column_for_abs.absolute_max_value_and_index value.should == 9.0 index.should == 1 end end ## Slices describe "Slices" do # Slicing vector returns a vector. it "should be able to slice vector" do @column_vector.slice(2..5).should == Vector.elements([ [29], [5], [10] ]) end # Note, that searching for max element in the slice returns it's index in the slice! # not in the original vector! it "another slice example" do @left_side_matrix = Matrix.rows([ [ 7, 8, 4, -6], [ -1, 6, -2, -6], [ 2, 9, 6, -4], [ 5, 9, 1, 1] ]) v,i = @left_side_matrix.column(2).slice(2..3).absolute_max_value_and_index v.should == 6 i.should == 0 end end end
true
0582840bc83d8c8578684fde9877e36043469262
Ruby
marksterr/aA-classwork
/week_6/day_1/rails1-practice/sql/spec/test_spec.rb
UTF-8
7,197
2.515625
3
[]
no_license
require 'rspec' require 'test' describe "SQL" do describe "gold_cat_toys" do it "finds all the toys that are `Gold` in color and have more than one word in the name" do expect(gold_cat_toys).to eq([["Bone Club"], ["Bubble Beam"], ["Chicken Milanese"], ["Chicken Wings"], ["Chilli con Carne"], ["Defense Curl"], ["Ebiten maki"], ["Ebiten maki"], ["Expecto Patronum"], ["Fettuccine Alfredo"], ["Fire Punch"], ["French Toast"], ["Fury Attack"], ["Ice Beam"], ["Ice Punch"], ["Jump Kick"], ["Leech Seed"], ["Leech Seed"], ["Low Kick"], ["Massaman Curry"], ["Pappardelle alla Bolognese"], ["Pasta Carbonara"], ["Pork Sausage Roll"], ["Quick Attack"], ["Risotto with Seafood"], ["Rolling Kick"], ["Scotch Eggs"], ["Seafood Paella"], ["Shadow Isles"], ["Solar Beam"], ["Solar Beam"], ["Solar Beam"], ["Som Tam"], ["Som Tam"], ["Stormraiders Surge"], ["Tuna Sashimi"], ["Vegetable Soup"], ["Vegetable Soup"]]) end end describe "extra_jet_toys" do it "shows which toys `Jet` has that have the same name and how many" do expect(extra_jet_toys).to eq([["Chicken Milanese", "3"], ["Kebab", "4"], ["Massaman Curry", "2"], ["Odio", "2"], ["Peking Duck", "2"], ["Quibusdam", "2"], ["Rerum", "2"], ["Tempora", "2"], ["Tiramisù", "6"]]) end end describe "cats_with_a_lot" do it "finds the names of all cats with more than seven toys" do expect(cats_with_a_lot).to eq([["Beatrice"], ["Calvin"], ["Chad"], ["Edmundo"], ["Forrest"], ["Freyja"], ["Garth"], ["Glendora"], ["Horace"], ["Jess"], ["Jet"], ["Junie"], ["Kiersten"], ["Latanya"], ["Lou"], ["Man"], ["Marcos"], ["Merissa"], ["Millicent"], ["Morgan"], ["Olevia"], ["Oralee"], ["Ozzie"], ["Pedro"], ["Peg"], ["Rene"], ["Roberto"], ["Shelton"], ["Shon"], ["Theo"], ["Valentin"], ["Vinita"]]) end end describe "just_like_orange" do it "lists all the cats of `Orange`'s breed excluding `Orange` the cat" do expect(just_like_orange).to eq([ ["Abdul", "Brazilian Shorthair"], ["Ai", "Brazilian Shorthair"], ["Aida", "Brazilian Shorthair"], ["Alejandra", "Brazilian Shorthair"], ["Allen", "Brazilian Shorthair"], ["Alvin", "Brazilian Shorthair"], ["Andrea", "Brazilian Shorthair"], ["Angie", "Brazilian Shorthair"], ["Anna", "Brazilian Shorthair"], ["Aracely", "Brazilian Shorthair"], ["Arden", "Brazilian Shorthair"], ["Arlinda", "Brazilian Shorthair"], ["Arron", "Brazilian Shorthair"], ["Arthur", "Brazilian Shorthair"], ["Ayana", "Brazilian Shorthair"], ["Beaulah", "Brazilian Shorthair"], ["Bobette", "Brazilian Shorthair"], ["Bonita", "Brazilian Shorthair"], ["Brianna", "Brazilian Shorthair"], ["Bud", "Brazilian Shorthair"], ["Candy", "Brazilian Shorthair"], ["Cary", "Brazilian Shorthair"], ["Chantel", "Brazilian Shorthair"], ["Charles", "Brazilian Shorthair"], ["Cheri", "Brazilian Shorthair"], ["Cherie", "Brazilian Shorthair"], ["Chuck", "Brazilian Shorthair"], ["Coleen", "Brazilian Shorthair"], ["Cori", "Brazilian Shorthair"], ["Cruz", "Brazilian Shorthair"], ["Dallas", "Brazilian Shorthair"], ["Damian", "Brazilian Shorthair"], ["Damon", "Brazilian Shorthair"], ["Daysi", "Brazilian Shorthair"], ["Deena", "Brazilian Shorthair"], ["Denyse", "Brazilian Shorthair"], ["Dominick", "Brazilian Shorthair"], ["Donnie", "Brazilian Shorthair"], ["Donny", "Brazilian Shorthair"], ["Ed", "Brazilian Shorthair"], ["Edgar", "Brazilian Shorthair"], ["Edith", "Brazilian Shorthair"], ["Edmundo", "Brazilian Shorthair"], ["Elia", "Brazilian Shorthair"], ["Elijah", "Brazilian Shorthair"], ["Estrella", "Brazilian Shorthair"], ["Ethan", "Brazilian Shorthair"], ["Freeman", "Brazilian Shorthair"], ["Giuseppe", "Brazilian Shorthair"], ["Glenda", "Brazilian Shorthair"], ["Harry", "Brazilian Shorthair"], ["Hilde", "Brazilian Shorthair"], ["Hollie", "Brazilian Shorthair"], ["Hosea", "Brazilian Shorthair"], ["Idell", "Brazilian Shorthair"], ["In", "Brazilian Shorthair"], ["Ione", "Brazilian Shorthair"], ["Jani", "Brazilian Shorthair"], ["Jannet", "Brazilian Shorthair"], ["Jerome", "Brazilian Shorthair"], ["Jesus", "Brazilian Shorthair"], ["Josef", "Brazilian Shorthair"], ["Katlyn", "Brazilian Shorthair"], ["Kendall", "Brazilian Shorthair"], ["Kenia", "Brazilian Shorthair"], ["Khadijah", "Brazilian Shorthair"], ["Kimbery", "Brazilian Shorthair"], ["Kum", "Brazilian Shorthair"], ["Laurena", "Brazilian Shorthair"], ["Leisa", "Brazilian Shorthair"], ["Lincoln", "Brazilian Shorthair"], ["Liz", "Brazilian Shorthair"], ["Lore", "Brazilian Shorthair"], ["Luann", "Brazilian Shorthair"], ["Lucas", "Brazilian Shorthair"], ["Luciano", "Brazilian Shorthair"], ["Lucretia", "Brazilian Shorthair"], ["Lyle", "Brazilian Shorthair"], ["Lyndsey", "Brazilian Shorthair"], ["Magaret", "Brazilian Shorthair"], ["Man", "Brazilian Shorthair"], ["Martina", "Brazilian Shorthair"], ["Meredith", "Brazilian Shorthair"], ["Min", "Brazilian Shorthair"], ["Myles", "Brazilian Shorthair"], ["Napoleon", "Brazilian Shorthair"], ["Nelly", "Brazilian Shorthair"], ["Norman", "Brazilian Shorthair"], ["Pauline", "Brazilian Shorthair"], ["Randee", "Brazilian Shorthair"], ["Regina", "Brazilian Shorthair"], ["Reita", "Brazilian Shorthair"], ["Rick", "Brazilian Shorthair"], ["Robin", "Brazilian Shorthair"], ["Rochelle", "Brazilian Shorthair"], ["Roger", "Brazilian Shorthair"], ["Russell", "Brazilian Shorthair"], ["Serina", "Brazilian Shorthair"], ["Seymour", "Brazilian Shorthair"], ["Sharita", "Brazilian Shorthair"], ["Soledad", "Brazilian Shorthair"], ["Sona", "Brazilian Shorthair"], ["Sung", "Brazilian Shorthair"], ["Sydney", "Brazilian Shorthair"], ["Teresa", "Brazilian Shorthair"], ["Trisha", "Brazilian Shorthair"], ["Ty", "Brazilian Shorthair"], ["Wendell", "Brazilian Shorthair"], ["Wendy", "Brazilian Shorthair"], ["Willis", "Brazilian Shorthair"], ["Winfred", "Brazilian Shorthair"], ["Zula", "Brazilian Shorthair"] ]) end end describe "expensive_tastes" do it "finds the name of the most expensive toy `Tiger` and the owners of that toy" do expect(expensive_tastes).to eq([["Beatrice", "Tiger", "Orchid"], ["Charles", "Tiger", "Orchid"], ["Elizabeth", "Tiger", "Orchid"], ["Erich", "Tiger", "Orchid"], ["Florene", "Tiger", "Orchid"], ["Josef", "Tiger", "Orchid"], ["Julissa", "Tiger", "Orchid"], ["Melissa", "Tiger", "Orchid"]]) end end end
true
74f9925125aa1b747c70a2e6582223ea353a19fc
Ruby
jdan/adventofcode
/2015/rb/2015/13b-knights-table.rb
UTF-8
1,022
3.6875
4
[]
no_license
# http://adventofcode.com/day/13 seating = {} people = [] ARGF.each do |line| re = /(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+)/ match = line.match(re) a = match[1] b = match[4] # Track the different people people << a sign = match[2] == "gain" ? 1 : -1 points = sign * match[3].to_i # Store the points seating["#{a},#{b}"] = points # Everyone is apathetic to sit next to you seating["#{a},Jordan"] = 0 seating["Jordan,#{a}"] = 0 end # Add yourself to the mix people << "Jordan" puts people.uniq.permutation.map { |group| # Add the first and second person to the end so we can "cycle" groups of # three with each_cons group << group[0] << group[1] total = 0 group.each_cons(3) do |trio| # Points looking left total += seating["#{trio[1]},#{trio[0]}"] # Points looking right total += seating["#{trio[1]},#{trio[2]}"] end total }.max
true
1b29466431a9f7638062f2a5478ad600ff7d0a0a
Ruby
otikev/msajili
/app/models/report.rb
UTF-8
2,147
2.734375
3
[ "MIT" ]
permissive
class Report attr_accessor :company, :job, :total_jobs, :open_jobs, :closed_jobs, :applications, :procedures_array, :start_date, :end_date def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def fetch(job) if job self.job=job else totaljobs = Job.where('DATE(created_at) >= ? and DATE(created_at) <= ?',start_date,end_date) self.total_jobs = totaljobs.count openjobs = totaljobs.where(:status => Job.status_open) self.open_jobs = openjobs.count closedjobs = totaljobs.where(:status => Job.status_closed) self.closed_jobs = closedjobs.count end self.applications = get_applications(job,start_date,end_date) self.procedures_array = get_stages(job,start_date,end_date) end def get_stages(job,start_date,end_date) procedures = Procedure.get_procedures(self.company.id) procedures_array = [] procedures.each do |p| stages_array = [] p.stages.each do |s| stages_hash = Hash.new stages_hash[:procedure] = p.title stages_hash[:name] = s.title stages_hash[:dropped] = s.get_dropped_applications.count stages_array.push(stages_hash) end procedures_array.push(stages_array) end procedures_array end def get_procedure(i) json_data = ActiveSupport::JSON.encode(self.procedures_array[i]) json_data end def get_applications(job,start_date,end_date) if job appls = job.get_completed_applications else appls = Application.joins(:job).where('DATE(applications.created_at) >= ? and DATE(applications.created_at) <= ? and applications.status = ? and jobs.company_id = ?',start_date,end_date,Application.status_complete,self.company.id) end i=0 data = [] start_date.upto(end_date) { |date| value = appls.where('DATE(applications.created_at) = ?', date).count point = Hash.new point[:period] = date point[:value] = value data.push(point) i+=1 } json_data = ActiveSupport::JSON.encode(data) json_data end def persisted? false end end
true
82ab041780aa03fc2f99b4e9ce907f0f834df1b5
Ruby
jmheyd/sinatra-dynamic-routes-lab-v-000
/app.rb
UTF-8
1,415
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'config/environment' class App < Sinatra::Base #dynamic route to accept name and render name backwards get '/reversename/:name' do params[:name].reverse end #dynmaic route to accept number and render square of that number get '/square/:number' do @number = params[:number].to_i square = @number * @number square.to_s end #dynamic route accepts a number and a phrase and returns that phrase #in a string the number of times given. get '/say/:number/:phrase' do @number = params[:number].to_i "#{params[:phrase]}\n" * @number end #dynamic route that accepts five words and returns a string with the #formatted as a sentence. get '/say/:word1/:word2/:word3/:word4/:word5' do "#{params[:word1]} #{params[:word2]} #{params[:word3]} #{params[:word4]} #{params[:word5]}." end #Create a dynamic route that accepts an operation (add, subtract, multiply or divide) #and performs the operation on the two numbers provided. #For example, going to /add/1/2 should render 3. get '/:operation/:number1/:number2' do num1 = params[:number1].to_i num2 = params[:number2].to_i operation = params[:operation] if operation == "add" answer = num1 + num2 elsif operation == "subtract" answer = num1 - num2 elsif operation == "multiply" answer = num1 * num2 elsif operation == "divide" answer = num1/num2 else "What??" end answer.to_s end end
true
54f8c9d8659e26f5253b55f7c403471fd1651721
Ruby
jstrait/beats
/lib/beats/beats_runner.rb
UTF-8
2,525
2.96875
3
[ "MIT" ]
permissive
module Beats class BeatsRunner # Each pattern in the song will be split up into sub patterns that have at most this many steps. # In general, audio for several shorter patterns can be generated more quickly than for one long # pattern, and can also be cached more effectively. OPTIMIZED_PATTERN_LENGTH = 4 def initialize(input_file_name, output_file_name, options) @input_file_name = input_file_name if output_file_name.nil? output_file_name = File.basename(input_file_name, File.extname(input_file_name)) + ".wav" end @output_file_name = output_file_name @options = options end def run base_path = @options[:base_path] || File.dirname(@input_file_name) song, kit = SongParser.parse(base_path, File.read(@input_file_name)) song = normalize_for_pattern_option(song) songs_to_generate = normalize_for_split_option(song) song_optimizer = SongOptimizer.new durations = songs_to_generate.collect do |output_file_name, song_to_generate| optimized_song = song_optimizer.optimize(song_to_generate, OPTIMIZED_PATTERN_LENGTH) AudioEngine.new(optimized_song, kit).write_to_file(output_file_name) end {duration: durations.last} end private # If the -p option is used, transform the song into one whose flow consists of # playing that single pattern once. def normalize_for_pattern_option(song) unless @options[:pattern].nil? pattern_name = @options[:pattern].downcase.to_sym unless song.patterns.has_key?(pattern_name) raise StandardError, "The song does not include a pattern called #{pattern_name}" end song.flow = [pattern_name] song.remove_unused_patterns end song end # Returns a hash of file name => song object for each song that should go through the audio engine def normalize_for_split_option(song) songs_to_generate = {} if @options[:split] split_songs = song.split split_songs.each do |track_name, split_song| extension = File.extname(@output_file_name) file_name = File.dirname(@output_file_name) + "/" + File.basename(@output_file_name, extension) + "-" + File.basename(track_name, extension) + extension songs_to_generate[file_name] = split_song end else songs_to_generate[@output_file_name] = song end songs_to_generate end end end
true
1e833c67c3586f09529db0c827765c92efa3ef4c
Ruby
VitalyDorozhkin/Ruby
/chest/chest.rb
UTF-8
1,656
3.5625
4
[]
no_license
board = [[],[],[],[],[],[],[],[]] class Game attr_accessor :max_time attr_accessor :time def start puts "start" end def finish puts "finish" end def info puts "variables: max_time, time" puts "methods: start(start the game), finish(end the game)" end end class Piece attr_accessor :color attr_accessor :type def initialize(color, type, column, row) @color = color @type = type @column = column @row = row end def move(column, row) #checking @column = column @row = row end def info puts "variables: color, type, column, row" puts "methods: move(moving to the new cell if it possible)" end end class Player @ready_state = false attr_accessor :first_name attr_accessor :last_name attr_accessor :age attr_accessor :rang attr_accessor :points attr_accessor :high_score @pieces = [] def initialize(first_name, last_name, age) @first_name = first_name @last_name = last_name @age = age @rang = "Baby Eagle" @points = 0 @high_score = 0 end def greeting puts "Hi, my name is #{@first_name + " " + @last_name}, I'm #{@age} years old and I'm #{@rang} in chest!" end def ready_to_start @ready_state = true puts "Сообщает на сервер (и/или другим игрокам) о том, что игрок готов начинать игру, как только появится соперник" end def info puts "variables: first_name, last_name, age, rang, points, high_score, pieces[](array with pieces" puts "methods: greeteng, ready_to_start(send ready signal to the server" end end
true
8ea3e4a70854eed8112fd94fbc8a44d5b460683f
Ruby
Hansen-Nick/Intro-to-Programming
/basics/exercise_3.rb
UTF-8
299
3.015625
3
[]
no_license
movies = { Casablanca: 1942, :"The Godfather" => 1972, :"Citizen Kane" => 1941, :"Pulp Fiction" => 1994, Goodfellas: 1990 } puts movies[:Casablanca] puts movies[:"The Godfather"] puts movies[:"Citizen Kane"] puts movies[:"Pulp Fiction"] puts movies[:Goodfellas]
true
eb0533ad7ea50b7736e0c4890e9b1ac858e0de37
Ruby
colehart/denver_puplic_library
/test/author_test.rb
UTF-8
1,057
3.078125
3
[]
no_license
require './test/test_helper' require './lib/author' class AuthorTest < Minitest::Test def setup @author = Author.new(first_name: 'Charlotte', last_name: 'Bronte') end def test_it_exists assert_instance_of Author, @author end def test_it_has_attributes assert_equal 'Charlotte', @author.first_name assert_equal 'Bronte', @author.last_name end def test_add_books_adds_new_instance_of_book book = @author.add_book('Jane Eyre', 'October 16, 1847') assert_instance_of Book, book assert_equal 'Charlotte', book.author_first_name assert_equal 'Bronte', book.author_last_name assert_equal 'Jane Eyre', book.title assert_equal '1847', book.publication_date end def test_can_add_another_instance_of_book book = @author.add_book('Villette', '1853') assert_instance_of Book, book assert_equal 'Charlotte', book.author_first_name assert_equal 'Bronte', book.author_last_name assert_equal 'Villette', book.title assert_equal '1853', book.publication_date end end
true
16e690db9d6d480c2a5a6c929e5c99c59211ccd6
Ruby
mcken-vince/ruby_math_game
/planning.rb
UTF-8
309
2.625
3
[]
no_license
# class Player # Variables: lives # Methods: ask_question, opponent_correct, opponent_incorrect, lose_life # --- Initialize--- @lives = 3 # class Game # Variables: players, whose_turn # Methods: next_round, declare_winner # class Question # Variables: min, max # Method: generate_number, generate_question
true
9627dafddb741bde4d537185f8cb173172650b23
Ruby
Kyvyas/Battleships
/spec/board_spec.rb
UTF-8
1,053
2.984375
3
[]
no_license
require 'board' describe Board do let(:ship) { double :ship, :coordinates => 'A5' } it { is_expected.to respond_to(:place_ship) } it 'has a ship once ship is placed' do allow(ship).to receive(:place) {ship} allow(ship).to receive(:coordinates) {ship} subject.place_ship ship expect(subject.place_ship ship).to be ship end it 'has a width of 10' do expect(subject.width).to eq(10) end it 'has a height of 10' do expect(subject.height).to eq(10) end it "can fire at a coordinate" do expect(subject).to respond_to(:fire).with(1).arguments end let(:location) { double :location } it "will tell you if you have hit a boat" do subject.place_ship ship expect(subject.fire("A5")).to eq("You have hit a boat") end it "will raise error if fired on same place more than once" do subject.place_ship ship subject.fire("A5") expect{subject.fire("A5")}.to raise_error "You have alread fired here" end # it 'has a direction' do # expect(subject).to respond_to(:direction) # end end
true
a508110b5d2ab65bfd3655a53b39facbcc60d85b
Ruby
CristianCristea/launch_school
/exercises/ruby/small_problems/easy_3/06_odd_lists.rb
UTF-8
803
4.6875
5
[]
no_license
# Odd Lists # Write a method that returns an Array that contains every other element of an Array that is passed in as an argument. The values in the returned list should be those values that are in the 1st, 3rd, 5th, and so on elements of the argument Array. def oddities(arr) arr.select { |elem| elem if arr.index(elem).even? } end def oddities(arr) odd_elements = [] arr.each { |elem| odd_elements << elem if arr.index(elem).even? } odd_elements end def oddities(arr) odd_elements = [] counter = 0 loop do odd_elements << arr[counter] if counter.even? end odd_elements end # Examples: puts oddities([2, 3, 4, 5, 6]) == [2, 4, 6] puts oddities([1, 2, 3, 4, 5, 6]) == [1, 3, 5] puts oddities(['abc', 'def']) == ['abc'] puts oddities([123]) == [123] puts oddities([]) == []
true
a22668122ecf32b74f510d68fbe37612bcf43658
Ruby
manoart/ruby_seminar
/code/iterators.rb
UTF-8
183
3.671875
4
[]
no_license
10.times do print "Hallo! " end puts puts (1..10).each do |i| puts i*i end puts [1,2,3,4,5,6,7,8].each do |x| if x.even? print x else print "..." end end puts
true
c8bd4b6f0114874e692fb5456749a314b13d2b48
Ruby
johncban/ruby-objects-has-many-through-lab-online-web-pt-041519
/lib/patient.rb
UTF-8
467
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Patient attr_accessor :name @@all = [] def initialize(p_name) @name = p_name @@all << self end def self.all @@all end def new_appointment(doctor, date) Appointment.new(date, self, doctor) end def appointments Appointment.all do |apt| apt.new == self end end def doctors appointments.map(&:doctor) # https://stackoverflow.com/questions/9429819/what-is-the-functionality-of-operator-in-ruby end end
true
d65487971cf3ea970cf044d767eb8d261e7f8a65
Ruby
NRothera/sparta-web-testing
/capybara/facebook_RSpec_pom/lib/pages/facebook_homepage.rb
UTF-8
1,042
2.609375
3
[]
no_license
require 'capybara/dsl' class FacebookHomepage include Capybara::DSL HOMEPAGE_URL = 'https://www.facebook.com/' FIRSTNAME_FIELD_ID = 'u_0_p' LASTNAME_FIELD_ID = 'u_0_r' MOBILE_OR_EMAIL_FIELD_ID = 'u_0_u' PASSWORD_FIELD_ID = 'u_0_11' DAY_ID = 'Day' MONTH_ID = 'Month' YEAR_ID = 'Year' FEMALE_RADIO_ID = 'u_0_b' MALE_RADIO_ID = 'u_0_c' CREATE_ACCOUNT_BUTTON_ID = 'u_0_17' def visit_home_page visit(HOMEPAGE_URL) end def fill_first_name(name) fill_in(FIRSTNAME_FIELD_ID, with: name) end def fill_last_name(name) fill_in(LASTNAME_FIELD_ID, with: name) end def fill_mobile_or_email(string) fill_in(MOBILE_OR_EMAIL_FIELD_ID, with: string) end def fill_passord(password) fill_in(PASSWORD_FIELD_ID, with: password) end def choose_day select('15', :from => DAY_ID) end def choose_month select('10', :from => MONTH_ID) end def choose_year select('1992', :from => YEAR_ID) end def choose_female_radio_button choose(FEMALE_RADIO_ID) end end
true
e480a41ce205531c1be31faf4376e7ccfec0632c
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/1130/source/12739.rb
UTF-8
799
3.53125
4
[]
no_license
#HW 1: Ruby calisthnics #Author: Anand Kapoor #Part 3 - Anagrams def find_elements(element_name, element_array, original_array) @result_index = [] element_array.each_index { |e| @result_index << original_array.at(e) if element_array.at(e) == element_name.to_s } return @result_index end def combine_anagrams(words) @result = [] @anagrams = [] words.each do |word| @sorted_word = [] @key = "" word.to_s.gsub(%r\([a-zA-Z])\) {|character| @sorted_word << character.to_s.downcase} @sorted_word.sort.each {|x| @key << x} @anagrams << @key end @anagrams_unique = @anagrams.uniq @anagrams_unique.each {|e| @result << find_elements(e, @anagrams, words) } return @result.to_a end combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four', 'scar', 'creams', 'scream'])
true
8316071b6a6c094a8388553209a897aaf37d1e20
Ruby
henrygarciaospina/challengers-ruby
/read_file_best.rb
UTF-8
115
2.515625
3
[]
no_license
system("clear") def read(file) File.exist?(file) ? File.read(file) : nil end resul = read("text.txt") puts resul
true
dc4f49b695122636dc17813d7983c2c32cd4f447
Ruby
DanielLaraSanchez/Family-Wallet-Project
/project/family_wallet/models/accounts.rb
UTF-8
3,909
3.078125
3
[]
no_license
require('pg') require_relative('../db/sql_runner.rb') require_relative('./transactions.rb') class Account attr_accessor(:holder_name, :holder_last_name, :account_number, :type, :credit) attr_reader(:id) def initialize ( account ) @id = account['id'].to_i() if account['id'].to_i() @holder_name = account['holder_name'] @holder_last_name = account['holder_last_name'] @account_number = account['account_number'].to_i() @type = account['type'] if account['credit'] @credit = account['credit'].to_i() else @credit = 0 end end def save() sql = ' INSERT INTO accounts (holder_name, holder_last_name, account_number, type, credit) VALUES ($1, $2, $3, $4, $5) RETURNING *;' values = [@holder_name, @holder_last_name, @account_number, @type, @credit] account_data = SqlRunner.run(sql, values) @id = account_data.first['id'].to_i() end def self.all() sql = 'SELECT * FROM accounts;' values = [] account_data = SqlRunner.run(sql, values) result = account_data.map { |account| Account.new(account)} return result end def self.find(id) sql = 'SELECT * FROM accounts WHERE id = $1' values = [id] account_data = SqlRunner.run(sql, values) result = Account.new(account_data.first) return result end def delete() sql = 'DELETE FROM accounts WHERE id = $1' values = [@id] account_data = SqlRunner.run(sql, values) end def self.delete_all() #why does it not have * and no values? sql = "DELETE FROM accounts" values = [] SqlRunner.run( sql, values ) end def update() sql = 'UPDATE accounts SET (holder_name, holder_last_name, account_number, type, credit) = ($1, $2, $3, $4, $5) WHERE id = $6' values = [@holder_name, @holder_last_name, @account_number, @type, @credit, @id] SqlRunner.run(sql, values) end def transactions() sql = "SELECT * FROM transactions WHERE account_id = $1;" values = [@id] result = SqlRunner.run(sql, values) account_transactions = result.map {|transaction_hash| Transaction.new(transaction_hash)} return account_transactions end def sum_transactions() total = 0 transactions = self.transactions() for transaction in transactions if transaction.type == 'Income' total += transaction.quantity else total -= transaction.quantity end end return total end # def update_credit() # credit = self.sum_transactions() # @credit = credit # # self.update() # end def add_credit(transaction) if transaction.type == 'Expense' @credit -= transaction.quantity.to_f else @credit += transaction.quantity.to_f end self.update() end def self.credit() total = 0 accounts = Account.all for account in accounts total += account.credit end return total end def transfer_credit( transfer, reciever_id) tag = Tag.new({'type' => 'Transfer', 'color' => 'yellow'}) tag.save reciever_account = Account.find(reciever_id) self.new_transaction({ 'tag_id' => tag.id, 'account_id' => @id, 'type' => 'Expense', 'quantity' => transfer, 'issuer' => reciever_account.holder_name }) reciever_account.new_transaction({ 'tag_id' => tag.id, 'account_id' => reciever_account.id, 'type' => 'Income', 'quantity' => transfer, 'issuer' => @holder_name }) end def self.sum_transactions_amount() total = 0 accounts = Transaction.all for account in accounts if transaction.type == 'Income' total += transaction.quantity else total -= transaction.quantity end end return total end def new_transaction(transaction_details) transaction = Transaction.new(transaction_details) transaction.save self.add_credit(transaction) end end
true
678c510800c7bfcf655dd00e3bf039ca4e48692d
Ruby
paragppanchal/Decrypt
/app/jobs/fetch_market_snapshot_job.rb
UTF-8
3,210
2.984375
3
[]
no_license
class FetchMarketSnapshotJob < ApplicationJob queue_as :default def perform(*args) # fetch current buy & sell price of all the exchanges on the Exchanges table all_exchanges = Exchange.all all_exchanges.each do |exchange| begin update_market_snashot_record(exchange, 'BTC', 'USD') # this will not raise any exception if exchange api call fails. # it will log the excption though rescue Exception => e p e end end end private def update_market_snashot_record(exchange, base_currency_code, quote_currency_code) case exchange.name when "cexio" fetched_exchange = CexioExchange.new('BTC', 'USD') when "coinbase" fetched_exchange = CoinbaseExchange.new('BTC', 'USD') when "exmo" fetched_exchange = ExmoExchange.new('BTC', 'USD') when "hitbtc" fetched_exchange = HitbtcExchange.new('BTC', 'USD') when "itbtc" fetched_exchange = ItbitExchange.new('BTC', 'USD') when "bitstamp" fetched_exchange = BitstampExchange.new('BTC', 'USD') when "bitfinex" fetched_exchange = BitfinexExchange.new('BTC', 'USD') when "kraken" fetched_exchange = KrakenExchange.new('BTC', 'USD') when "lykke" fetched_exchange = LykkeExchange.new('BTC', 'USD') when "independentreserve" fetched_exchange = IndependentreserveExchange.new('BTC', 'USD') else puts 'exchange not found...' end #fetch current buy and sell price of the exchange fetched_exchange.fetch_buy_price! fetched_exchange.fetch_sell_price! # create exchange obj. instance # exchange = Exchange.find_by(name: exchange.name) # create base_coin obj. instance base_coin = Coin.find_by(currency_code: fetched_exchange.base_currency_code) # create quote_coin obj. instance quote_coin = Coin.find_by(currency_code: fetched_exchange.quote_currency_code) # check if record already exists then update it or else create a new one. if MarketSnapshot.where(exchange: exchange, base_coin: base_coin, quote_coin: quote_coin).exists? # record already exists so update buy and sell prices market_snapshot_record = MarketSnapshot.find_by(exchange: exchange, base_coin: base_coin, quote_coin: quote_coin) market_snapshot_record.buy_price = fetched_exchange.buy_price market_snapshot_record.sell_price = fetched_exchange.sell_price market_snapshot_record.save! else # didn't find record so create new here market_snapshot_record = MarketSnapshot.new market_snapshot_record.exchange = exchange market_snapshot_record.base_coin = base_coin market_snapshot_record.quote_coin = quote_coin market_snapshot_record.buy_price = fetched_exchange.buy_price market_snapshot_record.sell_price = fetched_exchange.sell_price market_snapshot_record.save! end puts "#{exchange.name} Exchange" puts 'base Currency Code: ' + fetched_exchange.base_currency_code puts 'Currency Code: ' + fetched_exchange.quote_currency_code puts "Buy price: #{fetched_exchange.buy_price}" puts "Sell price: #{fetched_exchange.sell_price}" puts '-------------------------' end end
true
14cfc5271e58aa74857295f9ed65da7c1d3cabd9
Ruby
Sage/rubocop-custom-cops
/lib/rubocop/lint/swallowed_exception.rb
UTF-8
1,714
2.59375
3
[ "Apache-2.0" ]
permissive
require 'rubocop' # Rubocop Cop module module RuboCop # Rubocop Lint module module Lint # SwallowException class for enforcing correct exception handling class SwallowedException < RuboCop::Cop::Cop # determines whether exceptions are being handled correctly def on_resbody(node) unless node.children[2] add_offense(node, location: :expression, message: 'rescue body is empty!', severity: :fatal) return end body = node.children[2] return if raises?(body) return if newrelic_captured_exception?(body) # rubocop:disable Style/RedundantParentheses add_offense(node, location: :expression, message: (<<-MSG).strip, severity: :fatal) you have to raise exception or capture exception by NewRelic in rescue body. MSG # rubocop:enable Style/RedundantParentheses end private def newrelic_captured_exception?(node) if node.type == :begin node.children.any? { |c| newrelic_captured?(c) } else newrelic_captured?(node) end end def raises?(node) if node.type == :begin node.children.any? { |c| raise?(c) } else raise?(node) end end def newrelic_captured?(node) node.type == :send && newrelic?(node.children[0]) && node.children[1] == :notice_error end def newrelic?(node) node && node.type == :const && node.children[0].children[1] == :NewRelic && node.children[1] == :Agent end def raise?(node) node.type == :send && node.children[0].nil? && node.children[1] == :raise end end end end
true
14acea51763c325adcc48b664266a3c3b1e90b5a
Ruby
dotdoom/net-ssh-open3
/lib/net-ssh-open3.rb
UTF-8
22,134
2.59375
3
[]
no_license
require 'shellwords' # String#shellescape require 'thread' # ConditionVariable require 'net/ssh' # Monkeypatching require 'stringio' # StringIO for capture* class Class unless method_defined?(:alias_method_once) private # Create an alias +new_method+ to +old_method+ unless +new_method+ is already defined. def alias_method_once(new_method, old_method) #:nodoc: alias_method new_method, old_method unless method_defined?(new_method) end end end module Net::SSH module Process # Encapsulates the information on the status of remote process, similar to ::Process::Status. # # Note that it's impossible to retrieve PID (process ID) via an SSH channel (thus impossible to properly signal it). # # Although RFC4254 allows sending signals to the process (see http://tools.ietf.org/html/rfc4254#section-6.9), # current OpenSSH server implementation does not support this feature, though there are some patches: # https://bugzilla.mindrot.org/show_bug.cgi?id=1424 and http://marc.info/?l=openssh-unix-dev&m=104300802407848&w=2 # # As a workaround one can request a PTY and send SIGINT or SIGQUIT via ^C, ^\ or other sequences, # see 'pty' option in Net::SSH::Open3 for more information. # # Open3 prepends your command with 'echo $$; ' which will echo PID of your process, then intercepts this line from STDOUT. class Status # Integer exit code in range 0..255, 0 usually meaning success. # Assigned only if the process has exited normally (i.e. not by a signal). # More information about standard exit codes: http://tldp.org/LDP/abs/html/exitcodes.html attr_reader :exitstatus # Process ID of a remote command interpreter or a remote process. # See note on Net::SSH::Process::Status class for more information on how this is fetched. # false if PID fetching was disabled. attr_reader :pid # true when process has been killed by a signal and a core dump has been generated for it. def coredump? @coredump end # Integer representation of a signal that killed a process, if available. # # Translated to local system (so you can use Signal.list to map it to String). # Explanation: when local system is Linux (USR1=10) and remote is FreeBSD (USR1=30), # 10 will be returned in case remote process receives USR1 (30). # # Not all signal names are delivered by ssh: for example, SIGTRAP is delivered as "SIG@openssh.com" # and therefore may not be translated. Returns String in this case. def termsig Signal.list[@termsig] || @termsig end # true if the process has exited normally and returned an exit code. def exited? !!@exitstatus end # true if the process has been killed by a signal. def signaled? !!@termsig end # true if the process is still running (actually if we haven't received it's exit status or signal). def active? not (exited? or signaled?) end # Returns true if the process has exited with code 0, false for other codes and nil if killed by a signal. def success? exited? ? exitstatus == 0 : nil end # String representation of exit status. def to_s if @pid != nil "pid #@pid " << if exited? "exit #@exitstatus" elsif signaled? "#@termsig (signal #{termsig}) core #@coredump" else 'active' end else 'uninitialized' end end # Inspect this instance. def inspect "#<#{self.class}: #{to_s}>" end end end # Net::SSH Open3 extensions. # All methods have the same argument list. # # *optional* +env+: custom environment variables +Hash+. Note that SSH server typically restricts changeable variables to a very small set, # e.g. for OpenSSH see +AcceptEnv+ in +/etc/ssh/sshd_config+ (+AcceptEnv+ +LANG+ +LC_*+) # # +command+: a single shell command (like in +sh+ +-c+), or an executable program. # # *optional* +arg1+, +arg2+, +...+: arguments to an executable mentioned above. # # *optional* +options+: options hash, keys: # * +redirects+: Hash of redirections which will be appended to a command line (you can't transfer a pipe to a remote system). # Key: one of +:in+, +:out+, +:err+ or a +String+, value: +Integer+ to redirect to remote fd, +String+ to redirect to a file. # If a key is a Symbol, local +IO+ may be specified as a value. In this case, block receives +nil+ for the corresponding IO. # Example: # { '>>' => '/tmp/log', err: 1 } # translates to # '>>/tmp/log 2>&1' # Another example: # { in: $stdin, out: $stdout, err: $stderr } # * +channel_retries+: +Integer+ number of retries in case of channel open failure (ssh server usually limits a session to 10 channels), # or an array of [+retries+, +delay+] # * +stdin_data+: for +capture*+ only, specifies data to be immediately sent to +stdin+ of a remote process. # stdin is immediately closed then. # * +logger+: an object which responds to +debug/info/warn/error+ and optionally +init/stdin/stdout/stderr+ to log debug information # and data exchange stream. # * +fetch_pid+: prepend command with 'echo $$' and capture first line of the output as PID. Defaults to true. # * +pty+: true or a +Hash+ of PTY settings to request a pseudo-TTY, see Net::SSH documentation for more information. # A note about sending TERM/QUIT: use modes, e.g.: # Net::SSH.start('localhost', ENV['USER']).capture2e('cat', pty: { # modes: { # Net::SSH::Connection::Term::VINTR => 0x01020304, # INT on this 4-byte-sequence # Net::SSH::Connection::Term::VQUIT => 0xdeadbeef, # QUIT on this 4-byte sequence # Net::SSH::Connection::Term::VEOF => 0xfacefeed, # EOF sequence # Net::SSH::Connection::Term::ECHO => 0, # disable echoing # Net::SSH::Connection::Term::ISIG => 1 # enable sending signals # } # }, # stdin_data: [0xDEADBEEF].pack('L'), # logger: Class.new { alias method_missing puts; def respond_to?(_); true end }.new) # # log skipped ... # # => ["", #<Net::SSH::Process::Status: pid 1744 QUIT (signal 3) core true>] # Note that just closing stdin is not enough for PTY. You should explicitly send VEOF as a first char of a line, see termios(3). module Open3 # Captures stdout only. Returns [String, Net::SSH::Process::Status] def capture2(*args) stdout = StringIO.new stdin_data = extract_open3_options(args)[:stdin_data] run_popen(*args, stdin: stdin_data, stdout: stdout) do |waiter_thread| [stdout.string, waiter_thread.value] end end # Captures stdout and stderr into one string. Returns [String, Net::SSH::Process::Status] def capture2e(*args) stdout = StringIO.new stdin_data = extract_open3_options(args)[:stdin_data] run_popen(*args, stdin: stdin_data, stdout: stdout, stderr: stdout) do |waiter_thread| [stdout.string, waiter_thread.value] end end # Captures stdout and stderr into separate strings. Returns [String, String, Net::SSH::Process::Status] def capture3(*args) stdout, stderr = StringIO.new, StringIO.new stdin_data = extract_open3_options(args)[:stdin_data] run_popen(*args, stdin: stdin_data, stdout: stdout, stderr: stderr) do |waiter_thread| [stdout.string, stderr.string, waiter_thread.value] end end # Opens pipes to a remote process. # Yields +stdin+, +stdout+, +stderr+, +waiter_thread+ into a block. Will wait for a process to finish. # Joining (or getting a value of) +waither_thread+ inside a block will wait for a process right there. # 'status' Thread-Attribute of +waiter_thread+ holds an instance of Net::SSH::Process::Status for a remote process. # Careful: don't forget to read +stderr+, otherwise if your process generates too much stderr output # the pipe may overload and ssh loop will get stuck writing to it. def popen3(*args, &block) redirects = extract_open3_options(args)[:redirects] local_pipes = [] stdin_inner, stdin_outer = open3_ios_for(:in, redirects, local_pipes) stdout_outer, stdout_inner = open3_ios_for(:out, redirects, local_pipes) stderr_outer, stderr_inner = open3_ios_for(:err, redirects, local_pipes) run_popen(*args, stdin: stdin_inner, stdout: stdout_inner, stderr: stderr_inner, block_pipes: [stdin_outer, stdout_outer, stderr_outer], local_pipes: local_pipes, &block) end # Yields +stdin+, +stdout-stderr+, +waiter_thread+ into a block. def popen2e(*args, &block) redirects = extract_open3_options(args)[:redirects] local_pipes = [] stdin_inner, stdin_outer = open3_ios_for(:in, redirects, local_pipes) stdout_outer, stdout_inner = open3_ios_for(:out, redirects, local_pipes) run_popen(*args, stdin: stdin_inner, stdout: stdout_inner, stderr: stdout_inner, block_pipes: [stdin_outer, stdout_outer], local_pipes: local_pipes, &block) end # Yields +stdin+, +stdout+, +waiter_thread+ into a block. def popen2(*args, &block) redirects = extract_open3_options(args)[:redirects] local_pipes = [] stdin_inner, stdin_outer = open3_ios_for(:in, redirects, local_pipes) stdout_outer, stdout_inner = open3_ios_for(:out, redirects, local_pipes) run_popen(*args, stdin: stdin_inner, stdout: stdout_inner, block_pipes: [stdin_outer, stdout_outer], local_pipes: local_pipes, &block) end private def extract_open3_options(args, pop = false) if Hash === args.last pop ? args.pop : args.last else {} end end def open3_ios_for(name, redirects, locals) if redirects and user_supplied_io = redirects[name] and IO === user_supplied_io name == :in ? [user_supplied_io, nil] : [nil, user_supplied_io] else IO.pipe.tap { |pipes| locals.concat pipes } end end SSH_EXTENDED_DATA_STDERR = 1 #:nodoc: REMOTE_PACKET_THRESHOLD = 512 # headers etc #:nodoc: private_constant :SSH_EXTENDED_DATA_STDERR, :REMOTE_PACKET_THRESHOLD def install_channel_callbacks(channel, options) logger, stdin, stdout, stderr, local_pipes = options[:logger], options[:stdin], options[:stdout], options[:stderr], options[:local_pipes] if options[:fetch_pid] pid_initialized = false else channel.open3_waiter_thread[:status].instance_variable_set(:@pid, false) pid_initialized = true end channel.on_open_failed do |_channel, code, desc| message = "cannot open channel (error code #{code}): #{desc}" logger.error(message) if logger raise message end channel.on_data do |_channel, data| unless pid_initialized # First arrived line contains PID (see run_popen). pid_initialized = true pid, data = data.split(nil, 2) channel.open3_waiter_thread[:status].instance_variable_set(:@pid, pid.to_i) channel.open3_signal_open next if data.empty? end logger.stdout(data) if logger.respond_to?(:stdout) if stdout stdout.write(data) stdout.flush end end channel.on_extended_data do |_channel, type, data| if type == SSH_EXTENDED_DATA_STDERR logger.stderr(data) if logger.respond_to?(:stderr) if stderr stderr.write(data) stderr.flush end else logger.warn("unknown extended data type #{type}") if logger end end channel.on_request('exit-status') do |_channel, data| channel.open3_waiter_thread[:status].tap do |status| status.instance_variable_set(:@exitstatus, data.read_long) logger.debug("exit status arrived: #{status.exitstatus}") if logger end end channel.on_request('exit-signal') do |_channel, data| channel.open3_waiter_thread[:status].tap do |status| status.instance_variable_set(:@termsig, data.read_string) status.instance_variable_set(:@coredump, data.read_bool) logger.debug("exit signal arrived: #{status.termsig.inspect}, core #{status.coredump?}") if logger end end channel.on_eof do logger.debug('server reports EOF') if logger [stdout, stderr].each { |io| io.close if local_pipes.include?(io) && !io.closed? } end channel.on_close do logger.debug('channel close command received, will enforce EOF afterwards') if logger begin if stdin.is_a?(IO) self.stop_listening_to(stdin) stdin.close if !stdin.closed? && local_pipes.include?(stdin) end ensure channel.do_eof # Should already be done, but just in case. end end if stdin.is_a?(IO) send_packet_size = [1024, channel.remote_maximum_packet_size - REMOTE_PACKET_THRESHOLD].max logger.debug("will split stdin into packets with size = #{send_packet_size}") if logger self.listen_to(stdin) do begin data = stdin.readpartial(send_packet_size) logger.stdin(data) if logger.respond_to?(:stdin) channel.send_data(data) rescue EOFError logger.debug('sending EOF command') if logger self.stop_listening_to(stdin) channel.eof! end end elsif stdin.is_a?(String) logger.stdin(stdin) if logger.respond_to?(:stdin) channel.send_data(stdin) channel.eof! end end REDIRECT_MAPPING = { in: '<', out: '>', err: '2>' } private_constant :REDIRECT_MAPPING def run_popen(*args, internal_options) options = extract_open3_options(args, true) env = (args.shift if Hash === args.first) || {} cmdline = args.size == 1 ? args.first : Shellwords.join(args.map(&:to_s)) redirects = options[:redirects] and redirects.each_pair do |fd_and_dir, destination| if destination = popen_io_name(destination) cmdline << " #{REDIRECT_MAPPING[fd_and_dir] || fd_and_dir}#{destination}" end end logger = options[:logger] || @open3_logger pty_options = options[:pty] retries, delay = options[:channel_retries] retries ||= 5 delay ||= 1 fetch_pid = options[:fetch_pid] != false local_pipes = Array(internal_options[:local_pipes]) logger.init(host: self.transport.host_as_string, cmdline: cmdline, env: env, pty: pty_options) if logger.respond_to?(:init) cmdline = "echo $$; exec #{cmdline}" if fetch_pid begin channel = open3_open_channel do |channel| channel.open3_signal_open unless fetch_pid channel.request_pty(Hash === pty_options ? pty_options : {}) if pty_options env.each_pair { |var_name, var_value| channel.env(var_name, var_value) } channel.exec(cmdline) install_channel_callbacks channel, stdin: internal_options[:stdin], stdout: internal_options[:stdout], stderr: internal_options[:stderr], logger: logger, local_pipes: local_pipes, fetch_pid: fetch_pid end.open3_wait_open rescue ChannelOpenFailed logger.warn("channel open failed: #$!, #{retries} retries left") if logger if (retries -= 1) >= 0 sleep delay retry else raise end end logger.debug('channel is open and ready, calling user-defined block') if logger begin yield(*internal_options[:block_pipes], channel.open3_waiter_thread) ensure channel.wait end ensure local_pipes.each { |io| io.close unless io.closed? } end def popen_io_name(name) case name when Fixnum then "&#{name}" when String then Shellwords.shellescape(name) end end end module Connection class Session include Open3 attr_accessor :open3_logger alias_method_once :initialize_without_open3, :initialize # Overridden version of +initialize+ which starts an Open3 SSH loop. # @private def initialize(*args, &block) initialize_without_open3(*args, &block) @open3_channels_mutex = Mutex.new # open3_ping method will pull waiter thread out of select(2) call # to update watched Channels and IOs and process incomes. @open3_pinger_reader, @open3_pinger_writer = IO.pipe listen_to(@open3_pinger_reader) { @open3_pinger_reader.readpartial(1) } @session_loop = Thread.new { open3_loop } end alias_method_once :close_without_open3, :close def close(*args, &block) @open3_closing = true close_without_open3(*args, &block).tap { open3_ping rescue nil } end private def open3_open_channel(type = 'session', *extra, &on_confirm) @open3_channels_mutex.synchronize do local_id = get_next_channel_id channel = Connection::Channel.new(self, type, local_id, @max_pkt_size, @max_win_size, &on_confirm) channel.open3_waiter_thread = Thread.new do status = Thread.current[:status] = Process::Status.new @open3_channels_mutex.synchronize do msg = Buffer.from(:byte, CHANNEL_OPEN, :string, type, :long, local_id, :long, channel.local_maximum_window_size, :long, channel.local_maximum_packet_size, *extra) send_message(msg) channels[local_id] = channel open3_ping channel.open3_close_semaphore.wait(@open3_channels_mutex) if channels.key?(channel.local_id) end raise *channel.open3_exception if channel.open3_exception status end channel end end def open3_ping @open3_pinger_writer.write(?P) end def open3_loop r, w = nil while not closed? @open3_channels_mutex.synchronize do break unless preprocess { not closed? } # This may remove some channels. r = listeners.keys w = r.select { |w2| w2.respond_to?(:pending_write?) && w2.pending_write? } end break if @open3_closing readers, writers, = Compat.io_select(r, w, nil, nil) postprocess(readers, writers) end channels.each do |_id, channel| @open3_channels_mutex.synchronize do channel.open3_signal_open channel.open3_signal_close channel.do_close end end rescue warn "Caught exception in an Open3 loop: #$!; thread terminating, connections will hang." ensure [@open3_pinger_reader, @open3_pinger_writer].each(&:close) end end # All methods in this class were created for private use of Net::SSH::Open3. # You probably won't need to call them directly. # @private class Channel # A semaphore to flag this channel as closed. attr_reader :open3_close_semaphore # An exception tracked during channel opening, if any. attr_reader :open3_exception # Waiter thread that watches this channel. attr_reader :open3_waiter_thread alias_method_once :initialize_without_open3, :initialize # Overridden version of +initialize+ which creates synchronization objects. def initialize(*args, &block) initialize_without_open3(*args, &block) @open3_close_semaphore = ConditionVariable.new @open3_open_mutex = Mutex.new @open3_open_semaphore = ConditionVariable.new end alias_method_once :do_close_without_open3, :do_close # Overridden version of +do_close+ which tracks exceptions and sync. def do_close(*args) do_close_without_open3(*args) rescue @open3_exception = $! ensure open3_signal_close end alias_method_once :do_open_confirmation_without_open3, :do_open_confirmation # Overridden version of +do_open_confirmation+ which tracks exceptions. def do_open_confirmation(*args) do_open_confirmation_without_open3(*args) # Do not signal right now: we will signal as soon as PID arrives. rescue @open3_exception = $! end alias_method_once :do_open_failed_without_open3, :do_open_failed # Overridden version of +do_open_failed+ which tracks exceptions and sync. def do_open_failed(*args) do_open_failed_without_open3(*args) rescue @open3_exception = $! ensure open3_signal_open open3_signal_close end # +waiter_thread+ setter which may only be called once with non-false argument. def open3_waiter_thread=(value) @open3_waiter_thread = value unless @open3_waiter_thread end # Suspend current thread execution until this channel is opened. # Raises an exception if tracked during opening. def open3_wait_open @open3_open_mutex.synchronize { @open3_open_semaphore.wait(@open3_open_mutex) } raise *open3_exception if open3_exception self end # Wait for this channel to be closed. def wait @open3_waiter_thread.join self end # Flag this channel as opened and deliver signals. def open3_signal_open @open3_open_mutex.synchronize { @open3_open_semaphore.signal } end # Flag this channel as closed and deliver signals. # Should be called from within session's mutex. def open3_signal_close @open3_close_semaphore.signal end end end end
true
b0ba0b4d6e7328dd87f358498381c879cef783d3
Ruby
PauloHenrique222/TesteRspec
/spec/lib/calculator_spec.rb
UTF-8
563
3.203125
3
[]
no_license
require 'calculator' describe Calculator do describe "#add" do it "adds two numbers / no failure" do expect(subject.add(10, 5)).to eq(15) end it "adds two numbers / with failure" do expect(subject.add(10, 4)).not_to eq(15) end end describe "#factorial" do it "returns 1 when given 0 (0! = 1)" do expect(subject.factorial(0)).to eq(1) end it "returns 120 when given 5 (5! = 120)" do expect(subject.factorial(5)).to eq(120) end end end
true
40527063aa0c6bef645c35348c76bf741e29cd63
Ruby
EmilianoFusaro/GestioneProduzione_Dielle
/funzioni_caricoX.rb
UTF-8
16,332
2.546875
3
[]
no_license
#Stessa Funzione Ma Con Ricerca In Hash Non Eseguendo Query Con Molti Filtri e Dati è risultata più lenta della query sopra (a casa ma in ufficio è più veloce) #self.fase2=lista_reparti.detect{|f| f[:codice]=="#{self.ciclost[1]}"} def TrovaCicloX(cod,padre,codbarra,varianti,islaccato,lista_cicli) #---Funzione Che In Base Ai Dati Di Logy_Componenti Individua Il Ciclo Di Appartenenza #codice per Test #if cod=='7025' and padre=='066027101' #puts "#{cod} #{padre} #{codbarra} #{varianti}" #puts lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=="#{padre}"}[0] #ciclo=lista_cicli.select{|f| f.cod=='7025' and f.padre=='066027101' and f.laccato==false and f.variante !='' and '570=001;470=005'.include? f.variante} #puts ciclo.count #end #puts islaccato ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=="#{padre}" and f.laccato==islaccato and varianti.include? f.variante and f.variante !=''} if ciclo.count==1 #puts "A" #puts "Trovato Ciclo #{riga.pcod} => ciclo.count ciclo.variante cod-padre-variante" return ciclo elsif ciclo.count>1 #puts "B" #puts "Trovato Errore Ciclo Duplicato #{cod} => #{ciclo.count} cod-padre-variante" return false end ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=="#{padre}" and f.laccato==islaccato and f.variante==''} if ciclo.count==1 #puts "C" #puts "Trovato Ciclo #{riga.pcod} => #{ciclo.count} cod-padre" return ciclo elsif ciclo.count>1 #puts "D" #puts "Trovato Errore Ciclo Duplicato #{padre} => #{ciclo.count} cod-padre" return false end ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=='' and f.codbarra=="#{codbarra}" and f.laccato==islaccato and varianti.include? f.variante and f.variante !=''} if ciclo.count==1 #puts "E" #puts ciclo[0].ciclost #Contiene Oggetto Riga Ciclo #puts "Trovato Ciclo #{riga.pcod} => #{ciclo.count} ciclo.codbarra ciclo.variante cod-codbarra-variante" return ciclo elsif ciclo.count>1 #puts "F" #puts "Trovato Errore Ciclo Duplicato #{codbarra} => #{ciclo.count} cod-codbarra-variante" return false end ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=='' and f.codbarra=="#{codbarra}" and f.laccato==islaccato and f.variante==''} if ciclo.count==1 #puts "G" #puts "Trovato Ciclo #{riga.pcod} => #{ciclo.count} ciclo.codbarra cod-codbarra" return ciclo elsif ciclo.count>1 #puts "H" #puts "Trovato Errore Ciclo Duplicato #{codbarra} => #{ciclo.count} cod-codbarra" return false end ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=='' and f.codbarra=='' and f.laccato==islaccato and varianti.include? f.variante and f.variante !=''} if ciclo.count==1 #puts "I" #puts "Trovato Ciclo #{riga.ciclo} => #{ciclo.count} ciclo.cod ciclo.varianti cod-variani" return ciclo elsif ciclo.count>1 #puts "L" #puts "Trovato Errore Ciclo Duplicato #{cod} => #{varianti} cod-varianti" return false end ciclo=lista_cicli.select{|f| f.cod=="#{cod}" and f.padre=='' and f.codbarra=='' and f.laccato==islaccato and f.variante==''} if ciclo.count==1 #puts "M" #puts "Trovato Ciclo #{riga.ciclo} => #{ciclo.count} ciclo.cod cod" return ciclo elsif ciclo.count>1 #puts "N" #puts "Trovato Errore Ciclo Duplicato #{cod} => cod-varianti" return false end #puts "Ciclo Non Trovato #{padre} #{codbarra} #{cod}" return false end #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def TrovaMagazzinoX(riga,lista_magazzino) #---Funzione Che In Base Ai Dati Determina il componente a magazzino da utilizzare islaccato=false variante=riga[:var].split(";") variante.each{ |i| if ($stringa_laccati.include? i) and (i.size>=6) #verificare se necessario i.size>=6 islaccato=true break end } #olmonaturale (in caso di laccato olmo) #colore="OlmoNaturale" if islaccato==true #TODO: gestire laccato olmo # colore="Bianco" colore =riga[:laccodal] #puts colore #Bianco O Olmo Naturale else colore=Colore.trova_strvaropz(riga[:var]) end #15.11.14 alcune righe di 3cad arrivano senza colore perchè sono solo bianche es. ante specchio 051083017 if colore==nil puts "Attenzione Sto Forzando Questa Riga A Bianco Controllare Il Perche':" puts "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" puts riga puts "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" colore="bianco" #File.open("TEST.txt", 'a') { |file| file.write("#{@riga}\n") } #appende in un file di testo x TEST end #---esempio con array #condizione="f.#{colore.downcase}==true and f.dimx>=#{riga[:diml]} and f.dimy>=#{riga[:dima]} and dimz=#{riga[:dimp]}" #puts condizione #ciclo=lista_magazzino.select{|f| eval(condizione)} #puts ciclo.count trovato=false fm_lunghezza="" fm_profondita="" tipologia="" #------------------------------------------cerco misure diverse dal padre originale es. cassetto if riga[:orientamento]=="LAP" dim_x=riga[:diml] #+riga[:xtolleranza] dim_y=riga[:dima] #+riga[:ytolleranza] dim_z=riga[:dimp] adim_x=riga[:adiml] adim_y=riga[:adima] adim_z=riga[:adimp] elsif riga[:orientamento]=="LPA" dim_x=riga[:diml] #+riga[:xtolleranza] dim_y=riga[:dimp] #+riga[:ytolleranza] dim_z=riga[:dima] adim_x=riga[:adiml] adim_y=riga[:adimp] adim_z=riga[:adima] elsif riga[:orientamento]=="ALP" dim_x=riga[:dima] #+riga[:xtolleranza] dim_y=riga[:diml] #+riga[:ytolleranza] dim_z=riga[:dimp] adim_x=riga[:adima] adim_y=riga[:adiml] adim_z=riga[:adimp] elsif riga[:orientamento]=="APL" dim_x=riga[:dima] #+riga[:xtolleranza] dim_y=riga[:dimp] #+riga[:ytolleranza] dim_z=riga[:diml] adim_x=riga[:adima] adim_y=riga[:adimp] adim_z=riga[:adiml] elsif riga[:orientamento]=="PAL" dim_x=riga[:dimp] #+riga[:xtolleranza] dim_y=riga[:dima] #+riga[:ytolleranza] dim_z=riga[:diml] adim_x=riga[:adimp] adim_y=riga[:adima] adim_z=riga[:adiml] elsif riga[:orientamento]=="PLA" dim_x=riga[:dimp] #+riga[:xtolleranza] dim_y=riga[:diml] #+riga[:ytolleranza] dim_z=riga[:dima] adim_x=riga[:adimp] adim_y=riga[:adiml] adim_z=riga[:adima] else puts "----ERRORRE ORIENTAMENTO----" dim_x=riga[:diml] #+riga[:xtolleranza] dim_y=riga[:dima] #+riga[:ytolleranza] dim_z=riga[:dimp] adim_x=riga[:adiml] adim_y=riga[:adima] adim_z=riga[:adimp] end if riga[:xpannello]>0 dim_x=riga[:xpannello] end if riga[:ypannello]>0 dim_y=riga[:ypannello] end if riga[:zpannello]>0 dim_z=riga[:zpannello] end riga[:diml]=dim_x riga[:dima]=dim_y riga[:dimp]=dim_z riga[:adiml]=adim_x riga[:adima]=adim_y riga[:adimp]=adim_z if riga[:ciclofisso]==true #il ciclo viene forzato senza nessun controllo magazzino tipologia="PANNELLO" #Creazione Hash Fittizio Chiave,Valore r_mag = { :codice =>riga[:codart], :descrizione =>riga[:des], :dimx =>riga[:diml], :dimy =>riga[:dima], :dimz =>riga[:dimp], :tipologia =>tipologia, :bianco =>true, :larice =>true, :roverenaturale =>true, :corda =>true, :roveretabacco =>true, :olmoperla =>true, :olmonaturale =>true, :olmolava =>true, :mandarino =>true, :girasole =>true, :magnolia =>true, :alabastro =>true, :avio =>true, :verdeprimavera =>true, :glicine =>true, :acero =>true, :punto =>true, :riga =>true, :acxbianco =>true, :acxtortora =>true, :moro =>true, :cenere =>true, :famiglia =>"PANNELLO" } riga_magazzino=r_mag #puts riga_magazzino ciclo_magazzino=CicloMagazzino.new(riga,riga_magazzino,fm_lunghezza,fm_profondita,islaccato,tipologia) return ciclo_magazzino end #------------------------------------------Se Richiesto inverte l'ordine di ordinamento ordina_per="dimx,dimy" if riga[:ordinecerca]!=nil if riga[:ordinecerca][0]=="Y" ordina_per="dimy,dimx" puts "Ordinamento Magazzino Inverito" end end #---------------------------------------------------------------------CONTROLLO NORMALE riga[:famiglie].split(";").each{|famiglia| #puts "#{dim_x} - #{dim_y} totale #{dim_x+riga[:xtolleranza]}" #sql_condizione="select top 1 * from magazzino where famiglia='#{famiglia}' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by dimx,dimy" sql_condizione="select top 1 * from magazzino where famiglia='#{famiglia}' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by #{ordina_per}" #puts sql_condizione #puts sql_condizione #puts Magazzino.with_sql(sql_condizione).single_value #capire come funziona #Magazzino.with_sql(sql_condizione).select #Magazzino.with_sql(sql_condizione).select.all #gino=Magazzino.with_sql(sql_condizione).select.all riga_magazzino=nil DB_ECAD.fetch(sql_condizione) do |r_mag| #puts r_mag trovato=true tipologia="MAGAZZINO" if riga[:semprefm]==true tipologia="MAGAZZINOFM" #Alcuni Elementi Devono Essere Forzati a FM (fianchi obliqui) end riga_magazzino=r_mag if r_mag[:dimx]>(dim_x+riga[:xtolleranza]) fm_lunghezza="FM" tipologia="MAGAZZINOFM" end if r_mag[:dimy]>(dim_y+riga[:ytolleranza]) fm_profondita="FM" tipologia="MAGAZZINOFM" end end #------------------------------------------Gestione Tolleranza Solo Su FM (Se Presete ripeto la ricerca) if tipologia=="MAGAZZINOFM" and riga[:xtolleranzafm]!=nil and riga[:ytolleranzafm]!=nil if riga[:xtolleranzafm]!=0 or riga[:ytolleranzafm]!=0 puts "ATTENZIONE ENTRO IN TOLLERANZA FM" xtolleranzafm=riga[:xtolleranzafm] ytolleranzafm=riga[:ytolleranzafm] if (riga[:diml]==riga[:adiml]) and (fm_lunghezza=="") #non ho fuori misura in questo lato e quindi annullo tolleranza fm (riga mi indica fm su rubycomponentix fm_lunghezza potrebbe essere padre diverso da figlio) xtolleranzafm=0 else puts "Tolleranza su fuori misura in X" end if (riga[:dima]==riga[:adima]) and (fm_profondita=="") #non ho fuori misura in questo lato e quindi annullo tolleranza fm ytolleranzafm=0 else puts "Tolleranza su fuori misura in Y" end sql_condizione="select top 1 * from magazzino where famiglia='#{famiglia}' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+xtolleranzafm} and DimY>=#{dim_y+ytolleranzafm} order by #{ordina_per}" #puts sql_condizione trovato=false riga_magazzino=nil DB_ECAD.fetch(sql_condizione) do |r_mag| #puts r_mag trovato=true tipologia="MAGAZZINOFM" riga_magazzino=r_mag if r_mag[:dimx]>(dim_x+xtolleranzafm) fm_lunghezza="FM" tipologia="MAGAZZINOFM" end if r_mag[:dimy]>(dim_y+ytolleranzafm) fm_profondita="FM" tipologia="MAGAZZINOFM" end end end end #puts "#{riga_magazzino} Magazzino" #x debug if trovato==true #se presente in una famiglia interrompo la ricerca ciclo_magazzino=CicloMagazzino.new(riga,riga_magazzino,fm_lunghezza,fm_profondita,islaccato,tipologia) return ciclo_magazzino break end } tipologia="" #---------------------------------------------------------------------CONTROLLO DA BARRA #sql_condizione="select top 1 * from magazzino where famiglia='BARRA' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by dimx,dimy" sql_condizione="select top 1 * from magazzino where famiglia='BARRA' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by #{ordina_per}" riga_magazzino=nil DB_ECAD.fetch(sql_condizione) do |r_mag| #puts r_mag trovato=true tipologia="BARRA" riga_magazzino=r_mag if r_mag[:dimx]>(dim_x+riga[:xtolleranza]) fm_lunghezza="FM" tipologia="BARRAFM" end if r_mag[:dimy]>(dim_y+riga[:ytolleranza]) fm_profondita="FM" tipologia="BARRAFM" end end #puts "#{riga_magazzino} Barra" #x debug if trovato==true #se presente nelle barre interrompo la ricerca ciclo_magazzino=CicloMagazzino.new(riga,riga_magazzino,fm_lunghezza,fm_profondita,islaccato,tipologia) return ciclo_magazzino end #---------------------------------------------------------------------CONTROLLO DA PANNELLO #sql_condizione="select top 1 * from magazzino where famiglia='PANNELLO' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by dimx,dimy" sql_condizione="select top 1 * from magazzino where famiglia='PANNELLO' and #{colore.downcase}=1 and DimZ=#{dim_z} and DimX>=#{dim_x+riga[:xtolleranza]} and DimY>=#{dim_y+riga[:ytolleranza]} order by #{ordina_per}" riga_magazzino=nil DB_ECAD.fetch(sql_condizione) do |r_mag| trovato=true tipologia="PANNELLO" riga_magazzino=r_mag fm_lunghezza="FM" fm_profondita="FM" end #puts "#{riga_magazzino} Pannello" #x debug if trovato==true #se presente nelle barre interrompo la ricerca ciclo_magazzino=CicloMagazzino.new(riga,riga_magazzino,fm_lunghezza,fm_profondita,islaccato,tipologia) return ciclo_magazzino end #---------------------------------------------------------------------QUALCOSA NON FUNZIONA NELLA RICERCA puts "Magazzino Non Trovato" puts riga return nil #if trovato==true # puts "Elemento Presente A Magazzino #{fm_lunghezza} #{fm_profondita}" #else # puts "Elemento Non Presente A Magazzino" #end end
true
d32358497d72eddd3512822200d83876af3b990e
Ruby
kenosuda4/enjoy-ruby
/chapter-6/while3.rb
UTF-8
303
3.484375
3
[]
no_license
sum = 0 i = 1 while sum < 50 sum += i i += 1 end puts sum =begin while2と違い、条件がiではなくsumになっている。 sumが50より小さい間繰り返すという条件 sumが50を超える時にiが幾つになっているかわからないの = for文は使いづらい =end
true
a32b032530fdd650a0fca647aba3408a037ed195
Ruby
tsmango/rand
/lib/rand.rb
UTF-8
369
2.96875
3
[ "MIT" ]
permissive
class Array def rand(size = 1) return nil if size < 1 if size == 1 return self[Kernel.rand(self.length)] else random_candidates = self.collect size = self.length if size > self.length (0..(size - 1)).to_a.collect do random_candidates.delete_at(Kernel.rand(random_candidates.length)) end end end end
true
4046373de93a83230bd3e075ff12468cf2e6c208
Ruby
pulkitsharma07/modown
/lib/modown/options.rb
UTF-8
1,584
2.890625
3
[ "MIT" ]
permissive
require 'optparse' module Modown # This class handles command line options class Options def initialize @options = { input: nil, count: 1, format: '*' } # Dont know how to do case-insensitive glob matching @formats_glob = {} @formats_glob['3ds'] = '*.3[Dd][Ss]' @formats_glob['max'] = '*.[Mm][Aa][Xx]' @formats_glob['gsm'] = '*.[Gg][Ss][Mm]' @formats_glob['mtl'] = '*.[Mm][Tt][Ll]' @formats_glob['*'] = '*' end # Parse the command line arguments # @param args [command_line_arguments] # @return [Hash] def parse(args) parser = OptionParser.new do |opts| opts.banner = 'Usage: modown [options] Object' opts.on('-c', '--count COUNT', Integer, 'Number of different models you want') do |count| @options[:count] = count end opts.on('-f', '--format FORMAT', 'The file format you want.', "Supported formats are [#{@formats_glob.keys.join(',')}].", 'All files are stored if no FORMAT is provided') do |format| @options[:format] = @formats_glob[format] end opts.on('-h', '--help', 'Displays Help') do puts opts exit end end parser.parse!(args) raise '[ERROR] Please provide the object to search' if args.length == 0 raise "[ERROR] Please provide a valid format for the -f flag. Supported formats are [#{@formats_glob.keys.join(',')}]" if @options[:format].nil? @options[:search_term] = args[0] @options end end end
true
2eb3b09f31069687e49132df8c2be36d5874f854
Ruby
NotBadCode/SPOJandTimus
/SPOJ/Ruby/GETCORR.rb
UTF-8
99
3.34375
3
[]
no_license
f=0 6.times do a=gets.to_i if a%42==0 f+=1 end end if f==6 puts "Yes" else puts "No" end
true
d1d18a241c3a21113faff6226c1f669136534637
Ruby
mcolyer/config
/lib/config/patterns/directory.rb
UTF-8
930
2.71875
3
[ "MIT" ]
permissive
module Config module Patterns class Directory < Config::Pattern desc "The full path of the directory" key :path desc "The user that owns the directory" attr :owner, nil desc "The group that owns the directory" attr :group, nil desc "The octal mode of the directory, such as 0755" attr :mode, nil def describe "Directory #{pn}" end def create unless pn.exist? pn.mkdir changes << "created" end #stat = Config::Core::Stat.new(self, path) #stat.owner = owner if owner #stat.group = group if group #stat.mode = mode if mode #stat.touch if touch end def destroy if pn.exist? pn.rmtree changes << "deleted" end end protected def pn @pn ||= Pathname.new(path).cleanpath end end end end
true
fe5ee227825356885f650a79600c3929d4cbb953
Ruby
forkollaider/notepad
/read.rb
UTF-8
1,425
2.765625
3
[]
no_license
if (Gem.win_platform?) Encoding.default_external = Encoding.find(Encoding.local_charmap) Encoding.default_internal=__ENCODING__ [STDIN,STDOUT].each do |io| io.set_encoding(Encoding.default_external,Encoding.default_internal) end end require_relative 'post.rb' require_relative 'link.rb' require_relative 'memo.rb' require_relative 'task.rb' #id,limit,type require 'optparse' options = {} OptionParser.new do |opt| opt.banner = "Usage: read.rb [options]" opt.on('-h', 'Print this help') do puts opt exit end opt.on('--type POST_TYPE','какой тип постов показывать (по умолчанию любой)'){|o| options[:type] = o} opt.on('--id POST_ID','если задан id - показываем подробно только этот пост'){|o| options[:id] = o} opt.on('--limit NUMBER','сколько последних постов показать(по умолчанию все'){|o| options[:limit] = o} end.parse! result = Post.find(options[:limit], options[:type], options[:id]) if result.is_a?(Post) puts "Запись #{result.class.name}, id= #{options[:id]}" result.to_strings.each do |line| puts line end else print "| id\t| @type | @created_at\t\t\t| @text\t\t\t| @url\t\t| @due_date \t" result.each do |row| puts row.each do |element| print "| #{element.to_s.delete("\\n\\r")[0..40]}\t" end end end puts
true
10d32478889eed193d87b3d70c6fe03c60bbe4d6
Ruby
Gerula/interviews
/LeetCode/remote/house_robber.rb
UTF-8
1,310
3.515625
4
[ "MIT" ]
permissive
# You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. # # Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. # require 'test/unit' extend Test::Unit::Assertions def rob(nums) last = now = 0 pre = {} nums.each { |x| if last + x >= now max = last + x else max = now end last = now now = max } puts result.inspect return now end assert_equal(25, rob([1, 2, 3, 4, 5, 6, 7, 8, 9])) # No idea what was going on above.. # https://leetcode.com/submissions/detail/57718789/ # # Submission Details # 69 / 69 test cases passed. # Status: Accepted # Runtime: 108 ms # # Submitted: 1 minute ago # def rob(nums, hash = nil) hash ||= {} return 0 if nums.nil? || nums.empty? return hash[nums] if hash[nums] hash[nums] = [nums.first + rob(nums.drop(2), hash), rob(nums.drop(1), hash)].max end
true
e06b9b30baf7d0cd2d29132b3c0c71b5274624eb
Ruby
gardenzjd/JavaScriptCore-android-build
/script/prepare-icu.rb
UTF-8
626
2.546875
3
[]
no_license
#!/usr/bin/env ruby require "pathname" require "fileutils" require "shellwords" require_relative "lib/common" class PrepareIcuScript def main make_include_dir end def make_include_dir puts "make_include_dir" Dir.chdir(icu_dir.to_s) include_dir = icu_gen_dir + "include" if include_dir.exist? include_dir.rmtree end uc_dir = include_dir + "icuuc" uc_dir.mkpath FileUtils.cp_r((icu_dir + "common/unicode").to_s, uc_dir.to_s) i18n_dir = include_dir + "icui18n" i18n_dir.mkpath FileUtils.cp_r((icu_dir + "i18n/unicode").to_s, i18n_dir.to_s) puts "done" end end PrepareIcuScript.new.main
true
72c454fd1046bebe8805e080f1be63a9560df03a
Ruby
kasia-kaleta/imdb_lab
/models/star.rb
UTF-8
864
3.328125
3
[]
no_license
require_relative('../db/sql_runner') class Star attr_reader :id attr_accessor :first_name, :last_name def initialize(options) @id = options['id'].to_i if options['id'] @first_name = options['first_name'] @last_name = options['last_name'] end def save() sql = "INSERT INTO stars ( first_name, last_name ) VALUES ( $1, $2 ) RETURNING id" values = [@first_name, @last_name] star = SqlRunner.run( sql, values ).first @id = star['id'].to_i end def self.delete_all() sql = "DELETE FROM movies" SqlRunner.run(sql) end def update() sql = "UPDATE stars SET (first_name, last_name) = ($1, $2) WHERE id = $3 " values = [@first_name, @last_name, @id] SqlRunner.run(sql, values) end def self.all() sql = "SELECT * FROM stars" stars = SqlRunner.run(sql) result = stars.map { |star| Star.new(star)} return result end end
true
25bfee76f2d6b097d95a4982fb1a285df5e34715
Ruby
MMathew93/Ruby-Hangman
/game.rb
UTF-8
3,067
3.53125
4
[]
no_license
# frozen_string_literal: true require_relative 'display_text' require_relative 'game_saver' require 'yaml' # Class for the game class Game attr_accessor :guessed_letters, :random_word, :hidden_word, :misses include DisplayText include GameSaver def initialize @player_option = nil @random_word = nil end def start puts start_load player_option = gets.chomp.to_i until [1, 2, 3].include?(player_option) puts "That's not an option, please try again..." player_option = gets.chomp.to_i end player_selection(player_option) end def player_selection(mode) case mode when 1, 'y' initialize_game when 2 show_saved_files else puts quit_game exit end end def initialize_game random_word_from_dictionary @hidden_word = ['_'] * random_word.length @guessed_letters = [] @misses = 7 play_game end def play_game game_display player_input end # select a random word for game def random_word_from_dictionary dictionary = File.readlines('5desk.txt') cleaned_dictionary = dictionary.each(&:strip!).select { |word| word.length.between?(5, 12) } @random_word = cleaned_dictionary[rand(0..cleaned_dictionary.length)].downcase puts selected_word puts "#{random_word.length} letters, Good Luck!" end # display the current status of game def game_display puts "Number of misses left: #{misses}" p guessed_letters puts hidden_word.join end # get the player input def player_input puts guess_text input = gets.chomp.to_s.downcase until ('a'..'z').include?(input) || input == 'save' || input == 'exit' puts "That's not an option! Please guess a letter..." input = gets.chomp.to_s.downcase end player_options(input) end # check player input to see which option was input def player_options(input) case input when 'save' save_game game_over when 'exit' puts quit_game exit else verify_letter_guess(input) end end def verify_letter_guess(letter) if random_word.include?(letter) # update hidden word display random_word.chars.each_with_index do |element, i| @hidden_word[i] = letter if element == letter end else # check if guess has ben stated before guessed_letter_checker(letter) end # check if game is over and either end or repeat game_over end def guessed_letter_checker(letter) if guessed_letters.include?(letter) nil else guessed_letters << letter @misses -= 1 end end def game_over if hidden_word.join == random_word puts winner_text play_again elsif misses.zero? puts loser_text play_again else # allow player to guess again play_game end end def play_again input = gets.chomp.downcase until %w[y n].include?(input) puts "That's not an option!" input = gets.chomp.to_s.downcase end player_selection(input) end end
true
8029973494bb6e20678c6b055396bb8122d64ca0
Ruby
Try2Code/RussianNameGenerator
/getName
UTF-8
322
2.625
3
[]
no_license
#!/usr/bin/env ruby require "./lib/RussianNameGenerator.rb" if 0 == ARGV.size then ethnic = 'ALL' else ethnic = ARGV[0] unless RussianNameGenerator::VALID_ETHNICS.include?(ethnic) then warn "Could not find ethnic:#{ethnic}!" exit(1) end end ng = RussianNameGenerator.new ng.print(12,ethnic) #vim:ft=rb
true
aebc4228f03ca65c16dd9f91c08c702c27646c41
Ruby
jdcarey128/futbol
/lib/game_teams_tackles_manager.rb
UTF-8
720
2.71875
3
[]
no_license
class GameTeamsTacklesManager < GameTeamsManager attr_reader :game_teams, :stat_tracker def initialize(game_teams, stat_tracker) super(game_teams, stat_tracker) end def team_tackles(season) game_teams_by_season(season).reduce(Hash.new(0)) do |team_season_tackles, game| team_season_tackles[game.team_id] += game.tackles team_season_tackles end end def most_tackles(season) most_fewest_tackles(season, :max_by) end def fewest_tackles(season) most_fewest_tackles(season, :min_by) end def most_fewest_tackles(season, method_arg) @stat_tracker.fetch_team_identifier(team_tackles(season).method(method_arg).call do |team| team.last end.first) end end
true
bd993e1037233ff622a2aa97f3c15b62e34b3085
Ruby
bobjflong/mousey_revenge
/test/test_edible_sprite.rb
UTF-8
622
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'helper' class TestObject SPRITE_PATH = 'foo' include MouseyRevenge::EdibleSprite def grid MouseyRevenge::Grid.new(width: 5, height: 5, square_size: 10) end def position { x: 0, y: 0 } end def uuid '1234' end end class TestEdibleSprite < Test::Unit::TestCase setup do @edible = TestObject.new end should 'fallback to the normal sprite image path' do assert_equal 'foo', @edible.sprite_path end should 'use the alternative sprite image path when edible' do @edible.turn_into_cheese assert_equal '/../../assets/cheese.png', @edible.sprite_path end end
true
6945770d11f0d086b686a281a56e857365fc435d
Ruby
BivinsBrothers/castnotice
/app/models/incomplete_order.rb
UTF-8
1,177
2.53125
3
[]
no_license
require 'mysql_connection' IncompleteOrder = Struct.new(:order_id, :email, :code, :quantity) do def self.all(completed_order_ids=[]) conn = MysqlConnection.create completed_order_ids.unshift(0) ids = completed_order_ids.map(&:to_s).join(", ") sql = <<-SQL select o.order_id, o.user_email, od.model_number, od.quantity from ec_orderdetail od join ec_order o ON o.order_id=od.order_id where o.order_id NOT IN (#{ids}) order by o.order_id SQL all = conn.query sql if all.any? all.map do |r| new *r.values_at("order_id", "user_email", "model_number", "quantity") end end end def self.insert_on_db camps = Camp.all incomplete_orders =IncompleteOrder.all(CamperRegistration.pluck(:order_id)) unregistered = incomplete_orders ? incomplete_orders.group_by(&:code) : {} camps.each do |camp| if unregistered[camp.code].present? unregistered[camp.code].each do |order| CampersList.find_or_create_by(user_email: order.email) do |c| c.code = camp.code c.order_id = order.order_id end end end end end end
true
4a64e430c53c2905ef3ba0927c00a426e8bdbf94
Ruby
mouseed/zucker
/lib/zucker/array.rb
UTF-8
408
2.640625
3
[ "MIT" ]
permissive
require 'zucker' module Zucker Array = true end class Array def ^(other) # TODO: more efficient (self - other) + (other - self) end # can take an argument & block to be Rails compatible def sum(identity = 0, &block) # inject(:+) if block_given? map(&block).sum( identity ) else inject(:+) || identity end end def chrs self.pack 'C*' end end # J-_-L
true
232363f9516e1bb44f87a10e47491d0ab33c81f4
Ruby
Srossmanreich/Srossmanreich.github.io
/blogs/test2.rb
UTF-8
326
3.96875
4
[ "MIT" ]
permissive
def fibonacci(number) if number == 0 || number == 1 return number else (fibonacci(number - 1) + fibonacci(number - 2)) end end puts fibonacci(0) puts fibonacci(1) puts fibonacci(2) puts fibonacci(3) puts fibonacci(4) puts fibonacci(5) puts fibonacci(6) puts fibonacci(7) puts fibonacci(8) puts fibonacci(9)
true
09d940f75e14879aa3dec25f2e1b623362cb5a1c
Ruby
tschaffer1618/date_night
/lib/binary_search_tree.rb
UTF-8
942
3.4375
3
[]
no_license
class BinarySearchTree attr_reader :head_node def initialize @head_node = nil end def insert(score, movie) if @head_node.nil? @head_node = Node.new({score => movie}) else @head_node.insert(score, movie) end depth_of(score) end def depth_of(score, node = @head_node) @depth = 0 if score == node.score return @depth elsif score > node.score depth_of(score, node.right_node) @depth += 1 else depth_of(score, node.left_node) @depth += 1 end end def include?(score, node = @head_node) @value = true if score = node.score return @value elsif score > node.score if node.right_node.nil? @value = false else include?(score, node.right_node) end else if node.left_node.nil? @value = false else include?(score, node.left_node) end end @value end end
true
ef814d0c22b8fc4e2e6ca0d719e6f3db34cb0eb0
Ruby
jesus-sayar/contributors_mapping
/app/models/dashboard.rb
UTF-8
466
3.0625
3
[ "MIT" ]
permissive
class Dashboard attr_accessor :all_projects, :some_projects, :other_projects def initialize @all_projects = Project.all if @all_projects.any? @some_projects, @other_projects = @all_projects.each_slice((@all_projects.size/2.0).round).to_a else @some_projects = @other_projects = [] end end def some_projects @some_projects ? @some_projects : [] end def other_projects @other_projects ? @other_projects : [] end end
true
6f8050ac63e5e0438dea3d0b9dfa9299902db4cc
Ruby
szabokaroly/prep-course-exercises
/loop1/loop1.rb
UTF-8
209
3.59375
4
[]
no_license
loop do puts "Just keep printing..." break end # OR i = 0 loop do if i < 1 puts 'Just keep printing...' i += 1 end break if i == 1 end # OR 1.times do puts "Just keep printing..." end
true
ffabbd689d012c9c82d2356ee1a6af1416ada558
Ruby
williampowell92/bookmark-manager2
/spec/commander_data_spec.rb
UTF-8
1,754
2.765625
3
[]
no_license
require_relative '../lib/commander_data' describe CommanderData do let(:bookmark_class) { double :bookmark_class, new: nil} let(:connection) { double :database_connection, exec: rs } let(:id) { '1' } let(:title) { 'Google' } let(:url) { 'http://www.google.com' } let(:incorrect_title) { 'Boogle' } let(:incorrect_url) { 'http://www.goggle.com' } let(:rs) {[{'id' => id, 'title' => title, 'url' => url}]} describe '#all' do it 'returns urls from database' do described_class.all(bookmark_class, connection) expect(bookmark_class).to have_received(:new).with(id, title, url) end end describe '#valid' do it 'returns false for invalid url' do expect(described_class.valid?('Im not a url')).to be false end it 'returns true for a valid url' do expect(described_class.valid?('http://www.google.com')).to be true end end describe '#add' do it 'returns the sql stuff' do title = 'Google' url = 'http://google.com' described_class.add(title, url, connection) expect(connection).to have_received(:exec).with("INSERT INTO bookmarks(title, url) VALUES('#{title}', '#{url}')") end end describe '#delete' do it 'deletes the row' do described_class.add(title, url) described_class.delete(id, connection) expect(connection).to have_received(:exec).with("DELETE FROM bookmarks WHERE id = '#{id}'") end end describe '#update' do fit 'updates an entry' do described_class.add(incorrect_title, incorrect_url) described_class.update(id, title, url, connection) expect(connection).to have_received(:exec).with("UPDATE bookmarks SET title = '#{title}', url = '#{url}' WHERE id = '#{id}'") end end end
true
b04124020789981c591759de98247abedc9913af
Ruby
moneyadviceservice/dough
/lib/dough/forms/object_error.rb
UTF-8
1,217
2.6875
3
[ "MIT" ]
permissive
require 'active_model/model' module Dough module Forms class ObjectError include ActiveModel::Model attr_accessor :object, :field_name, :message, :counter, :prefix def ==(other) object == other.object && field_name == other.field_name && counter == other.counter && message == other.message end # Returns the error message with the field name and the message # as default. # If you need to display only the message without the field # name for a specific field then you will need to overwrite the # show_message_without_field_name? method: # # class MyCustomObjectErrorClass < Dough::Forms::ObjectError # def show_message_without_field_name? # field_name == :age # end # end # def full_message if show_message_without_field_name? message else "#{field_name} #{message}".humanize end end # Returns a unique identifier to be used on the summary hyperlink. # def unique_identifier "error-#{prefix}-#{counter}" end def show_message_without_field_name? false end end end end
true
7fdcc0c1738f0aec207bc1f8dbe31a570c8cc74f
Ruby
shi-mo/yukicoder
/0312.rb
UTF-8
291
3.765625
4
[]
no_license
require 'prime' n = gets.to_i if Prime.prime?(n) puts n exit 0 end if 0 == n % 3 puts 3 exit 0 end if 0 == n % 4 puts 4 exit 0 end if 0 == n % 2 && Prime.prime?(n/2) puts n/2 exit 0 end Prime.each(n) do |i| next if 2 == i next if 0 != n % i puts i exit 0 end
true
624f43e5c79c3be08fbcaeef8c9fc0a238e4866d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/cac65b405d9449d3a31a9179879b049d.rb
UTF-8
632
3.1875
3
[]
no_license
class Complement DNA_TO_RNA_COMPLEMENTS = {'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U'} DNA_NUCLEOTIDES = 'GCTA' RNA_NUCLEOTIDES = 'CGAU' def self.of_dna(dna) raise ArgumentError, 'Argument has not DNA nucleotides' unless dna.match(/[#{DNA_NUCLEOTIDES}]/) dna.gsub(/[#{DNA_NUCLEOTIDES}]/, DNA_TO_RNA_COMPLEMENTS) end def self.of_rna(rna) raise ArgumentError, 'Argument has not RNA nucleotides' unless rna.match(/[#{RNA_NUCLEOTIDES}]/) rna.gsub(/[#{RNA_NUCLEOTIDES}]/, DNA_TO_RNA_COMPLEMENTS.invert) end end
true
ad9209334b46f2e3c81d94e2713643eec39ee4ce
Ruby
RinatYaushev/Chat
/app/patterns/decorator.rb
UTF-8
794
3.765625
4
[]
no_license
module Decorator class ItemDecorator def initialize item @item = item end end class SwordDecorator < Decorator::ItemDecorator def price @item.price * 3 end def description @item.description + 'Sword' end end class BowDecorator < Decorator::ItemDecorator def price @item.price * 2 end def description @item.description + 'Bow' end end class Item attr_reader :price, :description def initialize @price = 10 @description = 'Item ' end end end # item = Decorator::Item.new # sword = Decorator::SwordDecorator.new(item) # puts "You can buy #{sword.description} for #{sword.price}" # bow = Decorator::BowDecorator.new(item) # puts "You can buy #{bow.description} for #{bow.price}"
true
53bf3223ea4a5f6434e0ec7f40c44eb9b446767c
Ruby
domke159/Hangman
/lib/hangman.rb
UTF-8
320
3.1875
3
[]
no_license
require_relative '../lib/dictionary.rb' require_relative '../lib/game.rb' loop do puts "\nWelcome to the Hangman Game \n" puts "\nStart new game (N) / Load previous game (L)?\n\n" gets.chomp.capitalize == 'N' ? Game.new : Game.load_game puts "\nPlay again (Y/N)?" exit unless gets.chomp.capitalize == 'Y' end
true
bd63acac8c3f791fd6e9378c966dd9951e7d8c1d
Ruby
rafaj777225/Cursocodeacamp
/Newbie/classComputer.rb
UTF-8
587
3.8125
4
[]
no_license
=begin Crea la clase Computer y agrega un método para cambiar y ver el color de la computadora. #test mac.color = "Platinum" p mac.color #=>"Platinum" =end #crea clase Computer class Computer #metodo de objeto para modificar o leer atributos attr_accessor :color #metodo constructor def initialize(color) #variable de instancia @color=color #fin de constructor end # fin de clase end mac=Computer.new("red") #metodo setter envia o asigna un nuevo valor al objeto mac.color = "Platinum" #metodo getter ya q ue solo lee la variable p mac.color
true
0be555c5bb5dec894ceca8865be53bdad6fc4eba
Ruby
DrDhoom/RMVXA-Script-Repository
/Vlue/after_battle_events.rb
UTF-8
2,468
2.59375
3
[ "MIT" ]
permissive
#After Battle Events v1.0 #----------# #Features: Process Troop Events when the player wins, escapes, or is defeated by setting a page # with the appropriate switch as it's conditional. # #Usage: Set your switches, set up your pages, run hog wild. # # Victory is called after all enemies are dead and before exp/gold/etc # Escape is called when the escape command is chosen and before the result # Abort is called when successfully escaping or manual battle abort # Defeat is called when all allies are dead # #~ #----------# #-- Script by: V.M of D.T # #- Questions or comments can be: # given by email: sumptuaryspade@live.ca # provided on facebook: http://www.facebook.com/DaimoniousTailsGames # All my other scripts and projects can be found here: http://daimonioustails.weebly.com/ # #--- Free to use in any project, commercial or non-commercial, with credit given # - - Though a donation's always a nice way to say thank you~ (I also accept actual thank you's) VICTORY_EVENT_SWITCH = 90 ESCAPE_EVENT_SWITCH = 91 ABORT_EVENT_SWITCH = 92 DEFEAT_EVENT_SWITCH = 93 module BattleManager class << self alias event_process_victory process_victory alias event_process_escape process_escape alias event_process_abort process_abort alias event_process_defeat process_defeat end def self.process_victory SceneManager.scene.play_victory_event return event_process_victory end def self.process_escape SceneManager.scene.play_escape_event return event_process_escape end def self.process_abort SceneManager.scene.play_abort_event return event_process_abort end def self.process_defeat SceneManager.scene.play_defeat_event return event_process_defeat end end class Scene_Battle def play_victory_event $game_switches[VICTORY_EVENT_SWITCH] = true process_end_event end def play_escape_event $game_switches[ESCAPE_EVENT_SWITCH] = true process_end_event end def play_abort_event $game_switches[ABORT_EVENT_SWITCH] = true process_end_event end def play_defeat_event $game_switches[DEFEAT_EVENT_SWITCH] = true process_end_event end def process_end_event while !scene_changing? $game_troop.interpreter.update $game_troop.setup_battle_event wait_for_message wait_for_effect if $game_troop.all_dead? process_forced_action break unless $game_troop.interpreter.running? end end end
true
77db3fb905b574b974fbf2114d38be314a172275
Ruby
wiggles66/oo-student-scraper-online-web-sp-000
/lib/animal.rb
UTF-8
90
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Animal def initialize end def self.new_pets(pets) puts pets end end
true
8c3089b47541231b54171ca88e4fd0a1e13b8021
Ruby
brendanthomas1/strategy_pattern
/app/models/motorcycle.rb
UTF-8
200
3.21875
3
[]
no_license
class Motorcycle attr_reader :top_speed def initialize(make, top_speed) @top_speed = top_speed end def accelerate_to_max_speed "VROOOM! Hit #{top_speed} on my motorcycle!" end end
true
3c226face6463a93ee172249bf557a642065a2ac
Ruby
betasve/notes-cli-app
/lib/tag.rb
UTF-8
1,097
3.25
3
[]
no_license
class Tag attr_accessor :id, :name, :notes def initialize(attrs={}) @id = attrs["id"] @name = attrs["attributes"]["name"] if attrs.has_key?("notes") && attrs["notes"] @notes = attrs["notes"].map do |note| { id: note["id"], title: note["attributes"]["title"] } end end end def show puts "Showing Tag #{name}".upcase puts "-" * 70 puts "Notes with that tag" puts "-" * 70 self.notes.each do |note| print " " + note[:id].to_s.ljust(6) print " " + note[:title].ljust(50) + "\n" end puts "No notes with that tag" if self.notes.empty? print "\n" puts "-" * 70 end def self.print_list(list) print " " + "ID".ljust(6) print " " + "Name".ljust(20) + "\n" puts "-" * 30 list.each do |tag| line = " " << tag.id.to_s.ljust(6) line << " " + tag.name.truncate(20).ljust(20) puts line end puts "No listings found" if list.empty? puts "-" * 30 end def to_s puts "#{self.id}".ljust(6) + "(Tag) #{self.name}".ljust(20) end end
true
b458d441e7ef0370d458634d9023e959926f9aa8
Ruby
VasaStulo/Ruby
/ruby/Lec5/bin/method_oviriding.rb
UTF-8
372
3.765625
4
[]
no_license
class Parent def hello #SELF ссылается на элемент класса(а-ля this в жабе) puts "Hello,my child! From #{self}" end def to_s 'parent' end end class Child < Parent def hello puts"hello from the Child" end def to_s 'child' end end parent = Parent.new parent.hello child =Child.new child.hello puts parent puts child
true
864f4a4e5c5137cce2ee0b8c65e165a21ea0a562
Ruby
substantial/sous-chef
/lib/sous-chef/node_builder.rb
UTF-8
529
2.59375
3
[ "MIT" ]
permissive
class SousChef::NodeBuilder include SousChef::NodeHelpers def initialize(name, collection_hash) @name = name @collection_hash = collection_hash end def build if node?(@collection_hash) SousChef::Node.new(@name, @collection_hash) else build_nodes end end private def build_nodes nodes = SousChef::Collection.new(@name) @collection_hash.each do |name, collection_hash| nodes[name] = SousChef::NodeBuilder.new(name, collection_hash).build end nodes end end
true
10366028fc0b18b0e59de288c041ea3823ecb125
Ruby
paulonegrao/codecore_out2015
/day_1/1019fb.rb
UTF-8
181
3.6875
4
[]
no_license
for i in 1..100 if i % 3 == 0 || i % 5 == 0 print "#{i} is a " if i % 3 == 0 print "FIZZ" end if i % 5 == 0 print "BUZZ" end puts "" end end
true
a42717145ce0d73b09d42d5523650d944244b8cc
Ruby
juani-garcia/POO_Ruby
/guias/tp10/ej1/html_tester.rb
UTF-8
1,019
3.15625
3
[]
no_license
require_relative 'plain_text' require_relative 'bold_text' require_relative 'italic_text' require_relative 'link_text' text = PlainText.new 'Hola' bold_text = BoldText.new(text) italic_text = ItalicText.new(text) puts bold_text # <b>Hola</b> puts italic_text # <i>Hola</i> bold_italic_text = BoldText.new(italic_text) puts bold_italic_text # <b><i>Hola</i></b> text.content = 'ITBA' puts bold_text # <b>ITBA</b> puts italic_text # <i>ITBA</i> puts bold_italic_text # <b><i>ITBA</i></b> link_text = LinkText.new(text, 'www.itba.edu.ar') link_bold_italic_text = LinkText.new(bold_italic_text, 'www.itba.edu.ar') bold_link_text = BoldText.new(link_text) puts link_text # <a href:"www.itba.edu.ar">ITBA</a> puts link_bold_italic_text # <a href:"www.itba.edu.ar"><b><i>ITBA</i></b></a> puts bold_link_text # <b><a href:"www.itba.edu.ar">ITBA</a></b> text.content = 'Ejemplo' puts link_bold_italic_text # <a href:"www.itba.edu.ar"><b><i>Ejemplo</i></b></a> puts bold_link_text # <b><a href:"www.itba.edu.ar">Ejemplo</a></b>
true
d5c06021d6458c0404dc51eae4b05ed5577aaa53
Ruby
pzol/deterministic
/spec/readme_spec.rb
UTF-8
1,129
2.921875
3
[ "MIT" ]
permissive
require 'spec_helper' include Deterministic::Prelude::Result Success(1).to_s # => "1" Success(Success(1)) # => Success(1) Failure(1).to_s # => "1" Failure(Failure(1)) # => Failure(1) Success(1).fmap { |v| v + 1} # => Success(2) Failure(1).fmap { |v| v - 1} # => Failure(0) Threenum = Deterministic::enum { Nullary() Unary(:a) Binary(:a, :b) } Deterministic::impl(Threenum) { def sum match { Nullary() { 0 } Unary() { |u| u } Binary() { |a, b| a + b } } end def +(other) match { Nullary() { other.sum } Unary() { |a| self.sum + other.sum } Binary() { |a, b| self.sum + other.sum } } end } describe Threenum do it "works" do expect(Threenum.Nullary + Threenum.Unary(1)).to eq 1 expect(Threenum.Nullary + Threenum.Binary(2, 3)).to eq 5 expect(Threenum.Unary(1) + Threenum.Binary(2, 3)).to eq 6 expect(Threenum.Binary(2, 3) + Threenum.Binary(2, 3)).to eq 10 end end
true
911b7c33358143e16d7057b1ce74dc9a63675c1f
Ruby
gl1002660/introtoprograming
/pythag therom calc.rb
UTF-8
101
3.46875
3
[]
no_license
puts "a?" a = gets.to_f puts "b?" b = gets.to_f x = (a**2) + (b**2) x = Math.sqrt(x) puts "c:" puts x
true
3dabcea542ab0b2d618322a0c6d627b72ef18c68
Ruby
kkozmo/toggler
/spec/models/user_spec.rb
UTF-8
1,680
2.734375
3
[]
no_license
require 'rails_helper' describe User do let(:user) { FactoryGirl.build(:user) } it "should have a valid name and email" do expect(user.valid?).to eq(true) end it "name should be present" do user.name = (' ') expect(user.valid?).to eq(false) end it "email should be present" do user.email = (' ') expect(user.valid?).to eq(false) end it "name should not be too long" do user.name = "a" * 51 expect(user.valid?).to eq(false) end it "email should not be too long" do user.email = "a" * 250 + "@gmail.com" expect(user.valid?).to eq(false) end it "email validation should accept valid addresses" do valid_addresses = %w[user@example.com USER@test.org user-foo@user.com user+foo@example.cn user.foo@example.jp] valid_addresses.each do |valid_address| user.email = valid_address puts "#{valid_address.inspect} should be valid" expect(user.valid?).to eq(true) end end it "email validation should reject invalid email addresses" do invalid_addresses = %w[user/me@example.com user.foo.com user@email. user@email+example.com] invalid_addresses.each do |invalid_address| user.email = invalid_address puts "#{invalid_addresses.inspect} should be invalid" expect(user.valid?).to eq(false) end end it 'email address should be unique' do duplicate_user = user.dup duplicate_user.email = user.email.upcase user.save expect(duplicate_user.valid?).to eq(false) end it "password should have a minimum length" do user.password = user.password_confirmation = "a" * 5 expect(user.valid?).to eq(false) end end
true
be31d88c0d15759e693046bccc1e54015e736442
Ruby
thibaudgg/rspactor
/lib/formatters/rspec_formatter.rb
UTF-8
657
2.515625
3
[ "MIT" ]
permissive
module RSpecFormatter def rspactor_title "RSpec results" end def rspactor_message(example_count, failure_count, pending_count, duration) message = "#{example_count} examples, #{failure_count} failures" if pending_count > 0 message << " (#{pending_count} pending)" end message << "\nin #{duration} seconds" message end # failed | pending | success def rspactor_image_path(failure_count, pending_count) icon = if failure_count > 0 'failed' elsif pending_count > 0 'pending' else 'success' end File.expand_path(File.dirname(__FILE__) + "/images/#{icon}.png") end end
true
b9a891d9e054114c9d14fc3d89940864084648ec
Ruby
dfitzgerald7/tweet-shortener-online-web-prework
/tweet_shortener.rb
UTF-8
824
3.8125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" # Write your code here. def dictionary my_hash = {"hello" => "hi", "to" => "2", "two" => "2", "too" => "2", "for"=> "4", "four"=> "4", "be" => "b","you" => "u", "at" => "@", "and" => "&"} end def word_substituter(tweet) tweet_array = tweet.split dictionary_array = dictionary long_words = dictionary_array.keys tweet_array.collect! do |word| if long_words.include?(word.downcase) word = dictionary_array[word.downcase] else word = word end end tweet_array.join(" ") end def bulk_tweet_shortener(array) array.each do |tweet| puts word_substituter(tweet) end end def selective_tweet_shortener(tweet) if tweet.length > 140 word_substituter(tweet) else tweet end end def shortened_tweet_truncator(tweet) tweet[0...140] end
true
870442b97051186434952d38c2785679e189fcf0
Ruby
emwads/advent-of-code
/day-09/day9.rb
UTF-8
1,580
3.28125
3
[]
no_license
class Day9 attr_accessor :num_players, :last_marble, :marbles, :player_scores, :current_player, :marble_to_play, :current_marble_idx def initialize(num_players, last_marble) @last_marble = last_marble @num_players = num_players @current_player = 0 @marble_to_play = 0 @current_marble_idx = 0 @player_scores = Hash.new(0) @marbles = [0] end def play! last_marble.times do |i| increment_turn end player_scores.values.max end def increment_turn @marble_to_play += 1 increment_player if marble_to_play % 23 == 0 play_twenty_third_marble else place_marble end print '.' if marble_to_play % 1000 == 0 end def place_marble placement_index = normalize_marble_idx(current_marble_idx + 2) left = marbles[0...placement_index] right = marbles[placement_index..-1] @marbles = left + [marble_to_play] + right @current_marble_idx = placement_index end def increment_player @current_player = (current_player + 1) % num_players end def play_twenty_third_marble marble_to_remove_idx = normalize_marble_idx(current_marble_idx - 7) marble_to_remove = @marbles.slice!(marble_to_remove_idx) @current_marble_idx = normalize_marble_idx(marble_to_remove_idx) player_scores[current_player] += (marble_to_play + marble_to_remove) end def normalize_marble_idx(idx) num_marbles = marbles.length (idx + num_marbles) % num_marbles end end # nope # t_start = Time.now # p Day9.new(418, 7076900).play! # t_end = Time.now # p t_end - t_start
true
b9504c48a8ad18304702afdb946b09643dd2ad84
Ruby
stogashi146/RubyPractice
/lankc_dict_step2.rb
UTF-8
710
3.625
4
[]
no_license
# n # s_1 # ... # s_n # m # p_1 a_1 # ... # p_m a_m # S # # 期待する出力 # S の受けた合計ダメージを出力してください。 # 末尾に改行を入れ、余計な文字、空行を含んではいけません。 # # 条件 # すべてのテストケースにおいて、以下の条件をみたします。 # # 入力例1 # 2 人数 # Kirishima # Kyoko # 2 攻撃回数 # Kyoko 受けた人 1 ダメージ数 # Kyoko 2 # Kyoko # # 出力例1 # 3 # 人数 n = gets.to_i # 登場人物 humans = {} n.times do name = gets.chomp humans[name] = 0 end # ダメージ m = gets.to_i m.times do a,b = gets.split(" ") humans[a] += b.to_i end word = gets.chomp puts humans[word]
true
8dc7dd99277351c43a85d3fa05636f69ae6795f7
Ruby
KennethCNg/Software_Prep
/Codefight/Linked_list.rb
UTF-8
1,219
3
3
[]
no_license
Remove K from List def removeKFromList(l, k) return nil if l.nil? fast_node = l.next slow_node = l until slow_node.value != k temp = slow_node.next slow_node.next = nil slow_node = temp l = slow_node return l if slow_node.nil? fast_node = fast_node.next end until fast_node.nil? if fast_node.value == k slow_node.next = fast_node.next else slow_node = slow_node.next end fast_node = fast_node.next end l end def isListPalindrome(l) return true if l.nil? list_length = 1 node = l # finds length until node.nil? list_length += 1 node = node.next end # reset node node = l # move to center of linked list second_head = node.next second_tail = node (list_length / 2).times do |i| second_head = second_head.next second_tail = second_tail.next end (list_length / 2.0).ceil.times do |i| temp = second_head.next second_head.next = second_tail second_tail = second_head second_head = temp end p l true end
true
b523c7d89c99d6072c7d5c0d53c9014e0a0a677d
Ruby
jnf/C3Projects--TaskListRails
/db/seeds.rb
UTF-8
1,233
2.875
3
[]
no_license
def random_time Time.at(rand * Time.now.to_i) end tasks = [ { name: "The First Task", description: "You should do this one first.", completed_at: random_time }, { name: "Go to Brunch", description: "Vittles is pretty good. Or Lola, if you got paid this week." }, { name: "Go to Lunch", description: "Rocco's or maybe just stay home and have a sandwich. :)", completed_at: random_time }, { name: "Go to Second Lunch", description: "Second Lunch is code for coffee and pastry. Yay pastries!" }, { name: "Play Video Games", description: "Dying Light is soooo scary, but it's a lot of fun.", completed_at: random_time }, { name: "High Five Somebody You Don't Know", description: "Stranger danger? Hardly. Express friendliness to those around you.", completed_at: random_time }, { name: "Plant Flowers", description: "Make the world a more beautiful place. Except for folks with allergies. Sorry allergy peeps. :(", completed_at: random_time }, { name: "Call Mom", description: "Seriously, it's been awhile." }, { name: "She worries, you know.", description: "I know, I know. I'll call her. Promise." }, { name: "Nap.", description: "YUS", completed_at: random_time } ] tasks.each do |task| Task.create task end
true
83cdb7d192f034625198c5fc3f7c761e0872317f
Ruby
Corsomk312/phase-0
/week-4/smallest-integer/my_solution.rb
UTF-8
771
4.15625
4
[ "MIT" ]
permissive
# Smallest Integer # I worked on this challenge [by myself, with: ]. # smallest_integer is a method that takes an array of integers as its input # and returns the smallest integer in the array # # +list_of_nums+ is an array of integers # smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+ # # If +list_of_nums+ is empty the method should return nil # Your Solution Below def smallest_integer(list_of_nums) i = 0 smallest_item = list_of_nums[0] if list_of_nums.length == 0 return nil else while i < list_of_nums.length item = list_of_nums[i] if item < smallest_item smallest_item = item end i += 1 end end return smallest_item end
true
91a8af25670db0eb60a22e26f9662e25c2792104
Ruby
ryanai3/repo
/rgit.rb
UTF-8
9,826
2.671875
3
[]
no_license
#!/usr/bin/env ruby require "rubygems" require 'thor' require_relative './Repo.rb' require 'pathspec' require 'pty' require 'pathname' #This Class functions as the CL utility for Rgit - handles #creating and calling Repo's in subdirectories #and user input class Rgit < Thor no_commands { def format_options(option_hash) result = "" option_hash.each { |k, v| key_str = " --#{k.to_s.gsub("_","-")}" case v # v is truthy in all cases except: nil, false when [true, false].include?(v) # it's a boolean result << key_str when String result << key_str << "=#{v}" when Fixnum result << key_str << "=#{v}" when Hash v.each { |key, val| result << key_str << " #{key}=#{val}" } end } result end } desc "add", "Add file contents to the index" method_option :dry_run, aliases: "n", type: :boolean, default: false method_option :verbose, aliases: "v", type: :boolean, default: false method_option :force, aliases: "f", type: :boolean, default: false method_option :interactive, aliases: "i", type: :boolean, default: false method_option :patch, aliases: "p", type: :boolean, default: false method_option :edit, aliases: "e", type: :boolean, default: false method_option :update, aliases: "u", type: :boolean, default: false method_option :no_ignore_removal, aliases: "A all", type: :boolean, default: false method_option :ignore_removal, aliases: "no-all", type: :boolean, default: false method_option :intent_to_add, aliases: "N", type: :boolean, default: false method_option :refresh, type: :boolean, default: false method_option :ignore_errors, type: :boolean, default: false method_option :ignore_missing, type: :boolean, default: false def add(*pathspecs) set_dir_info spec = PathSpec.new() spec.add(pathspecs) matched_files = spec.match_tree(@current_dir) headRepo = Repo.highest_above(@current_dir) headRepo.add(matched_files) end desc "branch", "List, create, or delete branches" def branch(branch_name = "") set_dir_info git_str = format_options(options) + branch_name repo = Repo.highest_above(@current_dir) puts(repo.branch(git_str)) end @init_descriptions = { long_desc: "This command creates an empty Git repository - basically a .git "\ "directory with subdirectories for objects, refs/heads, refs/tags, "\ "and template files. "\ "An initial HEAD file that references the HEAD of the master branch is "\ " also created."\ "\n\n"\ "If the $GIT_DIR environment variable is set then it specifies a path "\ "to use instead of ./.git for the base of the repository."\ "\n\n"\ "If the object storage directory is specified via the "\ "$GIT_OBJECT_DIRECTORY environment variable then the sha1 directories "\ "are created underneath - otherwise the default $GIT_DIR/objects "\ "directory is used."\ "\n\n"\ "Running git init in an existing repository is safe. It will not"\ "overwrite things that are already there. The primary reason for"\ "rerunning git init is to pick up newly added templates (or to move"\ "the repository to another place if --separate-git-dir is given).", quiet: "\n\t"\ "Only print error and warning messages; all other output will be suppressed."\ "\n\n", bare: "\n\t"\ "Create a bare repository. If GIT_DIR environment is not set, "\ "it is set to the current working directory."\ "\n\n", separate_git_dir: "\n\t"\ "Instead of initializing the repository as a directory to either "\ "$GIT_DIR or ./.git/, create a text file there containing the path "\ "to the actual "\ "\n\t"\ "repository. This file acts as filesystem-agnostic Git "\ "symbolic link to the repository."\ "\n\n\t"\ "If this is reinitialization, "\ "the repository will be moved to the specified path."\ "\n\n", shared: "\n\t"\ "Specify that the Git repository is to be shared amongst several users."\ "This allows users belonging to the same group to push into that repository."\ "\n\t"\ "When specified, the config variable \"core.sharedRepository\" is set so that"\ "files and directories under $GIT_DIR are created with the requested permissions."\ "\n\t"\ "When not specified, Git will use permissions reported by umask(2)."\ "\n\n", template: "\n\t"\ "Specify the directory from which templates will be used."\ "(See the \"TEMPLATE DIRECTORY\" section below.)"\ "\n\n", } desc "init", "Create an empty Rgit repository or reinitialize an existing one" long_desc @init_descriptions[:long_desc] method_option :quiet, { aliases: "q", type: :boolean, default: false, desc: @init_descriptions[:quiet] } method_option :bare, { type: :boolean, default: false, desc: @init_descriptions[:bare] } method_option :template, { type: :string, desc: @init_descriptions[:template] } method_option :separate_git_dir, { type: :string, desc: @init_descriptions[:separate_git_dir] } method_option :shared, { type: :string, enum: ["false", "true", "umask", "group", "all", "world", "everybody"], desc: @init_descriptions[:shared] } def init(directory = @current_dir) set_dir_info # If no dir is specified, use current dir, otherwise absolute path of specified dir directory = Pathname.new(directory).realpath # thor hands us a frozen hash, ruby-git messes with it, so we hand it a shallow copy of the hash Repo.init(directory, options.dup) puts("Initialized empty rGit repository in #{directory}") unless options[:quiet] end @clone_descriptions = { local: "When the repository to clone from is on a local machine, this flag bypasses the normal \"Git aware\" transport mechanism and clones the repository by making a copy of HEAD and everything under objects and refs directories. The files under .git/objects/ directory are hardlinked to save space when possible. If the repository is specified as a local path (e.g., /path/to/repo), this is the default, and --local is essentially a no-op. If the repository is specified as a URL, then this flag is ignored (and we never use the local optimizations). Specifying --no-local will override the default when /path/to/repo is given, using the regular Git transport instead.", bare: "" } desc "clone", "Clone a repository into a new directory" long_desc @clone_descriptions[:long_desc] method_option :local, { aliases: "l", type: :boolean, desc: @clone_descriptions[:local], } method_option :no_hardlinks, { type: :boolean, desc: @clone_descriptions[:no_hardlinks], } method_option :shared, { type: :boolean, desc: @clone_descriptions[:shared], } method_option :reference, { type: :string, desc: @clone_descriptions[:reference], } method_option :dissociate, { type: :boolean, desc: @clone_descriptions[:dissociate], } method_option :quiet, { aliases: "q", type: :boolean, desc: @clone_descriptions[:quiet], } method_option :verbose, { aliases: "v", type: :boolean, desc: @clone_descriptions[:verbose], } method_option :progress, { type: :boolean, desc: @clone_descriptions[:progress], } method_option :no_checkout, { aliases: "n", type: :boolean, desc: @clone_descriptions[:no_checkout], } method_option :bare, { type: :boolean, desc: @clone_descriptions[:bare], } method_option :mirror, { type: :boolean, desc: @clone_descriptions[:mirror], } method_option :branch, { aliases: "b", type: :string, desc: @clone_descriptions[:branch], } method_option :upload_pack, { aliases: "u", type: :boolean, desc: @clone_descriptions[:upload_pack], } method_option :template, { type: :string, desc: @clone_descriptions[:template], } method_option :config, { aliases: "c", type: :hash, desc: @clone_descriptions[:config], } method_option :depth, { type: :numeric, desc: @clone_descriptions[:depth], } method_option :single_branch, { type: :boolean, desc: @clone_descriptions[:single_branch], } method_option :separate_git_dir, { type: :string, desc: @clone_descriptions[:separate_git_dir], } def clone(repository, directory = @current_dir) directory = Pathname.new(directory).realpath opt_str = format_options(options) Repo.clone(repository, directory, opt_str) end desc "git", "Calls vanilla git with your args" def git(*args) sys_call_git(*args) end desc "pull", "Pulls TODO" def pull end desc "diff", "diffs TODO" def diff(*args) # Git does something very nice with diff and pathspecs, it simply doesn't do anything for # the pathspecs referring to git repositories inside the current one. set_dir_info repo = Repo.highest_above(@current_dir) repo.diff(*args) end desc "bind", "binds a set of commits together into one commit" def bind #TODO end desc "unbind", "unbinds a set of commits" def unbind end desc "test me", "pls" def test_me(notRequired="") end no_commands { def sys_call_git(*args) args_string = args.map { |i| i.to_s }.join(" ") system(' git ' + args_string) end def set_dir_info @current_dir = Pathname.pwd end } end Rgit.start
true
d3b05c65cfc10b953640d5febc5b8fe5b54f74ed
Ruby
vokomod/RubyLessons
/lesson23/app.rb
UTF-8
1,774
2.65625
3
[ "MIT" ]
permissive
require 'rubygems' require 'sinatra' get '/' do erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>" end get '/about' do erb :about end get '/visit' do erb :visit end get '/contacts' do erb :contacts end get '/message' do erb :message end post '/visit' do @userName = params[:userName] @userPhoneNumber = params[:userPhone] @dateAndTime = params[:userDate] @barber = params[:barber] @color = params['colorpicker-shortlist'] @title = "Hello #{@userName}, you are welcome!!" @message = "Your phone number #{@userPhoneNumber} is correct? We are waitnig for you at #{@dateAndTime} You want to color your hair in #{@color}" fileDataInput = File.open './public/users.txt', 'a' fileDataInput.write "User: #{@userName}, phone: #{@userPhoneNumber}, date: #{@dateAndTime}, barber: #{@barber}, color: #{@color}\n" fileDataInput.close erb :message end post '/contacts' do @emailFeedback = params[:emailFeedback] @textFeedback = params[:textFeedback] @title = "Thank you!" @message = "Your feedback is very important for us" fileDataInput = File.open './public/feedback.txt', 'a' fileDataInput.write "User: #{@emailFeedback}, text: #{@textFeedback}\n" fileDataInput.close erb :message end get '/admin' do erb :admin end post '/admin' do @adminPassword = params[:adminPassword] if @adminPassword.strip == "zzz" @title = "Secret place" @message = "Orders are <a href='/users.txt'>here</a> and feedback is <a href='/feedback.txt'>here</a>" erb :message else @message = "<a href='http://www.fuck.off'>go to mommy!</a>" @title = "Ooooh, cool xakep!" erb :message end end
true
c4e277604ea19ceb78567c70b185ae264a273ff8
Ruby
singsang2/ruby-enumerables-hash-practice-green-grocer-lab-prework
/grocer.rb
UTF-8
1,245
3.34375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" def consolidate_cart(cart) hash_cart = Hash.new cart.each do |item| #binding.pry hash_cart[item.keys[0]] = item.values[0] if hash_cart[item.keys[0]][:count] != nil hash_cart[item.keys[0]][:count] += 1 else hash_cart[item.keys[0]][:count] = 1 end end hash_cart end def apply_coupons(cart, coupons) coupons.each do |item| if cart[item[:item]] != nil disc_num = cart[item[:item]][:count]/item[:num] if disc_num != 0 #binding.pry cart[item[:item]][:count] -= disc_num*item[:num] cart[item[:item]+" W/COUPON"] = {:price => item[:cost]/item[:num],:clearance => cart[item[:item]][:clearance],:count => disc_num*item[:num]} end #cart.delete(item[:item]) if cart[item[:item]][:count] == 0 end end cart end def apply_clearance(cart) cart.keys.each do |item| #binding.pry cart[item][:price] = (0.8*cart[item][:price]).round(2) if cart[item][:clearance] end cart end def checkout(cart, coupons) cart = consolidate_cart(cart) cart = apply_coupons(cart, coupons) cart = apply_clearance(cart) total = 0 cart.keys.each {|n| total += cart[n][:price]*cart[n][:count]} total > 100 ? (0.9*total).round(2) : total end
true
13698021f9b0dfaa40d0dae042be075adb956305
Ruby
ErdemOzgen/leetcode
/ruby/1-Two-Sum.rb
UTF-8
166
3.28125
3
[ "MIT" ]
permissive
def two_sum(nums, target) hash = {} nums.each_with_index do |num, idx| return [hash[num], idx] if hash.key? num hash[target - num] = idx end nil end
true
5b364b032cc6d898e95ee4ef8b2e650540f95c43
Ruby
KenDuyNguyen/AppAcademy_Projects
/W2D2/piece.rb
UTF-8
2,177
3.9375
4
[]
no_license
require "singleton" class Piece def initialize(color, pos, board) @pos = pos @color = color @board = board end def to_s " o " end end class NullPiece < Piece include Singleton end class King < Piece include SteppingPiece def initialize(color, pos, value = 100) super @value = value end def move_dir direction = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] moves(direction) end end class Queen < Piece include SlidingPiece def initialize(color, pos, value = 9) super @value = value end def move_dir direction = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]] moves(direction) end end class Rook < Piece include SlidingPiece def initialize(color, pos, value = 5) super @value = value end def move_dir all_moves = [[1, 0], [0, 1], [-1, 0], [0, -1]] moves(all_moves) end end class Bishop < Piece include SlidingPiece def initialize(color, pos, value = 3) super @value = value end def move_dir all_moves = [[-1, -1], [-1, 1], [1, 1], [1, -1]] moves(all_moves) end end class Knight < Piece include SteppingPiece def initialize(color, pos, value = 3) super @value = value end def move_dir all_moves = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]] moves(all_moves) end end class Pawn < Piece def initialize(color, pos, value = 1) super @value = value end def moves end end module SlidingPiece def moves(direction) available_moves = [] direction.each do |dir| temp = [self.pos[0] + dir[0], self.pos[1], dir[1]] while temp.in_range? available_moves << temp temp = [temp[0] + dir[0], temp[1] + dir[1]] end end available_moves end def in_range? (0..7).cover?(self[0]) && (0..7).cover?(self[1]) end end module SteppingPiece def moves(direction) available_moves = [] direction.each do |dir| available_moves << [self.pos[0] + dir[0], self.pos[1] + dir[1]] end available_moves end end
true
981628b5e1348425eb538d58dbf51063301f2af5
Ruby
milandhar/mod5-project-backend
/app/models/project.rb
UTF-8
4,044
2.53125
3
[]
no_license
require 'dotenv/load' class Project < ApplicationRecord belongs_to :organization, optional: true belongs_to :theme, optional: true belongs_to :country, optional: true has_many :user_starred_projects has_many :users, through: :user_starred_projects validates :title, presence: true validates :image_url, presence: true validates :project_link, presence: true validates :theme_str_id, presence: true def self.queryActiveProjects(params) api_key = ENV['API_KEY'] if params[:nextProject] url = "https://api.globalgiving.org/api/public/projectservice/all/projects/active?api_key=#{api_key}&nextProjectId=#{params[:nextProject]}&status=active" else url = "https://api.globalgiving.org/api/public/projectservice/all/projects/active?api_key=#{api_key}&status=active" end json = JSON.parse(RestClient.get url, {content_type: :json, accept: :json}) end def self.fetch(params) #Add a check to see if Project count < 8000. Added bc of Heroku 10k row limit if (Project.all.count + Organization.all.count) < 8000 @projects = [] json = self.queryActiveProjects(params) NormalizeCountry.to = :alpha3 json.first[1]["project"].each do |project| if(project["organization"] && project["organization"]["themes"] && project["organization"]["countries"]) @project = Project.find_or_create_by( funding: project["funding"], goal: project["goal"], image_url: project["imageLink"], latitude: project["latitude"], longitude: project["longitude"], long_term_impact: project["longTermImpact"], activities: project["activities"], need: project["need"], gg_organization_id: project["organization"]["id"], gg_project_id: project["id"], project_link: project["projectLink"], status: project["status"], summary: project["summary"], theme_str_id: project["themeName"], title: project["title"] ) # add donation options to @project if project["donationOptions"] project["donationOptions"]["donationOption"].each do |option| if option["description"] && option["amount"] @project.donation_descriptions.push(option["description"]) @project.donation_amounts.push(option["amount"]) end end end if (!Organization.find_by(Gg_organization_id: project["organization"]["id"])) #find or create organization here @organization = Organization.create( Gg_organization_id: project["organization"]["id"], city: project["organization"]["city"], country: project["organization"]["country"], mission: project["organization"]["mission"], name: project["organization"]["name"], url: project["organization"]["url"] ) @project.organization = @organization @organization.save else @organization = Organization.find_by(Gg_organization_id: project["organization"]["id"]) @project.organization = @organization end @theme = Theme.find_or_create_by(name: project["themeName"]) @theme.save @project.theme = @theme @country = Country.find_by(name: project["country"]) @country.save @project.country = @country @project.save @projects << @project end end # Check to see if there are still more projects in the GlobalGiving API # If so --> output the next project ID to the console, and fetch the next list of projects from the API using the next projectId if json["projects"]["hasNext"] params[:nextProject] = json["projects"]["nextProjectId"] puts json["projects"]["nextProjectId"] self.fetch(params) end end end end
true
dc69ca99328f32f88b5eba7c8bac817544f15fe5
Ruby
imsaar/saarisms
/rmu-2010/lib/text_edit_imsaar.rb
UTF-8
816
3.0625
3
[]
no_license
# Ruby Mendicant University Entrance Exam Solution by Ali Rizvi # http://github.com/rmu/rmu-entrance-exam-2010 module TextEditor class Document def initialize @contents = "" @commands = [] @reverted = [] end def contents @contents = "" @commands.each {|command| command.call} @contents end def add_text(text, position=-1) execute { @contents.insert(position, text) } end def remove_text(first=0, last=contents.length) execute { @contents.slice!(first...last) } end def execute(&block) @commands << block @reverted = [] end def undo return if @commands.empty? @reverted << @commands.pop end def redo return if @reverted.empty? @commands << @reverted.pop end end end
true