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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dca234dbfa5d29242d306532f9d6b9b41dd89e30
|
Ruby
|
alliestehney/world_cup
|
/lib/Team.rb
|
UTF-8
| 545
| 3.609375
| 4
|
[] |
no_license
|
class Team
attr_accessor :country, :eliminated, :players
def initialize(country)
@country = country
@players = []
@eliminated = false
end
def add_player(player)
@players << player
return @players
end
def eliminated?
return @eliminated
end
def players_by_position(desired_position)
@same_position = []
@players.each do |player|
@same_position << player.position == desired_position
end
return @same_position
end
end
| true
|
12c7f45051a0c14eaada05084a61fa41f5535006
|
Ruby
|
tejasdev23/ruby-on-rails-course2
|
/module4/i_reviewed/db/seeds.rb
|
UTF-8
| 791
| 2.6875
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Book.destroy_all
Book.create! [
{name: "eloquent ruby",author: "Russ Olsen"},
{name: "Computer graphics",author: "Pauline Baker"},
{name: "Introduction to algorithms",author: "Thomas cormen"},
{name: "agile development in ruby",author: "Tejas Patel"},
{name: "database management",author: "Navathe bhau"},
]
eloquent= Book.find_by name: "eloquent ruby"
eloquent.notes.create! [
{title:"Wow",note:"great book to learn ruby"},
{title:"funny",note:"Doesn't put you to sleep"}
]
| true
|
f3b7f64d1374dd1638beb415bf225c9a296e99fb
|
Ruby
|
malak-dev/TwO-O-Player-Math-Game
|
/player.rb
|
UTF-8
| 215
| 3.203125
| 3
|
[] |
no_license
|
class Player
def initialize name
@name = name
@lives=3
end
def name
@name
end
def get
@lives
end
def lives(points)
@lives +=points
end
def dead?
@lives <= 1
end
end
| true
|
eaa2eb22387f34a36ada41a17c32f0e7873ff21a
|
Ruby
|
fadynaffa3/bitmap_editor
|
/lib/validator.rb
|
UTF-8
| 852
| 2.796875
| 3
|
[] |
no_license
|
module Validator
def validate_size!(constant, finish, direction)
valid = if direction == 'V'
@image.length > finish && @image[0].length > constant
else
@image.length > constant && @image[0].length > finish
end
raise ValidationError, 'out of bound' unless valid
end
def validate_colour!(colour)
raise ValidationError, 'invalid colour' unless ('A'..'Z').cover?(colour)
end
def validate_file!(file_path)
return unless file_path.nil? || !File.exist?(file_path)
raise ValidationError, 'please provide correct file'
end
def validate_command!(method, command)
raise ValidationError if method.nil?
raise ValidationError unless method[:length] == command.length
raise ValidationError, 'There is no image' if method[:name] != 'create' && @image.nil?
end
end
| true
|
c6f4d950d9c1443b17a7c519f631910acfb7fd42
|
Ruby
|
adamdawkins/mavenlink-ruby
|
/lib/mavenlink/list.rb
|
UTF-8
| 1,260
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Mavenlink
class List
include Enumerable
attr_accessor :data
attr_reader :page_number
attr_reader :page_count
def initialize(klass, response, options = {}, params = {})
@meta = response["meta"]
@klass = klass
@params = params
@page_number = @meta["page_number"]
@page_count = @meta["page_count"]
@options = options
results = setup_results(response)
@data = results.map { |thing| klass.construct_from(thing, @options) }
end
def each(&blk)
@data.each(&blk)
end
def auto_paging_each(&blk)
return enum_for(:auto_paging_each) unless blk
page = self
loop do
page.each(&blk)
break if page.last_page?
page = page.next_page
end
end
def last_page?
@page_number == @page_count
end
def next_page
@klass.list(@params.merge(page: @page_number + 1), @options)
end
private def setup_results(response)
results = Util.results(response)
if (filters = Util.stringify_keys(@options[:filters]))
results.select! do |res|
filters.map { |key, value| res[key] == value }.all?
end
end
results
end
end
end
| true
|
931ffd1e7c24a50644526a5c3d69d1e0979cd272
|
Ruby
|
oguzpol/ruby-tutorial
|
/p-method.rb
|
UTF-8
| 105
| 2.859375
| 3
|
[] |
no_license
|
puts "POM"
p "Mehmet Oğuz POLAT"
puts "Hi there, this is a
big line break"
p "Hi there, this is a
big line break"
| true
|
5bb6426e3c9eae281d7c43dd14d7968f9627ad5f
|
Ruby
|
hasandeveloper/ecommerce-code
|
/app/models/order.rb
|
UTF-8
| 1,163
| 2.578125
| 3
|
[] |
no_license
|
class Order < ApplicationRecord
has_many :order_line_items
belongs_to :address
belongs_to :user
validates_presence_of :order_number, :order_date, :user_id, :total, :address_id
before_validation :set_number_date_total
after_create :move_to_order_line_items
after_create :empty_cart_line_items
after_create :update_stock
def set_number_date_total
self.order_number="DCT-#{Random.rand(1000)}"
self.order_date=Date.today
self.total=calculate_total
end
def calculate_total
total=0
self.user.cart_line_items.each do |line_item|
total+=(line_item.quantity * line_item.product.price)
end
return total
binding.pry
end
def move_to_order_line_items
self.user.cart_line_items.each do |line_item|
OrderLineItem.create(product_id: line_item.product_id, quantity: line_item.quantity, price: line_item.product.price, order_id: self.id)
end
end
def empty_cart_line_items
CartLineItem.delete(self.user.cart_line_items.pluck(:id))
end
def update_stock
self.order_line_items.each do |line_item|
line_item.product.update_attributes(stock: line_item.product.stock - line_item.quantity)
binding.pry
end
end
end
| true
|
e9b93cd160e684f402428e8b31ce62e48f548af8
|
Ruby
|
darthdeus/ghc-modi-wrapper
|
/bin/ghc-modi-wrapper
|
UTF-8
| 2,339
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require "socket"
require "fileutils"
PID_FILE = ".ghc-modi-wrapper.pid"
SOCKET_FILE = ".ghc-modi-wrapper.sock"
def cleanup_temp
FileUtils.rm_f(PID_FILE)
FileUtils.rm_f(SOCKET_FILE)
end
def running_pid
if File.exists?(PID_FILE)
File.read(PID_FILE).strip.to_i
else
# TODO - do this in a better way
-1
end
end
def running?
Process.getpgid(running_pid)
true
rescue Errno::ESRCH
false
end
def kill_server
if File.exists?(PID_FILE)
begin
Process.kill("HUP", running_pid)
puts "Server stopped."
# This can only happen if the pid file was present but the server
# wasn't running.
rescue Errno::ESRCH
puts "Process wasn't running, but pid file was present. Removing pid file."
FileUtils.rm(PID_FILE)
end
else
puts "Server isn't running."
end
end
def ensure_server_running
if running?
unless File.exists?(SOCKET_FILE)
puts "Server is broken, killing the server. Please retry your command"
`pkill #{running_pid}`
cleanup_temp
exit 1
end
else
Process.spawn("ghc-modi-wrapper-server -f")
sleep 1
end
end
def send_command(command)
connection = UNIXSocket.new(SOCKET_FILE)
connection.puts command
consuming = true
consumed = []
count = 0
while consuming
line = connection.gets
if (count > 20) || (line && line.strip == "OK") || line[0..1] == "NG"
consuming = false
else
consumed << line
end
count += 1
end
connection.close
consumed.join("")
end
command = ARGV[0]
File.write("/tmp/something.txt", ARGV.join(" "))
if command == "kill"
kill_server
else
case command
when "check"
ensure_server_running
puts send_command("check #{ARGV[1]}")
when "browse"
final_command = ARGV.join(" ").split(" ").grep(/^[^-]/).join(" ")
File.open("/tmp/something.txt", "a") do |f|
f.puts ARGV.join(" ")
f.puts "Final command: #{final_command}"
end
puts send_command(final_command)
when "version"
puts `ghc-mod version`
else
# if ARGV.join(" ") =~ / type /
# ensure_server_running
# puts send_command(ARGV.join(" ").sub(/.*type/, "type"))
# else
File.open("/tmp/something.txt", "a") do |f|
f.puts ARGV.join(" ")
end
puts `ghc-mod #{ARGV.join(" ")}`
# end
end
end
| true
|
4c395ed1552403787eb65ba7b14b8e09db9d95e5
|
Ruby
|
STCTbone/tictactoe
|
/lib/tasks/generate_moves.rake
|
UTF-8
| 430
| 2.78125
| 3
|
[] |
no_license
|
task generate_moves: :environment do
game = Game.create
next_player = (game.player_turn == 'X' ? 'O' : 'X')
game.squares.each_with_index do |square, position|
unless square
next_squares = game.squares.dup
next_squares[position] = game.player_turn
next_game = Game.create(next_player, next_squares)
game.moves << next_game
generate_moves(next_game)
end
end
end
| true
|
e29b882f2d95c21d21d775ae923750ba1cf00b46
|
Ruby
|
dariocravero/pendragon
|
/lib/pendragon/engine/recognizer.rb
|
UTF-8
| 1,706
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
module Pendragon
class Recognizer
def initialize(routes)
@routes = routes
end
def call(request)
pattern, verb, params = parse_request(request)
raise_exception(400) unless valid_verb?(verb)
fetch(pattern, verb){|route| [route, params_for(route, pattern, params)] }
end
private
# @!visibility private
def params_for(route, pattern, params)
route.params(pattern, params)
end
# @!visibility private
def valid_verb?(verb)
Pendragon::HTTP_VERBS.include?(verb.downcase.to_sym)
end
# @!visibility private
def fetch(pattern, verb)
_routes = @routes.select{|route| route.match(pattern) }
raise_exception(404) if _routes.empty?
result = _routes.map{|route| yield(route) if verb == route.verb }.compact
raise_exception(405, :verbs => _routes.map(&:verb)) if result.empty?
result
end
# @!visibility private
def parse_request(request)
if request.is_a?(Hash)
[request['PATH_INFO'], request['REQUEST_METHOD'].downcase.to_sym, {}]
else
[request.path_info, request.request_method.downcase.to_sym, parse_request_params(request.params)]
end
end
# @!visibility private
def parse_request_params(params)
params.inject({}) do |result, entry|
result[entry[0].to_sym] = entry[1]
result
end
end
# @!visibility private
def raise_exception(error_code, options = {})
raise ->(error_code) {
case error_code
when 400
BadRequest
when 404
NotFound
when 405
MethodNotAllowed.new(options[:verbs])
end
}.(error_code)
end
end
end
| true
|
1eb5fa4d512761a87e221bc3bae89a3fa6d47087
|
Ruby
|
rafaj777225/Cursocodeacamp
|
/Newbie/conceptW.rb
|
UTF-8
| 5,798
| 3.390625
| 3
|
[] |
no_license
|
Inheritance
Es una relacion entre 2 clases y tienen una jerarquia en donde las
clases hijas heredan comportamientos(metodos y atributos ) de la clase padre y a su vez estas clases hijas pueden crear comportamientos propios
=begin
class Mamifero
def respirar
puts 'inspirar, espirar'
end
end
# el símbolo < indica que
# Gato es una subclase de Mamifero
class Gato < Mamifero
def maullar
puts 'Miaaaaaaaaaaau'
end
end
cribas = Gato.new
cribas.respirar
cribas.maullar
=end
Composition
omposición quiere decir que tenemos una instancia de una clase que contiene instancias de otras clases que implementan las funciones deseadas.
Es decir, estamos delegando las tareas que nos mandan a hacer a aquella pieza de código que sabe hacerlas. El código que ejecuta esa tarea
concreta está sólo en esa pieza y todos delegan el ella para ejecutar dicha tarea.
Por lo tanto estamos reutilizando código de nuevo.
Encapsulation
Es el proceso de almacenar en una misma sección los elementos de una abstracción que constituyen su estructura y su comportamiento; sirve para
separar el interfaz contractual de una abstracción y su implantación.
Existen tres niveles de acceso para el encapsulamiento, los cuales son:
Público (Public): Todos pueden acceder a los datos o métodos de una clase que se definen con este nivel, este es el nivel más bajo, esto es lo que tu quieres que la parte externa vea.
Protegido (Protected): Podemos decir que estás no son de acceso público, solamente son accesibles dentro de su clase y por subclases.
Privado (Private): En este nivel se puede declarar miembros accesibles sólo para la propia clase.
Voy a hacer un pequeño ejemplo, no usaré ningún lenguaje de Programación Orientado a Objetos, debido a que el Curso es Programación Orientada a Objetos en “General”.
El Ejemplo del Vehículo nuevamente, Usaremos la característica COLOR.
Duck Typing
Duck Typing se refiere a la tendencia de Ruby a centrarse menos en la clase de un objeto, y dar prioridad a su comportamiento: qué métodos se pueden usar, y qué operaciones se pueden
hacer con él.
The Law of Demeter (ej.)
Cada unidad debe tener un limitado conocimiento sobre otras unidades y solo conocer aquellas unidades estrechamente relacionadas a la unidad actual.
Cada unidad debe hablar solo a sus amigos y no hablar con extraños.
Solo hablar con sus amigos inmediatos.
Overriding Methods (and using super)
Las clases en Ruby sólo pueden tener un método con un nombre dado.
Para tener métodos "distintos" con el mismo nombre, se puede jugar
con el número de argumentos:
Scope
El alcance es una propiedad de las variables: se refiere a su
visibilidad (aquella región del programaa donde la variable puede utilizarse).
Los distintos tipos de variables, tienen distintas reglas de alcance. Hablemos
de dos tipos de variables: las globales y las locales.
Alcance global y variables globales
Empezarmos con el alcance que menos se usa, pero no por ello menos importante:
un alcance global significa que alcanza a todo el programa. Desde cualquier parte del programa,
puede usarse la variable.
Las variables globales son las que tienen alcance global.
Las variables globales se distinguen porque están precedidas del signo dólar ($).
Pueden ser vistas desde cualquier parte del programa, y por tanto pueden ser usadas en cualquier parte:
nunca quedan fuera de alcance. Sin embargo, las variables globales son usadas muy poco por los programadores
experimentados.
Variables globales por defecto
El intérprete Ruby tiene por defecto un gran número de variables globales iniciadas desde el principio.
Son variables que almacenan información útil que puede ser usada en cualquier momento y parte del programa.
Por ejemplo, la variable global $0 contiene el nombre del fichero que Ruby está ejecutando. La variable global
$: contiene los directorios en los que Ruby busca cuando se carga un fichero que no existe en el directorio de trabajo.
$$ contiene el id (identidad) del proceso que Ruby está ejecutando. Y hay muchas más.
Private vs Public Methods
public - los métodos públicos (public) pueden ser usados por cualquiera; no hay un control de acceso.
protected - los métodos protegidos (protected) pueden ser usados únicamente por objetos de la misma
clase y subclases, a las que pertenece el método; pero nunca por el propio objeto. Por así decirlo,
el método sólo lo pueden usar los otros miembro de la familia.
private - los métodos privados (private) sólo pueden ser usado por el propio objeto. Técnicamente,
se dice que el receptor del método siempre es el mismo: self.
El control de acceso se determina dinámicamente, a medida que el programa transcurre. Se obtiene una
violación de acceso siempre que se intenta ejecutar un método no públi
instancia = sacar un pbjeto de la clase
metodos de clase = simples metodos que estaqn dentro de una clase y qu epueden seer accesados solo por ella
metodos de instancia = son metodos dentro de la clase y estos pueden recibir o no argumentos
variables de instancia = son aquellas que son creadas en el metodo constructor y pueden ser utilizadas por
los metodos que existan en la clase
variables de clase = a diferencia de las variables de objeto estas su valor va a ser constante en todos los
metodos a menos que se haga algun cambio dentro o fuera del metodo pero dentro de la clase
Poliformismo
se refiere a la propiedad por la que es posible enviar mensajes sintácticamente iguales a objetos de tipos
distintos. El único requisito que deben cumplir los objetos que se utilizan de manera polimórfica es saber
responder al mensaje que se les envía.
Separation of Concerns
Basicamente es separar codigo por responsabiliadades
| true
|
48205f3778c673bda577396dd982b0642d189487
|
Ruby
|
MaxMEllon/sandbox
|
/yukicoder/525.rb
|
UTF-8
| 141
| 2.890625
| 3
|
[] |
no_license
|
h, m = gets.chomp.split(':').map(&:to_i)
m += 5
if m >= 60
m %= 60
h += 1
end
if h >= 24
h %= 24
h = 0
end
printf "%02d:%02d", h, m
| true
|
1d24575e5141d609fa20deaaf03720516499cf7c
|
Ruby
|
Lasiorhine/grocery-store
|
/lib/online_order.rb
|
UTF-8
| 3,709
| 3.203125
| 3
|
[] |
no_license
|
require 'csv'
require 'awesome_print'
require_relative '../lib/order'
module Grocery
class OnlineOrder < Grocery::Order
attr_reader :id, :customer_id, :status
attr_accessor :products
def initialize(id, products, customer_id, status)
super(id, products)
@customer_id = customer_id
@status = status
end
def total
super
sum_with_tax = super
if !@products.values.empty?
sum_with_tax = sum_with_tax + 10
end
return sum_with_tax
end
def add_product (product, price)
if @status == "paid"
super(product, price)
elsif @status == "pending"
super(product, price)
end
end
def self.process_order_csv(raw_order_array)
processed_order = []
processed_order[0] = raw_order_array[0]
separated_products = raw_order_array[1].split(";")
product_price_array = []
separated_products.each do |product_with_price|
product_price_pair = product_with_price.split(":")
product_price_pair[1] = product_price_pair[1].to_f #not sure if I need this, but it was driving me nuts
product_price_array << product_price_pair
end
processed_order[1] = product_price_array.to_h
processed_order[2] = raw_order_array[2]
processed_order[3] = raw_order_array[3]
return processed_order
end
def self.all
raw_csv_file = CSV.parse(File.read('../support/online_orders.csv'))
array_of_processed_orders = []
raw_csv_file.each do |initial_order_data|
processed_entry = process_order_csv(initial_order_data)
array_of_processed_orders << processed_entry
end
all_order_instances = []
array_of_processed_orders.each do |individual_order_array|
temporary_order = OnlineOrder.new(individual_order_array[0], individual_order_array[1], individual_order_array[2], individual_order_array[3])
all_order_instances << temporary_order
end
return all_order_instances
end
def self.find(query_id)
found_order = Grocery::OnlineOrder.all.find {|order_instance| order_instance.id == query_id}
if found_order.nil?
raise ArgumentError.new("That Order ID is not recognized")
end
return found_order
end
def self.find_by_customer(query_customer_id)
target_customer_orders = []
Grocery::OnlineOrder.all.each do |order_instance|
if order_instance.customer_id == query_customer_id
order_found = order_instance
target_customer_orders << order_found
end
end
return target_customer_orders
end
end
end
#MISC TROUBLESHOOTING STUFF
# ap Grocery::OnlineOrder.all
# puts Grocery::OnlineOrder.all[0].inspect
# puts Grocery::OnlineOrder.all[99].inspect
# puts Grocery::OnlineOrder.all.length
#
#
# ap Grocery::OnlineOrder.find("1")
# puts Grocery::OnlineOrder.find("1").inspect
# Grocery::OnlineOrder.find("103")
# ap Grocery::OnlineOrder.find("103")
# puts Grocery::OnlineOrder.find("103").inspect
# ap Grocery::OnlineOrder.find("1")
# puts Grocery::OnlineOrder.find("1").inspect
# Grocery::OnlineOrder.find("1")
# puts Grocery::OnlineOrder.find("1").inspect
# online_order_1 = Grocery::OnlineOrder.new("1", {"Lobster" => 17.18,
# "Annatto seed" => 58.38, "Camomile" => 83.21}, "25", "complete")
#
# puts online_order_1.total.inspect
# online_order_2 = Grocery::OnlineOrder.new("1", {}, "25", "complete")
#
# puts online_order_2.total.inspect
# online_order_paid = Grocery::OnlineOrder.new("39",{"Beans" => 78.89, "Mangosteens" => 35.01}, "31", "paid")
# online_order_paid.add_product("lugnuts", 5.50)
# puts online_order_paid.inspect
# ap online_order_paid
| true
|
e3572cea78ac1883966c2522c7ced56876f71f28
|
Ruby
|
GuiMarcelino/onebitcode
|
/IteracaoEmCollections/select_each_hash.rb
|
UTF-8
| 167
| 3.34375
| 3
|
[] |
no_license
|
hash = {zero: 0, um: 1, dois: 2, tres: 3}
puts 'Selecione keys com valor maior que 0'
selection_key = hash.select do |key, value |
value > 2
end
puts selection_key
| true
|
9c2b7f02528033934ed2e8d16379f49d3bf0e778
|
Ruby
|
ATung01/sinatra-nested-forms-web-060517
|
/app/models/ship.rb
|
UTF-8
| 263
| 2.90625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Ship
attr_reader :name, :type, :booty
@@all = []
def initialize(stats)
@name = stats[:name]
@type = stats[:type]
@booty = stats[:booty]
@@all << self
end
def self.all
@@all
end
def self.clear
@@all.clear
end
end
| true
|
570da22460455c410fdc9274454f1a197e03f728
|
Ruby
|
davis-campbell/ruby
|
/web-projects/twitterbot.rb
|
UTF-8
| 2,285
| 3.140625
| 3
|
[] |
no_license
|
require 'jumpstart_auth'
require "bitly"
class MicroBlogger
attr_reader :client
def initialize
puts "Initializing MicroBlogger"
@client = JumpstartAuth.twitter
end
def run
puts "Welcome to the JSL Twitter Client!"
command = ''
while command[0] != 'q'
printf 'enter command: '
command = gets.chomp.split(' ')
case command[0].downcase
when 'q' then puts 'Goodbye!'
when 't' then tweet(command[1..-1].join(' '))
when 'dm' then dm(command[1], command[2..-1].join(' '))
when 'f' then followers_list
when 'sp' then spam_my_followers(command[1..-1].join(' '))
when 'elt' then everyones_last_tweet
when 's' then shorten(command[1])
when 'turl' then tweet(command[1..-2].join(' ') + ' ' + shorten(command[-1]))
else puts "Sorry, I don't know how to #{command}."
end
end
end
def tweet(message)
@client.update(message)
end
def dm(user, message)
puts "Trying to send #{user} this message:"
puts message
screen_names = @client.followers.collect { |follower| @client.user(follower).screen_name }
if screen_names.include?(user)
message = "d @#{user} #{message}"
tweet message
else
puts "Failed to send direct message. User #{user} not a follower."
end
end
def followers_list
screen_names = @client.followers.collect { |follower| @client.user(follower).screen_name }
screen_names
end
def spam_my_followers(message)
list = followers_list
list.each { |user| dm(user, message) }
end
def everyones_last_tweet
friends = @client.friends.map { |friend| @client.user(friend) }
friends = friends.sort_by { |friend| friend.screen_name.downcase }
friends.each do |friend|
timestamp = friend.status.created_at
last_tweet = friend.status.text
puts "On #{timestamp.strftime("%A, %b %d")}, #{friend.screen_name} said..."
puts last_tweet
end
end
def shorten(url)
Bitly.use_api_version_3
bitly = Bitly.new('hungryacademy', 'R_430e9f62250186d2612cca76eee2dbc6')
puts "Shortening this URL: #{url}"
url = bitly.shorten(url).short_url
puts "Shortened URL: #{url}"
return url
end
end
blogger = MicroBlogger.new
blogger.run
| true
|
8c018f9ef55557bb891478c03499837f9ed929f8
|
Ruby
|
bencappello/Exercises
|
/minesweeper/minesweeper.rb
|
UTF-8
| 6,050
| 3.8125
| 4
|
[] |
no_license
|
require 'yaml'
class Tile
attr_accessor :flagged, :bomb, :revealed
# the tile needs to know its coordinates
# and calculate its number on the fly
def flagged?
@flagged
end
def initialize(board, position)
@flagged = false
@bomb = false
@revealed = false
@board = board
@position = position
end
def toggle_flag
@flagged = !@flagged
end
def number
neighbors = get_neighbors
bomb_count = 0
neighbor_tiles(neighbors).each do |neighbor|
bomb_count += 1 if neighbor.bomb
end
bomb_count
end
def reveal_tile
return :reveal if revealed
# check if it's a bomb
return :lose if bomb
# if not, get its number
# if it's zero, go through each adjacent tile and reveal_square it recursively
neighbors = get_neighbors
@revealed = true unless flagged
if self.number == 0
neighbor_tiles(neighbors).each do |neighbor|
neighbor.reveal_tile unless neighbor.flagged? || neighbor.revealed
end
end
end
def get_neighbors
deltas = [-1, 0, 1].repeated_permutation(2).to_a
neighbors = []
deltas.each do |delta|
delta_y, delta_x = delta
new_y = @position[0] + delta_y
new_x = @position[1] + delta_x
neighbors << [new_y, new_x] if @board.valid_square?([new_y,new_x])
end
neighbors
end
def neighbor_tiles(coord_array)
coord_array.map do |coords|
@board[coords]
end
end
end
class Board
attr_reader :grid, :start_time
def initialize
@start_time = Time.new
@BOMBS = 10
@X_DIM = 9
@Y_DIM = 9
@grid = Array.new(@Y_DIM) { Array.new(@X_DIM) }
@grid.each_with_index do |row, y|
row.each_with_index do |cell, x|
self[[y, x]] = Tile.new(self, [y, x])
end
end
seed_grid
end
def flag_tile(pos)
if !(self[pos].revealed) || self[pos].bomb
self[pos].toggle_flag
else
raise "Can't flag a numbered square"
end
end
def [](pos) # [0, 0]
y, x = pos
@grid[y][x]
end
def []=(pos, to_assign)
y, x = pos
@grid[y][x] = to_assign
end
def reveal_tile(y, x)
tile = @grid[y][x]
tile.reveal_tile
tile.number
end
def won?
# if there are no not-revealed tiles that are not bombs
won = true
@grid.each do |row|
row.each do |tile|
won = false if (!tile.revealed && !tile.bomb)
end
end
return won
end
# private
# def neighbor_tiles(coord_array)
# coord_array.map do |coords|
# @grid[coords]
# end
# end
def seed_grid
@BOMBS.times do
bomb_placed = false
until bomb_placed
pos = [rand(@Y_DIM), rand(@X_DIM)]
unless self[pos].bomb
self[pos].bomb = true
bomb_placed = true
end
end
end
end
# def get_neighbors(y, x)
# deltas = [-1, 0, 1].repeated_permutation(2).to_a
#
# neighbors = []
# deltas.each do |delta|
# delta_y, delta_x = delta
# new_y = y + delta_y
# new_x = x + delta_x
# neighbors << [new_y, new_x] if valid_square?(new_y, new_x)
# end
#
# neighbors
# end
def valid_square?(pos)
y, x = pos
y.between?(0, @Y_DIM-1) && x.between?(0, @X_DIM-1)
end
end
class Minesweeper
def initialize
@board = Board.new
end
def play
game_over = false
until game_over
user_input = get_user_input
user_y, user_x = user_input[1]
p user_input
if user_input[0] == :flag
@board.flag_tile(user_input[1])
elsif user_input[0] == :reveal
did_player_lose = @board[user_input[1]].reveal_tile
game_over = :lost if did_player_lose == :lose
end
unless game_over
game_over = :won if @board.won?
end
# TODO write test on Board to see if the game is over and if it's won or lost
end
end_time = Time.new
puts "You #{game_over.to_s} in #{end_time - @board.start_time} seconds"
display_board_game_over
end
def get_user_input
puts "Board:"
display_board
puts "Pick a square. Input your choice in the format row,column."
puts "Prefix your choice with r to reveal or f to flag."
#r3,7 or f0,0 etc.
user_input = gets.chomp
if user_input[0] == 'r'
user_action = :reveal
elsif user_input[0] == 'f'
user_action = :flag
elsif user_input[0] == 's'
puts "Name your game"
self.save(gets.chomp)
elsif user_input[0] == 'l'
puts "Which game would you like to load"
self.load_game(gets.chomp)
else
raise "Invalid input"
end
# TODO add error-checking to make sure the coords are valid
user_coordinates = user_input[1..-1].split(',').map(&:to_i)
[user_action, user_coordinates]
end
def execute_user_action(user_action, user_coordinates) # auto-decompose array
user_y, user_x = user_coordinates
if user_action == :flag
@board[user_coordinates].flag
elsif user_action == :reveal
@board[user_coordinates].reveal
end
end
def display_board
board_array = @board.grid #to-do refactor this later
board_array.each do |row|
row.each do |tile|
if tile.revealed
print tile.number == 0 ? "_" : tile.number
elsif tile.flagged
print "F"
else
if tile.bomb
print "."
else
print "."
end
end
end
puts ""
end
end
def display_board_game_over
board_array = @board.grid #to-do refactor this later
board_array.each do |row|
row.each do |tile|
if tile.bomb
print "*"
else
print tile.number == 0 ? "_" : tile.number
end
end
puts ""
end
nil
end
def save(name)
yaml_game = @board.to_yaml
File.open(name, "w") do |f|
f.puts yaml_game
end
end
def load_game(name)
yaml_game = File.read(name)
@board = YAML::load(yaml_game)
end
end
| true
|
cb856128971e210745b21657b1135a77d12eb8a8
|
Ruby
|
middledeveloper/Thinknetica
|
/lesson9/wagon.rb
|
UTF-8
| 1,121
| 2.953125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require_relative 'manufacturer'
require_relative 'accessors'
require_relative 'validation'
class Wagon
include Accessors
include Manufacturer
include Validation
attr_reader :number, :type
validate :manufacturer, :presence
validate :number, :presence
validate :type, :presence
def initialize(manufacturer, capacity)
@number = rand(1000...9000).to_s
@manufacturer = manufacturer
@capacity = capacity
@taken_capacity = 0
validate!
end
def free_capacity
capacity - taken_capacity
end
def valid?
validate!
true
rescue StandardError
false
end
private
# def validate!
# types = %w[Cargo Passenger]
# raise StandardError, 'Неизвестный тип вагона!' unless types.include?(type)
# # if manufacturer.empty?
# # raise StandardError, 'Некорректное наименование производителя!'
# # end
# if capacity.negative?
# raise StandardError, 'Некорректное значение вместительности!'
# end
# end
end
| true
|
e308e2414ac00d735a65790e0865a5c894f03d3a
|
Ruby
|
RobertoCarrilloAvila/maraton
|
/Modelo.rb
|
UTF-8
| 501
| 3.453125
| 3
|
[] |
no_license
|
class Game
attr_reader :cartas
def initialize
@cartas = []
@index=0
load_cards
end
private
def load_cards
arr_of_arrs = CSV.read("respuestas.csv")
arr_of_arrs.each do |array|
pregunta = array[0]
respuestas = array[1]
@cartas << Card.new(pregunta, respuesta)
end
end
end
class Card
attr_reader :pregunta
def initialize(pregunta, respuesta)
@pregunta=pregunta
@respuestas=respuesta
end
def respuesta_correcta?(string)
string.downcase==@respuesta
end
end
| true
|
ad235f5e6439f54d071553899468dd89b3318ce8
|
Ruby
|
velaluqa/gitdeploy
|
/lib/gitdeploy/command.rb
|
UTF-8
| 502
| 2.578125
| 3
|
[] |
no_license
|
module Gitdeploy
class Command
class << self
def flags(flags = nil)
short = (flags || []).select { |a| a.to_s.length <= 1 }
long = (flags || []).select { |a| a.to_s.length > 1 }
short.map!(&:to_s)
long.map! { |flag| "--#{flag} "}
"#{'-' + short.join unless short.empty?} #{long.join}"
end
def opts(opts = nil)
(opts || {}).map do |k, v|
"--#{k}=#{Shellwords.escape(v)} "
end.join
end
end
end
end
| true
|
16f596726d2656f7de9e2c85a1762f2203991ba8
|
Ruby
|
raffo1234/Ruby
|
/method.rb
|
UTF-8
| 48
| 2.859375
| 3
|
[] |
no_license
|
def double(val)
val * 2
end
puts double(2)
| true
|
7fc943238615f5f8f5417e11ad9aefdd6b89c2da
|
Ruby
|
jbgutierrez/delicious_api
|
/lib/delicious_api/tag.rb
|
UTF-8
| 1,276
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require File.dirname(__FILE__) + '/base'
module DeliciousApi
class Tag < Base
# Tag name
attr_accessor :name
# An alias for the tag name
alias :tag :name
# Number of times used
attr_reader :count
##
# Tag initialize method
# ==== Parameters
# * <tt>name</tt> - Tag name
# * <tt>params</tt> - An optional <tt>Hash</tt> containing any combination of the instance attributes
# ==== Result
# An new instance of the current class
def initialize(name, params = {})
params.symbolize_keys!.assert_valid_keys(:name, :tag, :count)
params.merge!(:name => name, :original_name => name)
assign params
end
# Retrieves a list of tags and number of times used from Delicious
def self.all
self.wrapper.get_all_tags
end
# Deletes a tag from Delicious
def delete
validate_presence_of :name
wrapper.delete_tag(@name) || raise(OperationFailed)
end
# Updates a tag name at Delicious (if necessary)
def save
validate_presence_of :name
unless @original_name == @name
wrapper.rename_tag(@original_name, @name) || raise(OperationFailed)
@original_name = @name
end
end
protected
attr_accessor :original_name
end
end
| true
|
56688f4484334b62f8e0bda47bd39c19fea4dfdf
|
Ruby
|
eva-barczykowska/Ruby
|
/Blocks_exercises.rb
|
UTF-8
| 319
| 4.03125
| 4
|
[] |
no_license
|
[3, 5, 7, 9].each { |number| puts number**2}
puts
evens = [2, 4, 6, 8, 10]
evens.each { |number| puts number**3}
puts
colors = ["magenta", "hazel", "turquoise"]
statements = colors.map { |color| puts "#{color} is a great color!"}
puts
5.times do |index|
puts index
puts "Let's move on to the next loop."
end
| true
|
19a19f65924ca6ccd6808f0806463eea3025b538
|
Ruby
|
daltonrenaldo/Developer-Applicant-Exercise
|
/simple_refactoring_exercise/template_spec.rb
|
UTF-8
| 614
| 2.78125
| 3
|
[] |
no_license
|
require_relative 'template'
describe Template do
include Template
before(:each) do
@alt = '56789-012'
end
it "should substitute %CODE% and %ALTCODE% in the template" do
# We only want this test to fail if the problem is with it,
# and not with a method that it's calling.
# So, we stub get_altcode
stub!(:get_altcode).with('5678901234').and_return(@alt)
template('Code is %CODE%; alt code is %ALTCODE%', '5678901234').should == 'Code is 5678901234; alt code is ' + @alt
end
it "should return the ALTCODE given the CODE" do
get_altcode('5678901234').should == @alt
end
end
| true
|
419c85dd1c31177be1688a6f706ff4df80092ed7
|
Ruby
|
adharmad/ruby-examples
|
/basics/string_methods.rb
|
UTF-8
| 1,658
| 4.3125
| 4
|
[] |
no_license
|
#!/usr/local/bin/ruby -w
# some useful methods on strings
# Run as:
# ruby string_methods.rb
# All string methods are documented here:
# http://corelib.rubyonrails.org/classes/String.html
#
# As with other ruby methods, a method ending in "!" is destructive
# and will alter the actual object state
puts "hello_world".capitalize # Hello_world
puts "test".upcase # TEST
puts "ABCD".downcase # abcd
puts "camelCase".swapcase # CAMELcASE
puts "america".reverse # acirema
# convert string to int
puts "1234".to_i + "5678".to_i # 6912
# string to float
puts "11.22".to_f + "33.44".to_f # 44.66
# concatenate strings
puts "hello" + "_" + "world" # hello_world
# copy a string n times
puts "tofa " * 3 + "laya " * 3
# <=> operator
# returns -1, 0 or 1 based on whether the string on the left side is
# less than, equal or greater than the string on the right side
"abcde" <=> "abcde" # 0
"Abcde" <=> "abcde" # -1
"abcde" <=? "Abcde" # 1
# check if strings are equal
astr1 = "foo"
astr2 = "foo1"
puts astr1.eql?(astr2) # false
# index of substring
# the index starts from zero
puts "hello".index('e') # 1
puts "world".index('ld') # 3
# remove leading and trailing whitespace and \n characters
# other methods are lstrip and rstrip
puts " hello ".strip # "hello"
# split string using split
"this is a string".split.each {|s|
puts s
}
# printing a string byte by byte
"ragamuffin".each_byte {|b|
puts b
}
| true
|
5d0047d908401bbe762b599048af90fa712fd52f
|
Ruby
|
fuvzn121/aoj-ruby
|
/introduction_to_programming/print_rectangle.rb
|
UTF-8
| 268
| 3.140625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
h_arr = []
w_arr = []
loop do
h, w = gets.split.map(&:to_i)
break if h == 0 && w == 0
h_arr.push(h)
w_arr.push(w)
end
h_arr.zip(w_arr) do |h, w|
h.times do
w.times do
print '#'
end
puts ''
end
puts ''
end
| true
|
0a004370034b5f4953547b617f85eb372a91a44a
|
Ruby
|
DigitPaint/roger_eslint
|
/test/lint_test.rb
|
UTF-8
| 3,066
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
require File.dirname(__FILE__) + "/../lib/roger_eslint/lint.rb"
require "test/unit"
require "roger/testing/mock_project"
# Fake tester to pass into the linter plugin
class TesterStub
attr_reader :messages
attr_writer :files
def initialize
@messages = []
@files = []
end
def project
# Creating a mock project with path will forego the construct creation
@project ||= Roger::Testing::MockProject.new(".")
end
def destroy
@project.destroy if @project
end
def log(_, message)
@messages.push(message)
end
def warn(_, message)
@messages.push(message)
end
def get_files(_, _)
@files
end
end
# Linting plugin unit test
class LintTest < Test::Unit::TestCase
def setup
end
def test_detect_eslint
assert_nothing_raised do
lint_files "test.js"
end
assert_raise(ArgumentError) do
lint_files "test.js", eslint: "eslint-blabla"
end
end
def test_lint_nonexisting_file
success, messages = lint_files("test/data/does_not_exist.js")
assert success
assert_equal "No files linted", messages[0]
end
def test_lint_multiple_files
success, messages = lint_files(
["test/data/error.js", "test/data/fixable.js"],
eslint_options: ["--no-eslintrc", "--rule", "semi: 2"]
)
assert !success
assert_equal("test/data/error.js: OK", messages[0])
assert_equal("test/data/fixable.js: 1:15 [Error (Fixable)] Missing semicolon.", messages[1])
end
def test_lint_with_default_eslintrc
eslintrc_file = ".eslintrc.js"
assert !File.exist?(eslintrc_file), ".eslintrc.js file already exists."
FileUtils.cp("./test/data/.eslintrc-no-undef.js", eslintrc_file)
file = "test/data/error.js"
success, messages = lint_files(file)
assert !success
assert_equal("#{file}: 1:1 [Error] 'x' is not defined.", messages[0])
assert_equal("#{file}: 2:1 [Error] 'alert' is not defined.", messages[2])
assert_equal("#{file}: 2:7 [Error] 'x' is not defined.", messages[4])
ensure
File.unlink eslintrc_file
end
def test_lint_pass_eslint_options
file = "test/data/globals.js"
success, messages = lint_files(file, eslint_options: ["--no-eslintrc", "--global", "my_global"])
assert success
assert_equal "#{file}: OK", messages[0]
end
def test_lint_fixable_errors
file = "test/data/fixable.js"
success, messages = lint_files(file, eslint_options: ["--no-eslintrc", "--rule", "semi: 2"])
assert !success
assert_equal "#{file}: 1:15 [Error (Fixable)] Missing semicolon.", messages[0]
assert_equal "1 problems can be fixed automatically. Run:", messages[2]
end
protected
def lint_files(files, options = {})
faketester = TesterStub.new
faketester.files = files.is_a?(Array) ? files : [files]
linter = RogerEslint::Lint.new options
success = linter.call(faketester, {})
messages = faketester.messages
# Chop off the first message is it just says "ESLinting files"
messages.shift
[success, messages]
ensure
faketester.destroy
end
end
| true
|
51285d02bdbce7cac1b691a75da04e11cd41ded5
|
Ruby
|
pockyhao518/AA_Homeworks
|
/W4D1/In class/KnightPathFinder/PolyTree.rb
|
UTF-8
| 1,672
| 3.703125
| 4
|
[] |
no_license
|
class PolyTreeNode
attr_accessor :value, :parent, :children
def initialize(value)
@value = value
@parent = nil
@children = []
end
def parent=(node)
if !node.nil?
if !self.parent.nil?
self.parent.children.delete(self)
end
@parent = node
if !node.children.include?(self)
node.children << self
end
else
@parent = nil
end
end
def add_child(node)
if !self.children.include?(node)
node.parent = self
end
end
def remove_child(node)
if node.parent == nil
raise "node is not a child node"
end
node.parent = nil
end
def inspect
@value.inspect
end
# a
# b c
# d e
def dfs(value)
return self if self.value == value
return nil if self.children == []
check = nil
self.children.each do |child|
check = child.dfs(value)
return check if check != nil
end
return check
end
def bfs(value)
queue = []
if self == nil
return nil
end
queue << self
until queue.empty?
# while !queue.empty?
if queue.first.value == value
return queue.first
else
queue += queue.first.children
queue.shift
end
end
return nil
end
end
| true
|
6c6e6cb068f874924014dd933ef52646f24828b2
|
Ruby
|
jsdelivrbot/Semaine-0
|
/day5/exo_11.rb
|
UTF-8
| 192
| 3.734375
| 4
|
[] |
no_license
|
puts "Donne moi un nombre"
user_number = gets.chomp
u = user_number.to_i
puts "Je vais afficher 'Salut, ça farte?' #{user_number} fois"
while (u > 0)
puts "Salut, ça farte?"
u = u - 1
end
| true
|
932b924ea8efd7759b5760b6c47851f82b2e2a0b
|
Ruby
|
hooptie45/xiki
|
/menu/itunes.rb
|
UTF-8
| 2,300
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
module Xiki
class Itunes
MENU = "
- .play/
- .pause/
- .next/
- .previous/
- .artists/
- .songs/
- .current/
- .playlist/
- api/
> Play a song
@ Itunes.songs 'Thunderstorm'
|
- docs/
| Play specific song
@itunes/songs/Around the Fur
|
| Play a playlist
@itunes/playlist/class
"
@@use_pipe_delimiter = "set Applescript's text item delimiters to \"|\""
def self.songs name=nil
# If nothing passed, list all songs
if name.nil?
tracks = Applescript.run "get the name of every track of library playlist 1 as string", :app=>"iTunes", :delimiter=>"|"
tracks.sub! /^\"(.+)\"$/, "\\1"
tracks = tracks.split("|")
return tracks.sort.uniq.select{|o| o != "" && o !~ /^ /}.map{|o| "- #{o}/\n"}.join
return
end
Applescript.run "iTunes", "play track \"#{name}\""
end
def self.current
Applescript.run "iTunes", "get name of current track"
end
def self.playlist name=nil
return View.prompt("Enter a name") if name.nil?
Applescript.run "iTunes", "play playlist \"#{name}\""
end
def self.play
Applescript.run "iTunes", "play"
end
def self.pause
Applescript.run "iTunes", "pause"
end
def self.next
Applescript.run "iTunes", "next track"
"@flash/- #{self.current.gsub('\"', '')}"
end
def self.previous
Applescript.run "iTunes", "previous track"
end
def self.artists artist=nil, track=nil
# If nothing passed, list artists
if artist.nil?
artists = Applescript.run "iTunes", 'get the artist of every track of library playlist 1'
artists = JSON[artists.sub(/^\{(.+)\}$/, "[\\1]")]
return artists.sort.uniq.select{|o| o != ""}.map{|o| "- #{o}/\n"}.join
end
# If just artist passed, list artists
if track.nil?
tracks = Applescript.run "iTunes", "get the name of every track of library playlist 1 whose artist is \"#{artist}\""
tracks = JSON[tracks.sub(/^\{(.+)\}$/, "[\\1]")]
return tracks.sort.uniq.select{|o| o != ""}.map{|o| "- #{o}/\n"}.join
end
self.songs track
"@flash/- Playing!"
end
end
end
| true
|
c7b171e121447e68308032735703e44eeacad049
|
Ruby
|
kalebealvs/webmotors
|
/app/services/web_motors_request_api.rb
|
UTF-8
| 553
| 2.515625
| 3
|
[] |
no_license
|
class WebMotorsRequestAPI
URI_MANUFACTURERS = URI('https://www.webmotors.com.br/carro/marcas')
URI_MODELS = URI('https://www.webmotors.com.br/carro/modelos')
def self.get_makes
makes = JSON.parse Net::HTTP.post_form(URI_MANUFACTURERS, {}).body
makes.each { |make| makes.delete make if make['Nome'] == ''}
return makes.uniq
end
def self.get_makes_names
get_makes.map { |manufacturer| manufacturer["Nome"] }.uniq
end
def self.get_models(make)
JSON.parse Net::HTTP.post_form(URI_MODELS, { marca: make }).body
end
end
| true
|
c42915986c7df3fbc2eec6874962c61b09c5d91a
|
Ruby
|
nwsmith/pawnzilla
|
/engine/src/geometry/coord.rb
|
UTF-8
| 3,662
| 3.46875
| 3
|
[] |
no_license
|
#
# Copyright 2005-2009 Nathan Smith, Ron Thomas, Sheldon Fuchs
#
# 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.
#
class Coord
NORTH = 0x01
SOUTH = 0x02
EAST = 0x04
WEST = 0x08
NORTHWEST = 0x10
NORTHEAST = 0x20
SOUTHWEST = 0x40
SOUTHEAST = 0x80
attr_reader :x
attr_reader :y
def initialize(x, y)
@x = x
@y = y
end
# Two coordinates are equal iff both their x and y coordinates are equal
def ==(c)
(@x == c.x) && (@y == c.y)
end
def to_s
"(#{x}, #{y})"
end
def go(direction)
return north if (Coord::NORTH == direction)
return south if (Coord::SOUTH == direction)
return east if (Coord::EAST == direction)
return west if (Coord::WEST == direction)
return northeast if (Coord::NORTHEAST == direction)
return northwest if (Coord::NORTHWEST == direction)
return southeast if (Coord::SOUTHEAST == direction)
return southwest if (Coord::SOUTHWEST == direction)
end
def north
return Coord.new(@x, @y+1)
end
def north!
@y += 1
end
def north_of?(coord)
@y > coord.y
end
def due_north_of?(coord)
@x == coord.x && @y > coord.y
end
def south
return Coord.new(@x, @y-1)
end
def south!
@y -= 1
end
def south_of?(coord)
@y < coord.y
end
def due_south_of?(coord)
@x == coord.x && @y < coord.y
end
def west
return Coord.new(@x-1, @y)
end
def west!
@x -= 1
end
def west_of?(coord)
@x < coord.x
end
def due_west_of?(coord)
@y == coord.y && @x < coord.x
end
def east
return Coord.new(@x+1, @y)
end
def east!
@x += 1
end
def east_of?(coord)
@x > coord.x
end
def due_east_of?(coord)
@y == coord.y && @x > coord.x
end
def northwest
return Coord.new(@x-1, @y+1)
end
def northwest!
north!
west!
end
def northwest_of?(coord)
@x < coord.x && @y > coord.y
end
def northeast
return Coord.new(@x+1, @y+1)
end
def northeast!
north!
east!
end
def northeast_of?(coord)
@x > coord.x && @y > coord.y
end
def southwest
return Coord.new(@x-1, @y-1)
end
def southwest!
south!
west!
end
def southwest_of?(coord)
@x < coord.x && @y < coord.y
end
def southeast
return Coord.new(@x+1, @y-1)
end
def southeast!
south!
east!
end
def southeast_of?(coord)
@x > coord.x && @y < coord.y
end
def on_diag?(c)
Coord.same_diag?(self, c)
end
def on_rank?(c)
Coord.same_rank?(self, c)
end
def on_file?(c)
Coord.same_file?(self, c)
end
def Coord.same_diag?(c0, c1)
(c1.x - c0.x).abs == (c1.y - c0.y).abs
end
def Coord.same_file?(c0, c1)
c0.x == c1.x
end
def Coord.same_rank?(c0, c1)
c0.y == c1.y
end
def Coord.from_alg(alg)
return nil unless alg[0].chr.between?('a', 'h')
return nil unless alg[1].chr.to_i.between?(1, 8)
alg.length == 2 ? Coord.new(alg[0] - 97, alg[1].chr.to_i - 1) : nil
end
def to_alg
return (97 + @x).chr + (@y + 1).to_s
end
def to_s
return to_alg
end
end
| true
|
11e29687b327b06b5ed4c4c167eb81600e9fb1fc
|
Ruby
|
pmichaeljones/eloquent_ruby
|
/document.rb
|
UTF-8
| 230
| 3.671875
| 4
|
[] |
no_license
|
# turn "The" into "ehT"
# turn "Patrick" into "kcirtaP"
def reverse_string(string)
new_string = ""
until string.length == 0 do
last_letter = string[-1]
string.chop!
new_string << last_letter
end
new_string
end
| true
|
877ff7c97a35cea5abc8e938176a5565b088f0e0
|
Ruby
|
JupiterLikeThePlanet/code_challenges
|
/ruby_todo/udacitask.rb
|
UTF-8
| 870
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'task_starter.rb'
require 'pp'
require 'date'
# Creates a new todo list
todo = TodoList.new('Stuff to do')
# Add four new items
todo.add_item('Buy Apples')
todo.add_item('Brush Teeth')
todo.add_item('Do Homework')
todo.add_item('Wash Car')
# Print the list
todo.print_list
# # Delete the first item
todo.delete_item(0)
# # Print the list
todo.print_list
# # Delete the second item
#todo.delete_item(1)
# # Print the list
# todo.print_list
# # Update the completion status of the first item to complete
todo.completed?(0)
todo.completed(0)
todo.completed?(0)
todo.completed(2)
# # Print the list
# todo.print_list
# # Update the title of the list
# todo.title = "Things to do"
# # Print the list
# todo.print_list
#Show completed items
todo.completed_items
# Add a tag
todo.add_tag(1, "chore")
todo.filter_by_tag('chore')
#todo.print_list
| true
|
1331fedf3c463ef5acd429df3a20e1ed299c2b1b
|
Ruby
|
nickzaf95/ruby-oo-complex-objects-school-domain-london-web-021720
|
/lib/school.rb
|
UTF-8
| 891
| 3.40625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# code here!
class School
@@all = []
def initialize(name)
@name = name
@@all << self
end
def roster
if @roster
return @roster
else
@roster = {}
return @roster
end
end
def add_student(name, x)
if @roster
if @roster[x]
@roster[x] << name
else
@roster[x] = []
@roster[x] << name
end
else
@roster = {}
if @roster[x]
@roster[x] << name
else
@roster[x] = []
@roster[x] << name
end
end
@roster
end
def grade(x)
@roster[x]
end
def sort
@roster.each { |grade, name| name.sort! }
@roster
end
def self.all
@@all
end
end
| true
|
9868a56d3d6804da2ca3cfe52b49e611380da378
|
Ruby
|
anoam/meeting_schedule
|
/spec/lib/schedule_spec.rb
|
UTF-8
| 1,889
| 2.578125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'rspec'
require 'schedule'
require 'meeting'
describe Schedule do
describe '#to_s' do
let(:first_room_morning_meetings) do
[
Meeting.new('All Hands meeting', 60),
Meeting.new('Marketing presentation', 30),
Meeting.new('Product team sync', 30)
]
end
let(:second_room_morning_meetings) do
[
Meeting.new('Ruby vs Go presentation', 45),
Meeting.new('New app design presentation', 45),
Meeting.new('Customer support sync', 30)
]
end
let(:first_room_afternoon_meetings) do
[
Meeting.new('Front-end coding interview', 60),
Meeting.new('Skype Interview A', 30),
Meeting.new('Skype Interview B', 30)
]
end
let(:second_room_afternoon_meetings) do
[
Meeting.new('Project Bananaphone Kickoff', 45),
Meeting.new('Developer talk', 60),
Meeting.new('API Architecture planning', 45),
]
end
subject do
Schedule.new(first_room_morning_meetings, second_room_morning_meetings, first_room_afternoon_meetings, second_room_afternoon_meetings)
.to_s
end
it "returns string representation of schedule" do
is_expected.to eql(<<~TEXT.strip)
Room 1:
09:00AM All Hands meeting 60min
10:00AM Marketing presentation 30min
10:30AM Product team sync 30min
12:00PM Lunch
01:00PM Front-end coding interview 60min
02:00PM Skype Interview A 30min
02:30PM Skype Interview B 30min
Room 2:
09:00AM Ruby vs Go presentation 45min
09:45AM New app design presentation 45min
10:30AM Customer support sync 30min
12:00PM Lunch
01:00PM Project Bananaphone Kickoff 45min
01:45PM Developer talk 60min
02:45PM API Architecture planning 45min
TEXT
end
end
end
| true
|
b0e88b0d5781d083522aebee2505fd69d0d5181c
|
Ruby
|
kkcook/ls_ruby_old
|
/small_problems/easy1/easy_1_prob_4.rb
|
UTF-8
| 896
| 4.09375
| 4
|
[] |
no_license
|
# frozen_string_literal: true
# Prob: write a method that counts the number of occurrences of each element in given array
# Input: array, output: hash
# Edge cases: empty array...
# Datastructure: array to hash
# Algorithm: iterate through each and see if key exists, if so, add one to count, otherwise create key and set value to 1
vehicles = %w[
car car truck car SUV truck
motorcycle motorcycle car truck
]
# def count_occurrences(list)
# output = {}
# list.each do |element|
# if output[element]
# output[element] += 1
# else
# output[element] = 1
# end
# end
#
# output
# end
def count_occurrences(list)
output = {}
list.uniq.each do |element|
output[element] = list.count(element)
end
output.each do |key, value|
puts "#{key} => #{value}"
end
end
count_occurrences(vehicles)
| true
|
23791f5e9f6b907ae716d82decb3ef3518f1a5a8
|
Ruby
|
Rexman17/oo-kickstarter-nyc-web-100818
|
/lib/backer.rb
|
UTF-8
| 521
| 2.765625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Phong
require 'pry'
class Backer
attr_accessor :name, :backed_projects
def initialize(name)
@name = name
@backed_projects = []
end
def back_project(project)
@backed_projects << project
project.backers << self
end
# also adds the backer to the project's backers array
# adding an instance of BACKER Class into the project's backers array
# self is the instance of the Backer Class
# Bob is being shoveled into project.backers
# backers method in project.rb
end
# binding.pry
| true
|
9a01d9d3c1360bf709443e3035de78748ea24184
|
Ruby
|
jleeman/blackjack-sinatra
|
/main.rb
|
UTF-8
| 4,870
| 3.171875
| 3
|
[] |
no_license
|
require 'rubygems'
require 'sinatra'
# require 'shotgun'
require 'pry'
set :sessions, true
# constants
BLACKJACK_VALUE = 21
DEALER_HIT_VALUE = 17
# define helper methods, can also use modules for this
helpers do
def init_deck
suits = ['Spades', 'Clubs', 'Diamonds', 'Hearts']
values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
suits.product(values).shuffle!
end
def first_deal(player_cards, dealer_cards, deck)
2.times do
player_cards << deck.pop
dealer_cards << deck.pop
end
end
def total(h)
values = h.map{|card| card[1]}
h_total = 0
values.each do |value|
if value == "Ace"
h_total += 11
else
h_total += value.to_i == 0 ? 10 : value.to_i
end
end
values.select{|value| value == "Ace"}.count.times do
break if h_total <= BLACKJACK_VALUE
h_total -= 10
end
h_total
end
def display_card(card)
suit = card[0]
value = card[1]
"<img src='/images/cards/#{suit.downcase}_#{value.downcase}.jpg' style='margin-right:10px' />"
end
def win!(message)
@show_hit_stay = false
@show_dealer_option = false
@play_again = true
# update player money
session[:money] += session[:bet]
@winner = "<strong>#{session[:player_name]} wins!!!</strong> #{message}<br />#{session[:player_name]} now has $#{session[:money]}."
end
def lose!(message)
@show_hit_stay = false
@show_dealer_option = false
@play_again = true
# update player money
session[:money] -= session[:bet]
@loser = "<strong>#{session[:player_name]} loses, sorry!</strong> #{message}<br />#{session[:player_name]} now has $#{session[:money]}."
end
def tie!(message)
@show_hit_stay = false
@show_dealer_option = false
@play_again = true
@winner = "<strong>It's a push!</strong> #{message}<br />#{session[:player_name]} still has $#{session[:money]}."
end
end
before do
@show_hit_stay = true
@show_dealer_option = false
@show_dealer_card = false
end
# routing processes here, get/posts
get '/' do
if session[:user_name]
redirect '/game'
else
redirect '/player/set_name'
end
end
get '/player/set_name' do
session[:money] = 500
erb :'/player/set_name'
end
post '/player/set_name' do
session[:player_name] = params[:player_name]
redirect '/player/set_bet'
end
get '/player/set_bet' do
erb :'/player/set_bet'
end
post '/player/set_bet' do
bet = params[:bet].to_i
if bet.nil? || bet == 0
@error = "Must make a bet!"
halt erb(:'player/set_bet')
elsif bet > session[:money]
@error = "You don't have enough money! Please try again."
halt erb(:'player/set_bet')
else
session[:bet] = bet
redirect '/game'
end
end
get '/game' do
session[:deck] = init_deck
session[:player_cards] = []
session[:dealer_cards] = []
first_deal(session[:player_cards], session[:dealer_cards], session[:deck])
session[:player_total] = total(session[:player_cards])
session[:dealer_total] = total(session[:dealer_cards])
if total(session[:player_cards]) == BLACKJACK_VALUE
win!("#{session[:player_name]} hit blackjack!")
end
erb :game
end
post '/player/hit' do
session[:player_cards] << session[:deck].pop
player_total = total(session[:player_cards])
if player_total == BLACKJACK_VALUE
win!("#{session[:player_name]} hit blackjack!")
elsif player_total > BLACKJACK_VALUE
lose!("#{session[:player_name]} went bust at #{player_total}!")
end
erb :game, layout: false
end
post '/player/stay' do
@success = "#{session[:player_name]} has chosen to stay."
@show_hit_stay = false
redirect '/dealer'
end
get '/dealer' do
@show_hit_stay = false
@show_dealer_card = true
dealer_total = total(session[:dealer_cards])
if dealer_total == BLACKJACK_VALUE
lose!("Dealer hit blackjack.")
elsif dealer_total > BLACKJACK_VALUE
win!("Dealer busted at #{dealer_total}!")
elsif dealer_total >= DEALER_HIT_VALUE
redirect '/compare'
else
@show_dealer_option = true
end
erb :game, layout: false
end
post '/dealer/hit' do
session[:dealer_cards] << session[:deck].pop
redirect '/dealer'
end
get '/compare' do
@show_hit_stay = false
@show_dealer_card = true
@show_dealer_option = false
player_total = total(session[:player_cards])
dealer_total = total(session[:dealer_cards])
if player_total < dealer_total
lose!("#{session[:player_name]} stayed at #{player_total} and dealer stayed at #{dealer_total}.")
elsif player_total > dealer_total
win!("#{session[:player_name]} stayed at #{player_total} and dealer stayed at #{dealer_total}.")
else
tie!("#{session[:player_name]} stayed at #{player_total} and dealer stayed at #{dealer_total}.")
end
erb :'/game'
end
get '/game_over' do
erb :'game_over', layout: false
end
| true
|
7b913d94782178779a4673ba587f9cdf97f255f5
|
Ruby
|
marsh-sb/Ruby_practice
|
/Lesson13_03.rb
|
UTF-8
| 171
| 3.484375
| 3
|
[] |
no_license
|
class Student
def initialize(name)
@name = name
end
def avg(math, english)
p @name,(math + english) / 2
end
end
a001 = Student.new("Sato")
a001.avg(30,70)
| true
|
a211a7b45b610b46033aad985a38cf3472e8ca3f
|
Ruby
|
rubsav/learn_ruby
|
/01_temperature/temperature.rb
|
UTF-8
| 215
| 3.296875
| 3
|
[] |
no_license
|
def ftoc(fahrenheit)
(fahrenheit - 32)*(5/9.0)
# if farenheit ==212
# 100
# elsif farenheit ==98.6
# 37
# elsif farenheit==68
# 20
# else
# 0
# end
end
def ctof(celsius)
(celsius * 9/5.0)+(32)
end
| true
|
6aff534784a97a74b9ed75acf2905eae5515eece
|
Ruby
|
Ohnao/pair_pro_class
|
/prac_test/t/year_converter_basic.rb
|
UTF-8
| 13,141
| 2.5625
| 3
|
[] |
no_license
|
$LOAD_PATH.push('lib')
require 'minitest/autorun'
require 'year_converter'
class YearConverterTest < Minitest::Test
def setup
@yc = YearConverter.new
end
# 令和テスト
def test_yc_1
assert_equal @yc.guess_ad_year("令和1年"), 2019, "令和1年は2019年"
end
def test_yc_2
assert_equal @yc.guess_ad_year("令和2年"), 2020, "令和2年は2020年"
end
def test_yc_3
assert_equal @yc.guess_ad_year("令和10年"), 2028, "令和10年は2028年"
end
# 平成2桁テスト(全部)
def test_yc_4
assert_equal @yc.guess_ad_year("平成31年"), 2019, "平成31年は2019年"
end
def test_yc_5
assert_equal @yc.guess_ad_year("平成30年"), 2018, "平成30年は2018年"
end
def test_yc_6
assert_equal @yc.guess_ad_year("平成29年"), 2017, "平成29年は2017年"
end
def test_yc_7
assert_equal @yc.guess_ad_year("平成28年"), 2016, "平成28年は2016年"
end
def test_yc_8
assert_equal @yc.guess_ad_year("平成27年"), 2015, "平成27年は2015年"
end
def test_yc_9
assert_equal @yc.guess_ad_year("平成26年"), 2014, "平成26年は2014年"
end
def test_yc_10
assert_equal @yc.guess_ad_year("平成25年"), 2013, "平成25年は2013年"
end
def test_yc_11
assert_equal @yc.guess_ad_year("平成24年"), 2012, "平成24年は2012年"
end
def test_yc_12
assert_equal @yc.guess_ad_year("平成23年"), 2011, "平成23年は2011年"
end
def test_yc_13
assert_equal @yc.guess_ad_year("平成22年"), 2010, "平成22年は2010年"
end
def test_yc_14
assert_equal @yc.guess_ad_year("平成21年"), 2009, "平成21年は2009年"
end
def test_yc_15
assert_equal @yc.guess_ad_year("平成20年"), 2008, "平成20年は2008年"
end
def test_yc_16
assert_equal @yc.guess_ad_year("平成19年"), 2007, "平成19年は2007年"
end
def test_yc_17
assert_equal @yc.guess_ad_year("平成18年"), 2006, "平成18年は2006年"
end
def test_yc_18
assert_equal @yc.guess_ad_year("平成17年"), 2005, "平成17年は2005年"
end
def test_yc_19
assert_equal @yc.guess_ad_year("平成16年"), 2004, "平成16年は2004年"
end
def test_yc_20
assert_equal @yc.guess_ad_year("平成15年"), 2003, "平成15年は2003年"
end
def test_yc_21
assert_equal @yc.guess_ad_year("平成14年"), 2002, "平成14年は2002年"
end
def test_yc_22
assert_equal @yc.guess_ad_year("平成13年"), 2001, "平成13年は2001年"
end
def test_yc_23
assert_equal @yc.guess_ad_year("平成12年"), 2000, "平成12年は2000年"
end
def test_yc_24
assert_equal @yc.guess_ad_year("平成11年"), 1999, "平成11年は1999年"
end
def test_yc_25
assert_equal @yc.guess_ad_year("平成10年"), 1998, "平成10年は1998年"
end
# 平成1桁テスト(全部)
def test_yc_26
assert_equal @yc.guess_ad_year("平成9年"), 1997, "平成9年は1997年"
end
def test_yc_27
assert_equal @yc.guess_ad_year("平成8年"), 1996, "平成8年は1996年"
end
def test_yc_28
assert_equal @yc.guess_ad_year("平成7年"), 1995, "平成7年は1995年"
end
def test_yc_29
assert_equal @yc.guess_ad_year("平成6年"), 1994, "平成6年は1994年"
end
def test_yc_30
assert_equal @yc.guess_ad_year("平成5年"), 1993, "平成5年は1993年"
end
def test_yc_31
assert_equal @yc.guess_ad_year("平成4年"), 1992, "平成4年は1992年"
end
def test_yc_32
assert_equal @yc.guess_ad_year("平成3年"), 1991, "平成3年は1991年"
end
def test_yc_33
assert_equal @yc.guess_ad_year("平成2年"), 1990, "平成2年は1990年"
end
def test_yc_34
assert_equal @yc.guess_ad_year("平成1年"), 1989, "平成1年は1989年"
end
# 昭和2桁テスト(一部)
def test_yc_35
assert_equal @yc.guess_ad_year("昭和64年"), 1989, "昭和64年は1989年"
end
def test_yc_36
assert_equal @yc.guess_ad_year("昭和63年"), 1988, "昭和63年は1988年"
end
def test_yc_37
assert_equal @yc.guess_ad_year("昭和62年"), 1987, "昭和62年は1987年"
end
def test_yc_38
assert_equal @yc.guess_ad_year("昭和60年"), 1985, "昭和60年は1985年"
end
def test_yc_39
assert_equal @yc.guess_ad_year("昭和59年"), 1984, "昭和59年は1984年"
end
def test_yc_40
assert_equal @yc.guess_ad_year("昭和54年"), 1979, "昭和54年は1979年"
end
def test_yc_41
assert_equal @yc.guess_ad_year("昭和53年"), 1978, "昭和53年は1979年"
end
def test_yc_42
assert_equal @yc.guess_ad_year("昭和48年"), 1973, "昭和48年は1973年"
end
def test_yc_43
assert_equal @yc.guess_ad_year("昭和40年"), 1965, "昭和40年は1965年"
end
def test_yc_44
assert_equal @yc.guess_ad_year("昭和36年"), 1961, "昭和36年は1961年"
end
def test_yc_45
assert_equal @yc.guess_ad_year("昭和28年"), 1953, "昭和28年は1953年"
end
def test_yc_46
assert_equal @yc.guess_ad_year("昭和20年"), 1945, "昭和20年は1945年"
end
def test_yc_47
assert_equal @yc.guess_ad_year("昭和12年"), 1937, "昭和12年は1937年"
end
def test_yc_48
assert_equal @yc.guess_ad_year("昭和10年"), 1935, "昭和10年は1935年"
end
# 昭和1桁テスト(一部)
def test_yc_49
assert_equal @yc.guess_ad_year("昭和9年"), 1934, "昭和12年は1934年"
end
def test_yc_50
assert_equal @yc.guess_ad_year("昭和1年"), 1926, "昭和12年は1926年"
end
# 大正2桁テスト(一部)
def test_yc_51
assert_equal @yc.guess_ad_year("大正15年"), 1926, "大正15年は1926年"
end
def test_yc_52
assert_equal @yc.guess_ad_year("大正10年"), 1921, "大正10年は1921年"
end
# 大正1桁テスト(一部)
def test_yc_53
assert_equal @yc.guess_ad_year("大正9年"), 1920, "大正9年は1920年"
end
def test_yc_54
assert_equal @yc.guess_ad_year("大正4年"), 1915, "大正4年は1915年"
end
def test_yc_55
assert_equal @yc.guess_ad_year("大正1年"), 1912, "大正1年は1912年"
end
# 明治2桁テスト(一部)
def test_yc_56
assert_equal @yc.guess_ad_year("明治45年"), 1912, "明治45年は1912年"
end
def test_yc_57
assert_equal @yc.guess_ad_year("明治33年"), 1900, "明治33年は1900年"
end
def test_yc_58
assert_equal @yc.guess_ad_year("明治32年"), 1899, "明治32年は1899年"
end
def test_yc_59
assert_equal @yc.guess_ad_year("明治23年"), 1890, "明治23年は1890年"
end
def test_yc_60
assert_equal @yc.guess_ad_year("明治18年"), 1885, "明治18年は1885年"
end
def test_yc_61
assert_equal @yc.guess_ad_year("明治10年"), 1877, "明治10年は1877年"
end
# 明治1桁テスト(一部)
def test_yc_62
assert_equal @yc.guess_ad_year("明治9年"), 1876, "明治9年は1876年"
end
def test_yc_63
assert_equal @yc.guess_ad_year("明治6年"), 1873, "明治6年は1873年"
end
def test_yc_64
assert_equal @yc.guess_ad_year("明治2年"), 1869, "明治2年は1869年"
end
def test_yc_65
assert_equal @yc.guess_ad_year("明治1年"), 1868, "明治1年は1868年"
end
# 慶応テスト
def test_yc_66
assert_equal @yc.guess_ad_year("慶応4年"), 1868, "慶応4年は1868年"
end
def test_yc_67
assert_equal @yc.guess_ad_year("慶応1年"), 1865, "慶応1年は1865年"
end
# 元年テスト
def test_yc_68
assert_equal @yc.guess_ad_year("平成元年"), 1989, "平成元年は1989年"
end
def test_yc_69
assert_equal @yc.guess_ad_year("昭和元年"), 1926, "昭和元年は1926年"
end
def test_yc_70
assert_equal @yc.guess_ad_year("大正元年"), 1912, "大正元年は1912年"
end
def test_yc_71
assert_equal @yc.guess_ad_year("明治元年"), 1868, "明治元年は1868年"
end
def test_yc_72
assert_equal @yc.guess_ad_year("慶応元年"), 1865, "慶応元年は1865年"
end
# 漢数字テスト:平成より
## 10の位に漢数字「十」を使うもの
def test_yc_73
assert_equal @yc.guess_ad_year("平成三十一年"), 2019, "平成三十一年は2019年"
end
def test_yc_74
assert_equal @yc.guess_ad_year("平成三十年"), 2018, "平成三十年は2018年"
end
def test_yc_75
assert_equal @yc.guess_ad_year("平成二十七年"), 2015, "平成二十七年は2015年"
end
def test_yc_76
assert_equal @yc.guess_ad_year("平成二十一年"), 2009, "平成二十一年は2009年"
end
def test_yc_77
assert_equal @yc.guess_ad_year("平成二十年"), 2008, "平成二十年は2008年"
end
def test_yc_78
assert_equal @yc.guess_ad_year("平成十一年"), 1999, "平成十一年は1999年"
end
def test_yc_79
assert_equal @yc.guess_ad_year("平成十年"), 1998, "平成十年は1998年"
end
## 10の位に漢数字「十」を使わないでアラビア数字のように位を位置取りするもの
## 1の位が 0 になる場合は、漢数字の「〇」を使う
## 10の位が 1 の場合に 15 を 一五 とする書き方は一般的ではないので、テストからは除外した
def test_yc_80
assert_equal @yc.guess_ad_year("平成三一年"), 2019, "平成三十一年は2019年"
end
def test_yc_81
assert_equal @yc.guess_ad_year("平成三〇年"), 2018, "平成三〇年は2018年"
end
def test_yc_82
assert_equal @yc.guess_ad_year("平成二七年"), 2015, "平成二十七年は2015年"
end
def test_yc_83
assert_equal @yc.guess_ad_year("平成二一年"), 2009, "平成二十一年は2009年"
end
def test_yc_84
assert_equal @yc.guess_ad_year("平成二〇年"), 2008, "平成二〇年は2008年"
end
#is guess_ad_year("平成一一年"), 1999, "平成十一年は1999年"; # 除外
#is guess_ad_year("平成一〇年"), 1998, "平成十年は1998年"; # 除外
## 1の位で収まるもの
def test_yc_85
assert_equal @yc.guess_ad_year("平成九年"), 1997, "平成九年は1997年"
end
def test_yc_86
assert_equal @yc.guess_ad_year("平成三年"), 1991, "平成三年は1991年"
end
def test_yc_87
assert_equal @yc.guess_ad_year("平成一年"), 1989, "平成一年は1989年"
end
# なお、漢数字のみの対応でよく、大字は不正なフォーマットとして除外して良い
# https://ja.wikipedia.org/wiki/%E5%A4%A7%E5%AD%97_(%E6%95%B0%E5%AD%97)
# 不正なフォーマット一例
def test_yc_88
assert !@yc.guess_ad_year("平成I年"), "ローマ数字Iは受け入れない"
end
def test_yc_89
assert !@yc.guess_ad_year("平成元元年"), "平成元元年はおかしい"
end
def test_yc_90
assert !@yc.guess_ad_year("平成元〇年"), "平成元〇年はおかしい"
end
def test_yc_91
assert !@yc.guess_ad_year("昭和平成5年"), "昭和平成5年はおかしい"
end
def test_yc_92
assert !@yc.guess_ad_year("平10年"), "平10年はおかしい"
end
def test_yc_93
assert !@yc.guess_ad_year("平成 10年"), "元号の後に空白は入らない"
end
def test_yc_94
assert !@yc.guess_ad_year(" 平成10年"), "元号の前に空白は入らない"
end
def test_yc_95
assert !@yc.guess_ad_year("西暦31年"), "西暦(31年)を受け入れてはいけない"
end
def test_yc_96
assert !@yc.guess_ad_year("西暦2021年"), "西暦(2021年)を受け入れてはいけない"
end
def test_yc_97
assert !@yc.guess_ad_year("昭和53.0年"), "数値的に正しくても小数点表記は受け入れない"
end
def test_yc_98
assert !@yc.guess_ad_year("昭和53年9月"), "元号の年表記の後に月などを伴ってはいけない"
end
# 範囲外の一例
def test_yc_99
assert !@yc.guess_ad_year("平成0年"), "平成0年は無い"
end
def test_yc_100
assert !@yc.guess_ad_year("平成32年"), "平成32年は無い"
end
def test_yc_101
assert !@yc.guess_ad_year("昭和65年"), "昭和65年は無い"
end
def test_yc_102
assert !@yc.guess_ad_year("昭和99999999999999年"), "昭和99999999999999年は無い"
end
def test_yc_103
assert !@yc.guess_ad_year("大正16年"), "大正16年は無い"
end
def test_yc_104
assert !@yc.guess_ad_year("明治46年"), "明治46年年は無い"
end
#追加課題のテスト
#十十年になった時の対応
def test_yc_105
assert !@yc.guess_ad_year("平成十十年"), "平成十十年は無い"
end
#〇が最初についた時の対応
def test_yc_106
assert !@yc.guess_ad_year("平成〇二年"), "平成〇二年は無い"
end
#全角数字がきた時の対応
def test_yc_107
assert_equal @yc.guess_ad_year("昭和12年"), 1937, "昭和12年は1937年"
end
def test_yc_108
assert_equal @yc.guess_ad_year("昭和12年"), 1937, "昭和12年は1937年"
end
#漢数字と数字が混在している時の対応
def test_yc_109
assert !@yc.guess_ad_year("平成十1年"), "平成十1年は無い"
end
def test_yc_110
assert !@yc.guess_ad_year("平成2十年"), "平成2十年は無い"
end
end
| true
|
fa232670a9df60984b27f2c1246098c437c1f018
|
Ruby
|
ogz00/angularjs_with_rails
|
/app/helpers/user_scores_helper.rb
|
UTF-8
| 2,313
| 2.5625
| 3
|
[] |
no_license
|
module UserScoresHelper
def self.calculate_user_scores(*args)
year = Time.now.year
@all_answers = Answer.all
user_ids = []
this_year_answers = []
@all_puzzles = []
@all_answers.each do |answer|
if answer.puzzle.year == year
this_year_answers << answer
end
end
this_year_answers.each do |answer|
user_ids << answer.user_id
end
if args.size == 0
@all_puzzles = PuzzlesHelper.current
else
args[0].each do |id|
@all_puzzles << Puzzle.find(id)
end
end
user_ids.uniq.each do |userId|
user_answers = []
answered_puzzles = []
user_score = 0
@all_puzzles.each do |puzzle|
@answer = Answer.where(:puzzle_id => puzzle.id)
.where(:user_id => userId)
unless @answer.empty?
answered_puzzles << puzzle
user_answers << @answer[0]
end
end
user_answers.each do |answer|
answered_puzzles.each do |puzzle|
if puzzle.id == answer.puzzle_id && answer.answer.to_s == puzzle.answer.to_s
user_score += (puzzle.score + answer.bonus)
end
end
end
@user_old_score = UserScore.where(:user_id => userId)
.where(:year => year)
if args.size == 0
unless @user_old_score.empty?
@user_old_score[0].update(:score => user_score)
else
@user_score_object = UserScore.new(:user_id => userId, :score => user_score, :year => year, :tabled_score => 0)
puts "new asdasdasdasd"
@user_score_object.save
end
else
unless @user_old_score.empty?
@user_old_score[0].update(:tabled_score => user_score)
else
puts "THERE IS NO OLD SCORE"
end
@oldTabledPuzzles = Puzzle.where(:isTabled => true)
@oldTabledPuzzles.update_all(:isTabled => false)
@all_puzzles.each do |puzzle|
@puzzle = Puzzle.find(puzzle.id)
@puzzle.update(:isTabled => true)
end
end
end
if args.size == 0
return UserScore.where(:year => year)
.order('score desc')
else
return UserScore.where(:year => year)
.order('tabled_score desc')
end
end
end
| true
|
27e72a1bdf9d523acdb75ba1f9726bd5fe77ce3c
|
Ruby
|
cheeseandpepper/euler_solutions
|
/euler_14.rb
|
UTF-8
| 1,318
| 3.96875
| 4
|
[] |
no_license
|
# The following iterative sequence is defined for the set of positive integers:
# n → n/2 (n is even)
# n → 3n + 1 (n is odd)
# Using the rule above and starting with 13, we generate the following sequence:
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
# It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
# Which starting number, under one million, produces the longest chain?
# NOTE: Once the chain starts the terms are allowed to go above one million.
require 'pry'
def find_longest_chain_for(max_number)
start_time = Time.now
longest_chain = 0
current_chain_size = 1
(1..max_number).each do |num|
current_chain_size = collatz_sequence_for([num], num)
longest_chain = current_chain_size if current_chain_size > longest_chain
end
end_time = Time.now
puts longest_chain
puts "Completed in #{end_time - start_time} seconds."
end
def collatz_sequence_for(sequence=[], number)
if number.even?
number = number / 2
else
number = (number * 3) + 1
end
sequence << number
collatz_sequence_for(sequence, number) if number != 1
return sequence.count
end
find_longest_chain(1000000)
| true
|
7262fb2f42258e5baa933c76802b8e5354379d65
|
Ruby
|
Yoshyn/interviews
|
/get_around/backend/level3/models/rental.rb
|
UTF-8
| 667
| 2.546875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require "active_record"
require_relative '../lib/extensions/active_record/jsonable_scope'
require_relative "../services/discouts/per_day"
require_relative "../services/commission"
class Rental < ActiveRecord::Base
jsonable_scope(only: :id, methods: [:price, :commission])
belongs_to :car
attribute :start_date, :date
attribute :end_date, :date
attribute :distance, :integer
def price
(Discounts::PerDay.combine(day_count) * car.price_per_day + distance * car.price_per_km).to_i
end
def commission
Commission.new(price, day_count).to_json
end
def day_count
(end_date - start_date).to_i + 1
end
end
| true
|
d87244fcdcacb0c5c0b1db092ff75c09a0936ad8
|
Ruby
|
sma/rainbowsend
|
/entity.rb
|
UTF-8
| 614
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
# entity.rb - Rainbow's End is an empire building strategy PBEM game
# rules (C)2001 Russell Wallace, source code (C)2001 Stefan Matthias Aust
class Entity
attr_accessor :id, :name
attr_reader :orders, :events
def initialize
@orders = []
@events = []
end
def nameid
"#{@name} [#{@id}]"
end
def event(*args)
@events.add("#{$slot}: #{args.join(' ')}.")
end
def quote(*args)
buf = "#{$slot}: >"
args.each do |arg|
buf << " "
arg = arg.to_s
if arg =~ / /
buf << '"' << arg << '"'
else
buf << arg
end
end
@events.add(buf)
end
end
| true
|
e55d64af717dec3edba44b575ec3c7cfb622950c
|
Ruby
|
JennicaStiehl/road_race
|
/test/race_test.rb
|
UTF-8
| 5,007
| 2.8125
| 3
|
[] |
no_license
|
require './test/test_helper'
require './lib/race'
require './lib/team'
require './lib/racer'
class RaceTest < Minitest::Test
def test_it_exists
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
assert_instance_of Race, salida_crit
end
def test_it_has_attributes
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
assert_equal "Salida Criterium", salida_crit.name
assert_equal "SW 3", salida_crit.category
assert_equal 25, salida_crit.cost
assert_equal 5, salida_crit.race_points
assert_equal 1, salida_crit.miles
end
def test_it_starts_the_day_without_participants
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
assert_equal [], salida_crit.teams
end
def test_it_can_register_racers
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
gs_boulder = Team.new("GS Boulder")
jennica = Racer.new("Jennica Rodriguez", "SW 3", 200)
ek = Racer.new("Eric Kenney", "SM 1", 150)
luis = Racer.new("Luis Rodrigiuez", "SM 3", 200)
jennifer = Racer.new("Jennifer Barber", "SW 3", 150)
rmrc = Team.new("Rocky Mountain Road Club")
nicole = Racer.new("Nicole Bell", "SW 2", 100)
steve = Racer.new("Steve Stoley", "SM 4", 100)
gs_boulder.add_member(jennica)
gs_boulder.add_member(ek)
gs_boulder.add_member(luis)
gs_boulder.add_member(jennifer)
rmrc.add_member(nicole)
rmrc.add_member(steve)
salida_crit.register_team(gs_boulder)
salida_crit.register_team(rmrc)
assert_equal [gs_boulder, rmrc], salida_crit.teams
end
def test_it_can_collect_money_from_racers
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
gs_boulder = Team.new("GS Boulder")
jennica = Racer.new("Jennica Rodriguez", "SW 3", 200)
ek = Racer.new("Eric Kenney", "SM 1", 150)
luis = Racer.new("Luis Rodrigiuez", "SM 3", 200)
jennifer = Racer.new("Jennifer Barber", "SW 3", 150)
rmrc = Team.new("Rocky Mountain Road Club")
nicole = Racer.new("Nicole Bell", "SW 2", 100)
steve = Racer.new("Steve Stoley", "SM 4", 100)
gs_boulder.add_member(jennica)
gs_boulder.add_member(ek)
gs_boulder.add_member(luis)
gs_boulder.add_member(jennifer)
rmrc.add_member(nicole)
rmrc.add_member(steve)
salida_crit.register_team(gs_boulder)
salida_crit.register_team(rmrc)
assert_equal 150, salida_crit.revenue
assert_equal 175, jennica.funds
end
def test_it_does_not_award_points_when_participants_less_10
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
gs_boulder = Team.new("GS Boulder")
jennica = Racer.new("Jennica Rodriguez", "SW 3", 200)
jennifer = Racer.new("Jennifer Barber", "SW 3", 150)
gs_boulder.add_member(jennica)
gs_boulder.add_member(jennifer)
rmrc = Team.new("Rocky Mountain Road Club")
nicole = Racer.new("Nicole Bell", "SW 3", 100)
rmrc.add_member(nicole)
primal = Team.new("Team Primal Racing")
rebecca = Racer.new("Rebecca Serratoni", "SW 3", 175)
primal.add_member(rebecca)
salida_crit.register_team(gs_boulder)
salida_crit.register_team(rmrc)
salida_crit.register_team(primal)
expected = ({"Jennica Rodriguez"=>0,
"Jennifer Barber"=>0,
"Nicole Bell"=>0,
"Rebecca Serratoni"=>0
})
assert_equal expected, salida_crit.award_points
end
def test_it_can_award_points
salida_crit = Race.new("Salida Criterium", "SW 3", 25, 5, 1, "60")
gs_boulder = Team.new("GS Boulder Cycling")
jennica = Racer.new("Jennica Rodriguez", "SW 3", 200)
jennifer = Racer.new("Jennifer Barber", "SW 3", 150)
tasha = Racer.new("Natasha Danko", "SW 3", 500)
gs_boulder.add_member(jennica)
gs_boulder.add_member(jennifer)
gs_boulder.add_member(tasha)
rmrc = Team.new("Rocky Mountain Road Club")
nicole = Racer.new("Nicole Bell", "SW 3", 100)
rmrc.add_member(nicole)
primal = Team.new("Team Primal Racing")
rebecca = Racer.new("Rebecca Serratoni", "SW 3", 175)
primal.add_member(rebecca)
joy = Racer.new("Joy Erdman", "SW 3", 100)
channa = Racer.new("Channa North-Hoffstaed", "SW 3", 100)
julie = Racer.new("Julie Dow", "SW 3", 150)
ambassadors = Team.new("Bike Ambassadors")
ambassadors.add_member(joy)
ambassadors.add_member(channa)
ambassadors.add_member(julie)
bike_law = Team.new("ColoBikeLaw.com")
nancy = Racer.new("Nancy Parker", "SW 3", 600)
tammi = Racer.new("Tammi Lake", "SW 3", 500)
bike_law.add_member(nancy)
bike_law.add_member(tammi)
salida_crit.register_team(gs_boulder)
salida_crit.register_team(rmrc)
salida_crit.register_team(primal)
salida_crit.register_team(ambassadors)
salida_crit.register_team(bike_law)
expected = ({"Jennica Rodriguez"=>5,
"Jennifer Barber"=>4,
"Natasha Danko"=>2,
"Nicole Bell"=>0,
"Rebecca Serratoni"=>0,
"Joy Erdman"=>0,
"Channa North-Hoffstaed"=>0,
"Julie Dow"=>0,
"Nancy Parker"=>0,
"Tammi Lake"=>0
})
assert_equal expected, salida_crit.award_points
end
end
| true
|
e12ff81becebad3f78f301ab3dd9b09a6797c9a3
|
Ruby
|
nanma80/mode-wca
|
/lib/local/tsv_file.rb
|
UTF-8
| 2,008
| 2.6875
| 3
|
[] |
no_license
|
module ModeWca
module Local
class TsvFile < LocalFile
def columns
return @columns_cache if @columns_cache
puts "Extracting columns from #{path}"
column_names = []
column_types = []
first_row = true
File.open(path).each do |line|
row = line.chomp.split("\t", -1)
if first_row
row.each do |cell|
column_names << ModeWca::Helper.camel_to_snake(cell)
end
first_row = false
else
update_column_types(column_types, row)
end
end
@columns_cache = pivot(column_names, column_types)
end
def to_csv(csv_filename = nil)
if csv_filename.nil?
csv_filename = base + '.csv'
end
output = CsvFile.new(csv_filename)
puts "Converting TSV #{path} to CSV #{output.path}"
first_row = true
line_counter = 0
CSV.open(output.path, "wb") do |csv|
File.open(path).each do |line|
if first_row
first_row = false
else
fields = line.chomp.split("\t", -1)
csv << fields
line_counter += 1
end
end
end
puts "Number of lines in #{output.path}: #{line_counter}"
puts "Size of #{output.path}: #{output.size}"
output.columns = columns
output
end
private
def update_column_types(column_types, row)
row.each_with_index do |cell, index|
unless column_types[index] == 'string'
if cell =~ /^[-+]?[0-9]+$/
type = 'integer'
else
type = 'string'
end
column_types[index] = type
end
end
end
def pivot(names, types)
result = []
names.each_with_index do |name, index|
result << {name: name, type: types[index]}
end
result
end
end
end
end
| true
|
da9f6630021f3d1d4393c1b149d1d4ab5bc234c7
|
Ruby
|
daxadax/quotes
|
/spec/services/kindle_importer_spec.rb
|
UTF-8
| 2,210
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
class KindleImporterSpec < ServiceSpec
let(:user_uid) { 23 }
let(:autotagger) { FakeAutotagService }
let(:input) { File.read("spec/support/sample_kindle_clippings.txt") }
let(:kindle_importer) do
Services::KindleImporter.new(user_uid, input, autotagger)
end
let(:result) { kindle_importer.import }
describe 'import' do
describe 'without valid input' do
let(:input) { '' }
it 'fails' do
assert_failure {result}
end
end
describe 'with valid input' do
let(:first_result) { result[0] }
it 'parses the file into quotes and autotags them' do
assert_kind_of Entities::Quote, first_result
assert_equal 'Ernest Becker', first_result.author
assert_equal 'The Denial of Death', first_result.title
assert_includes first_result.tags, 'autotagged'
end
it 'returns an array of objects' do
assert_kind_of Array, result
end
it 'only parses notes and highlights' do
assert_equal 3, result.size
end
describe 'used publications' do
describe 'with existing publications' do
before do
create_publication :author => 'Ernest Becker',
:title => 'The Denial of Death',
:publisher => 'Previously added publisher'
end
it 'uses existing publications if author and title match' do
assert_equal 'Ernest Becker', result.first.author
assert_equal 'The Denial of Death', result.first.title
assert_equal 'Previously added publisher', result.first.publisher
end
end
describe 'with no existing publications' do
it 'creates a new publication' do
assert_equal 'Ernest Becker', result.first.author
assert_equal 'The Denial of Death', result.first.title
assert_equal 'kindle import', result.first.publisher
end
end
end
end
end
class FakeAutotagService
def initialize(quote)
@quote = quote
end
def run
@quote.tags = ['autotagged']
@quote
end
end
end
| true
|
822c56436656eced60f5886339e231de1bf582ed
|
Ruby
|
Felipeandres11/desafioruby1
|
/CLASES/company.rb
|
UTF-8
| 571
| 3.421875
| 3
|
[] |
no_license
|
require 'date'
class Company
def initialize(name, *payments)
@name = name
@payments = payments.map {|date| Date.parse(date)}
#print @payments
end
def payments_before(filter_date)
@payments.select {|date| date < filter_date}
end
def payments_after(filter_date)
@payments.select {|date| date > filter_date}
end
end
file = File.open('proveedores.data','r')
data = file.readlines
file.close
company = []
data.each do |line|
ls = line.split (' ')
company.push Company.new(*ls)
end
print company[2].payments_before(Date.today)
| true
|
0807b5be02478ae59dfa77636b977b2ea0585166
|
Ruby
|
raphsutti/ZendeskTicketViewer
|
/authenticate.rb
|
UTF-8
| 637
| 2.96875
| 3
|
[] |
no_license
|
require 'net/http'
require 'uri'
require 'json'
require 'openssl'
def authenticate(username, password)
uri = URI.parse("https://firstorder.zendesk.com/api/v2/tickets.json")
Net::HTTP.start(uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
request = Net::HTTP::Get.new uri.request_uri
request.basic_auth username, password
response = http.request request
if response.code.to_i === 200
puts "Access granted"
return true
else
puts "Failed to authenticate, error code: " + response.code
return false
end
end
end
| true
|
ac6fb20a53064897837ff2a0d51a8af146f31745
|
Ruby
|
chris-ma/WDI_SYD_7_NEW
|
/chris/w01/d05/happytails/lib/shelter.rb
|
UTF-8
| 590
| 3.1875
| 3
|
[] |
no_license
|
module Shelter
# Define Animal as a class
require_relative = "animal"
require_relative = "client"
class Shelter
def relationship
Animal.new("Fido",2,"male","dog" )
end
puts "a | list animals"
puts "c | list clients"
puts "q | quit"
response = gets.strip
while response != 'q'
case response
when 'a'
list_animals(buildings)
when 'c'
list_clients(buildings)
else
puts "Please type in 'a' for animals, 'c' for clients or 'q' for quit"
end
response = gets.strip
end
end
| true
|
81bba0e257ce7b263fc25aee75c694ac06f9d6eb
|
Ruby
|
dremerten/Ruby_Intro
|
/variable_constant_scope.rb
|
UTF-8
| 32,218
| 4.25
| 4
|
[] |
no_license
|
# to load into irb use: require './variable_constant_scope.rb'
CONSTANT_OUT = 9 # outer constant
class TestClass
attr_accessor :localVar, :iVar, :name, :email
CONSTANT_CLASS = 10
@@classVar = 11
def initialize
@iVar = 12 # initialized at creation of new class object
end
def meth1 # will setup localVar and print out other values
localVar = 13
puts @@classVar
puts localVar
puts iVar
end
# when this is called @localVar will not print because it doesn't exist outside of meth1
def meth2
puts @@classVar
puts @iVar
puts @localVar
end
# method explained on line 352
def show_methods(klass)
puts Object.const_get(klass).methods.inspect
end
end
# a = TestClass.new
# a.meth1
# a.localVar = 5000
# a.meth2
# :: CONSTANT_OUT --- this says I want access from the overall object this constant. (outer constant)
# TestClass::CONSTANT_CLASS --- Says access the CONSTANT_CLASS within the TestClass.
=begin
:: is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes.
For example, say you had this setup:
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
You could access CONSTANT from outside the module as SomeModule::InnerModule::MyClass::CONSTANT.
It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .).
Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule
=end
# inherits from TestClass
class User < TestClass
class << self # creates a CLASS METHOD, anytime 'self' wraps a method within a class it is a class method.
def favorite_thing
puts "Ruby!!!"
end
end
def username(name)
@name = name
puts "Hey there #{name} nice to me you"
end
end
#puts User.favorite_thing # returns the CLASS METHOD
#=> "Ruby!!!"
# inheirts from User
class Invoice < User
# Class Method
def self.print_out
"Printed out invoice"
end
# Instance Method
def convert_to_pdf
"Converted documents to PDF"
end
end
# return the class method
#Invoice.print_out #===> "Printed out invoice"
# return the instance method
# first create an instance of Invoice class
#customerA = Invoice.new
# call the instance method
#customerA.convert_to_pdf #===> "Converted documents to PDF"
=begin
Ruby Inheritance
Ruby is the ideal object-oriented language. In an object-oriented programming language, inheritance is one of the most important features.
Inheritance allows the programmer to inherit the characteristics of one class into another class. Ruby supports only single class inheritance,
it does not support multiple class inheritance but it supports mixins.
The mixins are designed to implement multiple inheritances in Ruby, but it only inherits the interface part.
Inheritance provides the concept of “reusability”, i.e. If a programmer wants to create a new class and there is a class that already includes
some of the code that programmer wants, then he or she can derive a new class from the existing class. By doing this,
it increases the reuse of the fields and methods of the existing class without creating extra code.
Key terms in Inheritance:
Super class:The class whose characteristics are inherited is known as a superclass or base class or parent class.
Sub class:The class which is derived from another class is known as a subclass or derived class or child class.
You can also add its own objects, methods in addition to base class methods and objects etc.
Note: By default, every class in Ruby has a parent class. Before Ruby 1.9, Object class was the parent class of all the other classes
or you can say it was the root of the class hierarchy. But from Ruby 1.9 version,
BasicObject class is the super class(Parent class) of all other classes in Ruby. Object class is a child class of BasicObject class.
Syntax:
subclass_name < superclass_name
=end
# Example:
# Ruby program to demonstrate
# the Inheritance
#!/usr/bin/ruby
# Super class or parent class
class GeeksforGeeks
# constructor of super class
def initialize
puts "This is a Superclass initializer"
end
# method of the superclass
def super_method
puts "Method of a superclass"
end
end
# subclass or derived class
class Sudo_Placement < GeeksforGeeks
# constructor of deriver class
def initialize
puts "This is Subclass initializer"
end
end
=begin
# creating object of superclass
GeeksforGeeks.new
# creating object of subclass
sub_obj = Sudo_Placement.new
# calling the method of superclass using sub class object
sub_obj.super_method
Output:
This is Superclass initializer
This is a Subclass initializer
Method of superclass
############################################################################################################################
Overrriding of Parent or Superclass method:
Method overriding is a very effective feature of Ruby.
In method overriding, subclass and superclass contain the same method’s name(super_method), but performing different tasks or
we can say that one method overrides another method. If superclass contains a method and subclass also contains the
same method name then subclass method will get executed.
Example:
=end
# Ruby program to demonstrate
# Overrriding of Parent or Superclass method
#!/usr/bin/ruby
# parent class
class Geeks
# method of the superclass
def super_method
puts "This is a Superclass Method"
end
end
# derived class 'Ruby'
class Ruby < Geeks
# overriding the method of the superclass
def super_method
puts "Overriden by Subclass method"
end
end
=begin
# creating object of sub class
sub_obj = Ruby.new
# calling the method
sub_obj.super_method
Output:
Overriden by Subclass method
################################################################################################################################
Use of super Method in Inheritance:
This method is used to call the parent class method in the child class.
If the method does not contain any argument it automatically passes all its arguments.
A super method is defined by super keyword. Whenever you want to call parent class method of the same name so you can simply
write super or super().
Example:
=end
# Ruby Program to demonstrate the
# use of super method
#!/usr/bin/ruby
# base class
class Geeks_1
# method of superclass accpeting
# two parameter
def display a = 0, b = 0
puts "Parent class, 1st Argument: #{a}, 2nd Argument: #{b}"
end
end
# derived class Geeks_2
class Geeks_2 < Geeks_1
# subclass method having the same name
# as superclass
def display a, b
# calling the superclass method
# by default it will PASS
# both the arguments
super
# passing only one argument
super a
# passing both the argument
super a, b
# calling the superclass method
# by default it WILL NOT PASS
# both the arguments
super()
puts "Hey! This is subclass method"
end
end
=begin
# creating object of derived class
sub_obj = Geeks_2.new
# calling the method of subclass
sub_obj.display "Sudo_Placement", "GFG"
Output:
Parent class, 1st Argument: Sudo_Placement, 2nd Argument: GFG ---> super
Parent class, 1st Argument: Sudo_Placement, 2nd Argument: 0 ---> super a
Parent class, 1st Argument: Sudo_Placement, 2nd Argument: GFG ---> super a, b
Parent class, 1st Argument: 0, 2nd Argument: 0 ---? super()
Hey! This is subclass method
=end
##########################################
# A Deep Dive into the Ryby Object Model |
##########################################
=begin
*******************************************
** OBJECTS DON'T HAVE METHODS...CLASSES DO!| =======> VERY IMPORTANT TO UNDERSTAND !!!!!!!!!!!!!!
*******************************************
In Ruby, if you define a class and don't specifically inheirt from another class, by default the class will inheirt from the
"Object"(RubyClass) superclass. Everything inheirts from Basic object and Module respectively.
***************************************************************************************************
# A ruby Object written in C
strut = structure(think of it as the scafolding of an object)
iv = instance variable
st = symbol table
*m = method table
Value super = Reference to superclass(a superior class that ruby can inheirt from)
*const = Constants
strut RubyClass {
struct RBasic basic;
struct st_table *m_tbl;
VALUE super;
struct st_table *iv_index_tbl;
struct st_table *iv_tbl;
struct st_table *const_tbl;
};
struct RBasic {
VALUE flags; # store info on object(is it frozen or tainted?)
VALUE klass; # Reference to whatever thec lass of the object is
};
############################################
Example of superclass |
-----------------------
# Integer is the superclass to Fixnum
# Fixnum inheirits from Interger SuperClass
Fixnum.superclass # => Integer
############################################
What is Klass?
----------------
class is a keyword used to define a new class. Since it's a reserved keyword, you're not able to use it as a variable name.
You can't use any of Ruby's keywords as variable names, so you won't be able to have variables
named def or module or if or end, etc - class is no different.
For example, consider the following:
def show_methods(class)
puts Object.const_get(class).methods.inspect
end
show_methods "Kernel"
Trying to run this results in an error, since you can't use class as a variable name.
test.rb:1: syntax error, unexpected kCLASS, expecting ')'
def show_methods(class)
^
test.rb:2: syntax error, unexpected ')'
puts Object.const_get(class).methods.inspect
To fix it, we'll use the identifier klass instead. It's not special, but it's conventionally used as a variable name
when you're dealing with a class or class name. It's phonetically the same, but since it's not a reserved keyword, Ruby has no issues with it.
def show_methods(klass)
puts Object.const_get(klass).methods.inspect
end
show_methods "Kernel"
Output, as expected, is
["method", "inspect", "name", "public_class_method", "chop!"...
You could use any (non-reserved) variable name there, but the community has taken to using klass.
It doesn't have any special magic - it just means "I wanted to use the name 'class' here, but I can't, since it's a reserved keyword".
On a side note, since you've typed it out wrong a few times, it's worth noting that in Ruby, case matters.
Tokens that start with a capital letter are constants. Via the Pickaxe:
A constant name starts with an uppercase letter followed by name characters.
Class names and module names are constants, and follow the constant naming conventions.
By convention, constant variables are normally spelled using uppercase letters and underscores throughout.
Thus, the correct spelling is class and klass, rather than Class and Klass.
The latter would be constants, and both Class and Klass are valid constant names, but I would recommend against using them for clarity purposes.
##################################################################################################################################################
=end
=begin
###################
SINGLETON METHODS |
###################
# class method or instance method on User singleton class
# creates a singleton class
class User
def self.status
:hmm
end
# instance method
# adds to current method table
def status
:admin
end
end
#####################################################################
**********
MODULES |
**********
Module:
"Collections of methods and constants"
KEY DIFFERENCE FROM CLASSES:
Similar to classes but without any instance creation capabillites.
EXAMPLE: A Class superclass == Module
# Use a method as a collection of methods and constants
# create a module
module MyModule
PI = 3.141591 # constant, which gets added to constant table
# instance method
def some_method
puts "Hello, World"
end
end
# access the module constant syntax
# gives access to module namespace
MyModule::PI ==> 3.141592 (yay!)
# trying to call a method inside a module
MyModule.some_method ==> NoMethodError (why?)
# you only access module instance methods if the module is included into a class
# to access the module instance method(from above)
# create a class that includes the module
class User
include MyModule
end
# create a class instance
me = User.new
# Now call the module instance method
me.some_method ===> Hello, World
************************************************************
**************************
Variables in a Ruby Class|
**************************
Ruby provides four types of variables −
Local Variables − Local variables are the variables that are defined in a method.
Local variables are not available outside the method.
Local variables begin with a lowercase letter or _.
Instance Variables − Instance variables are available across methods for any particular instance or object.
That means that instance variables change from object to object. Instance variables are preceded
by the at sign (@) followed by the variable name.
Class Variables − Class variables are available across different objects. A class variable belongs to
the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
Global Variables − Class variables are not available across classes.
If you want to have a single variable, which is available across classes, you need to define a global variable.
The global variables are always preceded by the dollar sign ($).
Example:
Using the class variable @@no_of_customers, you can determine the number of objects that are being created.
This enables in deriving the number of customers.
class Customer
@@no_of_customers = 0
end
***************************************************************
*************************************
Custom Method to Create Ruby Objects|
*************************************
You can pass parameters to method new and those parameters can be used to initialize class variables.
When you plan to declare the new method with parameters, you need to declare the method initialize at the
time of the class creation.The initialize method is a special type of method, which will be executed when
the new method of the class is called with parameters.
Here is the example to create initialize method −
class Customer
@@no_of_customers = 0
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
end
In this example, you declare the initialize method with id, name, and addr as local variables. Here, def
and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters.
In the initialize method, you pass on the values of these local variables to the
instance variables @cust_id, @cust_name, and @cust_addr. Here local variables hold the values that are
passed along with the new method.
Now, you can create objects as follows −
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
#######################################################################################################################
**********************
Ruby Global Variables|
**********************
Global variables begin with $. Uninitialized global variables have the value nil and produce warnings with the -w option.
Assignment to global variables alters the global status. It is not recommended to use global variables.
They make programs cryptic.
Here is an example showing the usage of global variable.
#!/usr/bin/ruby
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
Here $global_variable is a global variable. This will produce the following result −
NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character
just before that variable or constant.
Global variable in Class1 is 10
Global variable in Class2 is 10
##########################################################################
************************
Ruby Instance Variables|
************************
Instance variables begin with @. Uninitialized instance variables have the value nil and produce warnings with the -w option.
Here is an example showing the usage of Instance Variables.
#!/usr/bin/ruby
class Customer
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.display_details()
cust2.display_details()
Here, @cust_id, @cust_name and @cust_addr are instance variables. This will produce the following result −
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
######################################################################################
*********************
Ruby Class Variables|
*********************
Class variables begin with @@ and must be initialized before they can be used in method definitions.
Referencing an uninitialized class variable produces an error. Class variables are shared among descendants
of the class or module in which the class variables are defined.
Overriding class variables produce warnings with the -w option.
Here is an example showing the usage of class variable −
#!/usr/bin/ruby
class Customer
@@no_of_customers = 0
def initialize(id, name, addr)
@cust_id = id
@cust_name = name
@cust_addr = addr
end
def display_details()
puts "Customer id #@cust_id"
puts "Customer name #@cust_name"
puts "Customer address #@cust_addr"
end
def total_no_of_customers()
@@no_of_customers += 1
puts "Total number of customers: #@@no_of_customers"
end
end
# Create Objects
cust1 = Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2 = Customer.new("2", "Poul", "New Empire road, Khandala")
# Call Methods
cust1.total_no_of_customers()
cust2.total_no_of_customers()
Here @@no_of_customers is a class variable. This will produce the following result −
Total number of customers: 1
Total number of customers: 2
##########################################################################################
*********************
Ruby Local Variables|
*********************
Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def,
or do to the corresponding end or from a block's opening brace to its close brace {}.
When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.
Assignment to uninitialized local variables also serves as variable declaration.
The variables start to exist until the end of the current scope is reached.
The lifetime of local variables is determined when Ruby parses the program.
In the above example, local variables are id, name and addr.
########################################################################################
***************
Ruby Constants|
***************
Constants begin with an uppercase letter. Constants defined within a class or module can be accessed
from within that class or module, and those defined outside a class or module can be accessed globally.
Constants may not be defined within methods. Referencing an uninitialized constant produces an error.
Making an assignment to a constant that is already initialized produces a warning.
class Example
VAR1 = 100
VAR2 = 200
def show
puts "Value of first Constant is #{VAR1}"
puts "Value of second Constant is #{VAR2}"
end
end
# Create Objects
object = Example.new()
object.show
Here VAR1 and VAR2 are constants. This will produce the following result −
Value of first Constant is 100
Value of second Constant is 200
##################################################################################################
**********************
Ruby Pseudo-Variables|
**********************
They are special variables that have the appearance of local variables but behave like constants.
You cannot assign any value to these variables.
self − The receiver object of the current method.
true − Value representing true.
false − Value representing false.
nil − Value representing undefined.
__FILE__ − The name of the current source file.
__LINE__ − The current line number in the source file.
############################################################################################
********************
Ruby Basic Literals|
********************
The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.
Integer Numbers.Ruby supports integer numbers. An integer number can range
from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of
class Fixnum and integers outside this range are stored in objects of class Bignum.
You write integers using an optional leading sign,
an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base.
Underscore characters are ignored in the digit string.
You can also get the integer value, corresponding to an ASCII character or escape the sequence
by preceding it with a question mark.
Example
123 # Fixnum decimal
1_234 # Fixnum decimal with underline
-500 # Negative Fixnum
0377 # octal
0xff # hexadecimal
0b1011 # binary
?a # character code for 'a'
?\n # code for a newline (0x0a)
12345678901234567890 # Bignum
Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −
Example
123.4 # floating point value
1.0e6 # scientific notation
4E20 # dot not required
4e+20 # sign before exponential
String Literals
Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution
and backslash notation but single-quoted strings don't allow substitution and allow backslash notation only for \\ and \'
Example
#!/usr/bin/ruby -w
puts 'escape using "\\"';
puts 'That\'s right';
This will produce the following result −
escape using "\"
That's right
You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression.
#!/usr/bin/ruby -w
puts "Multiplication Value : #{24*60*60}";
This will produce the following result −
Multiplication Value : 86400
Backslash Notations
Following is the list of Backslash notations supported by Ruby −
Notation Character represented
\n Newline (0x0a)
\r Carriage return (0x0d)
\f Formfeed (0x0c)
\b Backspace (0x08)
\a Bell (0x07)
\e Escape (0x1b)
\s Space (0x20)
\nnn Octal notation (n being 0-7)
\xnn Hexadecimal notation (n being 0-9, a-f, or A-F)
\cx, \C-x Control-x
\M-x Meta-x (c | 0x80)
\M-\C-x Meta-Control-x
\x Character x
Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored.
Example
#!/usr/bin/ruby
ary = [ "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
puts i
end
This will produce the following result −
fred
10
3.14
This is a string
last element
A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value.
A trailing comma is ignored.
Example
#!/usr/bin/ruby
hsh = colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
print key, " is ", value, "\n"
end
This will produce the following result −
red is 3840
green is 240
blue is 15
A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s...e literals, or with Range.new.
Ranges constructed using .. run from the start to the end inclusively. Those created using ... exclude the end value. When used as an iterator,
ranges return each value in the sequence.
A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1...5) means it includes 1, 2, 3, 4 values.
Example
#!/usr/bin/ruby
(10..15).each do |n|
print n, ' '
end
This will produce the following result −
10 11 12 13 14 15
################################################################################
****
Nil|
****
A Formal Introduction
What happens if you try to access a key that doesn’t exist, though?
In many languages, you’ll get an error of some kind. Not so in Ruby: you’ll instead get the special value nil.
Along with false, nil is one of two non-true values in Ruby. (Every other object is regarded as “truthy,” meaning that
if you were to type if 2 or if "bacon", the code in that if statement would be run.)
It’s important to realize that false and nil are not the same thing: false means “not true,” while nil is Ruby’s way of saying “nothing at all.”
##########################################################################################
********
Symbols|
********
What's a Symbol?
You can think of a Ruby symbol as a sort of name. It’s important to remember that symbols aren’t strings:
"string" == :string # false
Above and beyond the different syntax, there’s a key behavior of symbols that makes them different from strings.
While there can be multiple different strings that all have the same value, there’s only one copy of any particular symbol at a given time.
The .object_id method gets the ID of an object—it’s how Ruby knows whether two objects are the exact same object.
see that the two "strings" are actually different objects, whereas the :symbol is the same object listed twice.
puts "string".object_id
puts "string".object_id
puts :symbol.object_id
puts :symbol.object_id
What are Symbols Used For?
Symbols pop up in a lot of places in Ruby, but they’re primarily used either as hash keys or for referencing method names.
sounds = {
:cat => "meow",
:dog => "woof",
:computer => 10010110,
}
Symbols make good hash keys for a few reasons:
They’re immutable, meaning they can’t be changed once they’re created;
Only one copy of any symbol exists at a given time, so they save memory;
Symbol-as-keys are faster than strings-as-keys because of the above two reasons.
Converting Between Symbols and Strings
Converting between strings and symbols is a snap.
:sasquatch.to_s
# ==> "sasquatch"
"sasquatch".to_sym
# ==> :sasquatch
The .to_s and .to_sym methods are what you’re looking for!
Remember, there are always many ways of accomplishing something in Ruby. Converting strings to symbols is no different!
Besides using .to_sym, you can also use .intern. This will internalize the string into a symbol and works just like .to_sym:
"hello".intern
# ==> :hello
When you’re looking at someone else’s code, you might see .to_sym or .intern (or both!) when converting strings to symbols.
However, the hash syntax changed in Ruby 1.9. Just when you were getting comfortable!
The good news is that the changed syntax is easier to type than the old hash rocket syntax, and if you’re used to JavaScript objects or Python dictionaries, it will look very familiar:
new_hash = {
one: 1,
two: 2,
three: 3
}```
The two changes are:
1. You put the colon at the end of the symbol, not at the beginning;
2. You don't need the hash rocket anymore.
It's important to note that even though these keys have colons at the end instead of the beginning, they're still symbols!
```rb
puts new_hash
# => { :one => 1, :two => 2, :three => 3 }
From now on, we’ll use the 1.9 hash syntax when giving examples or providing default code.
You’ll want to be familiar with the hash rocket style when reading other people’s code, which might be older.
Dare to Compare
We mentioned that hash lookup is faster with symbol keys than with string keys. Here, we’ll prove it!
The code in the editor uses some new syntax, so don’t worry about understanding all of it just yet.
It builds two alphabet hashes: one that pairs string letters with their place in the alphabet ( “a” with 1, “b” with 2…)
and one that uses symbols (:a with 1, :b with 2…). We’ll look up the letter “r” 100,000 times to see which process runs faster!
It’s good to keep in mind that the numbers you’ll see are only fractions of a second apart, and we did the hash lookup 100,000 times each.
It’s not much of a performance increase to use symbols in this case, but it’s definitely there!
require 'benchmark'
string_AZ = Hash[("a".."z").to_a.zip((1..26).to_a)]
symbol_AZ = Hash[(:a..:z).to_a.zip((1..26).to_a)]
string_time = Benchmark.realtime do
200_000_000.times { string_AZ["r"] }
end
symbol_time = Benchmark.realtime do
200_000_000.times { symbol_AZ[:r] }
end
puts "String time: #{string_time} seconds."
puts "Symbol time: #{symbol_time} seconds."
require 'benchmark'
count = 100000000
Benchmark.bm do |bm|
bm.report('Symbol:') do
count.times { :symbol.hash }
end
bm.report('String:') do
count.times { "string".hash }
end
end
#######################################################################################################################################
We know how to grab a specific value from a hash by specifying the associated key, but what if we want to filter a hash
for values that meet certain criteria? For that, we can use .select.
grades = { alice: 100,
bob: 92,
chris: 95,
dave: 97
}
grades.select { |name, grade| grade < 97 }
# ==> { :bob => 92, :chris => 95 }
grades.select { |k, v| k == :alice }
# ==> { :alice => 100 }
In the example above, we first create a grades hash that maps symbols to integers.
Then we call the .select method and pass in a block of code. The block contains an expression for selecting matching key/value pairs.
It returns a hash containing :bob and :chris.
Finally, we call the .select method again. Our block looks only for the key :alice.
This is an inefficient method of getting a key/value pair, but it shows that .select does not modify the hash.
(Here we’re using “name” or “k” to stand for the key and “grade” or “v” to stand for the value, but as usual with blocks, you can call your variables whatever you like.)
More Methods, More Solutions
We’ve often found we only want the key or value associated with a key/value pair, and it’s kind of a pain to put both
into our block and only work with one. Can we iterate over just keys or just values?
Ruby includes two hash methods, .each_key and .each_value, that do exactly what you’d expect:
my_hash = { one: 1, two: 2, three: 3 }
my_hash.each_key { |k| print k, " " }
# ==> one two three
my_hash.each_value { |v| print v, " " }
# ==> 1 2 3
Let’s wrap up our study of Ruby hashes and symbols by testing these methods out.
=end
| true
|
2a4d1e4ec1e654f8bcbd9f3ede708e89ad981061
|
Ruby
|
gonyolac/ls_ruby_course
|
/ruby_more_topics/weekly_challenges/binary_search_tree.rb
|
UTF-8
| 185
| 3.125
| 3
|
[] |
no_license
|
class Bst
def self.new(data)
[data]
end
def self.insert(data)
end
def self.data
end
def self.left
end
def self.right
end
end
four = Bst.new(4)
p four.data
| true
|
0390e3770999d681459838a08784c0f4a806d4f3
|
Ruby
|
vy-labs/elasticsearch-dsl-builder
|
/lib/elasticsearch_dsl_builder/dsl/search/queries/term.rb
|
UTF-8
| 899
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
module ElasticsearchDslBuilder
module DSL
module Search
module Queries
class Term < Query
def initialize(field = nil, value = nil)
@type = :term
field(field) unless field.nil?
value(value) unless value.nil?
super()
end
def field(field)
field_valid = field.instance_of?(String) || field.instance_of?(Symbol)
raise ArgumentError, 'field must be a String or Symbol' unless field_valid
@field = field.to_sym
self
end
def value(value)
@value = value
self
end
def to_hash
raise InvalidQuery, 'field and value must be provided for Term Query' unless @field && @value
@query = { @field => @value }
super
end
end
end
end
end
end
| true
|
b7faa0de1e6728ebfb5396d80b889c0ab4a14458
|
Ruby
|
thegeekbrandon/rubyScripts
|
/Ruby-Scripts/exerciseOne.rb
|
UTF-8
| 162
| 2.734375
| 3
|
[] |
no_license
|
# Lesson 18: coding exercise one
puts "##########################"
puts "# Coded by Brandon Haulk #"
puts "# Ruby programming guru #"
puts "##########################"
| true
|
90135f3a813f07106757630d06312c7b07defac9
|
Ruby
|
tebriel/aoc2020.rb
|
/test/day04/main_test.rb
|
UTF-8
| 2,077
| 2.6875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'minitest/autorun'
require_relative '../../lib/day04/main'
describe 'PassportPart1' do
def setup
@passport = PassportPart1.new
end
describe '#add_line' do
it 'adds a line to make a valid passport' do
@passport.add_line 'ecl:gry pid:860033327 eyr:2020 hcl:#fffffd'
@passport.add_line 'byr:1937 iyr:2017 cid:147 hgt:183cm'
assert @passport.valid?
end
it 'adds a line to make an invalid passport' do
@passport.add_line 'iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884'
@passport.add_line 'hcl:#cfa07d byr:1929'
refute @passport.valid?
end
end
end
describe 'PassportPart2' do
def setup
@passport = PassportPart2.new
end
describe '#add_line' do
it 'adds a line to make a valid passport' do
@passport.add_line 'pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980'
@passport.add_line 'hcl:#623a2f'
assert @passport.valid?
end
it 'adds a line to make an invalid ecl passport' do
@passport.add_line 'pid:087499704 hgt:74in ecl:xxx iyr:2012 eyr:2030 byr:1980'
@passport.add_line 'hcl:#623a2f'
refute @passport.valid?
end
it 'adds a line to make an invalid passport' do
@passport.add_line 'eyr:1972 cid:100'
@passport.add_line 'hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926'
refute @passport.valid?
end
it 'does another invalid' do
@passport.add_line 'iyr:2019'
@passport.add_line 'hcl:#602927 eyr:1967 hgt:170cm'
@passport.add_line 'ecl:grn pid:012533040 byr:1946'
refute @passport.valid?
end
it 'does yet another' do
@passport.add_line 'cl:dab227 iyr:2012'
@passport.add_line 'ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277'
refute @passport.valid?
end
it 'does the last invalid example' do
@passport.add_line 'hgt:59cm ecl:zzz'
@passport.add_line 'eyr:2038 hcl:74454a iyr:2023'
@passport.add_line 'pid:3556412378 byr:2007'
refute @passport.valid?
end
end
end
| true
|
7768f4e129a2e28c0b78641dca5c3bdf41567af7
|
Ruby
|
michalberg/slibujeme
|
/spec/models/municipality_spec.rb
|
UTF-8
| 1,626
| 2.625
| 3
|
[] |
no_license
|
# encoding: utf-8
require 'spec_helper'
describe Municipality do
it "should form a tree" do
parent = create(:municipality)
children = []
3.times do
children << create(:municipality, :parent_id => parent.id)
end
parent.has_children?.should be_true
parent.children.should =~ children
children.each { |child| child.parent.should eql(parent) }
end
it "should form a multilevel tree" do
level1 = create(:municipality)
level2 = create(:municipality, :parent_id => level1.id)
level3 = create(:municipality, :parent_id => level2.id)
level1.is_root?.should be_true
level1.descendants.should =~ [level2, level3]
level2.descendants.should =~ [level3]
level2.descendants.should =~ level2.children
level2.parent.should eql(level1)
level3.parent.should eql(level2)
end
context "#full_title" do
let!(:shire) { create(:municipality, :title => "Jihomoravský kraj") }
let!(:district) do |district|
district = build(:municipality, :title => "Brno-Město")
district.parent = shire
district.save
district
end
let! :city do |city|
city = create(:municipality, :title => "Brno")
city.parent = district
city.save
city
end
it "is title with parent district in bracket if city" do
city.full_title.should eql("Brno (okr. Brno-Město)")
end
it "is only title if district" do
district.full_title.should eql("Brno-Město")
end
it "is only title if shire" do
shire.full_title.should eql("Jihomoravský kraj")
end
end
end
| true
|
e1952ffce72ca771eb79f43de466884467799729
|
Ruby
|
torresga/launch-school-code
|
/exercises/101-109_small_problems/easy_4/number_to_string.rb
|
UTF-8
| 2,871
| 4.75
| 5
|
[] |
no_license
|
# Convert a Number to a String!
# In the previous two exercises, you developed methods that convert simple numeric strings to signed Integers. In this exercise and the next, you're going to reverse those methods.
# Write a method that takes a positive integer or zero, and converts it to a string representation.
# You may not use any of the standard conversion methods available in Ruby, such as Integer#to_s, String(), Kernel#format, etc. Your method should do this the old-fashioned way and construct the string by analyzing and manipulating the number.
# Input: 0 or a positive integer
# Output: A string containing zero or positive integer
# Mental model: Turning an integer into a string without using to_s, String(), Kernel#format, etc.
# Examples
# integer_to_string(4321) == '4321'
# integer_to_string(0) == '0'
# integer_to_string(5000) == '5000'
# Data structure
# Hash to contain Integers as keys and Strings as values
# Somehow turn the number into an array - thats how we can work with number inside of the method
# Create string as output, mutate output string that we return to user
# Algorithm
# Break Integers into an array
# Create new string
# Loop through integer array
# Append value of hash to string
# Return string
# Code
NUM_VALUES = {
1 => "1",
2 => "2",
3 => "3",
4 => "4",
5 => "5",
6 => "6",
7 => "7",
8 => "8",
9 => "9",
0 => "0"
}
def integer_to_string(number)
int_string = ""
integers = number.digits.reverse
integers.each do |int|
int_string << NUM_VALUES[int]
end
int_string
end
puts integer_to_string(4321) == '4321'
puts integer_to_string(0) == '0'
puts integer_to_string(5000) == '5000'
# Further Exploration
# One thing to note here is the String#prepend method; unlike most string mutating methods, the name of this method does not end with a !. However, it is still a mutating method - it changes the string in place.
# This is actually pretty common with mutating methods that do not have a corresponding non-mutating form. chomp! ends with a ! because the non-mutating chomp is also defined. prepend does not end with a ! because there is no non-mutating form of prepend.
# How many mutating String methods can you find that do not end with a !. Can you find any that end with a !, but don't have a non-mutating form? Does the Array class have any methods that fit this pattern? How about the Hash class?
Mutating strings that do not end with a !
String#clear
String#concat
String#replace
String#insert
String#prepend
<<
Mutating arrays that do not end with a !
Array#<<
Array#append
Array#clear
Array#concat
Array#delete_if
Array#insert
Array#keep_if
Array#replace
Array#unshift
Array#prepend
Array#shift
Mutating hashes that do not end with a !
Hash#clear
Hash#delete_if
Hash#rehash
Hash#replace
Hash#shift
Hash#update
| true
|
eaf756c092869cac268cb7145a5fa97e17b39061
|
Ruby
|
connectfoursome/connect_four
|
/lib/bot_interface.rb
|
UTF-8
| 1,419
| 3.46875
| 3
|
[] |
no_license
|
require_relative 'board.rb'
require_relative 'twitter_bot.rb'
class BotInterface
attr_reader :board
def initialize(board_string, opponent)
@board = Board.from_twitter(board_string)
p @board
@opponent = opponent
p @opponent
end
def tweet_message
bot_board
if game_over?
"#{reply} #{@board} #{outcome_message} #dbc_c4 ##{random_hash}"
elsif @board.piece_count == 0
"#{reply} #{initial_message} #dbc_c4 ##{random_hash}"
elsif @board.piece_count == 1
"#{reply} #{@bot.board} #dbc_c4 ##{random_hash}"
else
move_bot
if game_over?
"#{reply} #{@bot.board} #{outcome_message} #dbc_c4 ##{random_hash}"
else
"#{reply} #{@bot.board} #dbc_c4 ##{random_hash}"
end
end
end
def game_over?
@bot.board.four_in_a_row?("X") || @bot.board.four_in_a_row?("O") || @bot.board.full?
end
def move_bot
@bot.move
end
def bot_board
@bot = TwitterBot.new(@board)
end
private
def initial_message
"Game on!"
end
def outcome_message
if @bot.board.four_in_a_row?("X")
"I win! Good game."
elsif @bot.board.four_in_a_row?("O")
"You win, cheater!"
elsif @bot.board.full?
"Draw game. Play again?"
else
""
end
end
def reply
"@#{@opponent}"
end
def random_hash
(('a'..'z').to_a + ('A'..'Z').to_a + (1..9).to_a).shuffle[0..2].join
end
end
| true
|
3c61e422ad2eda25b2d18265b7711bb0662e038b
|
Ruby
|
isabella232/viget-deployment
|
/lib/database/dump_file.rb
|
UTF-8
| 637
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
class Database
class DumpFile
def initialize(filename)
@filename = filename
end
def replace_extension(filename, extension)
filename.sub(/\.\w+/, ".#{extension}")
end
def archive_filename
replace_extension(@filename, 'zip')
end
def export_filename
replace_extension(@filename, 'sql')
end
def files
[export_filename]
end
def dump(&block)
yield export_filename
archive if archive?
end
def archive?
@filename.end_with?('.zip')
end
def archive
ZipFile.new(archive_filename).archive(export_filename)
end
end
end
| true
|
8e1c60b7d5372522cd485f111e32027ba149eb38
|
Ruby
|
Tuxt/Ruby-Cipher-4
|
/RC4.rb
|
UTF-8
| 685
| 3.34375
| 3
|
[] |
no_license
|
# Clase de RC4
class RC4
def initialize(key)
# Variables 'i' y 'j' para la salida (PRGA). Las de KSA son locales
@i = 0
@j = 0
# KSA ---------------------------------------: START
@key = key.bytes
@S = Array.new(256)
@S.each_index do |index|
@S[index] = index
end
key_len = @key.count
j = 0
256.times do |i|
j = (j + @S[i] + @key[i % key_len]) % 256
swap(i,j)
end
# KSA ---------------------------------------: END
end
# SWAP
def swap(i,j)
tmp = @S[i]
@S[i] = @S[j]
@S[j] = tmp
end
# PRGA
def more
@i = (@i + 1) % 256
@j = (@j + @S[@i]) % 256
swap(@i, @j)
k = @S[ ( @S[@i] + @S[@j] ) % 256 ]
return k
end
end
| true
|
46ab006b2593cd448a252b4cdaa474eb8853ee6d
|
Ruby
|
eva-barczykowska/Ruby
|
/arrays/slicing.rb
|
UTF-8
| 373
| 4.3125
| 4
|
[] |
no_license
|
#array/string slicing
#arr[startIndex..EndIndex] - includes the last element
#arr[startIndex...EndIndex] - ... excludes the last element
arr = ["ferrari", "fiat", "82-500", "opel", "toyota"]
print arr
puts
print arr[4] #it is not an array, just a string
puts
print arr[0..1]
puts
print arr[0...1]
puts
print arr[4]
puts
puts
str = "bootcamp"
p str[-2]
puts
p str[4..-2]
| true
|
1fe1ec109d9cec87d899c3abce2348be0e1b3d20
|
Ruby
|
moneyadviceservice/cms
|
/spec/models/table_captioner_spec.rb
|
UTF-8
| 1,225
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
describe TableCaptioner do
context 'when there is no table' do
let(:source) { '<p>hello</p>' }
subject do
described_class.new(double, source)
end
it 'does nothing' do
expect(subject.call).to eql(source)
end
end
context 'when there is a table' do
context 'and there is a paragraph with class "caption" immediately after it' do
let(:caption) { 'This is the caption' }
let(:source) { "<table><tr><td></td></tr></table><p class='caption'>#{caption}</p>" }
subject do
described_class.new(double, source)
end
it 'removes the paragraph and inserts the contents of it as a caption tag' do
# Include newlines due to Nokogiri's formatted output
expected_response = "<table>\n<caption>#{caption}</caption>\n<tr><td></td></tr>\n</table>"
expect(subject.call).to eql(expected_response)
end
end
context 'and it is followed by paragraph without any particular class' do
let(:source) { '<table><tr><td></td></tr></table>' }
subject do
described_class.new(double, source)
end
it 'does not make any changes' do
expect(subject.call).to eql(source)
end
end
end
end
| true
|
ac8c12f2178ed00d9057bd1a2d597e798cd4f3b0
|
Ruby
|
kallus/TrafficSim
|
/view/vector.rb
|
UTF-8
| 11,299
| 2.734375
| 3
|
[] |
no_license
|
require 'rvg/rvg'
include Magick
RVG::dpi = 144/8
class Vector
class << self
def draw!(cars, tile_grid, time)
return if File.exists?("output/#{("%06.2f" % [time]).sub(".", "")}.gif")
grid_size = [tile_grid[0].length,tile_grid.length]
size = [grid_size[0]*Tile.width,grid_size[1]*Tile.height]
if @rvg == nil
puts "drawing map"
@rvg = RVG.new((grid_size[0]*2.5).in,
(grid_size[1]*2.5).in
).viewbox(0,0,size[0],size[1]) do |canvas|
canvas.background_fill = 'white'
canvas.matrix(1, 0, 0, -1, 0, (grid_size[1]*2.5).in) #changing to cartesian coordinates
tile_grid.each_with_index do |tiles, y|
tiles.each_with_index do |tile, x|
tile!(canvas, tile, x*Tile.width, y*Tile.height)
end
end
end
@rvg.draw.write("output/map.gif")
end
frame_rvg = RVG.new((grid_size[0]*2.5).in,
(grid_size[1]*2.5).in).viewbox(0,0,size[0],size[1]) do |c|
# c.background_fill = 'white'
c.background_image = Magick::Image.read('output/map.gif').first
c.matrix(1, 0, 0, -1, 0, (grid_size[1]*2.5).in) #changing to cartesian coordinates
c.g.translate(0,2).matrix(1,0,0,-1,0,0).scale(0.5).text(0, 0, "Time: %.2f sec" % [time])
width = 2.5
wheels = RVG::Group.new do |_wheels|
_wheels.styles(:fill => 'black', :stroke => "black", :stroke_width => 0.1)
_wheels.rect(1, width/4.0, -(Car.length), width/2.0) # back, left
_wheels.rect(1, width/4.0, -(Car.length), -width/2.0 - width/4.0) # back, right
_wheels.rect(1, width/4.0, -2.0, width/2.0) # front, left
_wheels.rect(1, width/4.0, -2.0, -width/2.0 - width/4.0) #front, right
end
car_body = RVG::Group.new do |_car_body|
_car_body.styles(:fill => 'blue', :stroke => 'blue', :stroke_width => 0.1)
_car_body.rect(Car.length, width, -Car.length, -width/2)
end
car_graphics = RVG::Group.new do |_cg|
_cg.use(wheels)
_cg.use(car_body)
end
random_car_body = RVG::Group.new do |_car_body|
_car_body.styles(:fill => 'red', :stroke => 'red', :stroke_width => 0.1)
_car_body.rect(Car.length, width, -Car.length, -width/2)
end
random_car_graphics = RVG::Group.new do |_cg|
_cg.use(wheels)
_cg.use(random_car_body)
end
cars.each do |car|
unless car.dead
if car.rand_car?
car!(c, car, random_car_graphics)
else
car!(c, car, car_graphics)
end
end
end
end
frame_rvg.draw.write("output/#{("%06.2f" % [time]).sub(".", "")}.gif")
end
@@hlines = RVG::Group.new do |s|
s.styles(:stroke => 'black', :stroke_width => 0.2)
s.line(0, 35+Car.width, Tile.width, 35+Car.width)
s.line(0, 25-Car.width, Tile.width, 25-Car.width)
end
@@separating_line = RVG::Group.new do |s|
s.styles(:stroke => 'black', :fill => 'none', :stroke_dasharray => [2, 4], :stroke_width => 0.2)
s.line(0, 30, Tile.width, 30)
end
@@straight_tile = RVG::Group.new do |s|
s.use(@@hlines)
s.use(@@separating_line)
end
@@tcross_lines = RVG::Group.new do |s|
s.styles(:stroke => 'black', :stroke_width => 0.2)
s.line(0, 25-Car.width, Tile.width, 25-Car.width)
s.line(0, 35+Car.width, Tile.width/2 - 10, 35+Car.width)
s.line(Tile.width/2 - 10, 35+Car.width, Tile.width/2 - 10, Tile.height)
s.line(Tile.width/2 + 10, 35+Car.width, Tile.width, 35+Car.width)
s.line(Tile.width/2 + 10, 35+Car.width, Tile.width/2 + 10, Tile.height)
end
@@tcross_tile = RVG::Group.new do |s|
s.use(@@tcross_lines)
end
@@turn_lines = RVG::Group.new do |s|
s.styles(:stroke => 'black', :stroke_width => 0.2)
s.line(0, Tile.width/2 + 10, Tile.width/2 + 10, Tile.width/2 + 10)
s.line(Tile.width/2 + 10, Tile.width/2 + 10, Tile.width/2 + 10, 0)
s.line(0, Tile.width/2 - 10, Tile.width/2 - 10, Tile.width/2 - 10)
s.line(Tile.width/2 - 10, Tile.width/2 - 10, Tile.width/2 - 10, 0)
end
@@turn_separating_line = RVG::Group.new do |s|
s.styles(:stroke => 'black', :fill => 'none', :stroke_dasharray => [2, 4], :stroke_width => 0.2)
s.line(0, 30, Tile.width/2, 30)
s.line(Tile.width/2, 0, Tile.width/2, 30)
end
@@turn_tile = RVG::Group.new do |s|
s.use(@@turn_lines)
s.use(@@turn_separating_line)
end
@@cross_lines = RVG::Group.new do |s|
s.styles(:stroke => 'black', :stroke_width => 0.2)
s.line(0, Tile.width/2 + 10, Tile.width/2 - 10, Tile.width/2 + 10)
s.line(0, Tile.width/2 - 10, Tile.width/2 - 10, Tile.width/2 - 10)
s.line(Tile.width/2 + 10, Tile.width/2 + 10, Tile.width, Tile.width/2 + 10)
s.line(Tile.width/2 + 10, Tile.width/2 - 10, Tile.width, Tile.width/2 - 10)
s.line(Tile.width/2 - 10, 0, Tile.width/2 - 10, Tile.width/2 - 10)
s.line(Tile.width/2 - 10, Tile.width, Tile.width/2 - 10, Tile.width/2 + 10)
s.line(Tile.width/2 + 10, 0, Tile.width/2 + 10, Tile.width/2 - 10)
s.line(Tile.width/2 + 10, Tile.width, Tile.width/2 + 10, Tile.width/2 + 10)
end
@@cross_tile = RVG::Group.new do |s|
s.use(@@cross_lines)
end
def tile!(canvas, tile, x, y)
canvas.g.translate(x, y) do |solid|
# if $debug == true and tile.all_paths != nil
# path_nums = tile.all_paths.collect { |p| p.number.to_s }
# path_groups = []
# path_nums.each_slice(3) { |g3| path_groups << g3.join(", ") }
# path_string = path_groups.join(",\n")
# if path_string.length > 0
# solid.g.matrix(1,0,0,-1,0,0).translate(0, -20).scale(0.3).text(0, 0, path_string)
# end
# end
solid.styles(:stroke=>'black', :stroke_width=>0.2)
case tile
when HorizontalTile
solid.use(@@straight_tile)
when VerticalTile
solid.use(@@straight_tile).rotate(90).translate(*[0, -Tile.width])
# solid.line(25, 0, 25, Tile.height)
# solid.line(35, 0, 35, Tile.height)
when TurnSwTile
solid.use(@@turn_tile)
# path!(solid, tile.paths([0,25]).first)
# path!(solid, tile.paths([35,0]).first)
when TurnNeTile
solid.use(@@turn_tile).rotate(180).translate(*[-Tile.width, -Tile.height])
# path!(solid, tile.paths([Tile.width,35]).first)
# path!(solid, tile.paths([25,Tile.height]).first)
when TurnNwTile
solid.use(@@turn_tile).rotate(-90).translate(*[-Tile.width, 0])
# path!(solid, tile.paths([0,25]).first)
# path!(solid, tile.paths([25,Tile.height]).first)
when TurnSeTile
solid.use(@@turn_tile).rotate(90).translate(*[0, -Tile.width])
# path!(solid, tile.paths([Tile.width,35]).first)
# path!(solid, tile.paths([35,0]).first)
when TcrossNTile
solid.use(@@tcross_tile).rotate(180).translate(*[-Tile.width, -Tile.height])
# paths = tile.paths([0,25]) + tile.paths([35,0]) + tile.paths([Tile.width,35])
# paths.each { |p| path!(solid,p)}
when TcrossSTile
solid.use(@@tcross_tile)
# paths = tile.paths([0,25]) + tile.paths([25,Tile.height]) + tile.paths([Tile.width,35])
# paths.each { |p| path!(solid,p)}
when TcrossETile
solid.use(@@tcross_tile).rotate(90).translate(*[0, -Tile.width])
# paths = tile.paths([0,25]) + tile.paths([25,Tile.height]) + tile.paths([35,0])
# paths.each { |p| path!(solid,p)}
when TcrossWTile
solid.use(@@tcross_tile).rotate(-90).translate(*[-Tile.width, 0])
# paths = tile.paths([Tile.width,35]) + tile.paths([25,Tile.height]) + tile.paths([35,0])
# paths.each { |p| path!(solid,p)}
when CrossTile
solid.use(@@cross_tile)
# paths = []
# paths += tile.paths([Tile.width,35]) # from east
# paths += tile.paths([25,Tile.height]) # from north
# paths += tile.paths([35,0]) # from south
# paths += tile.paths([0, 25]) # from west
# paths.each { |p| path!(solid,p)}
when EmptyTile
else
raise "Unknown tile"
end
end
end
def car!(canvas, car, car_graphics)
# text_group = RVG::Group.new do |s|
# s.translate(*[car.pos[0], car.pos[1]+3]).matrix(1,0,0,-1,0,0).scale(0.3).text(0,0, "%d (%.1f m/s, %.1f m/s^2, %d %.1f m)" % [car.number, car.speed, car.acceleration, car.next_car_number, car.distance_to_next_obstruction])
# end
canvas.g do |s|
# s.use(text_group)
s.use(car_graphics).translate(*car.pos).rotate(car.angle)
end
end
def path!(solid, path)
if path.kind_of?(LockablePath) and path.is_locked?
solid.g.translate(0, 0) do |s|
s.styles(:stroke=>'red', :stroke_width=>0.8)
(1..path.length).to_a.each do |i|
s.line(*(path.point(i-1) + path.point(i)))
end
s.line(*(path.point(path.length-1) + path.end_point))
end
else
solid.g.translate(0, 0) do |s|
s.styles(:stroke=>'black', :stroke_width=>0.2)
(1..path.length).to_a.each do |i|
s.line(*(path.point(i-1) + path.point(i)))
end
s.line(*(path.point(path.length-1) + path.end_point))
end
end
end
end
end
# c.rect(Car.length, Car.width, car.x-Car.length, car.y)
#arrow
# x = car.x-0.15*Car.length
# y = car.y+Car.width*0.5
# c.line(car.x-Car.length+0.15*Car.length,
# car.y+Car.width*0.5,
# x,
# y)
# c.line(x, y, x-Car.length*0.15, y-Car.width*0.25)
# c.line(x, y, x-Car.length*0.15, y+Car.width*0.25)
# end
# canvas.g.translate(100, 150).rotate(-30) do |body|
# body.styles(:fill=>'yellow', :stroke=>'black', :stroke_width=>2)
# body.ellipse(50, 30)
# body.rect(45, 20, -20, -10).skewX(-35)
# end
# canvas.g.translate(130, 83) do |head|
# head.styles(:stroke=>'black', :stroke_width=>2)
# head.circle(30).styles(:fill=>'yellow')
# head.circle(5, 10, -5).styles(:fill=>'black')
# head.polygon(30,0, 70,5, 30,10, 62,25, 23,20).styles(:fill=>'orange')
# end
#
# foot = RVG::Group.new do |_foot|
# _foot.path('m0,0 v30 l30,10 l5,-10, l-5,-10 l-30,10z').
# styles(:stroke_width=>2, :fill=>'orange', :stroke=>'black')
# end
# canvas.use(foot).translate(75, 188).rotate(15)
# canvas.use(foot).translate(100, 185).rotate(-15)
# canvas.text(125, 30) do |title|
# title.tspan("duck|").styles(:text_anchor=>'end', :font_size=>20,
# :font_family=>'helvetica', :fill=>'black')
# title.tspan("type").styles(:font_size=>22,
# :font_family=>'times', :font_style=>'italic', :fill=>'red')
# end
# canvas.rect(249,249).styles(:stroke=>'blue', :fill=>'none')
| true
|
f4c08290cc9d4e93b549f0e0befb95fd827a5e6a
|
Ruby
|
robertleelittleiii/silverweb_cms
|
/app/uploaders/image_uploader.rb
|
UTF-8
| 6,562
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# encoding: utf-8
require "image_tools"
class ImageUploader < CarrierWave::Uploader::Base
# Include RMagick or ImageScience support:
include CarrierWave::RMagick
# include CarrierWave::ImageScience
include ImageTools
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# process :resize_to_fit => [1000, 1000]
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
def cropper(crop_width, crop_height)
manipulate! do |img|
width = img.columns
height= img.rows
if width == crop_width and height==crop_height then
img
else
img.crop(width / 2,height / 2,crop_width,crop_height)
end
end
end
def set_dpi
manipulate! do |img|
img.resample(72.0, 72.0)
end
end
def outliner
manipulate! do |img|
ImageTools::border_on_image(img,1,10,"white",1)
end
end
def old_resize_to_fill(width, height, gravity = 'Center', color = "white")
manipulate! do |img|
cols, rows = img[:dimensions]
img.combine_options do |cmd|
if width != cols || height != rows
scale = [width/cols.to_f, height/rows.to_f].max
cols = (scale * (cols + 0.5)).round
rows = (scale * (rows + 0.5)).round
cmd.resize "#{cols}x#{rows}"
end
cmd.gravity gravity
cmd.background "rgba(255,255,255,0.0)"
cmd.extent "#{width}x#{height}" if cols != width || rows != height
end
ilist = Magick::ImageList.new
rows < cols ? dim = rows : dim = cols
ilist.new_image(dim, dim) { self.background_color = "#{color}" }
ilist.from_blob(img.to_blob)
img = ilist.flatten_images
img = yield(img) if block_given?
img
end
end
def my_resize_to_fill(width, height, background="white", gravity=::Magick::CenterGravity)
manipulate! do |img|
# img.resize_to_fit!(width, he ight)
cols=img.columns
rows=img.rows
puts("cols: #{cols}, rows: #{rows} ")
if width != cols || height != rows
scale = [width/cols.to_f, height/rows.to_f].max
cols = (scale * (cols + 0.5)).round
rows = (scale * (rows + 0.5)).round
img.resize!(cols, rows)
end
new_img = ::Magick::Image.new(cols, rows) { self.background_color = background == :transparent ? 'rgba(255,255,255,0)' : background.to_s }
if background == :transparent
filled = new_img.matte_floodfill(1, 1)
else
filled = new_img.color_floodfill(1, 1, ::Magick::Pixel.from_color(background))
end
destroy_image(new_img)
filled.composite!(img, gravity, ::Magick::OverCompositeOp)
destroy_image(img)
filled = yield(filled) if block_given?
filled
end
end
# def my_resize_to_fill(height, width)
# manipulate! do |img|
# ImageTools::my_resize_to_fill(img,height, width)
# end
# end
version :preview, :if=>:not_pdf? do
process :resize_to_limit => [150, 150]
end
version :thumb, :if=>:not_pdf? do
process :resize_to_limit => [50, 50]
end
version :small, :if=>:not_pdf? do
process :resize_to_limit =>[100,100]
end
version :medium, :if=>:not_pdf? do
process :resize_to_limit =>[200,200]
end
version :large, :if=>:not_pdf? do
process :resize_to_limit =>[400,400]
end
#version :small_h do
# process :resize_to_fill =>[100,65]
#end
#version :tell_your_story do
# process :resize_to_fill =>[160,300]
#end
# version :collection_list do
# process :resize_to_fill =>[90,140]
# end
# version :store_list do
# process :resize_to_limit => [171,237]
# end
# version :store_list_mm do
# process :resize_to_fill => [115,180]
# end
# version :medium do
# process :resize_to_limit => [150, 150]
# end
# version :large do
# process :resize_to_limit => [300, 300]
# end
# version :view do
# process :resize_to_fill => [ 320, 441]
# process :outliner
# end
# version :view_h do
# process :resize_to_fill => [691,472]
# # process :outliner
# end
# version :primary do
# process :resize_to_fill =>[171,237]
# # process :resize_to_limit => [270, 410]
# # process :cropper=>[250,410]
# # process :outliner
# end
version :slider, :if=>:not_pdf? do
process :resize_to_fill => [634, 423]
# process :outliner
end
# version :product_slider do
# process :resize_to_fill => [651, 340]
# end
# version :advertisement do
# process :resize_to_limit => [140, 140]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
# %w(jpg jpeg gif png)
# end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
def pdf?(file)
File.extname(current_path).upcase == ".PDF"
end
def not_pdf?(file)
File.extname(current_path).upcase != ".PDF"
end
def cover
manipulate! do |frame, index|
frame if index.zero? # take only the first page of the file
end
end
version :pdf_preview , :if => :pdf? do
process :cover
process :resize_to_fit => [150, 150]
process :convert => :jpg
def full_filename (for_file = model.source.file)
super.chomp(File.extname(super)) + '.jpg'
end
end
version :pdf_thumb, :if => :pdf? do
process :cover
process resize_to_fit: [100, 100]
process :convert => :jpg
def full_filename (for_file = model.source.file)
super.chomp(File.extname(super)) + '.jpg'
end
end
# try to load local initializers for the image uploader.
image_uploader_additions = Rails.root.join('config', 'initializers', 'image_uploader.rb')
if File.exist?(image_uploader_additions) then
load image_uploader_additions
end
def validate_integrity
end
end
| true
|
8eb7dbb92f67a99d745b90c37f51d92bce60930b
|
Ruby
|
jessiegibson/looping-break-gets-001
|
/levitation_quiz.rb
|
UTF-8
| 214
| 3.421875
| 3
|
[] |
no_license
|
def levitation_quiz
#your code here
loop do
puts "What is the spell that enacts levitation?"
answer = gets.chomp
break if answer == "Wingardium Leviosa"
end
puts "You passed the quiz!"
end
| true
|
bc05e55e0294137bbc0b54cd5c4733095da64db2
|
Ruby
|
Kojack8/Ruby_odin_projects
|
/binary_search_tree/node.rb
|
UTF-8
| 269
| 2.984375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
# creates and modifies nodes to be used within the balanced binary search tree
class Node
def initialize(data, left = nil, right = nil)
@data = data
@left = left
@right = right
end
attr_accessor :left, :right, :data
end
| true
|
39485ecc4419cb887602a9628a08e6a18014ac56
|
Ruby
|
wojciech-stelmaszewski/projecteuler
|
/26.rb
|
UTF-8
| 2,573
| 3.34375
| 3
|
[] |
no_license
|
MAX_CYCLE_OFFSET = 10000
MAX_CYCLE_LENGTH = 1000 #For 1/p max cycle length cant be larger than (p-1)
MAX_ZERO_SECTION_LENGTH = 100
CYCLE_DETECTION_THRESHOLD = 7
class Integer
def only_2_or_5_are_proper_dividers?
n = self
while n > 1 do
previous_n = n
n /= 2 if n%2 == 0
n /= 5 if n%5 == 0
return false if previous_n == n
end
true
end
end
def get_decimal_expansion_section nominator, denominator, offset, length
number = Rational(nominator, denominator)
number = (number*(10**offset))
number = number - number.truncate
(number*(10**(length))).truncate
end
def length_of_cycle_in_decimal_expansion d
outer_cycle_length = 0
(0..MAX_CYCLE_OFFSET).each{|offset|
nil_decimal_expansion_test_result = get_decimal_expansion_section(1, d, offset, MAX_ZERO_SECTION_LENGTH)
if nil_decimal_expansion_test_result == 0 then
break
end
next_decimal_section_was_ever_greater_than_zero = false
(1..MAX_CYCLE_LENGTH).each{|cycle_length|
inner_cycle_found = true
(0..CYCLE_DETECTION_THRESHOLD).each{|x|
this_decimal_section = get_decimal_expansion_section(1, d, offset + cycle_length*x, cycle_length)
next_decimal_section = get_decimal_expansion_section(1, d, offset + (cycle_length*(x + 1)), cycle_length)
inner_cycle_found = false if this_decimal_section != next_decimal_section
if next_decimal_section != 0 then
next_decimal_section_was_ever_greater_than_zero = true
end
if(inner_cycle_found == false) then break end
}
if(!next_decimal_section_was_ever_greater_than_zero && cycle_length > MAX_ZERO_SECTION_LENGTH) then
break
end
decimal_expansion = get_decimal_expansion_section(1, d, offset, cycle_length)
if decimal_expansion != 0 && inner_cycle_found then
outer_cycle_length = cycle_length
break
end
}
return outer_cycle_length if outer_cycle_length != 0
}
nil
end
MAX_NUMBER = 1000
time_start = Time.now.to_f
#result_array = Array.new
max_number = -1
max_cycle_length = -1
(1..MAX_NUMBER).reverse_each{|x|
next if x.only_2_or_5_are_proper_dividers?
cycle_length = length_of_cycle_in_decimal_expansion x
if(cycle_length > max_cycle_length) then
max_number = x
max_cycle_length = cycle_length
end
break if(cycle_length == (x - 1))
}
time_end = Time.now.to_f
puts "The largest cycle (length equals #{max_cycle_length}) in decimal expansion has #{max_number}."
puts "Calculations took #{(time_end-time_start).round(3)} seconds."
| true
|
6b8230d83f2be572e479b78867d9e619818a2a57
|
Ruby
|
chef/chef
|
/chef-utils/lib/chef-utils/parallel_map.rb
|
UTF-8
| 4,756
| 2.796875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# frozen_string_literal: true
#
# Copyright:: Copyright (c) Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require "concurrent/executors"
require "concurrent/future"
require "singleton" unless defined?(Singleton)
module ChefUtils
#
# This module contains ruby refinements that adds several methods to the Enumerable
# class which are useful for parallel processing.
#
module ParallelMap
refine Enumerable do
# Enumerates through the collection in parallel using the thread pool provided
# or the default thread pool. By using the default thread pool this supports
# recursively calling the method without deadlocking while using a globally
# fixed number of workers. This method supports lazy collections. It returns
# synchronously, waiting until all the work is done. Failures are only reported
# after the collection has executed and only the first exception is raised.
#
# (0..).lazy.parallel_map { |i| i*i }.first(5)
#
# @return [Array] output results
#
def parallel_map(pool: nil)
return self unless block_given?
pool ||= ChefUtils::DefaultThreadPool.instance.pool
futures = map do |item|
Concurrent::Future.execute(executor: pool) do
yield item
end
end
futures.map(&:value!)
end
# This has the same behavior as parallel_map but returns the enumerator instead of
# the return values.
#
# @return [Enumerable] the enumerable for method chaining
#
def parallel_each(pool: nil, &block)
return self unless block_given?
parallel_map(pool: pool, &block)
self
end
# The flat_each method is tightly coupled to the usage of parallel_map within the
# ChefFS implementation. It is not itself a parallel method, but it is used to
# iterate through the 2nd level of nested structure, which is tied to the nested
# structures that ChefFS returns.
#
# This is different from Enumerable#flat_map because that behaves like map.flatten(1) while
# this behaves more like flatten(1).each. We need this on an Enumerable, so we have no
# Enumerable#flatten method to call.
#
# [ [ 1, 2 ], [ 3, 4 ] ].flat_each(&block) calls block four times with 1, 2, 3, 4
#
# [ [ 1, 2 ], [ 3, 4 ] ].flat_map(&block) calls block twice with [1, 2] and [3,4]
#
def flat_each(&block)
map do |value|
if value.is_a?(Enumerable)
value.each(&block)
else
yield value
end
end
end
end
end
# The DefaultThreadPool has a fixed thread size and has no
# queue of work and the behavior on failure to find a thread is for the
# caller to run the work. This contract means that the thread pool can
# be called recursively without deadlocking and while keeping the fixed
# number of threads (and not exponentially growing the thread pool with
# the depth of recursion).
#
class DefaultThreadPool
include Singleton
DEFAULT_THREAD_SIZE = 10
# Size of the thread pool, must be set before getting the thread pool or
# calling parallel_map/parallel_each. Does not (but could be modified to)
# support dynamic resizing. To get fully synchronous behavior set this equal to
# zero rather than one since the caller will get work if the threads are
# busy.
#
# @return [Integer] number of threads
attr_accessor :threads
# Memoizing accessor for the thread pool
#
# @return [Concurrent::ThreadPoolExecutor] the thread pool
def pool
@pool ||= Concurrent::ThreadPoolExecutor.new(
min_threads: threads || DEFAULT_THREAD_SIZE,
max_threads: threads || DEFAULT_THREAD_SIZE,
max_queue: 0,
# "synchronous" redefines the 0 in max_queue to mean 'no queue' instead of 'infinite queue'
# it does not mean synchronous execution (no threads) but synchronous offload to the threads.
synchronous: true,
# this prevents deadlocks on recursive parallel usage
fallback_policy: :caller_runs
)
end
end
end
| true
|
02525870d07d317b1f972f18d122b305a9ce9eb9
|
Ruby
|
xflagstudio/zenform-rb
|
/lib/zenform/commands/apply/base.rb
|
UTF-8
| 2,420
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
module Zenform
module Commands
module Apply
class Base
attr_reader :client, :project_path, :new_contents, :shell
MESSAGE_SKIPPED = "Skipped to create %{count} %{content_name} because they are already created."
MESSAGE_SUCCESS = "Success to create %{content_name}(slug: %{slug})!"
MESSAGE_FAILED = "Failed to create %{content_name}(slug: %{slug}) because %{error}."
def initialize(client, project_path, new_contents, shell)
@client = client
@project_path = project_path
@new_contents = create_param_list new_contents
@shell = shell
end
def run
created_contents = not_created_contents.map { |slug, content| [slug, create(content, slug)] }.to_h.compact
Zenform::FileCache.write project_path, content_name, cached_contents.merge(created_contents)
end
def content_name
raise NotImplementedError
end
private
def cached_contents
@cached_contents ||= Zenform::FileCache.read(project_path, content_name)
@cached_contents ||= {}
@cached_contents
end
def not_created_contents
already_created, not_created = new_contents.partition { |slug, _| cached_contents.keys.include? slug }.map(&:to_h)
if already_created.present?
shell.say MESSAGE_SKIPPED % { content_name: content_name, count: already_created.size }
shell.indent { already_created.keys.each { |slug| shell.say slug } }
end
not_created
end
def create_param_list(contents)
param_klass = Zenform::Param.const_get self.class.to_s.split("::").last
contents.inject({}) { |map, (slug, content)| map.merge slug => param_klass.new(content, extra_params) }
end
def extra_params
raise NotImplementedError
end
def create(content, slug = nil)
message_params = { method: __method__, content_name: content_name, slug: slug }
content = client.send(content_name).create!(content.tap(&:validate!).format)
shell.say MESSAGE_SUCCESS % message_params, :green
content.to_h
rescue ZendeskAPI::Error::ClientError, Zenform::ContentError => e
shell.say MESSAGE_FAILED % message_params.merge(error: e.to_s), :red
nil
end
end
end
end
end
| true
|
9ad7c36ed6ea063797c538e35b974947d2aaea97
|
Ruby
|
ISABELLA888/kwk-l1-mothers-day-methods-kwk-students-l1-port-072318
|
/mothers_day.rb
|
UTF-8
| 188
| 3.609375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
## Define your method, mothers_day, below. Go through the README and update your method as needed!
def mothers_day
mom = gets.strip
puts "Happy Mother's day #{mom}"
end
mothers_day
| true
|
a4f18bec27e4bc8ed12f78e8abff3ca26c3642ca
|
Ruby
|
Macro80-20/oo-counting-sentences-london-web-career-031119
|
/lib/count_sentences.rb
|
UTF-8
| 460
| 3.390625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class String
def sentence?
self.end_with?(".")
end
def question?
self.end_with?("?")
end
def exclamation?
self.end_with?("!")
end
def count_sentences
nu_of_setence = self.split(/[.?!]/).reject {|string| string.empty?}.length
end
end
# def sentence?(string)
# if string[string.length-1] == "."
# return true
# end
# return false
# end
# binding.pry
# sentence?("Hi, my name is Sophie.")
#str.sentence?
| true
|
d77935462fd8e9541b7b18e93d7b65a56708f8f6
|
Ruby
|
KerryKDiehl/test-first-ruby
|
/lib/14_array_extensions.rb
|
UTF-8
| 1,072
| 3.78125
| 4
|
[] |
no_license
|
class Array
def sum
sum_total = 0
self.each do |x|
sum_total += x
end
sum_total
end
def square
self.map do |x|
x * x
end
end
def square!
self.each_with_index do |x,i|
if x > 0
self[i] = x * x
end
end
end
def my_uniq
unique = []
self.each do |x|
if !unique.include?(x)
unique << x
end
end
unique
end
def two_sum
pairs = []
self.each_with_index do |x, n|
i = n + 1
while i < self.length
y = self[i]
if (x + y) == 0 && i != n
pairs << [n,i]
end
i += 1
end
end
pairs
end
def median
if self.length.odd?
self[self.length/2]
else
mid = (self.length/2-1)
(self[mid].to_f + self[mid+1].to_f)/2
end
end
def my_transpose
transpose = []
self.each_with_index do |x, i|
x.each_with_index do |y , n|
if !transpose[n]
transpose[n] = []
end
transpose[n][i] = y
end
end
transpose
end
end
| true
|
448537d785371f3f67e12db77055d215f52694a0
|
Ruby
|
dot-Sean/src
|
/rb/array.rb
|
UTF-8
| 97
| 2.671875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
a = []
a.push("Hello")
a.push("World")
puts a, a.length
| true
|
a981ac3428173d6b8963617829463aa9406f97b9
|
Ruby
|
felkh/image_blur
|
/image_blur_2.rb
|
UTF-8
| 1,292
| 3.796875
| 4
|
[] |
no_license
|
class Image
def initialize(array)
@image = array
end
def output_image
@image.each do |row|
puts row.join
end
end
def get_ones
ones = []
@image.each_with_index do |img_array, img_array_index|
img_array.each_with_index do |img_array_item, img_array_item_index|
if img_array_item == 1
ones << [img_array_index, img_array_item_index]
end
end
end
ones
end
def blur
ones = get_ones
@image.each_with_index do |img_array, img_array_index|
img_array.each_with_index do |img_array_item, img_array_item_index|
ones.each do |x_row_num, y_col_num|
if img_array_index == x_row_num && img_array_item_index == y_col_num
@image[img_array_index -1][img_array_item_index] = 1 unless img_array_index == 0
@image[img_array_index +1][img_array_item_index] = 1 unless img_array_index >= 4
@image[img_array_index][img_array_item_index -1] = 1 unless img_array_item_index == 0
@image[img_array_index][img_array_item_index +1] = 1 unless img_array_item_index >= 4
end
end
end
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.blur
image.output_image
| true
|
ef4e678dc9a0f557eaf36f86f92b98d2a40e761c
|
Ruby
|
SilverNightFall/Introduction-to-Programming-with-Ruby
|
/lab_in_word.rb
|
UTF-8
| 274
| 3.03125
| 3
|
[] |
no_license
|
def lab_in_word?(word)
if /lab/i.match(word)
puts "Lab is in the word #{word}"
else
puts "Lab is not in the word #{word}"
end
end
lab_in_word?("laboratory")
lab_in_word?("experiment")
lab_in_word?("Pans Labyrinth")
lab_in_word?("elaborate")
lab_in_word?("polar bear")
| true
|
ffa7bb7f1e84ba35057f08aa4c82fddfc730551b
|
Ruby
|
kamalpandey/phone_number_to_words_combinations
|
/lib/phone_number_to_words/phone_number_to_words.rb
|
UTF-8
| 2,406
| 3.546875
| 4
|
[] |
no_license
|
# frozen_string_literal: true
MIN_LENGTH = 3
MAX_LENGTH = 10
require_relative './dictionary_utils.rb'
require_relative 'exceptions.rb'
require_relative 'possible_combinations.rb'
class PhoneNumberToWords
def initialize
@phone_number = ''
@dictionary = load_dictionary
@final_result = []
@possible_combinations = []
end
def perform!
takes_input_and_validate
print('Results', generate_words(phone_number))
puts("\n")
end
def takes_input_and_validate
begin
puts 'Please enter the 10 digit mobile number :'
@phone_number = gets.chomp
raise Exceptions::InvalidPhoneNumber unless valid_number?(phone_number)
rescue Exceptions::InvalidPhoneNumber => e
puts e.message
end
end
# returns all the possible combinations for given number
def all_possible_combinations(phone_number)
@possible_combinations = PossibleCombinations.number_of_possible_combinations(
phone_number,
MIN_LENGTH,
MAX_LENGTH
)
end
def load_dictionary
@dictionary = DictionaryUtils.load_dictionary
@dictionary
end
def get_words_from_dictionary(number)
words = dictionary[number] unless number.nil?
return unless words
words.map { |_, value| value } # returns only the value as key contains the numeric version of the word due to group by
end
def generate_final_result(results)
results.each do |combinations|
next if combinations.first.nil? || combinations.last.nil?
first_combination, *rest_combinations = combinations
@final_result << first_combination.product(*rest_combinations)
end
@final_result.flatten(1).delete_if { |array| array.join.length < MAX_LENGTH } # removing if the combined word length is less than 10
end
def generate_words(phone_number)
possible_combinations = []
all_possible_combinations(phone_number).each do |combinations|
temp_combinations = []
combinations.each do |combination|
words_from_dictionary = get_words_from_dictionary(combination)
temp_combinations << words_from_dictionary if words_from_dictionary
end
possible_combinations << temp_combinations
end
generate_final_result(possible_combinations)
end
def valid_number?(phone_number)
phone_number.gsub(/[^2-9]/, '').length == MAX_LENGTH
end
attr_accessor :phone_number, :possible_combinations, :dictionary
end
| true
|
f6c4143409b8052d9f9c065a92040176b0ecbfcf
|
Ruby
|
mickeysanchez/tour_planner
|
/vendor/plugins/temboo-ruby-sdk-1.77/lib/Library/Instapaper.rb
|
UTF-8
| 5,938
| 2.921875
| 3
|
[] |
no_license
|
require "temboo"
module Instapaper
##############################################################################
#
# AddURL
#
# Add a document to an Instapaper account.
#
##############################################################################
class AddURL < Choreography
####
# Create a new instance of the AddURL Choreo. A TembooSession object, containing a valid
# set of Temboo credentials, must be supplied.
####
def initialize(session)
super(session, "/Library/Instapaper/AddURL")
end
####
# Obtain an InputSet object, used to define inputs for an execution of this Choreo.
#
# @return AddURLInputSet
####
def new_input_set()
return AddURLInputSet.new()
end
def make_result_set()
return AddURLResultSet.new()
end
####
# Execute the Choreo using the specified InputSet as parameters, wait for the Choreo to complete
# and return a ResultSet containing the execution results.
# @param choreoInputs
# @return
# @throws TembooException
####
def execute(input_set = nil)
resp = super(input_set)
results = AddURLResultSet.new(resp)
return results
end
####
# An InputSet with methods appropriate for specifying the inputs to the AddURL
# Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
####
class AddURLInputSet < Choreography::InputSet
####
# Set the value of the Password input for this Choreo.
#
# @param String - (required, string) Your Instapaper password.
###
def set_Password(value)
set_input("Password", value)
end
####
# Set the value of the Selection input for this Choreo.
#
# @param String - (optional, string) Enter a description of the URL being added.
###
def set_Selection(value)
set_input("Selection", value)
end
####
# Set the value of the Title input for this Choreo.
#
# @param String - (optional, string) Enter a titile for the uploaded URL. If no title is provided, Instapaper will crawl the URL to detect a title.
###
def set_Title(value)
set_input("Title", value)
end
####
# Set the value of the URL input for this Choreo.
#
# @param String - (required, string) Enter the URL of the document that is being added to an Instapaper account.
###
def set_URL(value)
set_input("URL", value)
end
####
# Set the value of the Username input for this Choreo.
#
# @param String - (required, string) Your Instapaper username.
###
def set_Username(value)
set_input("Username", value)
end
end
####
# A ResultSet with methods tailored to the values returned by the AddURL Choreo.
# The ResultSet object is used to retrieve the results of a Choreo execution.
####
class AddURLResultSet < Choreography::ResultSet
####
# Retrieve the value for the "Response" output from this Choreo execution
#
# @return String - (integer) The response from Instapaper. Successful reqests will return a 201 status code.
####
def get_Response()
return @outputs["Response"]
end
end
end # class AddURL
##############################################################################
#
# Authenticate
#
# Validate an Instapaper account.
#
##############################################################################
class Authenticate < Choreography
####
# Create a new instance of the Authenticate Choreo. A TembooSession object, containing a valid
# set of Temboo credentials, must be supplied.
####
def initialize(session)
super(session, "/Library/Instapaper/Authenticate")
end
####
# Obtain an InputSet object, used to define inputs for an execution of this Choreo.
#
# @return AuthenticateInputSet
####
def new_input_set()
return AuthenticateInputSet.new()
end
def make_result_set()
return AuthenticateResultSet.new()
end
####
# Execute the Choreo using the specified InputSet as parameters, wait for the Choreo to complete
# and return a ResultSet containing the execution results.
# @param choreoInputs
# @return
# @throws TembooException
####
def execute(input_set = nil)
resp = super(input_set)
results = AuthenticateResultSet.new(resp)
return results
end
####
# An InputSet with methods appropriate for specifying the inputs to the Authenticate
# Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
####
class AuthenticateInputSet < Choreography::InputSet
####
# Set the value of the Password input for this Choreo.
#
# @param String - (required, string) Your Instapaper password.
###
def set_Password(value)
set_input("Password", value)
end
####
# Set the value of the Username input for this Choreo.
#
# @param String - (required, string) Your Instapaper username.
###
def set_Username(value)
set_input("Username", value)
end
end
####
# A ResultSet with methods tailored to the values returned by the Authenticate Choreo.
# The ResultSet object is used to retrieve the results of a Choreo execution.
####
class AuthenticateResultSet < Choreography::ResultSet
####
# Retrieve the value for the "Response" output from this Choreo execution
#
# @return String - (xml) The response from Instapaper. Successful reqests will return a 200 status code.
####
def get_Response()
return @outputs["Response"]
end
end
end # class Authenticate
end # module Instapaper
| true
|
7eef3f3c96d8cee983f95f826beb07978881734d
|
Ruby
|
eduardopoleo/myflix
|
/app/models/stripe_wrapper.rb
|
UTF-8
| 1,779
| 2.890625
| 3
|
[] |
no_license
|
module StripeWrapper
#this is just a wrapper so no need to extend from Active Record Base
class Charge
attr_reader :response, :status
#This allows me this some_charge = Charge.new(some_response, some_status)
#some_charge.response = some_response
#some_charge.status = some_status
#We need this methods available because the succesful and error methods use them implicitly
def initialize(response, status)
@response = response
@status = status
end
def self.create(options={})
begin
response = Stripe::Charge.create(customer: options[:customer],
amount: options[:amount],
description: options[:description],
currency: 'usd',
card: options[:card])
new(response, :success)
#This is the same as saying Charge.new, since this is a class method there is no need to write it explicitly
rescue Stripe::CardError => e
new(e, :error)
end
end
def successful?
status == :success
end
def error
response.message
end
end
class Costumer
attr_accessor :response, :status
def initialize(response, status)
@response = response
@status = status
end
def self.create(options={})
begin
response = Stripe::Customer.create(
email: options[:user].email,
card: options[:card],
plan: 'regular'
)
new(response, :success)
rescue Stripe::CardError => e
new(e, :error)
end
end
def successful?
status == :success
end
def error
response.message
end
end
end
| true
|
ecdb1dbbe1d74fff90b2c53154b64ac8a1d56580
|
Ruby
|
ciihla/simple_tooltip
|
/lib/generators/simple_tooltip/install_generator.rb
|
UTF-8
| 3,609
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module SimpleTooltip
module Generators
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
desc "This generator installs all the files necessary for the simple_tooltip gem"
def copy_stylesheet_and_images
path = "public/stylesheets/simple_tooltip.css"
copy_file "./#{path}", path
path = "public/images/simple_tooltip_help_icon.png"
copy_file "./#{path}", path
path = "public/images/simple_tooltip_close_icon.png"
copy_file "./#{path}", path
end
def copy_javascript
path = "public/javascripts/simple_tooltip.js"
copy_file "./#{path}", path
end
def copy_migration
# Migration file name is preceded by the date/time string - UTC timestamp Time.now.gmtime.strftime("%Y%m%d%H%M%S")
copy_file "./db/migrate/create_tooltips.rb",
"db/migrate/#{Time.now.gmtime.strftime("%Y%m%d%H%M%S")}_create_tooltips.rb"
end
def copy_app_files
path = "app/controllers/tooltips_controller.rb"
copy_file "./#{path}", path
path = "app/models/tooltip.rb"
copy_file "./#{path}", path
path = "app/helpers/tooltip_helper.rb"
copy_file "./#{path}", path
path = "app/views/tooltips"
directory "./#{path}", path
end
def copy_tests
path = "test/unit/tooltip_test.rb"
copy_file "./#{path}", path
path = "test/unit/helpers/tooltips_helper_test.rb"
copy_file "./#{path}", path
path = "test/fixtures/tooltips.yml"
copy_file "./#{path}", path
path = "test/functional/tooltips_controller_test.rb"
copy_file "./#{path}", path
end
# Add this multi line definition to the routes file - but only a single call to route
# otherwise they are placed in reverse line order!
def setup_route
route "resources :tooltips do\n" +
" collection do\n" +
" get 'tooltip_content'\n" +
" end\n" +
" end"
end
# Output installation instructions for the user
def instructions
puts '---------------------------------------------------------------'
puts 'To complete your installation...'
puts ''
puts "1: Add this gem to your project Gemfile and run 'bundle install'"
puts ''
puts " gem 'simple-tooltip'"
puts ''
puts '2: Run db:migrate to create the tooltips database table'
puts ''
puts " $ rake db:migrate"
puts ''
puts '3: Make sure you have the jQuery JavaScript library installed (via jquery-rails)'
puts ''
puts ' $ rails generate jquery:install'
puts ''
puts '4: Check that these first two lines are in layouts/application.html.erb and add the third'
puts ''
puts ' <%= stylesheet_link_tag :all %>'
puts ' <%= javascript_include_tag :defaults %>'
puts " <%= javascript_include_tag 'simple_tooltip.js' %>"
puts ''
puts '5: Create some tooltip entries in /tooltips and then add links'
puts ' to them in views of your other models'
puts " <%= tooltip('tooltip title', :hover) %>"
puts ''
puts 'For more information see the project page on GitHub'
puts ' https://github.com/craic/simple_tooltip'
puts '---------------------------------------------------------------'
end
end
end
end
| true
|
6e677772cc6822e75d4a00e19de87e50abf21538
|
Ruby
|
thesyaf/rollcallatron
|
/attendance_app.rb
|
UTF-8
| 6,983
| 3.484375
| 3
|
[] |
no_license
|
<<<<<<< HEAD
=======
require "csv"
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
require "terminal-table"
require "artii"
# The hash array containing the students (Keys) and their answers (Values)
class_list = {
Terence: "",
Cindy: "",
Jonathan: "",
Ali: "",
Timothy: "",
Sophie: "",
Carmen: "",
Khaled: "",
Peter: "",
Rajani: "",
Sakshi: "",
Sana: "",
Travis: "",
Nathanial: "",
Kevin: "",
Ric: "",
James: "",
Olivia: "",
Omar: "",
Neil: "",
Takuya: "",
Thomas: "",
Gregory: "",
Alex: "",
Bianca: "",
Tessa: "",
Paul: "",
Richard: "",
David: "",
Kasumi: "",
Syaf: "",
}
<<<<<<< HEAD
# Creates and stores the student/answer data
class Answers
def initialize(name, answer)
@name = name
@answer = answer
=======
class Students
def initalize(id)
@id = id
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
end
attr_accessor :id
<<<<<<< HEAD
def writetoarray(class_list,todays_question) #this is being done in the loop.
class_list[@name.to_sym] = @answer
table = Terminal::Table.new :headings => ["Name", todays_question],:rows => class_list
puts table
=======
def choose_student
youth = [
"Terence",
"Cyndi",
"Jonathan",
"Ali",
"Timothy",
"Sophie",
"Carmen",
"Khaled",
"Peter",
"Rajani",
"Sakshi",
"Sana",
"Travis",
"Nathanial",
"Kevin",
"Ric",
"James",
"Olivia",
"Omar",
"Neil",
"Takuya",
"Thomas",
"Gregory",
"Alex",
"Bianca",
"Tessa",
"Paul",
"Richard",
"David",
"Kasumi",
"Syaf",
]
todays_student = youth.shuffle.first
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
end
end
# Randomly selects the student that takes the roll
class Students
def initalize(id)
@id = id
end
attr_accessor :id
def choose_student
youth = [
"Terence",
"Cindy",
"Jonathan",
"Ali",
"Timothy",
"Sophie",
"Carmen",
"Khaled",
"Peter",
"Rajani",
"Sakshi",
"Sana",
"Travis",
"Nathanial",
"Kevin",
"Ric",
"James",
"Olivia",
"Omar",
"Neil",
"Takuya",
"Thomas",
"Gregory",
"Alex",
"Bianca",
"Tessa",
"Paul",
"Richard",
"David",
"Kasumi",
"Syaf",
]
todays_student = youth.shuffle.first
end
end
# Randomly selects the question
class Questions
def initialize(question=0)
@question = question
end
def randomise_q
questions = [
"Would you rather be rich and ugly, or poor and good looking?",
"Do you regularly read movie reviews?",
"What's your favourite sports team?",
"What celebrity do you like to follow?",
"What is the best thing that has happened to you this week?",
"If you could have one super power, what would it be?",
"What is your biggest fear?",
"If you were asked to teach a class, what class would you teach?",
"What do you do to stay in shape?",
"Do you follow your heart or your head?",
"What is your dream job?",
"Would you rather have summer weather or winter weather all year round?",
"Who is your favorite actor/actress?",
"Who is the most famous person you have met?",
"What is your biggest regret this week?",
"Do you prefer to travel or stay close to home?",
"What do you wear to sleep?",
"What is the longest that you've stayed awake for?",
"If you could be any celebrity, who would it be?",
"What did you have for lunch yesterday?",
"What do you usually eat in the morning?",
"Do you recycle?",
"What job would you choose to try?",
"Are you an indoor or outdoor person?",
"Do you prefer talking over the phone or face to face?",
"Do you have any pets?",
"What drink do you usually order with your food?",
"Where do you work?",
"What's your favourite cheese?",
"What's your favourite pizza topping?",
"PC or Mac?",
"What’s your favourite colour?",
"What’s your favourite dessert?",
"Coffee or tea?",
"If you could travel anywhere in the world where would you go?",
"What’s your favourite hobby?",
"Can you drive?",
"Have you ever been camping?",
"Have you ever been on a roadtrip?",
"Sunset or Sunrise?"
]
todays_question = questions.shuffle.first
end
end
## This part should get a randomised question from the Question class
todays_question = Questions.new.randomise_q
todays_student = Students.new.choose_student
## This generates the initial list of names with todays question.
table = Terminal::Table.new :headings => ["Name", todays_question],:rows => class_list
a = Artii::Base.new :font => 'slant'
<<<<<<< HEAD
titleroll = a.asciify('Rollcallatron')
# Program starts here
system("clear")
puts titleroll
puts table
puts
print "The person taking the role today is"
sleep(1)
print "."
sleep(1)
print "."
sleep(1)
print "."
sleep(1)
puts "*drumroll please*"
sleep(1)
puts "#{todays_student}, you're up!"
sleep(1)
=======
titleroll = a.asciify('Roll-call-atron')
puts
puts "The person taking the role today is ..."
sleep(1)
puts "*drumroll please*"
sleep(1)
puts "#{todays_student} is taking the role today"
sleep(2)
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
## This loops over the process to select a person and get their answer
loop do
system("clear")
puts titleroll
puts table
puts "Who are you marking off?"
idno = gets.chomp.capitalize
if class_list[idno.to_sym].nil?
puts "Check your spelling or the name entered is not in the class."
else
puts todays_question
<<<<<<< HEAD
ans = Answers.new(idno, gets.chomp)
system("clear")
end
puts titleroll
ans.writetoarray(class_list,todays_question)
puts "\nMark off next person? (yes) (no) \n \nFinalise and export (export)"
mark_next = gets.chomp
if mark_next == "no"
break
# Exports current state of array to txt file.
=======
ans = gets.chomp
class_list[idno.to_sym] = ans
table = Terminal::Table.new :headings => ["Name", todays_question],:rows => class_list
system("clear")
end
puts titleroll
puts table
puts "Mark off another person? (yes) (no) \nFinalise and export (export)"
mark_next = gets.chomp
if mark_next == "no"
break
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
elsif mark_next == "export"
d = Time.now.strftime("%d%m%Y")
saved_file = File.new("#{d}:#{todays_question}.txt", "w+")
File.open(saved_file, 'w') do |file|
class_list.each{ |k, v| file.write("#{k}: #{v}\n") }
<<<<<<< HEAD
print "Exporting file"
sleep(1)
print "."
sleep(1)
print "."
sleep(1)
print "."
puts "File exported."
abort
break
=======
abort
>>>>>>> bd5a3b6dae4a5a8687757456c30e65108ac4a02e
end
end
end
| true
|
992d24ac74777517386e9387b511bdaa28d9ebee
|
Ruby
|
ta1m1kam/Atcoder
|
/050/A.rb
|
UTF-8
| 116
| 3.296875
| 3
|
[] |
no_license
|
arr = gets.chomp.split
if arr[1] == '+'
puts arr[0].to_i + arr[2].to_i
else
puts arr[0].to_i - arr[2].to_i
end
| true
|
fcf90c8d7c8d002e052f8231907e6d0a886d9be0
|
Ruby
|
Pustelto/Bracketeer
|
/test/language_files/ruby.rb
|
UTF-8
| 725
| 4.28125
| 4
|
[
"MIT"
] |
permissive
|
def get_numbers_stack(list)
stack = [[0, []]]
output = []
until stack.empty?
index, taken = stack.pop
next output << taken if index == list.size
stack.unshift [index + 1, taken]
stack.unshift [index + 1, taken + [list[index]]]
end
output
end
s = "Hi there. How are you?"
print s.length, " [" + s + "]\n"
# Selecting a character in a string gives an integer ascii code.
print s[4], "\n"
printf("%c\n", s[4])
# The [n,l] substring gives the starting position and length. The [n..m]
# form gives a range of positions, inclusive.
print "[" + s[4,4] + "] [" + s[6..15] + "]\n"
print "Wow " * 3, "\n"
print s.index("there"), " ", s.index("How"), " ", s.index("bogus"), "\n"
print s.reverse, "\n"
| true
|
e122c24d15ab0b20e9cb792251b935b657cff0f9
|
Ruby
|
wyhaines/iowa
|
/src/iowa/Mutex.rb
|
UTF-8
| 2,851
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
module Iowa
# Iowa::Mutex is a slight modification of the standard Ruby Mutex class.
# This class changes the array operations used to manage the queue of
# threads waiting for a lock in order to get better memory management
# behavior from the array. This mutex will also not block if the thread
# holding a lock on a mutex calls lock on that mutex again. If nested
# locking occurs, the locks must be matched by an equal number of unlocks
# before the mutex will actually be unlocked.
class Mutex
# Creates a new Mutex.
def initialize
@waiting = []
@locked = false;
@nested_locks = 0
@waiting.taint # enable tainted comunication
self.taint
end
# Returns the thread that holds the lock or +false+ if the mutex is not locked.
def locked?
@locked
end
# Attempts to obtain the lock and returns immediately. Returns +true+ if the
# lock was granted.
def try_lock
@nested_locks += 1 and return true if @locked == Thread.current
result = false
Thread.critical = true
unless @locked
@locked = Thread.current
result = true
end
Thread.critical = false
result
end
# Attempts to obtain a lock on the mutex. Block if a lock can not be
# obtained immediately and waits until the lock can be obtained.
# If this thread already holds this lock, returns immediately.
# Returns the mutex.
def lock
if @locked == Thread.current
@nested_locks += 1
else
while (Thread.critical = true; @locked)
@waiting.unshift Thread.current
Thread.stop
end
@locked = Thread.current
Thread.critical = false
end
self
end
# Releases this thread's lock on the mutex and wakes the next thread
# waiting for the lock, if any.
def unlock
return unless @locked
if @nested_locks > 0
@nested_locks -= 1
else
Thread.critical = true
@locked = false
begin
t = @waiting.pop
t.wakeup if t
rescue ThreadError
retry
end
Thread.critical = false
begin
t.run if t
rescue ThreadError
end
end
self
end
# If the mutex is locked, unlocks the mutex, wakes one waiting thread, and
# yields in a critical section.
def exclusive_unlock
return unless @locked
if @nested_locks > 0
@nested_locks -= 1
else
Thread.exclusive do
@locked = false
begin
t = @waiting.pop
t.wakeup if t
rescue ThreadError
retry
end
yield
end
end
self
end
# Obtains a lock, runs the block, and releases the lock when the block
# completes. See the example under Mutex.
def synchronize
lock
begin
yield
ensure
unlock
end
end
def synchronize_unless(cond)
unless cond
lock
begin
yield
ensure
unlock
end
else
yield
end
end
end
end
| true
|
652e8d0cc5281f4da2970fc0081541d10a3f35d4
|
Ruby
|
jywei/ruby-toys
|
/small_script5.rb
|
UTF-8
| 209
| 3
| 3
|
[] |
no_license
|
#逐一行印出
f = File.open("small_script1.rb")
while line = f.gets do
puts line
end
f.close
#逐一行顯示
File.open( "small_script2.rb" , "r" ) do |f|
while line = f.gets
puts line
end
end
| true
|
83778cd8bc70d8a61dc9dcdc19797c6ea212ee21
|
Ruby
|
tiagofoks/MentoriaLucas
|
/crud.rb
|
UTF-8
| 1,160
| 3.296875
| 3
|
[] |
no_license
|
require './post'
require './menu'
menu
action = gets.chomp
if action == '1'
puts 'Digite seu post:'
param_text = gets.chomp
post = Post.new
post.text = param_text
post.create
puts "Ultimo post cadastrado:"
post = Post.read_last_one
puts post.text
end
if action == '2'
puts 'Digite o Id referente qual mensagem deseja ler'
puts 'Para ler todas as mensagens digite all'
post_id_or_all = gets.chomp
if post_id_or_all == 'all'
Post.read_all.each do |post|
puts post.text
end
else
post = Post.read_individual(post_id_or_all)
puts post.text
end
end
if action == '3'
puts 'Informe o id da mensagem que deseja atualizar'
post_id = gets.chomp
post = Post.read_individual(post_id)
puts 'Digite a nova mensagem para o Post:'
message_update = gets.chomp
post.text = message_update
post.update
puts 'Confira sua mensagem atualizada!'
up_post = Post.read_individual(post_id)
puts up_post.text
end
if action == '4'
puts 'Digite o Id da mensagem que deseja deletar'
id_message = gets.chomp
post = Post.read_individual(id_message)
post.delete
puts 'Esta mensagem foi deletada!'
end
| true
|
a3997c4c8da3af8157220230225ac1d0c0fd53cf
|
Ruby
|
adamgriffis/code-eval-solutions
|
/DollarText/test.rb
|
UTF-8
| 2,273
| 4.03125
| 4
|
[] |
no_license
|
def get_single(num)
if num == 0
return "Zero"
elsif num == 1
return "One"
elsif num == 2
return "Two"
elsif num == 3
return "Three"
elsif num == 4
return "Four"
elsif num == 5
return "Five"
elsif num == 6
return "Six"
elsif num == 7
return "Seven"
elsif num == 8
return "Eight"
elsif num == 9
return "Nine"
elsif num == 10
return "Ten"
elsif num == 11
return "Eleven"
elsif num == 12
return "Twelve"
elsif num == 13
return "Thirteen"
elsif num == 14
return "Fourteen"
elsif num == 15
return "Fifteen"
elsif num == 16
return "Sixteen"
elsif num == 17
return "Seventeen"
elsif num == 18
return "Eighteen"
elsif num == 19
return "Nineteen"
end
return ""
end
def base_ten(num)
if num == 2
return "Twenty"
elsif num == 3
return "Thirty"
elsif num == 4
return "Forty"
elsif num == 5
return "Fifty"
elsif num == 6
return "Sixty"
elsif num == 7
return "Seventy"
elsif num == 8
return "Eighty"
else
return "Ninety"
end
end
def get_tens(num)
result = ""
if num >= 20
result = base_ten(num/10)
remainder = num%10
if remainder > 0
result = result + get_single(remainder)
end
else
result = get_single(num)
end
return result
end
def get_hundred_count(num)
result = ""
hundreds = (num/100)
if hundreds > 0
result = get_tens(hundreds) + "Hundred"
end
remainder = num % 100
result = result + get_tens(remainder)
end
File.open(ARGV[0]).each_line do |line|
origNum = line.to_i
num = line.to_i
result = ""
if num >= 1000000
result = get_hundred_count(num/1000000) + "Million"
num = num % 1000000
end
if num >= 1000
result = result + get_hundred_count(num/1000) + "Thousand"
num = num % 1000
end
result = result + get_hundred_count(num) + "Dollar"
if origNum != 1
result = result + "s"
end
puts result.to_s
end
| true
|
5519f45d7ceebb60e13f8021245ec2eb35c11c14
|
Ruby
|
jvshahid/Android
|
/android.rb
|
UTF-8
| 3,024
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require "term/ansicolor"
String.send :include, Term::ANSIColor
def script_name
File.basename $0
end
if ARGV.count != 1
puts "Usage: #{script_name} [setup | update | recover | [upload image_name]]".red
puts "where: "
puts " setup: sets up the android development kit (implies update)"
puts " update: run 'android update sdk --fitler 'platform-tool' --no-ui'"
puts " recover: installs the original sdk that was shipped with the galaxy s2"
puts " clockwork: installs clockworkmod"
puts " upload: uploads the given image to your android"
end
def error msg
puts msg.red
exit 1
end
def android_sdk_version
'20.0.1'
end
def android_sdk_url
"http://dl.google.com/android/android-sdk_r#{android_sdk_version}-linux.tgz"
end
def update
Dir.chdir 'adk' do
system("./tools/android update sdk --filter 'platform-tool' --no-ui")
end
end
def setup
unless Dir.exists? 'adk'
Dir.mkdir 'adk'
Dir.chdir 'adk' do
system("curl '#{android_sdk_url}' > adk.tar.gz") or error("Cannot retrieve the android sdk from #{android_sdk_url}")
system("tar --strip-components=1 -xvzf adk.tar.gz")
end
end
if RUBY_PLATFORM =~ /686/
system("sudo dpkg -i heimdall_1.3.0_i386.deb")
else
system("sudo dpkg -i heimdall_1.3.0_amd64.deb")
end
update
end
def is_adb_server_up?
system("pgrep -f adb")
end
def start_adb_server
system("./adb/platform-tools/adb start-server") unless is_adb_server_up?
end
def stop_adb_server
system("pkill -f adb")
end
def upload_zimage
system("sudo heimdall flash --kernel recovery/zImage --factoryfs recovery/factoryfs.img")
end
def prompt
print "Is your phone in download mode (by turning it off, unplugging usb, holding the volume down and reinserting usb ? [Yn] ".green
unless STDIN.getc =~ /Y|y/
puts "Aborting".red
exit 1
end
end
def clockworkmod
prompt
system("sudo heimdall flash --kernel clockworkmod/zImage")
end
def recover
prompt
system("sudo heimdall flash --kernel recovery/zImage --factoryfs recovery/factoryfs.img")
end
def upload
puts "This step requires manual intervention at the moment".green
puts "Enter the recovery mode by first turning off the device, then holding volume up, down and power button at the same time".green
puts "The device should start, then restart and enter into the recovery mode".green
puts "When in recovery mode, mount the sdcard, then copy the cyanogenmod file to the root directory".green
puts "Select 'install from sdcard' and select the file that you uploaded".green
puts "In order to get google apps you have to follow the same instruction to install the google apps zip".green
puts "Note: each cyanogen mod has its own version of google apps see (http://wiki.cyanogenmod.com/wiki/Latest_Version/Google_Apps)".red
end
if ARGV.first == 'setup'
setup
elsif ARGV.first == 'update'
update
elsif ARGV.first == 'recover'
recover
elsif ARGV.first == 'clockworkmod'
clockworkmod
elsif ARGV.first == 'upload'
upload
end
| true
|
a499617269969ab4ec34856d31f7c2445f024cd5
|
Ruby
|
Shidame/Terres-du-Nil
|
/app/models/city_creator.rb
|
UTF-8
| 336
| 2.578125
| 3
|
[] |
no_license
|
class CityCreator
def initialize(user)
@user = user
end
def create!
nb_cities = @user.cities.count
City.transaction do
city = City.new
city.user = @user
city.name = "#{@user.username}-#{nb_cities+1}"
city.save!
map = MapCreator.new(city)
map.create!
city
end
end
end
| true
|
c37ef48ee9c78687d8c53de47c032569802fc83b
|
Ruby
|
thomthom/shadow-catcher
|
/tt_shadowcatcher.rb
|
WINDOWS-1250
| 20,411
| 2.515625
| 3
|
[] |
no_license
|
#-------------------------------------------------------------------------------
#
# Thomas Thomassen
# thomas[at]thomthom[dot]net
#
#-------------------------------------------------------------------------------
require 'sketchup.rb'
require 'TT_Lib2/core.rb'
TT::Lib.compatible?('2.6.0', 'TT Shadow Catcher')
#-------------------------------------------------------------------------------
module TT::Plugins::ShadowCatcher
=begin
http://stackoverflow.com/a/2818881/486990
Imagine the projection onto a plane as a "view" of the model (i.e. the direction
of projection is the line of sight, and the projection is what you see). In that
case, the borders of the polygons you want to compute correspond to the
silhouette of the model.
The silhouette, in turn, is a set of edges in the model. For each edge in the
silhouette, the adjacent faces will have normals that either point away from the
plane or toward the plane. You can check this be taking the dot product of the
face normal with the plane normal -- look for edges whose adjacent face normals
have dot products of opposite signs with the projection direction.
Once you have found all the silhouette edges you can join them together into the
boundaries of the desired polygons.
Generally, you can find more about silhouette detection and extraction by
googling terms like mesh silouette finding detection.
=end
### CONSTANTS ### ------------------------------------------------------------
# Plugin information
PLUGIN_ID = 'TT_ShadowCatcher'.freeze
PLUGIN_NAME = 'Shadow Catcher'.freeze
PLUGIN_VERSION = TT::Version.new( 1,0,0 ).freeze
SHADOWS_MATERIAL_NAME = '02 - Shadows'.freeze
SHADOWS_MATERIAL_COLOR = Sketchup::Color.new( 255, 0, 0 )
SHADOWS_MATERIAL_ALPHA = 0.5
### MENU & TOOLBARS ### ------------------------------------------------------
unless file_loaded?( __FILE__ )
# Menus
menu = TT.menu( 'Plugins' )
menu.add_item( 'Catch Shadows' ) { self.catch_shadows }
end
### LIB FREDO UPDATER ### ----------------------------------------------------
def self.register_plugin_for_LibFredo6
{
:name => PLUGIN_NAME,
:author => 'thomthom',
:version => PLUGIN_VERSION.to_s,
:date => '27 Sep 12',
:description => 'Catches shadows on selected face.',
:link_info => 'http://forums.sketchucation.com/viewtopic.php?f=0&t=0'
}
end
### MAIN SCRIPT ### ----------------------------------------------------------
# Projects shadows from instances in the current context onto selected face.
#
# Shadow casting instances can be limited by selecting the instances that
# should cast shadows.
#
# @since 1.0.0
def self.catch_shadows
model = Sketchup.active_model
selection = model.selection
context = model.active_entities
direction = model.shadow_info['SunDirection'].reverse
# Validate User Input
# Ensure there is one, and only one, face that receives shadows in the
# selection.
faces = selection.select { |e|
e.is_a?( Sketchup::Face ) &&
e.receives_shadows?
}
instances = self.select_visible_instances( selection.to_a - faces )
if faces.empty?
UI.messagebox( 'There must be a face receiving shadows in the selection.' )
return nil
elsif faces.size > 1
UI.messagebox( 'There can be only one face receiving shadows in the selection.' )
return nil
end
# If no instances are selected then all instances in the current context is
# processed.
#
# (?) Detect and ignore previously processed shadow groups?
if instances.empty?
instances = self.select_visible_instances( model.active_entities )
end
# Ensure there is something to cast shadows.
if instances.empty?
UI.messagebox( 'There is no geometry to cast shadow.' )
return nil
end
model.start_operation( 'Catch Shadows', true )
target_face = faces.first # Face to catch shadows for.
instance_shadows = context.add_group # Group containing generated shadows.
for instance in instances
# Cast shadows from the instance onto the plane of the target face.
transformation = instance.transformation
shadows, ground_area = self.shadows_from_entities(
target_face, instance, direction, instance_shadows.entities
)
# Trim shadows to the target face.
trim_group = self.create_trim_group( target_face, instance_shadows.entities )
trim_group_definition = TT::Instance.definition( trim_group )
for shadow in shadows.entities
self.trim_to_face(
target_face, shadow.entities, transformation, trim_group_definition
)
end
trim_group.erase!
# Merge shadows from each mesh group into one.
self.merge_instances( shadows.entities )
end
# Merge shadows from all instances into one.
self.merge_instances( instance_shadows.entities )
# Organize shadow group into a layer with a descriptive name.
instance_shadows.layer = self.get_shadow_layer
instance_shadows.name = "Shadows: #{self.get_formatted_shadow_time}"
# Output area data.
self.calculate_shadow_statistics(
target_face, instance_shadows.entities, ground_area
)
model.commit_operation
end
# Intersect doesn't always split the mesh like you would expect.
#
# A +
# |\
# | \
# B +--+--+ C
# ^
# D
#
# In this polygon ( ABCD ) vertex D overlaps edge BC, but intersect doesn't
# split it. BC and CD both connects to face ABCD even though they overlap.
#
# This method creates a set of zero length edges at each vertex in a temp
# group which will cause the edges to properly split when the temp group is
# exploded.
#
# @param [Sketchup::Entities] entities
#
# @return [Nil]
# @since 1.0.0
def self.split_at_vertices( entities )
edges = entities.select { |e| e.is_a?( Sketchup::Edge ) }
vertices = edges.map { |edge| edge.vertices }
vertices.flatten!
vertices.uniq!
vector = Geom::Vector3d.new( 0, 0, 10.m )
end_vertices = []
temp_group = entities.add_group
for vertex in vertices
pt1 = vertex.position
pt2 = pt1.offset( vector )
temp_edge = temp_group.entities.add_line( pt1, pt2 )
end_vertices << temp_edge.end
end
temp_group.entities.transform_by_vectors( end_vertices, [vector.reverse] * end_vertices.size )
temp_group.explode
nil
end
# Return all instance that casts shadows.
#
# @note This method does not check parent path for visibility or shadow
# casting.
#
# @param [Sketchup::Entities] entities
#
# @return [Array<Sketchup::Group|Sketchup::ComponentInstance>]
# @since 1.0.0
def self.select_visible_instances( entities )
entities.select { |e|
TT::Instance.is?( e ) &&
e.casts_shadows? &&
( e.visible? && e.layer.visible? )
}
end
# @return [String] The current model time in a readable string.
# @since 1.0.0
def self.get_formatted_shadow_time
model = Sketchup.active_model
time = model.shadow_info['ShadowTime'].getutc
time.strftime( '%H:%M - %d %B' )
end
# Ensures there's a layer for the current shadow named based on the current
# model time. The layer will be visible to the current scene only.
#
# @return [Sketchup::Layer]
# @since 1.0.0
def self.get_shadow_layer
model = Sketchup.active_model
layername = "02 - #{self.get_formatted_shadow_time}"
unless layer = model.layers[ layername ]
layer = Sketchup.active_model.layers.add( layername )
layer.page_behavior = LAYER_IS_HIDDEN_ON_NEW_PAGES
model.pages.each { |page|
next if model.pages.selected_page == page
page.set_visibility( layer, false )
}
end
layer
end
# @param [Sketchup::Face] ground_face
# @param [Sketchup::Entities] entities
# @param [Numeric] footprint_area Size of area to be excluded.
#
# @return [Nil]
# @since 1.0.0
def self.calculate_shadow_statistics( ground_face, shadow_entities, footprint_area )
model = ground_face.model
entities = ground_face.parent.entities
# Calculate
site_area = ground_face.area # The whole site
ground_area = site_area - footprint_area # Site without building footprints
shadow_area = total_area( shadow_entities )
sun_area = ground_area - shadow_area
footprint_percent = ( footprint_area / site_area ) * 100.0
ground_percent = ( ground_area / site_area ) * 100.0
shadow_percent = ( shadow_area / ground_area ) * 100.0
sun_percent = ( sun_area / ground_area ) * 100.0
# Format
site_area = Sketchup.format_area( site_area )
ground_area = Sketchup.format_area( ground_area )
footprint_area = Sketchup.format_area( footprint_area )
shadow_area = Sketchup.format_area( shadow_area )
sun_area = Sketchup.format_area( sun_area )
footprint_percent = sprintf( "%.2f", footprint_percent )
ground_percent = sprintf( "%.2f", ground_percent )
shadow_percent = sprintf( "%.2f", shadow_percent )
sun_percent = sprintf( "%.2f", sun_percent )
# Output
output = <<-EOT.gsub(/^ {6}/, '')
Site Area: #{site_area}
Ground Area: #{ground_area} ( #{ground_percent}% of Site )
Footprint Area: #{footprint_area} ( #{footprint_percent}% of Site )
Sun Area: #{sun_area} ( #{sun_percent}% of Ground )
Shadow Area: #{shadow_area} ( #{shadow_percent}% of Ground )
EOT
while model.active_path
# If a note is added while not in root context it will shift about when
# oriting the view.
model.close_active
end
model.selection.clear
note = model.add_note( output, 0.4, 0.1 )
note.layer = self.get_shadow_layer
nil
end
# @param [Sketchup::Entities] entities
#
# @return [Numeric]
# @since 1.0.0
def self.total_area( entities )
area = 0.0
for face in entities
next unless face.is_a?( Sketchup::Face )
area += face.area
end
area
end
# @param [Sketchup::Entities] entities
#
# @return [Nil]
# @since 1.0.0
def self.merge_instances( entities )
for entity in entities.to_a
next unless TT::Instance.is?( entity )
entity.explode
end
self.remove_inner_faces( entities )
nil
end
# @param [Sketchup::Entities] entities
#
# @return [Nil]
# @since 1.0.0
def self.remove_inner_faces( entities )
inner_edges = []
for entity in entities
next unless entity.is_a?( Sketchup::Edge )
inner_edges << entity if entity.faces.size != 1
end
entities.erase_entities( inner_edges )
end
# @param [Sketchup::Face] face
# @param [Sketchup::Entities] entities
#
# @return [Sketchup::Group]
# @since 1.0.0
def self.create_trim_group( face, entities )
group = entities.add_group
for edge in face.edges
points = edge.vertices.map { |v| v.position }
group.entities.add_line( *points )
end
group
end
# @param [Sketchup::Edge] edge
#
# @return [Geom::Point3d]
# @since 1.0.0
def self.mid_point( edge )
pt1, pt2 = edge.vertices.map { |v| v.position }
mid = Geom.linear_combination( 0.5, pt1, 0.5, pt2 )
end
# @param [Sketchup::Edge] face
# @param [Sketchup::Entities] entities
# @param [Geom::Transformation] transformation
# @param [Sketchup::Group] trim_group
#
# @return [Nil]
# @since 1.0.0
def self.trim_to_face( face, entities, transformation, trim_group )
# Intersect with trim edges.
g = entities.add_instance( trim_group, transformation.inverse )
tr0 = Geom::Transformation.new
entities.intersect_with(
false, # (intersection lines will be put inside of groups and components within this entities object).
tr0, # The transformation for this entities object.
entities, # The entities object where you want the intersection lines to appear.
tr0, # The transformation for entities1.
false, # true if you want hidden geometry in this entities object to be used in the intersection.
g # A single entity, or an array of entities.
)
g.erase!
# Remove geometry that is outside the target.
outside = []
for edge in entities.to_a
next unless edge.is_a?( Sketchup::Edge )
pt = self.mid_point( edge )
result = face.classify_point( pt.transform(transformation) )
error = result == Sketchup::Face::PointUnknown
inside = result <= Sketchup::Face::PointOnEdge
# <debug>
# Visualize mid points which is checked to be inside the face.
# entities.add_cpoint( pt )
# entities.add_cpoint( pt.offset( Z_AXIS, 10.m ) ) if inside
# entities.add_cline( pt, pt.offset( Z_AXIS, 10.m ) )
# </debug>
next if inside
outside << edge
end
entities.erase_entities( outside )
nil
end
# @return [Sketchup::Material]
# @since 1.0.0
def self.get_shadow_material
model = Sketchup.active_model
m = model.materials[ SHADOWS_MATERIAL_NAME ]
unless m
m = model.materials.add( SHADOWS_MATERIAL_NAME )
m.color = SHADOWS_MATERIAL_COLOR
m.alpha = SHADOWS_MATERIAL_ALPHA
end
m
end
# @param [Sketchup::Edge] target_face
# @param [Sketchup::Group, Sketchup::ComponentInstance] instance
# @param [Geom::Vector3d] direction
#
# @return [Array<Sketchup::Group, Numeric>]
# @since 1.0.0
def self.shadows_from_entities( target_face, instance, direction, context )
# Source instance.
transformation = instance.transformation
definition = TT::Instance.definition( instance )
entities = definition.entities
# Entities collection containing the target face and where the shadows will
# be created.
#context = target_face.parent.entities
# Target
# Transform target plane and sun direction into the coordinates of the
# instance - this avoids transforming every 3D point in this mesh to the
# parent and should be faster.
to_local = transformation.inverse
target_normal = target_face.normal.transform( to_local )
plane = [target_face.vertices.first.position, target_face.normal]
target_plane = plane.map { |x| x.transform( to_local ) }
direction = direction.transform( to_local )
# Ground Polygons
# These are the faces we cast shaodows from on the target plane. These are
# used later to remove their footprint.
ground_area = 0.0
ground_polygons = entities.select { |e|
if e.is_a?( Sketchup::Face ) &&
e.normal.parallel?( target_normal ) &&
e.vertices.first.position.on_plane?( target_plane )
ground_area += e.area
true
else
false
end
}.map { |face| face.outer_loop.vertices.map { |v| v.position } }
# Group Meshes
# Each set of connected meshes are processed by them self to avoid
# unpredictable behaviour with overlapping shadows,
meshes = []
stack = entities.select { |e| e.respond_to?( :all_connected ) }
until stack.empty?
meshes << stack.first.all_connected
stack -= meshes.last
end
# Output Groups
# Destination groups with the faces representing the shadows.
shadows_group = context.add_group
shadows_group.transform!( transformation )
shadows_group.material = self.get_shadow_material
shadows = shadows_group.entities
# Project Shadows
# Find the edges outlined from the sun's position and project them to the
# target plane.
Sketchup.status_text = 'Projecting outlines...'
for mesh in meshes
shadow_group = shadows.add_group
shadow = shadow_group.entities
for edge in mesh
next unless edge.is_a?( Sketchup::Edge )
shadow_faces = edge.faces.select { |face| face.casts_shadows? }
next if shadow_faces.empty?
if shadow_faces.size > 1
dots = shadow_faces.map { |face| direction % face.normal < 0 }
next if dots.all? { |dot| dot == dots.first }
end
# Project outlines to target plane.
rays = edge.vertices.map { |v| [ v.position, direction ] }
points = rays.map { |ray| Geom.intersect_line_plane( ray, target_plane ) }
# <debug>
# Visualize projected rays onto target plane.
# for i in (0...rays.size)
# shadow.add_cline( rays[i][0], points[i] )
# shadow.add_cpoint( rays[i][0] )
# shadow.add_cpoint( points[i] )
# end
# </debug>
shadow.add_line( points )
end
end
# Create shadow faces.
Sketchup.status_text = 'Finding faces...'
for shadow in shadows
se = shadow.entities
# Intersect edges as the outline might be crossing itself.
tr = Geom::Transformation.new
se.intersect_with( false, tr, se, tr, true, se.to_a )
# Find all possible faces.
for edge in shadow.entities.to_a
next unless edge.is_a?( Sketchup::Edge )
edge.find_faces
end
# Clean up inner edges.
inner_edges = shadow.entities.select { |e|
e.is_a?( Sketchup::Edge ) && e.faces.size > 1
}
shadow.entities.erase_entities( inner_edges )
end
# Remove ground polygons.
Sketchup.status_text = 'Removing ground polygons...'
for shadow in shadows
se = shadow.entities
tr = Geom::Transformation.new
for polygon in ground_polygons
# Create a face representing the ground polygon and erase it.
face = se.add_face( polygon )
# If edges of the new face overlaps the shadow face it might not split
# at vertex intersections. Manually trigger merges for this.
# Group & Explore or Intersection does not work.
self.split_at_vertices( se )
# (?) Can face be invalid at this point due to the merge?
edges = face.edges
face.erase!
# Intersect and remove edges with midpoint inside the polygon.
se.intersect_with( false, tr, se, tr, true, edges )
redundant_edges = []
for edge in se.to_a
next unless edge.is_a?( Sketchup::Edge )
# Remove stray edges
if edge.faces.empty?
redundant_edges << edge
next
end
# Remove edges inside ground polygon.
pt1, pt2 = edge.vertices.map { |v| v.position }
mid = Geom.linear_combination( 0.5, pt1, 0.5, pt2 )
next unless Geom.point_in_polygon_2D( mid, polygon, false )
redundant_edges << edge
end
se.erase_entities( redundant_edges )
end
# Clean up more. Some times there are strange overlaps that intersect
# doesn't properly split.
self.split_at_vertices( se )
redundant_edges = []
for edge in se.to_a
next unless edge.is_a?( Sketchup::Edge )
next if edge.faces.size == 1
redundant_edges << edge
end
se.erase_entities( redundant_edges )
end # for
[ shadows_group, ground_area ]
end
### DEBUG ### ----------------------------------------------------------------
# @note Debug method to reload the plugin.
#
# @example
# TT::Plugins::ShadowCatcher.reload
#
# @since 1.0.0
def self.reload( tt_lib = false )
original_verbose = $VERBOSE
$VERBOSE = nil
load __FILE__
ensure
$VERBOSE = original_verbose
end
end # module
#-------------------------------------------------------------------------------
file_loaded( __FILE__ )
#-------------------------------------------------------------------------------
| true
|
5b6df45346e909df517e0b34abf2749fae6c385e
|
Ruby
|
shogo-tksk/at_coder
|
/abc153/recursive.rb
|
UTF-8
| 502
| 3.484375
| 3
|
[] |
no_license
|
# 基本的な再帰関数
def func(n)
# ベースケース
# ベースケースに対して return する処理を必ず入れる
return 0 if n == 0
# 再帰呼び出しを行ったときの問題が、元の問題よりも小さな問題となるように再帰呼び出しを行い、
# そのような「より小さい問題の系列」が最終的にベースケースに辿り着くようにする
n + func(n - 1)
end
(0..10).each do |n|
puts "#{n} までの和は #{func(n)}"
end
| true
|
ca23cd847a45cee0b2173b11f1fe799341a0a354
|
Ruby
|
cregg/slideshare-api
|
/lib/document_rater.rb
|
UTF-8
| 2,189
| 2.6875
| 3
|
[] |
no_license
|
require 'json'
class DocumentRater
@array_of_search_terms
@array_of_docs
@ranking_strategy
@key
def initialize(array_of_search_terms, array_of_docs, key, ranking_strategy)
@array_of_search_terms = array_of_search_terms
@array_of_docs = array_of_docs
@key = key
@ranking_strategy = ranking_strategy
end
def update_and_return_rating_array
ranked_docs = $redis[@key] != nil ? JSON.parse($redis[@key]) : []
tf_dash_idf = TFDashIDF.new(@array_of_search_terms, @array_of_docs.map{|doc| doc["Transcript"]})
docs_parsed = 0
@array_of_docs.each do |document|
rating = 0
document["found_terms"] = [];
@array_of_search_terms.each do |term|
rating += tf_dash_idf.get_term_score(document["ID"], document["Transcript"].downcase, term)
document["found_terms"].push(term) if document["Transcript"].include? term
end
document["rating"] = rating.nan? ? 0 : rating
#Let's remove the transcript before storing. The transcript's can be pretty big.
document["Transcript"] = ""
ranked_docs.push document
ranked_docs = ranked_docs.sort_by {|hash| hash["rating"] * -1}
docs_parsed += 1
$redis[@key + "_status"] = "Parsing Doc: " + docs_parsed.to_s + "/" + @array_of_docs.length.to_s
$redis[@key] = ranked_docs.to_json
end
ranked_docs
end
#Deprecated but holding on for fallback.
def update_and_return_rating_array_dep
ranked_docs = $redis[@key] != nil ? JSON.parse($redis[@key]) : []
byebug
tf_dash_idf = TFDashIDF.new(@array_of_search_terms, array_of_docs.map{|doc| doc["Description"]})
@array_of_docs.each do | document |
rating = @ranking_strategy.rank(document, @array_of_search_terms, @array_of_docs)
document["rating"] = rating
ranked_docs.push document
ranked_docs = ranked_docs.sort_by {|hash| hash["rating"] * -1}
$redis[@key] = ranked_docs.to_json
end
ranked_docs
end
end
| true
|
4d84186e2e20698e4c9a26054e5fa46172105e52
|
Ruby
|
jakenotjacob/ruby_basics
|
/compare_hashes.rb
|
UTF-8
| 484
| 3.65625
| 4
|
[] |
no_license
|
things = {
rock: 'heavy',
scissors: 'ok',
paper: 'light'
}
things.each do |thing, weight|
answer = weight.to_s == 'ok'
if answer == true
puts "The #{thing} fits!"
else
puts "We must aquit."
end
end
#!!!!!
#Bonus: Modify to use a conditional ("conditional expression")
#This will turn in the above code inside the blocks to...
#
#answer = 'ok'
#(weight == answer) ? (p "DAS TRU.") : ( p "AIN'T TRUE")
#
#=>i.e. - "if true... then do this... otherwise this..."#
| true
|
16727e45cc5b7bc04c29e72c6bcf3336ad39b41c
|
Ruby
|
emcooper/hashcards
|
/lib/round.rb
|
UTF-8
| 330
| 3.25
| 3
|
[] |
no_license
|
require 'pry'
class Round
attr_reader :deck, :guesses, :current_card
def initialize(deck)
@deck = deck
@guesses = []
@current_card = deck.cards.first
end
def record_guess(guess)
@guesses << Guess.new(guess, @current_card)
end
def number_correct
@guesses.count {|guess| guess.correct?}
end
end
| true
|
172ce1f5500415c05d85ec5a31502d8be737ed2c
|
Ruby
|
YujohnNattrass/ruby_small_problems
|
/easy1/sum_of_digits_2.rb
|
UTF-8
| 747
| 4.65625
| 5
|
[] |
no_license
|
=begin
input: Integer
output: new Integer
rules: returns the sum of adding all the individual digits in the integer
Data structure / Algorithm:
define method sum with 1 parameter variable num
split num into an array of individual digits
add digits together with sum method
=end
def sum(num)
num.digits.sum
end
puts sum(23) == 5
puts sum(496) == 19
puts sum(123_456_789) == 45
=begin
On lines 10 - 12 we define the method sum that takes in one parameter variable num
On line 11 we invoke #digits method on the local variable num to split the digits
in the integer to individual elements in an array.
We then invoke the #sum method on the return value array which add's all the
elements in the array and returns an Interger of the sum
=end
| true
|
902015113d9eed2f5159f981d97c3ffd0c59b992
|
Ruby
|
blevy115/ruby_fundamentals1
|
/exercise4-3.rb
|
UTF-8
| 167
| 3.625
| 4
|
[] |
no_license
|
my_name = "Brandon"
puts "What's your name?"
your_name = gets.chomp
if my_name == your_name
puts "We have the same name!"
else
puts "Our names are different!"
end
| true
|
dc052e1df49c50c16f7eb32dfe331e14d7a2b9fd
|
Ruby
|
Adrianjewell91/algo-work
|
/singlepointoffailure.rb
|
UTF-8
| 5,330
| 3.90625
| 4
|
[] |
no_license
|
require 'byebug'
def maximalSquare(matrix)
max = 0
squares = Hash.new(nil)
i = 0
while i < matrix.length
j = 0
length = 0
while j < matrix[i].length
if matrix[i][j] == '1'
length += 1
if max == 0
max = 1
else
# byebug
if squares[[i,j]]
squares[[i,j]].each do |square|
square[:indices] += 1
# byebug
if isComplete(square) && square[:length]**2 > max
max = square[:length]**2
else
if squares[nextIndex(square)]
squares[nextIndex(square)].push(square)
else
squares[nextIndex(square)] = [square]
end
end
end
squares[[i,j]] = Array.new()
end
if length > Math.sqrt(max)
new_length = length
while new_length > Math.sqrt(max)
new_square = Hash.new(nil)
new_square[:length] = new_length
new_square[:first] = [i,j-new_length+1]
new_square[:indices] = 0
column = j - new_length + 1
while column <= j
new_square[:indices] += 1
column += 1
end
if squares[nextIndex(new_square)]
squares[nextIndex(new_square)].push(new_square)
else
squares[nextIndex(new_square)] = [new_square]
end
new_length -= 1
end
end
end
else
length = 0
end
j += 1
end
i += 1
end
return max
end
def isComplete(square)
square[:indices] == square[:length]**2
end
def nextIndex(square)
return [square[:first][0] + (square[:indices]/square[:length]),
(square[:first][1] + (square[:indices] % square[:length]))]
end
# There is an O(n) solution:
# For each index that is a 1, log its relationships to the others around it, and if a 1 completes a square then log the new square's area if it's larger than the current one.
# I know i've found a square when and index is the corner stone of a square, and all of the square has been filled it.
# I've found a square when the last number is filled in a model of a square that I have started.
# For all other numbers, I know I'm adding to potential squares when the index is directly adjacent to other numbers.
# For each index with a 1, it either starts a new square or fits into an existing potential square.
# OFr each index of a 1 to the right of a 1, a new potential square starts of that length.
# So for each row, each index of 1 can start a new square, fill a role in a previous square or do both at the same time. Starting a new square can be done in two ways: a brand new length or expanding a previously start square with a previous intended length.
# So for each index that is a 1, the options are:
# If the max is zero, then set the max = 1, because a single index of 1 is a square with area 1.
# else:
# Iterate through all previously started squares (length >= 2) and see if it fits into any of them.
# Start a new square.
#
# Naive solution is to try to build a square at each index, and store the largest one found yet.
# For each idnex that is 1 do a search and down and try to build a square.
# How to represent a square, a collection of indices, a hash of areas, and area is an array of possible squares with the indices as the options, if any of these are all true then a square is completed, and all of the hashes with that area can be deleted.
# [{[0,0]: true [0,1]: true, [1,0]: false, [1,1]:false}, {...}, {...}]
#
# ARe there any other ways? Is this really more efficient? YEs, because it's a single iteration through the matrix, and then an iteration through previous started squares, but the number of iterations will descrease as larger squares are found, for example there will be no point in starting a new 4 area square when the max is already 4, only 9 area squares will be started or kept.
# How to assign a value to a potential square: at that area, for each hash, check is the current index is in the area, if it is, assign it, and then check if all of the values are checked, if so, then the square is complete, and this is the new max.
# [10, 3, 0, 5, 10, 0, 5, 0, 8, 10, 8, 13, 3, 3, 2]
#
# saved 5
# next_idx 5
# new_root 0
if $PROGRAM_NAME == __FILE__
p maximalSquare(
[["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]])
end
| true
|
a4d802dac21ce2140b7a58a857a60d350726be88
|
Ruby
|
timomitchel/black_thursday
|
/lib/invoice_repository.rb
|
UTF-8
| 1,246
| 2.859375
| 3
|
[] |
no_license
|
require_relative 'invoice'
require 'csv'
class InvoiceRepository
attr_reader :data, :parent
def initialize(data, parent)
@data = csv_load(data).map {|row| Invoice.new(row, self)}
@parent = parent
end
def csv_load(file_path)
CSV.open file_path, headers: true, header_converters: :symbol
end
def all
@data
end
def find_invoice_item_by_invoice_id(id)
parent.find_invoice_item_by_invoice_id(id)
end
def find_transaction_by_invoice_id(id)
parent.find_transaction_by_invoice_id(id)
end
def find_customer_by_invoice_id(id)
parent.find_customer_by_invoice_id(id)
end
def find_item_by_invoice_id(id)
parent.find_item_by_invoice_id(id)
end
def find_merchant_by_invoice(merchant)
parent.find_merchant_by_invoice(merchant)
end
def find_by_id(invoice_id)
data.find {|invoice|invoice.id.to_i == invoice_id}
end
def find_all_by_customer_id(customer)
data.select {|invoice| invoice.customer_id.to_i == customer}
end
def find_all_by_merchant_id(merchant)
data.select {|invoice| invoice.merchant_id.to_i == merchant}
end
def find_all_by_status(stats)
data.select {|invoice| invoice.status == stats}
end
def inspect
"#{self.class}"
end
end
| true
|
9b1704b631527ac011131412a545776703b3085b
|
Ruby
|
Sigill/OggAlbumTagger
|
/lib/ogg_album_tagger/library.rb
|
UTF-8
| 19,037
| 3.203125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'ogg_album_tagger/version'
require 'ogg_album_tagger/tag_container'
require 'ogg_album_tagger/exceptions'
require 'set'
require 'fileutils'
require 'colorize'
module OggAlbumTagger
# A Library is just a hash associating each ogg file to a TagContainer.
# A subset of file can be selected in order to be tagged.
class Library
attr_reader :path
attr_reader :selected_files
# Build a Library from a list of TagContainer.
#
# dir:: The name of the directory supposed to contain all the files. Pass any name if the
# tracks of that library are related, +nil+ otherwise.
# containers:: A hash mapping the files to the containers.
def initialize dir, tracks
@path = dir
@files = tracks.map { |e| e }
@selected_files = @files.slice(0, @files.size).to_set
end
# Return the number of files in this library.
def size
@files.size
end
# Returns the list of the tags used in the selected files.
def tags_used
s = Set.new
@selected_files.each do |file|
s.merge file.tags
end
s.to_a.map { |v| v.downcase }
end
# Returns an hash of hashes describing the selected files for the specified tag.
#
# If no tag is specified, all tags are considered.
#
# The first hash is indexed by the tags used. The second level of hashes is indexed
# by the positions of the files in the library and points to a alphabetically sorted list
# of values associated to the tag.
#
# {
# 'TITLE' => {
# 0 => ['Title of track 0'],
# 3 => ['Title of track 3']
# },
# ...
# }
def summary(selected_tag = nil)
data = Hash.new { |h, k| h[k] = Hash.new }
@files.each_with_index { |file, i|
next unless @selected_files.include? file
file.each do |tag, values|
next unless selected_tag.nil? or tag.eql?(selected_tag)
data[tag][i] = values.sort
end
}
data
end
# Returns a hash where keys are the positions of the files in the library
# and values are sorted lists of values associated to the tag.
def tag_summary(tag)
summary(tag)[tag]
end
# Pick from the selected files one single value associated to the specified tag.
def first_value(tag)
tag_summary(tag).first[1].first
end
# Write the tags to the files.
def write
@selected_files.each do |file|
file.write(file.path)
end
end
# Tags the selected files with the specified values.
#
# Any previous value will be removed.
def set_tag(tag, *values)
tag.upcase!
@selected_files.each { |file| file.set_values(tag, *values) }
self
end
# Tags the selected files with the specified values.
def add_tag(tag, *values)
tag.upcase!
@selected_files.each { |file| file.add_values(tag, *values) }
self
end
# Remove the specified values from the selected files.
#
# If no value is specified, the tag will be removed.
def rm_tag(tag, *values)
tag.upcase!
@selected_files.each { |file| file.rm_values(tag, *values) }
self
end
# Rename a tag.
def mv_tag(from_tag, to_tag)
from_tag.upcase!
to_tag.upcase!
@selected_files.each { |file| file.mv_tag(from_tag, to_tag) }
self
end
# Return a list of the files in the library.
def ls
@files.each_with_index.map do |file, i|
{ file: (@path.nil? ? file.path : file.path.relative_path_from(@path)).to_s, selected: @selected_files.include?(file) }
end
end
# Build a Set representing the selected files specified by the selectors.
#
# The available selector are:
# * "all": all files.
# * "3": the third file.
# * "5-7": the files 5, 6 and 7.
#
# The two last selector can be prefixed by "+" or "-" in order to add or remove items
# from the current selection. They are called cumulative selectors.
#
# Non-cumulative selectors cannot be specified after a cumulative one.
def build_selection(selectors)
return @selected_files if selectors.empty?
mode = :absolute
first_rel = !!(selectors.first =~ /^[+-]/)
sel = first_rel ? Set.new(@selected_files) : Set.new
selectors.each do |selector|
case selector
when 'all'
raise OggAlbumTagger::ArgumentError, "Cannot use the \"#{selector}\" selector after a cumulative selector (+/-...)" if mode == :cumulative
sel.replace @files
when /^([+-]?)([1-9]\d*)$/
i = $2.to_i - 1
raise OggAlbumTagger::ArgumentError, "Item #{$2} is out of range" if i >= @files.size
items = [@files.slice(i)]
case $1
when '-'
sel.subtract items
mode = :cumulative
when '+'
sel.merge items
mode = :cumulative
else
raise OggAlbumTagger::ArgumentError, "Cannot use the \"#{selector}\" selector after a cumulative selector (+/-...)" if mode == :cumulative
sel.merge items
end
when /^([+-]?)(?:([1-9]\d*)-([1-9]\d*))$/
i = $2.to_i - 1
j = $3.to_i - 1
raise OggAlbumTagger::ArgumentError, "Range #{$2}-#{$3} is invalid" if i >= @files.size or j >= @files.size or i > j
items = @files.slice(i..j)
case $1
when '-'
sel.subtract items
mode = :cumulative
when '+'
sel.merge items
mode = :cumulative
else
raise OggAlbumTagger::ArgumentError, "Cannot use the \"#{selector}\" selector after a cumulative selector (+/-...)" if mode == :cumulative
sel.merge items
end
else
raise OggAlbumTagger::ArgumentError, "Unknown selector \"#{selector}\"."
end
end
return sel
end
# Modify the list of selected files.
def select(args)
@selected_files.replace(build_selection(args))
return self
end
def with_selection(selectors)
begin
previous_selection = Set.new(@selected_files)
@selected_files = build_selection(selectors)
yield
ensure
@selected_files = previous_selection
end
end
def move(from, to)
raise ::IndexError, "Invalid from index #{from}" unless (0...@files.size).include?(from)
raise ::IndexError, "Invalid to index #{to}" unless (0..@files.size).include?(to)
# Moving item N before item N does nothing
# Just like moving item N before item N+1
return if to == from or to == from + 1
item = @files.delete_at(from)
@files.insert(from < to ? to - 1 : to, item)
end
# Automatically set the TRACKNUMBER tag of the selected files based on their position in the selection.
def auto_tracknumber
i = 0
@files.each { |file|
next unless @selected_files.include? file
file.set_values('TRACKNUMBER', (i+1).to_s)
i += 1
}
end
# Test if a tag satisfy a predicate on each selected files.
def validate_tag(tag)
values = @selected_files.map { |file| file[tag] }
values.reduce(true) { |r, v| r && yield(v) }
end
# Test if a tag is used at least one time in an ogg file.
def tag_used?(tag)
values = @selected_files.map { |file| file[tag] }
values.reduce(false) { |r, v| r || v.size > 0 }
end
# Test if a tag is used k times on each selected files.
def tag_used_k_times?(tag, k)
self.validate_tag(tag) { |v| v.size == k }
end
# Test if a tag is used once on each selected files.
def tag_used_once?(tag)
self.tag_used_k_times?(tag, 1)
end
# Test if at least one of the files has multiple values for the specified tag..
def tag_used_multiple_times?(tag)
values = @selected_files.map { |file| file[tag] }
values.reduce(false) { |r, v| r || (v.size > 1) }
end
# Test if a tag is absent from each selected files.
def tag_unused?(tag)
self.tag_used_k_times?(tag, 0)
end
# Test if multiple tags satisfy a predicate.
def validate_tags(tags)
tags.reduce(true) { |result, tag| result && yield(tag) }
end
# Test if a tag has a single value and is uniq across all selected files.
def uniq_tag?(tag)
values = @selected_files.map { |file| file[tag] }
values.reduce(true) { |r, v| r && (v.size == 1) } && (values.map { |v| v.first }.uniq.length == 1)
end
# Test if a tag holds a numerical value > 0.
def numeric_tag?(tag)
validate_tag(tag) { |v| (v.size == 0) || (v.first.to_s =~ /^[1-9][0-9]*$/) }
end
# TODO ISO 8601 compliance (http://www.cl.cam.ac.uk/~mgk25/iso-time.html)
def date_tag?(tag)
validate_tag(tag) { |v| (v.size == 0) || (v.first.to_s =~ /^\d\d\d\d$/) }
end
# Verify that the library is properly tagged.
#
# * ARTIST, TITLE and DATE must be used once per file.
# * TRACKNUMBER must be used once on an album/compilation.
# * DATE must be a valid date.
# * ALBUM must be uniq.
# * ALBUMARTIST should have the value "Various artists" on a compilation.
# * ALBUMDATE must be unique. It is not required if DATE is unique.
# * DISCNUMBER must be used at most one time per file.
# * TRACKNUMBER and DISCNUMBER must have numerical values.
def check
# Catch all the tags that cannot have multiple values.
%w{ARTIST TITLE DATE ALBUM ALBUMDATE ARTISTALBUM TRACKNUMBER DISCNUMBER}.each do |t|
raise OggAlbumTagger::MetadataError, "The #{t} tag must not appear more than once per track." if tag_used_multiple_times?(t)
end
%w{DISCNUMBER TRACKNUMBER}.each do |t|
raise OggAlbumTagger::MetadataError, "If used, the #{t} tag must have a numeric value." unless numeric_tag?(t)
end
%w{DATE ALBUMDATE}.each do |t|
raise OggAlbumTagger::MetadataError, "If used, the #{t} tag must be a valid year." unless date_tag?(t)
end
once_tags = %w{ARTIST TITLE DATE}
once_tags << "TRACKNUMBER" unless @path.nil?
once_tags.each do |t|
raise OggAlbumTagger::MetadataError, "The #{t} tag must be used once per track." unless tag_used_once?(t)
end
return if @path.nil?
raise OggAlbumTagger::MetadataError, "The ALBUM tag must have a single and unique value among all songs." unless uniq_tag?('ALBUM')
if tag_used?('ALBUMDATE')
unless uniq_tag?('ALBUMDATE')
raise OggAlbumTagger::MetadataError, "The ALBUMDATE tag must have a single and unique value among all songs."
end
if uniq_tag?('DATE') && first_value('DATE') == first_value('ALBUMDATE')
raise OggAlbumTagger::MetadataError, "The ALBUMDATE tag is not required since it is unique and identical to the DATE tag."
end
else
unless uniq_tag?('DATE')
raise OggAlbumTagger::MetadataError, "The ALBUMDATE tag is required."
end
end
if @selected_files.size == 1
raise OggAlbumTagger::MetadataError, 'This album has only one track. The consistency of some tags cannot be verified.'
end
if uniq_tag?('ARTIST')
if tag_used?('ALBUMARTIST')
raise OggAlbumTagger::MetadataError, 'The ALBUMARTIST is not required since all tracks have the same and unique ARTIST.'
end
else
if not uniq_tag?('ALBUMARTIST') or (first_value('ALBUMARTIST') != 'Various artists')
raise OggAlbumTagger::MetadataError, 'This album seems to be a compilation. The ALBUMARTIST tag should have the value "Various artists".'
end
end
end
def short_path(file)
@path.nil? ? file : file.relative_path_from(@path)
end
# Auto rename the directory and the ogg files of the library.
#
# For singles, the format is:
# Directory: N/A
# Ogg file: ARTIST - DATE - TITLE
#
# For an album, the format is:
# Directory: ARTIST - DATE - ALBUM
# Ogg file: ARTIST - DATE - ALBUM - [DISCNUMBER.]TRACKNUMBER - TITLE
#
# For a single-artist compilation (an album where tracks have different dates), the format is:
# Directory: ARTIST - ALBUMDATE - ALBUM
# Ogg file: ARTIST - ALBUMDATE - ALBUM - [DISCNUMBER.]TRACKNUMBER - TITLE - DATE
#
# For a compilation, the format is:
# Directory: ALBUM - ALBUMDATE|DATE
# Ogg file: ALBUM - ALBUMDATE|DATE - [DISCNUMBER.]TRACKNUMBER - ARTIST - TITLE - DATE
#
# Disc and track numbers are padded with zeros.
def compute_rename_fields
dir_fields = nil
file_fields = nil
if @path.nil?
file_fields = %w{artist date title}
else
if uniq_tag?('ARTIST')
if uniq_tag?('DATE')
file_fields = %w{artist albumdate album index title}
else
file_fields = %w{artist albumdate album index title date}
end
dir_fields = %w{artist albumdate album}
else
file_fields = %w{album albumdate index artist title date}
dir_fields = %w{album albumdate}
end
end
return dir_fields, file_fields
end
def get_index_formatter
tn_maxlength = tag_summary('TRACKNUMBER').values.map { |v| v.first.to_s.length }.max
tn_format = '%0' + tn_maxlength.to_s + 'd'
has_discnumber = tag_used_once?('DISCNUMBER')
if has_discnumber
dn_maxlength = tag_summary('DISCNUMBER').values.map { |v| v.first.to_s.length }.max
dn_format = '%0' + dn_maxlength.to_s + 'd'
end
return lambda do |tags|
s = ''
if has_discnumber
s += sprintf(dn_format, tags.first('DISCNUMBER').to_i) + '.'
end
s += sprintf(tn_format, tags.first('TRACKNUMBER').to_i)
end
end
def test_mapping_uniq(mapping)
if mapping.values.uniq.size != @selected_files.size
raise OggAlbumTagger::MetadataError, 'Generated filenames are not unique.'
end
end
def compute_rename_mapping(dir_fields, file_fields)
newpath = nil
mapping = {}
# TODO Should UTF-8 chars be converted to latin1 in order to have Windows-safe filenames?
cleanup_for_filename = Proc.new { |v| v.gsub(/[\\\/:*?"<>|]/, ' ').gsub(/\s+/, ' ').strip() }
unless @path.nil?
index_formatter = get_index_formatter()
albumdate = tag_used?('ALBUMDATE') ? first_value('ALBUMDATE') : first_value('DATE')
end
@selected_files.each { |file|
fields = {
'artist' => file.first('ARTIST'),
'title' => file.first('TITLE'),
'date' => file.first('DATE')
}
unless @path.nil?
fields['album'] = file.first('ALBUM')
fields['index'] = index_formatter.call(file)
fields['albumdate'] = albumdate
end
mapping[file] = file_fields.map { |e| cleanup_for_filename.call(fields[e]) }.join(' - ') + '.ogg'
}
unless @path.nil?
fields = {
'artist' => first_value('ARTIST'),
'album' => first_value('ALBUM'),
'albumdate' => albumdate
}
albumdir = dir_fields.map { |e| cleanup_for_filename.call(fields[e]) }.join(' - ')
newpath = @path.dirname.join(albumdir).cleanpath
end
return newpath, mapping
end
def print_mapping(dir_fields, file_fields, newpath, mapping)
unless @path.nil?
puts "Directory format: ".colorize(:blue) + (dir_fields.nil? ? 'N/A' : dir_fields.join(' - '))
puts "- " + @path.to_s.colorize(:red)
puts "+ " + newpath.to_s.colorize(:green)
end
puts "File format: ".colorize(:blue) + file_fields.join(' - ') + '.ogg'
Set.new(@selected_files).each { |file|
puts "- " + short_path(file.path).to_s.colorize(:red)
puts "+ " + mapping[file].to_s.colorize(:green)
}
end
def try_rename(dir_fields_opt, file_fields_opt)
check()
dir_fields, file_fields = compute_rename_fields()
dir_fields = dir_fields_opt unless dir_fields_opt.nil?
file_fields = file_fields_opt unless file_fields_opt.nil?
newpath, mapping = compute_rename_mapping(dir_fields, file_fields)
print_mapping(dir_fields, file_fields, newpath, mapping)
test_mapping_uniq(mapping)
end
def auto_rename(dir_fields_opt, file_fields_opt)
check()
dir_fields, file_fields = compute_rename_fields()
dir_fields = dir_fields_opt unless dir_fields_opt.nil?
file_fields = file_fields_opt unless file_fields_opt.nil?
newpath, mapping = compute_rename_mapping(dir_fields, file_fields)
test_mapping_uniq(mapping)
# Renaming the ogg files
Set.new(@selected_files).each do |file|
begin
oldfilepath = file.path
newfilepath = (@path.nil? ? oldfilepath.dirname : @path).join(mapping[file]).cleanpath
# Don't rename anything if there's no change.
if oldfilepath != newfilepath
rename(oldfilepath, newfilepath)
file.path = newfilepath
end
rescue Exception
raise OggAlbumTagger::SystemError, "Cannot rename \"#{short_path(oldfilepath)}\" to \"#{short_path(newfilepath)}\"."
end
end
# Renaming the album directory
unless @path.nil?
oldpath = @path
begin
# Don't rename anything if there's no change.
if @path != newpath
rename(@path, newpath)
@path = newpath
@files.each { |file|
newfilepath = newpath + file.path.relative_path_from(oldpath)
file.path = newfilepath
}
end
rescue Exception
raise OggAlbumTagger::SystemError, "Cannot rename \"#{oldpath}\" to \"#{newpath}\"."
end
end
end
def rename(oldpath, newpath)
FileUtils.mv(oldpath, newpath)
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.