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
6636a09f35e8358299097e245191ebd0f7552041
Ruby
SlicingDice/slicingdice-ruby
/lib/rbslicer/core/requester.rb
UTF-8
1,732
2.765625
3
[ "MIT" ]
permissive
# coding: utf-8 require 'net/https' require 'uri' require 'json' module Core # Public: Make full post request class Requester def initialize(timeout) @timeout = timeout end # Public: Make a HTTP request. # # url(String) - A url String to make request # headers(Hash) - A Hash with our own headers # req_type(String) - The request type, should be get, post, put or delete # data(Hash) - A Hash to send in request # # Returns a object with result request def run(url, headers, req_type, data = nil, sql = false) begin uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) if uri.port.to_s == "443" http.use_ssl = true end http.read_timeout = @timeout http.verify_mode = OpenSSL::SSL::VERIFY_NONE requester = nil parsed_data = data if !sql parsed_data = data.to_json end if req_type == "post" requester = Net::HTTP::Post.new(uri.request_uri, initheader = headers) requester.body = parsed_data elsif req_type == "put" requester = Net::HTTP::Put.new(uri.request_uri, initheader = headers) requester.body = parsed_data elsif req_type == "get" requester = Net::HTTP::Get.new(uri.request_uri, initheader = headers) elsif req_type == "delete" requester = Net::HTTP::Delete.new(uri.request_uri, initheader = headers) end http.request(requester) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e raise e end end end end
true
5461ae81465daa118a7178ff9067d00d45835fa7
Ruby
carolgreene/collections_practice-v-000
/collections_practice.rb
UTF-8
665
3.78125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort.reverse end def sort_array_char_count(array) array.sort{|left, right| left.length <=> right.length} end def swap_elements(array) array[1], array[2] = array[2], array[1] return array end def reverse_array(array) array.reverse end def kesha_maker(array) array.each do |name| name.slice!(2) name.insert(2, "$") end end def find_a(array) array.select { |str| str.start_with?('a')} end def sum_array(array) array.inject(0) { |sum, x| sum + x } end def add_s(array) array.each_with_index do |word, i| if word[i] != word[1] word << "s" end end end
true
e7b1e66fd8c920b5548beda47c50360682151500
Ruby
khanhhuy288/Ruby-Aufgaben
/A4-Relationen und Abbildungen/RelationenGenerator.rb
UTF-8
1,453
3.5625
4
[]
no_license
require './Relation' class RelationenGenerator def RelationenGenerator.generiere_relation(set_a,set_b,k) # create new Relations from 2 Sets relation = Relation.new(set_a, set_b) # return empty Relation if k is not valid (k > max_tupels) max_tupels = set_a.size * set_b.size raise 'k muss <= maximale Anzahl der Tupels sein.' if k > max_tupels ary_a = set_a.to_a() ary_b = set_b.to_a() a_size = set_a.size() b_size = set_b.size() # add k Tupels to Relation while relation.size < k # get 1 random element from each Set to make a Tupel relation.add(Tupel.new(ary_a[ rand(a_size)], ary_b[rand(b_size)])) end return relation end def RelationenGenerator.generiere_abbildung(set_a,set_b) # create new function from 2 Sets relation = Relation.new(set_a, set_b) # Abbildung: von jedem a muss genau ein Pfeil ausgehen, also linksvollständig und rechtseindeutig set_a.each { |a| rand_b = rand(set_b.size) relation.add(Tupel.new(a, set_b.to_a[rand_b])) } return relation end end # set_a = Set.new([1, 2, 3]) # set_b = Set.new([4, 5, 6, 7]) # # relation_1 = Relation.new(set_a, set_b) # relation_2 = Relation.new(set_a, set_b) # relation_1.add(Tupel.new(1,5)).add(Tupel.new(2,7)).add(Tupel.new(3,4)) # relation_2.add(Tupel.new(1,5)).add(Tupel.new(3,4)).add(Tupel.new(2,7)) # puts relation_1 # puts relation_2 # puts relation_1 == relation_2
true
9078929a9d794029aeb42100bae288a11b22c924
Ruby
louiehchen/phase-0-tracks
/ruby/house.rb
UTF-8
2,020
4.34375
4
[]
no_license
# HOUSE MAKER # Allow user to create a house, # then add rooms, # then add items # House can have up to 5 rooms #Room can have an unlimited number of items def add_room_to_house!(house, room_name) # house becomes a hash if house.keys.length == 5 # limits number of rooms to 5. Rooms are keys. false else house[room_name] = [] true end end def add_item_to_room!(house, room_name, item_name) house[room_name] << item_name end house = {} # USER INTERFACE def print_house(house) puts "----------------------" puts "Current house configuration" house.keys.each_with_index do |room_name, index| # Assigns index number to each room puts "#{index} - #{room_name}: #{house[room_name]}" # house[room_name] turns into item end puts "----------------------" end # Let user add rooms can_add_rooms = true # Stop loop when room cannot be added while can_add_rooms # Get a room name from the user puts "Type the name of a room to add (or type 'done'):" room_name = gets.chomp # If the user is done, stop loop break if room_name == 'done' # Otherwise, add the room to the house can_add_rooms = add_room_to_house!(house, room_name) print_house(house) end # Let the user add items to rooms # In an infinite loop: loop do # Ask the user for the number of the room they want to add items to puts "Enter the number of the room to add an item to (or type 'done'):" inputted_index = gets.chomp # If user is done, break break if inputted_index == 'done' # Otherwise, add the item to the room room_index = inputted_index.to_i puts "Enter the item to add: " item_to_add = gets.chomp add_item_to_room!(house, house.keys[room_index], item_to_add) # print new house configuration print_house() end # Stop loop when rooms cannot be added # TEST CODE =begin rooms = ["living room", "bedroom", "bathroom", "kitchen", "bedroom2", "bedroom3"] rooms.each do |room| room_added = add_room_to_house!(house, room) add_item_to_room!(house, room, "cat") if room_added end print_house(house) =end
true
5cbf5edbab4d02a4c5a242845aa1f0979fa8501f
Ruby
RomanADavis/challenges
/exercism/ruby/bracket-push/bracket_push.rb
UTF-8
478
3.078125
3
[]
no_license
class Brackets OPEN_TO_CLOSE = {'(' => ')', '[' => ']', '{' => '}'} def self.paired?(string) memory = [] string.each_char do |char| memory << char if OPEN_TO_CLOSE.keys.include? char if OPEN_TO_CLOSE.values.include? char # If I don't put the parenthesis here it doesn't work; no idea why. OPEN_TO_CLOSE[memory[-1]] == char ? memory.pop : (return false) end end memory.empty? end end module BookKeeping VERSION = 3 end
true
d44f1f4c846d5228158f6cb2457264081b4596e2
Ruby
GBJim/ptt_push_demp
/data_preprocess/preprocessor.rb
UTF-8
2,399
2.8125
3
[]
no_license
require 'csv' require 'set' CSV.foreach(filename, :headers => true) do |row| User.create!(row.to_hash) end filename = "data_preprocess/pushList.csv" CSV.foreach(filename, :headers => true) do |row| user = User.find_or_create_by(name: row[:user_name]) user.pushes.create(body: row[:body]) user.save end usersSet = Set.new users_to_id = {} user_names = [] columns = [:name] f = File.open("data_preprocess/sample_result.txt") f.each_line do |line| row = line.strip.split(",") userA = row[0] userB = row[1] usersSet.add(userA) usersSet.add(userB) end user_to_id = {} pushes = [] usersSet.each do |user_name| user = User.find_by(name: user_name) user_to_id[user_name] = user.id unless user.nil? end similarities = [] CSV.foreach('data_preprocess/sample_result.txt', :headers => true) do |row| userA = row.to_hash['userA'] userB = row.to_hash['userB'] score = row.to_hash['score'] user_id = user_to_id[userA] similarity = Similarity.new({user_id:user_id, score: score, partner: userB}) similarities << similarity end puts similarities.length Similarity.import similarities usersSet = Set.new users_to_id = {} user_names = [] columns = [:name] f = File.open("data_preprocess/sample_result.txt") f.each_line do |line| row = line.strip.split(",") userA = row[0] userB = row[1] usersSet.add(userA) usersSet.add(userB) end user_to_id = {} pushes = [] usersSet.each do |user_name| user = User.find_by(name: user_name) user_to_id[user_name] = user.id unless user.nil? end f = File.open("data_preprocess/pushes.txt") f.each_line do |line| row = line.strip.split("\t") user = row[0] if user_to_id.has_key?(user) body = row[1] user_id = user_to_id[user] pushes << Push.new({user_id: user_id, body: body}) end end Push.import pushes =begin CSV.open("data_preprocess/pushList.csv", "w") do |csv| csv << ["user_name", "body"] f = File.open("data_preprocess/pushes.txt") f.each_line do |line| row = line.strip.split("\t") user = users_to_id[row[0]] body = row[1] csv << [user, body] end end usersSet = Set.new CSV.foreach('sample_result.txt', :headers => true) do |row| userA = row.to_hash['userA'] userB = row.to_hash['userB'] score = [''] usersSet.add(userA) usersSet.add(userB) end puts usersSet.length CSV.open("userList.csv", "w") do |csv| csv << ["user"] usersSet.each do |user| csv << [user] end =end
true
8b5b7b4d6639542150a134b0d4b529839d738965
Ruby
justindelatorre/rb_101
/small_problems/easy_3/easy_3_10.rb
UTF-8
532
4.625
5
[]
no_license
=begin Write a method that returns true if its integer argument is palindromic, false otherwise. A palindromic number reads the same forwards and backwards. Examples: palindromic_number?(34543) == true palindromic_number?(123210) == false palindromic_number?(22) == true palindromic_number?(5) == true =end def palindromic_number?(num) num.to_s == num.to_s.reverse end puts palindromic_number?(34_543) == true puts palindromic_number?(123_210) == false puts palindromic_number?(22) == true puts palindromic_number?(5) == true
true
b6f1a00a355b9f4346e5fb313bc2b61b66c94c83
Ruby
andresgap/wc18
/app/modules/position_board.rb
UTF-8
1,289
2.65625
3
[ "MIT" ]
permissive
class PositionBoard attr_reader :leaderboard def initialize(leaderboard = nil) @leaderboard = leaderboard end def members @members ||= positions.sort_by { |position| [position.index, position.name.downcase] } end def title @title ||= leaderboard ? leaderboard.name : 'general' end private def positions @positions ||= prediction_sets.map { |prediction_set| OpenStruct.new(position_row(prediction_set)) } end def users @users ||= leaderboard ? leaderboard.users.active.includes(:prediction_set).all : User.active.includes(:prediction_set).all .reject { |user| user.prediction_set.points == 0 } end def prediction_sets @prediction_sets ||= PredictionSet.where(tournament: gc19).includes(:user).all #.reject { |prediction_set| prediction_set.points == 0 } end def position_row(prediction_set) { name: prediction_set.user.name, picture: prediction_set.user.picture, points: prediction_set.points, index: order_points.index(prediction_set.points) + 1, prediction_set: prediction_set } end def order_points @order_points ||= prediction_sets.map(&:points).sort.reverse.uniq end def gc19 @gc19 ||= Tournament.where(code: 'GC19').first end end
true
06d997c31bd3a577bd5a335ef2c45b882254fc4c
Ruby
JMazzy/134141414kjkjfksjafsakfjl
/lib/battle_bot.rb
UTF-8
1,950
3.5625
4
[]
no_license
class BattleBot attr_reader :name, :health, :enemies, :weapon, :dead @@count = 0 def self.count @@count end def initialize(name,health=100) raise ArgumentError, "no name given" if name == nil @name = name @health = health @weapon = nil @enemies = [] @dead = false @@count += 1 end def dead? !!@dead end def has_weapon? !!@weapon end def pick_up(weapon) raise ArgumentError, "not a weapon" if !weapon.is_a?(Weapon) raise ArgumentError, "weapon already wielded" if weapon.bot != nil if @weapon == nil weapon.bot = self @weapon = weapon else nil end end def drop_weapon @weapon.bot = nil @weapon = nil end def take_damage(damage) raise ArgumentError, "not a Fixnum" if !damage.is_a? Fixnum if @health - damage >= 0 @health -= damage else @health = 0 @dead = true @@count -= 1 end @health end def heal if !dead? if @health + 10 <= 100 @health += 10 else @health = 100 end @health end end def attack(enemy) raise ArgumentError, "enemy is not a BattleBot" if !enemy.is_a?(BattleBot) raise ArgumentError, "cannot attack yourself" if enemy == self raise ArgumentError, "no weapon" if @weapon == nil enemy.receive_attack_from(self) end def receive_attack_from(attacking_bot) raise ArgumentError, "enemy is not a BattleBot" if !attacking_bot.is_a?(BattleBot) raise ArgumentError, "cannot attack yourself" if attacking_bot == self raise ArgumentError, "attacking bot is unarmed" if attacking_bot.weapon == nil take_damage(attacking_bot.weapon.damage) @enemies << attacking_bot unless @enemies.include?(attacking_bot) defend_against(attacking_bot) end def defend_against(enemy) if !dead? && has_weapon? attack(enemy) end end def has_weapon? !!@weapon end end
true
b868a5b4ef72846788aa789ecb3571b9f159388e
Ruby
0100354256/Prct12M17
/lib/Prct12M17/threads.rb
UTF-8
1,218
2.859375
3
[ "MIT" ]
permissive
require "Prct12M17/naranjero.rb" Thread.abort_on_exception = true class Threads attr_reader :naranjero def initialize(mutex, cv, naranjero) @mutex = mutex @cv = cv @naranjero = naranjero end def ejecucion consumidor = Thread.new do until (@naranjero.edad == Naranjero::EDAD_MUERTE) tiempo = rand(0..5) print "Orange picker going to sleep for #{tiempo}\n" sleep(tiempo) print "Orange picker woke up after sleeping for #{tiempo}\n" @mutex.synchronize do @naranjero.recolectar_una print "Orange picker waiting patiently...\n" if (@naranjero.edad < Naranjero::EDAD_MUERTE) @cv.wait(@mutex) end end end end productor = Thread.new do until (@naranjero.edad == Naranjero::EDAD_MUERTE) tiempo = rand(0..5) print "Age increaser going to sleep for #{tiempo}\n" sleep(tiempo) print "Age increaser woke up after sleeping for #{tiempo}\n" @mutex.synchronize do @naranjero.uno_mas print "Age increaser increased the age\n" @cv.signal end end end [consumidor, productor] end end
true
36fadc54f06f5fd9d4f4c8cf14dc85c27b8548f0
Ruby
make-void/reactive_opal
/app.rb
UTF-8
1,145
2.796875
3
[]
no_license
# required: opal + browser `self.$require("browser");` `self.$require("browser/http");` class State @@state = {} def self.all @@state end def self.all=(state) @@state = state end end # env.rb: initial state State.all = { line: 1 } # actions def add_element line.append_to $document["container"] end class Actions def self.handle_click -> do State.all = { line: State.all[:line]+1 } add_element end end end # lib def apply_view_event_bindings(app_container) # real code should scan views and apply listeners when finds on-click="handl" app_container.on :click, &Actions.handle_click end # view partial def line DOM { div.info { span.red "added line: #{State.all[:line]}" } } end # view (main view atm) $document.ready do app_container = $document["container"] # router / controller # # if route == "/" line.append_to app_container # else # info_view.append_to app_container # end apply_view_event_bindings app_container end # notes: # Browser::HTTP.get "/test.json" do # on :success do |res| # alert res.json.inspect # end # end
true
d656f1d3d22a0d075931ac5ae722c601d1d7c3bd
Ruby
tiy-austin-ror-jan2015/Third-Day
/blackjack.rb
UTF-8
1,804
4.25
4
[]
no_license
# Blackjack puts "Let's play Blackjack!" puts "-" * 20 class Blackjack def initialize @player = player.new # You are calling .new on a variable (which has not been set, so it is nil) and not on the Class - JH @dealer = dealer.new # You are calling .new on a variable (which has not been set, so it is nil) and not on the Class - JH end #<< You're not ending your Blackjack class, which means the rest of the file is *within* that class. class Gambler attr_accessor :cards, :bank def initialize @cards = Deck.new @bank = 100 end end class Deck attr_accessor :cards def initialize @cards = ((1..11).to_a * 4).shuffle #Missing a few cards in your deck - JH end def count @cards.count end def shuffle @cards.shuffle end def draw @cards.shift end end end # << This is the end of your Blackjack class - JH # Player draws 2 cards and dealer draws 2 cards # Each round will cost player $100 def play # << This method doesnt exist in any class - JH while @player.cards.count > 0 do # @player is going to be not defined out here - JH first_card = @player.cards.draw second_card = @player.cards.draw round = @bank - 10 puts "Your cards are #{first_card} and #{second_card}." third_card = @dealer.cards.draw fourth_card = @dealer.cards.draw puts "Dealer's hand is #{third_card} and #{fourth_card}." if first_card + second_card == 21 puts "Outstanding! You win!" elsif third_card + fourth_card == 21 puts "Dealer wins. You lose." elsif first_card + second_card > 21 puts "You lost kid." elsif third_card + fourth_card > 21 puts "House loses." #You don't need all these extra lines down here before your end -JH end end end
true
bcb9081a71954400215337c8759c009f8f874564
Ruby
psytown/learn-ruby-the-hard-way
/ex31.rb
UTF-8
1,393
3.6875
4
[]
no_license
# encoding: UTF-8 # author:ouyangzhiping # title:learn the ruby the hard way # website:https://github.com/ouyangzhiping/learn-ruby-the-hard-way #Author:Zhangxi #Title:Learn ruby the hard way def prompt print">" end puts"You enter a dark room with two doors.Do you go through door #1 or door #2?" prompt;door =gets.chomp if door=="1" puts"There's a giant bear here eating cheese cake.What do you do?" puts"1.Take the cake." puts"2.Scream at the bear." prompt;bear =gets.chomp if bear =="1" puts "The bear eats your face off. Good job!" puts "Do you want continue?" puts "1.Add coins and continue." puts "2.No thanks." prompt;restart=gets.chomp if restart=="1" puts "Yes,you are the real hero,welcome back." elsif restart =="2" puts "We are very sorry about that ,you miss a perfect game." end elsif bear =="2" puts "Well, doing #{bear} is probably better. Bear runs away." end elsif door=="2" puts "You stare into the endless abyss at Cthuhulu's retina." puts "1.Blueberries." puts "2.Yellow jacket clothespins." puts "3.Understanding revolvers yelling melodies." prompt;insanity =gets.chomp if insanity =="1"or insanity=="2" puts "Your body survives powered by a mind of jello. Good job." else puts "The insanity rots your eyes into a pool of muck. Good job." end end
true
7a4d516384ce799608e08a26a93d6b09b3daf18b
Ruby
Friindel33/RubyLessons
/Myapp4/hash_demo2.rb
UTF-8
490
3.515625
4
[]
no_license
@hh = {} def add_person options puts "Already in the list!" if @hh[options[:name]] @hh[options[:name]] = options[:age] end def show_hash @hh.keys.each do |key| age = @hh[key] puts "Name: #{key}, age: #{age}" end end loop do print "Enter name: " name = gets.strip.capitalize if name == '' show_hash exit end print "Enter age: " age = gets.to_i options = {:name => name, :age => age} add_person options # or add_person :name => name, :age => age end
true
0b95c3b96b95f5fca11945c474c6c652333395a1
Ruby
IQ-SCM/burgundy
/lib/burgundy/collection.rb
UTF-8
693
2.96875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Burgundy class Collection def initialize(items, wrapping_class = nil, *args) @items = items @wrapping_class = wrapping_class @args = args end def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing to_ary.send(name, *args, &block) end def respond_to?(name, include_all = false) to_ary.respond_to?(name, include_all) end def to_ary @to_ary ||= if @wrapping_class @items.map {|item| @wrapping_class.new(item, *@args) } else @items.to_a end end alias to_a to_ary end end
true
2bae06658f30ec38b3f0106a526597ce31d76194
Ruby
psyho/fun.rb
/spec/fun/curry_spec.rb
UTF-8
963
3.09375
3
[ "MIT" ]
permissive
require 'spec_helper' describe Fun::Curry do def ac(&block) Fun.auto_curry(block) end describe "auto_curry" do it "creates a lambda" do sum = ac{|a,b,c| a + b + c} expect(sum[1, 2, 3]).to eq(6) end it "creates an auto-curried lambda" do sum = ac{|a,b| a + b} inc = sum[1] expect(inc[5]).to eq(6) end it "creates a lambda that can be curried until all arguments are given" do join = ac{ |a,b,c,d,e,f,g,h,i,j| [a,b,c,d,e,f,g,h,i,j].join(',') } expect(join[1][2,3][][4,5,6][7][8,9,10]).to eq("1,2,3,4,5,6,7,8,9,10") end it "allows auto-currying lambdas with known arity" do varargs = lambda{|*args| args.join(',') } join = Fun.auto_curry(varargs, -4) # min 3 arguments expect(join[1][2][3]).to eq("1,2,3") end it "creates an immediately-callable lambda for zero-arg lambdas" do foo = ac{:foo} expect(foo[]).to eq(:foo) end end end
true
b285e3483482881685a14ed70a723c91c7db9707
Ruby
YuraPlinto/SeaBattle
/field.rb
UTF-8
20,014
3.25
3
[]
no_license
class Field =begin Класс Field отвечает за представление поля. Он инкапсулирует все методы ввода/вывода для экземпляра поля. В классе описаны все возможные состояния поля. В класс встроено распознавание координат. Класс ведёт учёт количества живых кораблей и хранит информацию сдался ли пользователь - владелец поля. Не имеет значения в однопользовательской или многопользовательской игре будет использован класс. Класс не отвечает за игровую логику (неважно сколько и каких кораблей нужно потопить для победы, каковы правила заполнения поля, где и как оно заполняется, каков порядок ходов в случае многопользовательской игры). @field - это массив состояний клеток поля. 0 - закрытая пустая клетка 1 - закрытая неповреждённая клетка корабля 2 - открытая пустая клетка поля 3 - открытая повреждённая клетка корабля @surrender - это флаг сдачи для экземпляра поля =end @letterToNumber attr_reader :letterToNumber @field @surrender attr_reader :surrender @shipCount#Общее количество клеток поля, занятых кораблями attr_reader :shipCount #В переменной @shipCountByDeck храниться коллекция типов кораблей #(в виде количества палуб)и количество кораблей для кадого типа @shipCountByDeck def initialize(type, value1, value2, value3, value4) @shipCountByDeck=Hash.new @shipCountByDeck.[]=(1, value1)#singleDeckCount @shipCountByDeck.[]=(2, value2)#doubleDeckedCount @shipCountByDeck.[]=(3, value3)#threeDeckedCount @shipCountByDeck.[]=(4, value4)#fourDeckedCount @shipCount=0 @shipCountByDeck.each do |key,val| @shipCount+=key*val end @letterToNumber=Hash.new letter='A' for i in 0..9 do @letterToNumber.[]=(letter, i) letter.succ! end @field=Array.new(10) @field.each_index { |x| @field[x]=Array.new(10, 0) } @surrender=false #Далее расставим корабли case type when 0 #Расстановка кораблей случайным образом result=false loop do result=fillFieldByRandom if (result==true) then break else #print "Failed fill the field randomly! Try again.\n" #gets #Обнулим поле после неудачного заполнения @field.each_index { |x| @field[x].each_index { |y| @field[x][y]=0 } } end end when 1 #Ручная расстановка кораблей на поле fillFieldByHands else #Если в инциализатор передано незаданное значение аргумента type print "Error! Unknown type in initialize method.\n" end end def shoot(value) coordinates=parseUserInputString(value) #Если введены корректные координаты - можно стрелять if (coordinates!=false) then #Далее стреляем (изменяем состояние массива клеток поля) #Сейчас по уже поражённым клеткам стрелять можно - их состояние просто не изменится. #Если это поведение требуется изменить, то можно сообщать об ошибках #в соответствующих ветвях данного оператора case. case @field[coordinates[0]][coordinates[1]] when 0, 2 @field[coordinates[0]][coordinates[1]]=2 when 1 @field[coordinates[0]][coordinates[1]]=3 @shipCount-=1 when 3 @field[coordinates[0]][coordinates[1]]=3 else system('cls') puts 'Error! Not valid value in field.' gets exit 1 end end #Иначе ничего не делаем end #Проверить!!! def setCell(coord1, coord2) case @field[coord1][coord2] when 0 @field[coord1][coord2]=1 return true when 1 return false when 3 system('cls') puts "Error! Field you try to fill aren't empty.\n" gets exit 1 else system('cls') puts 'Error! Not valid value in field.' gets exit 1 end end def parseUserInputString (value) result=Array.new str=value.to_s.strip! if (str=~/\b(S|s)urrender\b/) then @surrender=true return false else #Далее определим, введены координаты в допустимом формате или что-то иное if !(str=~/[A-J]([1-9]|10)\b/) then print "Not valid value of coordinates! Try again.\n" gets return false else #2-ая координата result[1]=@letterToNumber[str[0]] str=str[1,str.length] #1-ая координата result[0]=str.to_i-1#Учитываем, что номерация в массиве с 0, а для пользователя с 1 return result end end end def checkNextCell(value1, value2, coord1, coord2) #аргументы value1, value2 - это координаты проверяемой клетки #аргументы coord1, coord2 - это координаты предыдущей клетки устанавливаемого корабля flag=true #Сначала проверим, находится ли проверяемая клетка в поле if (value1>=0)&&(value2>=0)&&(value1<=9)&&(value2<=9) then #Проверка подходит ли клетка для установки следующей клетки корабля. # ****X**** # ***XOX*** # ****X**** #Она должна находиться на "кресте" вокруг предыдущей клетки, которая передаётся #в метод как аргумент. if ((value1==coord1)&&(value2==coord2+1))||((value1==coord1)&&(value2==coord2-1))|| ((value1==coord1+1)&&(value2==coord2))||((value1==coord1-1)&&(value2==coord2)) then #Проверим клетки окружения, чтобы понять в допустимое ли место мы поставили палубу корабля. for i in (value1-1)..(value1+1) do for j in (value2-1)..(value2+1) do #Проверим, что клетка окружения с такими координатами есть в поле if (i>=0)&&(j>=0)&&(i<=9)&&(j<=9) then #Проверим, что в недопустимой близости нет кораблей кроме предыдущей клетки #устанавливаемого в данный момент. (На уже открытые клетки #ставить корабли тоже нельзя. Если это нужно, то следует изменить условие ниже.) if ((@field[i][j]!=0)&&((i!=coord1)||(j!=coord2))) then flag=false end end end end else flag=false end else flag=false end return flag end def determineDirection(coordinates, oldCoordinates) #Функция принимает два массива координат по 2 элемента в каждом. #Функция возвращает числовое обозначение одного из 4-х направлений. direction=0 if ((coordinates[0]==oldCoordinates[0])&&(coordinates[1]==oldCoordinates[1]+1)) direction=1 if ((coordinates[0]==oldCoordinates[0])&&(coordinates[1]==oldCoordinates[1]-1)) direction=2 if ((coordinates[0]==oldCoordinates[0]+1)&&(coordinates[1]==oldCoordinates[1])) direction=3 if ((coordinates[0]==oldCoordinates[0]-1)&&(coordinates[1]==oldCoordinates[1])) return direction end def fillFieldByHands direction=0#Переменная используется чтобы определять в какую сторону повёрнут корабль. newDirection=0#Переменная используется для сравнения направлений. coordinates=Array.new oldCoordinates=Array.new deckCount=0 #Создадим в методе локальную копию переменной, хранящей количество корабельных клеток cellsToFill=@shipCount #Создадм в методе локальную копию хэша, хранящего количество кораблей по палубам notPlaced=Hash.new @shipCountByDeck.each do |key, val| notPlaced.[]=(key, val) end while cellsToFill>0 do system('cls') printFieldWhileFill loop do print "Enter count of decks:\n" deckCount=gets break if (deckCount=~/\A[1-4]\Z/) print "Error! Not valid count of decks. Try again.\n" gets system('cls') printFieldWhileFill end deckCount=deckCount.to_i currentDeck=1 if (notPlaced[deckCount]>0) then #Корабли нужного типа есть. Ставим корабль. while (currentDeck<=deckCount) do #Цикл установки первой клетки корабля loop do system('cls') print "Enter coordinates of cell to fill.\n" st=gets coordinates=parseUserInputString(st) if (coordinates!=false) then #Тут проверяем подходящая ли клетка выбрана, #тип проверки зависит от того какая по счёту палуба устанавливается case currentDeck when 1 result=checkCellForShooting(coordinates[0], coordinates[1]) when 2 result=checkNextCell(coordinates[0], coordinates[1], oldCoordinates[0], oldCoordinates[1]) #Установка второй палубы корабля определяет в какую сторону он повёрнут. #Выявим это направление. direction=determineDirection(coordinates, oldCoordinates) else #result=checkOtherCell(coordinates[0], coordinates[1]) #Определим в какую сторону смотрит последняя поставленая палуба относительно предпоследней. newDirection=determineDirection(coordinates, oldCoordinates) if (newDirection==direction) then result=checkNextCell(coordinates[0], coordinates[1], oldCoordinates[0], oldCoordinates[1]) else result=false end end if (result!=false) then result=setCell(coordinates[0], coordinates[1]) end #Если в какая-либо функция из вызванных выше вернула false, значит координаты неправильные if (result==false) then print "Not suitable coordinates! Try to enter coordinates again.\n" gets else #Если ошибок не было ни в одной из функций, значит клетка успешно заполнена #Из цикла выбора клетки для заполнения можно выйти cellsToFill-=1 #Сохраним координаты предыдущей палубы, если она есть oldCoordinates = coordinates.clone break end end end currentDeck+=1#Переходим к следующей палубе, если она предусмотрена типом корабля end notPlaced[deckCount]-=1 else #Кораблей нужного типа нет. Нужно выбрать другой. print "There aren't that ships. Choose other type.\n" gets end end system('cls') printFieldWhileFill print "All ships was placed correctly\n" gets end def fillFieldByRandom #Для некоторых последовательностей псевдослучайных чисел возможна ситуация, #когда все места на поле, подходящие для кораблей какого-либо размера уже #заняты, а корабли такого размера ещё надо ставить. Тогда цикл поиска #подходящего места будет работать бесконечно. #Чтобы это предотвратить, введём переменную-счётчик итераций цикла поиска, если #он превысит определённый порог, то функция должна вернуть ложное значение. #Это будет означать, что сформировать случайную расстановку на поле не удалось. counter=0 #Метод не проверяет, есть ли достаточное количество свободных клеток на поле! #Чтобы избежать бесконечного цикла рекомендуется вызывать его только для пустого поля (заполненного 0). cellCoord1=1 cellCoord2=1 @shipCountByDeck.each do |key, val| #Найдём место для корабля случайным образом и проверим, подходит ли оно for i in 1..val do breakFlag=true direction=0 counter=0#Обнулим счётчик перед циклом поиска loop do #Флаг breakFlag определяет надо ли продолжать поиск подходящих координат #в цикле или подходящие координаты уже найдены breakFlag=true cellCoord1=1+rand(9) cellCoord2=1+rand(9) #Выберем ориентацию случайным образом: горизонтальную или вертикальную direction=rand(2) case direction when 0 #Размещаем корабль вправо от точки for k in 0..(key-1) do breakFlag=false if (checkCellForShooting(cellCoord1, cellCoord2+k)==false) end when 1 #Размещаем корабль вниз от точки for k in 0..(key-1) do breakFlag=false if checkCellForShooting(cellCoord1-k, cellCoord2)==false end else system('cls') puts 'Error! Wrong direction to accommodate the ship.' gets exit 1 end counter+=1#Ещё 1 итерация! return false if counter>300#Поле забито. Расставить всё не удалось! break if breakFlag==true end #Разместим на поле корабли case direction when 0 #Размещаем корабль вправо от точки for k in 0..(key-1) do @field[cellCoord1][cellCoord2+k]=1 end when 1 #Размещаем корабль вниз от точки for k in 0..(key-1) do @field[cellCoord1-k][cellCoord2]=1 end else system('cls') puts 'Error! Wrong direction to accommodate the ship.' gets exit 1 end end end return true end def checkCellForShooting(value1, value2) flag=true #Сначала проверим, находится ли проверяемая клетка в поле if (value1>=0)&&(value2>=0)&&(value1<=9)&&(value2<=9) then for i in (value1-1)..(value1+1) do for j in (value2-1)..(value2+1) do #Проверим, что клетка окружения с такими координатами есть в поле if (i>=0)&&(j>=0)&&(i<=9)&&(j<=9) then #Проверим, что в недопустимой близости нет кораблей. (На уже открытые клетки #ставить корабли тоже нельзя. Если это нужно, то следует изменить условие ниже.) if (@field[i][j]!=0) then flag=false end end end end else flag=false end return flag end def printField(space) print ' '*(space+1) @letterToNumber.each_key do |key| print ' '+key end print "\n" i=1 @field.each { |x| print ' '*space+i.to_s print' ' if i!=10#Для двузначных чисел отступ не нужен. Тут только 10 двузначное x.each {|y| case y when 0 print '* ' when 1 if @surrender==false then print '* ' else print 'S ' end when 2 print 'o ' when 3 print 'x ' else system('cls') puts 'Error! Not valid value in field.' gets exit 1 end } print "\n" i+=1 } #Отступ после поля print "\n" end def printFieldWhileFill #Функция предназначена для показа содержимого поля во время его заполнения #Её нельзя применять для поля со следами попаданий print ' ' @letterToNumber.each_key do |key| print ' '+key end print "\n" i=1 @field.each { |x| print i.to_s print' ' if i!=10#Для двузначных чисел отступ не нужен. Тут только 10 двузначное x.each {|y| case y when 0 print '* ' when 1 print 'S ' else system('cls') puts 'Error! Not valid value in field.' gets exit 1 end } print "\n" i+=1 } #Отступ после поля print "\n" end end
true
49ab115c3df486ea928b359c3111f327343bfef9
Ruby
kdaigle/ruby-for-doers
/case.rb
UTF-8
344
3.90625
4
[ "CC-BY-4.0" ]
permissive
#!/usr/bin/env ruby # Sometimes, a simple `if then` statement isn't useful enough. You may have mulitple branches # that need to be considered. That's when a case statement is useful. dog = "woof" case dog when "woof" puts "Woof! Woof! ::grown::" when "meow" puts "Meow... meow... ::prrr::" else puts "I don't know what to say..." end
true
fd8dd3a1a801f087d14a5c16b065293fed936807
Ruby
amine91480/J3-lib
/lib/01_pyramids.rb
UTF-8
1,434
3.453125
3
[]
no_license
def half_pyramid puts "Salut, bienvenue dans ma pyramide ! Combien d'étage veux tu entre ?" etage = gets.to_i if etage <= 0 || etage >= 25 puts "Le paramètre renseigner et incorrect" else a = 1 x = etage etage.times do b = " " * x d = "#" * a a = a + 1 x = x - 1 print b puts d end end end def full_pyramid puts "Salut, bienvenue dans ma pyramide ! Combien d'étage veux tu entre ?" etage = gets.chomp etage = etage.to_i if etage <=0 || etage >= 25 puts "Le nombre d'étage entré et incorrect" else a = 1 x = etage etage.times do b = " " * x d = "#" * a a = a + 2 x = x - 1 print b puts d end end end def wtf_pyramid puts "Salut, bienvenue dans ma pyramide ! Combien d'étage veux tu entre ? Ton seul choix et un chiffre impaire :P" etage = gets.chomp etage = etage.to_i a = 1 x = etage / 2 y = etage / 2 if etage.even? puts "Se chiffre et paire, sa ne fonctionne pas..." else x.times do b = " " * x c = "#" * a a = a + 2 x = x - 1 print b puts c end y = y + 1 y.times do b = " " * x c = "#" * a a = a - 2 x = x + 1 print b puts c end end end wtf_pyramid # nb = etage / 2 - 0.5 # d = " " * nb # puts "#{d}##{d}"
true
0f72533487f69763f6bbbeb8d0073656d931a043
Ruby
Spakman/isoworks
/test/paginatable_test.rb
UTF-8
901
2.65625
3
[ "MIT" ]
permissive
require_relative "test_helper" describe Paginatable do let(:object) { Array(1..100) } let(:number_of_pages) { 34 } before do object.extend(Paginatable) end it "returns the number of pages in the paginated object" do assert_equal number_of_pages, object.number_of_pages end it "returns the items for a given page" do assert_equal Array(4..6), object.items_for_page(2) end describe "failing when the extended instance doesn't respond to required messages" do let(:object) { Object.new } it "raises a NotImplementedError error if the extended object does not respond to #size" do assert_raises(NotImplementedError) do object.size end end it "raises a NotImplementedError error if the extended object does not respond to #slice" do assert_raises(NotImplementedError) do object.slice(0, 10) end end end end
true
9608221eab909cdda2c528f0e565d2bb9685c950
Ruby
edwinmonroy/rubycourse
/ch06/angryBoss.rb
UTF-8
303
3.4375
3
[]
no_license
puts puts puts 'Whatchu up to my lovely favorite boss?' puts puts puts 'Stop being a kiss ass and tell me what you want.' puts puts puts 'uh...well...' request = gets.chomp puts puts puts '...you wasted my time for that?' puts puts puts (request + ' is the stupidest request I have ever heard!').upcase
true
50c82236ecb6845dd662e7919f470a8650678830
Ruby
jaclynj/Drill
/week02/distillery/distillery.rb
UTF-8
817
3.28125
3
[]
no_license
class Distillery def initialize(name) @name = name @cellar = {} # When a new distillery is created, a new marketing department should be created at the same time # and should be pointed to by an instance variable of the new distillery object. @marketing_dept = Marketing_Department.new end def name @name end def marketing_dept() @marketing_dept end def cellar @cellar end def brew_beverage() bev_name = @marketing_dept.generate_beverage_name new_beverage = Beverage.new(bev_name) #For each beverage object created, ask the marketing department for a new name to name the beverage. @cellar[new_beverage.name] = new_beverage end def sell_beverage(beverage) @cellar.delete(beverage) end def beverage_count @cellar.length end end
true
f20469f6d632f1053c562ea20ebdb551b6afee8a
Ruby
Yashwanth-nr/RentBike
/app/models/booking.rb
UTF-8
574
2.609375
3
[]
no_license
class Booking < ActiveRecord::Base belongs_to :bike belongs_to :user validate :check_availability private def check_availability bookings = self.bike.bookings.where('confirmed = ?', true) new_booking_dates = ( self.start_datetime.to_date..self.end_datetime.to_date).to_a bookings.each do |booking| booking_dates = (booking.start_datetime.to_date..booking.end_datetime.to_date).to_a if !((booking_dates - new_booking_dates).length == booking_dates.length) errors.add(:base ,"This bike is already been booked for these days") end end end end
true
5cad1b5c2572d9979a15df8dbc22d76e329f5ea2
Ruby
rbuda/phase-0
/week-4/concatenate-arrays/my_solution.rb
UTF-8
336
3.59375
4
[ "MIT" ]
permissive
# Concatenate Two Arrays # I worked on this challenge [by myself]. # Your Solution Below def array_concat(array_1, array_2) if array_1.empty? && array_2.empty? final_array = [] else count = 0 while count < array_2.length final_array = array_1.push array_2[count] count += 1 end end return final_array end
true
83f26764435467f5eb0b8fed11f2ada80d9f6fd7
Ruby
sfrasica/ruby-project-alt-guidelines-dumbo-web-010620
/lib/models/command_line_interface.rb
UTF-8
216
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CommandLineInterface # Inro message def greet puts "************** Welcome to the GifShoppe! ************************" puts "World renowned one stop shop for all things GIF!" end end
true
524184c64db5436f1cc760f0955049f5d483bb3c
Ruby
Vincelep/pyramide
/pyramide.rb
UTF-8
233
3.390625
3
[]
no_license
puts "Hello, bienvenue dans ma super pyramide ! Combien d'étages tu veux ? " i = gets.chomp.to_i #j = "".to_s k = 0 l = "#" puts "voici la pyramide" i.times do #puts " #{j += "#"}" #end puts l*(k += 1) end #normalement c'est bon
true
cbfeb58052a06427ef60be5cfbc7000b5d5c9380
Ruby
davidlrnt/loqal
/app/data_fetchers/location.rb
UTF-8
231
2.625
3
[]
no_license
require 'pry' class Location attr_reader :urlhash def initialize @urlhash = JSON.load(open("http://ipinfo.io/json")) end def coordinates @urlhash["loc"] end def zipcode @urlhash["postal"] end end
true
28d54c784ad8ae632302adf885a093d1a70d812d
Ruby
omahacodeschool/ruby-toy__phone-number-formatter
/lib/phone_number_formatter.rb
UTF-8
171
3.15625
3
[]
no_license
# This method takes a string like `"4122226644"` and # returns a properly formatted phone number. def format_phone_number(phone_number_str) return phone_number_str end
true
ed4a18e858fe11235f256d156cdcc3f1350bc01b
Ruby
MLampa/ninety-nine-bottles-challenge
/beer.rb
UTF-8
1,891
4.125
4
[]
no_license
counter = 99 until counter == 2 puts "#{counter} bottles of beer on the wall, #{counter} bottles of beer! You take one down, you pass it around, #{counter-1} bottles of beer on the wall!\n\n" counter -= 1 if counter == 2 puts "#{counter} bottles of beer on the wall, #{counter} bottles of beer! You take one down, you pass it around, #{counter-1} bottle of beer on the wall!\n\n" puts "1 bottle of beer on the wall, 1 bottle of beer! You take one down, pass it around, no more bottles of beer on the wall!\n\n" puts "No more bottles of beer on the wall, no more bottles of beer! Go to the store and buy some more...\n\n" puts "...99 bottles of beer on the wall!" end end =begin This is me playing with class methods... class NinetyNineBottles def song counter = 99 until counter == 2 puts "#{counter} bottles of beer on the wall, #{counter} bottles of beer! You take one down, you pass it around, #{counter-1} bottles of beer on the wall!\n\n" counter -= 1 if counter == 2 puts "#{counter} bottles of beer on the wall, #{counter} bottles of beer! You take one down, you pass it around, #{counter-1} bottle of beer on the wall!\n\n" puts "1 bottle of beer on the wall, 1 bottle of beer! You take one down, pass it around, no more bottles of beer on the wall!\n\n" puts "No more bottles of beer on the wall, no more bottles of beer! Go to the store and buy some more...\n\n" puts "...99 bottles of beer on the wall!" end end end ninety_nine_bottles = NinetyNineBottles.new ninety_nine_bottles.song puts "\nWould you like to hear the song again?(y/n)" play = gets.chomp.downcase if play == 'y' ninety_nine_bottles.song elsif play == 'n' else puts "\nWhat was that? Eh, let's play it again!" ninety_nine_bottles.song end end =end
true
9ff6081a63755a59817af9d93d5f7769cb1d1da3
Ruby
haf/logirel
/spec/queries/bool_query_spec.rb
UTF-8
988
2.625
3
[ "Apache-2.0" ]
permissive
require 'logirel/queries' module Logirel module Queries describe BoolQ, "when given input" do before(:each) { @out = StringIO.new } it "input says no, second time" do io = StringIO.new "x\nn" b = BoolQ.new "Yes or no?", true, io, @out b.exec.should be_false end it "input says yet, second time" do io = StringIO.new "x\ny" b = BoolQ.new "Yes or no?", false, io, @out b.exec.should be_true end it "input says yes" do io = StringIO.new "y" b = BoolQ.new "Yes or no?", false, io, @out b.exec.should be_true end it "input says no" do io = StringIO.new "n" b = BoolQ.new("Yes or no?", true, io, @out) b.exec.should be_false end it "input is default" do io = StringIO.new "\n" b = BoolQ.new("Yes or no?", true, io, @out) b.exec.should be_true end end end end
true
3a37cc999b33dcfe9b232e12626ba28636b3a2b2
Ruby
athityakumar/ruby-chem-eqn
/helpers/get_elements/get_elements_helpers/order_by_syntax.rb
UTF-8
348
2.703125
3
[ "MIT" ]
permissive
require_relative "get_index" def order_by_syntax bracket_status , open_bracket , close_bracket , hash while open_bracket.count != 0 do key = close_bracket[0] index = get_index(open_bracket,key) value = open_bracket[index] hash[key] = value open_bracket.delete(value) close_bracket.delete(key) end return hash end
true
8fb4e6a7a6cb4c78800690ec75112dd7f0da6c59
Ruby
jessicatriana/ruby-oo-self-cash-register-lab-austin-web-012720
/lib/cash_register.rb
UTF-8
1,057
3.453125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class CashRegister attr_accessor :total, :discount, :quantity @@all = [] def initialize(discount= nil, quantity= 0) @total = 0 @discount = discount @quantity = quantity @item_list = [] end def add_item(title, price, quantity= 1) @total += price * quantity @last_price = price @last_quantity = quantity # check in to quanity.times method isntead while quantity > 0 do @item_list << title quantity -= 1 end end def discount @discount end def apply_discount if @discount @total = @total - (@discount * 10) return "After the discount, the total comes to $#{@total}." else return "There is no discount to apply." @total -= @discount end end def items @item_list end def void_last_transaction @total -= @last_price @item_list.pop(@last_quantity) if @item_list == [] @total = 0.0 end end end
true
0da576ff2988f569b61b338164d6137863a01002
Ruby
AJ8GH/ruby-udemy
/hashes/sort_and sort_by_methods_on_a_hash.rb
UTF-8
375
3.625
4
[]
no_license
pokemon = {squirtle: 'Water', bulbasaur: 'Grass', charizard: "Fire"} p pokemon.sort # converts to multi-dimensional array then sorts by keys, alphabetically p pokemon.sort.reverse puts p pokemon.sort_by { |pokemon, type| type } # just put the value or the key in the block to specify which you want to sort by p pokemon.sort_by { |pokemon, type| type }.reverse
true
1494a91e55f070afced83b9ac89b92f401d10d53
Ruby
ryanmjacobs/room-thermostat
/discovery/listen.rb
UTF-8
836
2.6875
3
[]
no_license
require "json" require "socket" require "colorize" def netcolor(addr) return :red if addr.map{|x| x.start_with?("192.168.")}.any? return :yellow if addr.map{|x| x.start_with?("10.0.1")}.any? return :blue end PORT = 31001 socket = UDPSocket.new socket.bind("", PORT) while true do begin data = socket.recvfrom(32768)[0] jd = JSON.parse(data) addr = jd["addr"] .filter{|x| x["ifname"] != "lo" && !x["ifname"].start_with?("docker") && x["operstate"] != "DOWN" && x["addr_info"].length >= 1} .map{|x| x["addr_info"][0]["local"]} addr_color = netcolor(addr) pretty_addr = addr.map{|x| x.ljust(16)}.join(",") puts "#{jd["hostname"].rjust(16).bold.colorize(addr_color)} - #{pretty_addr}" rescue puts jd end STDOUT.flush end
true
95cbfeabe6d78b7d4b6e281e4d2b79a5078a04fe
Ruby
nickjcarr/NicholasCarr_T1A3
/company.rb
UTF-8
83
2.6875
3
[ "MIT" ]
permissive
class Company attr_accessor :name def initialize(name) @name = name end end
true
3fa8a8bfe709c71edde43bb1fed8c6e89cfcb688
Ruby
abosaudtech/Ruby_on_Rails
/Sololearn/class_constants.rb
UTF-8
571
3.5625
4
[]
no_license
=begin A class can also contain constants. Remember, constants variables do not change their value and start with capital letter. It is common to have uppercase names for constants, as in: =end class Calc PI = 3.14 end # You can access constants using the class name, # followed by two colo symbols (::) and the # constant name, for example: puts Calc::PI # Run the code and see how it works! # Drage and drop from the options below to output # the constant ID of the Test class: # Options: Test, ID, const, <<, self. puts Test::ID
true
89f8cb647c213663c74f9f1959373eb219072ef6
Ruby
smilesr/op-rb-rw-15-serverclient
/server.rb
UTF-8
1,561
2.9375
3
[]
no_license
require 'socket' require 'json' server = TCPServer.open(2000) puts "Server listening on port 2000" loop { client = server.accept request = "" while line = client.gets request += line break if request =~ /\r\n\r\n$/ end request_arr = request.split(" ") verb = request_arr[0] uri = request_arr[1].tr("/","") puts "#{verb} request received . . ." if File.file?(uri) if verb == "GET" status_code = "200" status_message = "OK" bytes_number = 0 content = '' f= File.open(uri, "r") content= f.read bytes_number = content.bytesize f.close client.puts "HTTP/1.1 " + "#{status_code} " + "#{status_message} " client.puts "Date: " + "#{Time.now.ctime} " client.puts "Content-Type: text/html " client.puts "Content-Length: " + "#{bytes_number}" + "\r\n\r\n" client.puts content client.close elsif verb == "POST" body_size = request_arr.last.to_i body = client.read(body_size) params = JSON.parse(body) template = File.read(uri) result = '' for i in params.keys params[i].each do |k,v| result << "<li> #{k} : #{v} </li>" end end final_html = template.gsub!("<%= yield %>",result) client.print "HTTP/1.0 200 OK\r\n" client.print "\r\n" client.print final_html client.close end else status_code = "400" status_message = "File Not Found" client.puts "Status Code: #{status_code} - #{status_message}" client.close end }
true
9afeac30c3145d9c2a8e331c31d1de329f1f396b
Ruby
kilimchoi/teamleada.com
/db/seeds/projects/013_statricks_project.rb
UTF-8
20,300
3.171875
3
[]
no_license
# @author: Guang Yang # @editor: Tristan Tao # @mktime: 2014/06/10 # @description: web scraper project for boattrader.com in python main_page_content = [ ['text', 'In this project, you are tasked with building a web scraper for Statricks, an analytics technology company that aggregates price data on used goods.'], ['text', 'This project is designed to test your abilities to:'], ['text', '1. Build an effective and efficient data collection script in python'], ['text', '2. Navigate through terse html files'], ['text', '3. Utilize existing packages in python to your advantage'], ] project = Project.create!( title: "Statricks: Data Collection with Python", description: main_page_content, short_description: "A project sponsored by Statricks, an e-Commerce analytics company. In this data challenge you will build a web scraper using the Beautiful Soup library to extract listing information. This data challenge is for users with experience in Python and some HTML.", number: 13, enabled: false, has_leaderboard: false, has_written_submit: true, uid: 13, difficulty: 'Intermediate', category: Project::CHALLENGE, company_overview: "", is_new: false, deadline: 2.weeks, featured: false, cover_photo: "statricks", ) puts "============ Created project: #{project.title}." ############################################ ########## -- PROJECT OVERVIEW -- ########## ############################################ project_overview_content0 = [ ['text', 'In this project, you are tasked with building a web scraper for Statricks, an analytics technology company that aggregates price data on used goods.'], ['text', 'This project is designed to test you abilities to:'], ['text', '1. Building an effective and efficient data collection script in python'], ['text', '2. Navigate through terse html files'], ['text', '3. Utilize existing packages in python to your advantage'], ['lesson_links', nil], ] project_overview = Lesson.create!( title: "Project Overview", project: project, lesson_id: 0, ) project_overview_slide0 = Slide.create!( content: project_overview_content0, parent: project_overview, slide_id: 0, ) ########## -- PROJECT OVERVIEW: Background -- ########## project_overview_background_content0 = [ ['text', 'Statricks is an analytics technology company specializing in pricing used goods.'], ['text', 'By aggregating price data from different sources, Statricks provides price trends for users to find good deals when buying, and maximize returns when selling used goods'], ['text', 'In order for price trends to be accurate, Statricks needs data from various sources (eBay, craigslist, and CarMax) – while some of these sources have Application Programming Interfaces (APIs) in place that enable easy data acquisition, a majority of them do not.'], ['text', 'As a result, we need to “scrape” these websites to get the pricing data we want.'], ['next_steps', nil], ] project_overview_background = Step.create!( title: "Background", lesson: project_overview, step_id: 0, ) project_overview_background_slide0 = Slide.create!( content: project_overview_background_content0, parent: project_overview_background, slide_id: 0, ) ########## -- PROJECT OVERVIEW: Our Goal -- ########## project_overview_our_goal_content0 = [ ['text', 'You are tasked with making a web scraper in python for the following website:'], ['link', "http://www.boattrader.com"], ['text', 'It\'s a website that specializes in used boats.'], ['text', 'Speifically, we need an automated way of doing two things:'], ['text', '1. Find the URL for each and every boat being listed on the entire website'], ['text', '2. For each boat, find and store the unique boat information (title, contact number, price etc)'], ['next_steps', nil], ] project_overview_our_goal = Step.create!( title: "Our Goal", lesson: project_overview, step_id: 1, ) project_overview_our_goal_slide0 = Slide.create!( content: project_overview_our_goal_content0, parent: project_overview_our_goal, slide_id: 0, ) ########## -- PROJECT OVERVIEW: Resources -- ########## project_overview_resources_content0 = [ ['text', 'For both tasks, you might find these two popular python packages very helpful:'], ['text', '1. BeautifulSoup'], ['text', '2. Requests'], ['next_steps', nil], ] project_overview_resources = Step.create!( title: "Resources", lesson: project_overview, step_id: 2, ) project_overview_resources_slide0 = Slide.create!( content: project_overview_resources_content0, parent: project_overview_resources, slide_id: 0, ) ############################################## ########## -- Building a Crawler -- ########## ############################################## crawler_content0 = [ ['text', 'Before we begin to extract details from a boat listing, we need to first find the URL of that particular webpage and read the content of the html file.'], ['text', 'Since we are interested in ALL of the listtings, we need to make a class of functions that will help us do this.'], ['text', 'Make sure to name your functions as specified in the left navigation bar.'], ['lesson_links', nil], ] crawler = Lesson.create!( title: "Building a Crawler", project: project, lesson_id: 1, ) crawler_slide0 = Slide.create!( content: crawler_content0, parent: crawler, slide_id: 0, ) ########## -- BUILDING A CRAWLER: get_raw_html -- ########## crawler_getRaw_content0 = [ ['text', 'Let us start by creating a function that when given a raw URL link, queries and returns the raw html file as String.'], ['user_code', ''], ['next_steps', nil], ] crawler_getRaw = Step.create!( title: "get_raw_html", lesson: crawler, step_id: 0, ) crawler_getRaw_slide0 = Slide.create!( content: crawler_getRaw_content0, parent: crawler_getRaw, slide_id: 0, ) crawler_getRaw_context0 = SubmissionContext.create!( title: "Raw HTML.", description: "User is asked to create a function that queries and returns the raw html when given a raw URL link.", slide: crawler_getRaw_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- BUILDING A CRAWLER: get_listing_urls -- ########## crawler_getListing_content0 = [ ['text', 'Next, given a raw html of a single search result page, we want to extract the list of URL links to actual listings.'], ['user_code', ''], ['next_steps', nil], ] crawler_getListing = Step.create!( title: "get_listing_urls", lesson: crawler, step_id: 1, ) crawler_getListing_slide0 = Slide.create!( content: crawler_getListing_content0, parent: crawler_getListing, slide_id: 0, ) crawler_getListing_context0 = SubmissionContext.create!( title: "List of URLs.", description: "User is asked to create a function that extracts the list of URL links to actual listings when given a raw html of a single search result page.", slide: crawler_getListing_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- BUILDING A CRAWLER: generate_search_links -- ########## crawler_scrape_search_content0 = [ ['text', 'Lastly, we want to generate search result links.'], ['text', 'Do a sample boat search to see what the url looks like.'], ['text', 'What do you notice? Perhaps the URL seems structured?'], ['text', 'Well, that\'s because the URL is a REST endpoint.'], ['text', 'Do you see a way to generate the search result links? Try a few different searches (and visit multiple result pages). Explain below:'], ['user_response', 'User Response here!'], ['text', 'Don\' forget to think about how you would want to parameterize the function.'], ] crawler_scrape_search_content1 = [ ['text', 'Now write the code that generates a series of search result pages\' url.'], ['user_code', 'User Code here'], ['next_steps', nil], ] crawler_scrape_search = Step.create!( title: "generate_search_url", lesson: crawler, step_id: 2, ) crawler_scrape_search_slide0 = Slide.create!( content: crawler_scrape_search_content0, parent: crawler_scrape_search, slide_id: 0, ) crawler_scrape_search_slide1 = Slide.create!( content: crawler_scrape_search_content1, parent: crawler_scrape_search, slide_id: 1, ) crawler_scrape_search_context0 = SubmissionContext.create!( title: "Generate Search Links - Response", description: "User is asked explain how he/she plans to generate search result page url, given that it is REST.", slide: crawler_scrape_search_slide0, submission_context_id: 0, submission_type: SubmissionContext::RESPONSE, ) crawler_scrape_search_context1 = SubmissionContext.create!( title: "Generate Search Links - Code", description: "User is asked write code that generates a formatted REST urls that represent search page results.", slide: crawler_scrape_search_slide1, submission_context_id: 1, submission_type: SubmissionContext::CODE, ) ###################################################### ########## -- Extracting Listing Details -- ########## ###################################################### extract_content0 = [ ['text', 'To extract information from a boat listing, we need to find the URL of that particular webpage.'], ['text', 'We already built the modules to help us achieve that!'], ['text', 'We first use the "generate_search_url" with some parameter to load a search result url.'], ['text', 'Then you can use the "get_listing_urls" function to get individual url.'], ['text', 'Once you have the raw html to a single listing page, the following functions will come in handy.'], ['lesson_links', nil], ] extract = Lesson.create!( title: "Extracting Listing Details", project: project, lesson_id: 2, ) extract_slide0 = Slide.create!( content: extract_content0, parent: extract, slide_id: 0, ) ########## -- EXTRACTING LISTING DETAILS: get_UID -- ########## extract_uid_content0 = [ ['text', 'Given a URL, write a function that returns the unique identifier (UID) of the listing.'], ['text', 'HINT: perhaps the "get_raw_html()" will be useful!'], ['user_code', ''], ['next_steps', nil], ] extract_uid = Step.create!( title: "get_UID", lesson: extract, step_id: 3, ) extract_uid_slide0 = Slide.create!( content: extract_uid_content0, parent: extract_uid, slide_id: 0, ) extract_uid_context0 = SubmissionContext.create!( title: "Extract Unique ID.", description: "User is asked to write a function that returns the unique identifier (UID) of the listing given a listing URL.", slide: extract_uid_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_title -- ########## extract_title_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns the title of an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_title = Step.create!( title: "get_title", lesson: extract, step_id: 4, ) extract_title_slide0 = Slide.create!( content: extract_title_content0, parent: extract_title, slide_id: 0, ) extract_title_context0 = SubmissionContext.create!( title: "Extract Title.", description: "User is asked to write a function that returns the title of the listing given a beautifulsoup object.", slide: extract_title_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_price -- ########## extract_price_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns the price of an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_price = Step.create!( title: "get_price", lesson: extract, step_id: 5, ) extract_price_slide0 = Slide.create!( content: extract_price_content0, parent: extract_price, slide_id: 0, ) extract_price_context0 = SubmissionContext.create!( title: "Extract Price.", description: "The user is asked to write a function that returns the price of the listing given a beautifulsoup object.", slide: extract_price_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_description -- ########## extract_description_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns the description of an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_description = Step.create!( title: "get_description", lesson: extract, step_id: 6, ) extract_description_slide0 = Slide.create!( content: extract_description_content0, parent: extract_description, slide_id: 0, ) extract_description_context0 = SubmissionContext.create!( title: "Extract Description.", description: "User is asked to write a function that returns the description of a listing given a beautifulsoup object.", slide: extract_description_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_img_URL -- ########## extract_img_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns a list of image URLs of an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_img = Step.create!( title: "get_img_URL", lesson: extract, step_id: 7, ) extract_img_slide0 = Slide.create!( content: extract_img_content0, parent: extract_img, slide_id: 0, ) extract_img_context0 = SubmissionContext.create!( title: "Extract Image URL.", description: "User is asked to write a function that returns the image URL of a listing given a beautifulsoup object.", slide: extract_img_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_phone_num -- ########## extract_phone_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns the phone number in an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_phone = Step.create!( title: 'get_phone_num', lesson: extract, step_id: 8, ) extract_phone_slide0 = Slide.create!( content: extract_phone_content0, parent: extract_phone, slide_id: 0, ) extract_phone_context0 = SubmissionContext.create!( title: "Extract Phone Number.", description: "User is asked to write a function that returns the phone number of a listing given a beautifulsoup object.", slide: extract_phone_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ########## -- EXTRACTING LISTING DETAILS: get_details -- ########## extract_details_content0 = [ ['text', 'Given a beautifulsoup object, write a function that returns the "details section" of an individual listing page.'], ['user_code', ''], ['next_steps', nil], ] extract_details = Step.create!( title: "get_details", lesson: extract, step_id: 9, ) extract_details_slide0 = Slide.create!( content: extract_details_content0, parent: extract_details, slide_id: 0, ) extract_details_context0 = SubmissionContext.create!( title: "Extract Details.", description: "User is asked to write a function that returns the \"details section\" of a listing given a beautifulsoup object.", slide: extract_details_slide0, submission_context_id: 0, submission_type: SubmissionContext::CODE, ) ######################################## ########## -- All Together -- ########## ######################################## all_together_content_zero = [ ['text', 'Now to put everything together.'], ['text', 'Consider the following:'], ['text', '1. You have the code that generates the search results.'], ['text', '2. You have the code that grabs the URL of the invidual listing page from search results.'], ['text', '3. You have the functions that extract various information from the listing page.'], ['text', 'Now you have to put it together!'], ['lesson_links', nil], ] all_together_lesson = Lesson.create!( title: "The Complete Scraper", project: project, lesson_id: 3, ) all_together_slide0 = Slide.create!( content: all_together_content_zero, parent: all_together_lesson, slide_id: 0, ) ########## -- ALL TOGETHER: A Functioning Algorithm -- ########## all_together_put_together_content_0 = [ ['text', 'Put the module together into a single file.'], ['text', 'You can organize the code however you deem fit.'], ['text', 'For now, you can have the code print the information extracted. We\'ll get to outputting/storing data last.'], ['text', 'Make sure you comment on how to run it.'], ['text', 'Also be prepared to explain why you organized it the way you did.'], ['text', 'Paste the entire codebase below. Don\'t forget to comment on how to run the code!'], ['user_code', ''], ] all_together_put_together_content_1 = [ ['text', 'How did you organize the code?'], ['text', 'What were some of the issues you considered?'], ['text', 'Why did you organize it that way?'], ['text', 'Explain any relevant thoughts below:'], ['user_response', ''], ['next_steps', nil], ] combining_module_step = Step.create!( title: "Combining the Modules", lesson: all_together_lesson, step_id: 0, ) all_together_put_slides_0 = Slide.create!( content:all_together_put_together_content_0, parent: combining_module_step, slide_id: 0, ) all_together_put_slides_1 = Slide.create!( content:all_together_put_together_content_1, parent: combining_module_step, slide_id: 1, ) all_together_put_code_context = SubmissionContext.create!( title: "Complete Module - code", description: "User is asked to put together the entire modules, effectively creating a working scarper.", slide: all_together_put_slides_0, submission_context_id: 0, submission_type: SubmissionContext::COMPLETE_CODE, ) all_together_put_response_context = SubmissionContext.create!( title: "Complete Module - response", description: "User is asked to explain process/how/why they organized the scraper code.", slide: all_together_put_slides_1, submission_context_id: 1, submission_type: SubmissionContext::RESPONSE, ) ######################################## #### -- Concluding Section -- ########## ######################################## presentation_one = [ ['text', 'Now that you have a working scraper, you\'ll have to present your process!'], ['text', 'We\'re going to ask you to create (and present) a 3 slide presentation.'], ['text', 'On the first 2 slides, explain what you did with the scraper.'], ['text', 'On the last (3rd) slide, explain how you would store the scraped data.'], ['text', 'The last slide is about design. You won\'t be asked to code up your plan, but be ready to explain it.'], ] presentation_two = [ ['text', 'Submit a link to a google presentation (3 slides) of your analysis and conclusion.'], ['user_response', ''], ] presentation_three = [ ['text', 'Submit a link to a video of you presenting your conclusions (2 min max). Production quality is not important.'], ['user_response', ''], ['finish_project_button', 'http://www.surveygizmo.com/s3/1654603/Project-Feedback-Form'], ] presentation_lesson = Lesson.create!( title: "Final Presentation - Statricks", project: project, lesson_id: 4, ) all_together_slide_one = Slide.create!( content: presentation_one, parent: presentation_lesson, slide_id: 0, ) presentation_slide_two= Slide.create!( content: presentation_two, parent: presentation_lesson, slide_id: 1, ) presentation_slide_three = Slide.create!( content: presentation_three, parent: presentation_lesson, slide_id: 2, ) presentation_context = SubmissionContext.create!( title: "Presentation - Slides", description: "User is asked create a 3 slides presentation for the statricks project.", slide: presentation_slide_two, submission_context_id: 0, submission_type: SubmissionContext::PRESENTATION_SLIDES_LINK, ) return_code_context = SubmissionContext.create!( title: "Presentation - Video", description: "User is asked to create a video presentation (no longer than 2 min) of the statricks slides.", slide: presentation_slide_three, submission_context_id: 1, submission_type: SubmissionContext::PRESENTATION_VIDEO_LINK, )
true
178fb18e07f68ef8d9ba1c5ae2539774470504ad
Ruby
DocsWebApps/system-dashboard-rails
/test/models/company_test.rb
UTF-8
1,006
2.78125
3
[ "MIT" ]
permissive
# == Schema Information # # Table name: companies # # id :integer not null, primary key # name :string(255) # created_at :datetime # updated_at :datetime # require 'test_helper' class CompanyTest < ActiveSupport::TestCase def setup @company=FactoryGirl.create :company @[email protected] end test 'Model Validations' do # it's attribute :name can not be blank company=FactoryGirl.build :company, name: nil assert !company.valid?, ':name nil, should not be valid' company=FactoryGirl.build :company, name: 'Test company' assert company.valid?, ':name OK, should be valid' # it's attribute :name must be unique company=FactoryGirl.build :company, name: @name assert !company.valid?, ':name already taken, should not be valid' end test 'Model Methods' do # it's method Company.return_name must return the :name attribute assert_equal Company.company_name, @name end end
true
05becbf328798722ce6545effe210a92f530c884
Ruby
bdisney/ror
/lesson_06/models/route.rb
UTF-8
1,607
3.59375
4
[ "MIT" ]
permissive
class Route attr_reader :stations def initialize(start, finish) @stations = [start, finish] validate! end def is_valid? validate! rescue false end def include(station) raise "Станция уже содержится в маршруте" if in_route?(station) include!(station) end def exclude(station) raise "Станция не найдена" if !in_route?(station) raise "Нельзя удалить начальную и конечную точку маршрута." if endpoint?(station) exclude!(station) end def next(current) if current != self.stations.last self.stations.at(self.stations.index(current) + 1) end end def prev(current) if current != self.stations.first self.stations.at(self.stations.index(current) - 1) end end def list list = "Маршрут #{self}: " self.stations.each_with_index { |station, i| list += "#{i + 1}. #{station}" } list end def to_s "«#{self.stations.first} — #{self.stations.last}»" end protected def validate! self.stations.each_with_index do |station, i| raise "Объект #{i + 1} в маршруте не является станцией!" if !station.is_a?(Station) end true end private def in_route?(station) self.stations.include?(station) end def endpoint?(station) station == self.stations.first || station == self.stations.last end def include!(station) self.stations.insert(-2, station) end def exclude!(station) self.stations.delete(station) end end
true
d9343df0fb7592d22f7fd33c8861630ffa8555dd
Ruby
criacuervos/recursion-writing
/lib/recursive-methods.rb
UTF-8
1,783
3.875
4
[]
no_license
# Authoring recursive algorithms. Add comments including time and space complexity for each method. # Time complexity: O(n^2) # Space complexity: O(n^2) def factorial(n) if n < 0 raise ArgumentError elsif n <= 1 return 1 else return n * factorial(n - 1) end end # Time complexity: O(n) # Space complexity: O(n) def reverse(s) reversed_string = "" if s.length >= 1 reversed_string = reverse(s[1..-1]) reversed_string += s[0] else return reversed_string end end # Time complexity: O(n) # Space complexity: O(1) def reverse_inplace(s, i = 0, j = -1) n = s.length if i == n / 2 return s else letter = s[i] s[i] = s[j] s[j] = letter reverse_inplace(s, i + 1, j - 1) end end # Time complexity: O(n) # Space complexity: O(n) def bunny(n, ears = 0) if ears == n + n return ears else ears += n bunny(n, ears) end end # Time complexity: O(n) # Space complexity: O(n) def nested(s, low = 0, high = (s.length - 1)) if s.length.odd? return false elsif low < high if s[low] != "(" && s[high] != ")" return false end return nested(s, low + 1, high - 1) else return true end end # Time complexity: O(n) # Space complexity: ? def search(array, value) new_array_minus_one = 0..-2 if array.empty? return false elsif array[-1] == value return true else search(array[new_array_minus_one], value) end end # Time complexity: O(n) # Space complexity: O(1) def is_palindrome(s, i = 0, j = -1) n = s.length if i >= s.length + j return true elsif s[i] != s[j] return false elsif s[i] == s[j] is_palindrome(s, i + 1, j - 1) end end # Time complexity: ? # Space complexity: ? def digit_match(n, m) end
true
9a3843859c9a109dbe2a3b53598737edc739a441
Ruby
Vorgnr/randstone
/spec/models/card_spec.rb
UTF-8
11,787
2.609375
3
[]
no_license
require 'rails_helper' RSpec.describe Card, type: :model do describe '.random_numplet' do context 'when users have enough cards' do it 'should return uniq cards nuplet' do cards = 5.times.map { create(:card) } expect(cards.uniq { |c| c.id }.length).to eq 5 nuplet = Card.random_nuplet(5, cards) u = nuplet.uniq { |c| c.id } expect(u.length).to eq 5 end end context 'when users have not enough cards' do context 'when cards is nil' do it 'should raise error ' do expect { Card.random_nuplet(5, nil) }.to raise_error end end context 'when cards is not nil' do it 'should return duplicate cards nuplet ' do cards = 2.times.map { create(:card) } expect(Card.random_nuplet(5, cards).length).to eq 5 end end end end describe '.i_to_quality' do it 'should convert integer to Card.quality' do expect(Card.i_to_quality(0)).to eq 'base' expect(Card.i_to_quality(1)).to eq 'common' expect(Card.i_to_quality(2)).to be nil expect(Card.i_to_quality(3)).to eq 'rare' expect(Card.i_to_quality(4)).to eq 'epic' expect(Card.i_to_quality(5)).to eq 'legendary' expect(Card.i_to_quality(6)).to be nil end end describe '.random_quality' do it 'should return an int or an array of int' do quality = Card.random_quality [5, 4, 3] result = (quality.is_a? Integer) || quality.all? { |q| q.is_a? Integer } expect(result).to be true end end describe '.cards_to_draw' do context 'when qualities is nil' do it 'should return cards with any qualities' do 5.times { create(:card, :with_base_quality) } 5.times { create(:card, :with_common_quality) } 5.times { create(:card, :with_epic_quality) } expect(Card.cards_to_draw.length).to eq 15 end end context 'when qualities is not nil' do it 'should return cards with expected qualities' do 5.times { create(:card, :with_base_quality) } 5.times { create(:card, :with_common_quality) } 5.times { create(:card, :with_epic_quality) } expect(Card.cards_to_draw(qualities: [0, 1]).length).to eq 10 expect(Card.cards_to_draw(qualities: 4).length).to eq 5 end end context 'when hero_id is nil' do it 'should return cards with any hero' do hero = create(:hero) 5.times { create(:card, hero: hero) } 5.times { create(:card) } expect(Card.cards_to_draw.length).to eq 10 end end context 'when hero_id is not nil' do it 'should return cards with expected hero and all cards without any hero' do hero = create(:hero) hero2 = create(:hero) 5.times { create(:card, hero: hero) } 5.times { create(:card, hero: hero2) } 5.times { create(:card) } expect(Card.cards_to_draw(hero_id: hero.id).length).to eq 10 end end context 'when user_id is not nil' do it "should return user's cards" do user = create(:user) user2 = create(:user) cards = 2.times.map { create(:card) } user.cards << cards + cards user2.cards << cards create(:card) expect(Card.cards_to_draw(user_id: user.id).length).to eq 2 end end context 'when all parameters are set' do it 'should return expected cards' do hero = create(:hero) user = create(:user) bases = 5.times.map { create(:card, :with_base_quality) } common = 5.times.map { create(:card, :with_common_quality) } common_with_hero= 5.times.map { create(:card, :with_common_quality, hero: hero) } epic = 5.times.map { create(:card, :with_epic_quality) } epic_with_hero = 1.times.map { create(:card, :with_epic_quality, hero: hero) } user.cards << [bases.first, common.first, common_with_hero.first, epic.first, epic_with_hero.first] expect(Card.cards_to_draw(user_id: user.id, qualities: [0, 1], hero_id: hero.id).length).to eq 3 end end end describe '.i_to_quality' do context 'when all qualities are availables' do it 'should convert integer to quality' do availables_qualities = [5, 4, 3] expect(Card.random_to_quality(1, availables_qualities)).to eq 5 expect(Card.random_to_quality(2, availables_qualities)).to eq 4 expect(Card.random_to_quality(11, availables_qualities)).to eq 3 expect(Card.random_to_quality(50, availables_qualities)).to eq [0, 1] end end context 'when all qualities are not availables' do context 'when legendary quality is not available' do it 'should convert integer to quality' do expect(Card.random_to_quality(1, [4, 3])).to eq 4 expect(Card.random_to_quality(1, [3])).to eq 3 end end context 'when epic quality is not available' do it 'should convert integer to quality' do expect(Card.random_to_quality(1, [5, 3])).to eq 5 expect(Card.random_to_quality(2, [5, 3])).to eq 3 end end context 'when rare quality is not available' do it 'should convert integer to quality' do expect(Card.random_to_quality(15, [5, 4])).to eq [0, 1] end end end end describe '.clean_total' do it 'should return expected clean total' do expect { Card.clean_total(0) }.to raise_error expect { Card.clean_total(1) }.to raise_error expect(Card.clean_total(2)).to eq 1 expect(Card.clean_total(3)).to eq 1 expect(Card.clean_total(4)).to eq 2 end end describe '.flatten' do context 'when total has not to be cleaned' do it 'it flattened cards' do user = create(:user) cards = 5.times.map { create(:card) } user.cards << cards + cards cards = Card.cards_to_draw(user_id: user.id) flat_cards = Card.flatten(cards); expect(flat_cards.length).to eq 10 expect(flat_cards.all? { |c| c.is_a? Card }).to be true end end end describe '.get_trio' do context 'when there is an opponent' do it 'should return trio of cards' do user = create(:user) userb = create(:user) base = 2.times.map { create(:card, :with_base_quality) } common = 2.times.map { create(:card, :with_common_quality) } epic = 4.times.map { create(:card, :with_epic_quality) } rare = 4.times.map { create(:card, :with_rare_quality) } legendary = 4.times.map { create(:card, :with_legendary_quality) } cards = base + common + rare + epic + legendary user.cards << cards + cards userb.cards << cards trio = Card.get_trio(user_id: user.id, opponent_id: userb.id) expect(trio.length).to eq 3 end end context 'when there is no opponent' do it 'should return trio of cards' do user = create(:user) cards = 5.times.map { create(:card) } user.cards << cards trio = Card.get_trio(user_id: user.id) expect(trio.length).to eq 3 end end context 'when current_deck already has cards' do it 'should remove those cards' do cards = 4.times.each_with_index.map { |x,i| create(:card, id: i + 1) } user = create(:user, :with_pick_cards_deck) deck = user.current_deck user.cards << cards + cards card_one = Card.find(1) deck.cards << [card_one] cards_to_draw = Card.cards_to_draw(user_id: user.id) expect(cards_to_draw.length).to eq 4 flattened_cards = Card.flatten(cards_to_draw) expect(flattened_cards.length).to eq 8 Card.remove_cards_already_in_deck(deck.cards, flattened_cards) expect(flattened_cards.length).to eq 7 end end end describe 'all_with_collection_of' do it 'should return all card' do user = create(:user) cards = 5.times.map { create(:card) } expect(Card.all_with_collection_of(user.id).length).to eq 5 end it 'should return a total column' do user = create(:user) cards = 5.times.map { create(:card) } expect(Card.all_with_collection_of(user.id).first.total).to eq 0 end it 'should correctly count card in user\'s collection' do user = create(:user) cards = 5.times.map { create(:card) } user.cards << [cards[0], cards[0], cards[1]] all_card_and_user_collection = Card.all_with_collection_of(user.id) expect(all_card_and_user_collection.find(cards[0]).total).to eq 2 expect(all_card_and_user_collection.find(cards[1]).total).to eq 1 end end describe 'all_that_user_can_add' do context 'when not used with with_qualities filer' do context 'when user has one legendary card' do it 'should return all legendary except this one' do user = create(:user) cards = 5.times.map { create(:card, :with_legendary_quality) } user.cards << cards.first expect(Card.all_that_user_can_add(user.id).length).to eq 4 end end end context 'when used with with_qualities filer' do context 'when user has one legendary card' do it 'should return all legendary except this one' do user = create(:user) cards = 5.times.map { create(:card, :with_legendary_quality) } user.cards << cards.first expect(Card.all_that_user_can_add(user.id).with_qualities(5).length).to eq 4 expect(Card.all_that_user_can_add(user.id).with_qualities(2).length).to eq 0 end end end end describe 'join_collection_of' do it 'should filter by cards of user' do user = create(:user) cards = 5.times.map { create(:card) } user.cards << [cards[0], cards[1]] expect(Card.join_collection_of(user.id).length).to eq 2 end end describe 'filter_by_cost' do before(:each) do create(:card, cost: 2) create(:card, cost: 9) create(:card, cost: 7) end context 'when cost == All' do it 'should not filter' do expect(Card.filter_by_cost.length).to eq 3 end end context 'when cost == 7' do it 'should return card with cost >= 7' do expect(Card.filter_by_cost(7).length).to eq 2 end end context 'when cost < 7' do it 'should return card with cost < 7' do expect(Card.filter_by_cost(2).length).to eq 1 end end end describe 'with_name' do before(:each) do 2.times { create(:card, name: 'dummy') } end it 'should return which start with name' do create(:card, name: 'abcxxx') expect(Card.with_name('abc').length).to eq 1 end it 'should return which contains name' do create(:card, name: 'xxxxabcxxx') expect(Card.with_name('abc').length).to eq 1 end it 'should return which end with name' do create(:card, name: 'xxxxabc') expect(Card.with_name('abc').length).to eq 1 end end describe 'filter_by_hero' do let(:hero_a) { create(:hero) } let(:hero_b) { create(:hero) } before(:each) do create(:card, hero: hero_a) create(:card) create(:card, hero: hero_b) end context 'when hero is empty' do it 'should return card without hero' do expect(Card.filter_by_hero('').length).to eq 1 end end context 'when hero == All' do it 'should not filter by hero' do expect(Card.filter_by_hero('All').length).to eq 3 end end context 'when hero is a correct hero id' do it 'should filter by hero id' do expect(Card.filter_by_hero(hero_a.id.to_s).length).to eq 1 end end end end
true
6e1478b5bf63bd4839258952b9969860b5f0a61c
Ruby
txus/kleisli
/test/kleisli/composition_test.rb
UTF-8
1,956
3.140625
3
[ "MIT" ]
permissive
require 'test_helper' class CompositionTest < Minitest::Test def test_one_method f = F . first result = f.call([1]) assert Fixnum === result, "#{result} is not a number" assert_equal 1, result end def test_two_methods f = F . first . last result = f.call([1, [2,3]]) assert Fixnum === result, "#{result} is not a number" assert_equal 2, result end def test_one_function my_first = lambda { |x| x.first } f = F . fn(&my_first) result = f.call([1]) assert Fixnum === result, "#{result} is not a number" assert_equal 1, result end def test_two_functions my_first = lambda { |x| x.first } my_last = lambda { |x| x.last } f = F . fn(&my_first) . fn(&my_last) result = f.call([1, [2,3]]) assert Fixnum === result, "#{result} is not a number" assert_equal 2, result end def test_one_function_one_block my_last = lambda { |x| x.last } f = F . fn { |x| x.first } . fn(&my_last) result = f.call([1, [2,3]]) assert Fixnum === result, "#{result} is not a number" assert_equal 2, result end def test_one_function_one_method my_last = lambda { |x| x.last } f = F . first . fn(&my_last) result = f.call([1, [2,3]]) assert Fixnum === result, "#{result} is not a number" assert_equal 2, result end def test_undefined_method f = F . foo assert_raises(NoMethodError) { f.call(1) } end def test_identity assert_equal 1, F.call(1) end def test_partially_applied_method f = F . split(":") result = f.call("localhost:9092") assert Array === result, "#{result} is not an array" assert_equal ["localhost", "9092"], result end def test_partially_applied_fn split = lambda { |x, *args| x.split(*args) } f = F . fn(":", &split) result = f.call("localhost:9092") assert Array === result, "#{result} is not an array" assert_equal ["localhost", "9092"], result end end
true
6a6d37c080c92845c02a9aa5f778ef0d35c3c2ce
Ruby
cider-load-test/decawell
/fusor_controller/duty_cycle_study.rb
UTF-8
445
3.140625
3
[]
no_license
#http://en.wikipedia.org/wiki/Pulse-width_modulation wavelength = 10.0 #length in seconds for the wavelength duty_cycle = 0.7 # a float between 0 and 1 time_on = wavelength*duty_cycle start_time = Time.now() state = true while true time_now = Time.now() (duration = (time_on) ) if state (duration = (wavelength - time_on)) unless state if ((time_now - start_time) > (duration)) state = !state start_time = time_now end puts state end
true
a6f0c3f4c8b61cb7745aeaf7cd0ad9bf95ba0674
Ruby
BoTreeConsultingTeam/skill-hunt
/spec/models/user_spec.rb
UTF-8
5,986
2.59375
3
[]
no_license
require 'spec_helper' describe User do include_context 'initialize_common_objects' let(:user) { User.new } let!(:errors) { user.save; user.errors } it { should respond_to(:first_name) } it { should respond_to(:last_name) } it { should respond_to(:gender) } it { should respond_to(:email) } it { should respond_to(:password) } it { should respond_to(:blocked) } it { should respond_to(:country_id) } context "#first_name" do it "cannot be blank" do expect(errors[:first_name]).to_not be_empty end it "when blank shows user-friendly message" do expect(errors[:first_name]).to include("is required") end end context "#last_name" do it "cannot be blank" do expect(user.errors[:last_name]).to_not be_empty end it "when blank shows user-friendly message" do expect(user.errors[:last_name]).to include("is required") end end context "#gender" do it "cannot be blank" do expect(errors[:gender]).to_not be_empty end it "when not selected shows user-friendly message" do expect(errors[:gender]).to include("must be selected") end it "must have only one character" do user.gender= "M" * 1 user.save expect(errors[:gender]).to be_empty end it "must be either F or M" do user.gender = "A" user.save expect(errors[:gender]).to include("must be M or F") end end context "#email" do it "email cannot be blank " do user.save expect(user.errors[:email]).to_not be_empty end it "email already taken" do user = User.new(first_name:"Ankur", last_name: "Vyas", gender: "M", email: "[email protected]", password: "Ankur12@#", blocked: "false", country_id: india_country.id ) user.save expect(user.errors).to be_empty other_user = User.new(first_name:"Ambika", last_name: "Bhatt", gender: "F", email: "[email protected]", password: "Ankur12@#", blocked: "false", country_id: india_country.id ) other_user.save expect(other_user.errors[:email]).to include 'has already been taken' end it "must be in proper format" do user.email = "[email protected]" user.save expect(user.errors[:email]).to_not be_empty end end context "#password" do it "cannot be blank" do expect(errors[:password]).to_not be_empty end it "when blank shows custom message " do expect(errors[:password]).to include("is required") end context "is invalid" do it "when have less than 8 characters" do user.password = "a"*6 user.save expect(errors[:password]).to include("should be more than 8 characters") end it "when have more than 20 characters" do user.password = "a"*21 user.save expect(errors[:password]).to include("should be less than 20 characters") end it "when does not contain 1 captial letter, special symbol or number" do user.password = "abcdefghi" user.save expect(errors[:password]).to include("should have atleast 1 capital letter, 1 special symbol and 1 number") end end context "is valid" do it "when have exact 1 captial letter, 1 special symbol and 1 number " do user.password = 'Ankurr1t@' user.save expect(user.errors[:password]).to be_empty end it "when have more than 1 captial letter, special symbol or number" do user.password = "AAnkur12!@" user.save expect(user.errors[:password]).to be_empty end end end context "#country_id" do it "cannot be blank" do expect(errors[:country_id]).to_not be_empty end it "when not selected shows user-friendly message" do expect(errors[:country_id]).to include("must be selected") end end context "#blocked" do it "must not be blank" do expect(user.blocked).to be false end it "must be false by default" do expect(user.blocked).to be false end it "must be true when set to true" do user.blocked = true expect(user.blocked).to be true end end context "#is_administrator?" do it "returns false when user does not have any role" do expect(user.is_administrator?).to be false end it "returns true when user is assigned administrator role" do user.role = admin_user_role expect(user.is_administrator?).to be true end it "returns false when user is not assigned administrator role" do user.role = end_user_role expect(user.is_administrator?).to be false end end context "#is_end_user?" do it "returns false when user does not have any role" do expect(user.is_end_user?).to be false end it "returns true when user is assigned administrator role" do user.role = end_user_role expect(user.is_end_user?).to be true end it "returns false when user is not assigned administrator role" do user.role = admin_user_role expect(user.is_end_user?).to be false end end context "#is_company_representative" do it "returns false when user does not have any role" do expect(user.is_company_representative?).to be false end it "returns true when user is assigned administrator role" do user.role = company_representative_role expect(user.is_company_representative?).to be true end it "returns false when user is not assigned administrator role" do user.role = admin_user_role expect(user.is_company_representative?).to be false end end end
true
42365e48b11d47274140e7dde7b61bd2399bc599
Ruby
jeremiahkellick/algorithms-coursework
/shell_sort.rb
UTF-8
273
3.03125
3
[]
no_license
require_relative "insertion_sort" def shell_sort(arr, &prc) prc ||= Proc.new { |a, b| a <=> b } interval = 1; interval = interval * 3 + 1 while interval < arr.length / 3 while interval >= 1 insertion_sort(arr, interval, &prc) interval /= 3 end arr end
true
07c484d4374f0def17d5ec6e9a2ef3cf8f7b8787
Ruby
despino/Five_Problems
/alt.rb
UTF-8
184
3.15625
3
[]
no_license
@l1 = [1,2,3] @l2 = ['a','b','c'] @final_arr = [] def alternate @l1.each do |i| @final_arr << @l1[i-1] @final_arr << @l2[i-1] end puts @final_arr.join ', ' end alternate
true
ac5f6679d754153c0b823e8e77ffbca0ddc4a3ba
Ruby
vladfreel/primes
/prime.rb
UTF-8
278
3.625
4
[]
no_license
require 'prime' primes = [] Prime.take_while do |n| if primes.sum + n < 1000000 primes.push(n) end end until Prime.prime?(primes.sum) primes.pop end puts puts "Biggest sum of consecutive primes below million: #{primes.sum}" puts puts "Primes: #{primes.join(' , ')}"
true
584ab4e901636ff0660e6fa006d5cfad44b62664
Ruby
ReseauEntourage/entourage-ror
/lib/mixpanel_tools.rb
UTF-8
1,583
2.53125
3
[ "MIT" ]
permissive
module MixpanelTools class ResponseError < RuntimeError; end def self.request path, params={} puts "GET #{path} #{params.inspect}" response = HTTParty.get( File.join("https://mixpanel.com/api/2.0/", path.to_s), basic_auth: { username: ENV['MIXPANEL_SECRET'] }, query: params ) body = response.parsed_response if response.code.to_s[0] != '2' || body.has_key?('error') p body raise ResponseError, body['error'] end body end def self.paginated_request path, params={} Enumerator.new do |y| pagination = {} page_size = nil loop do response = request path, pagination.merge(params) response['results'].each do |result| y << result end page_size = response['page_size'] || page_size break if response['results'].count < page_size pagination = { session_id: response['session_id'], page: response['page'] + 1 } end end end def self.get_people params={} paginated_request('/engage/', params) end def self.batch_update updates updates.each_slice(50).map do |updates| updates.each do |update| update['$token'] = ENV['MIXPANEL_TOKEN'] update['$ip'] ||= '0' update['$ignore_time'] = !update.has_key?('$time') end puts "POST /engage/ with #{updates.count} updates" HTTParty.post( "https://api.mixpanel.com/engage/", body: { data: Base64.strict_encode64(JSON.fast_generate(updates)) } ).parsed_response end end end
true
870a40e9a6a1359c8c1bc739b0538af9ab172d12
Ruby
schneems/repl_runner
/test/repl_runner_test.rb
UTF-8
2,227
2.515625
3
[ "MIT" ]
permissive
require 'test_helper' class ReplRunnerTest < Test::Unit::TestCase def test_local_irb_stream ReplRunner.new(:irb).run do |repl| repl.run('111+111') {|r| assert_match '222', r } repl.run("'hello' + 'world'") {|r| assert_match 'helloworld', r } repl.run("a = 'foo'") repl.run("b = 'bar'") {} # test empty block doesn't throw exceptions repl.run("a * 5") {|r| assert_match 'foofoofoofoofoo', r } end ReplRunner.new(:irb, "irb").run do |repl| repl.run('111+111') {|r| assert_match '222', r } repl.run("'hello' + 'world'") {|r| assert_match 'helloworld', r } repl.run("a = 'foo'") repl.run("b = 'bar'") {} # test empty block doesn't throw exceptions repl.run("a * 5") {|r| assert_match 'foofoofoofoofoo', r } end end def test_forgot_run assert_raise RuntimeError do ReplRunner.new(:irb, "irb") do |repl| end end end def test_does_not_have_trailing_prompts ReplRunner.new(:irb, "irb ").run do |repl| repl.run('111+111') {|r| assert_equal "=> 222", r.strip } end end def test_ensure_exit assert_raise(ReplRunner::NoResultsError) do ReplRunner.new(:irb, "irb -r ./test/require/never-boots.rb", startup_timeout: 2).run do |repl| repl.run('111+111') {|r| } end end end def test_bash ReplRunner.new(:bash).run do |repl| repl.run('ls') {|r| assert_match /Gemfile/, r} end end def test_unknown_command assert_raise ReplRunner::UnregisteredCommand do ReplRunner.new(:zootsuite) end end def test_zipping_commands commands = [] results = [] commands << "a = 3\n" commands << "b = 'foo' * a\n" commands << "puts b" repl = ReplRunner.new(:irb) zip = repl.zip(commands.join("")) repl.run do |repl| commands.each do |command| repl.run(command.rstrip) {|r| results << r } end end expected = [[commands[0].rstrip, results[0]], [commands[1].rstrip, results[1]], [commands[2].rstrip, results[2]]] assert_equal expected, zip assert_equal expected.flatten, zip.flatten end end
true
4d0e5a2075a20ba43c3acccc897db8b32b685738
Ruby
Lasiorhine/factorial
/lib/factorial.rb
UTF-8
374
3.71875
4
[]
no_license
require 'pry' # Computes factorial of the input number and returns it def factorial(number) accumulator = 1 if number.nil? raise ArgumentError.new("You can't factorialize 'nil.' ") elsif number == 0 || number == 1 return 1 else until number == 0 do accumulator = number * accumulator number -= 1 end end return accumulator end
true
57583d4f0cd2f9db4ff827652a7ae518636c99ea
Ruby
amandaungco/api-muncher
/lib/edamam_api_wrapper.rb
UTF-8
1,456
2.96875
3
[]
no_license
require 'httparty' require 'awesome_print' class EdamamApiWrapper BASE_URL = "https://api.edamam.com/" APP_KEY = ENV["app_key"] APP_ID = ENV["app_id"] RETURN_RECIPE= "http%3A%2F%2Fwww.edamam.com%2Fontologies%2Fedamam.owl%23" def self.list_recipes(search_term) url = BASE_URL + "search?q=#{search_term}" + "&app_id=#{APP_ID}&app_key=#{APP_KEY}&from=0&to=100" data = HTTParty.get(url) recipes = [] if data["hits"] data["hits"].map do |hit| recipes << make_recipe(hit["recipe"]) end return recipes else return [] end end# return new recipes array def self.format_uri(uri) change_uri = uri.split('_') r = change_uri[1] return r end def self.make_recipe(data_source) if (data_source["uri"]).include? "_" uri = format_uri(data_source["uri"]) else uri = data_source["uri"] end image_url = data_source["image"] recipe_url = data_source["url"] label = data_source["label"] dietaryinformation = data_source["healthLabels"] ingredients = data_source["ingredientLines"] recipe = Recipe.new(label, uri, image_url, recipe_url, dietaryinformation, ingredients) return recipe end def self.find_recipe(uri) api_url = BASE_URL + "search?&app_id=#{APP_ID}&app_key=#{APP_KEY}" + "&r=#{RETURN_RECIPE}#{uri}" data = HTTParty.get(api_url) if data[0] make_recipe(data[0]) else return [] end end# return n end
true
740b7f47b26d8924c794e4177a333af3007dd60c
Ruby
trschmitt/notes
/09/4-thursday-44/ancestors.rb
UTF-8
602
3.390625
3
[]
no_license
require 'date' class Elephant def initialize(name, born_on) @name = name @born_on = born_on end attr_accessor :name # attr_reader :name # def name # @name # end # attr_writer :name # def name=(other) # @name = other # end def a_method self end def self.repopulate 3.times.map do new("Clone", Time.now) end end end charles = Elephant.new("Charles", Date.new(1972, 6, 12)) charles.name charles.name=("Charles IV") charles.name charles.a_method def charles.bark "woof" end charles.bark Elephant.repopulate # require 'pry' # binding.pry
true
3a2721e2e1f0b570c72ee64775445e9b65894ce4
Ruby
samuelmolinari/dissertation
/ror/DissertationSystem/app/controllers/account_controller.rb
UTF-8
2,224
2.53125
3
[]
no_license
=begin Controller related to the account management @version 06/06/2012 @author Samuel Molinari =end require 'fileutils' require 'RMagick' class AccountController < ApplicationController # No need of authentification when creating an account before_filter :require_auth, :except => [:create] ## # Create an account/user def create # Init. new user @user = User.new # Only create when it's a post request if request.post? # Init. new user with posted parameters @user = User.new(params[:user]) # Save new user if @user.save # Create session for the new user session[:user] = @user.id # Redirect to the photo management page respond_to do |format| format.html { redirect_to :controller => :manage, :action => :index } end end end end ## # Delete account/user def delete # Delete the session or cookies of that user trying to log out if [email protected]? cookies.delete :user session.delete :user end # Destroy user @user.destroy end ## # User profile page def profile # If it's a post request, update user profile/attributes if request.post? @user.update_attributes(params[:user]) end end ## # Allow user to build its own face profile for the face recognition def train_new_face # Temp reference number and face id must be given for the training to take place if params[:ref] && params[:face] # Load face image img = Magick::ImageList.new(@user.tmp_private_location+"#{params[:ref]}/#{params[:file]}") # Create new face in DB face = Face.create({ :user_id => @user.id, }) # Create directory for the face to be stored if it doesn't already exists FileUtils.mkdir_p(face.dir) # Copy the face image to that location img.write(face.location) # Remove temporary dir FileUtils.remove_dir(@user.tmp_private_location+params[:ref]+"/") end # Redirect to the previous page respond_to do |format| format.html { redirect_to :back } end end end
true
a5cef4b229000f7835b058265dbff4d87bc53787
Ruby
AhmedAmin90/indeed_web_scraper
/lib/scraper.rb
UTF-8
1,589
3.03125
3
[ "MIT" ]
permissive
require 'httparty' require 'nokogiri' require 'rainbow' require 'csv' class Scraper attr_accessor :all_jobs, :vacancies, :page_number, :posted_days, :url_date def initialize @vacancies = ['front+end+developer', 'back+end+developer&', 'full+sack+developer', 'ruby+developer', 'javascript+developer'] @page_number = ['', '&start=10', '&start=20', '&start=30', '&start=40'] @posted_days = [1, 3, 7, 14, 'all'] @all_jobs = [] @url_date = url_date end def scraper(job, days, pages) looking_for = vacancies[job - 1] date_posted = posted_days[days - 1] page_result = page_number[pages - 1] url_date = if days == 5 "https://www.indeed.com/jobs?q=#{looking_for}&l=Remote" else "https://www.indeed.com/jobs?q=#{looking_for}&l=Remote&fromage=#{date_posted}#{page_result}" end self.url_date = url_date end def make_array scrapped_page = Nokogiri::HTML(HTTParty.get(@url_date).body) job_cards = scrapped_page.css('div.jobsearch-SerpJobCard') job_cards.each do |vacancy| one_job = { title: vacancy.css('a.jobtitle').text, company: vacancy.css('span.company').text, link: "https://www.indeed.com#{vacancy.css('a')[0].attributes['href'].value}", date: vacancy.css('span.date').text } all_jobs << one_job end all_jobs end def page_result Rainbow("\nThe link of the page: \n").bold.underline + Rainbow("#{url_date}\n").purple end end
true
e163b5c43d96b9067e13955b44d820d24a60e58c
Ruby
COASST/coasst-old
/vendor/plugins/deep_copy/lib/deepcopy.rb
UTF-8
159
2.59375
3
[]
no_license
# Deep Copy # # ruby lacks deep copying, use marshal to create true duplicates class Object def m_dup Marshal.load(Marshal.dump(self)) end end
true
b81435fba1821ea13c2d6370a3932dbf3edecfd6
Ruby
marcwright/WDI_ATL_1_Instructors
/REPO - DC - Students/w02/d02/Elaine/calculator/lib/calc.rb
UTF-8
456
3.71875
4
[]
no_license
class Calculator def add(number1, number2) return number1 + number2 end def subtract(number1, number2) return number1 - number2 end def power(number1, number2) return number1**number2 end def sum(array) return array.reduce(0, :+) end def multiply(*nums) return nums.reduce(:*) end def factorial(number) if number < 2 return 1 else return number * factorial(number - 1) end end end
true
1368e5d74521ddc55330d09e09aedbcfa701345a
Ruby
harrybrown/vendor-import-export
/lib/extensions/ruby_patches.rb
UTF-8
1,824
2.9375
3
[]
no_license
module Kernel def caller_method_name parse_caller(caller(2).first).last end def parse_caller(at) if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at file = Regexp.last_match[1] line = Regexp.last_match[2].to_i method = Regexp.last_match[3] [file, line, method] end end end class Hash # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3} def except(*keys) rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys) reject { |key,| rejected.include?(key) } end def except!(*keys) replace(except(*keys)) end # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1} def only(*keys) self.dup.reject { |k,v| !keys.include? k.to_sym } end # lets through the keys in the argument # >> {:one => 1, :two => 2, :three => 3}.pass(:one) # => {:one=>1} def pass(*keys) tmp = self.clone tmp.delete_if {|k,v| ! keys.include?(k) } tmp end # blocks the keys in the arguments # >> {:one => 1, :two => 2, :three => 3}.block(:one) # => {:two=>2, :three=>3} def block(*keys) tmp = self.clone tmp.delete_if {|k,v| keys.include?(k) } tmp end end module Enumerable def map_if( &block ) find_all(&block).map(&block) end end class Array def compact_strip self.delete_if{|x| x.blank?} end end class String def is_number? self.to_i.to_s == self ? true : false end end # class Object # # Pretty self explanatory # def in_development? # return Rails.env.development? ? true : false # end # # def in_production? # return Rails.env.production? ? true : false # end # # def in_test? # return Rails.env.test? ? true : false # end # # def in_env?(inquiry) # return Rails.env.send("#{inquiry}?") ? true : false # end # end
true
78cf66db03b0bcfa1379cf373962db9e266349e3
Ruby
softsprocket/async_tcpsocket
/test.rb
UTF-8
376
2.78125
3
[]
no_license
#!/usr/bin/ruby require 'async_tcpsocket' socket = AsyncTCPSocket.new socket.once :error, Proc.new { |err| STDERR.puts "Error: #{err}" socket.close } socket.once :close, Proc.new { |err| socket.close } socket.on :data, Proc.new { |data| puts "#{data}" } socket.connect 'localhost', 80 socket.puts "GET / HTTP 1.1\r\n\r\n" #wait for return key gets socket.close
true
b684d7f4c13d659c400c44196c5549b1fb6339a2
Ruby
AntonBarkan/tgt
/lib/CodeHolders/method_holder.rb
UTF-8
667
3.421875
3
[]
no_license
class MethodHolder attr_accessor :method_name attr_accessor :method_return_type attr_accessor :parameters def initialize(method_name) @method_name = method_name @parameters = Array.new end def addParameter(field) @parameters << field end def print methodString = 'def ' + method_name if [email protected]? methodString += '(' end @parameters.each_with_index do |param, index| methodString += param if index != @parameters.size - 1 methodString += ', ' end end if [email protected]? methodString += ')' end methodString += "\n" methodString += "end\n" end end
true
e6b6c42ee037ecfecffcc5b7de2bcdecdf3d27c3
Ruby
Zander2/BEWD11-ClassWork
/ruby/Array_loops/Lab2.rb
UTF-8
110
3.109375
3
[]
no_license
array_copy = [1, 2, 3, 4, 5] # your code destination = array_copy.select {|i| i < 4 } puts destination
true
71374396017eb68c341ad7490dd2506cd00fd6b4
Ruby
joyhuangg/oo-relationships-practice
/app/models/location.rb
UTF-8
454
2.84375
3
[]
no_license
class Location @@all = [] attr_accessor :location def self.all @@all end def initialize(location:) @location = location @@all << self end def self.least_clients Location.all.min_by {|location| location.clients} end def trainers Trainer.all.select {|trainer| trainer.locations.include?(self)} end def clients result = [] trainers.each {|trainer| result.concat(trainer.clients)} result end end
true
fadc5f9f2b196b296c658ecbb4c2d40ad03b08fd
Ruby
AnaTeresaDona/Cepas2
/app/models/wine.rb
UTF-8
779
2.671875
3
[]
no_license
class Wine < ApplicationRecord has_many :wine_strains, dependent: :destroy has_many :strains, through: :wine_strains has_many :oenologist_wines, dependent: :destroy has_many :oenologists, through: :oenologist_wines def addStrainPercent(percents) percents.each do |strain_id, percentage| if percentage != "" temp_strain = self.wine_strains.where(strain_id: strain_id.to_i).first temp_strain.percentage = percentage.to_i temp_strain.save end end end def getPercentageByStrainId(strain_id) if self.wine_strains.where(strain_id: strain_id.to_i).first self.wine_strains.where(strain_id: strain_id.to_i).first.percentage end end end
true
920f1d463d6463c4dc573c0fc5df1cb9139f047c
Ruby
ozPop/reverse-each-word-001-prework-web
/reverse_each_word.rb
UTF-8
172
3.65625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(s) arrS = s.split(" ") arrS.each { |el| el.reverse! }.join(" ") end def reverse_each_word2(s) s.split.collect { |el| el.reverse }.join(" ") end
true
88e1bd44293774bb7c14a8ad9be8f2b63f25f832
Ruby
andryjohn/ruby_concept-
/hashes.rb
UTF-8
176
3.125
3
[]
no_license
states = { :Pennsylvania => "PA", "New York" => "NY", "California" => "CA", "Oregon" => "Oregon" } puts states[:Pennsylvania] #or #puts states[1] using index
true
9e4a9943b47f1b180f622a20973b1659cbf48f07
Ruby
BonbonLemon/Chess
/sliding_subclasses.rb
UTF-8
842
3.03125
3
[]
no_license
require_relative 'sliding_pieces' class Rook < SlidingPiece MOVE_DIRECTIONS = [ [ 0, 1], [ 1, 0], [-1, 0], [ 0, -1] ] def to_s ' ♖ '.colorize(@color) end def move_dirs MOVE_DIRECTIONS end def dup Rook.new(@pos, @color, nil) end end class Bishop < SlidingPiece MOVE_DIRECTIONS = [ [ 1, 1], [ 1,-1], [-1,-1], [-1, 1] ] def to_s ' ♗ '.colorize(@color) end def move_dirs MOVE_DIRECTIONS end def dup Bishop.new(@pos, @color, nil) end end class Queen < SlidingPiece MOVE_DIRECTIONS = [ [ 1, 1], [ 1,-1], [-1,-1], [-1, 1], [ 0, 1], [ 1, 0], [-1, 0], [ 0,-1] ] def to_s ' ♕ '.colorize(@color) end def move_dirs MOVE_DIRECTIONS end def dup Queen.new(@pos, @color, nil) end end
true
9dad79a6b3b6e3d20f18651c7e2eaed8d754dd70
Ruby
ensallee/the-bachelor-todo-nyc-web-042318
/lib/bachelor.rb
UTF-8
1,799
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def get_first_name_of_season_winner(data, season) data.each do |season_number, season_data| if season_number == season season_data.each do |keys| keys.each do |person_key, person_value| if person_value == "Winner" full_name=keys["name"].split return full_name[0] end end end end end end def get_contestant_name(data, occupation) data.each do |season_number, season_data| season_data.each do |keys| keys.each do |person_key, person_value| if person_value == occupation return keys["name"] end end end end end def count_contestants_by_hometown(data, hometown) counter = 0 data.each do |season_number, season_data| season_data.each do |keys| keys.each do |person_key, person_value| if person_value == hometown counter += 1 end end end end counter end def get_occupation(data, hometown) data.each do |season_number, season_data| season_data.each do |keys| keys.each do |person_key, person_value| if person_value == hometown return keys["occupation"] end end end end end def get_average_age_for_season(data, season) data.each do |season_number, season_data| if season_number == season ages_array=[] season_data.each do |keys| keys.each do |person_key, person_value| if person_key == "age" integer_age=keys[person_key].to_f ages_array.push(integer_age) end end end total=0 ages_array.each do |number| total += number end final_average=total.to_f / ages_array.length.to_f return final_average.round end end end
true
bb5314478ac858bd60af37d98bd8609666aa2f78
Ruby
yui-knk/pycall
/lib/pycall/pyobject.rb
UTF-8
4,598
2.765625
3
[ "MIT" ]
permissive
module PyCall Py_LT = 0 Py_LE = 1 Py_EQ = 2 Py_NE = 3 Py_GT = 4 Py_GE = 5 RICH_COMPARISON_OPCODES = { :< => Py_LT, :<= => Py_LE, :== => Py_EQ, :!= => Py_NE, :> => Py_GT, :>= => Py_GE }.freeze module PyObjectMethods def rich_compare(other, op) opcode = RICH_COMPARISON_OPCODES[op] raise ArgumentError, "Unknown comparison op: #{op}" unless opcode other = Conversions.from_ruby(other) unless other.kind_of?(PyObject) return other.null? if self.null? return false if other.null? value = LibPython.PyObject_RichCompare(self, other, opcode) raise "Unable to compare: #{self} #{op} #{other}" if value.null? value.to_ruby end RICH_COMPARISON_OPCODES.keys.each do |op| define_method(op) {|other| rich_compare(other, op) } end def py_none? to_ptr == LibPython.Py_None.to_ptr end def kind_of?(klass) case klass when PyTypeObject Types.pyisinstance(self, klass) else super end end end class PyObject < FFI::Struct include PyObjectMethods def self.null new(FFI::Pointer::NULL) end alias __aref__ [] alias __aset__ []= def [](*indices) if indices.length == 1 indices = indices[0] else indices = PyCall.tuple(*indices) end PyCall.getitem(self, indices) end def []=(*indices_and_value) value = indices_and_value.pop indices = indices_and_value if indices.length == 1 indices = indices[0] else indices = PyCall.tuple(*indices) end PyCall.setitem(self, indices, value) end def +(other) value = LibPython.PyNumber_Add(self, other) return value.to_ruby unless value.null? raise PyError.fetch end def -(other) value = LibPython.PyNumber_Subtract(self, other) return value.to_ruby unless value.null? raise PyError.fetch end def *(other) value = LibPython.PyNumber_Multiply(self, other) return value.to_ruby unless value.null? raise PyError.fetch end def /(other) value = LibPython.PyNumber_TrueDivide(self, other) return value.to_ruby unless value.null? raise PyError.fetch end def coerce(other) [Conversions.from_ruby(other), self] end def call(*args, **kwargs) args = PyCall::Tuple[*args] kwargs = kwargs.empty? ? PyObject.null : PyCall::Dict.new(kwargs).__pyobj__ res = LibPython.PyObject_Call(self, args.__pyobj__, kwargs) return res.to_ruby if LibPython.PyErr_Occurred().null? raise PyError.fetch end def method_missing(name, *args, **kwargs) if PyCall.hasattr?(self, name) PyCall.getattr(self, name) else super end end def to_s s = LibPython.PyObject_Repr(self) if s.null? LibPython.PyErr_Clear() s = LibPython.PyObject_Str(self) if s.null? LibPython.PyErr_Clear() return super end end s.to_ruby end alias inspect to_s end class PyTypeObject < FFI::Struct include PyObjectMethods def ===(obj) obj.kind_of? self end def inspect "pytype(#{self[:tp_name]})" end end def self.getattr(pyobj, name, default=nil) name = check_attr_name(name) value = LibPython.PyObject_GetAttrString(pyobj, name) if value.null? return default if default raise PyError.fetch end value.to_ruby end def self.setattr(pyobj, name, value) name = check_attr_name(name) value = Conversions.from_ruby(value) return self unless LibPython.PyObject_SetAttrString(pyobj, name, value) == -1 raise PyError.fetch end def self.hasattr?(pyobj, name) name = check_attr_name(name) 1 == LibPython.PyObject_HasAttrString(pyobj, name) end def self.check_attr_name(name) return name.to_str if name.respond_to? :to_str return name.to_s if name.kind_of? Symbol raise TypeError, "attribute name must be a String or a Symbol: #{name.inspect}" end private_class_method :check_attr_name def self.getitem(pyobj, key) pykey = Conversions.from_ruby(key) value = LibPython.PyObject_GetItem(pyobj, pykey) return value.to_ruby unless value.null? raise PyError.fetch end def self.setitem(pyobj, key, value) pykey = Conversions.from_ruby(key) value = Conversions.from_ruby(value) return self unless LibPython.PyObject_SetItem(pyobj, pykey, value) == -1 raise PyError.fetch end end
true
72f6cca55265e9241ef97471a81dcfd403b1d003
Ruby
locomote/translations_checker
/lib/translations_checker/locale_file_key_map.rb
UTF-8
1,070
2.65625
3
[ "MIT" ]
permissive
module TranslationsChecker class LocaleFileKeyMap def initialize(content) @content = content end def key_at(line_number) key_map[line_number] end def key_line(key) key_map.key(key) end private attr_reader :content def lines content.yaml.lines end def key_lines lines.each_with_index.map do |line, index| indent, key = line.scan(%r{(\A\s*)(?:(\w[/\w]+):)?}).flatten [index + 1, indent.size / 2, key] end.select(&:last) end def parent_key(key_map, depth) key_map.values.reverse_each.detect { |key_path| key_path.size <= depth } end # :reek:ManualDispatch def key_map @key_map ||= begin key_map = key_lines.each_with_object({}) do |(line_number, depth, key), memo| memo[line_number] = [*parent_key(memo, depth), key] end key_map.select do |_, (*parent_key, name)| parent = content[parent_key] parent.respond_to?(:key?) && parent.key?(name) end end end end end
true
8489531ea670820356f350d0c85bc4f73af6b623
Ruby
chian88/course_120
/exercise/easy3/5.rb
UTF-8
383
3.21875
3
[]
no_license
class Television def self.manufacturer end def model end end tv = Television.new tv.manufacturer # can't work because #manufacturer is a class method. tv.model # will work because #model is a instance method. Television.manufacturer # will work because #manufacturer is a class method. Television.model # can't work because #model is a instance method.
true
a7cb01bb2f87258df70fbafcf5797a462a1dff07
Ruby
MarioRoncador/blocitoff-rails
/db/seeds.rb
UTF-8
437
2.703125
3
[]
no_license
include Faker # Create Users 5.times do User.create!( email: Faker::Internet.email, password: Faker::Internet.password, ) end User.create!( email: "[email protected]", password: "111111", ) users = User.all # Create Items 50.times do Item.create!( name: Faker::Lorem.sentence, user: users.sample, ) end items = Item.all puts "Seed finished" puts "#{User.count} users created" puts "#{Item.count} items created"
true
f5db12d080a0beb6558b54e9b135fbc8dc2a13e5
Ruby
6twenty/project_euler
/ruby/problem_15/program.rb
UTF-8
532
3.6875
4
[]
no_license
# Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner. # # How many routes are there through a 20x20 grid? # # THE MATRIX @solutions = [[2], [3,6], [4,10,20]] # results of "1", "2" and "3" # start at "4" (4..20).to_a.each do |x| array = [] index = (x-2) previous = @solutions[index] array << start = (x+1) (x-2).times do |a| array << (array.last + previous[a+1]) end array << (array.last * 2) @solutions << array end puts @solutions.last
true
b4ee797df7a5fd3da0a12aef001beb76d6023447
Ruby
oriff/multiplier
/create_channel.rb
UTF-8
1,472
2.875
3
[ "MIT" ]
permissive
require 'rubygems' require 'json' require 'yaml' require 'rest_client' $base_url = "www.pushray.com:8080/api/v1/" # Function that create channel with rest_api and check if channel exsists first def create_channel(channel) puts "running create_channel, channel = #{channel.inspect}" key_check = RestClient.get "#{$base_url}/channels/#{channel["key"]}" #space should be escaped :) if key_check.nil? || key_check['key'].nil? #params = { 'key' => channel["key"], 'name' => channel["name"], 'description' => channel["description"] }, result = RestClient.post "#{$base_url}/channels/create", channel.to_json, :content_type => :json puts result.inspect # Test for checking that request is valid else puts "Error, Channel is already exsists - #{key_check.inspect}" end end def create_message(message) puts "running create_message, message = #{message.inspect}" #params = { 'key' => message["key"], 'name' => message["name"], 'description' => message["description"] }, result = RestClient.post "#{$base_url}/messages/create/", message.to_json, :content_type => :json puts result.inspect # Test for checking that request is valid end channel_list = YAML.load_file("#{File.dirname(__FILE__)}/poll_list.yml") channel_list.each do |channel| create_channel(channel) end messages_list = YAML.load_file("#{File.dirname(__FILE__)}/twitter_accounts.yml") messages_list.each do |message| create_message(message) end
true
a0925435824779d41c19c682345624cac79bbf10
Ruby
nrozmus/looping-for-online-web-prework
/for.rb
UTF-8
163
2.8125
3
[]
no_license
def using_for checklist = 1..10 def using_for checklist = 1..10 #your code here end for checklist in checklist do puts "Wingardium Leviosa" end end
true
8b481362d4a97fef6a16addd584c2c0a77027fd9
Ruby
nezetic/ruby-xbmc
/lib/ruby-xbmc.rb
UTF-8
15,671
2.84375
3
[]
no_license
#!/usr/bin/env ruby =begin ruby-xbmc ruby-xbmc is a ruby wrapper for the XBMC Web Server HTTP API. It provides a remote access to any XBMC running on the local network, in a simple way (methods follow the ones from XBMC API). Example: irb(main):001:0> xbmc = XBMC::XBMC.new(hostname, port, user, pass) => #<XBMC::XBMC:0x1128e7c> irb(main):002:0> pp xbmc.GetMediaLocation("music") [{"name"=>"Jazz", "type"=>"1", "path"=>"/mnt/data/Music/Jazz/"}, {"name"=>"Electro", "type"=>"1", "path"=>"/mnt/data/Music/Electro/"}, {"name"=>"Metal", "type"=>"1", "path"=>"/mnt/data/Music/Metal/"}, {"name"=>"Last.fm", "type"=>"1", "path"=>"lastfm://"}] Copyright (C) 2009 Cedric TESSIER Contact: nezetic.info This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. =end begin require 'rubygems' rescue LoadError end require 'iconv' require 'uri' require 'open-uri' require 'nokogiri' class Object def caller_method caller[1] =~ /`([^']*)'/ and $1 end end class Array def to_hash(keys) return nil if(keys.length != self.length) Hash[*keys.zip(self).flatten] end end class String def transliterate Iconv.iconv('ASCII//IGNORE//TRANSLIT', 'UTF-8', self).to_s rescue self end end # Module for the library # #=Usage example # First, we need to create the link between us and XBMC: # # xbmc = XBMC::XBMC.new(hostname, port, user, pass) # # then, we can do a lot of things, following XBMC API. # #==Set current XBMC Volume # xbmc.SetVolume(95) #==Get currently playing file data # xbmc.GetCurrentlyPlaying #==Get a files list from music library, with insertion dates # xbmc.GetMediaLocation("music", "/mnt/data/Music/Jazz/", true) #==Retrieve playlist contents # xbmc.GetPlaylistContents #==Get some system information # xbmc.GetSystemInfoByName("weather.location","weather.temperature") # module XBMC #User Agent Name NAME = 'Ruby/XBMC' #Library Version VERSION = '0.1' #Complete User-Agent USER_AGENT = "%s %s" % [NAME, VERSION] # scheme used in HTTP transfers (http/https) SCHEME = "http" # XBMC Command API CMDPATH = "/xbmcCmds/xbmcHttp?command=" MUSIC_PLAYLIST = 0 VIDEO_PLAYLIST = 1 TYPE_DIRECTORY = 1 TYPE_FILE = 0 #Error class when not authenticated class XBMC::UnauthenticatedError < StandardError def initialize(m=nil) super(m.nil? ? "You are not connected (no user/password)": m) end end #Error class when password and user mismatched class XBMC::WrongCredentialsError < XBMC::UnauthenticatedError def initialize() super("User / password mismatched") end end #Connection class used to specify credentials and proxy settings class Connection #network hostname attr_accessor :host #network port attr_accessor :port #username attr_accessor :user #password attr_accessor :password #proxy url eg. http://user:pass@proxy:8080 attr_writer :proxy def initialize(host, port=nil, user=nil, pass=nil) @host=host @port=port @user=user @password=pass end #proxy getter def proxy return @proxy unless @proxy.nil? ENV["proxy"] end def exec(command) #:nodoc: command.rstrip! command += "()" if command[-1,1] != ")" url = SCHEME + "://" + host + ":" + port + CMDPATH + command begin return open(url,"r",http_opts) rescue OpenURI::HTTPError => e if e.io.status.first.to_i == 401 raise (user.nil? ? UnauthenticatedError.new : WrongCredentialsError.new ) end raise e end end protected def http_opts #:nodoc: ret={} ret[:http_basic_authentication]=[user,password] unless user.nil? ret[:proxy]=proxy ret["User-Agent"]=USER_AGENT return ret end end class XBMC attr_accessor :error ##### XBMC API # Commands that Retrieve Information def GetMediaLocation(type, path=nil, showdate=false) if(showdate) parse_asdictlist(cmd(with_args(type, path, "showdate")), ["name", "path", "type", "date"]) else parse_asdictlist(cmd(with_args(type, path)), ["name", "path", "type"]) end end def GetShares(type) parse_asdictlist(cmd(with_args(type)), ["name", "path"]) end def GetCurrentPlaylist parse(cmd()) end def GetCurrentlyPlaying song = parse_asdict(cmd()) return nil if(song.length <= 1) song end def GetCurrentSlide parse(cmd()) end def GetDirectory(directory, mask=" ", showdate=false) if(showdate) parse_asdictlist(cmd(with_args(directory, mask, 1)), ["path", "date"]) else parse_aslist(cmd(with_args(directory, mask))) end end def GetGuiDescription parse_asdict(cmd()) end def GetGuiSetting(type, name) parse(cmd(with_args(type, name))) end def GetGuiStatus parse_asdict(cmd()) end def GetMovieDetails puts "Not implemented" end def GetPercentage parse(cmd()) end def GetPlaylistContents(playlist=nil) parse_aslist(cmd(with_args(playlist))) end def GetPlaylistLength(playlist=nil) parse(cmd(with_args(playlist))) end def GetPlaylistSong(position=nil) parse(cmd(with_args(position))) end def GetPlaySpeed parse(cmd()) end def GetMusicLabel puts "Not implemented" end def GetRecordStatus puts "Not implemented" end def GetVideoLabel puts "Not implemented" end def GetSlideshowContents parse_aslist(cmd()) end def GetSystemInfo(*args) parse_aslist(cmd(with_args(args))) end def GetSystemInfoByName(*args) parse_aslist(cmd(with_args(args))) end def GetTagFromFilename(fullpath) parse_asdict(cmd(with_args(fullpath))) end def GetThumbFilename puts "Not implemented" end def GetVolume parse(cmd()) end def GetLogLevel parse(cmd()) end def QueryMusicDatabase puts "Not implemented" end def QueryVideoDatabase puts "Not implemented" end # Commands that Modify Settings def AddToPlayList(media, playlist=nil, mask=nil, recursive=true) if(recursive == true) recursive = 1 else recursive = 0 end success?(parse(cmd(with_args(media, playlist, mask, recursive)))) end def AddToSlideshow(media, mask="[pictures]", recursive=true) if(recursive == true) recursive = 1 else recursive = 0 end success?(parse(cmd(with_args(media, mask, recursive)))) end def ClearPlayList(playlist=nil) success?(parse(cmd(with_args(playlist)))) end def ClearSlideshow success?(parse(cmd())) end def Mute success?(parse(cmd())) end def RemoveFromPlaylist(item, playlist=nil) success?(parse(cmd(with_args(item, playlist)))) end def SeekPercentage(percentage) success?(parse(cmd(with_args(percentage)))) end def SeekPercentageRelative(percentage) success?(parse(cmd(with_args(percentage)))) end def SetCurrentPlaylist(playlist) success?(parse(cmd(with_args(playlist)))) end def SetGUISetting(type, name, value) success?(parse(cmd(with_args(type, name, value)))) end def SetPlaylistSong(position) success?(parse(cmd(with_args(position)))) end def SetPlaySpeed(speed) success?(parse(cmd(with_args(speed)))) end def SlideshowSelect(filename) success?(parse(cmd(with_args(filename)))) end def SetVolume(volume) success?(parse(cmd(with_args(volume)))) end def SetLogLevel(level) success?(parse(cmd(with_args(level)))) end def SetAutoGetPictureThumbs(boolean=true) success?(parse(cmd(with_args(boolean)))) end # Commands that Generate Actions def Action(code) # Sends a raw Action ID (see key.h) success?(parse(cmd(with_args(code)))) end def Exit success?(parse(cmd())) end def KeyRepeat(rate) success?(parse(cmd(with_args(rate)))) end def Move(deltaX, deltaY) success?(parse(cmd(with_args(deltaX, deltaY)))) end def Pause success?(parse(cmd())) end def PlayListNext success?(parse(cmd())) end def PlayListPrev success?(parse(cmd())) end def PlayNext success?(parse(cmd())) end def PlayPrev success?(parse(cmd())) end def PlaySlideshow(directory=nil, recursive=true) success?(parse(cmd(with_args(directory, recursive)))) end def PlayFile(filename, playlist=nil) success?(parse(cmd(with_args(filename, playlist)))) end def Reset success?(parse(cmd())) end def Restart success?(parse(cmd())) end def RestartApp success?(parse(cmd())) end def Rotate success?(parse(cmd())) end def SendKey(buttoncode) success?(parse(cmd(with_args(buttoncode)))) end def ShowPicture(filename) success?(parse(cmd(with_args(filename)))) end def Shutdown success?(parse(cmd())) end def SpinDownHardDisk success?(parse(cmd())) end def Stop success?(parse(cmd())) end def TakeScreenshot(width=300, height=200, quality=90, rotation=0, download=true, filename="xbmc-screen.jpg", flash=true, imgtag=false) if(imgtag) imgtag = "imgtag" else imgtag = nil end parse(cmd(with_args(filename, flash, rotation, width, height, quality, download, imgtag))) end def Zoom(zoom) success?(parse(cmd(with_args(zoom)))) end # Commands that Modify Files def FileCopy(src, dst) success?(parse(cmd(with_args(src, dst)))) end def FileDelete(filename) success?(parse(cmd(with_args(filename)))) end def FileDownload(filename, bare=nil) parse(cmd(with_args(filename, bare))) end def FileDownloadFromInternet(url, filename=nil, bare=nil) parse(cmd(with_args(url, filename, bare))) end def FileExists(filename) return true if parse(cmd(with_args(filename))) == "True" false end def FileSize(filename) parse(cmd(with_args(filename))).to_i end def FileUpload(filename, contents) success?(parse(cmd(with_args(filename, contents)))) end ##### END XBMC API def initialize(host, port=nil, user=nil, pass=nil) @@connection = Connection.new(host, port, user, pass) end def error? not error.nil? end def print_error $stderr.puts "Error: " + @error if @error != nil end def host @@connection.host end def port @@connection.port end # private members private def with_args(*args) args.flatten! if args.length == 1 command = self.caller_method command += "(" cmdargs = "" args.each {|arg| cmdargs += (";" + (URI.escape(arg.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")))) unless arg.nil? } cmdargs = cmdargs[1..-1] command += cmdargs unless cmdargs.nil? command += ")" end def cmd(command=nil) command = self.caller_method if command.nil? response = @@connection.exec(command) end def success?(res) (not error? and not res.nil? and res == "OK") end def parse_resp(response) doc = Nokogiri::HTML(response) list = (doc/"li") if(list.length > 0) text = list.inner_text if(text[0,5] == "Error") idx = text.index(':') if(idx != nil) @error = text[(idx+2)..-1] else @error = "Unknown error" end else @error = nil end else # file download (screenshot) return doc end list end def parse(response) resp = parse_resp(response).inner_text.transliterate return "" if error? resp end def parse_aslist(response) list = [] parse_resp(response).each {|item| list.push(item.inner_text.transliterate.chomp)} return [] if error? list end def parse_asdictlist(response, keys) list = [] parse_aslist(response).each {|item| list.push((item.split(';').collect {|x| x.transliterate.chomp.rstrip}).to_hash(keys) )} return [] if error? list end def parse_asdict(response) dict = {} resp = parse_resp(response) return dict if error? resp.each {|item| item = item.inner_text.transliterate idx = item.index(':') next if item == nil key = item[0..idx-1] value = item[idx+1..-1].chomp dict[key]=value } dict end end end
true
7063fde13cea30447b99882d16e5835430b61263
Ruby
pv97/Poker
/spec/tdd_spec.rb
UTF-8
1,421
3.375
3
[]
no_license
require "tdd" require "rspec" describe "#uniq"do it "correctly removes duplicates" do expect([1,1,2,3].my_uniq).to eq([1,2,3]) end it "doesn't modifty a non duplicate array" do expect([1,2,3].my_uniq).to eq([1,2,3]) end it "doesn't modifty a non duplicate array" do expect([1,2,3].my_uniq).to eq([1,2,3]) end it "handles empty arrays" do expect([].my_uniq).to eq([]) end end describe "#two_sum" do it "doesn't sum two indices which don't add to two" do expect([-2, 0, 4].two_sum).to eq([]) end it "correctly returns two indices which sum to zero" do expect([-2, 2, 5].two_sum).to eq([[0,1]]) end it "correctly orders two indices, mutliptle times" do expect([0,0,0].two_sum).to eq([[0,1], [0,2], [1,2]]) end end describe "#my_transpose" do it "doesn't modify empty arrays" do expect([[]].my_transpose).to eq([[]]) end it "correctly transposes a 2x2 matrix" do expect([[0,1],[2,3]].my_transpose).to eq([[0,2],[1,3]]) end it "correctly transposes a 3x3 matrix" do expect([[0,1,2],[3,4,5],[6,7,8]].my_transpose).to eq([[0,3,6],[1,4,7],[2,5,8]]) end describe "#stock_picker" do it "doesn't sell stock before it is bought" do test = [100,45,2,12,56].stock_picker expect(test[0]>test[1]).to be false end it "buys low sells high" do expect([2,45,56,12,3].stock_picker).to eq([0,2]) end end end
true
cd34f28889871c1132fc0b592bde80e0973a6a7b
Ruby
tpkg/client
/lib/tpkg/thirdparty/net-ssh-2.1.0/lib/net/ssh/transport/cipher_factory.rb
UTF-8
3,677
2.8125
3
[ "MIT" ]
permissive
require 'openssl' require 'net/ssh/transport/identity_cipher' module Net; module SSH; module Transport # Implements a factory of OpenSSL cipher algorithms. class CipherFactory # Maps the SSH name of a cipher to it's corresponding OpenSSL name SSH_TO_OSSL = { "3des-cbc" => "des-ede3-cbc", "blowfish-cbc" => "bf-cbc", "aes256-cbc" => "aes-256-cbc", "aes192-cbc" => "aes-192-cbc", "aes128-cbc" => "aes-128-cbc", "idea-cbc" => "idea-cbc", "cast128-cbc" => "cast-cbc", "[email protected]" => "aes-256-cbc", "arcfour128" => "rc4", "arcfour256" => "rc4", "arcfour512" => "rc4", "none" => "none" } # Ruby's OpenSSL bindings always return a key length of 16 for RC4 ciphers # resulting in the error: OpenSSL::CipherError: key length too short. # The following ciphers will override this key length. KEY_LEN_OVERRIDE = { "arcfour256" => 32, "arcfour512" => 64 } # Returns true if the underlying OpenSSL library supports the given cipher, # and false otherwise. def self.supported?(name) ossl_name = SSH_TO_OSSL[name] or raise NotImplementedError, "unimplemented cipher `#{name}'" return true if ossl_name == "none" return OpenSSL::Cipher.ciphers.include?(ossl_name) end # Retrieves a new instance of the named algorithm. The new instance # will be initialized using an iv and key generated from the given # iv, key, shared, hash and digester values. Additionally, the # cipher will be put into encryption or decryption mode, based on the # value of the +encrypt+ parameter. def self.get(name, options={}) ossl_name = SSH_TO_OSSL[name] or raise NotImplementedError, "unimplemented cipher `#{name}'" return IdentityCipher if ossl_name == "none" cipher = OpenSSL::Cipher::Cipher.new(ossl_name) cipher.send(options[:encrypt] ? :encrypt : :decrypt) cipher.padding = 0 cipher.iv = make_key(cipher.iv_len, options[:iv], options) if ossl_name != "rc4" key_len = KEY_LEN_OVERRIDE[name] || cipher.key_len cipher.key_len = key_len cipher.key = make_key(key_len, options[:key], options) cipher.update(" " * 1536) if ossl_name == "rc4" return cipher end # Returns a two-element array containing the [ key-length, # block-size ] for the named cipher algorithm. If the cipher # algorithm is unknown, or is "none", 0 is returned for both elements # of the tuple. def self.get_lengths(name) ossl_name = SSH_TO_OSSL[name] return [0, 0] if ossl_name.nil? || ossl_name == "none" cipher = OpenSSL::Cipher::Cipher.new(ossl_name) key_len = KEY_LEN_OVERRIDE[name] || cipher.key_len cipher.key_len = key_len return [key_len, ossl_name=="rc4" ? 8 : cipher.block_size] end private # Generate a key value in accordance with the SSH2 specification. def self.make_key(bytes, start, options={}) k = start[0, bytes] digester = options[:digester] or raise 'No digester supplied' shared = options[:shared] or raise 'No shared secret supplied' hash = options[:hash] or raise 'No hash supplied' while k.length < bytes step = digester.digest(shared + hash + k) bytes_needed = bytes - k.length k << step[0, bytes_needed] end return k end end end; end; end
true
ee86a1718efc277292ed68e37895a1c4ca2058d2
Ruby
Andrewglass1/texter
/app/models/station_matcher.rb
UTF-8
419
3.171875
3
[]
no_license
class StationMatcher require 'amatch' def initialize(input) @input = input end def match station = Station.all.detect{|station| fuzzy_match(station.name)} station ||= nickname_match end def nickname_match Station.all.detect {|station| station.nicknames.any?{|nn| fuzzy_match(nn)}} end def fuzzy_match(matching) m = Amatch::Jaro.new(@input) m.match(matching) > 0.9 end end
true
48e6a4347c188436c0975feba9cc8b5c474efd2c
Ruby
serioja90/fleck
/examples/actions.rb
UTF-8
1,875
2.75
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # frozen_string_literal: true require 'fleck' user = ENV['USER'] || 'guest' pass = ENV['PASS'] || 'guest' CONCURRENCY = (ENV['CONCURRENCY'] || 2).to_i SAMPLES = (ENV['SAMPLES'] || 10).to_i QUEUE = 'actions.example.queue' Fleck.configure do |config| config.default_user = user config.default_pass = pass config.loglevel = Logger::DEBUG end connection = Fleck.connection(host: '127.0.0.1', port: 5672, user: user, pass: pass, vhost: '/') client = Fleck::Client.new(connection, QUEUE, concurrency: CONCURRENCY.to_i) class MyConsumer < Fleck::Consumer configure queue: QUEUE, concurrency: CONCURRENCY.to_i action 'hello', "An action which returns 'Hello'" def hello ok! result: 'Hello', message: 'Ciao' end action 'ciao', "An action which returns 'Ciao'" param :world, type: 'boolean', required: true, default: false def my_custom_method ok! params[:world] ? 'Ciao, Mondo!' : 'Ciao!' end action :aloha param :number, type: 'integer', clamp: [1, 10], required: true param :name, type: 'string', default: 'John Doe', required: true def my_aloha ok! "#{params[:number]}. Aloha, #{params[:name]}!" end def not_an_action logger.warn("I'm not an action, so you should not be able to call me!") end end actions = %i[hello ciao aloha not_an_action] SAMPLES.to_i.times do |num| action = actions.sample name = ['John Doe', 'Willie Wonka', 'Billie Smith'].sample client.request(action: action, params: { num: num, name: name, number: rand * 100, world: %w[yes no].sample }, timeout: 5) do |_, response| if response.status == 200 Fleck.logger.info "ACTION: (#{action.inspect}) #{response.body.inspect}" else Fleck.logger.error "ACTION: (#{action.inspect}) #{response.errors.join(', ')} --- #{response.body.inspect}" end end end
true
ea79cad08756f2708ed882ea0992a3f60182e6f7
Ruby
buntine/bolverk
/lib/operations/or.rb
UTF-8
853
2.875
3
[]
no_license
class Bolverk::Operations::Or < Bolverk::Operations::Base map_to "0111" parameter_layout [ [:register_a, 4], [:register_b, 4], [:destination, 4] ] # Performs an OR operation on register_a and register_b and stores the result in "destination". # # Example: # 725A => 0111001001011010=> OR the contents of registers 2 and 5 and store the result in register A. def execute operand_a = @emulator.register_read(@register_a) operand_b = @emulator.register_read(@register_b) result = perform_or(operand_a, operand_b) @emulator.register_write(@destination, result) end private # Performs an OR operation on two binary codes. def perform_or(mask, source) result = "" (0..mask.length-1).each do |byte| result.concat((mask[byte] == ?0 and source[byte] == ?0) ? "0" : "1") end result end end
true
566b22a73b9655c3743609495961ea0fe0fe3c7a
Ruby
Michael-Gr/CodeKatas
/Can_santa_save_christmas.rb
UTF-8
1,182
3.953125
4
[]
no_license
################# # Link to kata: # ################# # # https://www.codewars.com/kata/5857e8bb9948644aa1000246 # ################ # Description: # ################ # # Oh no! Santa's little elves are sick this year. He has to distribute the presents on his own. # But he has only 24 hours left. Can he do it? # Your job is to determine if Santa can distribute all the presents in 24 hours. # # Your Task: # # You will get an array as input with time durations as string in the following format: # "hh:mm:ss" # # Each duration is a present Santa has to distribute. # # Return true or false whether he can do it in 24 hours or not. # ########### # Answer: # ########### def determineTime(durations) h = [] m = [] s = [] if durations.empty? return true else durations.each do |time| split_time = time.split(":").map(&:to_i) h << split_time[0] m << split_time[1] s << split_time[2] end hours_seconds = h.inject(:+) * 3600 minutes_seconds = m.inject(:+) * 60 sum_time = hours_seconds + minutes_seconds + s.inject(:+) if durations.empty? || sum_time > 86400 return false else return true end end end
true
da24a6ba8a0f59d62d1940588c19e9fe82783f29
Ruby
Lorenzo892/Ironhack-bootcamp
/Week1/Day3-Ironhack/gameofrooms.rb
UTF-8
2,057
4.15625
4
[]
no_license
class Room def initialize(name, welcome) @name = name @welcome = welcome end def name @name end def enter_room puts @welcome end end class Game_array def initialize(x,y) @x = x @y = y end def position (game_array) puts "Game is ON, try to get to the treasure as fast as possible" while game_array [@x][@y].name != "Dead" #|| @x < 4 || @y < 5) puts game_array [@x][@y].name game_array [@x][@y].enter_room puts "Chose between W, S, E, N" option = gets.chomp if option == "W" @y-=1 elsif option == "S" @x +=1 elsif option == "E" @y +=1 elsif option == "N" @x -=1 end end if game_array [@x][@y].name == "Dead" puts " You are dead !!!!" end end end boring = Room.new("Boring Room", "welcome to the boring room, hurry up if you don't to get bored") sleeping_room = Room.new("Sleeping Room", "Welcome to the sleepy Room, if you keep that way you are going to sleep forever") tropical = Room.new("Tropical Room", "Welcome to tropicos, it feels good for the moment but don't get relaxed") forest = Room.new("Forest", "This is the forest!! Run for your life!!") bridge = Room.new("Bridge", "Watch your step, you are getting closer") happy = Room.new("Happy", "Happy times for happy people, hope it stays the same") pirates = Room.new("Pirates", "Get ready to fight the Pirates!!") dead = Room.new("Dead", "GAME OVER you have reached the death room") christmas = Room.new("Christmas", "Christmas is around the corner") savana = Room.new("Savana", "Savana room, watch out for lions") heaven = Room.new("Heaven", "You are in heaven, WELCOME") treasure = Room.new("Treasure", "YOU MADE IT, you reached the last room!! Congrats") game_array = [ [boring, sleeping_room, dead, dead], [tropical, forest, bridge, treasure], [dead, happy, dead, heaven], [dead, pirates, christmas, savana] ] first_game = Game_array.new(0,0) first_game.position (game_array)
true
42ab442b466f39e164e5e32be5d64b6946195730
Ruby
leslieyi/postwork-data-structures-and-algorithms
/03-week-3--additional-practice/00-bonus-1--balancing-parenetheses/solutions/balancing_parentheses.rb
UTF-8
2,307
4.21875
4
[]
no_license
def balancing_parentheses(string) missing = 0 openings = 0 string.chars.each do |char| if char == '(' openings += 1 next end if openings > 0 openings -= 1 else missing += 1 end end missing + openings end if __FILE__ == $PROGRAM_NAME puts "Expecting: 0" puts balancing_parentheses('(()())') puts puts "Expecting: 2" puts balancing_parentheses('()))') puts puts "Expecting: 1" puts balancing_parentheses(')') # Don't forget to add your own! puts puts "Expecting: 0" puts balancing_parentheses('()') puts puts "Expecting: 1" puts balancing_parentheses('(') puts puts "Expecting: 2" puts balancing_parentheses(')(') puts puts "Expecting: 1" puts balancing_parentheses(')()') puts puts "Expecting: 2" puts balancing_parentheses(')((((()))((())))()(()))(') puts puts "Expecting: 3" puts balancing_parentheses(')))') puts puts "Expecting: 3" puts balancing_parentheses('(((') end # Please add your pseudocode to this file ################################################################################## # initialize missing to 0 (will store unmatched closing parens count) # initialize openings to 0 (will store opening parens count) # # iterate over string: # if char == '(': # increment openings # else: # if openings is 0: # increment missing # else: # decrement openings # # return missing + openings ################################################################################## # And a written explanation of your solution ################################################################################## # We can calculate the number of parentheses needed by counting the number of opening # parentheses that occur in the string and decrementing that count any time a closing # parenthesis is encountered after that. If we encounter a closing parenthesis and there # are no opening parentheses (openings = 0), we add to missing. Once we've iterated # over the whole string, we just need to add the missing count with the openings count, # since the openings count will track any opening parentheses for which there were no # matching closing ones. ##################################################################################
true
03cb1e9cf8ccd72ff3c51227477cd89e7b6d78c1
Ruby
telwell/project_tdd_minesweeper
/lib/square.rb
UTF-8
1,135
3.703125
4
[]
no_license
class Square attr_accessor :mine, :flag, :displayed, :surrounding_mines attr_reader :coords, :adjacent_squares def initialize(coords, size) # I know there are a bunch of instance # variables here but I need most of them # for this Square class. @coords = coords @size = size @mine = false @flag = false @displayed = false @adjacent_squares = get_adjacent_squares(@coords) @surrounding_mines = 0 end # Turns the square into a mine def make_mine @mine = true end # Turn a flag on or off def switch_flag @flag = !@flag end # Show a square as displayed def display_square @displayed = true end # Get adjacent squares # NOTE: For this method we don't need to put this on the # square class- should probably be part of the board. def get_adjacent_squares(coords) x, y, adj_squares = coords[0], coords[1], [] # Loop through the columns (x-1).upto(x+1) do |column| # Loop through the rows (y-1).upto(y+1) do |row| (adj_squares << [column, row]) if (row >= 1 && row <= @size) && (column >= 1 && column <= @size) && !(column == x && row == y) end end adj_squares end end
true
39a41e17504dddf9107aadc13e835bc7a9192684
Ruby
misoton665/Calculator
/main.rb
UTF-8
200
2.53125
3
[]
no_license
require 'treetop' require './calculator_node_classes' Treetop.load 'calculator' loop { print "$> " input = STDIN.gets tree = CalculatorParser.new.parse(input) puts "=> #{tree.eval.to_s}" }
true
2a497ad2922d0ca74f83f58b9af46a81c5f3e015
Ruby
vanrails/Learn-To-Program
/chapter05/fullnamegreeting.rb
UTF-8
291
3.21875
3
[]
no_license
# 5.6 page 25 # Full name greeting puts 'Hello, what\'s first name?' firstName = gets.chomp puts 'And your middle name?' middleName = gets.chomp puts 'Finally your last name?' lastName = gets.chomp puts 'Pleased to meet you ' + firstName + middleName + lastName
true
3d0caee1c3ec67a8186f8cd7054aa98ebcaf0123
Ruby
mattsan/withings
/lib/withings.rb
UTF-8
702
2.640625
3
[ "MIT" ]
permissive
require 'pathname' require 'csv' require 'ostruct' require 'time' require 'withings/version' require 'withings/activity' require 'withings/blood_pressure' require 'withings/height' require 'withings/sleep' require 'withings/weight' class Withings MODELS = { activity: Withings::Activity, blood_pressure: Withings::BloodPressure, height: Withings::Height, sleep: Withings::Sleep, weight: Withings::Weight } def initialize(path) @path = ::Pathname.new(path) MODELS.each do |name, model| define_singleton_method(name) { instance_variable_get("@#{name}") || instance_variable_set("@#{name}", model.new(@path + model::FILENAME)) } end end end
true
2504127cf54c01addccc6fa3e0a1c1f468ad8db1
Ruby
square/shuttle
/app/models/blob.rb
UTF-8
4,198
2.734375
3
[ "Apache-2.0" ]
permissive
# Copyright 2014 Square Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Represents a Git blob found in a Project and imported. A Blob record is # created to indicate that this blob has already been scanned for strings, # optimizing future imports. # # Associations # ============ # # | | | # |:----------|:-----------------------------------------------------| # | `project` | The {Project} whose repository this blob belongs to. | # | `keys` | The {Key Keys} found in this blob. | # | `commits` | The {Commit Commits} with this blob. | # # Fields # ====== # # | | | # |:----------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------| # | `sha` | The Git identifier for the blob. | # | `path` | The file path for the blob. | # | `parsed` | If `true`, at least one worker finished parsing the {Key Keys} for this blob. Set to true when {Commit commit} import is finished if parsing the blob didn't error out. | # | `errored` | If `true`, parsing this blob has failed. Defaults to false. | class Blob < ActiveRecord::Base belongs_to :project, inverse_of: :blobs has_many :blobs_keys, inverse_of: :blob, dependent: :delete_all has_many :keys, through: :blobs_keys has_many :blobs_commits, inverse_of: :blob, dependent: :delete_all has_many :commits, through: :blobs_commits extend DigestField digest_field :path, scope: :with_path validates :project, presence: true validates :sha, presence: true, uniqueness: {scope: [:project_id, :path_sha], on: :create} validates :path, presence: true attr_readonly :project_id, :sha, :path_sha # Scopes scope :with_sha, -> (s) { where(sha: s) } # Searches the blob for translatable strings, creates or updates Translations, # and associates them with this Blob. Imported strings are approved by # default. If the base locale is provided (or no locale), pending Translations # for the Project's other locales are also created (and filled with 100% # matches if possible). # # @param [Class] importer The Importer::Base subclass to process this blob. # @param [Commit] commit New Keys will be added to this Commit's `keys` association. # @raise [Git::BlobNotFoundError] If the blob could not be found in the Git # repository. def import_strings(importer, commit) blob! # make sure blob exists importer.new(self, commit).import end # @return [Rugged::Blob] The Git blob this Blob represents. def blob project.repo.lookup(sha) end # Same as {#blob}, but fetches the repository of the blob SHA isn't found. # # @return [Rugged:Blob] The Git blob this Blob represents. # @raise [Git::BlobNotFoundError] If the blob could not be found in the Git # repository. def blob! unless blob_object = project.find_or_fetch_git_object(sha) raise Git::BlobNotFoundError, sha end blob_object end end
true
3069db69234abe55d9749ac1f505f162771e11a9
Ruby
samwich/advent_of_code_2020
/24/test_day24.rb
UTF-8
1,226
3
3
[]
no_license
require 'test/unit' require 'strscan' require_relative 'floor' class TestDay24 < Test::Unit::TestCase def setup @floor = Floor.new('./test_input') end def test_file_load expected = [:se, :se, :nw, :ne, :ne, :ne, :w, :se, :e, :sw, :w, :sw, :sw, :w, :ne, :ne, :w, :se, :w, :sw] assert_equal(expected, @floor.instruction_lists.first) end def test_esew list = [:e, :se, :w] @floor.run_list(list) assert_equal(true, @floor.tiles[[0,-1,1]]) end def test_nwwswee list = [:nw, :w, :sw, :e, :e] @floor.run_list(list) assert_equal(true, @floor.tiles[[0,0,0]]) end def test_part1 assert_equal(10, @floor.part1) end def test_part2_one_day @floor.part1 @floor.process_floor! assert_equal(15, @floor.black_tile_count) end def test_part2_d3 @floor.part1 3.times do @floor.process_floor! end assert_equal(25, @floor.black_tile_count) end def test_part2_d4 @floor.part1 4.times do |i| @floor.process_floor! puts "Day #{i+1}: #{@floor.black_tile_count}" end assert_equal(14, @floor.black_tile_count) end def test_part2_full @floor.part2 assert_equal(2208, @floor.black_tile_count) end end
true
0f4302afc621ffdbae44dc663986bdff3fe679a1
Ruby
gmccreight/mdpg
/spec/mdpg/services/page_links_spec.rb
UTF-8
2,697
2.53125
3
[]
no_license
# frozen_string_literal: true require_relative '../../spec_helper' describe PageLinks do before do $data_store = memory_datastore @user = create_user @zebra_page = Page.create name: 'zebra-training', text: 'page 1' @alaska_page = Page.create name: 'alaska-crab', text: "link to [[mdpgpage:#{@zebra_page.id}]]" @user.add_page @zebra_page @user.add_page @alaska_page @user_pages = UserPages.new(@user) @page_links = PageLinks.new(@user) end describe 'internal links to user-clickable link' do it 'should take the name of the page by default' do assert_equal('link to [zebra-training](/p/zebra-training)', @page_links.internal_to_user_clickable_links(@alaska_page.text)) end it 'should be able to override the page name' do @alaska_page.text = "link to [[mdpgpage:#{@zebra_page.id}]]((YO, Zebras!))" @alaska_page.save assert_equal('link to [YO, Zebras!](/p/zebra-training)', @page_links.internal_to_user_clickable_links(@alaska_page.text)) end end describe 'internal links to page name links for editing' do it 'should work' do link_text = "hey there [[mdpgpage:#{@zebra_page.id}]] foo" assert_equal('hey there [[zebra-training]] foo', @page_links.internal_links_to_links_for_editing(link_text)) end end describe 'page names to ids' do it 'should work if page exists' do assert_equal("[[mdpgpage:#{@zebra_page.id}]]", @page_links.page_name_links_to_ids('[[zebra-training]]')) end describe 'where the page does not exist' do it 'should not make change if no such page exists' do assert_equal('[[no-such-page]]', @page_links.page_name_links_to_ids('[[no-such-page]]')) end it 'should create a page if the link had new- at the start' do assert_match(/\[\[mdpgpage:\d+\]\]/, @page_links.page_name_links_to_ids('[[new-a-great-page]]')) new_page_id = @user_pages.find_page_with_name('a-great-page').id assert_equal 'a-great-page', Page.find(new_page_id).name end end end describe 'ids of the links' do it 'should return empty array if nothing' do assert_equal([], @page_links.get_page_ids('what foo')) end it 'should return a single page id' do assert_equal([@zebra_page.id], @page_links.get_page_ids("what [[mdpgpage:#{@zebra_page.id}]] foo")) end it 'should return multiple page ids' do text = "[[mdpgpage:#{@alaska_page.id}]] [[mdpgpage:#{@zebra_page.id}]]" assert_equal([@zebra_page.id, @alaska_page.id].sort, @page_links.get_page_ids(text).sort) end end end
true
c08c310b0818c097b9d5d381a6cefd2330055462
Ruby
marynavoitenko/vinyls-collection
/db/seeds.rb
UTF-8
1,397
2.71875
3
[]
no_license
# frozen_string_literal: true require 'csv' csv_text = File.read(Rails.root.join('lib', 'seeds', 'vinyls_collection.csv')) csv = CSV.parse(csv_text, headers: true, encoding: 'ISO-8859-1') csv.each do |row| # get all values of artists_tracks columns for the row artists_tracks = row.find_all do |i| i[0] == 'artists_names_track_title' && !i[1].nil? end.map(&:last) # build tracks_attributes tracks_attributes = artists_tracks.map do |artists_track| artists, track = artists_track.split('-').map(&:strip) artists = artists.split(',').map(&:strip) artists_attributes = artists.map do |artist| { name: artist } end { title: track, artists_attributes: artists_attributes } end release_date = Date.strptime(row['vinyl_release_date'], '%m/%d/%Y') vinyl_params = { code: row['vinyl_code'], title: row['vinyl_title'], release_date: release_date, label_attributes: { name: row['label_name'] }, genres_attributes: [ { name: row['genre_name'] } ], tracks_attributes: tracks_attributes } vinyl = Vinyl.new(vinyl_params) if vinyl.save p "#{vinyl.title} created" else p "#{vinyl.title} NOT created" end end p "Created #{Label.count} labels" p "Created #{Vinyl.count} vinyls" p "Created #{Track.count} tracks" p "Created #{Artist.count} artists" p "Created #{Genre.count} genres"
true
b1b90f43bfdff034241e27c28b025fd8b1655ea6
Ruby
eternal44/hacker_rank
/warm_up/library_fines.rb
UTF-8
504
3.3125
3
[]
no_license
def fee(actual, expected) if actual[2] > expected[2] fine = 10_000 elsif actual[1] > expected[1] && actual[2] >= expected[2] fine = (actual[1] - expected[1]) * 500 elsif actual[0] > expected[0] && actual[1] >= expected[1] && actual[2] >= expected[2] fine = (actual[0] - expected[0]) * 15 else fine = 0 end puts fine end t = "28 2 2015" y = "15 4 2015" t = t.split(" ").map(&:to_i) y = y.split(" ").map(&:to_i) fee(t,y) # puts t.inspect # puts y.inspect
true
18de04425cbf1c69c2bb6d1e8fbfae636ed989ce
Ruby
funeace/Project-Euler
/Problem005_pattern1.rb
UTF-8
797
3.5
4
[]
no_license
# 2520 は 1 から 10 の数字の全ての整数で割り切れる数字であり, そのような数字の中では最小の値である. # では, 1 から 20 までの整数全てで割り切れる数字の中で最小の正の数はいくらになるか. # 20の倍数であることは確定しているから 割り算の結果が0になればいい next = i * 20 # a % i == 0 # 動いたが重すぎ(答え232792560 もうちょっと小さいと思って回して後悔した) # # 初期値を20に設定 number = 20 answer = 0 until number == 0 (1..20).each do |i| # loopの数字で割り切れるか確認 if number % i == 0 && i == 20 answer = number number = number % i elsif number % i != 0 number += 20 break end end end p answer
true
3907daa4e2bf4c4f906afb3aa3b0aa4713bcfdaf
Ruby
christian-marie/ns_connector
/lib/ns_connector/attaching.rb
UTF-8
1,249
2.6875
3
[ "MIT" ]
permissive
# Provide attach! and detach! methods module NSConnector::Attaching # Attach any number of ids to klass # Arguments:: # klass:: target class to attach to, i.e. Contact # attachee_id:: internal id of the record to make the attach(s) to # ids:: array of target ids # attributes:: optional attributes for the attach, i.e. {:role => -5} def attach!(klass, attachee_id, ids, attributes = nil) unless ids.kind_of?(Array) then raise ::ArgumentError, 'Expected ids to be an array' end NSConnector::Restlet.execute!( :action => 'attach', :type_id => type_id, :target_type_id => klass.type_id, :attachee_id => attachee_id, :attributes => attributes, :data => ids ) end # Unattach any number of ids to klass # Arguments:: # klass:: target class to detach from, i.e. Contact # attachee_id:: internal id of the record to make the detach(s) from # ids:: array of target class ids def detach!(klass, attachee_id, ids) unless ids.kind_of?(Array) then raise ::ArgumentError, 'Expected ids to be an array' end NSConnector::Restlet.execute!( :action => 'detach', :type_id => type_id, :target_type_id => klass.type_id, :attachee_id => attachee_id, :data => ids ) end end
true
2ff10e9daae93c821c91edd37fb5d729225c5060
Ruby
quentinbrasseur/rails-yelp-mvp
/db/seeds.rb
UTF-8
951
2.609375
3
[]
no_license
puts 'Cleaning database...' Restaurant.destroy_all puts 'Creating restaurants...' restaurants_attributes = [ { name: "Epicure au Bristol", address: "112 rue du Fg St-Honoré 75008 Paris", phone_number: "01 75 16 78 98", category: "french" }, { name: "The Waffle Factory", address: "30 rue du Lombard 1000 Bruxelles", phone_number: "02 50 56 78 47", category: "belgian" }, { name: "Pekin express", address: "Route de la soie 00000 Pekin", phone_number: "66 66 66 78 98", category: "chinese" }, { name: "Sushi express", address: "Rue du marché au poisson 1000 Bruxelles", phone_number: "02 24 50 78 41", category: "japanese" }, { name: "Ma che c****", address: "Strada vieilla 92828 Roma", phone_number: "92 14 59 68 24", category: "italian" } ] Restaurant.create!(restaurants_attributes) puts 'Finished!'
true
ccaa786ee845cfbb5108a5ef75f21cb9d3238ba9
Ruby
tw-oocamp-201512/homework
/homework1/zhou xing/taximeter/lib/checker.rb
UTF-8
695
3.3125
3
[]
no_license
require 'colorize' class Checker class << self def check(theme, error="", &block) begin block.call rescue InputError => e puts ("\n") puts ('-' * 60).colorize(:red) puts error puts ('-' * 60).colorize(:red) exit end end def check_input(input) check "#{input}", "#{input} should be a number" do p input.class raise InputError unless is_number? input end check "{input}", "#{input} should greater than 0" do raise InputError if input.to_i < 0 end true end private def is_number? string true if Float(string) rescue false end end end
true
569974912acde1387a79c69199fab9b5dc57fbb0
Ruby
rafamorais/Curso-ruby
/app/hello-world.rb
UTF-8
278
3.109375
3
[]
no_license
# puts "Hello World \n" # print "Hello World" + "\n" # printf("Hello World \n") puts "What is your name:" $name = STDIN.gets() print "Hello World:" + $name + "from School of NET \n" print "Hello " + "World\n" $value = "Rafa" # var - Local # @var - Instance # $var - Global
true
8f93c406b11ae878ceb6a1714350ab5c9217354d
Ruby
kunishi/algebra-ruby2
/sample/sample-set01.rb
UTF-8
272
3.078125
3
[ "MIT" ]
permissive
require "algebra" #intersection p Set[0, 1, 2, 4] & Set[1, 3, 5] == Set[1] p Set[0, 1, 2, 4] & Set[7, 3, 5] == Set.phi #union p Set[0, 1, 2, 4] | Set[1, 3, 5] == Set[0, 1, 2, 3, 4, 5] #membership p Set[1, 3, 2].has?(1) #inclusion p Set[3, 2, 1, 3] < Set[3, 1, 4, 2, 0]
true
b2461c3a4b5a015ec0a5510e63b4a9d328751163
Ruby
frankmeszaros/ruby-gui
/lib/gui/selector.rb
UTF-8
1,655
2.90625
3
[ "Apache-2.0" ]
permissive
# Copyright 2014 Noel Cower # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ----------------------------------------------------------------------------- # # selector.rb # Selector chain class. module GUI class Selector class << self def view_matches_attr(view, name, value) view.respond_to?(name) && view.__send__(name) == value end def build(selector_str) end end # singleton_class # The next attr_accessor :succ # Array of proc/lambda objects that receive a view and return true if # the view matches, otherwise nil/false attr_accessor :attributes attr_accessor :direct def initialize @succ = nil @attributes = [] @direct = false end # Whether this selector matches a view. def matches?(view) attributes.empty? || attributes.all? { |sel_attr| sel_attr[view] } end def find_match(view) # TODO: Grab leaves and test selectors in reverse order further = direct ? nil : self if matches?(view) return view unless @succ further = @succ end view.subviews.detect { |subview| further.find_match(subview) } end end # Selector end # GUI
true
96921933a45a85a94159560f69b4176f1c36c412
Ruby
fenixchen/rubystudy
/operator.rb
UTF-8
565
3.15625
3
[]
no_license
#!/usr/bin/ruby -w a, b, c = 10, 20, 30 (1..10).each do |i| printf "%d\t", i end puts (1...10).each do |i| printf "%d\t", i end puts foo = 42 puts defined? foo # => "local-variable" puts defined? $_ # => "local-variable" puts defined? nil puts defined? puts puts defined? yield MR_COUNT = 0 # 定义在主 Object 类上的常量 module Foo MR_COUNT = 0 ::MR_COUNT = 1 # 设置全局计数为 1 MR_COUNT = 2 # 设置局部计数为 2 end puts MR_COUNT # 这是全局常量 puts Foo::MR_COUNT # 这是 "Foo" 的局部常量
true