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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
652256d25960740bcaa47ba4063e4f1774b3d80f | Ruby | theo-browne/W4D4 | /poker/spec/deck_spec.rb | UTF-8 | 393 | 2.671875 | 3 | [] | no_license | require "rspec"
require "deck"
RSpec.describe Deck do
describe "Deck::all_cards"
it "should generate a deck of 52 cards" do
expect(Deck.all_cards.uniq.length).to eq(52)
end
describe "Deck#initialize" do
let(:deck) { Deck.new }
it "should set instance variable, @cards, to represent the deck of cards" do
expect(deck.cards.count).to eq(52)
end
end
end | true |
b781d5f60ccbadb97dc0b8c75463464769e2995b | Ruby | h4hany/yeet-the-leet | /algorithms/Medium/1343.number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.rb | UTF-8 | 1,570 | 3.59375 | 4 | [] | no_license | #
# @lc app=leetcode id=1343 lang=ruby
#
# [1343] Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
#
# https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/description/
#
# algorithms
# Medium (64.20%)
# Total Accepted: 11.6K
# Total Submissions: 18.1K
# Testcase Example: '[2,2,2,2,5,5,5,8]\n3\n4'
#
# Given an array of integers arr and two integers k and threshold.
#
# Return the number of sub-arrays of size k and average greater than or equal
# to threshold.
#
#
# Example 1:
#
#
# Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
# Output: 3
# Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6
# respectively. All other sub-arrays of size 3 have averages less than 4 (the
# threshold).
#
#
# Example 2:
#
#
# Input: arr = [1,1,1,1,1], k = 1, threshold = 0
# Output: 5
#
#
# Example 3:
#
#
# Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
# Output: 6
# Explanation: The first 6 sub-arrays of size 3 have averages greater than 5.
# Note that averages are not integers.
#
#
# Example 4:
#
#
# Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
# Output: 1
#
#
# Example 5:
#
#
# Input: arr = [4,4,4,4], k = 4, threshold = 1
# Output: 1
#
#
#
# Constraints:
#
#
# 1 <= arr.length <= 10^5
# 1 <= arr[i] <= 10^4
# 1 <= k <= arr.length
# 0 <= threshold <= 10^4
#
#
# @param {Integer[]} arr
# @param {Integer} k
# @param {Integer} threshold
# @return {Integer}
def num_of_subarrays(arr, k, threshold)
end
| true |
9a03e760620182dd8e5380299f184deb701ead26 | Ruby | ensons/beacon | /lib/beacon/states/three.rb | UTF-8 | 405 | 2.71875 | 3 | [
"MIT"
] | permissive | module Beacon
module States
# Wait 3 intervals.
class Three
def call
blink
wait
next_state
end
private
def blink
Leds.blink! 3
end
def wait
Log.debug { "Waiting because I'll retry in 30 seconds" }
Sleep.call Beacon.config.delay
end
def next_state
States::Two
end
end
end
end
| true |
1ed0aff6da2eed117190a1bf5f08f1390723ad99 | Ruby | roomorama/concierge | /apps/web/middlewares/health_check.rb | UTF-8 | 1,447 | 2.5625 | 3 | [] | no_license | require_relative "../../../lib/concierge/json"
require_relative "../../../lib/concierge/version"
module Web
module Middlewares
# +Web::Middlewares::HealthCheck+
#
# Implements a simple endpoint for health checking, necessary for the load
# balancer to determine if the server is healthy.
#
# Requests coming to the +/_ping+ endpoint will always return a +200+ success
# status, with a small JSON response with the current timestamp.
class HealthCheck
include Concierge::JSON
attr_reader :app, :env
HEALTH_CHECK_PATH = "/_ping"
def initialize(app)
@app = app
end
def call(env)
@env = env
if health_check?
response = {
status: "ok",
app: "web",
time: Time.now.strftime("%Y-%m-%d %T %Z"),
version: Concierge::VERSION
}
[200, { "Content-Type" => "application/json" }, [json_encode(response)]]
else
app.call(env)
end
end
private
def health_check?
request_path == [namespace, HEALTH_CHECK_PATH].join
end
def namespace
case Hanami.env
when "development"
"/web"
else
""
end
end
def request_path
env["REQUEST_PATH"] || env["PATH_INFO"]
end
def query_string
env["QUERY_STRING"]
end
end
end
end
| true |
24609ee94099296c60ce744fb99c1f8f9b7ad468 | Ruby | jslabovitz/photo-utils | /lib/photo-utils/values/aperture.rb | UTF-8 | 766 | 3.015625 | 3 | [] | no_license | module PhotoUtils
class ApertureValue < Value
APEX_LABEL = 'Av'
def self.parse(s)
case s.strip
when %r{^(f/?)?([\d\.]+)$}i
new($2.to_f)
when %r{^US\s+([\d\.]+)$}i
new_from_us_stop($1.to_f)
else
raise ValueParseError, "Can't parse #{s.inspect} as aperture value"
end
end
def self.new_from_v(v)
new(Math.sqrt(2 ** v.to_f))
end
def self.new_from_us_stop(us)
new_from_v(Math.log2(us) + 4)
end
def to_v
Math.log2(to_f ** 2)
end
def succ
self.class.new_from_v(to_v + 1)
end
def string
'f/%s' % float_string
end
def us_string
'US %s' % us_stop.round
end
def us_stop
2 ** (to_v - 4)
end
end
end | true |
5bbbc602cdbe5f9e08712ba4c7e461ea4133a5c9 | Ruby | nemilya/ruby-todo-demo | /app.rb | UTF-8 | 5,781 | 2.59375 | 3 | [
"MIT"
] | permissive | # Простое ToDo приложение на базе Ruby/Sinatra/DataMapper
#
# [github][src], [демо][demo]
#
# [src]: https://github.com/nemilya/ruby-todo-demo
# [demo]: http://ruby-todo-demo.cloudfoundry.com
# подключение Sinatra и DataMapper библиотек
require "rubygems"
require "sinatra"
require 'dm-core'
require 'dm-migrations'
# Таблица
# <pre>
# todos
# * id [integer]
# * todo [string]
# * is_done [boolean]
# </pre>
class Todos
include DataMapper::Resource
property :id, Serial, :key => true
property :todo, String
property :is_done, Boolean, :default=>false
end
# для тестовых задач - настраиваем на БД Sqlite3
conn_string = "sqlite3://#{Dir.pwd}/todos.db"
# при выкладывании на CloudFoundry (там приложение автоматически запускается в режиме `production`,
# и подключённом сервисе MySQL
# необходимо проинициализировать данные доступа к БД
# `ENV['VCAP_SERVICES']` - переменная окружения проинициализированная CloudFoundry сервисом
configure :production do
if ENV['VCAP_SERVICES']
require "json"
mysql_service = JSON.parse(ENV['VCAP_SERVICES'])['mysql-5.1'].first
dbname = mysql_service['credentials']['name']
username = mysql_service['credentials']['username']
password = mysql_service['credentials']['password']
host = mysql_service['credentials']['host']
port = mysql_service['credentials']['port']
conn_string = "mysql://#{username}:#{password}@#{host}:#{port}/#{dbname}"
end
end
# инициализируем DataMapper на адаптер Базы Данных:
DataMapper.setup(:default, conn_string)
# обработка модели:
DataMapper.finalize
# автоматическая миграция, если изменились поля в модели:
DataMapper.auto_upgrade!
# набор "функций-хелперов" добавляем хелпер "h" для автоматического преобразования html в безопасный для отображения html:
helpers do
def h(html_test)
Rack::Utils.escape_html(html_test)
end
end
# отображение страницы:
get "/" do
@todos = Todos.all(:is_done => false, :order => [:id.desc])
@done_todos = Todos.all(:is_done => true, :order => [:id.desc])
erb :index
end
# обработка на нажатие `[Кнопка Добавить]` - добавление пункта, передаётся `'text'`:
post "/add" do
todo = Todos.new(:todo => params[:text])
todo.save
redirect "/"
end
# обработка на нажатие `[Кнопка Выполнены]` - отметка о выполнении, передаётся массив `'ids[]'`:
post "/done" do
if params[:ids]
params[:ids].each do |todo_id|
Todos.get(todo_id).update(:is_done => true)
end
end
redirect "/"
end
# обработка на нажатие `[Кнопка Архивировать]` - удаление всех выполненных todo пунктов:
post "/archive" do
Todos.all(:is_done => true).destroy
redirect "/"
end
# в Sinatra возможно встраивать шаблоны в программу,
# окончание программы определяется по `__END__`
# далее идут шаблоны, название шаблона указывается после `@@`
__END__
#
# шаблоны отображения:
#
# `layout` - внешний шаблон,
#
# `index` - главная страница.
#
# согласно постановке:
# <pre>
# h1. Простое ToDo приложение
#
# h2. Актуальные
#
# [текстовое поле] [Кнопка Добавить]
#
# // список todo пунктов, снизу вверх (по id)
# [checkbox] [текст todo1]
# [checkbox] [текст todo2]
# ...
# [Кнопка Выполнены]
#
# h2. Выполненные
#
# // список выполненных todo пунктов,
# // с сортировкой снизу вверх (по id)
# // визуально перечёркнуты
# [текст done-todo1]
# [текст done-todo2]
# ...
# [Кнопка Архивировать]
# </pre>
@@layout
<!DOCTYPE html>
<html>
<head>
<title>Ruby ToTo Demo App</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Простое ToDo приложение</h1>
<%= yield %>
<br />
<small>
github:
<a href="https://github.com/nemilya/ruby-todo-demo">исходны код</a> |
<a href="https://github.com/nemilya/ruby-todo-demo/blob/master/spec.ru.md">постановка</a> |
<a href="http://nemilya.github.com/ruby-todo-demo/app.html">описание</a>
</small>
</body>
</html>
@@index
<h2>Актуальные</h2>
<form action="/add" method="post">
<input type="text" name="text">
<input type="submit" value="Добавить">
</form>
<br />
<% if @todos.size > 0 %>
<form action="/done" method="post">
<% @todos.each do |todo| %>
<input type="checkbox" name="ids[]" value="<%= todo.id %>"> <%= h todo.todo %><br />
<% end %>
<br />
<input type="submit" value="Выполнены">
</form>
<% end %>
<% if @done_todos.size > 0 %>
<h2>Выполненные</h2>
<form action="/archive" method="post">
<% @done_todos.each do |todo| %>
<del><%= h todo.todo %></del><br />
<% end %>
<br />
<input type="submit" value="Архивировать">
</form>
<% end %> | true |
c371dcb4256185dabc6484a731f297d2ed98d16d | Ruby | lambsubstitute/new-test-webdriver | /Features/support/page_objects/login_po.rb | UTF-8 | 760 | 2.5625 | 3 | [] | no_license | # encoding: utf-8
# class documentation
class LoginPo
include PageInitializer
# Container identifier
LOGIN_DIV_ID = 'login-panel'
# Element identifiers
USERNAME_INPUT_ID = 'username'
PASSWORD_INPUT_ID = 'password'
SUBMIT_INPUT_ID = 'login'
def get_login_div
@browser.div(:id, LOGIN_DIV_ID).wait_until_present
@browser.div(:id, LOGIN_DIV_ID)
end
def enter_username(username)
login_panel = get_login_div
login_panel.text_field(:id, USERNAME_INPUT_ID).set(username)
end
def enter_password(password)
login_panel = get_login_div
login_panel.text_field(:id, PASSWORD_INPUT_ID).set(password)
end
def click_login
login_panel = get_login_div
login_panel.button(:id, SUBMIT_INPUT_ID).click
end
end
| true |
764c2ed7d73fbbe5fd825acfdf0f16aa3049963f | Ruby | m-chrzan/aoc2020 | /08/a.rb | UTF-8 | 439 | 3.203125 | 3 | [] | no_license | code = []
File.readlines('input.txt').each do |line|
instruction, number = line.split
code.push [instruction, number.to_i]
end
visited = {}
current_line = 0
acc = 0
while !visited[current_line]
visited[current_line] = true
case code[current_line][0]
when 'nop'
current_line += 1
when 'acc'
acc += code[current_line][1]
current_line += 1
when 'jmp'
current_line += code[current_line][1]
end
end
puts acc
| true |
1faf19b2285ea89bfbb58c958fb0fd61eb2153ac | Ruby | justindelatorre/itpwr | /flow_control/flow_control-3.rb | UTF-8 | 581 | 4.09375 | 4 | [] | no_license | =begin
Write a program that takes a number from
the user between 0 and 100 and reports
back whether the number is between 0 and
50, 51 and 100, or above 100.
=end
puts "Please select a number between 0 and 100."
# Convert input String into an Integer
num = gets.chomp.to_i
case
when num < 0
puts "You can't submit a negative number."
when num <= 50
puts "Your number is between 0 and 50."
when num >= 51 && num <= 100
puts "Your number is between 51 and 100."
when num > 100
puts "Your number is greater than 100."
else
puts "I don't know what to do about your number."
end
| true |
07f3c5a37c7653a3eeb4c35efc094ad12728fc80 | Ruby | TiffanyChio/betsy | /test/models/orderitem_test.rb | UTF-8 | 4,842 | 2.65625 | 3 | [] | no_license | require "test_helper"
describe Orderitem do
let(:new_orderitem) {
Orderitem.new(
quantity: 1,
product: products(:stella),
order: orders(:order1),
shipped: false
)
}
describe "validation" do
it "can instantiate a valid orderitem" do
expect(new_orderitem.save).must_equal true
end
it "has all required fields" do
new_orderitem.save
orderitem = Orderitem.last
[:quantity, :product_id, :order_id].each do |field|
expect(orderitem).must_respond_to field
end
end
it "cannot create an orderitem with no quantity" do
new_orderitem.quantity = nil
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "can't be blank"
end
it "cannot create an orderitem with negative quantity" do
new_orderitem.quantity = -9
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "must be greater than 0"
end
it "cannot create an orderitem with quantity = 0" do
new_orderitem.quantity = 0
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "must be greater than 0"
end
it "cannot create an orderitem with a non-numeric quantity" do
new_orderitem.quantity = "nine"
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "is not a number"
end
it "cannot create an orderitem with a non-integer quantity" do
new_orderitem.quantity = 0.999999
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "must be an integer"
end
it "cannot create an orderitem with an invalid product" do
new_orderitem.product_id = -1
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :product
expect(new_orderitem.errors.messages[:product]).must_include "must exist"
end
it "cannot create an orderitem with an invalid order" do
new_orderitem.order_id = -1
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :order
expect(new_orderitem.errors.messages[:order]).must_include "must exist"
end
it "cannot create an orderitem with quantity greater than stock available" do
new_orderitem.quantity = 10
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :quantity
expect(new_orderitem.errors.messages[:quantity]).must_include "order exceeds inventory in stock"
end
it "cannot create an orderitem from a retired product" do
products(:stella).update(retired: true)
expect(products(:stella).retired).must_equal true
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :product_id
expect(new_orderitem.errors.messages[:product_id]).must_include "Stella Artois is no longer available"
end
it "can create an orderitem with shipped status false" do
new_orderitem.shipped = false
new_orderitem.save
expect(new_orderitem.valid?).must_equal true
end
it "cannot create an orderitem with shipped status nil" do
new_orderitem.shipped = nil
new_orderitem.save
expect(new_orderitem.valid?).must_equal false
expect(new_orderitem.errors.messages).must_include :shipped
expect(new_orderitem.errors.messages[:shipped]).must_include "shipped status must be a boolean value: true or false"
end
end
describe "relationships" do
it "belongs to a product" do
new_orderitem.save!
expect(new_orderitem.product_id).must_equal products(:stella).id
expect(new_orderitem.product).must_equal products(:stella)
end
it "belongs to an order" do
new_orderitem.save!
expect(new_orderitem.order_id).must_equal orders(:order1).id
expect(new_orderitem.order).must_equal orders(:order1)
end
end
describe "custom methods" do
describe "subtotal" do
it "can calculate the correct subtotal" do
expect(orderitems(:heineken_oi).subtotal).must_be_close_to 22.22
end
end
end
end
| true |
b449e7d188b06aa67391bfa39d7d79c239adfd4a | Ruby | tatianabespalko/tatianabespalko.github.io | /tasks/mkdev/lesson_05/movies.rb | UTF-8 | 1,266 | 3.125 | 3 | [] | no_license | require 'csv'
require 'ostruct'
require 'date'
require_relative './movies_col.rb'
class Movie
attr_accessor :link, :name, :year, :country, :release_date, :genre, :length, :rating, :director, :actors, :collection, :month, :release_year
def initialize (film_collection, film)
film.each { |k,v| instance_variable_set("@#{k}", v) }
@collection = film_collection
@genre = @genre.to_s.split(",")
@actors = @actors.to_s.split(",")
@release_year = @release_date.to_s[0..3].to_i
end
def inspect
format("| %50s | %10s | %12s | %27s | %7s | %3s | %23s | %s", "#{@name}", "#{@release_date}", "#{@country}", "#{@genre}", "#{@length}", "#{@rating}", "#{@director}", "#{@actors}\n")
end
def year
@release_year
end
def month
if @release_date.to_s[6..7] != nil
@month = Date.strptime(@release_date, "%Y-%m").strftime("%B")
end
end
def match? (filter_name, filter_value)
if send(filter_name).is_a?(Array)
send(filter_name).any? { |val| filter_value === val }
else
filter_value === send(filter_name)
end
end
def has_genre? (genre)
raise ArgumentError, "Genre \"#{genre}\" do not exist in collection" unless @collection.genre_exist?(genre)
@genre.include?(genre)
end
end
| true |
7ec03b688992703b4fa6525b170017fa8e751a6d | Ruby | igrigorik/em-proxy | /examples/balancing.rb | UTF-8 | 5,188 | 3.0625 | 3 | [
"MIT"
] | permissive | $:<< '../lib' << 'lib'
require 'em-proxy'
require 'ansi/code'
require 'uri'
# = Balancing Proxy
#
# A simple example of a balancing, reverse/forward proxy such as Nginx or HAProxy.
#
# Given a list of backends, it's able to distribute requests to backends
# via different strategies (_random_, _roundrobin_, _balanced_), see <tt>Backend.select</tt>.
#
# This example is provided for didactic purposes. Nevertheless, based on some preliminary benchmarks
# and live tests, it performs well in production usage.
#
# You can customize the behaviour of the proxy by changing the <tt>BalancingProxy::Callbacks</tt>
# callbacks. To give you some ideas:
#
# * Store statistics for the proxy load in Redis (eg.: <tt>$redis.incr "proxy>backends>#{backend}>total"</tt>)
# * Use Redis' _SortedSet_ instead of updating the <tt>Backend.list</tt> hash to allow for polling from external process
# * Use <b>em-websocket</b>[https://github.com/igrigorik/em-websocket] to build a web frontend for monitoring
#
module BalancingProxy
extend self
BACKENDS = [
{:url => "http://0.0.0.0:3000"},
{:url => "http://0.0.0.0:3001"},
{:url => "http://0.0.0.0:3002"}
]
# Represents a "backend", ie. the endpoint for the proxy.
#
# This could be eg. a WEBrick webserver (see below), so the proxy server works as a _reverse_ proxy.
# But it could also be a proxy server, so the proxy server works as a _forward_ proxy.
#
class Backend
attr_reader :url, :host, :port
attr_accessor :load
alias :to_s :url
def initialize(options={})
raise ArgumentError, "Please provide a :url and :load" unless options[:url]
@url = options[:url]
@load = options[:load] || 0
parsed = URI.parse(@url)
@host, @port = parsed.host, parsed.port
end
# Select backend: balanced, round-robin or random
#
def self.select(strategy = :balanced)
@strategy = strategy.to_sym
case @strategy
when :balanced
pp [list, list.sort_by { |b| b.load }.first]
backend = list.sort_by { |b| b.load }.first
when :roundrobin
@pool = list.clone if @pool.nil? || @pool.empty?
backend = @pool.shift
when :random
backend = list[ rand(list.size-1) ]
else
raise ArgumentError, "Unknown strategy: #{@strategy}"
end
Callbacks.on_select.call(backend)
yield backend if block_given?
backend
end
# List of backends
#
def self.list
@list ||= BACKENDS.map { |backend| new backend }
end
# Return balancing strategy
#
def self.strategy
@strategy
end
# Increment "currently serving requests" counter
#
def increment_counter
self.load += 1
end
# Decrement "currently serving requests" counter
#
def decrement_counter
self.load -= 1
end
end
# Callbacks for em-proxy events
#
module Callbacks
include ANSI::Code
extend self
def on_select
lambda do |backend|
puts black_on_white { 'on_select'.ljust(12) } + " #{backend.inspect}"
backend.increment_counter if Backend.strategy == :balanced
end
end
def on_connect
lambda do |backend|
puts black_on_magenta { 'on_connect'.ljust(12) } + ' ' + bold { backend }
end
end
def on_data
lambda do |data|
puts black_on_yellow { 'on_data'.ljust(12) }, data
data
end
end
def on_response
lambda do |backend, resp|
puts black_on_green { 'on_response'.ljust(12) } + " from #{backend}", resp
resp
end
end
def on_finish
lambda do |backend|
puts black_on_cyan { 'on_finish'.ljust(12) } + " for #{backend}", ''
backend.decrement_counter if Backend.strategy == :balanced
end
end
end
# Wrapping the proxy server
#
module Server
def run(host='0.0.0.0', port=9999)
puts ANSI::Code.bold { "Launching proxy at #{host}:#{port}...\n" }
Proxy.start(:host => host, :port => port, :debug => false) do |conn|
Backend.select do |backend|
conn.server backend, :host => backend.host, :port => backend.port
conn.on_connect &Callbacks.on_connect
conn.on_data &Callbacks.on_data
conn.on_response &Callbacks.on_response
conn.on_finish &Callbacks.on_finish
end
end
end
module_function :run
end
end
if __FILE__ == $0
require 'rack'
class Proxy
def self.stop
puts "Terminating ProxyServer"
EventMachine.stop
$servers.each do |pid|
puts "Terminating webserver #{pid}"
Process.kill('KILL', pid)
end
end
end
# Simple Rack app to run
app = proc { |env| [ 200, {'Content-Type' => 'text/plain'}, ["Hello World!"] ] }
# Run app on ports 3000-3002
$servers = []
3.times do |i|
$servers << Process.fork { Rack::Handler::WEBrick.run(app, {:Host => "0.0.0.0", :Port => "300#{i}"}) }
end
puts ANSI::Code::green_on_black { "\n=> Send multiple requests to the proxy by running `ruby balancing-client.rb`\n" }
# Start proxy
BalancingProxy::Server.run
end
| true |
12fd14b3492b4212065a7ca11fbdad695743afa9 | Ruby | fhmurakami/cookbook-campuscode | /db/seeds.rb | UTF-8 | 1,127 | 2.546875 | 3 | [] | no_license | user = User.create(name: 'Teste', email: 'teste@email.com', password: '123456', city: 'São Paulo', admin: false)
admin = User.create(name: 'Admin', email: 'admin@email.com', password: '123456', city: 'São Paulo', admin: true)
RecipeType.create(name: 'Sobremesa')
RecipeType.create(name: 'Entrada')
Cuisine.create(name: 'Portuguesa')
brazilian_cuisine = Cuisine.create(name: 'Brasileira')
italian_cuisine = Cuisine.create(name: 'Italiana')
recipe_type = RecipeType.create(name: 'Prato Principal')
Recipe.create(title: 'Feijoada', recipe_type: recipe_type,
cuisine: brazilian_cuisine,
difficulty: 'Médio', cook_time: 120,
ingredients: 'Feijão e carnes.',
cook_method: 'Misturar o feijão com as carnes.',
featured: true, user: user)
Recipe.create(title: 'Macarronada', recipe_type: recipe_type,
cuisine: italian_cuisine,
difficulty: 'Fácil', cook_time: 30,
ingredients: 'Macarrão e molho de tomate',
cook_method: 'Cozinhar o macarrão e misturar com o molho.',
featured: false, user: user)
| true |
36314042e8dbbffb100e4f878a0def2e244ae1d2 | Ruby | mick-thumvilai/Lovemac_IntroToIce_Final | /lib/lovemac.rb | UTF-8 | 256 | 3.515625 | 4 | [] | no_license | #Siwat Thumvilai 5631378321
def lovemac(number)
if number%3 == 0 and number%5 ==0
return "HateWindows"
elsif number%3 == 0
return "Love"
elsif number%5 == 0
return "Mac"
else
return number
end
end
(1..50).each do |number|
puts lovemac(number)
end | true |
c6eb6dc8a45b94f180895f6001eb8fcc858dacd1 | Ruby | GratefulGarmentProject/StockAid | /spec/models/item_spec.rb | UTF-8 | 2,533 | 2.578125 | 3 | [
"MIT"
] | permissive | require "rails_helper"
describe Item do
describe ".for_category" do
it "returns items for_category" do
category = categories(:flip_flops)
expect(Item.unscoped.where(category_id: category.id).count).to eq(4)
flip_flop_items = Item.for_category(category.id)
expect(flip_flop_items.count).to eq(3)
end
it "returns all items if no category is given exists" do
expect(Item.count).to eq(6)
expect(Item.for_category(nil).count).to eq(6)
end
end
describe ".program_ratio_split_for" do
let(:item) { items(:large_flip_flops) }
let(:resource_closets) { programs(:resource_closets) }
let(:pack_it_forward) { programs(:pack_it_forward) }
let(:dress_for_dignity) { programs(:dress_for_dignity) }
let(:beautification_projects) { programs(:beautification_projects) }
it "splits evenly if all programs are included" do
ratios = item.program_ratio_split_for([resource_closets, pack_it_forward, dress_for_dignity])
expect(ratios[resource_closets]).to eq(0.5)
expect(ratios[pack_it_forward]).to eq(0.25)
expect(ratios[dress_for_dignity]).to eq(0.25)
end
it "doesn't include split for programs not part of the ratios" do
ratios = item.program_ratio_split_for([resource_closets, pack_it_forward, dress_for_dignity, beautification_projects])
expect(ratios).to have_key(resource_closets)
expect(ratios).to have_key(pack_it_forward)
expect(ratios).to have_key(dress_for_dignity)
expect(ratios).to_not have_key(beautification_projects)
end
it "adjusts split when programs are missing" do
ratios = item.program_ratio_split_for([pack_it_forward, dress_for_dignity])
expect(ratios).to_not have_key(resource_closets)
expect(ratios[pack_it_forward]).to eq(0.5)
expect(ratios[dress_for_dignity]).to eq(0.5)
ratios = item.program_ratio_split_for([resource_closets, pack_it_forward])
expect(ratios).to_not have_key(dress_for_dignity)
expect(ratios[resource_closets]).to be_within(0.0000000001).of(2 / 3.0)
expect(ratios[pack_it_forward]).to be_within(0.0000000001).of(1 / 3.0)
end
it "uses the ratios as is if none of the programs are included" do
ratios = item.program_ratio_split_for([beautification_projects])
expect(ratios).to_not have_key(beautification_projects)
expect(ratios[resource_closets]).to eq(0.5)
expect(ratios[pack_it_forward]).to eq(0.25)
expect(ratios[dress_for_dignity]).to eq(0.25)
end
end
end
| true |
75f30c6b05563a9e7825d8cb06ae9a3af9d6bc6c | Ruby | mateforlife/cryptodo | /lib/requester/coinmarketcap.rb | UTF-8 | 342 | 2.5625 | 3 | [] | no_license | module Requester
class Coinmarketcap
include HTTParty
base_uri 'https://api.coinmarketcap.com/v1/ticker'
def initialize(coin_name, convert)
@response = self.class.get("/#{coin_name}/?convert=#{convert}", format: :plain)
end
def parsed_response
JSON.parse(@response, symbolize_names: true)
end
end
end | true |
1cd8294de9f8fe45e5b1d38399269155cdbfc531 | Ruby | D0947506/opencspm | /docker/app/jobs/lib/fetcher/types/local_fetcher.rb | UTF-8 | 968 | 2.53125 | 3 | [
"MIT"
] | permissive | # frozen-string-literal: true
class LocalFetcher
def initialize(local_dirs, load_dir)
@local_dirs = local_dirs
@load_dir = load_dir
end
def fetch
puts @local_dirs
# Enumerate **/*manifest.txt and /*manifest.txt
@local_dirs.each do |local_dir|
dirs = Dir["#{local_dir}/*/*manifest.txt"] + Dir["#{local_dir}/*manifest.txt"]
dirs.each do |manifest_file|
manifest_base_dir = File.dirname(manifest_file)
cai_files = []
begin
File.readlines(manifest_file).each do |cai_file|
source_file_path = "#{manifest_base_dir}/#{cai_file}".chomp
file_data = File.read(source_file_path)
dest_file_path = "#{@load_dir}/combined_for_load.json"
puts "Appending #{source_file_path} to #{dest_file_path}"
File.write(dest_file_path, file_data, mode: "ab")
end
rescue => e
puts e.inspect
end
end
end
end
end
| true |
d148108bf137852c9f5d45be13e1a077f696df30 | Ruby | ryanmillergm/code_challenge | /app/models/street_cafe.rb | UTF-8 | 763 | 2.78125 | 3 | [] | no_license | class StreetCafe < ApplicationRecord
validates_presence_of :restaurant_name,
:street_address,
:post_code,
:number_of_chairs
def self.cafes_by_size(*size)
if size.count == 1
where("category LIKE ?", "%#{size[0]}")
elsif size.count == 2
where("category LIKE ?", "%#{size[0]}").or(where("category LIKE ?", "%#{size[1]}"))
# where("category LIKE '%#{size[0]}' OR category LIKE '%#{size[1]}'")
else
raise ArgumentError, "Wrong number of arguments. Expecting 1-2."
end
end
def self.concatenate_cafes(cafes)
cafes.map do |cafe|
name = cafe.category + ' ' + cafe.restaurant_name
cafe.update!(restaurant_name: name)
end
end
end
| true |
1028214ef782ddcf5e554a3a62488c5bdac1faca | Ruby | cloudwow/rdesk | /lib/rdesk/project/auto_build.rb | UTF-8 | 1,761 | 2.546875 | 3 | [] | no_license |
class Project
def initialize(name,root_dir,source_dirs,build_command,error_regexes)
@name=name
@root_dir=root_dir
@source_dirs=source_dirs
@build_command=build_command
@error_regexes=error_regexes
@last_build_time=Time.now
end
def is_modified?
@source_dirs.each do |src_dir|
path=File.join(@root_dir,src_dir)
return true if is_directory_modified?(path)
end
false
end
def is_directory_modified?(dir)
Dir.entries(dir).each do |entry|
next if entry=="." || entry==".."
path=File.join(dir,entry)
if File.stat(path).directory?
return true if is_directory_modified?(path)
else
return true if is_file_modified?(path)
end
end
false
end
def is_file_modified?(path)
if File.stat(path).mtime>@last_build_time
puts "&&&&&&&&&&&&& modified file: #{path}"
return true
end
return false
end
def build
Dir.chdir(@root_dir) do
IO.popen(@build_command+" 2>&1") do |pipe|
while line=pipe.gets
@error_regexes.each do |err_regex|
if err_regex.match(line)
puts "********"+line
end
end
end
end
end
@last_build_time=Time.now
end
end
# p=Project.new("GC",
# "/Users/david/workspace/davidknight/GlobalCoordinate2",
# ["app","lib","config","test"],
# "rake test",
# [/error/] )
# while true
# if p.is_modified?
# p.build
# end
# sleep 3
# end
| true |
268a37fa72858dee28ab29704f10c44bf70cba71 | Ruby | ejdelsztejn/order_up | /app/models/chef.rb | UTF-8 | 394 | 2.78125 | 3 | [] | no_license | class Chef <ApplicationRecord
validates_presence_of :name
has_many :dishes
def most_popular_ingredients
ingredient_count = Hash.new(0)
self.dishes.each do |dish|
dish.ingredients.each do |ingredient|
ingredient_count[ingredient.name] += 1
end
end
ingredient_count.sort_by{ |ingredient, count| count }.last(3).map{|ingredient| ingredient[0]}
end
end
| true |
fccadaaf47c8465be1ec4f9fcad2e06d1e9e99c0 | Ruby | mcousin/tippspiel | /spec/models/matchday_spec.rb | UTF-8 | 5,124 | 2.53125 | 3 | [] | no_license | require 'spec_helper'
describe Matchday do
context "associations" do
it { should belong_to(:league) }
it { should have_many(:matches).dependent(:destroy) }
end
context "method start" do
subject { FactoryGirl.build(:matchday) }
context "should have a default start if it has no matches" do
its(:start) { should eq DateTime.new(2222)}
end
context "returning the beginning of the first of its matches, if any" do
before { subject.matches = [ FactoryGirl.build(:match, match_date: 1.day.from_now),
@match = FactoryGirl.build(:match, match_date: 1.day.ago),
FactoryGirl.build(:match, match_date: 2.days.from_now)] }
its(:start) { should eq @match.match_date }
end
end
context "comparing matchdays" do
let (:early_matchday) { FactoryGirl.build(:matchday) }
let (:late_matchday) { FactoryGirl.build(:matchday) }
before { early_matchday.stubs(:start).returns(2.days.ago) }
before { late_matchday.stubs(:start).returns(1.day.ago) }
specify { (early_matchday <=> late_matchday).should eq(-1) }
specify { [late_matchday, early_matchday].sort.should eq([early_matchday, late_matchday]) }
end
context "method has_started?" do
subject { FactoryGirl.build(:matchday) }
context "for a started match" do
before { subject.stubs(:start).returns(1.day.ago) }
it { should have_started }
end
context "for a future match" do
before { subject.stubs(:start).returns(1.day.from_now) }
it { should_not have_started }
end
end
context "method complete?" do
subject { FactoryGirl.build(:matchday) }
context "should return true if it has no matches" do
it { should be_complete }
end
context "all of its matches have ended" do
before { subject.matches = [FactoryGirl.build(:match, match_date: 1.day.ago, has_ended: true),
FactoryGirl.build(:match, match_date: 2.days.ago, has_ended: true)] }
it { should be_complete }
end
context "should return false if it has a match that has not ended yet" do
before { subject.matches = [FactoryGirl.build(:match, match_date: 1.day.ago, has_ended: true),
FactoryGirl.build(:match, match_date: 1.day.from_now, has_ended: false)] }
it { should_not be_complete }
end
end
context "Matchday.next_to_bet" do
subject { Matchday.next_to_bet }
context "returning the matchday that contains the next match" do
before { FactoryGirl.create(:match, match_date: 1.day.ago) }
before { @match = FactoryGirl.create(:match, match_date: 1.day.from_now) }
before { FactoryGirl.create(:match, match_date: 2.days.from_now) }
it { should eq @match.matchday }
end
context "Match.next returns nil" do
before { Match.stubs(:next).returns(nil) }
it { should be_nil }
end
end
context "methods last_complete and first_incomplete" do
before { @match1 = FactoryGirl.create(:match, match_date: 3.days.ago, has_ended: true) }
before { @match2 = FactoryGirl.create(:match, match_date: 2.day.ago, has_ended: false) }
before { @match3 = FactoryGirl.create(:match, match_date: 1.days.ago, has_ended: true) }
before { @match4 = FactoryGirl.create(:match, match_date: 1.day.from_now, has_ended: false) }
specify { Matchday.last_complete.should eq @match3.matchday }
specify { Matchday.first_incomplete.should eq @match2.matchday }
context "no complete matchday" do
before { Matchday.any_instance.stubs(:complete?).returns(false) }
specify { Matchday.last_complete.should be_nil }
specify { Matchday.first_incomplete.should eq @match1.matchday }
end
context "no incomplete matchday" do
before { Matchday.any_instance.stubs(:complete?).returns(true) }
specify { Matchday.last_complete.should eq @match4.matchday }
specify { Matchday.first_incomplete.should be_nil }
end
end
context "Matchday.current" do
subject { Matchday.current }
let(:mocked_matchday) { mock("matchday") }
context "should return the matchday that next to bet, if any" do
before { Matchday.stubs(:next_to_bet).returns(mocked_matchday) }
it { should eq mocked_matchday }
end
context "should return the first incomplete matchday if there are no matches to bet" do
before { Matchday.stubs(:next_to_bet).returns(nil) }
before { Matchday.stubs(:first_incomplete).returns(mocked_matchday) }
it { should eq mocked_matchday }
end
context "should return the last complete matchday if there are no matches to bet and no incomplete matchdays" do
before { Matchday.stubs(:next_to_bet).returns(nil) }
before { Matchday.stubs(:first_incomplete).returns(nil) }
before { Matchday.stubs(:last_complete).returns(mocked_matchday) }
it { should eq mocked_matchday }
end
context "should return nil if no matchdays exist" do
it { should be_nil }
end
end
end
| true |
e4001b6a436c849651f63a4ff910ac3ef7042394 | Ruby | ryanatwork/google-civic | /lib/google-civic.rb | UTF-8 | 555 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'google-civic/client'
module GoogleCivic
class << self
# Alias for GoogleCivic::Client.new
#
# @return [GoogleCivic::Client]
def new(options={})
GoogleCivic::Client.new(options)
end
# Delegate to GoogleCivic::Client.new
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method, include_private=false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
end
| true |
aafe92292ae5155a4edb2801b322acf01d3e5611 | Ruby | fuchsto/aurita | /lib/aurita/modules/gui/lang.rb | UTF-8 | 2,865 | 2.59375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
require('yaml')
class Language_Pack
def initialize(pack, params={})
@lang = params[:lang].to_sym
@plugin = params[:plugin].to_sym
@pack = pack
end
def [](symbol)
s = @pack[@plugin][@lang][symbol] if @pack[@plugin] && @pack[@plugin][@lang]
return s if s
s = @pack[:main][@lang][symbol] if symbol != :main
return s if s
return s.to_s
end
end
class Lang
@@language_packs = { :main => { :de => YAML::load(File::open(Aurita::Application.base_path+'main/lang/de.yaml')),
:en => YAML::load(File::open(Aurita::Application.base_path+'main/lang/en.yaml'))
}
}
def self.add_plugin_language_pack(plugin_name)
yaml_path = Aurita::App_Configuration.plugins_path + plugin_name + '/lang/'
if !File.exists?(yaml_path) then
yaml_path = Aurita::App_Configuration.plugins_path + plugin_name + '/lib/lang/'
end
plugin_name = plugin_name.downcase.to_sym
@@language_packs[plugin_name] = {}
Aurita.log { "Searching for plugin language packs in #{yaml_path}" }
Dir.glob(yaml_path + '*.yaml').each { |f|
Aurita.log { "Adding plugin language pack #{f}" }
lang = f.split('/').at(-1).gsub('.yaml','').to_sym
pack = (YAML::load(File::open(f)))
@@language_packs[plugin_name][lang] = pack unless @@language_packs[plugin_name][lang]
@@language_packs[plugin_name][lang].update(pack) if @@language_packs[plugin_name][lang]
}
end
def self.add_project_language_pack(plugin_name)
yaml_path = "#{Aurita.project.base_path}lang/#{plugin_name}/"
plugin_name = plugin_name.downcase.to_sym
@@language_packs[plugin_name] = {} unless @@language_packs[plugin_name]
Dir.glob(yaml_path + '*.yaml').each { |f|
Aurita.log { "Adding project language pack #{f}" }
lang = f.split('/').at(-1).gsub('.yaml','').to_sym
pack = (YAML::load(File::open(f)))
if @@language_packs[plugin_name][lang]
@@language_packs[plugin_name][lang].update(pack)
else
@@language_packs[plugin_name][lang] = pack
end
}
end
def self.get(plugin, symbol)
plugin = plugin.to_sym
symbol = symbol.to_s
lang = Aurita.session.language.to_sym
if !@@language_packs[plugin] || !@@language_packs[plugin][lang] then
error = 'Missing language pack: Plugin ' << plugin.inspect + ', language ' << lang.inspect + "\n"
raise ::Exception.new(error)
end
s = @@language_packs[plugin.to_sym][lang][symbol]
return s if s
s = @@language_packs[:main][lang][symbol]
return s if s
return plugin.to_s + '__' + symbol.to_s
end
def self.[](plugin_name)
return Language_Pack.new(@@language_packs,
:lang => Aurita.session.language,
:plugin => plugin_name)
end
end
| true |
8680c7f6a028aebe20adaba49ce431925ca66acd | Ruby | Elian1978/ruby_training | /1_strings.rb | UTF-8 | 284 | 3.71875 | 4 | [] | no_license | a= "Esto es un lindo string"
b = "Otro string"
#En ruby casi todo es un objeto
puts a.length
puts b.length
#string de multiples lineas
c ='Esto es\nun string\nde multiples lineas'
puts c
age = 42
#Interpolacion de variables solo funciona con comillas dobles
puts "Mi edad es, #{age} " | true |
df9e89c18e1421b53a5de670612b7e49e21bb752 | Ruby | gustavokath/advent-of-code-2020 | /18B/main.rb | UTF-8 | 361 | 3.09375 | 3 | [] | no_license | sum = 0
$stdin.each_line do |line|
expression = line.strip.split(' ')
sum_idx = []
expression.each_with_index do |v, idx|
sum_idx.push idx if v == '+'
end
sum_idx.each do |idx|
expression[idx-1] = "(#{expression[idx-1]}"
expression[idx+1] = "#{expression[idx+1]})"
end
value = eval(expression.join(' '))
sum += value
end
p sum
| true |
a24b5de450f43db99565f78931395e86359356c5 | Ruby | vannak1/ttt-with-ai-project-v-000 | /lib/game.rb | UTF-8 | 895 | 3.4375 | 3 | [] | no_license | class Game
include GameStatus::InstanceMethods
attr_accessor :board, :player_1, :player_2
def initialize(player_1 = Player::Human.new("X"), player_2 = Player::Human.new("O"), board = Board.new)
@player_1 = player_1
@player_2 = player_2
@board = board
end
def turn
player = current_player
current_move = player.move(@board)
if !board.valid_move?(current_move)
turn
else
puts "Move ##{self.board.turn_count+1}"
self.board.display
self.board.update(current_move, player)
puts "#{player.token} moved #{current_move}"
self.board.display
end
end
def current_player
self.board.turn_count % 2 == 0 ? self.player_1 : self.player_2
end
def play
while !over?
self.turn
end
if won?
puts "Congratulations #{self.winner}!"
elsif draw?
puts "Cats Game!"
end
end
end | true |
6327b6eb968c3ee939da90c3341baeddc5a23114 | Ruby | fukuiretu/ruboty-todoist | /example/example.rb | UTF-8 | 799 | 2.546875 | 3 | [
"MIT"
] | permissive | require "open-uri"
require "pp"
require "json"
require 'time'
require 'dotenv'
Dotenv.load
API_URL = "https://todoist.com/API/v6"
# params = { token: TOKEN }
# request_url = "#{API_URL}/get_all_completed_items?#{URI.encode_www_form(params)}"
params = { token: ENV["TODOIST_TOKEN"], seq_no: 0, resource_types: '["all"]' }
request_url = "#{API_URL}/sync/?#{URI.encode_www_form(params)}"
res = open(request_url)
code, message = res.status
pp code
pp message
result = JSON.parse(res.read)
result["Items"].each do |item|
# プロジェクト指定
if item["project_id"] == 144157733
pp item
pp Time.strptime(item["due_date"], "%a %d %b %Y %T") unless item["due_date"].nil?
# 今日のタスク
# if true
# end
end
end
# result["Projects"].each do |item|
# pp item
# end
| true |
e1131524b60d4b8153093ca80bdca41da7277d4c | Ruby | taratip/chillow | /lib/occupant.rb | UTF-8 | 156 | 3.140625 | 3 | [] | no_license | class Occupant
attr_reader :first_name, :last_name
def initialize(firstname, lastname)
@first_name = firstname
@last_name = lastname
end
end
| true |
e32e5b0b9c3b4e87e702810acdbec0bcb38634f5 | Ruby | Elenkanee/ita | /hw_23/lib/script_23_01.rb | UTF-8 | 654 | 2.875 | 3 | [] | no_license | # ========================================================================
# Script = __FILE__
# ========================================================================
# Description = "This is a description of the script"
# Name = "Your Name"
# Email = "your@email.com"
# ========================================================================
require 'optparse'
require 'json'
OptionParser.new do |opts|
opts.on("-i", "--input") do
$file_name = ARGV[0]
end
end.parse!
json_file = File.read($file_name)
element = JSON.parse(json_file)
puts "My favorite fruits are #{element["fruit_a"] }s and #{ element["fruit_b"] }s" | true |
6a5002112a8a8a9995ce44437a80bd1182478e1d | Ruby | monorkin/FER-RASUS | /first_assignment/Klijent/client.rb | UTF-8 | 7,964 | 2.75 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
require 'socket'
require 'securerandom'
require 'net/http'
require 'singleton'
require 'csv'
require 'json'
require 'logger'
LOGGER = Logger.new(STDOUT)
$stdout.sync = true
class Reading
ATTRIBUTES = %i[temperature pressure humidity co no2 so2].freeze
attr_reader :data
attr_reader :row
attr_reader :time_alive
attr_reader :temperature
attr_reader :pressure
attr_reader :humidity
attr_reader :co
attr_reader :no2
attr_reader :so2
def initialize(data, row, time_alive)
@row = row
@time_alive = time_alive
@data = data || []
@temperature = self.data[0]
@pressure = self.data[1]
@humidity = self.data[2]
@co = self.data[3]
@no2 = self.data[4]
@so2 = self.data[5]
end
def inspect
"#<#{self.class}:#{object_id} "\
"row: #{row} "\
"time_alive: #{time_alive} "\
"data: #{data.inspect}>"
end
def to_s
inspect
end
def to_json
{
row: row,
time_alive: time_alive,
data: data
}.to_json
end
def |(other)
data =
ATTRIBUTES.map do |attr|
(other&.send(attr) || send(attr) || 0)
end
self.class.new(
data,
row,
time_alive
)
end
def %(other)
return dup unless other
data =
ATTRIBUTES.map do |attr|
((other&.send(attr) || 0) + (send(attr) || 0)) / 2
end
self.class.new(
data,
row,
time_alive
)
end
end
class Service
def self.call(*args)
new(*args).call
end
end
class ReadingGenerator < Service
attr_reader :data_source
attr_reader :time
def initialize(data_source, time = nil)
@data_source = data_source
@time = time || Time.now
end
def call
t = alive_time
r = row(t)
Reading.new(table[r], r, t)
end
private
def table
@table ||= CSV.read(data_source, converters: :numeric)
end
def row(time)
(time % 100) + 2
end
def alive_time
Time.now.to_i - time.to_i
end
end
module HTTPClient
DEFAULT_HEADERS = {
'Content-Type' => 'application/json'
}.freeze
def ipv4_address
Socket.ip_address_list.find do |ai|
ai.ipv4? && !ai.ipv4_loopback?
end.ip_address
end
def register(sensor)
payload = {
'username' => sensor.username,
'latitude' => sensor.latitude,
'longitude' => sensor.longitude,
'IPaddress' => ipv4_address,
'port' => sensor.server.port
}.to_json
url = "#{ENV['SERVER_HOST']}/register"
response = Net::HTTP.post(URI(url), payload, DEFAULT_HEADERS)
JSON.parse(response.body)
end
def nearest_neighbour(sensor)
payload = {
'username' => sensor.username
}
params = URI.encode_www_form(payload)
url = "#{ENV['SERVER_HOST']}/searchNeighbour?#{params}"
response = Net::HTTP.get(URI(url))
JSON.parse(response)
end
def store_measurments(reading, sensor)
results = Reading::ATTRIBUTES.map do |attr|
store_measurment(attr, reading, sensor)
end
Reading::ATTRIBUTES.zip(results).to_h
end
def store_measurment(attribute, reading, sensor)
return false unless reading.send(attribute)
payload = {
'username' => sensor.username,
'parameter' => attribute,
'averageValue' => reading.send(attribute)
}.to_json
url = "#{ENV['SERVER_HOST']}/storeMeasurments"
response = Net::HTTP.post(URI(url), payload, DEFAULT_HEADERS)
JSON.parse(response.body)
end
extend self
end
class SocketRegistry
include Singleton
attr_accessor :store
def [](addr)
@store ||= {}
sock = @store[addr]
if sock.nil? || sock&.closed?
LOGGER.debug("Creating new socket for '#{addr}'")
uri = URI("tcp://#{addr}")
@store[addr] = TCPSocket.new(uri.host, uri.port)
@store[addr]
else
sock
end
end
def []=(addr, sock)
@store ||= {}
@store[addr] = sock
sock
end
def register(sock)
info = sock.addr
addr = "#{info[-1]}:#{info[1]}"
self[addr] = sock
end
end
class RequestProcessor < Service
attr_reader :socket
attr_reader :sensor
attr_reader :request
def initialize(socket, sensor)
@socket = socket
@sensor = sensor
end
def call
loop do
@request = JSON.parse(socket.gets)
case method
when 'requestMeasurment' then send_reading
when 'terminateConnection' then terminate_connection
else log_error("unknown method '#{method}'")
end
end
rescue => e
log_error(e)
ensure
socket.close
end
protected
def method
request['method']
end
def args
request['args']
end
private
def send_reading
reading = sensor.reading
LOGGER.info "Generated reading #{reading} for '#{args&.first}'"
socket.puts reading.to_json
end
def terminate_connection
LOGGER.info "Terminating connection to #{socket.addr}"
socket.close
end
def log_error(error)
LOGGER.error "ERROR WHILE PROCESSING REQUEST: #{error} - #{error.class}"
end
end
class Server
HOST = '0.0.0.0'
attr_reader :port
attr_reader :sensor
attr_reader :tcp_server
attr_reader :thread
def self.run(*args)
server = new(*args)
server.start
server
end
def initialize(sensor, port = nil)
@sensor = sensor
@port = port || 0
end
def start
@tcp_server = TCPServer.new(HOST, port)
@port = @tcp_server.addr[1]
@thread = Thread.new do
loop do
client = tcp_server.accept
SocketRegistry.instance.register(client)
RequestProcessor.call(client, sensor)
end
end
end
end
class Sensor
attr_accessor :longitude
attr_accessor :latitude
attr_accessor :data_generator
attr_accessor :previous_readings
attr_accessor :username
attr_accessor :server
def initialize(port = nil)
@data_generator = ReadingGenerator.new('measurments.csv')
@previous_readings = []
@server = Server.run(self, port)
generate_username
generate_location
end
def generate_username
@username = SecureRandom.uuid
end
def generate_location
@longitude = rand(15.87..16)
@latitude = rand(45.75..45.85)
end
def reading
reading = data_generator.call
previous_readings << reading
previous_readings.shift if previous_readings.count > 5
previous_readings.last
end
def nearest_neighbour_reading
address = HTTPClient.nearest_neighbour(self)
return unless address
LOGGER.info "Requesting reading from '#{address}'..."
socket = SocketRegistry.instance[address]
socket.puts({ method: 'requestMeasurment', args: [username] }.to_json)
reading = JSON.parse(socket.gets)
Reading.new(reading['data'], reading['row'], reading['time_alive'])
rescue
nil
end
def register
HTTPClient.register(self)
end
end
offset = rand(9) + 1
LOGGER.info "Starting main thread in #{offset}sec..."
sleep(offset)
sensor = Sensor.new(ENV['PORT']&.to_i)
loop do
LOGGER.info "Registering sensor '#{sensor.username}' with the server..."
sleep 1
begin
if sensor.register
LOGGER.info "Sensor '#{sensor.username}' registered!"
break
else
LOGGER.error "Sensor '#{sensor.username}' rejected by server."
sensor.generate_username
next
end
rescue Errno::ECONNREFUSED
LOGGER.error 'Unable to connect to server.'
rescue => e
LOGGER.error "REGISTRATION FAILED: #{e} - #{e.class}"
end
end
LOGGER.info 'Sensor listening on '\
"#{HTTPClient.ipv4_address}:#{sensor.server.port}"
sleep_interval = (ENV['SLEEP_INTERVAL'] || 5).to_i
loop do
own = sensor.reading
LOGGER.info "Generated reading #{own}"
other = sensor.nearest_neighbour_reading
LOGGER.info "Fetched neighbour reading #{other.inspect}"
result = (own | other) % own
LOGGER.info "Resulting normalized reading #{result}"
store_result = HTTPClient.store_measurments(result, sensor)
LOGGER.info "Reading stored on the server - #{store_result}"
sleep(sleep_interval)
end
| true |
804db4c2c8dc560a12df4dcdf4b68e28346e9adb | Ruby | chrishunt/exercises | /2020-02-19-max-in-subarray/solution.rb | UTF-8 | 202 | 3.03125 | 3 | [] | no_license | class Solution
def self.max_values(array:, k:)
max_values = []
i = 0
while (i + k) <= array.size
max_values.push(array[i..i+k-1].max)
i += 1
end
max_values
end
end
| true |
5aeea403361095297625cf82442fc40f8d0891d6 | Ruby | ankane/lockbox | /lib/lockbox/padding.rb | UTF-8 | 1,254 | 3.234375 | 3 | [
"MIT"
] | permissive | module Lockbox
module Padding
PAD_FIRST_BYTE = "\x80".b
PAD_ZERO_BYTE = "\x00".b
def pad(str, **options)
pad!(str.dup, **options)
end
def unpad(str, **options)
unpad!(str.dup, **options)
end
# ISO/IEC 7816-4
# same as Libsodium
# https://libsodium.gitbook.io/doc/padding
# apply prior to encryption
# note: current implementation does not
# try to minimize side channels
def pad!(str, size: 16)
raise ArgumentError, "Invalid size" if size < 1
str.force_encoding(Encoding::BINARY)
pad_length = size - 1
pad_length -= str.bytesize % size
str << PAD_FIRST_BYTE
pad_length.times do
str << PAD_ZERO_BYTE
end
str
end
# note: current implementation does not
# try to minimize side channels
def unpad!(str, size: 16)
raise ArgumentError, "Invalid size" if size < 1
str.force_encoding(Encoding::BINARY)
i = 1
while i <= size
case str[-i]
when PAD_ZERO_BYTE
i += 1
when PAD_FIRST_BYTE
str.slice!(-i..-1)
return str
else
break
end
end
raise Lockbox::PaddingError, "Invalid padding"
end
end
end
| true |
b6609393a501c095da3dbf4afa0e88d95ab37751 | Ruby | orbanbotond/ruby_exercise | /spec/algorythms/alg_future_training_01_tree_depth_spec.rb | UTF-8 | 903 | 3.25 | 3 | [] | no_license | require 'spec_helper'
describe 'Tree depth' do
# you can use puts for debugging purposes, e.g.
# puts "this is a debug message"
def solution(a)
if a.l.nil? && a.r.nil?
0
else
d1 = d2 = 0
d1 = 1 + solution(a.l) if a.l
d2 = 1 + solution(a.r) if a.r
d1 > d2 ? d1 : d2
end
end
class Tree
attr_accessor :x, :l, :r
def initialize( x, l, r)
self.x = x
self.l = l
self.r = r
end
end
specify 'extreme small ones' do
t = Tree.new(5, Tree.new(3, Tree.new(20, nil, nil), Tree.new(21, nil, nil)), Tree.new(10, Tree.new(1, nil, nil), nil))
expect(solution(t)).to eq(2)
end
specify 'extreme small zeros' do
t = Tree.new(5, Tree.new(3, Tree.new(20, nil, Tree.new(12, nil, Tree.new(25, nil, nil))), Tree.new(21, nil, nil)), Tree.new(10, Tree.new(1, nil, nil), nil))
expect(solution(t)).to eq(4)
end
end
| true |
ef460c40e323b2e518b664948ff1b6aef8b8a4ad | Ruby | chn-challenger/test_rspec | /ch9_e1_spec.rb | UTF-8 | 906 | 3.59375 | 4 | [] | no_license | def old_roman_numeral num
num_of_m = (num/1000).to_i
num_of_d = ((num%1000)/500).to_i
num_of_c = ((num%500)/100).to_i
num_of_l = ((num%100)/50).to_i
num_of_x = ((num%50)/10).to_i
num_of_v = ((num%10)/5).to_i
num_of_i = (num%5).to_i
roman = "#{'M'*num_of_m}#{'D'*num_of_d}#{'C'*num_of_c}#{'L'*num_of_l}#{'X'*
num_of_x}#{'V'*num_of_v}#{'I'*num_of_i}"
puts roman
return roman
end
describe 'old school roman numerals' do
numerals = ['I','II','III','IIII','V','VI','VII','VIII','VIIII','X',
'XI','XII','XIII','XIIII','XV','XVI','XVII','XVIII','XVIIII','XX']
numerals.each.with_index do |numeral, i|
it "translates #{i+1} to #{numeral}" do
allow(STDOUT).to receive(:puts) #whatever the case, the effect of this line
#is to suppress any puts within the method called during the test.
expect(old_roman_numeral(i+1)).to eq numeral
end
end
end | true |
2c58408d7622a06c4bb6cfae77583e3f25406d2b | Ruby | enricogenauck/labhound | /spec/models/payment_gateway_subscription_spec.rb | UTF-8 | 2,439 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'rails_helper'
describe PaymentGatewaySubscription do
context '.subscribe' do
context 'existing subscription' do
it 'appends id to repo_ids metadata' do
stripe_subscription = MockStripeSubscription.new(repo_ids: [1])
subscription = PaymentGatewaySubscription.new(stripe_subscription)
expect(stripe_subscription.metadata['repo_ids']).to eq '1'
subscription.subscribe(2)
expect(stripe_subscription.metadata['repo_ids']).to eq '1,2'
end
it 'converts legacy format to new format' do
legacy_subscription = MockLegacyStripeSubscription.new(repo_id: 1)
subscription = PaymentGatewaySubscription.new(legacy_subscription)
expect(legacy_subscription.metadata['repo_id']).to eq '1'
subscription.subscribe(2)
expect(legacy_subscription.metadata['repo_id']).to be_nil
expect(legacy_subscription.metadata['repo_ids']).to eq '1,2'
end
end
end
context '.unsubscribe' do
it 'removes repo_id from repo_ids' do
stripe_subscription = MockStripeSubscription.new(repo_ids: [1, 2])
allow(stripe_subscription).to receive(:delete)
allow(stripe_subscription).to receive(:save)
subscription = PaymentGatewaySubscription.new(stripe_subscription)
subscription.unsubscribe(2)
expect(stripe_subscription.metadata['repo_ids']).to eq '1'
expect(stripe_subscription).not_to have_received(:delete)
expect(stripe_subscription).to have_received(:save)
end
it "doesn't blow up when unsubscribing from a legacy subscription" do
legacy_subscription = MockLegacyStripeSubscription.new(repo_id: 1)
allow(legacy_subscription).to receive(:delete)
allow(legacy_subscription).to receive(:save)
subscription = PaymentGatewaySubscription.new(legacy_subscription)
subscription.unsubscribe(1)
expect(legacy_subscription).to have_received(:delete)
expect(legacy_subscription).not_to have_received(:save)
end
end
class MockStripeSubscription
attr_accessor :quantity, :metadata
def initialize(repo_ids:)
@quantity = repo_ids.count
@metadata = { 'repo_ids' => repo_ids.join(',') }
end
def save; end
def delete; end
end
class MockLegacyStripeSubscription < MockStripeSubscription
def initialize(repo_id:)
@quantity = 1
@metadata = { 'repo_id' => repo_id.to_s }
end
end
end
| true |
8ba4f56dc290a144ef1c7ff89d17276d767a4632 | Ruby | jkeen/comma_splice | /lib/comma_splice/helpers/option_scorer.rb | UTF-8 | 3,059 | 3.078125 | 3 | [
"MIT"
] | permissive | module CommaSplice
# scores options based on how likely they are to be correct
class OptionScorer
attr_reader :option
def initialize(option, separator: ',')
@option = option
@start_score = 100
@separator = separator
end
def breakdown
score = @start_score
breakdown = []
rules.each do |rule|
rule_score = send(rule.to_sym)
score += rule_score
breakdown << "#{rule_score.to_s.ljust(3)} #{rule.to_sym}" if rule_score != 0
end
breakdown.unshift("score: #{score}")
end
def score
score = @start_score
rules.each do |rule|
score += send(rule.to_sym)
end
score
end
def options_that_start_with_a_space
option.select do |o|
o.to_s.starts_with?(' ')
end.size * -10
end
def options_that_start_with_a_quote_followed_by_a_space
option.select do |o|
o.to_s.starts_with?('" ')
end.size * -1
end
def options_that_start_with_a_separator
option.select do |o|
o.to_s.starts_with?(@separator)
end.size * -5
end
def options_that_end_with_a_separator
option.select do |o|
o.to_s.ends_with?(@separator)
end.size * -5
end
def options_that_have_words_joined_by_separators
option.select do |o|
Regexp.new("[^0-9\\s]#{@separator}\\w").match(o.to_s) || Regexp.new("\\w#{@separator}[^0-9\\s]").match(o.to_s)
end.compact.size * -5
end
def options_that_are_blank
option.select do |o|
o.to_s.strip.blank?
end.size * -5
end
def options_that_have_longest_comma_separated_number
# return 0 unless @separator == ','
# favor items that have a longer comma separated number
# i.e in the following example, option 1 should win
# (1) artist : Half Japanese
# title : 1,000,000,000 Kisses
# albumtitle: Beautiful Songs: The Best of Jad Fair & Half Japanese
# label : Stillwater/Fire
#
#
# (2) artist : Half Japanese,1,000,000
# title : 000 Kisses
# albumtitle: Beautiful Songs: The Best of Jad Fair & Half Japanese
# label : Stillwater/Fire
#
#
# (3) artist : Half Japanese,1
# title : 000,000,000 Kisses
# albumtitle: Beautiful Songs: The Best of Jad Fair & Half Japanese
# label : Stillwater/Fire
#
#
# (4) artist : Half Japanese,1,000
# title : 000,000 Kisses
# albumtitle: Beautiful Songs: The Best of Jad Fair & Half Japanese
# label : Stillwater/Fire
option.collect do |o|
result = o.to_s.scan(/\d{1,3}(?:,\d{1,3})*(?:\.\d+)?/)
if result.size.positive? && result.first.index(',')
result.join(',').size
else
0
end
end.max.to_i
end
private
def rules
methods.grep(/options_that/)
end
end
end
| true |
33cf48fca6d657553c622b485f1c484ae1c1e0a6 | Ruby | vaxinate/stupid-board-game | /lib/creature.rb | UTF-8 | 1,085 | 2.8125 | 3 | [] | no_license | class Creature < Chingu::GameObject
attr_accessor :name, :speed, :position, :enchantments
attr_writer :selected
def self.selected
all.select { |cr| cr.selected? }
end
def initialize(options)
super
@name = options[:name] if options[:name]
@board = options[:board] if options[:board]
end
def setup
# @image = Image['wizard.png']
self.speed = 4
end
def draw(x, y, z)
Image['wizard.png'].draw(x, y, z, 2, 2)
end
def selected?
@selected
end
def select!
Creature.each { |cr| cr.deselect! }
@selected = true
self
end
def deselect!
@selected = false
self
end
# def position
# index = @board.grid.find_index { |tile| tile.include? self }
# puts self.name
# puts index.class
# index
# end
def move_grid
MoveGrid.new :position => self.position, :speed => self.speed
end
# def pick_up(ball)
# @ball = ball
# end
# def drop_ball
# temp = @ball
# @ball = nil
# temp
# end
# def move_to(x, y)
# @board.move_to(self, x, y) if @board
# end
end
| true |
330d8f45459de5a57a0c59cfd8ac2b8bf85f3021 | Ruby | omareltahasantos/ruby | /expresion_regular.rb | UTF-8 | 1,639 | 3.90625 | 4 | [] | no_license | m1 = /Ruby/.match("El futuro de Ruby")
puts m1 #Devuelve la palabra en caso de encontrarla
puts m1.class #Devuelve MatchData en caso de haberlo en contrado o nil en caso contrario.
#Para buscar caracteres especiales se usa el escape \
m2 = /\?/.match("Estais bien?")
puts m2
puts m2.class
#Si queremos buscar una palabra que empiece por x letra podemos hacer
#En este caso que empiece por c o m
m3 = /[mc]azado/.match("mazado")
m4 = /[mc]azado/.match("cazado")
puts m3
puts m3.class
puts m4
puts m4.class
#Encuentra cualquier palabra que contenga una letra minuscula
m5 = /[a-z]/.match("Hola esto es una prueba")
puts m5
puts m5.class
#Encuentra cualquier numero hexadecimal
m6 = /[A-Fa -f0-9]/
#Si queremos encontrar la condicion contraria a la impuesta en la expresion regular usamos ^
m7 = /[^A-Fa -f0-9]/ #Encuentra cualquier caracter excepto los hexadecimales
#Si queremos generar una expresion regular para buscar numeros decimales usamos /\d/
#Si queremos generar una expresion regular para buscar cualquier digito, letra o guion bajo usamos /\w/
#Si queremos generar una expresion regular para buscar cualquier espacio en blanco /\s/
#Si queremos hacer una negacion de estos caracteres los ponemos en mayuscula tipo /\D/, /\S/, /\W/\
#Ejercicio
string = "Mi numero de telefono es (123) 555-1234."
expre_regular = /\((\d{3})\)\s+(\d{3})-(\d{4})/
m = expre_regular.match(string)
unless (m)
puts 'No hubo concordancias'
exit #Sirve para salir del script
end
print "El string de la busqueda es: "
puts m.string #String de la busqueda
puts "La parte del string que concuerda con la busqueda es: #{m[0]}"
| true |
f1bc59ec7cca18abba5a8f5247b7ba8c47bb96ef | Ruby | llpereiras/tictactoe | /support/colorize.rb | UTF-8 | 688 | 3.5625 | 4 | [] | no_license | class Colorize
def self.colorize(text, color = "default", bgColor = "default")
colors = {"default" => "38","black" => "30","red" => "31","green" => "32","brown" => "33", "blue" => "34", "purple" => "35",
"cyan" => "36", "gray" => "37", "dark gray" => "1;30", "light red" => "1;31", "light green" => "1;32", "yellow" => "1;33",
"light blue" => "1;34", "light purple" => "1;35", "light cyan" => "1;36", "white" => "1;37"}
color_code = colors[color]
return "\033[#{color_code}m#{text}\033[0m"
end
def self.print(text)
return colorize(text, "light blue") if text == "X"
return colorize(text, "red") if text == "O"
colorize(text, "white")
end
end
| true |
e877c7c13a808247c78b28450b12857f58e9fc43 | Ruby | atecdeveloper/ruby_lessons | /plus_exercises/exercise9.rb | UTF-8 | 59 | 2.5625 | 3 | [] | no_license | #Hash with nested array
hash = {key: [1 , 2], key2: [3, 4]} | true |
d0697d5196063d3cd1486400836aa131066a85c9 | Ruby | matthewford/merb-meet-aop | /gems/gems/aquarium-0.4.0/lib/aquarium/aspects/dsl/aspect_dsl.rb | UTF-8 | 2,079 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'aquarium/aspects/aspect'
require 'aquarium/utils/type_utils'
# Convenience methods added to Object to promote an AOP DSL. If you don't want these methods added to Object,
# then only require aspect.rb and create instances of Aspect.
module Aquarium
module Aspects
module DSL
module AspectDSL
def advise *options, &block
o = append_implicit_self options
Aspect.new *o, &block
end
%w[before after after_returning after_raising around].each do |advice_kind|
module_eval(<<-ADVICE_METHODS, __FILE__, __LINE__)
def #{advice_kind} *options, &block
advise :#{advice_kind}, *options, &block
end
ADVICE_METHODS
end
%w[after after_returning after_raising].each do |after_kind|
module_eval(<<-AFTER, __FILE__, __LINE__)
def before_and_#{after_kind} *options, &block
advise :before, :#{after_kind}, *options, &block
end
AFTER
end
alias :after_returning_from :after_returning
alias :after_raising_within :after_raising
alias :after_raising_within_or_returning_from :after
alias :before_and_after_returning_from :before_and_after_returning
alias :before_and_after_raising_within :before_and_after_raising
alias :before_and_after_raising_within_or_returning_from :before_and_after
def pointcut *options, &block
o = append_implicit_self options
Pointcut.new *o, &block
end
# Add the methods as class, not instance, methods.
def self.append_features clazz
super(class << clazz; self; end)
end
private
def append_implicit_self options
opts = options.dup
if (!opts.empty?) && opts.last.kind_of?(Hash)
opts.last[:default_objects] = self
else
opts << {:default_objects => self}
end
opts
end
end
end
end
end
| true |
9d9b4343ed4edb5aa1a7282ea65220e6215d18ef | Ruby | AnguillaJaponica/Ruby_Library_For_Contests | /ABC/ABC129/C.rb | UTF-8 | 340 | 2.609375 | 3 | [] | no_license | n, m = gets.split.map(&:to_i)
mod = 1_000_000_007
dp = Array.new(n + 2, 0)
a = []
dp[0] = 1
m.times do |i|
a[i] = gets.to_i
dp[a[i]] = -1
end
n.times do |i|
next if dp[i] == -1
if dp[i + 1] != -1
dp[i + 1] += dp[i]
dp[i + 1] %= mod
end
if dp[i + 2] != -1
dp[i + 2] += dp[i]
dp[i + 2] %= mod
end
end
puts dp[n]
| true |
6e7ed4c5d068f69efbb3cb353db1136547949cec | Ruby | JorgeDDW/pokedex | /pokedex.rb | UTF-8 | 1,082 | 2.953125 | 3 | [] | no_license |
require 'telegram/bot'
require 'net/http'
require 'rest-client'
require 'json'
require 'open-uri'
token = 'Toke goes here'
puts "Ready to Go!"
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
pokemon_search = message.text
case message.text
when '/start'
p "starting"
bot.api.send_message(chat_id: message.chat.id, text: "Hola, #{message.from.first_name}")
when /pokemon/
name = message.text
name = name.split.last
puts name
url = 'http://pokeapi.co/api/v2/pokemon/'+name
response = RestClient.get(url)
data = JSON.parse(response)
bot.api.send_message(chat_id: message.chat.id, text: "Información del Pokemon: #{data["name"].capitalize}
\n #{data["sprites"]["front_default"]}
\n Este pokemon es del tipo: #{data["types"][0]["type"]["name"].capitalize}
\n El ID de este Pokemon es el: #{data["id"]}")
when '/stop'
bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}")
end
end
end
| true |
11ea9ab29e89e8932daf78c9cd629e9886a4047e | Ruby | s-rayed/W2D3 | /lighthouse-test-oop-RETEST_rev1/spec/04_giant_salmon_and_tuna.rb | UTF-8 | 625 | 2.859375 | 3 | [] | no_license | require_relative 'spec_helper'
describe GiantSalmon do
before :each do
@salmon = GiantSalmon.new
end
it "should be a Fish" do
expect(@salmon).to be_a(Fish)
end
it "should weigh 4 kgs" do
expect(@salmon.weight).to eq(4)
end
it "should be worth 30 dollars" do
expect(@salmon.value).to eq(30)
end
end
describe GiantTuna do
before :each do
@tuna = GiantTuna.new
end
it "should be a Fish" do
expect(@tuna).to be_a(Fish)
end
it "should weigh 2 kgs" do
expect(@tuna.weight).to eq(2)
end
it "should be worth 25 dollars" do
expect(@tuna.value).to eq(25)
end
end
| true |
83983fa67d1fb3516623f15392dcc36c5e8589e7 | Ruby | mliu-dark-knight/CS242 | /MP2/src/cs_air.rb | UTF-8 | 6,979 | 3.203125 | 3 | [] | no_license | require_relative 'graph'
require 'pp'
require 'json'
class CSAir < Graph
# get name of all cities
def allCity()
return allVerticesInfo('name')
end
# get longest single flight
def longestSingleFlight()
return reduceVariable('edges', 'distance', '>')
end
# get shortest single flight
def shortestSingleFlight()
return reduceVariable('edges', 'distance', '<')
end
# get average flight distance
def averageFlightDistance()
return averageVariable('edges', 'distance')
end
# get city with largest population
def biggestCity()
return reduceVariable('vertices', 'population', '>')
end
# get city with smallest population
def smallestCity()
return reduceVariable('vertices', 'population', '<')
end
# get average population of all cities
def averageCityPopulation()
return averageVariable('vertices', 'population')
end
# return a dictionary whose key is continent and value is all cities in it
def aggregateByContinent()
continents = Hash.new
@vertices.each do |key, value|
if not continents.has_key? value.continent
continents[value.continent] = Set.new
end
continents[value.continent].add(value.name)
end
return continents
end
# open map in browser
def visualize()
url = 'http://www.gcmap.com/mapui?P='
allEdges().each do |pair|
url += (pair[0] + '-' + pair[1] + ',+')
end
url = url[0..-3]
system('open', url)
end
# remove city with code
def removeCity(code)
if not @vertices.has_key? code
puts('City does not exist')
return
end
@vertices.delete(code)
@neighbours.delete(code)
@neighbours.each do |key, value|
value.delete(code)
@edges.delete([key, code])
@edges.delete([code, key])
end
end
# remove route with srcCode and destCode
def removeRoute(srcCode, destCode)
if not @edges.has_key? [srcCode, destCode]
puts('Route does not exist')
return
end
@edges.delete([srcCode, destCode])
@edges.delete([destCode, srcCode])
@neighbours[srcCode].delete(destCode)
if @neighbours[srcCode].empty?()
@neighbours.delete(srcCode)
@vertices.delete(srcCode)
end
@neighbours[destCode].delete(srcCode)
if @neighbours[destCode].empty?()
@neighbours.delete(destCode)
@vertices.delete(destCode)
end
end
# add city with associated information
def addCity(code, name, country, continent, timezone, coordinates, population, region)
if @vertices.has_key? code
puts('City already exists')
return
end
if population <= 0
puts('Population cannot be negative')
return
end
@vertices[code] = Metro.new(code, name, country, continent, timezone, coordinates, population, region)
@neighbours[code] = Set.new
end
# add route with associated information
def addRoute(srcCode, destCode, distance)
if @edges.has_key? [srcCode, destCode] or @edges.has_key? [destCode, srcCode]
puts('Route already exists')
return
end
if not @vertices.has_key? srcCode or not @vertices.has_key? destCode
puts('Add route failed because city does not exist')
return
end
if distance <= 0
puts('Distance cannot be negative')
return
end
@edges[[srcCode, destCode]] = Route.new([srcCode, destCode], distance)
@edges[[destCode, srcCode]] = Route.new([destCode, srcCode], distance)
@neighbours[srcCode].add(destCode)
@neighbours[destCode].add(srcCode)
end
# edit city, set attribute of city with code to value
def editCity(code, attr, value)
if not @vertices.has_key? code
puts('City does not exist')
return
end
if not @vertices[code].instance_variable_defined?('@' + attr)
puts('Attribute does not exist')
return
end
if attr == 'population' and value <= 0
puts('Population cannot be negative')
return
end
@vertices[code].instance_variable_set('@' + attr, value)
end
# edit route, set attribute with srcCode and destCode to value
def editRoute(srcCode, destCode, attr, value)
if not @edges.has_key? [srcCode, destCode]
puts('Route does not exist')
return
end
if not @edges[[srcCode, destCode]].instance_variable_defined?('@' + attr)
puts('Attribute does not exist')
return
end
if attr == 'distance' and value <= 0
puts('Distance cannot be negative')
return
end
@edges[[srcCode, destCode]].instance_variable_set('@' + attr, value)
@edges[[srcCode, destCode]].instance_variable_set('@' + attr, value)
end
# dump to json format
def dump(fname)
metros = []
routes = []
@vertices.each do |key, value|
metros.push(value.tojson())
end
@edges.each do |key, value|
routes.push(value.tojson())
end
dict = Hash.new
dict['metros'] = metros
dict['routes'] = routes
File.open(fname,"w") do |f|
f.write(JSON.pretty_generate(dict))
end
end
# distance of route, metros is an array of city code
def routeDistance(metros)
distance = 0
metros.each_with_index do |val, idx|
if idx + 1 == metros.length
break
end
if not @edges.has_key? [val, metros[idx + 1]]
puts('Route does not exist')
return -1
end
distance += @edges[[val, metros[idx + 1]]].distance
end
return distance
end
# cost of route, metros is an array of city code
def routeCost(metros)
cost = 0
per_kilo = 0.35
metros.each_with_index do |val, idx|
if idx + 1 == metros.length
break
end
if not @edges.has_key? [val, metros[idx + 1]]
puts('Route does not exist')
return -1
end
cost += per_kilo * @edges[[val, metros[idx + 1]]].distance
per_kilo -= 0.05
if per_kilo <= 0
break
end
end
return cost
end
# time from city with srcCode to city with destCode
def time(srcCode, destCode)
if @edges[[srcCode, destCode]].distance < 400
return 2 * Math.sqrt(@edges[[srcCode, destCode]].distance * 400.0 / (750**2))
end
return 400.0 / 375.0 + (@edges[[srcCode, destCode]].distance - 400) / 750.0
end
# time of route, metros is an array of city code
def routeTime(metros)
time = 0
metros.each_with_index do |val, idx|
if idx + 1 == metros.length
break
end
if not @edges.has_key? [val, metros[idx + 1]]
puts('Route does not exist')
return -1
end
time += time(val, metros[idx + 1])
if idx != 0
time += (2 - (@neighbours[val].length() - 1) / 6.0)
end
end
return time
end
# shortest path from city with srcCode to city with destCode
def shortestPath(srcCode, destCode)
if not @vertices.has_key? srcCode or not @vertices.has_key? destCode
puts('City does not exist')
return nil
end
return dijkstra(srcCode, destCode, 'distance')
end
end | true |
83427a2ddacaba6ae5d8c442044257179db0550f | Ruby | mstanislav/basecampnext | /lib/basecampnext.rb | UTF-8 | 1,356 | 2.625 | 3 | [] | no_license | require 'yaml'
require 'httparty'
require 'json'
class BasecampNext
def initialize(username = nil, password = nil, account = nil, api = nil)
@username = username || BASECAMPNEXT_CONFIG['username']
@password = password || BASECAMPNEXT_CONFIG['password']
@account = account || BASECAMPNEXT_CONFIG['account']
@api = api || BASECAMPNEXT_CONFIG['api']
return false if @username.blank? or @password.blank? or @account.blank? or @api.blank?
@endpoint = "https://basecamp.com/#{@account}/api/v#{@api}"
@params = { :basic_auth => { :username => @username, :password => @password }, :headers => { 'User-Agent' => @username } }
end
def project(project_id)
request "projects/#{project_id}.json"
end
def projects
request "projects.json"
end
def todo(project_id, todo_id)
request "projects/#{project_id}/todos/#{todo_id}.json"
end
def todolists
request "todolists.json"
end
def todolists(project_id)
request "projects/#{project_id}/todolists.json"
end
def todolist(project_id, todolist_id)
request "projects/#{project_id}/todolists/#{todolist_id}.json"
end
private
def request(path)
handle HTTParty.get "#{@endpoint}/#{path}", @params
end
def handle(response)
if response.code == 200
JSON.parse(response.body)
else
return false
end
end
end
| true |
2b881a360931c1274c08765d3d46d42db1b0be2f | Ruby | ximengch/ruby_sample | /chapter7_8/hello_class.rb | UTF-8 | 763 | 3.875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
class HelloWorld
@@count=0 #类方法
attr_accessor:name
def initialize(myname="Ruby")
@name=myname
end
def hello
@@count+=1
puts "Hello,world.I am #{@name}"
end
def HelloWorld.hello(name) #类方法
puts "#{name} said Hello.这是类方法"
end
class<<self #类方法
def helloChina(name)
puts "#{name}说你好!"
end
end
def self.helloSelf #类方法
puts "self hello"
end
def self.count
@@count
end
end
bob=HelloWorld.new("Bob")
alice=HelloWorld.new("Alice")
ruby=HelloWorld.new
bob.hello
alice.hello
ruby.hello
puts bob.name
HelloWorld::helloChina("陈君")
HelloWorld::hello 'gege'
puts HelloWorld::count
| true |
83f2a0fa22508087d937046cf9560fdd2a3904a6 | Ruby | realalien/rubyplayground | /ktools/test.rb | UTF-8 | 956 | 2.734375 | 3 | [] | no_license | #encoding:UTF-8
# --------------------------------
# self explanable where the knowledge(assumption) is got or can be confirmed.
# following the example function to demonstrate funcitionalities similar to the ones appear in Python's method comments, DSL, and
def administrative_divisions_of_china
meta = { } # TODO: create more attributes for the instances of Methods class. Can be turned off for performance/no-error-checking.
end
# --------------------------------
# DSL parts, do I need this?
# --------------------------------
# Misc. ideas
# one person's history tracking, on publication, lectures and works
# use above info to find reusable tools/datasets, then create local data interface to facilate later reuse
# data aggregation to find the similiar or the common features.
# find out why there are so many programmer lacking of statistical knowledge.
# how to create tools to facilitate the learning and using
| true |
8e39348d401bd010c34c929d677b89f8f0adb626 | Ruby | timcmartin/pdfmetadata | /app/models/chart.rb | UTF-8 | 839 | 2.546875 | 3 | [] | no_license | # chart.rb
class Chart
include Filemover
include ActiveModel::Model
attr_accessor(:title, :path, :composer, :genre, :keywords, :format, :filename)
validates_with ChartValidator
def initialize(attributes = {})
super
end
def pdf_hash
{ Title: title, Author: composer, Keywords: keywords, Subject: genre, Creator: format }
end
def backup_file
File.join(Rails.public_path, ENV["BACKUP"], path)
end
def processed_file
File.join(Rails.public_path, ENV["OUTPUT"], path)
end
def raw_file
File.join(ENV["INPUT"], path)
end
def process_pdf
return unless self.valid?
backup_and_move(raw_file, backup_file, processed_file)
pdf = Prawn::Document.new(template: processed_file, info: pdf_hash)
pdf.render_file processed_file
move_with_path(processed_file, raw_file)
end
end
| true |
1c0c9d499eb16d6f87342d3ce654dfddd0e282c6 | Ruby | tomyancey/coderbyte_solutions | /letter_changes.rb | UTF-8 | 807 | 4.3125 | 4 | [] | no_license | =begin
Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
Use the Parameter Testing feature in the box below to test your code with different arguments.
=end
def letter_changes(str)
arr = str.downcase.split(//)
new = []
vowels = %w[a e i o u]
arr.each do |x|
if x.match(/[a-y]/)
new << x.next
elsif x.match(/z/)
new << 'a'
else
new << x
end
end
new.map! { |x| vowels.include?(x) ? x.upcase : x }
new.join
end | true |
8b1f1e2d3506ba2d4d1c639775971f27e77537fd | Ruby | cody-castro/say-hello-ruby-nyc-fasttrack-062020 | /say_hello.rb | UTF-8 | 164 | 3.34375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Build your say_hello method here
# say_hello = "Hello Ruby Programmer"
name = "Gabriela"
def say_hello(name = "Ruby Programmer")
puts "Hello #{name}!"
end
| true |
ddd3bcfd198eeb315e63205ba75b1becb0d14c4b | Ruby | erhsparks/Poker_FiveCardDraw | /spec/hand_spec.rb | UTF-8 | 3,276 | 3.640625 | 4 | [] | no_license | require 'rspec'
require 'hand'
describe Hand do
subject(:hand) { Hand.new }
let(:card1) { double("card1", :suit => :♠, :value => :"10") }
let(:card2) { double("card2", :suit => :♠, :value => :J) }
let(:card3) { double("card3", :suit => :♠, :value => :Q) }
let(:card4) { double("card4", :suit => :♠, :value => :K) }
let(:card5) { double("card5", :suit => :♠, :value => :A) }
describe "#initialize" do
it "creates empty array in instance variable @card" do
expect(hand.cards).to be_an(Array)
expect(hand.cards).to be_empty
end
end
describe "#[]" do
it "returns Hand#cards at given index" do
expect(hand[0]).to eq(hand.cards[0])
end
end
describe "#add_cards" do
it "adds a card to an empty hand" do
hand.add_cards(card3)
new_hand = hand.cards
expect(new_hand.size).to eq(1)
expect(new_hand).to include(card3)
end
it "adds a card to a hand with cards in it" do
hand.add_cards(card1)
hand.add_cards(card2)
new_hand = hand.cards
expect(new_hand.size).to eq(2)
expect(new_hand).to include(card1)
expect(new_hand).to include(card2)
end
it "adds multiple cards to a hand" do
hand.add_cards(card1, card2, card5)
new_hand = hand.cards
expect(new_hand.size).to eq(3)
expect(new_hand).to include(card1)
expect(new_hand).to include(card2)
expect(new_hand).to include(card5)
end
it "does not allow hand to be greater than five cards" do
hand.add_cards(card1, card2, card3, card4, card5)
card6 = double("card6", :suit => :♠, :value => :"9")
expect { hand.add_cards(card6) }.to raise_error
end
end
describe "#discard" do
before(:each) do
hand.add_cards(card1, card2, card3, card4, card5)
end
it "raises an error if input card is not in hand" do
expect { hand.delete(card6) }.to raise_error
end
it "removes a specific card from hand" do
hand.discard(card2)
new_hand = hand.cards
expect(new_hand.size).to eq(4)
expect(new_hand).to_not include(card2)
end
it "removes multiple cards from hand" do
hand.discard(card1, card4)
new_hand = hand.cards
expect(new_hand.size).to eq(3)
expect(new_hand).to_not include(card1)
expect(new_hand).to_not include(card4)
end
end
describe "#winning_hand" do
before(:each) do
hand.add_cards(card1, card2, card3, card4, card5)
end
let(:possible_values) { Hand::ALPHABET }
before(:each) do
@best = hand.winning_hand
@winning_move = @best.first
@card_hash = @best.last
@card_values = @card_hash.keys
@card_suits = @card_hash.values
end
it "returns an array" do
expect(@best).to be_an(Array)
end
it "the first element of output is a symbol" do
expect(@winning_move).to be_a(Symbol)
end
it "the last element of the output is a hash" do
expect(@card_hash).to be_a(Hash)
end
it "hash keys are card values" do
expect(@card_values.all? { |k| possible_values.include?(k) }).to be true
end
it "hash values are arrays of suits" do
expect(@card_suits.all? { |v| v.is_a?(Array) }).to be true
end
end
end
| true |
598d6881a76443c3e33721226e46b0120babb813 | Ruby | Val-Lee/epam | /1.rb | UTF-8 | 1,118 | 3.203125 | 3 | [] | no_license | class University
end
class Faculty < University
end
class Group < Faculty
attr_accessor :supahash
def initialize(name)
@name = name
@supahash = Hash.new(@name)
end
def add_student(student)
@supahash[@name] = [student]
end
def show_group
return @supahash
end
end
class Student < Group
attr_accessor :name, :l_name, :supahash, :subject
def initialize(f_name, l_name)
@f_name = f_name
@l_name = l_name
@supahash = Hash.new
end
def show
return @f_name, @l_name
end
def marks(subject, mark)
@supahash[subject] = mark.to_f
end
def show_marks
return @supahash
end
def avg_marks
return @supahash.values.inject { |sum,v| sum+ v }/ @supahash.size
end
# def avg_mark_by_subj(subject)
# return @
# end
end
g = Group.new("1")
a = Student.new('Valentin','Lee')
p a.show
b = Student.new('Zhora','Rzhavii')
p b.show
g.add_student(a)
g.add_student(b)
p g.show_group
a.marks('Math', 5)
a.marks('OS', 3)
b.marks('Math', 10)
b.marks('OS', 5)
a.marks('Android', 8)
# p a.subject
p a.show_marks
p a.avg_marks
p b.show_marks
p b.avg_marks
| true |
7a8ec6bec6259ab0c454c210f6c03fe7a2bbbd15 | Ruby | CodeandoMexico/retos-civicos | /spec/models/location_spec.rb | UTF-8 | 2,255 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
describe Location do
describe 'search' do
fixtures :locations
describe 'given a valid query' do
describe 'given the search result has a locality' do
it 'should return a hash with state, city, and locality' do
expect(Location.search('64000').first.locality).to eq 'Col. Centro'
end
end
describe 'given the search result does not have a locality' do
it 'should return a hash with state, city, but no locality' do
expect(Location.search('48400').first.locality).to eq nil
end
end
describe 'given the search query uses accents' do
it 'should return results independent if accents are used' do
pending 'Not quite sure how to make it accent independent without affecting UX. Not a big deal in meantime.'
expect(Location.search('León').length).to eq 1
expect(Location.search('Leon').length).to eq 1
end
end
describe 'given the search query uses weird caps' do
it 'should return results independent of query case' do
expect(Location.search('NUEVO LEON').length).to eq 1
end
end
describe 'given the search matches several locations with the same city & state' do
it 'should only return one of the locations' do
expect(Location.search('Nuevo Leon').length).to eq 1
end
it 'should return at most 5 results' do
expect(Location.search('Jalisco').length).to eq 5
end
end
describe 'given the search query includes a typo' do
describe 'given an incomplete zip code' do
it 'should return a fuzzy-searched result with the most relevant locations' do
expect(Location.search('48401').first.city).to eq('Tequila')
end
end
describe 'given a incorrectly typed city or state' do
it 'should return a fuzzy-searched result with the most relevant Locations' do
expect(Location.search('Teqilaa').first.city).to eq('Tequila')
end
end
end
describe 'given the search is empty' do
it 'should return nil' do
expect(Location.search('')).to eq nil
end
end
end
end
end
| true |
c6efea32d7cf5147d3a0baa77ceeceb0c91cd9ea | Ruby | bomattsson/battleship | /spec/player_spec.rb | UTF-8 | 735 | 2.984375 | 3 | [] | no_license | require 'grid'
require 'player'
describe 'Player' do
subject { Player.new }
it 'it creates a my_board' do
expect(subject.my_board).to be_kind_of Grid
end
it 'can place ship' do
subject.place_ship(:A1)
expect(subject.my_board.grid[:A1]).to eq "s"
end
it 'can receive a hit' do
subject.place_ship(:A1)
subject.shoot_at(:A1)
expect(subject.my_board.grid).to include :A1 => "hit"
end
it 'can receive a miss' do
subject.place_ship(:A2)
subject.shoot_at(:A1)
expect(subject.my_board.grid).to include :A1 => "miss"
end
it 'can shoot at opponent' do
player2 = Player.new
subject.shoot(player2,:A1)
expect(subject.opponents_board.grid).to include :A1 => "miss"
end
end | true |
5aac3de6d99ea6c13540f42e80cdad61e04e4ab9 | Ruby | AdamGoodApp/zero-robot | /lib/queue/ScheduledQueue.rb | UTF-8 | 3,177 | 2.546875 | 3 | [] | no_license | require 'concurrent/scheduled_task'
require 'concurrent/executor/thread_pool_executor'
require 'concurrent/utility/processor_counter'
module ActiveJob
module QueueAdapters
class ScheduledQueue
def initialize(**executor_options, &block)
@config = Configuration.new(&block)
@scheduler = Scheduler.new(@config, **executor_options)
end
def enqueue(job)
@config.queues[job.queue_name.to_sym] << job
end
def enqueue_at(*)
raise NotImplementedError, "This queue doesn't support explicitly delayed jobs (they all are delayed by design)"
end
def shutdown(wait: true)
@scheduler.shutdown wait: wait
end
class Queue
def initialize
@job = nil
@lock = Mutex.new
end
def execute
job = nil
@lock.synchronize do
return if @job.nil?
job = @job
@job = nil
end
Base.execute job.serialize
end
def <<(job)
@lock.synchronize do
if @job.nil?
job.arguments = [[job.arguments]]
@job = job
else
@job.arguments[0] << job.arguments
end
end
end
end
class Configuration
attr_accessor :schedules, :queues
def initialize(&block)
@schedules = {}
@queues = {}
instance_eval(&block)
end
def schedule(queue, every: nil)
if every.nil?
raise ArgumentError, "You need to specify a 'every' argument for '#{queue}'"
end
@schedules[queue] = {every: every}
@queues[queue] = Queue.new
end
end
class Scheduler
DEFAULT_EXECUTOR_OPTIONS = {
min_threads: 0,
max_threads: Concurrent.processor_count,
auto_terminate: true,
idletime: 60,
max_queue: 0,
fallback_policy: :caller_runs
}.freeze
def initialize(config, **options)
@stop = false
@async_executor = Concurrent::ThreadPoolExecutor.new(DEFAULT_EXECUTOR_OPTIONS.merge(options))
setup_schedules(config)
end
def setup_schedules(config)
config.schedules.each do | name, options |
queue = config.queues[name]
schedule_block = Proc.new do | &block |
Concurrent::ScheduledTask.execute(options[:every], args: [], executor: @async_executor, &block)
end
execute_block = Proc.new do
begin
queue.execute
rescue => e
Rails.logger.debug("Exception while executing scheduled task: #{e}\n\t#{e.backtrace.join("\n\t")}")
ensure
schedule_block.call(&execute_block) unless @stop
end
end
schedule_block.call(&execute_block)
end
end
def shutdown(wait: true)
@stop = true
@async_executor.shutdown
@async_executor.wait_for_termination if wait
end
end
end
end
end
| true |
845c30563203b8d4f9d3d3927e4ebb4e5620fda6 | Ruby | JulieLev/bank-tech-test | /lib/bank_account.rb | UTF-8 | 854 | 3.40625 | 3 | [] | no_license | require 'date'
require_relative 'transaction'
class BankAccount
attr_reader :show_balance, :date, :read_transactions
def initialize
@balance = 0
@date = Date.today
@transactions = []
end
def withdraw(amount, date=Date.today)
withdrawal_update_balance(amount)
add_transaction('debit', amount, date)
end
def deposit(amount, date=Date.today)
deposit_update_balance(amount)
add_transaction('credit', amount, date)
end
def show_balance
@balance
end
def read_transactions
@transactions
end
private
def deposit_update_balance(amount)
@balance += amount
end
def withdrawal_update_balance(amount)
@balance -= amount
end
def add_transaction(type, amount, date)
transaction = Transaction.new(type: type, amount: amount, date: date)
@transactions << transaction
end
end
| true |
9e8c603182c025d65f3d406a0c37fb000fd569fe | Ruby | nicolasm/jekyll-metaweblog | /post.rb | UTF-8 | 4,474 | 3.1875 | 3 | [] | no_license | require 'yaml'
class Post
attr_accessor :base, :filename, :date, :body, :data, :type, :slug
def initialize(base, filename)
self.base = base
self.filename = filename
self.slug = filename
self.date = Date.today
self.type = :page
# the page itself
self.data = {}
self.data["layout"] = "post"
self.body = ""
# page filenames need to start with a date
m = self.filename.match(/^_posts\/(\d{4})-(\d\d)-(\d\d)-(.*)$/)
if m
self.date = Date.civil(m[1].to_i, m[2].to_i, m[3].to_i)
self.slug = m[4]
self.type = :post
end
end
# return bool true iff this file is actually a Jekyll source file
def read
# note to self - the better long-term way of doing this is to read the first
# 4 bytes, look fior '---\n', then read till we have the preamble and parse it,
# then read the rest, rather than always reading Xk of the file and splitting it
# up. But this works.
if not File.exists? File.join(self.base, self.filename)
return false
end
# read the first 500k from the file. If the post is longer than this, it'll be truncated.
# but we need to limit to a certain point or we'll slurp in the entirety of every file
# in the folder.
content = File.open(File.join(self.base, self.filename), "r") {|f| f.read(500 * 1024) }
if not content
# 0-length file
return false
end
# file must begin with YAML
preamble = content.split(/---\s*\n/)[1]
if not preamble
#puts "#{ self.filename } looks like a post but doesn't start with YAML preamble!"
return false
end
begin
self.data = YAML.load(preamble)
rescue Exception => e
STDERR.puts("can't load YAML from #{self.filename}")
return false
end
# so, this is tricky. Should body contain preamble? not sure. Tilting
# towards no right now - if you want something clever, do it with a
# text editor.
self.body = content.split(/---\s*\n/, 3)[2]
return true
end
def write
# if the format type has changed, the file on disk will have a different filename
# (because the format type is the file extension).
if self.type == :post
self.slug = self.title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') + ".markdown"
new_filename = sprintf("_posts/%04d-%02d-%02d-%s", self.date.year, self.date.month, self.date.day, self.slug)
else
new_filename = self.slug
end
# create surrounding folder.
folder = File.dirname File.join(self.base, new_filename)
if not File.directory? folder
# TODO - fix for recursive mkdir
Dir.mkdir folder
end
# write a .temp file rather than overwriting the old file, in case something
# goes wrong. TODO - Write a hidden file to avoid confusing jekyll
tempname = File.join(self.base, new_filename + ".temp")
File.open(tempname, "w") do |f|
f.write YAML.dump( self.data )
f.write "---\n\n"
f.write self.body.strip + "\n"
end
# if the file extension changed, remove the old file.
if new_filename != self.filename and File.exist? File.join(self.base, self.filename)
File.delete File.join(self.base, self.filename)
end
# replace the file with the temp file we wrote.
File.rename( tempname, File.join(self.base, new_filename) )
self.filename = new_filename
end
def to_s
return "#<Post (#{self.type}) #{self.filename}>"
end
# some utility accessors to get/set standard values out of the data hash
def title
return self.data["title"]
end
def title=(t)
self.data["title"] = t
end
def tags
return self.data["tags"] || []
end
def tags=(t)
self.data["tags"] = t
end
def photo
return self.data["photo"]
end
def photo=(p)
self.data["photo"] = p
end
def photoAltText
return self.data["photo-alt-text"]
end
def photoAltText=(p)
self.data["photo-alt-text"] = p
end
end
| true |
1e1532f41e5bec77bce66ab7a49f6fd68b3911ce | Ruby | iangraham20/cs214 | /labs/01/Bird.rb | UTF-8 | 430 | 3.609375 | 4 | [] | no_license | #!/usr/bin/ruby
# Bird.rb Defines a Bird superclass to be extended by specific bird sub-classes
# Begun by: Dr. Adams, for CS 214 at Calvin College
# Completed by: Ian Christensen, for CS 214 at Calvin College
# Date: Spring, 2018
class Bird
attr_reader :name
def initialize(name)
@name = name
end
def call
'Squaaaaaaawk!'
end
def className
self.class.to_s
end
def print
puts name + className + " says " + call
end
end
| true |
b66c957cd6101cdcd804f942aa5da8309b5b06aa | Ruby | ioquatix/geospatial | /lib/geospatial/circle.rb | UTF-8 | 3,053 | 3.1875 | 3 | [
"MIT"
] | permissive | # Copyright, 2015, by Samuel G. D. Williams. <http://www.codeotaku.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
require 'matrix'
module Geospatial
# A circle is a geometric primative where the center is a location and the radius is in meters.
class Circle
class << self
alias [] new
end
# Center must be a vector, radius must be a numeric value.
def initialize(center, radius)
@center = center
@radius = radius
end
attr :center
attr :radius
def to_s
"#{self.class}[#{@center}, #{@radius}]"
end
def distance_from(point)
Location.new(point[0], point[1]).distance_from(@center)
end
def include_point?(point, radius = @radius)
distance_from(point) <= radius
end
def include_box?(other)
# We must contain the for corners of the other box:
other.corners do |corner|
return false unless include_point?(corner)
end
return true
end
def include_circle?(other)
# We must be big enough to contain the other point:
@radius >= other.radius && include_point?(other.center.to_a, @radius - other.radius)
end
def include?(other)
case other
when Box
include_box?(other)
when Circle
include_circle?(other)
end
end
def intersect?(other)
case other
when Box
intersect_with_box?(other)
when Circle
intersect_with_circle?(other)
end
end
def midpoints
@bounds ||= @center.bounding_box(@radius)
yield([@bounds[:longitude].begin, @center.latitude])
yield([@bounds[:longitude].end, @center.latitude])
yield([@center.longitude, @bounds[:latitude].begin])
yield([@center.longitude, @bounds[:latitude].end])
end
def intersect_with_box?(other)
# If we contain any of the four corners:
other.corners do |corner|
return true if include_point?(corner)
end
midpoints do |midpoint|
return true if other.include_point?(midpoint)
end
return false
end
def intersect_with_circle?(other)
include_point?(other.center.to_a, @radius + other.radius)
end
end
end
| true |
b59d42fdbc82ff6666271596068a55e2de142bd9 | Ruby | jinstrider2000/dynamic-orm-lab-v-000 | /lib/student.rb | UTF-8 | 346 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative "../config/environment.rb"
require 'active_support/inflector'
require 'interactive_record.rb'
class Student < InteractiveRecord
self.column_names.each do |col_name|
attr_accessor col_name.to_sym
end
def self.find_by_name(name)
DB[:conn].execute("SELECT * FROM #{self.table_name} WHERE name = ?",name)
end
end
| true |
f9e215f324f1c7a8d63719e556c21e73ed65b257 | Ruby | ECHOInternational/your_membership | /lib/your_membership/base.rb | UTF-8 | 7,626 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'httparty/ym_xml_parser'
module YourMembership
# Base Class inherited by all Your Membership SDK Classes.
class Base
include HTTParty
base_uri YourMembership.config[:baseUri]
# rubocop:disable Style/ClassVars
# Call IDs are usually tied to sessions, this is a unique call id for use whenever a session is not needed.
@@genericCallID = nil
# @return [Integer] Auto Increments ad returns the genericCallID as required by the YourMembership.com API
def self.new_call_id
if @@genericCallID.nil?
# We start with a very high number to avoid conflicts when initiating a new session.
@@genericCallID = 10_000
else
@@genericCallID += 1
end
@@genericCallID
end
# rubocop:enable Style/ClassVars
# Fix bad XML from YM API by using custom parser.
# @api private
# @override HTTParty::ClassMethods#post
# @return [HTTParty::Response]
def self.post(path, options = {}, &block)
opt = options.merge(parser: ::HTTParty::YMXMLParser)
super(path, opt, &block)
end
# A Guard Method that returns true if the response from the API can be processed and raises an exception if not.
# @param [Hash] response
# @return [Boolean] true if no errors found.
# @raise [HTTParty::ResponseError] if a communication error is found.
def self.response_valid?(response)
if response.success?
!response_ym_error?(response)
else
raise HTTParty::ResponseError.new(response), 'Connection to YourMembership API failed.'
end
end
# Checks for error codes in the API response and raises an exception if an error is found.
# @param [Hash] response
# @return [Boolean] false if no error is found
# @raise [YourMembership::Error] if an error is found
def self.response_ym_error?(response)
if response['YourMembership_Response']['ErrCode'] != '0'
raise YourMembership::Error.new(
response['YourMembership_Response']['ErrCode'],
response['YourMembership_Response']['ErrDesc']
)
else
return false
end
end
# Creates an XML string to send to the API
# @todo THIS SHOULD BE MARKED PRIVATE and refactored to DRY up the calls.
def self.build_XML_request(callMethod, session = nil, params = {}) # rubocop:disable Style/MethodLength, Style/MethodName
builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
# Root Node Is always <YourMembership>
xml.YourMembership do
# API Version
xml.Version_ YourMembership.config[:version]
# API Key: For System Administrative tasks it is the private key and
# passcode, for all others it is the public key
if callMethod.downcase.start_with?('sa.')
xml.ApiKey_ YourMembership.config[:privateKey]
xml.SaPasscode_ YourMembership.config[:saPasscode]
else
xml.ApiKey_ YourMembership.config[:publicKey]
end
# Pass Session ID and Session Call ID unless there is no session, then
# send call id from class
if session
if session.is_a? YourMembership::Session
xml.SessionID_ session.session_id
else
xml.SessionID_ session
end
xml.CallID_ session.call_id
else
xml.CallID_ new_call_id
end
xml.Call(:Method => callMethod) do
params.each do |key, value|
xml_process(key, value, xml)
end
end
end
end
builder.to_xml
end
# This is a helper method to always return an array (potentially empty) of responses (Hashes) for methods that can
# have multiple results. The default behavior of the API is to return a nil if no records are found, a hash if one
# record is found and an array if multiple records are found.
#
# @param [Hash] response_body This is the nodeset that returns nil if an empty data set is returned.
# @param [Array] keys This is a list of keys, in order that are nested inside the response body, these keys will be
# traversed in order before retrieving the data associated with the last key in the array
# @return [Array] A single dimension array of hashes.
def self.response_to_array_of_hashes(response_body, keys = [])
return_array = []
if response_body
# http://stackoverflow.com/questions/13259181/what-is-the-most-ruby-ish-way-of-accessing-nested-hash-values-at-arbitrary-depth
response_body_items = keys.reduce(response_body) { |h, key| h[key] }
if response_body_items.class == Array
response_body_items.each do |response_item|
return_array.push response_item
end
else
return_array.push response_body_items
end
end
return_array
end
# Converts the desired portion of the XML response to a single dimension array.
# This is useful when you don't have a need for key, value pairs and want a clean array of values to work with.
#
# @param [Hash] response_body This is the nodeset that returns nil if an empty data set is returned.
# @param [Array] keys This is a list of keys, in order that are nested inside the response body, these keys will be
# traversed in order before retrieving the data associated with the key_for_array
# @param [String] key_for_array this is the key that represents the list of items you want to turn into an array.
# @return [Array] A single dimension array of values.
def self.response_to_array(response_body, keys = [], key_for_array)
return_array = []
response_hash_array = response_to_array_of_hashes(response_body, keys)
response_hash_array.each do |item|
return_array.push item[key_for_array]
end
return_array
end
private
# Convenience method to convert Ruby DateTime objects into ODBC canonical strings as are expected by the API
# @param [DateTime] dateTime
# @return [String] An ODBC canonical string representation of a date as is expected by the API
def self.format_date_string(dateTime)
dateTime.strftime('%Y-%m-%d %H:%M:%S')
end
def self.xml_process(key, value, xml)
case value
when Array
xml_process_array(key, value, xml)
when Hash
xml_process_hash(key, value, xml)
when YourMembership::Profile
xml_process_profile(value, xml)
when DateTime
xml.send(key, format_date_string(value))
else
xml.send(key, value)
end
end
def self.xml_process_profile(profile, xml)
profile.data.each do |k, v|
xml_process(k, v, xml)
end
xml.send('CustomFieldResponses') do
profile.custom_data.each do |k, v|
xml_process_custom_field_responses(k, v, xml)
end
end
end
def self.xml_process_hash(key, value, xml)
xml.send(key) do
value.each { |k, v| xml_process(k, v, xml) }
end
end
def self.xml_process_array(key, value, xml)
xml.send(key) do
value.each { |tag| xml.send(tag[0], tag[1]) }
end
end
def self.xml_process_custom_field_responses(key, value, xml)
xml.send('CustomFieldResponse', :FieldCode => key) do
xml.send('Values') do
case value
when Array
value.each do | item |
xml.send('Value', item)
end
else
xml.send('Value', value)
end
end
end
end
end
end
| true |
01674503f6dfb104ba865a1297650354af631fdc | Ruby | aaduru/technical_interview_problems | /remove_nth_node.rb | UTF-8 | 480 | 3.6875 | 4 | [] | no_license | class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
def remove_nth_from_end(head, n)
temp_node = ListNode.new(0)
temp_node.next = head
len = 0
first = head
while first != nil
len += len
first = first.next
end
len = len - n
first = temp_node
while len > 0
len = len -1
first = first.next
end
first.next = first.next.next
return temp_node.next
end
| true |
ecc1b33a06dd319956a8b39710aa17d4b01594bf | Ruby | sizucca/meeting-schedule | /app/helpers/schedule_helper.rb | UTF-8 | 2,778 | 2.90625 | 3 | [] | no_license | # coding: utf-8
module ScheduleHelper
#
# selectのoptions:年
#
def select_year_options(options = {})
select_year_options = []
time_now = Time.zone.now
start_year = time_now.year.to_i
end_year = start_year + (options[:over_year] ||= 10).to_i
(start_year).upto(end_year) do |year|
select_year_options << ["#{year} #{options[:unit]}", year]
end
return select_year_options
end
#
# selectのoptions:月
#
def select_month_options(options = {})
select_month_options = []
(1).upto(12) do |month|
select_month_options << ["#{month} #{options[:unit]}", month]
end
return select_month_options
end
#
# selectのoptions:日
#
def select_day_options(options = {})
select_day_options = []
(1).upto(31) do |day|
select_day_options << ["#{day} #{options[:unit]}", day]
end
return select_day_options
end
#
# selectのoptions:時
#
def select_hour_options(options = {})
select_hour_options = []
(0).upto(23) do |hour|
select_hour_options << ["#{hour} #{options[:unit]}", hour]
end
return select_hour_options
end
#
# selectのoptions:分
#
def select_min_options(options = {})
select_min_options = []
step = options[:step] ? options[:step].to_i : 1
(0).step(59, step) do |min|
min = "%02d" % min
select_min_options << ["#{min} #{options[:unit]}", min]
end
return select_min_options
end
#
# selectのoptions:登録者
#
def select_user_options(users = {})
select_user_options = []
if users.present? && users.size > 0
users.each do |u|
user_name = ""
user_name += u[:family_name]
user_name += " #{u[:first_name]}"
if(u[:family_kana].present? || u[:first_kana].present?)
user_name += "("
user_name += "#{u[:family_kana].to_hiragana}"
user_name += " #{u[:first_kana].to_hiragana}"
user_name += ")"
end
select_user_options << [user_name, u.id]
end
end
return select_user_options
end
#
# selectのoptions:会議室
#
def select_facility_options(facilities = {})
select_facility_options = []
if facilities.present? && facilities.size > 0
facilities.each do |f|
facility_name = f[:name]
if f[:sub_name].present?
facility_name += ":#{f[:sub_name]}"
end
select_facility_options << [facility_name, f.id]
end
end
return select_facility_options
end
#
# 会議室名の成型
#
def facility_name(facility = {})
facility_name = facility[:name]
if facility[:sub_name].present?
facility_name += ":#{facility[:sub_name]}"
end
return facility_name
end
end
| true |
ffab0ede5c5e7d87cba8852e39a890bf3b7db3a6 | Ruby | arimay/time_scheduler | /sample/base_8.rb | UTF-8 | 391 | 2.953125 | 3 | [
"MIT"
] | permissive | require "time_scheduler"
Scheduler = TimeScheduler.new
cyclic1 = {
msec: "*/100"
}
cyclic2 = {
sec: "*/2"
}
Scheduler.wait( **cyclic1 ) do |time|
p [time.iso8601(3), :cyclic1]
end
goal = Time.now + 5
Scheduler.wait( **cyclic2 ) do |time|
p [time.iso8601(3), :cyclic2]
if time > goal
p [time.iso8601(3), :quit]
exit
end
end
p [Time.now.iso8601(3), :ready]
sleep
| true |
5556c29c4c3fa92cdd05f31364271dc5b1cd9b56 | Ruby | cgaraudy/ruby_practice | /bartender.rb | UTF-8 | 287 | 4.15625 | 4 | [] | no_license | puts "Hey, what ya drinkin'?"
answer = gets.chomp
puts "Okay, cool, one #{answer} coming right up. Wait, how old are you?"
age = gets.to_i
x = 21 - age
if age >= 21
puts "Right on."
else
puts "I can't serve you. You have to wait #{x} years 'til you're old enough to drink."
end
| true |
c7862e7a9ed49e00739a2a2d8e6ec15bfc2f0c86 | Ruby | stuarthalloway/relevance-ruby-samples | /rails_samples/vendor/plugins/relevance_tools/test/relevance/object_additions_test.rb | UTF-8 | 838 | 2.671875 | 3 | [
"MIT"
] | permissive | require File.join(File.dirname(__FILE__), "/../test_helper")
require 'relevance/object_additions'
class ObjectAdditionsTest < Test::Unit::TestCase
def test_should_get_metaclass
obj = Object.new
metaklass = (class << obj; self; end;)
assert_equal metaklass, obj.metaclass
end
def test_should_be_able_to_add_methods_to_the_meta_class
obj = Object.new
obj.meta_def(:speak) { "bark!" }
assert obj.respond_to?(:speak)
another_obj = Object.new
assert_false another_obj.respond_to?(:speak)
end
class Foo; end
def test_should_be_able_to_define_instance_methods_from_the_class
Foo.class_def(:hi) { "hello!" }
assert_equal "hello!", Foo.new.hi
assert_false Foo.respond_to?(:hi)
end
def test_assert_big_decimal
assert 'Object Addition Test', self.class_titleize
end
end | true |
e7e1dfd144d8caaf344960dbb94494d719de28b3 | Ruby | JNaftali/phase-0-tracks | /ruby/secret_agents.rb | UTF-8 | 1,303 | 4.75 | 5 | [] | no_license | #loop through each letter of the string.
#increase each letter, using a counter
#to keep track of where it is in the word
#
def encrypt (greeting)
letter = 0
result = ""
# use the index to print
while letter < greeting.length
if greeting[letter] == "z"
result += "a"
elsif greeting[letter] == " "
result += " "
else
result += greeting[letter].next
end
letter += 1
end
p result
end
#add the alphabet in one string
#find the index of each letter in the alphabet, subtract one, and add that letter to result
#special rules for "a" and " "
def decrypt (greeting)
letter = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
result = ""
while letter < greeting.length
if greeting[letter] == "a"
result += "z"
elsif greeting[letter] == " "
result += " "
else
result += alphabet[alphabet.index(greeting[letter]) - 1]
end
letter += 1
end
p result
end
#decrypt(encrypt("swordfish"))
#calls decrypt on the result of encrypt, which turns it back to "swordfish"
puts "Would you like to encrypt or decrypt a password?"
answer = gets.chomp
puts "What is your password?"
password = gets.chomp
if answer == "encrypt"
encrypt(password)
elsif answer == "decrypt"
decrypt(password)
else
puts "Invalid input."
end | true |
7244ab0b33133a8104faba7b1c4b137e8c8dbb40 | Ruby | ggwc82/takeaway-challenge | /lib/menu.rb | UTF-8 | 119 | 2.5625 | 3 | [] | no_license | class Menu
def initialize
@show = {ribs: 3, beef: 4, rolls: 3, chips: 2, pies: 5}
end
attr_reader :show
end | true |
3f69ec5440e07bb09a795804678c55847d27925b | Ruby | perplexes/porcupine | /lib/porcupine/dataflow/map_reduce.rb | UTF-8 | 1,290 | 2.921875 | 3 | [
"MIT"
] | permissive | class Porcupine
# In MapReduce terms, this is Input/Map together.
# Map and Reduce, at least in framework code, are the same.
class MapFunction < Porcupine
def getFallback
[]
end
end
# TODO: This doesn't take into account other threads working currently,
# we need some thread sharing instead of thread shedding.
THREADS = 10
class MapReduce < Link
# Block must accept an array of objects and emit [key, [value]] pairs
def initialize(instance_name, group_name, map_function_class=MapFunction, threads=THREADS, &block)
super(instance_name, group_name, &nil)
@threads = threads || THREADS
@map_function_class = map_function_class || MapFunction
@map = block
end
# TODO: Instance, group names
def call(enumerable)
enumerable.each_slice(slice_size(enumerable)).map.with_index do |objects, index|
@map_function_class.new(instance_name + "::index:#{index}", group_name) do
@map.call(objects)
end.queue
end.map(&:get).inject({}) do |hash, pairs|
pairs.each do |key, value|
hash[key] ||= []
hash[key] << value
end
hash
end
end
private
def slice_size(enumerable)
[enumerable.size/@threads, 1].max
end
end
end | true |
b3a8bd65eb926725f41900268098b821c6a9d946 | Ruby | busyra/proga | /output.rb | UTF-8 | 2,893 | 3.640625 | 4 | [] | no_license | class Output
require 'pry'
def initialize
@dependent_hash = {}
@installed_components = []
read_text
end
def process(command, components)
if command == 'DEPEND' then depends(components)
elsif command == 'INSTALL' then installs(components)
elsif command == 'REMOVE' then removes(components)
elsif command == 'LIST' then lists(components)
else
end_prog
end
end
def depends(components)
main_component = components.shift
dependencies = components
new_hash = {}
new_hash[main_component] = dependencies
@dependent_hash.merge!(new_hash)
end
def installs(component)
if @installed_components.include? component[0].to_s
puts ' ' + component[0].to_s + ' is already installed.'
elsif @dependent_hash.key?(component[0])
add_with_dependencies(component)
else
@installed_components << component[0]
puts ' Installing ' + component[0].to_s
end
end
def removes(component)
if !@installed_components.include? component[0]
puts ' ' + component[0] + ' is not installed'
elsif @dependent_hash.key?(component[0])
remove_with_dependencies(component)
# checks if components is val to any other component key in @dependents_hash
# checks if component key is in @installed_components
# removes from component from @installed_components
elsif !dependent_to_installed(component[0])
@installed_components.delete(component[0])
puts ' Removing ' + component[0]
else
puts ' Can not remove ' + component[0]
end
end
def lists(components)
puts @installed_components
end
private
def read_text
File.open('input.txt').each do |line|
puts line
command = parse_command(line)
components = parse_components(line)
process(command, components)
end
end
def parse_command(line)
line.split.first
end
def parse_components(line)
components_array = line.split
components_array.shift
components_array
end
def add_with_dependencies(component)
@installed_components << component[0]
puts ' Installing ' + component[0].to_s
@dependent_hash[component[0]].each do |x|
if @installed_components.include? x
puts ' ' + x + ' is already installed.'
else
@installed_components << x
puts ' Installing ' + x
end
end
end
def remove_with_dependencies(component)
@installed_components.delete(component[0])
puts ' Removing!! ' + component[0].to_s
@dependent_hash[component[0]].each do |x|
if !dependent_to_installed(x)
@installed_components.delete(x)
puts ' REMOVING!!!!!! ' + x
end
end
end
def dependent_to_installed(component)
# check for if component is value in the dependent_hash
# and key is currently in @installed_components
end
def end_prog; end
self
end.new
| true |
0443abfc59322836d617394bfa5629c5b08e0188 | Ruby | pry/pry-exception_explorer | /lib/pry-exception_explorer/commands.rb | UTF-8 | 3,511 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'pry-stack_explorer'
module PryExceptionExplorer
module ExceptionHelpers
include PryStackExplorer::FrameHelpers
private
def exception
frame_manager.user[:exception]
end
def in_exception?
frame_manager && exception
end
def last_exception
_pry_.last_exception
end
def enterable_exception?(ex=last_exception)
PryExceptionExplorer.enabled && ex && ex.exception_call_stack
end
def inline_exception?
in_exception? &&
frame_manager.user[:inline_exception]
end
def internal_exception?
in_exception? && exception.internal_exception?
end
def normal_exception?
in_exception? && frame_manager.user[:exception].continuation
end
end
Commands = Pry::CommandSet.new do
create_command "enter-exception", "Enter the context of the last exception" do
include PryExceptionExplorer::ExceptionHelpers
banner <<-BANNER
Usage: enter-exception
Enter the context of the last exception
BANNER
def process
ex = extract_exception
if enterable_exception?(ex)
PryStackExplorer.create_and_push_frame_manager(ex.exception_call_stack, _pry_)
PryExceptionExplorer.setup_exception_context(ex, _pry_)
# have to use _pry_.run_command instead of 'run' here as
# 'run' works on the current target which hasnt been updated
# yet, whereas _pry_.run_command operates on the newly
# updated target (the context of the exception)
_pry_.run_command "cat --ex 0"
elsif ex
raise Pry::CommandError, "Exception can't be entered! (perhaps an internal exception)"
else
raise Pry::CommandError, "No exception to enter!"
end
end
def extract_exception
if !arg_string.empty?
ex = target.eval(arg_string)
raise if !ex.is_a?(Exception)
ex
else
last_exception
end
rescue
raise Pry::CommandError, "Parameter must be a valid exception object."
end
end
create_command "exit-exception", "Leave the context of the current exception." do
include ExceptionHelpers
banner <<-BANNER
Usage: exit-exception
Exit active exception and return to containing context.
BANNER
def process
if !in_exception?
raise Pry::CommandError, "You are not in an exception!"
elsif !prior_context_exists?
run "exit-all"
else
popped_fm = PryStackExplorer.pop_frame_manager(_pry_)
_pry_.last_exception = popped_fm.user[:exception]
end
end
end
create_command "continue-exception", "Attempt to continue the current exception." do
include ExceptionHelpers
banner <<-BANNER
Usage: continue-exception
Attempt to continue the current exception.
BANNER
def process
if internal_exception?
raise Pry::CommandError, "Internal exceptions (C-level exceptions) cannot be continued!"
elsif inline_exception?
PryStackExplorer.pop_frame_manager(_pry_)
run "exit-all PryExceptionExplorer::CONTINUE_INLINE_EXCEPTION"
elsif normal_exception?
popped_fm = PryStackExplorer.pop_frame_manager(_pry_)
popped_fm.user[:exception].continue
else
raise Pry::CommandError, "No exception to continue!"
end
end
end
end
end
| true |
0edf80aa5425768e820c112ddf8da2f06d0399a6 | Ruby | rmeritz/coursera | /algorithms-divide-conquer/sort.rb | UTF-8 | 3,831 | 3.171875 | 3 | [] | no_license | #!/usr/bin/env ruby
gem 'minitest'
require "minitest/autorun"
class Array
def swap!(a, b)
self[a], self[b] = self[b], self[a]
self
end
end
class Sort
def brute_force_sort l
naive_sort([], l)
end
def merge_sort l
len = l.length
if len <= 1
l
else
merge(merge_sort(l.take(len/2)), merge_sort(l.drop(len/2)))
end
end
def quick_sort l
if l.length <= 1
l
else
pivot, rest_of_list = choose_pivot(l)
less_than_pivot, greater_than_pivot = partition(pivot, rest_of_list)
quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
end
end
def inplace_quick_sort l
do_inplace_quick_sort l, 0, l.length - 1
end
private
def do_inplace_quick_sort l, left_most_bound, right_most_bound
if right_most_bound - left_most_bound <= 0
l
else
pivot_position = Random.new.rand(left_most_bound..right_most_bound)
pivot = l[pivot_position]
l.swap!(left_most_bound, pivot_position)
less_than_pivot_bound = left_most_bound + 1
for j in (less_than_pivot_bound .. right_most_bound)
if l[j] < pivot
l.swap!(less_than_pivot_bound, j)
less_than_pivot_bound = less_than_pivot_bound + 1
end
end
l.swap!(left_most_bound, less_than_pivot_bound - 1)
do_inplace_quick_sort(l, left_most_bound, less_than_pivot_bound - 2)
do_inplace_quick_sort(l, less_than_pivot_bound, right_most_bound)
end
end
#############
def choose_pivot l
[l.first, l.drop(1)]
end
def partition pivot, rest_of_list
less_than_pivot, greater_than_pivot = [], []
rest_of_list.each do |e|
if e > pivot
greater_than_pivot << e
else
less_than_pivot << e
end
end
[less_than_pivot, greater_than_pivot]
end
#####################
def merge(a, b)
do_merge(a, b, [])
end
def do_merge(a, b, merged_list)
if a.first.nil?
merged_list + b
elsif b.first.nil?
merged_list + a
elsif a.first < b.first
do_merge(a.drop(1), b, merged_list << a.first)
elsif a.first >= b.first
do_merge(a, b.drop(1), merged_list << b.first)
end
end
######################
def naive_sort(sorted, unsorted)
if unsorted.empty?
sorted
else
naive_sort(simple_insert(sorted, 0, unsorted.shift), unsorted)
end
end
def simple_insert(sorted, sorted_pointer, to_insert)
if sorted[sorted_pointer].nil?
sorted + [to_insert]
elsif to_insert < sorted[sorted_pointer]
sorted.take(sorted_pointer) + [to_insert] + sorted.drop(sorted_pointer)
else
simple_insert sorted, sorted_pointer + 1, to_insert
end
end
end
class SortTest < Minitest::Test
def setup
@sort = Sort.new
@sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@already_sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@backwards = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
@random = [6, 1, 10, 9, 5, 8, 7, 4, 2, 3]
end
def test_brute_force_sort
assert_equal @sorted, @sort.brute_force_sort(@already_sorted)
assert_equal @sorted, @sort.brute_force_sort(@backwards)
assert_equal @sorted, @sort.brute_force_sort(@random)
end
def test_merge_sort
assert_equal @sorted, @sort.merge_sort(@already_sorted)
assert_equal @sorted, @sort.merge_sort(@backwards)
assert_equal @sorted, @sort.merge_sort(@random)
end
def test_quick_sort
assert_equal @sorted, @sort.quick_sort(@already_sorted)
assert_equal @sorted, @sort.quick_sort(@backwards)
assert_equal @sorted, @sort.quick_sort(@random)
end
def test_inplace_quick_sort
assert_equal @sorted, @sort.inplace_quick_sort(@already_sorted)
assert_equal @sorted, @sort.inplace_quick_sort(@backwards)
assert_equal @sorted, @sort.inplace_quick_sort(@random)
end
end
| true |
6ba31cb491a17254f4d81ec6452921c80f78065c | Ruby | michaelsmith19951/isbn_number_web_app | /app.rb | UTF-8 | 1,179 | 2.984375 | 3 | [] | no_license | require "sinatra"
require_relative "isbn_functions.rb"
enable :sessions
get '/' do
isbn_output = params[:isbn_output]
validity_final = params[:validity_final]
isbn_orig = params[:isbn_orig]
isbn2 = params[:isbn2]
erb :isbn_number_main_page, locals:{isbn2: isbn2, isbn_output: isbn_output, isbn_orig: isbn_orig, validity_final: validity_final}
end
post '/isbn_number_main_page' do
puts params
isbn = params[:isbn]
p "test if isbn is #{isbn} on main page"
isbn2 = isbn.split
p "#{isbn2} is isbn2 and #{isbn2.class} is isbn2 class and #{isbn2.length} is isbn2 length on main page"
isbn_output = {}
isbn2.each do
for isbn in isbn2
isbn_output["Validity"] = choose_isbn10_or_isbn13(isbn)
end
isbn_output["Validity"]
end
isbn2.each do
for isbn in isbn2
isbn_output["ISBN"] = isbn
end
isbn_output["ISBN"]
end
isbn_orig = isbn_output.values
validity_final = isbn_output.values
p "test if isbn orig class is #{isbn_orig.class} on main page"
p "test if validity final class is #{validity_final.class} on main page"
erb :isbn_number_main_page, locals:{isbn2: isbn2, isbn_output: isbn_output, isbn_orig: isbn_orig, validity_final: validity_final}
end | true |
8b61e7e09b1c2a74a666cda09c4e1a02477f6dca | Ruby | wildDAlex/rus_bank | /test/test_rus_bank.rb | UTF-8 | 4,099 | 2.640625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # encoding: utf-8
require "test_helper"
class TestRusBank < Test::Unit::TestCase
VALID_BIC = "044585216"
INVALID_BIC = "0445852169999"
VALID_INT_CODE = "450000650"
INVALID_INT_CODE = "450000650999999"
VALID_REG_NUMBER = "316"
INVALID_REG_NUMBER = "289375237580009"
VALID_REGION = "16"
INVALID_REGION = "999"
INVALID_ORG_NAME = "djhgsjdlksl"
VALID_ORG_NAME = "ХКФ БАНК"
context "RusBank" do
setup do
@cbr = RusBank.new
end
should "Service return implemented methods" do
assert_contains(@cbr.operations, :bic_to_int_code)
assert_contains(@cbr.operations, :bic_to_reg_number)
assert_contains(@cbr.operations, :enum_bic_xml)
assert_contains(@cbr.operations, :credit_info_by_int_code_xml)
end
should ":bic_to_int_code return correct value" do
assert_equal(VALID_INT_CODE, @cbr.BicToIntCode(VALID_BIC))
assert_equal(nil, @cbr.BicToIntCode(INVALID_BIC), "Should return nil if value not found")
end
should ":bic_to_reg_number return correct value" do
assert_equal(VALID_REG_NUMBER, @cbr.BicToRegNumber(VALID_BIC))
assert_equal(nil, @cbr.BicToRegNumber(INVALID_BIC), "Should return nil if value not found")
end
should ":reg_num_to_int_code return correct value" do
assert_equal(VALID_INT_CODE, @cbr.RegNumToIntCode(VALID_REG_NUMBER))
assert_equal(nil, @cbr.RegNumToIntCode(INVALID_REG_NUMBER), "Should return nil if value not found")
end
should ":int_code_to_reg_num return correct value" do
assert_equal(VALID_REG_NUMBER, @cbr.IntCodeToRegNum(VALID_INT_CODE))
assert_equal(nil, @cbr.IntCodeToRegNum(INVALID_INT_CODE), "Should return nil if value not found")
end
should ":enum_bic_xml returns array of elements" do
assert(@cbr.EnumBic.instance_of?(Array), "This should be array")
assert(@cbr.EnumBic.length > 100, "This should return more than 100 elements")
end
should ":regions_enum_xml returns array of elements" do
assert(@cbr.RegionsEnum.instance_of?(Array), "This should be array")
assert(@cbr.RegionsEnum.length > 70, "This should return more than 70 elements")
end
should ":search_by_region_code_xml returns array of elements" do
assert(@cbr.SearchByRegionCode(VALID_REGION).instance_of?(Array), "This should be array")
assert(@cbr.SearchByRegionCode(VALID_REGION).length > 10, "This should return more than 10 banks")
assert_equal(nil, @cbr.SearchByRegionCode(INVALID_REGION), "Should return nil if value not found")
end
should ":search_by_name_xml return correct value" do
assert(@cbr.SearchByName(VALID_ORG_NAME).instance_of?(Array), "This should be array")
assert_equal(VALID_ORG_NAME, @cbr.SearchByName(VALID_ORG_NAME).first[:org_name])
assert_equal(nil, @cbr.SearchByName(INVALID_ORG_NAME), "Should return nil if value not found")
end
should ":get_offices_xml returns array of elements" do
assert(@cbr.GetOffices(VALID_INT_CODE).instance_of?(Array), "This should be array")
assert(@cbr.GetOffices(VALID_INT_CODE).length > 2, "This should return more than 2 offices")
assert_equal(nil, @cbr.GetOffices(INVALID_INT_CODE), "Should return nil if value not found")
end
should ":get_offices_by_region_xml returns array of elements" do
assert(@cbr.GetOfficesByRegion(VALID_REGION).instance_of?(Array), "This should be array")
assert(@cbr.GetOfficesByRegion(VALID_REGION).length > 10, "This should return more than 10 offices")
assert_equal(nil, @cbr.GetOfficesByRegion(INVALID_REGION), "Should return nil if value not found")
end
should ":credit_info_by_int_code_xml return correct bank" do
assert_equal(VALID_REG_NUMBER, @cbr.CreditInfoByIntCode(VALID_INT_CODE)[:co][:reg_number])
assert_equal(VALID_ORG_NAME, @cbr.CreditInfoByIntCode(VALID_INT_CODE)[:co][:org_name])
assert_equal(VALID_BIC, @cbr.CreditInfoByIntCode(VALID_INT_CODE)[:co][:bic])
assert_equal(nil, @cbr.CreditInfoByIntCode(INVALID_INT_CODE), "Should return nil if value not found")
end
end
end
| true |
886ccfe75aa83d20be58b7868c6bd245149e7968 | Ruby | ZinChen/bakery-ruby | /bin/bakery_start.rb | UTF-8 | 1,002 | 3.015625 | 3 | [] | no_license | require_relative '../lib/bakery'
require_relative '../lib/order'
require_relative '../lib/order_breakdown'
require_relative '../lib/order_parser'
require_relative '../lib/product'
vegemite_scroll = Product.new('Vegemite Scroll', 'VS5')
blueberry_muffin = Product.new('Blueberry Muffin', 'MB11')
croissant = Product.new('Croissant', 'CF')
bakery = Bakery.new
bakery.add_package(vegemite_scroll, 3, 6.99)
bakery.add_package(vegemite_scroll, 5, 8.99)
bakery.add_package(blueberry_muffin, 2, 9.95)
bakery.add_package(blueberry_muffin, 5, 16.95)
bakery.add_package(blueberry_muffin, 8, 24.95)
bakery.add_package(croissant, 3, 5.95)
bakery.add_package(croissant, 5, 9.95)
bakery.add_package(croissant, 9, 16.99)
order_breakdown = OrderBreakdown.new(bakery)
order_parser = OrderParser.new
ARGF.each_line do |line|
begin
order_parser.parse(line)
order = order_breakdown.breakdown(order_parser.code, order_parser.quantity)
puts order.to_s
rescue StandardError => e
p e.message
end
end
| true |
d829c1606083c158c0f856d4030dcf0d54a3584e | Ruby | justindelatorre/rb_101 | /small_problems/easy_9/easy_9_4.rb | UTF-8 | 1,045 | 4.46875 | 4 | [] | no_license | =begin
Write a method that takes an integer argument, and returns an Array of all
integers, in sequence, between 1 and the argument.
You may assume that the argument will always be a valid integer that is greater
than 0.
Inputs:
- integer
Outputs:
- array (of integers)
Requirements:
- output array should include integers in sequence from 1 to argument
Questions:
- How to handle non-integer, negative, 0, or empty arguments?
Abstraction:
- Initialize empty target array
- Initialize counter variable at 1
- While counter is less than or equal to argument integer, loop
- Add current counter value to target array
- Increment counter by 1
- Return target array
Examples:
sequence(5) == [1, 2, 3, 4, 5]
sequence(3) == [1, 2, 3]
sequence(1) == [1]
=end
def sequence(num)
arr = []
counter = 1
while counter <= num
arr << counter
counter += 1
end
arr
end
p sequence(5) == [1, 2, 3, 4, 5]
p sequence(3) == [1, 2, 3]
p sequence(1) == [1]
=begin
Alternate solution:
def sequence(number)
(1..number).to_a
end
=end
| true |
13ff474119e1b3e86d72d124391597b3c7651daa | Ruby | grh/scavenger-hunt | /lib/tasks/our_doc.rb | UTF-8 | 3,818 | 2.9375 | 3 | [] | no_license | module OurDoc
class Comment
attr_accessor :type, :content
def initialize (type)
@type = type
@content = []
end
end
def self.get_comments(t)
# initialize empty comments array and grab all .rb files
comments = []
rbfiles = File.join('**', '*.rb')
# iterate over every .rb file
Dir.glob(rbfiles).each do |file|
File.open(file) do |f|
while line = f.gets
# grab each line and remove leading whitespace and newline
line.lstrip!; line.chomp!
# similar to rdoc, a comment is signalled by '=begin'
if line == '=begin'
# read the next line and get the type
type = f.gets.split[1].downcase.to_sym
if type == t
# create a new comment object of that type
comment = Comment.new(type) if type == t
while true
# keep grabbing lines until '=end'
line = f.gets.chomp; line.lstrip!
case line[0..1]
when '=e' # end of comment
break
when '' # skip blank lines
next
when '= ' # h3 tags
comment.content << { h3: line.split[1..-1].join(' ') }
when '* ' # ul and li tags
li = []
while line[0..1] == '* '
li << line.split(' ', 2)[1]
line = f.gets.chomp; line.lstrip!
end
comment.content << { ul: li }
else # p tags
str = ''
until line.empty?
str += line + ' '
line = f.gets.chomp; line.lstrip!
end
str.lstrip!
comment.content << { p: str }
end
end
comments << comment if type == t
end
end
end
end
end
return comments
end
def self.write_comments(comments)
type = comments.first.type.to_s
basedir_str = 'app/views/html'
provides_str = "<%= provide(:title, '#{type.capitalize}') %>"
container_div = '<div class="container">'
row_div = '<div class="row">'
col9_div = '<div class="col-md-9 col-centered">'
col10_div = '<div class="col-md-11 col-md-offset-2 col-centered" style="padding-top:1em;">'
div_close = '</div>'
File.open("#{basedir_str}/#{type}_doc.html.erb", 'w') do |f|
f.puts provides_str
f.puts container_div
f.puts row_div
f.puts col9_div
f.puts "<h3>#{type.capitalize}</h3>"
# start iterating over the about comments...
comments.each do |comment|
comment.content.each do |item|
for k, v in item
case k
when :h3
f.puts div_close
f.puts div_close
f.puts row_div
f.puts col9_div
f.puts ("<h3>#{v.capitalize}</h3>")
when :p
f.puts row_div
f.puts col10_div
f.puts ("<p>#{v}</p>")
f.puts div_close
f.puts div_close
when :ul
f.puts row_div
f.puts col10_div
f.puts '<ul>'
v.each do |li|
f.puts "<li>#{li}</li>"
end
f.puts '</ul>'
f.puts div_close
f.puts div_close
end
end
end
end
f.puts div_close
f.puts div_close
f.puts div_close
end
end
end
| true |
4645ada299b984215373b59e75e12bcb8743d646 | Ruby | mystioreo/array_intersection | /lib/array_intersection.rb | UTF-8 | 440 | 3.5625 | 4 | [] | no_license | #space complexity O[n], time complexity O[n*m]
# Creates a new array to return the intersection of the two input arrays
def intersection(array1, array2)
i = 0
intersect = []
unless array1 == nil || array2 == nil
until array1[i] == nil
j = 0
until array2[j] == nil
if array1[i] == array2[j]
intersect << array1[i]
end
j += 1
end
i += 1
end
end
return intersect
end
| true |
f11afe7239a581f457f62a648e93ca15327d65ac | Ruby | jeffreyzhen/chillow | /lib/dwelling.rb | UTF-8 | 236 | 3.0625 | 3 | [] | no_license | class Dwelling
attr_reader :address, :city_or_town, :state, :zipcode
def initialize(address, city_or_town, state, zipcode)
@address = address
@city_or_town = city_or_town
@state = state
@zipcode = zipcode
end
end
| true |
06fa42a2c8bf5d95fd28d60213781822df61f827 | Ruby | EJLarcs/playlister-cli-web-0715-public | /app/models/artist.rb | UTF-8 | 1,060 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
require_relative 'song'
require_relative 'genre'
class Artist
# code here
#attr_reader as genres
attr_accessor :name, :song, :genres
@@artists = []
def initialize(name=nil)
@name = name
@@artists << self
@songs = []
@genres = []
end
def self.all
@@artists
end
def self.reset_all
@@artists = []
end
def self.count
@@artists.length
end
def self.find_by_name(name)
@@artists.each { |object| return object if object.name = name }
end
def self.create_by_name(name)
Artist.new(name)
end
def add_songs(songs)
songs.each { |song| @songs << song }
end
def add_song(song)
@songs << song
song.artist = self
@genres << song.genre unless @genres.include?(song.genre)
if song.genre
song.genre.artists = [] unless song.genre.artists
song.genre.artists << self unless song.genre.artists.include?(self)
end
end
def songs
@songs
end
end
# genre_object.add_artist(self)
# binding.pry
#if that song has a genre shouldnt that artist have a genre
| true |
3370bb8a536d80c6d9021a773da97af9e2200c4a | Ruby | lrnzgll/newgps | /app/services/weather.rb | UTF-8 | 258 | 2.6875 | 3 | [] | no_license | module Weather
attr_reader :lat, :lng, :location
def initialize(lat,lng, location = nil)
@lat = lat
@lng = lng
@forecast ||= ForecastIO.forecast(@lat,@lng, params:{ exclude: 'flags,minutely,hourly,alert'})
@location = location
end
end
| true |
ef0ea433239728fa28b9e13cf06903a2d4cd5f4a | Ruby | kathleen-carroll/backend_module_0_capstone | /day_7/ceaser_cipher.rb | UTF-8 | 731 | 3.296875 | 3 | [] | no_license | cipher = {
'A' => 'X',
'B' => 'Y',
'C' => 'Z',
'D' => 'A',
'E' => 'B',
'F' => 'C',
'G' => 'D',
'H' => 'E',
'I' => 'F',
'J' => 'G',
'K' => 'H',
'L' => 'I',
'M' => 'J',
'N' => 'K',
'O' => 'L',
'P' => 'M',
'Q' => 'N',
'R' => 'O',
'S' => 'P',
'T' => 'Q',
'U' => 'R',
'V' => 'S',
'W' => 'T',
'X' => 'U',
'Y' => 'V',
'Z' => 'W',
' ' => ' '
}
#alphabet = ("A".."Z").to_a
#puts alphabet
string = "Hello World"
letters= Array(string.upcase.split(//))
puts string.upcase.split(//)[1]
puts letters
puts letters.first
puts letters[1]
#puts letters(1)
cipher.each do |alph, ciph|
if string.upcase.split(//) [0] == alph
puts ciph
elsif letters[1] == alph
puts ciph
else "no"
end
end
| true |
60b3bec6bd3fb78ba35057c04a4f9526887f052e | Ruby | garedean/tamagotchi_sinatra | /spec/tamagotchi_spec.rb | UTF-8 | 1,271 | 3.265625 | 3 | [] | no_license | require('rspec')
require('tamagotchi')
require('pry')
describe('Tamagotchi') do
describe('#name') do
# get name
it('returns the name string') do
expect(Tamagotchi.new('Bob').name).to(eq('Bob'))
end
# set name
it('sets a name for the tamagotchi') do
expect(Tamagotchi.new('Bob').name = 'Bill').to(eq('Bill'))
end
end
describe('#food_level') do
it('checks the food level') do
expect(Tamagotchi.new('a').food_level).to(eq(10))
end
it('sets the food level') do
expect(Tamagotchi.new('a').food_level = 5).to(eq(5))
end
end
describe('#feed') do
it('feeds if hungry') do
expect(Tamagotchi.new('aa').feed).to(eq(20))
end
it("doesn't feed if not hungry") do
critter = Tamagotchi.new('aa')
critter.food_level = 80
critter.feed(15)
expect(critter.food_level).to(eq(80))
end
end
describe('#dead?') do
it('returns dead if the food level is 0 or 100') do
critter = Tamagotchi.new('b')
critter.food_level = 0
expect(critter.dead?).to(eq(true))
end
end
describe('#hungry?') do
it('indicates whether critter is hungry') do
critter = Tamagotchi.new('c')
expect(critter.hungry?).to(eq(true))
end
end
end
| true |
a88aedbf52aa9c6e8b1784ea82587f5523f2b1fc | Ruby | jasonporritt/Hextown | /src/hexagon.rb | UTF-8 | 1,410 | 3 | 3 | [] | no_license | #class HexagonView < ActorView
# def draw(target, x_off, y_off, z)
# radius = 25
# x = @actor.x + x_off - radius
# y = @actor.y + y_off - radius
#
# rotation = @actor.rotation
# draw_ngon target, x,y, rotation, radius, 6, [200,200,255,140], z
# target.draw_line x,y, x+offset_x(rotation,radius), y+offset_y(rotation,radius), [200,200,255.140], z
#
# end
#
# def draw_ngon(target, cx,cy,a,r,sides,color, z)
# x1, y1 = offset_x(a, r), offset_y(a, r)
# angle = (360.0/sides)
# (1..sides).each { |s|
# x2, y2 = offset_x(angle*s + a, r), offset_y(angle*s + a, r)
# target.draw_line cx + x1, cy + y1, cx + x2, cy + y2, color, z
# x1, y1 = x2, y2
# }
# end
#end
class Hexagon < Actor
attr_accessor :stuck_to_player, :player_attractor
@stuck_to_player = false
def self.get_verts()
angle = (360.0/6)
r = 25
verts = (1..6).map { |s| [offset_x(angle*s,r), offset_y(angle*s,r)] }.reverse
end
has_behaviors :graphical,:updatable, :physical => {
:shape => :poly,
#:verts => verts,
:verts => Hexagon::get_verts(),
:mass => 10,
:elasticity => 0,
:friction => 0.4,
#:moment => 500
}
def edge_nearest(vector)
Hexagon::get_verts.map { |v|
{:distance => Math.sqrt( (x + v[0] - other_x)**2 + (y + v[1] - other_y)**2 ), :vert => v}
}.sort_by! { |e| e[:distance] }.take(2).map { |e| e[:vert] }
end
end
| true |
ff0cda846f1c0edc9e3d58c519f2bc9fa33e9604 | Ruby | daniero/code-challenges | /aoc2018/ruby/15/io.rb | UTF-8 | 1,167 | 3.921875 | 4 | [] | no_license | require 'set'
ATTACK = 3
HEALTH = 200
Unit = Struct.new(:x, :y, :team, :hp, :attack)
def read_input(filename)
units = Set[]
walls = Set[]
height = 0
width = 0
File.open(filename).each_line.with_index do |row, y|
row.chomp.each_char.with_index do |cell, x|
if cell == 'E'
units << Unit.new(x,y, :elf, HEALTH, ATTACK)
elsif cell == 'G'
units << Unit.new(x,y, :goblin, HEALTH, ATTACK)
elsif cell == '#'
walls << [x,y]
end
width = x + 1
end
height = y + 1
end
return units, walls.freeze, width, height
end
def print_state(width, height, units, walls)
puts height.times.map { |y|
width.times.map { |x|
next '#' if walls.include? [x,y]
units_at_spot = units.select { |unit| unit.x == x && unit.y == y }
next '·' if units_at_spot.empty?
alive_unit = units_at_spot.find { |unit| unit.hp > 0 }
if alive_unit && alive_unit.team == :elf
"\e[31mE\e[0m"
elsif alive_unit
"\e[32mG\e[0m"
elsif units_at_spot.first.team == :elf
"\e[31m✝\e[0m"
else
"\e[32m✝\e[0m"
end
}.join
}.join("\n")
end
| true |
7378ce11626b08872768204001fa5a650bc05a29 | Ruby | CartoDB/cartodb | /spec/helpers/unique_names_helper.rb | UTF-8 | 819 | 2.625 | 3 | [
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
] | permissive | # These helpers are meant to be used in tests to generate random data which may collide, e.g: usernames
# The methods are parameter-less in purpose, so it is easier to modify the name generation if needed
module UniqueNamesHelper
@@item_count = 0
def unique_string
sprintf '%08d', unique_integer
end
def unique_email
r = unique_string
"e#{r}@d#{r}.com"
end
def unique_name(prefix)
prefix + unique_string
end
def unique_integer
@@item_count += 1
test_run_id * 1000000 + @@item_count
end
def test_run_id
@@test_run_id ||= if ENV['PARALLEL_SEQ']
ENV['PARALLEL_SEQ'].to_i
elsif ENV['CHECK_SPEC']
ENV['CHECK_SPEC'].to_i
else
0
end
end
end
| true |
f78a7b66d03115402d41eadde82f7dfb6a3b2e20 | Ruby | hectorip/Ruby-Exercises | /Easy/SelfDescribingNumbers.rb | UTF-8 | 588 | 3.375 | 3 | [] | no_license | File.open(ARGV[0]).each_line do |line|
line.strip!
if line != ''
digits = []
success = true
line.each_char.with_index do | digit, index |
n = digit.to_i
if(digits[index] == nil)
digits[index] = [n,0]
else
digits[index][0] = n
end
if digits[n] != nil
digits[n][1] += 1
else
digits[n] = [0,1]
end
end
digits.each do |d|
unless d[0] == d[1]
puts '0'
success = false
break
end
end
if success
puts 1
end
end
end | true |
8136a69c322fd4c862d57abb67b83fbc2d982ad5 | Ruby | leav/S.TEST | /Scripts/Game_ActionResult.rb | UTF-8 | 6,745 | 3.046875 | 3 | [] | no_license | #encoding:utf-8
#==============================================================================
# ■ Game_ActionResult
#------------------------------------------------------------------------------
# 战斗行动结果的管理类。本类在 Game_Battler 类的内部使用。
#==============================================================================
class Game_ActionResult
#--------------------------------------------------------------------------
# ● 定义实例变量
#--------------------------------------------------------------------------
attr_accessor :used # 使用的标志
attr_accessor :missed # 命中失败的标志
attr_accessor :evaded # 回避成功的标志
attr_accessor :critical # 关键一击的标志
attr_accessor :success # 成功的标志
attr_accessor :hp_damage # HP 伤害
attr_accessor :mp_damage # MP 伤害
attr_accessor :tp_damage # TP 伤害
attr_accessor :hp_drain # HP 吸收
attr_accessor :mp_drain # MP 吸收
attr_accessor :added_states # 被附加的状态
attr_accessor :removed_states # 被解除的状态
attr_accessor :added_buffs # 被附加的能力强化
attr_accessor :added_debuffs # 被附加的能力弱化
attr_accessor :removed_buffs # 被解除的强化/弱化
#--------------------------------------------------------------------------
# ● 初始化对象
#--------------------------------------------------------------------------
def initialize(battler)
@battler = battler
clear
end
#--------------------------------------------------------------------------
# ● 清除
#--------------------------------------------------------------------------
def clear
clear_hit_flags
clear_damage_values
clear_status_effects
end
#--------------------------------------------------------------------------
# ● 清除命中的标志
#--------------------------------------------------------------------------
def clear_hit_flags
@used = false
@missed = false
@evaded = false
@critical = false
@success = false
end
#--------------------------------------------------------------------------
# ● 清除伤害值
#--------------------------------------------------------------------------
def clear_damage_values
@hp_damage = 0
@mp_damage = 0
@tp_damage = 0
@hp_drain = 0
@mp_drain = 0
end
#--------------------------------------------------------------------------
# ● 生成伤害
#--------------------------------------------------------------------------
def make_damage(value, item)
@critical = false if value == 0
@hp_damage = value if item.damage.to_hp?
@mp_damage = value if item.damage.to_mp?
@mp_damage = [@battler.mp, @mp_damage].min
@hp_drain = @hp_damage if item.damage.drain?
@mp_drain = @mp_damage if item.damage.drain?
@hp_drain = [@battler.hp, @hp_drain].min
@success = true if item.damage.to_hp? || @mp_damage != 0
end
#--------------------------------------------------------------------------
# ● 清除状态效果
#--------------------------------------------------------------------------
def clear_status_effects
@added_states = []
@removed_states = []
@added_buffs = []
@added_debuffs = []
@removed_buffs = []
end
#--------------------------------------------------------------------------
# ● 获取被附加的状态的实例数组
#--------------------------------------------------------------------------
def added_state_objects
@added_states.collect {|id| $data_states[id] }
end
#--------------------------------------------------------------------------
# ● 获取被解除的状态的实例数组
#--------------------------------------------------------------------------
def removed_state_objects
@removed_states.collect {|id| $data_states[id] }
end
#--------------------------------------------------------------------------
# ● 判定是否受到任何状态的影响
#--------------------------------------------------------------------------
def status_affected?
!(@added_states.empty? && @removed_states.empty? &&
@added_buffs.empty? && @added_debuffs.empty? && @removed_buffs.empty?)
end
#--------------------------------------------------------------------------
# ● 判定最后是否命中
#--------------------------------------------------------------------------
def hit?
@used && !@missed && !@evaded
end
#--------------------------------------------------------------------------
# ● 获取 HP 伤害的文字
#--------------------------------------------------------------------------
def hp_damage_text
if @hp_drain > 0
fmt = @battler.actor? ? Vocab::ActorDrain : Vocab::EnemyDrain
sprintf(fmt, @battler.name, Vocab::hp, @hp_drain)
elsif @hp_damage > 0
fmt = @battler.actor? ? Vocab::ActorDamage : Vocab::EnemyDamage
sprintf(fmt, @battler.name, @hp_damage)
elsif @hp_damage < 0
fmt = @battler.actor? ? Vocab::ActorRecovery : Vocab::EnemyRecovery
sprintf(fmt, @battler.name, Vocab::hp, -hp_damage)
else
fmt = @battler.actor? ? Vocab::ActorNoDamage : Vocab::EnemyNoDamage
sprintf(fmt, @battler.name)
end
end
#--------------------------------------------------------------------------
# ● 获取 MP 伤害的文字
#--------------------------------------------------------------------------
def mp_damage_text
if @mp_drain > 0
fmt = @battler.actor? ? Vocab::ActorDrain : Vocab::EnemyDrain
sprintf(fmt, @battler.name, Vocab::mp, @mp_drain)
elsif @mp_damage > 0
fmt = @battler.actor? ? Vocab::ActorLoss : Vocab::EnemyLoss
sprintf(fmt, @battler.name, Vocab::mp, @mp_damage)
elsif @mp_damage < 0
fmt = @battler.actor? ? Vocab::ActorRecovery : Vocab::EnemyRecovery
sprintf(fmt, @battler.name, Vocab::mp, -@mp_damage)
else
""
end
end
#--------------------------------------------------------------------------
# ● 获取 TP 伤害的文字
#--------------------------------------------------------------------------
def tp_damage_text
if @tp_damage > 0
fmt = @battler.actor? ? Vocab::ActorLoss : Vocab::EnemyLoss
sprintf(fmt, @battler.name, Vocab::tp, @tp_damage)
elsif @tp_damage < 0
fmt = @battler.actor? ? Vocab::ActorGain : Vocab::EnemyGain
sprintf(fmt, @battler.name, Vocab::tp, -@tp_damage)
else
""
end
end
end
| true |
565852f10e984a52d9b32c02e88734c85616fc7b | Ruby | eac/predictomatic | /lib/predictomatic/input/feature.rb | UTF-8 | 374 | 2.765625 | 3 | [] | no_license | module Predictomatic::Input
class Feature
attr_reader :name, :value
def initialize(name, value = nil)
@name = name
@value = value
end
def to_s
pair = [ escaped_name, value ]
pair.compact!
pair.join(':')
end
def escaped_name
escaped = name.to_s
escaped.gsub!(':', 'X')
escaped
end
end
end
| true |
dd72b9b3f06f79807ffba4d99a33bbb58f140911 | Ruby | eelsivart/nessus-report-downloader | /nessus6-report-downloader.rb | UTF-8 | 8,422 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env ruby
#################################################################################################
# Name: Nessus 6 Report Downloader
# Author: Travis Lee
#
# Version: 1.0
# Last Updated: 2/28/2016
#
# Description: Interactive script that connects to a specified Nessus 6 server using the
# Nessus REST API to automate mass report downloads. It has the ability to download
# multiple or all reports/file types/chapters and save them to a folder of
# your choosing. This has been tested with Nessus 6.5.5 and *should* work with
# Nessus 6+, YMMV.
#
# File types include: NESSUS, HTML, PDF, CSV, and DB.
#
# Chapter types include: Vulnerabilities By Plugin, Vulnerabilities By Host,
# Hosts Summary (Executive), Suggested Remediations, Compliance Check (Executive),
# and Compliance Check.
#
# Usage: ruby ./nessus6-report-downloader.rb
#
# Reference: https://<nessus-server>:8834/api
#
#################################################################################################
require 'net/http'
require 'fileutils'
require 'io/console'
require 'date'
require 'json'
# This method will download the specified file type from specified reports
def report_download(http, headers, reports, reports_to_dl, filetypes_to_dl, chapters_to_dl, rpath, db_export_pw)
begin
puts "\nDownloading report(s). Please wait..."
# if all reports are selected
if reports_to_dl[0].eql?("all")
reports_to_dl.clear
# re-init array with all the scan ids
reports["scans"].each do |scan|
reports_to_dl.push(scan["id"].to_s)
end
end
# iterate through all the indexes and download the reports
reports_to_dl.each do |rep|
rep = rep.strip
filetypes_to_dl.each do |ft|
# export report
puts "\n[+] Exporting scan report, scan id: " + rep + ", type: " + ft
path = "/scans/" + rep + "/export"
data = {'format' => ft, 'chapters' => chapters_to_dl, 'password' => db_export_pw}
resp = http.post(path, data.to_json, headers)
fileid = JSON.parse(resp.body)
# check export status
status_path = "/scans/" + rep + "/export/" + fileid["file"].to_s + "/status"
loop do
sleep(5)
puts "[+] Checking export status..."
status_resp = http.get(status_path, headers)
status_result = JSON.parse(status_resp.body)
break if status_result["status"] == "ready"
puts "[-] Export not ready yet, checking again in 5 secs."
end
# download report
puts "[+] Report ready for download..."
dl_path = "/scans/" + rep + "/export/" + fileid["file"].to_s + "/download"
dl_resp = http.get(dl_path, headers)
# create final path/filename and write to file
fname_temp = dl_resp.response["Content-Disposition"].split('"')
fname = "#{rpath}/#{fname_temp[1]}"
# write file
open(fname, 'w') { |f|
f.puts dl_resp.body
}
puts "[+] Downloading report to: #{fname}"
end
end
rescue StandardError => download_report_error
puts "\n\nError downloading report: #{download_report_error}\n\n"
exit
end
end
# This method will return a list of all the reports on the server
def get_report_list(http, headers)
begin
# Try and do stuff
path = "/scans"
resp = http.get(path, headers)
#puts "Number of reports found: #{reports.count}\n\n"
results = JSON.parse(resp.body)
printf("%-7s %-50s %-30s %-15s\n", "Scan ID", "Name", "Last Modified", "Status")
printf("%-7s %-50s %-30s %-15s\n", "-------", "----", "-------------", "------")
# print out all the reports
results["scans"].each do |scan|
printf("%-7s %-50s %-30s %-15s\n", scan["id"], scan["name"], DateTime.strptime(scan["last_modification_date"].to_s,'%s').strftime('%b %e, %Y %H:%M %Z'), scan["status"])
end
return results
rescue StandardError => get_scanlist_error
puts "\n\nError getting scan list: #{get_scanlist_error}\n\n"
exit
end
end
# This method will make the initial login request and set the token value to use for subsequent requests
def get_token(http, username, password)
begin
path = "/session"
data = {'username' => username, 'password' => password}
resp = http.post(path, data.to_json, 'Content-Type' => 'application/json')
token = JSON.parse(resp.body)
headers = {
"User-Agent" => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0',
"X-Cookie" => 'token=' + token["token"],
"Accept" => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
"Accept-Language" => 'en-us,en;q=0.5',
"Accept-Encoding" => 'text/html;charset=UTF-8',
"Cache-Control" => 'max-age=0',
"Content-Type" => 'application/json'
}
return headers
rescue StandardError => get_token_error
puts "\n\nError logging in/getting token: #{get_token_error}\n\n"
exit
end
end
### MAIN ###
puts "\nNessus 6 Report Downloader 1.0"
# Collect server info
print "\nEnter the Nessus Server IP: "
nserver = gets.chomp.to_s
print "Enter the Nessus Server Port [8834]: "
nserverport = gets.chomp.to_s
if nserverport.eql?("")
nserverport = "8834"
end
# https object
http = Net::HTTP.new(nserver, nserverport)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# Collect user/pass info
print "Enter your Nessus Username: "
username = gets.chomp.to_s
print "Enter your Nessus Password (will not echo): "
password = STDIN.noecho(&:gets).chomp.to_s
# login and get token cookie
headers = get_token(http, username, password)
# get list of reports
puts "\n\nGetting report list..."
reports = get_report_list(http, headers)
print "Enter the report(s) your want to download (comma separate list) or 'all': "
reports_to_dl = (gets.chomp.to_s).split(",")
if reports_to_dl.count == 0
puts "\nError! You need to choose at least one report!\n\n"
exit
end
# select file types to download
puts "\nChoose File Type(s) to Download: "
puts "[0] Nessus (No chapter selection)"
puts "[1] HTML"
puts "[2] PDF"
puts "[3] CSV (No chapter selection)"
puts "[4] DB (No chapter selection)"
print "Enter the file type(s) you want to download (comma separate list) or 'all': "
filetypes_to_dl = (gets.chomp.to_s).split(",")
if filetypes_to_dl.count == 0
puts "\nError! You need to choose at least one file type!\n\n"
exit
end
# see which file types to download
formats = []
cSelect = false
dbSelect = false
filetypes_to_dl.each do |ft|
case ft.strip
when "all"
formats.push("nessus")
formats.push("html")
formats.push("pdf")
formats.push("csv")
formats.push("db")
cSelect = true
dbSelect = true
when "0"
formats.push("nessus")
when "1"
formats.push("html")
cSelect = true
when "2"
formats.push("pdf")
cSelect = true
when "3"
formats.push("csv")
when "4"
formats.push("db")
dbSelect = true
end
end
# enter password used to encrypt db exports (required)
db_export_pw = ""
if dbSelect
print "\nEnter a Password to encrypt the DB export (will not echo): "
db_export_pw = STDIN.noecho(&:gets).chomp.to_s
print "\n"
end
# select chapters to include, only show if html or pdf is in file type selection
chapters = ""
if cSelect
puts "\nChoose Chapter(s) to Include: "
puts "[0] Vulnerabilities By Plugin"
puts "[1] Vulnerabilities By Host"
puts "[2] Hosts Summary (Executive)"
puts "[3] Suggested Remediations"
puts "[4] Compliance Check (Executive)"
puts "[5] Compliance Check"
print "Enter the chapter(s) you want to include (comma separate list) or 'all': "
chapters_to_dl = (gets.chomp.to_s).split(",")
if chapters_to_dl.count == 0
puts "\nError! You need to choose at least one chapter!\n\n"
exit
end
# see which chapters to download
chapters_to_dl.each do |chap|
case chap.strip
when "all"
chapters << "vuln_hosts_summary;vuln_by_plugin;vuln_by_host;remediations;compliance_exec;compliance;"
when "0"
chapters << "vuln_by_plugin;"
when "1"
chapters << "vuln_by_host;"
when "2"
chapters << "vuln_hosts_summary;"
when "3"
chapters << "remediations;"
when "4"
chapters << "compliance_exec;"
when "5"
chapters << "compliance;"
end
end
end
# create report folder
print "\nPath to save reports to (without trailing slash): "
rpath = gets.chomp.to_s
unless File.directory?(rpath)
FileUtils.mkdir_p(rpath)
end
# run report download
if formats.count > 0
report_download(http, headers, reports, reports_to_dl, formats, chapters, rpath, db_export_pw)
end
puts "\nReport Download Completed!\n\n"
| true |
665cb3e7d4e4a3d0e1085dee3bcd18f9f33f1da8 | Ruby | janpieper/Onions-Rails-API | /app/models/onion.rb | UTF-8 | 3,215 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'base64'
require 'openssl'
class Onion < ActiveRecord::Base
attr_accessible :HashedInfo, :HashedTitle, :HashedUser, :Title_Iv, :Info_Iv, :Title_AuthTag, :Info_AuthTag
# Take Onions from DB and decrypt them all after a User logs in
def self.decrypted_onions_with_key(onions,key)
if onions && key
betaProblems = false
onions.each do |o|
hash = Onion.decrypted_onion(key, o)
if hash[:BetaProblems]
betaProblems = true
end
end
end
return {:Onions => onions, :BetaProblems => betaProblems}
end
# Encrypt data
def self.aes256_encrypt(key, data)
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize)
aes = OpenSSL::Cipher::AES.new(256, :CBC)
aes.encrypt
aes.key = key
new_iv = aes.random_iv
encrypted_data = aes.update(data) + aes.final
auth_tag = Digest::SHA256.digest(ENV['AUTH_TAG'] + encrypted_data)
# return encrypted data, the iv, and the authentication info
return {:EncryptedData => Base64.encode64(encrypted_data), :Iv => Base64.encode64(new_iv), :AuthTag => Base64.encode64(auth_tag)}
end
# Decrypt data
def self.aes256_decrypt(key, data, iv, auth_tag)
if Digest::SHA256.digest(ENV['AUTH_TAG'] + data) == auth_tag
key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize)
aes = OpenSSL::Cipher::AES.new(256, :CBC)
aes.decrypt
aes.key = key
aes.iv = iv
return {:Data => aes.update(data) + aes.final, :BetaProblems => false}
else
# Message didn't authenticate
return {:Data => data, :BetaProblems => true}
end
end
def self.create_new_onion(key,title,info,user)
@e_title_hash = Onion.aes256_encrypt(key,(title.length > 0 ? title : ' '))
@e_info_hash = Onion.aes256_encrypt(key,(info.length > 0 ? info : ' '))
@new_onion = Onion.create(:HashedUser => user, :HashedTitle => @e_title_hash[:EncryptedData], :Title_Iv => @e_title_hash[:Iv], :Title_AuthTag => @e_title_hash[:AuthTag], :HashedInfo => @e_info_hash[:EncryptedData], :Info_Iv => @e_info_hash[:Iv], :Info_AuthTag => @e_info_hash[:AuthTag])
end
def edit_onion_with_new_data(key,new_title,new_info)
@e_title_hash = Onion.aes256_encrypt(key,(new_title.length > 0 ? new_title : ' '))
@e_info_hash = Onion.aes256_encrypt(key,(new_info.length > 0 ? new_info : ' '))
self.HashedTitle = @e_title_hash[:EncryptedData]
self.Title_Iv = @e_title_hash[:Iv]
self.Title_AuthTag = @e_title_hash[:AuthTag]
self.HashedInfo = @e_info_hash[:EncryptedData]
self.Info_Iv = @e_info_hash[:Iv]
self.Info_AuthTag = @e_info_hash[:AuthTag]
self.save
end
def self.decrypted_onion(key,onion)
hashedTitle = Onion.aes256_decrypt(key,Base64.decode64(onion.HashedTitle),Base64.decode64(onion.Title_Iv),Base64.decode64(onion.Title_AuthTag))
hashedInfo = Onion.aes256_decrypt(key,Base64.decode64(onion.HashedInfo),Base64.decode64(onion.Info_Iv),Base64.decode64(onion.Info_AuthTag))
onion.HashedTitle = hashedTitle[:Data]
onion.HashedInfo = hashedInfo[:Data]
betaProblems = hashedTitle[:BetaProblems] || hashedInfo[:BetaProblems]
return {:BetaProblems => betaProblems}
end
end
| true |
1c481e2783d42be650a1d483f61095dd6b9f9dfb | Ruby | rsoemardja/Codecademy | /Ruby/Learn Ruby/Object-Oriented Programming, Part II/Object-Oriented Programming, Part II in Ruby/The Marriage of Module and Classes.rb | UTF-8 | 768 | 4.03125 | 4 | [] | no_license | # In this exercise we will mixed together the behaviors of a class and a module
#When a module is used to mix additional behavior and information into a class
# It is called a mixin
# Mixins allows us to customize a class without having to rewrite code
# in this code they are define the jump method in the Action module
# and mix it into the Rabbit and Cricket classes
module Action
def jump
@distance = rand(4) + 2
puts "I jumped forward #{@distance} feet!"
end
end
class Rabbit
include Action
attr_reader :name
def initialize(name)
@name = name
end
end
class Cricket
include Action
attr_reader :name
def initialize(name)
@name = name
end
end
peter = Rabbit.new("Peter")
jiminy = Cricket.new("Jiminy")
peter.jump
jiminy.jump | true |
5147cdd5c7cf7dd0442c8f1586f8dd6a8aa89f5a | Ruby | greghxc/advent-of-code | /main/day_06/lib.rb | UTF-8 | 600 | 3.375 | 3 | [] | no_license | class CodeFinder
def count_chars(data)
count = []
data.each do |d|
d.chars.each_with_index do |c, i|
count[i] = {} unless count[i]
count[i][c] ? count[i][c] += 1 : count[i][c] = 1
end
end
count
end
def get_char(count, day)
grab = [
->(c) { c.sort_by { |_, v| v }.reverse[0][0] },
->(c) { c.sort_by { |_, v| v }[0][0] }
]
grab[day - 1].call(count)
end
def translate(data, day = 1)
result = []
count = count_chars(data)
count.each do |c|
result.push(get_char(c, day))
end
result.join
end
end
| true |
e5d0f084d2873f3a69c314357fae4dccec416ecd | Ruby | glassbead0/homework_assignments | /methods_and_flow_control/fizz_buzz.rb | UTF-8 | 363 | 4.0625 | 4 | [] | no_license | #!/usr/bin/env ruby
# print the numbers 1 - 100
# if the number is divisible by 3, print Fizz
# if the number is divisible by 5, print Buzz
# if the number is divisible by 3 and 5, print FizzBuzz
(1..100).each do |x|
if (x % 15).zero?
puts 'FizzBuzz'
elsif (x % 3).zero?
puts 'Fizz'
elsif (x % 5).zero?
puts 'Buzz'
else
puts x
end
end
| true |
df1981c27e6c2700b173042fed91dfd48931dede | Ruby | evantravers/euler | /ruby/31.rb | UTF-8 | 476 | 3.359375 | 3 | [] | no_license | require 'pry'
require 'set'
Options = [200, 100, 50, 20, 10, 5, 2, 1]
@total_ways = Set.new
class Array
def sum
self.inject(:+)
end
end
# list is the current position
# start is the point after which it has to search
def evaluate list, start
in_hand = list
in_hand << Options[start]
if in_hand.sum == 200
@total_ways << in_hand.sort!
evaluate(list, start+1)
else
evaluate(in_hand, start)
end
end
evaluate(Array.new, 0)
puts @total_ways.size
| true |
9c2c0bb350b0c4aa486d4ee4d62cbbef83890460 | Ruby | zachlatta/shirts | /lib/shirts.rb | UTF-8 | 327 | 2.671875 | 3 | [
"MIT"
] | permissive | # Require all of the ruby files in the given directory. Taken from Jekyll.
#
# @param [String] Relative path from here to the directory.
def require_dir(path)
glob = File.join(File.dirname(__FILE__), path, '*.rb')
Dir[glob].each do |f|
require f
end
end
require_dir 'shirts'
module Shirts
class << self
end
end
| true |
aada40e1b3706ef39309e4eb014101f9c054c170 | Ruby | ilabsea/verboice-external-step | /app/models/period_rating.rb | UTF-8 | 2,394 | 2.625 | 3 | [] | no_license | class PeriodRating < ActiveRecord::Base
validates :code, :step_id, :from_date, :to_date, presence: true
serialize :numbers, Array
belongs_to :step
validates :code, uniqueness: true
validates :code, numericality: { greater_than: 0, less_than: 100 }
validate :from_date_must_be_less_than_to_date
validate :unique_date_range
SEPERATOR = ","
SEPERATOR_DISPLAY = ", "
NON_EXISTING_OR_RATED = -1
class << self
def get_code_of(date, tel)
period_rating_code = NON_EXISTING_OR_RATED
rating = get date
if rating
period_rating_code = rating.code unless rating.has_telephone?(tel)
end
period_rating_code
end
def get(date)
rating = nil
all.each do |r|
if r.has_date? date
rating = r
break
end
end
rating
end
end
def from_date_must_be_less_than_to_date
errors.add(:date, 'to_date must be greater than from_date') if from_date > to_date
end
def unique_date_range
PeriodRating.where.not(id: self.id).each do |rating|
if rating.in_range? from_date, to_date
errors.add(:date, 'date range already exists')
end
end
end
def exist?(tel, date)
found = false
if has_date?(date)
if has_telephone?(tel)
found = true
end
end
found
end
def in_range? first_date, second_date
first_date.between?(from_date, to_date) || (first_date.less_than_or_equal?(from_date) && second_date.greater_than_or_equal?(from_date))
end
def has_date? date
date.between?(from_date, to_date)
end
def has_telephone? tel
numbers.include?(tel.without_prefix)
end
def sync_numbers_with!(project_id, variable_id)
is_modified = false
call_log_answers = Service::CallLogAnswer.fetch_by project_id, variable_id, from_date.to_string('%Y-%m-%d'), (to_date + 1.day).to_string('%Y-%m-%d')
call_log_answers.each do |answer|
if answer.value
is_modified = true
number_without_voip = answer.call_log[:prefix_called_number] ? answer.call_log[:address][answer.call_log[:prefix_called_number].length..-1] : answer.call_log[:address]
tel = Tel.new number_without_voip
register! tel
end
end
save if is_modified
end
def register! tel
unless has_telephone?(tel)
numbers.push tel.without_prefix
save
end
end
end
| true |
03ea6e397e29fc928e20ee7cf6703a3c2fa7c862 | Ruby | ImperialOctopus/avalon-app | /speech/google-cloud.rb | UTF-8 | 971 | 3 | 3 | [
"Apache-2.0"
] | permissive | require "google/cloud/text_to_speech"
client = Google::Cloud::TextToSpeech.new
input_file = "input_lines.txt"
voice = {
:language_code => "en-GB",
:name => "en-GB-Wavenet-D",
:ssml_gender => "MALE"
}
audio_config = { :audio_encoding => "MP3" }
output_directory = "en-GB-D";
unless output_directory == "" then
Dir.mkdir(output_directory) unless File.exists?(output_directory)
output_directory += "/"
end
inputfile = File.new(input_file, "r")
inputfile.each_line() { |line|
line.chomp!
input_text = { :text => line }
output_file = output_directory + input_text[:text].gsub(" ", "-").downcase[0..15].chomp("-") + ".mp3"
#output_file = "hello.mp3"
response = client.synthesize_speech(input_text, voice, audio_config)
# The response's audio_content is binary.
File.open(output_file, "wb") do |file|
# Write the response to the output file.
file.write(response.audio_content)
end
puts "Successfully acquired: '" + output_file + "'"
}
| true |
dde0e0f540a671f966b3495889af99993cefaaf0 | Ruby | leequarella/dr-scripts | /lee/disarm.rb | UTF-8 | 5,919 | 2.671875 | 3 | [] | no_license | class Disarm
attr_reader :sprung, :disarmed, :more_traps
DISARMING = Regexp.union([
/not yet fully disarmed/,
/proves too difficult to manipulate/,
/something to shift/,
/lock springs out and stabs you painfully in the finger/,
/An acrid stream of sulfurous air hisses quietly/,
/A stream of corrosive acid sprays out from the/,
/With a sinister swishing noise, a deadly sharp scythe blade whips out the front of the/,
/There is a sudden flash of greenish light, and a huge electrical charge sends you flying/,
/A stoppered vial opens with a pop and cloud of thick green vapor begins to pour out of the/,
/breaks in half. A glass sphere on the seal begins to glow with an eerie black light/,
/Just as your ears register the sound of a sharp snap/,
/Looking at the needle, you notice with horror the rust colored coating on the tip/,
/You barely have time to register a faint click before a blinding flash explodes around you/,
/Moving with the grace of a pregnant goat, you carelessly flick at the piece of metal causing/,
/You make a small hole in the side of the box and take deep breath to blow the powder free but a /,
/With a cautious hand, you attempt to undo the string tying the bladder to the locking mechanism /,
/The dart flies though your fingers and plants itself solidly in your forehead!/,
/Almost casually, you press on the tiny hammer set to break the tube. The hammer slips from its locked/,
/Nothing happened. Maybe it was a dud./,
/You get a feeling that something isn't right. Before you have time to think what it might be you find/,
/and emits a sound like tormented souls being freed, then fades away suddenly./,
/has gotten much bigger!/,
/and clumsily shred the fatty bladder behind it in the process/,
/liquid shadows/,
/You wiggle the milky-white tube back and forth for a few moments in an attempt to remove it from/,
/With a nasty look and a liberal amount of hurled, unladylike epithets, she wiggles back inside and slams/,
/Not sure where to start, you begin by prying off the body of the crusty scarab, hoping to break it free/,
/You feel like you've done a good job of blocking up the pinholes, until you peer closely to examine /,
/You work with the trap for a while but are unable to make any progress/,
/for a while but are unable to make any progress/,
/you feel satisfied that the trap/,
/you carefully pry at the studs working them/,
/you manage to bend it well away from the mesh bag/,
/allowing it to be opened safely/,
/You work with the trap for a while but are unable to make any progress/,
/Roundtime/,
])
def initialize(box, difficulty)
@box = box
@difficulty = difficulty
@sprung = false
@disarmed = false
disarm
end
def disarm
verb = "DISARM MY #{@box} #{@difficulty}"
check = dothis verb, DISARMING
waitrt?
disarmed? check
disarm unless @disarmed || @sprung
end
def disarmed? check
if(check =~ /not yet fully disarmed/)
fput "NOT DISARMED, MOAR TRAPS!!!!!"
@disarmed = true
@more_traps = true
elsif(check =~ /lock springs out and stabs you painfully in the finger/ ||
check =~ /An acrid stream of sulfurous air hisses quietly/ ||
check =~ /A stream of corrosive acid sprays out from the/ ||
check =~ /With a sinister swishing noise, a deadly sharp scythe blade whips out the front of the/ ||
check =~ /There is a sudden flash of greenish light, and a huge electrical charge sends you flying/ ||
check =~ /A stoppered vial opens with a pop and cloud of thick green vapor begins to pour out of the/
check =~ /breaks in half. A glass sphere on the seal begins to glow with an eerie black light/ ||
check =~ /Just as your ears register the sound of a sharp snap/ ||
check =~ /Looking at the needle, you notice with horror the rust colored coating on the tip/ ||
check =~ /You barely have time to register a faint click before a blinding flash explodes around you/ ||
check =~ /Moving with the grace of a pregnant goat, you carelessly flick at the piece of metal causing/ ||
check =~ /You make a small hole in the side of the box and take deep breath to blow the powder free but a / ||
check =~ /With a cautious hand, you attempt to undo the string tying the bladder to the locking mechanism / ||
check =~ /The dart flies though your fingers and plants itself solidly in your forehead!/ ||
check =~ /Almost casually, you press on the tiny hammer set to break the tube. The hammer slips from its locked/ ||
check =~ /Nothing happened. Maybe it was a dud./ ||
check =~ /You get a feeling that something isn't right. Before you have time to think what it might be you find/ ||
check =~ /and emits a sound like tormented souls being freed, then fades away suddenly./ ||
check =~ /has gotten much bigger!/ ||
check =~ /and clumsily shred the fatty bladder behind it in the process/ ||
check =~ /liquid shadows/ ||
check =~ /You wiggle the milky-white tube back and forth for a few moments in an attempt to remove it from/ ||
check =~ /With a nasty look and a liberal amount of hurled, unladylike epithets, she wiggles back inside and slams/ ||
check =~ /Not sure where to start, you begin by prying off the body of the crusty scarab, hoping to break it free/ ||
check =~ /You feel like you've done a good job of blocking up the pinholes, until you peer closely to examine /)
sprung!
elsif(check =~ /something to shift/)
be_careful!
elsif(check =~ /You work with the trap for a while but are unable to make any progress/)
@disarmed = false
else
@disarmed = true
end
end
def sprung!
@sprung = true
end
def be_careful!
@difficulty = "careful"
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.