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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c63e99789402ca7ccb151f1856aebac47165e99a
|
Ruby
|
yuuyas222/class_inherit
|
/dvd.rb
|
UTF-8
| 452
| 3.546875
| 4
|
[] |
no_license
|
class DVD < Product
# attr_reader :running_time
# def initialize(name, price, running_time)
# super(name, price)
# @running_time = running_time
# end
# def to_s
# "name: #{name}" #スーパークラスのprivateメソッド
# end
private
def name
"An nice product"
end
end
# dvd = DVD.new('great movie', 1000, 120)
# dvd.name # "greate movie"
# dvd.price #1000
# dvd.running_time #120
| true
|
2aaa11745269084a41e8545d3e7266c737c499ad
|
Ruby
|
snikch/suitebar.co.nz
|
/app/models/diary.rb
|
UTF-8
| 290
| 3.609375
| 4
|
[] |
no_license
|
class Diary
def self.day_valid? date
# Sun, thur, fri, sat
date.sunday? || date.thursday? || date.friday? || date.saturday?
end
def self.hour_valid? date
date.hour >= 18 && date.hour <= 22
end
def self.minutes_valid? date
[0, 30].include? date.minute
end
end
| true
|
64174e62bcf75aeed82caab31d30253152ec44d3
|
Ruby
|
glooer/dip
|
/module/Widgets/PoPaginator.rb
|
UTF-8
| 2,980
| 2.65625
| 3
|
[] |
no_license
|
class PoPaginator < Qt::Widget
slots "_update_index(QString)", "pages_prev()", "pages_next()", "pages_stat()", "test(int)"
signals "currentPageChanged(int)"
def initialize parent = 0, pages_size_select = [30, 50, 100, 500, 1000]
super parent
@layout = Qt::HBoxLayout.new self
self.setLayout @layout
@layout.setContentsMargins(0, 0, 0, 0)
@pages_selecter = Qt::ComboBox.new self
@pages_navig_left = Qt::ToolButton.new self do
self.text = "<"
end
@pages_navig_right = Qt::ToolButton.new self do
self.text = ">"
end
@pages_size_selecter = Qt::ComboBox.new self do
self.insertItems(0, pages_size_select.map(&:to_s))
end
@layout.addWidget @pages_navig_left
@layout.addWidget @pages_selecter
@layout.addWidget @pages_navig_right
@layout.addItem Qt::SpacerItem.new(40, 20, Qt::SizePolicy::Expanding, Qt::SizePolicy::Minimum)
@layout.addWidget @pages_size_selecter
update(0)
#@old_size = currentSize
connect(@pages_size_selecter, SIGNAL("currentIndexChanged(QString)"), SLOT("_update_index(QString)"))
connect(@pages_selecter, SIGNAL("currentIndexChanged(int)"), SLOT("pages_stat()"))
connect(@pages_navig_left, SIGNAL("clicked()"), SLOT("pages_prev()"))
connect(@pages_navig_right, SIGNAL("clicked()"), SLOT("pages_next()"))
connect(self, SIGNAL("currentPageChanged(int)"), SLOT("test(int)"))
end
def test i
p "test - #{i}"
end
def currentIndexPagesSizeSelecter
@pages_size_selecter.currentIndex
end
def setIndexPagesSizeSelecter i
@pages_size_selecter.setCurrentIndex i
end
def pages_stat
@pages_navig_left.enabled = @pages_selecter.currentIndex < 1 ? false : true
@pages_navig_right.enabled = @pages_selecter.currentIndex + 1 == countPages ? false : true
emit currentPageChanged currentOffset if @pages_selecter.currentIndex > -1
end
def pages_prev
@pages_selecter.setCurrentIndex @pages_selecter.currentIndex - 1
end
def pages_next
@pages_selecter.setCurrentIndex @pages_selecter.currentIndex + 1
end
def _update_index str
update 0
end
def pagesEnabled state
@pages_navig_left.enabled = state
@pages_selecter.enabled = state
@pages_navig_right.enabled = state
end
def currentSize
@pages_size_selecter.currentText.to_i
end
def update num, size = currentSize
if num <= size
@pages_selecter.clear
pagesEnabled false
else
setPagesSelecter -(-num / size)
end
end
def currentPage
@pages_selecter.currentText.to_i - 1
end
def currentOffset
currentPage * currentSize
end
def countPages
@pages_selecter.count
end
def setPagesSelecter count
@pages_selecter.clear
@pages_selecter.blockSignals true
@pages_selecter.insertItems(0, Array.new(count){ |i| i.next.to_s })
@pages_selecter.blockSignals false
pagesEnabled true
end
end
| true
|
3cf5d49e92c0bfd1bea46159a52d5f171b1438f4
|
Ruby
|
UsmanJ/codewars
|
/simple_string_validation.rb
|
UTF-8
| 845
| 4.09375
| 4
|
[] |
no_license
|
# This method accepts a single argument, a string to be validated.
# The string can be of any length and have any contents. But to be considered valid, it must have zero or more blanks followed by zero to eight numeric digits followed by, again, zero or more blanks.
# If it is valid, the number within the string + 1 is returned. Otherwise, the string 'invalid' is returned. A completely blank string is considered valid, equal to zero.
# ' 7 ' returns 8
# ' 2 8 ' returns 'invalid' (there mustn't be any spaces (or any other characters) between digits
# ' a 8 ' returns 'invalid'
# ' ' returns 1
# 'abc1' returns 'invalid'
def validation string
if string.empty? == true
return 0
elsif string.map { |s| s =~ /\A\[ \t]+/[0-9]/[ \t]+/ }
return string.to_i +1
else
return "invalid"
end
end
| true
|
61db90bb636c0b28dba67019c1d2049c1ca2a657
|
Ruby
|
Arcath/Markabb
|
/lib/markabb/classes/tag.rb
|
UTF-8
| 2,560
| 3.296875
| 3
|
[] |
no_license
|
module Markabb
# The hash which markabb stores all the avaliable tags in
Tags = {}
# Inserts a tag into Markabb::Tags
#
# Takes 3 inputs:
# name - a symbol which is used as its key
# tag - a Markabb::Tag object
# group - a way to group similar tags so they can all be disabled
#
# register_tag(:foo, Markabb::Tag, :bar)
#
# would produce a tags hash of
#
# {:bar => {:foo => Markabb::Tag}}
def self.register_tag(name, tag, group = nil)
tag.name = name
if group
tag.group = group
Tags[group] ||= {}
Tags[group][name] = tag
else
Tags[name] = tag
end
end
# Removes a tag from Markabb::Tags
# takes the symbol for the key to delete
def self.remove_tag(name)
Tags.delete(name)
end
# Used for all tags (passed to register_tag)
# Takes a REGEX matcher and a string to replace it with
class Tag
attr_reader :matcher, :replace
attr_accessor :name, :group
# Creates the Markabb::Tag object
def initialize(matcher, replace)
if matcher.is_a? String
@matcher = generate_matcher(matcher)
elsif matcher.is_a? Regexp
@matcher = matcher
else
raise 'matcher is not valid'
end
if replace.is_a? String
@replace = replace
elsif replace.is_a? Markabb::Callback
@replace = false
@callback = replace
else
raise 'Replace is not valid'
end
end
# Runs the tag on the input string
#
# Takes the target string and a Markabb::Config object
def run(s, config)
if @replace
return s.gsub(@matcher, generate_replacement(@replace, config))
elsif @callback
return run_callback(s)
end
end
private
def run_callback(s)
s.gsub(@matcher) { |match| @callback.run(match.scan(@matcher).first) }
end
def generate_replacement(replace, config)
if replace.scan(/config\[:(.*?)\]/) != [] then
return replace.gsub(/config\[(.*?)\]/, config[$1.to_sym])
else
return replace
end
end
def generate_matcher(tag)
/\[#{tag}\](.*?)\[\/#{tag}\]/
end
end
end
| true
|
85ed68b331797afd13e8bf3cf97ef71f9e12e17a
|
Ruby
|
tjlee/OpenGenesis
|
/test-automation/cucumber/lib/genesis_client.rb
|
UTF-8
| 2,580
| 2.765625
| 3
|
[] |
no_license
|
require 'httparty'
require 'yaml'
class GenesisClient
include HTTParty
attr_accessor :auth
def initialize()
config = YAML::load(File.open(File.dirname(__FILE__) + "/../config.yml"))
@host = config["genesis"]["host"]
@port = config["genesis"]["port"]
@auth = {:username => config["genesis"]["user"], :password => config["genesis"]["password"] }
end
def ping
self.class.get(genesis_path + "/")
end
def whoami
get("/whoami")
end
def project_id(name)
response = get('/projects')
resp = JSON.parse(response.body)
found = resp.select { |r| r["name"] == name }
if found.size > 0
found[0]["id"]
else
nil
end
end
def create_project(name, manager, description = nil)
project = {:name => name, :projectManager => manager, :description => description}
post('/projects', :body=>project.to_json)
end
def delete_project(id)
delete("/projects/#{id}")
end
def get_template(project, template, version)
get("/projects/#{project}/templates/#{template}/v#{version}")
end
def env_id(project, name)
response = get("/projects/#{project}/envs")
found = JSON.parse(response.body).select { |e| e["name"] == name }
if found.size > 0
found[0]["id"]
end
end
def create_env(id, name, template, version, variables = {})
env = {:envName => name, :templateName => template, :templateVersion => version, :variables => variables }
post("/projects/#{id}/envs", :body=> env.to_json)
end
def delete_projects
resp = get('/projects')
JSON.parse(resp.body).map { |p| delete_project(p["id"]) }
end
def rename_env(id, env_id, newname)
resp = {:environment => {:name => newname}}
put("/projects/#{id}/envs/#{env_id}", :body => resp.to_json)
end
private
def genesis_path
"http://#{@host}:#{@port}"
end
def get(p, options = {})
options.merge!({:basic_auth => auth}) unless auth.nil?
self.class.get(path(p), options)
end
def post(p, options = {})
options.merge!({:basic_auth => auth, :headers => {'Content-Type' => 'application/json'}}) unless auth.nil?
self.class.post(path(p), options)
end
def put(p, options = {})
options.merge!({:basic_auth => auth, :headers => {'Content-Type' => 'application/json'}}) unless auth.nil?
self.class.put(path(p), options)
end
def delete(p, options = {})
options.merge!({:basic_auth => auth}) if auth
self.class.delete(path(p), options)
end
def path(p)
genesis_path + '/rest/' + p
end
end
| true
|
d17ae5896788acf195956c3be1ad152dc7a47215
|
Ruby
|
chaganiu/playwright-ruby-client
|
/lib/playwright/route_handler_entry.rb
|
UTF-8
| 633
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
module Playwright
class RouteHandlerEntry
# @param url [String]
# @param base_url [String|nil]
# @param handler [Proc]
def initialize(url, base_url, handler)
@url_value = url
@url_matcher = UrlMatcher.new(url, base_url: base_url)
@handler = handler
end
def handle(route, request)
if @url_matcher.match?(request.url)
@handler.call(route, request)
true
else
false
end
end
def same_value?(url:, handler: nil)
if handler
@url_value == url && @handler == handler
else
@url_value == url
end
end
end
end
| true
|
a2b1644da9e4e037f2e7ce838d8d8dc1f2ec9779
|
Ruby
|
destinf/t5008_converter
|
/lib/t5008_converter.rb
|
UTF-8
| 1,903
| 2.875
| 3
|
[] |
no_license
|
require "t5008_converter/version"
require "t5008_converter/row_data"
require "t5008_converter/exchange_rate/exchange_rate_api"
require "csv"
module T5008Converter
class Error < StandardError; end
REQUIRED_INPUT_COLUMNS = [
"quantity",
"closing date",
"currency (original)",
"proceeds of disposition (original)",
"adjusted cost base (original)",
"outlays and expenses (original)",
"currency (converted)"
]
COLUMNS = REQUIRED_INPUT_COLUMNS + [
"name of fund",
"gain (or loss) (original)",
"proceeds of disposition (converted)",
"adjusted cost base (converted)",
"outlays and expenses (converted)",
"gain (or loss) (converted)",
"exchange rate used"]
def self.generate_template(output_template_file_name)
CSV.open(output_template_file_name, "wb",
write_headers: true,
headers: COLUMNS) do |output_csv|
end
end
def self.fill_csv(input_file_name, output_file_name, exchange_rate_service)
CSV.open(output_file_name, "wb",
write_headers: true,
headers: COLUMNS) do |output_csv|
CSV.foreach(input_file_name, headers: true) do |row|
row_data = RowData.new(row, exchange_rate_service)
row_data.fill_missing_values!
output_csv << convert_row_data_to_row(row_data)
end
end
end
private
def self.convert_row_data_to_row(row_data)
[
row_data.quantity,
row_data.closing_date,
row_data.original_currency,
row_data.original_proceeds,
row_data.original_cost,
row_data.original_expenses,
row_data.converted_currency,
row_data.name,
row_data.original_gain_loss,
row_data.converted_proceeds,
row_data.converted_cost,
row_data.converted_expenses,
row_data.converted_gain_loss,
row_data.exchange_rate
]
end
end
| true
|
5a6cc30dbc6a25649ce3249f7ee5bd560a3bc799
|
Ruby
|
toasterbob/review
|
/challenges/ruby/hackerrank/implementation/birthday_choc.rb
|
UTF-8
| 320
| 3.375
| 3
|
[] |
no_license
|
#!/bin/ruby
def getWays(squares, d, m)
total = 0
squares.each_cons(m) do |block|
total += 1 if block.reduce(:+) == d
end
return total
end
n = gets.strip.to_i
s = gets.strip
s = s.split(' ').map(&:to_i)
d,m = gets.strip.split(' ')
d = d.to_i
m = m.to_i
result = getWays(s, d, m)
print(result)
| true
|
3b1cff3c4b92b323d7255fbbf2d832292076fbfa
|
Ruby
|
cpjolicoeur/rails
|
/activesupport/lib/active_support/core_ext/object/try.rb
|
UTF-8
| 2,335
| 3.4375
| 3
|
[
"Ruby",
"MIT"
] |
permissive
|
class Object
# Invokes the public method whose name goes as first argument just like
# +public_send+ does, except that if the receiver does not respond to it the
# call returns +nil+ rather than raising an exception.
#
# This method is defined to be able to write
#
# @person.do_or_do_not(:name)
#
# instead of
#
# @person ? @person.name : nil
#
# +do_or_do_not+ returns +nil+ when called on +nil+ regardless of whether it responds
# to the method:
#
# nil.do_or_do_not(:to_i) # => nil, rather than 0
#
# Arguments and blocks are forwarded to the method if invoked:
#
# @posts.do_or_do_not(:each_slice, 2) do |a, b|
# ...
# end
#
# The number of arguments in the signature must match. If the object responds
# to the method the call is attempted and +ArgumentError+ is still raised
# otherwise.
#
# If +do_or_do_not+ is called without arguments it yields the receiver to a given
# block unless it is +nil+:
#
# @person.do_or_do_not do |p|
# ...
# end
#
# Please also note that +do_or_do_not+ is defined on +Object+, therefore it won't work
# with instances of classes that do not have +Object+ among their ancestors,
# like direct subclasses of +BasicObject+. For example, using +do_or_do_not+ with
# +SimpleDelegator+ will delegate +do_or_do_not+ to the target instead of calling it on
# delegator itself.
def do_or_do_not(*a, &b)
if a.empty? && block_given?
yield self
else
public_send(*a, &b) if respond_to?(a.first)
end
end
# Same as #do_or_do_not, but will raise a NoMethodError exception if the receiving is not nil and
# does not implement the tried method.
def do_or_do_not!(*a, &b)
if a.empty? && block_given?
yield self
else
public_send(*a, &b)
end
end
end
class NilClass
# Calling +do_or_do_not+ on +nil+ always returns +nil+.
# It becomes specially helpful when navigating through associations that may return +nil+.
#
# nil.do_or_do_not(:name) # => nil
#
# Without +do_or_do_not+
# @person && !@person.children.blank? && @person.children.first.name
#
# With +do_or_do_not+
# @person.do_or_do_not(:children).do_or_do_not(:first).do_or_do_not(:name)
def do_or_do_not(*args)
nil
end
def do_or_do_not!(*args)
nil
end
end
| true
|
589ba41f92d11ae37cf472086d7799380c2726b2
|
Ruby
|
sekoudosso82/ruby-oo-relationships-practice-blood-oath-exercise-nyc-web-012720
|
/app/models/flower.rb
|
UTF-8
| 932
| 3.609375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Flower
attr_accessor :name, :age, :life_motto
@@all = []
def initialize(name, age, life_motto)
@name = name
@age = age
@life_motto = life_motto
@@all << self
end
def cults
# returns an Array of this follower's cults
BloodOath.all.select do |bloodOath|
bloodOath.cult = self
end
end
def join_cult(cult)
# takes in an argument of a Cult instance and adds this follower to the cult's list of followers
list = BloodOath.all.select do |bloodOath|
bloodOath.flower == self
end
list << cult
end
def self.all
@@all
end
def self.of_a_certain_age(age)
# takes an Integer argument that is an age and returns an Array of followers who are the given age or older
@@all.select do |flower|
flower.age >= age
end
end
end
| true
|
f2d747f87a414c939d314cddd226fcb5e5cae5bc
|
Ruby
|
MaxSechz/appacademy-exercises
|
/poker/spec/card_spec.rb
|
UTF-8
| 1,605
| 3.203125
| 3
|
[] |
no_license
|
require 'rspec'
require 'card.rb'
describe Card do
subject(:card) { Card.new(:king, :club) }
it "initializes with a suit" do
expect(card.suit).to eq(:club)
end
it "initializes with a face" do
expect(card.face).to eq(:king)
end
describe "#>" do
let(:larger_card) { Card.new(:ace, :heart) }
let(:smaller_card) { Card.new(:ten, :diamond) }
let(:better_suit) { Card.new(:king, :diamond)}
let(:worse_suit) { Card.new(:king, :heart)}
it "returns true if left card greater than right card" do
expect(card > smaller_card).to eq(true)
end
it "returns false if left card smaller than right card" do
expect(card > larger_card).to eq(false)
end
it "returns true if faces are equal but left card has better suit" do
expect(card > worse_suit).to eq(true)
end
it "returns false if faces equal but left card has worse suit" do
expect(card > better_suit).to eq(false)
end
end
describe "#==" do
let(:equal) { Card.new(:king, :club)}
let(:different_suit) { Card.new(:king, :heart)}
let(:different_face) {Card.new(:queen, :club)}
let(:different) {Card.new(:ace, :diamond)}
it "returns true if both face and suit are the same" do
expect(card==equal).to eq(true)
end
it "returns false if the suits differ" do
expect(card==different_suit).to eq(false)
end
it "returns false if the faces differ" do
expect(card==different_face).to eq(false)
end
it "returns false if both face and suit differ" do
expect(card==different).to eq(false)
end
end
end
| true
|
8507bbf30ad9b76ed6cc09564a4004f74b079280
|
Ruby
|
stringham/contests
|
/2012-mebipenny/contest/biological-entropy/solution.rb
|
UTF-8
| 1,613
| 3.359375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
KEEP_RESULT = false
def formatter(significant, next_code)
# format with the right number of hex digits for our size
result = format("%0#{significant}x", next_code)
[result, next_code + 1]
end
def compress(line, size)
# initialize
dictionary = {}
sequence = ""
result = ""
length = 0
next_code = 0
significant = size / 4
%w(A G C T).map do |dna|
dictionary[dna], next_code = formatter(significant, next_code)
end
# for each character
line.each_char do |char|
next_sequence = "#{sequence}#{char}"
# if the sequence with the new char is in the dict, continue
if dictionary.has_key?(next_sequence)
sequence = next_sequence
# otherwise
else
# make a new code, if possible
if next_code < (2 ** size)
dictionary[next_sequence], next_code = formatter(significant, next_code)
end
# add the code to the result
result += dictionary[sequence] if KEEP_RESULT
length += dictionary[sequence].length
# and continue with the new char
sequence = char
end
end
# finish up any loose ends
result += dictionary[sequence] if KEEP_RESULT
length += dictionary[sequence].length
length
end
while line = gets
line = line.strip
options = [
# length of 2 bit encoding is just length of string * 2
[line.length * 2, "2"],
# all the rest we are keeping track of in hex, so multiply by 4 for bits
[compress(line, 4) * 4, "4"],
[compress(line, 8) * 4, "8"],
[compress(line, 16) * 4, "16"],
[compress(line, 32) * 4, "32"],
]
puts options.sort_by{|opt| opt.first}.first[1]
end
| true
|
6f976ba226a474143c28e667fc33e341bf020e1f
|
Ruby
|
codesicario/ls-intro-ruby
|
/exercise_string.dir/string2.rb
|
UTF-8
| 310
| 3.296875
| 3
|
[] |
no_license
|
words = 'car human elephant airplane'
plural_words = words.split
plural_words.each { |x| puts x + "s"}
#another option
words.split(' ').each do |word|
puts word + 's'
end
colors = 'blue boredom pink yellow orange'
puts colors.include?("yellow")
puts colors.include?("purple")
puts colors.include?("red")
| true
|
2bbc9a103fea6bbe16f95a103839129dc9a5dce2
|
Ruby
|
AnaTeresaDona/Ruby-Ejercicios2-2020
|
/calculo_notas2.rb
|
UTF-8
| 409
| 3.46875
| 3
|
[] |
no_license
|
data1 = open("notas.data").readlines
data = data1.map{|elemento| elemento.split(",")}
def notas_mas_alta (array)
n_arreglo = []
array.each do |arreglo_interno|
nombres = arreglo_interno[0]
notas = (arreglo_interno[1..arreglo_interno.count].map{|nota| nota.to_i}).max
nombres_y_nota = [nombres,notas]
n_arreglo.push(nombres_y_nota)
end
print n_arreglo
end
print notas_mas_alta(data)
| true
|
fdf4c32826fa47a2c576587798adf745e0b2ce70
|
Ruby
|
realestate-com-au/blobby
|
/lib/blobby/key_constraint.rb
|
UTF-8
| 723
| 2.734375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require "uri"
module Blobby
# Defines the keys we allow for use in BLOB-store implementations.
#
# Basically, we allow anything that would be a valid URI "path" component.
#
module KeyConstraint
BAD_PATTERNS = [
%r{\A\Z}, # blank
%r{\A/}, # leading slash
%r{/\Z}, # trailing slash
%r{//+}, # multiple slashes
%r{:} # colon
].freeze
module_function
def allows?(key)
BAD_PATTERNS.none? { |pattern| pattern =~ key } &&
URI.parse(key).path == key
rescue URI::InvalidURIError
false
end
def must_allow!(key)
fail ArgumentError, "invalid key: #{key.inspect}" unless allows?(key)
end
end
end
| true
|
83e5d374d7e793ecf7639568c03437493a56ebaa
|
Ruby
|
sbfaulkner/byebug
|
/test/commands/catch_test.rb
|
UTF-8
| 1,235
| 2.6875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
# frozen_string_literal: true
require "test_helper"
module Byebug
#
# Tests exception catching
#
class CatchTest < TestCase
def test_catch_adds_catchpoints
enter "catch NoMethodError"
debug_code(minimal_program)
assert_equal 1, Byebug.catchpoints.size
end
def test_catch_removes_specific_catchpoint
enter "catch NoMethodError", "catch NoMethodError off"
debug_code(minimal_program)
assert_empty Byebug.catchpoints
end
def test_catch_off_removes_all_catchpoints_after_confirmation
enter "catch NoMethodError", "catch off", "y"
debug_code(minimal_program)
assert_empty Byebug.catchpoints
end
def test_catch_without_arguments_and_no_exceptions_caught
enter "catch"
debug_code(minimal_program)
check_output_includes "No exceptions set to be caught."
end
def test_catch_without_arguments_and_exceptions_caught
enter "catch NoMethodError", "catch"
debug_code(minimal_program)
check_output_includes "NoMethodError: false"
end
def test_catch_help
enter "help catch"
debug_code(minimal_program)
check_output_includes "cat[ch][ (off|<exception>[ off])]"
end
end
end
| true
|
cff4f887984c26146f7e80107adbf0084d48eb66
|
Ruby
|
myoan/sudoku
|
/spec/sudoku/data_validator_spec.rb
|
UTF-8
| 1,227
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
require "rspec"
RSpec.describe Sudoku::DataValidator do
describe ".validate_format!" do
subject { Sudoku::DataValidator.validate_format!(data) }
context "when line size less than 81" do
let(:data) { Array.new(80) { "1" }.join }
it { expect { subject }.to raise_error Exception }
end
context "when line size eq 9" do
let(:data) { Array.new(81) { "1" }.join }
it { expect { subject }.not_to raise_error }
end
context "when line size greater than 9" do
let(:data) { Array.new(82) { "1" }.join }
it { expect { subject }.to raise_error Exception }
end
end
describe ".validate_data!" do
subject { Sudoku::DataValidator.validate_data!(data) }
context "exist whitespace" do
let(:data) { [" "] }
it { expect { subject }.not_to raise_error }
end
context "exist number (not zero)" do
let(:data) { ["123456789"] }
it { expect { subject }.not_to raise_error }
end
context "exist zero" do
let(:data) { ["0"] }
it { expect { subject }.to raise_error Exception }
end
context "exist charactor" do
let(:data) { ["a"] }
it { expect { subject }.to raise_error Exception }
end
end
end
| true
|
b26934d04be386827823da452889444b49051722
|
Ruby
|
saintaze/Hotel-Checkin
|
/hotel.rb
|
UTF-8
| 1,078
| 3.59375
| 4
|
[] |
no_license
|
class Hotel
attr_reader :rooms
def initialize(name = "Transalvania Inn")
@name = name
@rooms = {
"lovelace" => Room.new(2),
"hopper" => Room.new(2),
"turing" => Room.new(1)
}
end
def room_exists?(name)
@rooms.has_key?(name)
end
def check_in(room, guest)
@rooms[room].add_occupant(guest)
end
def has_vacanacy
@rooms.all? {|k, v| v.available_space? > 0}
end
def list_rooms
puts "------ ".brown + "Rooms and Remaining Spaces".brown + " ------".brown
@rooms.each do |k, v|
puts k.capitalize.cyan + " : " + v.available_space?.to_s.brown
end
puts ("=" * 40).brown
end
def list_rooms_with_names
puts "---------- ".brown + "Rooms and Occupants".brown + " ---------".brown
@rooms.each do |k, v|
print k.capitalize.cyan + " : "; puts v.occupants.to_s.brown
end
puts ("=" * 40).brown
end
def validate_room_name(room_name)
until @rooms.has_key?(room_name)
print "Enter a valid room name!"
room_name = gets.chomp.downcase
end
room_name
end
end
| true
|
621368d5984ae879a4cb7530c7a799f61d6b9160
|
Ruby
|
Hansen-Nick/RB101
|
/101-109_practice_problems/easy_2/greeting.rb
|
UTF-8
| 188
| 3.640625
| 4
|
[] |
no_license
|
print "What is your name? "
name = gets.chomp!
if name.split('').include?("!")
name.gsub!("!", '')
puts "HELLO #{name.upcase}. WHY ARE WE SCREAMING?"
else
puts "Hello #{name}."
end
| true
|
c466072bee36789bfb2ca23a6de4ca9545c2fc86
|
Ruby
|
BWStearns/Chess
|
/Chess_piece.rb
|
UTF-8
| 3,467
| 3.375
| 3
|
[] |
no_license
|
# Assumptions
# => White is on the bottom of the board (high indexes)
# => White moves first
#
# require 'debugger'
class Piece
attr_accessor :board, :pos, :color
BOARD_RANGE = (0..7).to_a
CARDINAL_DELTA = [[0,1], [1,0], [-1,0], [0,-1]]
DIAG_DELTA = [[1,1], [-1,-1], [1,-1], [-1,1]]
COMP_DELTA = CARDINAL_DELTA + DIAG_DELTA
def initialize(board = nil, pos, color)# color = :b/:w
@board, @pos, @color = board, pos, color
board[pos] = self
end
private
def on_board?(move)
move.all? { |coord| BOARD_RANGE.include?(coord) }
end
end
class SlidingPiece < Piece
private
def possible_slides(deltas) #NEED to refactor
moves = []
deltas.each do |delta|
potential_move = pos.add_delta(delta)
next unless on_board?(potential_move)
target = board[potential_move]
while on_board?(potential_move) && (target.nil? || target.color != self.color)
moves << potential_move.dup
break if (target != nil && target.color != self.color)
potential_move.add_delta!(delta)
target = board[potential_move] if on_board?(potential_move)
end
end
moves
end
end
class Castle < SlidingPiece
def possible_moves
possible_slides(CARDINAL_DELTA)
end
end
class Bishop < SlidingPiece
def possible_moves
possible_slides(DIAG_DELTA)
end
end
class Queen < SlidingPiece
def possible_moves
possible_slides(COMP_DELTA)
end
end
class Pawn < Piece
attr_accessor :moved
KILLDELTA = [[0,-1],[0,1]]
def initialize(board, pos, color)
super(board, pos, color)
@moved = false # move to main class if castling
end
def possible_moves
regular_move + double_move + kill_move
end
private
def regular_move
color == :w ? [[(pos[0] - 1),(pos[1])]] : [[(pos[0] + 1),(pos[1])]]
end
def double_move #prevent if blocked
return [] if moved
moved = true
color == :w ? [[(pos[0] - 2),(pos[1])]] : [[(pos[0] + 2),(pos[1])]]
end
def kill_move #need to specify that a enemy is in kill pos
# if color == :w
# [[(pos[0]-1),(pos[1]+1)],[(pos[0]-1),(pos[1]-1)]].keep_if do |target|
# (board[target].class != nil) && (board[target].color == :b)
# end #white pawn
# else
# [[(pos[0]+1),(pos[1]+1)],[(pos[0]+1),(pos[1]-1)]].keep_if do |target|
# (board[target].class != nil) && (board[target].color == :w)
# end #black pawn
# end
[]
end
def kill_move
kill_targets = color == :w ? [[-1,1],[-1,-1]] : [[1,1],[1,-1]]
kill_targets.map!.with_index {|target| target.add_delta(pos)}
kill_targets.keep_if do |square|
(board[square] != nil) && (board[square].color != color)
end
end
end
class SteppingPiece < Piece
private
def in_range_moves(deltas) #possibly move to main class if needed
deltas.map { |x, y| [self.pos[0]+x, self.pos[1]+y] }.keep_if do |move|
on_board?(move)
end
end
end
class Knight < SteppingPiece
KNIGHT_DELTA = [1,2,-1,-2].permutation(2).to_a.keep_if {|x,y| x != -y }
def possible_moves
in_range_moves(KNIGHT_DELTA)#narrow to moves that are legal
end
end
class King < SteppingPiece
def possible_moves
in_range_moves(COMP_DELTA)
end
end
class Array
def add_delta(delta, &prc)
self.dup.add_delta!(delta, &prc)
end
def add_delta!(delta, &prc)
prc = Proc.new{ |x,y| x + y } unless prc
self.each_with_index { |item,index| self[index] = prc.call(item,delta[index]) }
end
end
| true
|
8c1910a4db0c99a73162b66670eb090203b5cadc
|
Ruby
|
omahacodeschool/event-attendance
|
/services/meetup.rb
|
UTF-8
| 3,815
| 3.484375
| 3
|
[] |
no_license
|
# Wrapper for the information about one Meetup event, from the Meetup API.
# This class is the bridge between an event from Meetup and an event in our
# database--handling transformation of data as needed.
class Meetup
# event_info - api result converted to json hash
#
# itializing a meetup event will automatically add the event to the event table,
# and delete the original entry if it already existed
def initialize(event_info)
@event_info = event_info
@id = @event_info["id"]
overwriteEntry
save_to_events
end
# this is called by the controller, ultimately runs all functions in this class
#
# main purpose of this function is to loop through each meetup group
# will access the api for each group and get the events
# ultimately loads all events into the event table in the database
def Meetup.groups
meetups = $database.all("meetups")
meetups.each do |group|
events(group["url"])
end
end
# Accesses the meetup API and makes a Meetup object for each event
#
# group - the slug for the group meetup url
#
#
def Meetup.events(group)
response_as_array = JSON.parse(Meetup.response(group))
if response_as_array != []
response_as_array.map do |e|
Meetup.new(e)
end
end
end
# Get events for a group from the Meetup api
#
# group - the slug for the group meetup url
#
# returns the api response as a String
def Meetup.response(group)
uri = URI('https://api.meetup.com/' + group + '/events')
Net::HTTP.get(uri)
end
# Checks if an event is already in the database and delete it if so
#
# Returns nothing, this is necessary to be able to update event info
def overwriteEntry
if $database.checkExistenceOf("events", "id" , @id)
$database.deleteRow("events", "id = '#{@id}'")
end
end
# adds event to the event table of the database
def save_to_events
Event.create({
:id => @id,
:title => title,
:group_name => group_name,
:time => time,
:address => address,
:location => location,
:link => link,
:date => date,
:description => description
})
end
# removes ' from names since they are difficult to insert in sql
#
# returns group name
def group_name
name = @event_info["group"]["name"]
name.gsub(/'/, "")
end
# returns event title
def title
@event_info["name"]
end
# returns event date as yyyy-mm-dd
def date
d = Time.at(@event_info["time"]/1000)
date = d.strftime('%F')
end
# returns event time as hh:mm pm/am
def time
d = Time.at(@event_info["time"]/1000)
time = d.strftime('%I:%M %p')
end
# returns event location or tbd if none provided
def location
if @event_info["venue"]
return @event_info["venue"]["name"]
else
return "TBD"
end
end
# returns event address or empty string if none provided
def address
if @event_info["venue"]
return @event_info["venue"]["address_1"]
else
return ""
end
end
# returns full link url to event
def link
@event_info["link"]
end
# returns the first 2 sentences of the description
def description
cleanedDescription = cleanDescription
return shorten(cleanedDescription)
end
private
def cleanDescription
if @event_info['description']
# Removes all html tags
clean = @event_info["description"].gsub(/<(.*?)>/, "")
# Removes unicode
cleaner = clean.gsub(/\\u\d{4}/, "")
# Removes '
cleanest = cleaner.gsub("'","")
else
@event_info["description"] = "No description"
end
end
def shorten(cleanedDescription)
# Gets the first two sentences
return cleanedDescription.slice!(/\A[^.||!||?]+[.||!||?][^.||!||?]+[.||!||?]/)
end
end
| true
|
3ac334e3ce127642560a173f31f71595290052e7
|
Ruby
|
SupahNickie/WorkingPortfolio
|
/test/features/project_test.rb
|
UTF-8
| 2,626
| 2.609375
| 3
|
[] |
no_license
|
require "test_helper"
# SAD PATH FOR VISITORS
feature "a project cannot be created by a non-user" do
scenario "a site visitor doesn't see the controls to make a new post" do
# Given that some malicious user goes to my site
# When they try to change anything to my projects listing
visit projects_path
# Then they can't find the controls
page.wont_have_content "Edit"
page.wont_have_content "Destroy"
page.wont_have_content "New Project"
end
scenario "a site visitor gets rejected by Pundit if they try to hack around" do
# Given that that malicious douchebag tries to hack to the proper URL
# When they try to do anything, then Pundit doesn't let them
visit edit_project_path(projects(:project1))
page.must_have_content "You are not authorized to perform this action."
visit new_project_path
page.must_have_content "You are not authorized to perform this action."
end
end
# HAPPY PATH FOR THE ADMIN
feature "a project can be CRUD'd by the site admin" do
scenario "the admin can post a new project" do
# Given the admin is signed in
sign_in_user
# When he visits the proper URL to create a new project and fills out valid data
visit new_project_path
fill_in "Title", with: "Test project name"
fill_in "Technologies used", with: "Tech"
fill_in "Body", with: "Test body"
click_on "Create Project"
# The new project should be listed
page.must_have_content "Test project name"
page.must_have_content "Tech"
page.must_have_content "Test body"
end
scenario "the admin can edit an existing project" do
# Given the admin is signed in
sign_in_user
# When he tries to edit an existing project
visit edit_project_path(projects(:project1))
fill_in "Title", with: "Changed title"
fill_in "Technologies used", with: "Changed tech"
fill_in "Body", with: "Changed body"
click_on "Update Project"
# Then the page should reflect that change
page.must_have_content "Changed title"
page.must_have_content "Changed tech"
page.must_have_content "Changed body"
end
scenario "the admin can destroy an existing project" do
# Given the admin is signed in
sign_in_user
# When he tries to delete an existing project
visit projects_path
page.find("tr#project_#{projects(:project1).id}").click_on "Destroy"
# Then the project is deleted
page.wont_have_content "Test project"
page.wont_have_content "Tech stuff"
page.wont_have_content "Test body"
end
end
| true
|
53bd66f613418e5353a1061578bbfba53a70b667
|
Ruby
|
Alex-Linhares/bongard_problem_generator
|
/spec/grid_spec.rb
|
UTF-8
| 15,865
| 2.765625
| 3
|
[] |
no_license
|
# Author:: Max Craigie (@MaxCraigie)
# Copyright:: Copyright (c) 2017 Max Craigie
# License:: Attribution-NonCommercial 3.0 Australia (CC BY-NC 3.0 AU)
require_relative '../grid.rb'
describe Bongard::Grid do
describe '#initialize' do
it 'fails if the cell data does not match the size' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
expect { Bongard::Grid.new(cells, 4) }.to raise_error CellDataShapeError
end
it 'fails if the cell data is incomplete' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8]]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError
end
it 'fails if the cell data is incomplete' do
cells = [[1, 2], [4, 5], [7, 8]]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError
end
it 'fails if the cell data is incomplete' do
cells = [[1, 2, 3], [4, 5, 6]]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataShapeError
end
it 'fails if the cell data contains nil' do
cells = [[1, 2, 3], [4, nil, 6], [7, 8, 9]]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError
end
it 'fails if the cell data contains nil' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9], nil]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError
end
it 'fails if the cell data contains nil' do
cells = [nil, [4, 5, 6], [7, 8, 9]]
expect { Bongard::Grid.new(cells, 3) }.to raise_error CellDataNilError
end
it 'fails if the size is less than 3' do
cells = [[1, 2], [3, 4]]
expect { Bongard::Grid.new(cells, 2) }.to raise_error BelowMinimumSizeError
end
it 'fails if the size is less than 3' do
cells = [[1]]
expect { Bongard::Grid.new(cells, 1) }.to raise_error BelowMinimumSizeError
end
end
describe '#each' do
it 'visits all cells once' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
tally = Hash.new(0)
grid.each do |cell|
tally[cell.value] += 1
end
expect(tally).to eq({
1 => 1,
2 => 1,
3 => 1,
4 => 1,
5 => 1,
6 => 1,
7 => 1,
8 => 1,
9 => 1,
})
end
end
describe '#size' do
it 'returns the size' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
expect(grid.size).to eq(3)
end
it 'returns the size' do
cells = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
grid = Bongard::Grid.new(cells, 4)
expect(grid.size).to eq(4)
end
end
describe '#any?' do
before(:all) do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid = Bongard::Grid.new(cells, 3)
end
it 'returns true if any cell matches the block' do
expect(@grid.any? { |c| c.value == 5 }).to be true
end
it 'returns false if no cell matches the block' do
expect(@grid.any? { |c| c.value == 0 }).to be false
end
end
describe '#all?' do
before(:all) do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid = Bongard::Grid.new(cells, 3)
end
it 'returns true if all cells match the block' do
expect(@grid.all? { |c| c.value > 0 }).to be true
end
it 'returns false if any cell does not match the block' do
expect(@grid.all? { |c| c.value != 2 }).to be false
end
end
describe '#find' do
it 'returns an array of cells that meet the block criteria' do
cells = [[1, 2, 3], [5, 5, 5], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
find_all_results = grid.find_all { |c| c.value == 5 }.map { |c| c.value }
expect(find_all_results).to eq([5, 5, 5])
end
it 'returns an array of cells that meet the block criteria' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
find_all_results = grid.find_all { |c| c.value == 0 }.map { |c| c.value }
expect(find_all_results).to be_empty
end
end
describe '#count' do
it 'returns the number of cells that meet the block criteria' do
cells = [[1, 2, 3], [5, 5, 5], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
expect(grid.count { |c| c.value == 5 }).to eq(3)
end
it 'returns the number of cells that meet the block criteria' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
expect(grid.count { |c| c.value == 5 }).to eq(1)
end
end
describe '#cell_at' do
before(:all) do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid = Bongard::Grid.new(cells, 3)
end
it 'gets the cell at the specified position' do
expect(@grid.cell_at(1, 1).value).to eq(1)
end
it 'gets the cell at the specified position' do
expect(@grid.cell_at(3, 3).value).to eq(9)
end
it 'returns nil if you specify a cell that does not exist' do
expect(@grid.cell_at(0, 0)).to be_nil
end
it 'returns nil if you specify a cell that does not exist' do
expect(@grid.cell_at(0, 1)).to be_nil
end
it 'returns nil if you specify a cell that does not exist' do
expect(@grid.cell_at(4, 0)).to be_nil
end
it 'returns nil if you specify a cell that does not exist' do
expect(@grid.cell_at(4, 4)).to be_nil
end
end
describe '#cells_in_row' do
before(:all) do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid = Bongard::Grid.new(cells, 3)
end
it 'returns an array containing all the cells in the specified row' do
results = @grid.cells_in_row(1).map { |c| c.value }
expect(results).to eq([1, 2, 3])
end
it 'returns an array containing all the cells in the specified row' do
results = @grid.cells_in_row(3).map { |c| c.value }
expect(results).to eq([7, 8, 9])
end
it 'returns nil if you specify a row that does not exist' do
expect(@grid.cells_in_row(0)).to be_nil
end
it 'returns nil if you specify a row that does not exist' do
expect(@grid.cells_in_row(4)).to be_nil
end
end
describe '#cells_in_col' do
before(:all) do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid = Bongard::Grid.new(cells, 3)
end
it 'returns an array containing all the cells in the specified col' do
results = @grid.cells_in_col(1).map { |c| c.value }
expect(results).to eq([1, 4, 7])
end
it 'returns an array containing all the cells in the specified col' do
results = @grid.cells_in_col(3).map { |c| c.value }
expect(results).to eq([3, 6, 9])
end
it 'returns nil if you specify a col that does not exist' do
expect(@grid.cells_in_col(0)).to be_nil
end
it 'returns nil if you specify a col that does not exist' do
expect(@grid.cells_in_col(4)).to be_nil
end
end
describe '#edge_cells' do
it 'returns an array containing all the cells at the edge' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
results = grid.edge_cells.map { |c| c.value }.sort
expect(results).to eq([1, 2, 3, 4, 6, 7, 8, 9])
end
it 'returns an array containing all the cells at the edge' do
cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
grid = Bongard::Grid.new(cells, 4)
results = grid.edge_cells.map { |c| c.value }.sort
expect(results).to eq([1, 2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16])
end
end
describe '#corner_cells' do
it 'returns an array containing all corner cells' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
results = grid.corner_cells.map { |c| c.value }.sort
expect(results).to eq([1, 3, 7, 9])
end
it 'returns an array containing all corner cells' do
cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
grid = Bongard::Grid.new(cells, 4)
results = grid.corner_cells.map { |c| c.value }.sort
expect(results).to eq([1, 4, 13, 16])
end
end
describe '#center_cell' do
it 'returns the center cell if the grid size is odd' do
cells = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid = Bongard::Grid.new(cells, 3)
expect(grid.center_cell.value).to eq(5)
end
it 'returns nil if the grid size is even' do
cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
grid = Bongard::Grid.new(cells, 4)
expect(grid.center_cell).to be_nil
end
end
describe '#walk_dir (#walk_horizontal #walk_vertical)' do
before(:all) do
cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
@grid = Bongard::Grid.new(cells, 4)
end
it 'walks left 1' do
starting_cell = @grid.cell_at(2, 1)
destination = @grid.walk_horizontal(starting_cell, -1)
expect(destination.value).to eq(1)
end
it 'walks right 1' do
starting_cell = @grid.cell_at(1, 1)
destination = @grid.walk_horizontal(starting_cell, 1)
expect(destination.value).to eq(2)
end
it 'walks up 1' do
starting_cell = @grid.cell_at(2, 2)
destination = @grid.walk_vertical(starting_cell, -1)
expect(destination.value).to eq(2)
end
it 'walks down 1' do
starting_cell = @grid.cell_at(3, 3)
destination = @grid.walk_vertical(starting_cell, 1)
expect(destination.value).to eq(15)
end
it 'walks left 3' do
starting_cell = @grid.cell_at(4, 1)
destination = @grid.walk_horizontal(starting_cell, -3)
expect(destination.value).to eq(1)
end
it 'walks right 3' do
starting_cell = @grid.cell_at(1, 1)
destination = @grid.walk_horizontal(starting_cell, 3)
expect(destination.value).to eq(4)
end
it 'walks up 3' do
starting_cell = @grid.cell_at(3, 4)
destination = @grid.walk_vertical(starting_cell, -3)
expect(destination.value).to eq(3)
end
it 'walks down 3' do
starting_cell = @grid.cell_at(1, 1)
destination = @grid.walk_vertical(starting_cell, 3)
expect(destination.value).to eq(13)
end
it 'walks off-grid on the left by 1' do
starting_cell = @grid.cell_at(1, 1)
destination = @grid.walk_horizontal(starting_cell, -1)
expect(destination).to be_nil
end
it 'walks off-grid on the right by 1' do
starting_cell = @grid.cell_at(4, 2)
destination = @grid.walk_horizontal(starting_cell, 1)
expect(destination).to be_nil
end
it 'walks off-grid from the top by 1' do
starting_cell = @grid.cell_at(2, 1)
destination = @grid.walk_vertical(starting_cell, -1)
expect(destination).to be_nil
end
it 'walks off-grid from the bottom by 1' do
starting_cell = @grid.cell_at(2, 4)
destination = @grid.walk_vertical(starting_cell, 1)
expect(destination).to be_nil
end
it 'walks off-grid on the left by 2' do
starting_cell = @grid.cell_at(1, 1)
destination = @grid.walk_horizontal(starting_cell, -2)
expect(destination).to be_nil
end
it 'walks off-grid on the right by 2' do
starting_cell = @grid.cell_at(4, 1)
destination = @grid.walk_horizontal(starting_cell, 2)
expect(destination).to be_nil
end
it 'walks off-grid from the top by 2' do
starting_cell = @grid.cell_at(3, 1)
destination = @grid.walk_vertical(starting_cell, -2)
expect(destination).to be_nil
end
it 'walks off-grid from the bottom by 2' do
starting_cell = @grid.cell_at(4, 4)
destination = @grid.walk_vertical(starting_cell, 2)
expect(destination).to be_nil
end
end
describe '#match?' do
before(:all) do
cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
@grid = Bongard::Grid.new(cells, 4)
end
it 'returns true if the pattern exists' do
expect(@grid.match?('(?1)>(R2,?3)>(D1,?7)>(L1,?6)')).to be true
end
it 'returns false if the pattern does not exist' do
expect(@grid.match?('(?1)>(R2,?1)')).to be false
end
it 'returns true if the pattern exists' do
expect(@grid.match?('(?2)>(R2,?4)')).to be true
end
it 'returns false if the pattern does not exist' do
expect(@grid.match?('(?2)>(R2,?0)')).to be false
end
it 'returns true if the pattern exists' do
expect(@grid.match?('(?2)>(D1,?6)')).to be true
end
end
describe '#==' do
before(:all) do
@cells1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
@grid1 = Bongard::Grid.new(@cells1, 4)
end
it 'is true if the grids have the same values for all cells' do
same_grid = Bongard::Grid.new(@cells1, 4)
expect(@grid1).to eq(same_grid)
end
it 'is false if the grids do not have the same values for all cells' do
cells2 = [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]
different_grid = Bongard::Grid.new(cells2, 4)
expect(@grid1).not_to eq(different_grid)
end
end
# describe '#to_json' do
# it 'converts the grid object to JSON' do
# cells = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
# grid = Bongard::Grid.new(cells, 4)
# grid_as_json = '[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]'
# expect(grid.to_json).to eq(grid_as_json)
# end
# end
describe '#rotate' do
before(:all) do
cells1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
@starting_grid = Bongard::Grid.new(cells1, 4)
cells2 = [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]]
@rotated_right_1 = Bongard::Grid.new(cells2, 4)
cells3 = [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]
@rotated_right_2 = Bongard::Grid.new(cells3, 4)
cells4 = [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]
@rotated_right_3 = Bongard::Grid.new(cells4, 4)
end
it 'returns a copy of the grid rotated once clockwise' do
expect(@starting_grid.rotate(:clockwise, 1)).to eq(@rotated_right_1)
end
it 'returns a copy of the grid rotated twice clockwise' do
expect(@starting_grid.rotate(:clockwise, 2)).to eq(@rotated_right_2)
end
it 'returns a copy of the grid rotated once anticlockwise' do
expect(@starting_grid.rotate(:anticlockwise, 1)).to eq(@rotated_right_3)
end
it 'returns a copy of the grid rotated twice anticlockwise' do
expect(@starting_grid.rotate(:anticlockwise, 2)).to eq(@rotated_right_2)
end
end
describe '#mirror' do
before(:all) do
cells_1a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@grid_1a = Bongard::Grid.new(cells_1a, 3)
cells_1b = [[7, 8, 9], [4, 5, 6], [1, 2, 3]]
@grid_1b = Bongard::Grid.new(cells_1b, 3)
cells_1c = [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
@grid_1c = Bongard::Grid.new(cells_1c, 3)
cells_2a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
@grid_2a = Bongard::Grid.new(cells_2a, 4)
cells_2b = [[13, 14, 15, 16], [9, 10, 11, 12], [5, 6, 7, 8], [1, 2, 3, 4]]
@grid_2b = Bongard::Grid.new(cells_2b, 4)
cells_2c = [[4, 3, 2, 1], [8, 7, 6, 5], [12, 11, 10, 9], [16, 15, 14, 13]]
@grid_2c = Bongard::Grid.new(cells_2c, 4)
end
it 'returns a copy of the grid mirrored vertically' do
expect(@grid_1a.mirror(:vertical)).to eq(@grid_1b)
end
it 'returns a copy of the grid mirrored horizontaly' do
expect(@grid_1a.mirror(:horizontal)).to eq(@grid_1c)
end
it 'returns a copy of the grid mirrored vertically' do
expect(@grid_2a.mirror(:vertical)).to eq(@grid_2b)
end
it 'returns a copy of the grid mirrored horizontaly' do
expect(@grid_2a.mirror(:horizontal)).to eq(@grid_2c)
end
end
end
| true
|
13a23bd73a18970e82ea681dc80c67fc7b5610fd
|
Ruby
|
Odin94/RubyCollision
|
/Rectangle.rb
|
UTF-8
| 1,659
| 3.296875
| 3
|
[] |
no_license
|
class Rectangle
def initialize(x, y, w, h)
@x = x
@y = y
@w = w
@h = h
end
attr_accessor :x, :y, :w, :h
def handle_collisions(collidingRectangles)
for rect in collidingRectangles
resolve_x_collision(rect)
resolve_y_collision(rect)
resolve_xy_collosion(rect) # for diagonal movement it's possible to enter another rect by one pixel without this
end
end
def resolve_x_collision(rect)
while rectv_rectv_collide?(@x + @vel_x, @y, @w, @h, rect.x, rect.y, rect.w, rect.h)
if @vel_x == 0
break
end
if @vel_x.abs < 1.1
@vel_x = abs_decrease_by(@vel_x, 0.5) # prevents leaving 1 pixel space between a rect and this
else
@vel_x = abs_decrease(@vel_x)
end
end
end
def resolve_y_collision(rect)
while rectv_rectv_collide?(@x, @y + @vel_y, @w, @h, rect.x, rect.y, rect.w, rect.h)
if @vel_y == 0
break
end
if @vel_y.abs < 1.1 then
@vel_y = abs_decrease_by(@vel_y, 0.5) # prevents leaving 1 pixel space between a rect and this
else
@vel_y = abs_decrease(@vel_y)
end
end
end
def resolve_xy_collosion(rect)
while rectv_rectv_collide?(@x + @vel_x, @y + @vel_y, @w, @h, rect.x, rect.y, rect.w, rect.h)
if @vel_y == 0 and @vel_x == 0
break
end
@vel_y = abs_decrease(@vel_y)
@vel_x = abs_decrease(@vel_x)
end
end
end
| true
|
1850a0a4e1d9b7c3a8786ee1acf233b591b6a2d4
|
Ruby
|
bluefish733/learn-and-share
|
/hello.rb
|
UTF-8
| 155
| 2.640625
| 3
|
[] |
no_license
|
#! /usr/bin/env ruby
def hello
puts 'hello world!'
puts 'test rebase'
puts 'zjl - 1'
puts 'zjll - 2'
puts 'zjl -3'
puts 'zjl -4'
end
hello()
| true
|
7866be20a1fb2a55ba8e1597411537077d5fa03b
|
Ruby
|
inDuberitably/WrightCSHelpRoom
|
/bots/Email/EmailRequestForm.rb
|
UTF-8
| 308
| 2.546875
| 3
|
[] |
no_license
|
class EmailRequestForm
class << self
attr_accessor :sender, :email_id, :original_msg, :hours, :completed, :total_hours
def to_s
return "Sender:#{self.sender}\nEmail_id:#{self.email_id}\nOriginal_msg:#{self.original_msg}\nHours:#{self.hours}\nCompleted?:#{self.completed}\n"
end
end
end
| true
|
eb7173e65f441849bfa2f7ad5260eecec745010b
|
Ruby
|
chendry/LSY201
|
/test.rb
|
UTF-8
| 438
| 2.859375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'serialport'
serial = SerialPort.new("/dev/tty.usbmodem3a21", 38400)
buffer = []
while true
buffer << serial.readbyte
buffer = buffer.last(2)
if buffer == [ 0xFF, 0xD8 ]
while buffer.last(2) != [ 0xFF, 0xD9 ]
buffer << serial.readbyte
end
File.open("test.jpg", "w") do |f|
f.write buffer.pack("C*")
end
puts "wrote #{buffer.length} bytes"
buffer = []
end
end
| true
|
d54e758b41a503b75f3ceff23d7e4c9968470512
|
Ruby
|
bantic/first-word-api
|
/app/models/poll_item.rb
|
UTF-8
| 1,075
| 2.671875
| 3
|
[] |
no_license
|
class PollItem < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
belongs_to :poll
has_one :photo, dependent: :destroy
def self.normalize_word(word)
word.split(' ')[0].downcase.gsub(/[^a-z]+/, '')
end
def add_word word
normalized_word = self.class.normalize_word(word)
increment_list_item(normalized_word)
increment_total_word_count
end
# Total count for all words for this poll_item
def word_count
(redis.get(word_count_key) || 0).to_i
end
# Array of tuples in desc order i.e. [ ["good", 3], ["great", 2] ]
def sorted_words
start = 0
stop = -1 # all
options = {with_scores: true}
redis.zrevrange(word_list_key, start, stop, options)
end
private
def increment_total_word_count
redis.incr(word_count_key)
end
def increment_list_item(list_item)
amount = 1
redis.zincrby(word_list_key, amount, list_item)
end
def word_list_key
"#{friendly_id}-word-list"
end
def word_count_key
"#{friendly_id}-word-count"
end
def redis
$redis
end
end
| true
|
ba5f41d4f6fb7fd9618e24dbdac4aa52c296f818
|
Ruby
|
Altovate/bearded-octo-adventure
|
/app/helpers/search_conditions.rb
|
UTF-8
| 1,537
| 2.65625
| 3
|
[] |
no_license
|
# This class is used to generate search paramaters for offers
class SearchConditions
def initialize()
@wheres = []
@values = []
end
# Parse Key Value pairs and add them to the array
def parse_param_string(params)
# overriden in subclass
end
# Add where/value clauses to the array
def add(where, value = nil)
@wheres << where
if value.instance_of?(Array)
value.collect {|v| @values << v }
else
@values << value unless value.nil?
end
end
# Return an array of values
def conditions
unless @wheres.nil? or @values.nil?
[@wheres.join(" AND ")] + @values
else
[]
end
end
def joins
["inner join crm_cases on crm_cases.connection_id = crm_connections.id inner join contact_infos on contact_infos.id=crm_connections.contact_info_id inner join email_addresses on email_addresses.contact_info_id=contact_infos.id inner join addresses on addresses.contact_info_id=contact_infos.id inner join phones on phones.contact_info_id=contact_infos.id inner join quoting_results on quoting_results.id=crm_cases.approved_details_id or quoting_results.id=crm_cases.quoted_details_id or quoting_results.id=crm_cases.submitted_details_id inner join carriers on carriers.id=quoting_results.carrier_id inner join crm_policy_types on crm_policy_types.id=quoting_results.policy_type_id inner join states on states.id=contact_infos.state_id inner join crm_statuses on crm_statuses.id=crm_cases.status_id"]
end
end
| true
|
251cf4cc62ce2b9c27f61c223c074f3df6ee21ff
|
Ruby
|
arkency/md_pp_string_calculator
|
/string_calculator_spec.rb
|
UTF-8
| 879
| 3.09375
| 3
|
[] |
no_license
|
require 'rspec'
require './string_calculator'
describe StringCalculator do
let(:calculator) { StringCalculator.new }
specify { expect(calculator). to respond_to(:add) }
specify { expect(calculator.add("")). to eql(0) }
specify { expect(calculator.add("1")). to eql(1) }
specify { expect(calculator.add("1,2")).to eql(3) }
specify { expect(calculator.add("1,2,3,4")).to eql(10) }
specify { expect(calculator.add("1\n2,3")).to eql(6) }
custom_delimiters = ((33..46).to_a + (58..63).to_a).map(&:chr)
custom_delimiters.map do |delimiter|
specify { expect(calculator.add("//#{delimiter}\n3#{delimiter}5")).to eql(8) }
end
specify { expect{calculator.add("-1,-2")}.to raise_error(NegativesNotAllowed, "-1, -2")}
specify { expect(calculator.add("2,1001")).to eql(2) }
end
| true
|
cc68a6ef735160f13db435603084c47528e57ff3
|
Ruby
|
birdcarrie/CacheExercise
|
/MyHashMap/lib/p02_hashing.rb
|
UTF-8
| 567
| 3.375
| 3
|
[] |
no_license
|
class Fixnum
# Fixnum#hash already implemented for you
end
class Array
def hash
hash_key = self.length * 5717
hash_key = hash_key * self[-1] if self[-1].is_a?(Fixnum)
hash_key = hash_key * self[0].ord if self[0].is_a?(String)
hash_key
end
end
class String
def hash
hash_key = self.length * 1741
hash_key = hash_key * self[-1].ord ** 2 if self[0].ord.even?
hash_key = hash_key * self[0].ord ** 2 if self[0].ord.odd?
hash_key = hash_key * self[self.length/2].ord
hash_key
end
end
# class Hash
# def hash
# end
# end
| true
|
767e87dd39fd883cde3865ad49db3496ff864890
|
Ruby
|
oliverpdahl/ttt-8-turn-online-web-sp-000
|
/lib/turn.rb
|
UTF-8
| 1,122
| 4.09375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
display_board(move(board,index))
else
puts "Please enter a valid input"
turn(board)
end
end
def input_to_index(input)
input = input.to_i
return input - 1
end
def display_board(boardIn)
if boardIn == nil
puts "That was an unacceptable input"
else
puts " #{boardIn[0]} | #{boardIn[1]} | #{boardIn[2]} "
puts "-----------"
puts " #{boardIn[3]} | #{boardIn[4]} | #{boardIn[5]} "
puts "-----------"
puts " #{boardIn[6]} | #{boardIn[7]} | #{boardIn[8]} "
end
end
def move(boardIn, input_index, character = "X")
boardIn[input_index] = character
return boardIn
end
# code your #valid_move? method here
def valid_move?(board, index)
return index.between?(0,8) && !(position_taken?(board, index))
end
# re-define your #position_taken? method here, so that you can use it in the #valid_move? method above.
def position_taken?(board, index)
spot = board[index]
if spot == " " || spot == "" || spot == nil
false
else
true
end
end
| true
|
c9d77b1c5662673f09ea63c5dbf47ae88285f412
|
Ruby
|
ifad/eaco
|
/lib/eaco/acl.rb
|
UTF-8
| 5,242
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
module Eaco
##
# An ACL is an Hash whose keys are Designator string representations and
# values are the role symbols defined in the Resource permissions
# configuration.
#
# Example:
#
# authorize Document do
# roles :reader, :editor
# end
#
# @see Actor
# @see Resource
#
class ACL < Hash
##
# Builds a new ACL object from the given Hash representation with strings
# as keys and values.
#
# @param definition [Hash] the ACL hash
#
# @return [ACL] this ACL
#
def initialize(definition = {})
(definition || {}).each do |designator, role|
self[designator] = role.intern
end
end
##
# Gives the given Designator access as the given +role+.
#
# @param role [Symbol] the role to grant
# @param designator [Variadic] (see {#identify})
#
# @return [ACL] this ACL
#
def add(role, *designator)
identify(*designator).each do |key|
self[key] = role
end
self
end
##
# Removes access from the given Designator.
#
# @param designator [Variadic] (see {#identify})
#
# @return [ACL] this ACL
#
# @see Designator
#
def del(*designator)
identify(*designator).each do |key|
self.delete(key.to_s)
end
self
end
##
# @param name [Symbol] The role name
#
# @return [Set] A set of Designators having the given +role+.
#
# @see Designator
# @see Resource
#
def find_by_role(name)
self.inject(Set.new) do |ret, (designator, role)|
ret.tap { ret.add Designator.parse(designator) if role == name }
end
end
##
# @return [Set] all Designators in the ACL, regardless of their role.
#
def all
self.inject(Set.new) do |ret, (designator,_)|
ret.add Designator.parse(designator)
end
end
##
# Gets a map of Actors in the ACL having the given +role+.
#
# This is a useful starting point for an Enterprise summary page of who is
# granted to access a resource. Given that actor resolution is dynamic and
# handled by the application's Designators implementation, you can rely on
# your internal organigram APIs to resolve actual people out of positions,
# groups, department of assignment, etc.
#
# @param name [Symbol] The role name
#
# @return [Hash] keyed by designator with Set of Actors as values
#
# @see Actor
# @see Resource
#
def designators_map_for_role(name)
find_by_role(name).inject({}) do |ret, designator|
actors = designator.resolve
ret.tap do
ret[designator] ||= Set.new
ret[designator].merge Array.new(actors)
end
end
end
##
# @param name [Symbol] the role name
#
# @return [Set] Actors having the given +role+.
#
# @see Actor
# @see Resource
#
def actors_by_role(name)
find_by_role(name).inject(Set.new) do |set, designator|
set |= Array.new(designator.resolve)
end.to_a
end
##
# Pretty prints this ACL in your console.
#
def inspect
"#<#{self.class.name}: #{super}>"
end
alias pretty_print_inspect inspect
##
# Pretty print for +pry+.
#
def pretty_inspect
"#{self.class.name}\n#{super}"
end
protected
##
# There are three ways of specifying designators:
#
# * Passing an +Designator+ instance obtained from somewhere else:
#
# >> designator
# => #<Designator(User) value:42>
#
# >> resource.acl.add :reader, designator
# => #<Resource::ACL {"user:42"=>:reader}>
#
# * Passing a designator type and an unique ID valid in the designator's
# namespace:
#
# >> resource.acl.add :reader, :user, 42
# => #<Resource::ACL {"user:42"=>:reader}>
#
# * Passing a designator type and an Actor instance, will add all
# designators of the given type owned by the Actor.
#
# >> actor
# => #<User id:42 name:"Ethan Siegel">
#
# >> actor.designators
# => #<Set:{
# | #<Designator(User) value:42>,
# | #<Designator(Group) value:"astrophysicists">,
# | #<Designator(Group) value:"medium bloggers">
# | }>
#
# >> resource.acl.add :editor, :group, actor
# => #<Resource::ACL {
# | "group:astrophysicists"=>:editor,
# | "group:medium bloggers"=>:editor
# | }
#
# @param designator [Designator] the designator to grant
# @param actor_or_id [Actor] or [String] the actor
#
def identify(designator, actor_or_id = nil)
if designator.is_a?(Eaco::Designator)
[designator]
elsif designator && actor_or_id.respond_to?(:designators)
designator = designator.to_sym
actor_or_id.designators.select {|d| d.type == designator}
elsif designator.is_a?(Symbol)
[Eaco::Designator.make(designator, actor_or_id)]
else
raise Error, <<-EOF
Cannot infer designator
from #{designator.inspect}
and #{actor_or_id.inspect}
EOF
end
end
end
end
| true
|
8d0350b8b920b50471366ff83f7b9c19abbbb841
|
Ruby
|
robhurring/bingo
|
/app/models/move.rb
|
UTF-8
| 255
| 3.03125
| 3
|
[] |
no_license
|
class Move
def initialize(name, word, found = true)
@name, @word, @found = name, word, found
@hash = Digest::MD5.hexdigest(word)
end
def to_h
{
name: @name,
found: @found,
word: @word,
hash: @hash
}
end
end
| true
|
f3e1398163af1a4877f7e6e4d4e0cac1776b19b9
|
Ruby
|
Harmonickey/EnHabit
|
/Core/Accounts/update_account.rb
|
UTF-8
| 3,519
| 2.515625
| 3
|
[] |
no_license
|
#!/usr/local/bin/ruby
absPath = Dir.pwd
base = absPath.split("/").index("public_html")
deploymentBase = absPath.split("/")[0..(base + 1)].join("/") #this will reference whatever deployment we're in
$: << "#{deploymentBase}/Libraries"
require 'json'
require 'moped'
require 'bson'
require 'PasswordHash'
require 'tools'
def UpdateUser(isAdmin, key, userId, isLandlord, isVerified, isActive, isAdminData, username, firstName, lastName, email, phoneNumber, newPassword)
mongoSession = Moped::Session.new(['127.0.0.1:27017']) # our mongo database is local
mongoSession.use("enhabit") # this is our current database
usrObj = Hash.new
usrObj["Username"] = username
usrObj["FirstName"] = firstName
usrObj["LastName"] = lastName
usrObj["Email"] = email
usrObj["PhoneNumber"] = phoneNumber
usrObj["Password"] = PasswordHash.createHash(newPassword) unless newPassword.nil?
usrObj["IsAdmin"] = (isAdminData.nil? ? false : isAdminData)
usrObj["IsActive"] = (isActive.nil? ? true : isActive)
usrObj["IsVerified"] = (isVerified.nil? ? true : isVerified)
usrObj["IsLandlord"] = (isLandlord.nil? ? false : isLandlord)
queryObj = Hash.new
queryObj["Username"] = username if isAdmin
queryObj[key] = userId unless isAdmin
retMsg = ""
#Username has a unique constraint attached, so we want to catch the raised error just in case
begin
mongoSession.with(safe: true) do |session|
account = session[:accounts].find(queryObj).to_a
# this is a safe query because it is assumed UpdateListing.rb is called
# on an existing account
if (account[0]["LandlordId"].nil? and isLandlord)
usrObj["LandlordId"] = SecureRandom.uuid
landlordObj = Hash.new
landlordObj["Landlord"] = usrObj["Username"]
session[:listings].find(landlordObj).update_all('$set' => {"LandlordId" => usrObj["LandlordId"]})
end
session[:accounts].find(queryObj).update('$set' => usrObj)
end
retMsg = "Okay"
rescue Moped::Errors::OperationFailure => e
if e.message.include? "enhabit.accounts.$Email_1"
retMsg = "That email is already registered with another user!"
end
end
mongoSession.disconnect
return retMsg
end
begin
data = JSON.parse(ARGV[0].delete('\\')) unless ARGV[0].empty?
#we are checking this because it's an optional thing on the UI
newPassword = data["Password"] if not data["Password"].nil? and not data["Password"].empty?
isLandlord = data["IsLandlord"].to_b if not data["IsLandlord"].nil? and not data["IsLandlord"].empty?
isVerified = data["IsVerified"].to_b if not data["IsVerified"].nil? and not data["IsVerified"].empty?
isActive = data["IsActive"].to_b if not data["IsActive"].nil? and not data["IsActive"].empty?
isAdminData = data["IsAdmin"].to_b if not data["IsAdmin"].nil? and not data["IsAdmin"].empty?
id = ARGV[1].split(",")[0] unless ARGV[1].empty?
key = ARGV[2] unless ARGV[2].empty?
isAdmin = ARGV[3].to_b unless ARGV[3].empty?
puts UpdateUser(isAdmin, key, id, isLandlord, isVerified, isActive, isAdminData, data["Username"], data["FirstName"], data["LastName"], data["Email"], data["PhoneNumber"], newPassword)
rescue Exception => e
puts e.inspect
end
| true
|
83c59dac15464b893bb71af50c3e29d45071386e
|
Ruby
|
ErickLedesma/E7CP2A1
|
/ejercicio1.rb
|
UTF-8
| 1,259
| 4.5625
| 5
|
[] |
no_license
|
# Dado el array:
# a = [1, 2, 3, 9, 1, 4, 5, 2, 3, 6, 6]
# 1. Utilizando map aumentar el valor de cada elemento del array en 1.
# 2. Utilizando map convertir todos los valores a float.
# 3. Utilizando map convertir todos los valores a string.
# 4. Utilizando reject descartar todos los elementos menores a 5 en el array.
# 5. Utilizando select descartar todos los elementos mayores a 5 en el array.
# 6. Utilizando inject obtener la suma de todos los elementos del array.
# 7. Utilizando group_by agrupar todos los números por paridad (si son pares, es un
# grupos, si son impares es otro grupo).
# 8. Utilizando group_by agrupar todos los números mayores y menores que 6.
a = [1, 2, 3, 9, 1, 4, 5, 2, 3, 6, 6]
# 1
a.map! { |item| item += 1 }
print a
puts ''
# 2
a_float = a.map { |item| item.to_f }
print a_float
puts ''
# 3
a_string = a.map { |item| item.to_s}
print a_string
puts ''
# 4
a_mayores = a.reject { |item| item < 5}
print a_mayores
puts ''
# 5
a_menores = a.select { |item| item <= 5 }
print a_menores
puts ''
# 6
a_suma = a.inject { |suma, item| suma += item}
puts a_suma
# 7
a_group = a.group_by { |item| item.even? }
print a_group
puts ''
# 8
a_group = a.group_by { |item| item > 6 }
print a_group
puts ''
| true
|
20267b98f992bde57845cbf116e4dc6bfd19ecf7
|
Ruby
|
pcapr-local/pcapr-local
|
/lib/mu/pcap/sctp/chunk/data.rb
|
UTF-8
| 3,206
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
# http://www.mudynamics.com
# http://labs.mudynamics.com
# http://www.pcapr.net
module Mu
class Pcap
class SCTP
class Chunk
class Data < Chunk
FLAG_LAST_SEG = 0x01
FLAG_FIRST_SEG = 0x02
FLAG_UNORDERED = 0x04
attr_accessor :tsn, :sid, :ssn, :ppid
def initialize
super
@type = CHUNK_DATA
@tsn = 0
@sid = 0
@ssn = 0
@ppid = 0
end
def self.from_bytes flags, size, bytes
# Basic validation
Pcap.assert(bytes.length >= 12,
"Truncated data chunk header: 12 > #{bytes.length}")
# Read init chunk header
tsn, sid, ssn, ppid = bytes.unpack('NnnN')
# Create data chunk
data = Data.new
data.flags = flags
data.size = size
data.tsn = tsn
data.sid = sid
data.ssn = ssn
data.ppid = ppid
# Save the payload
data.payload_raw = data.payload = bytes[12..size - 5]
# Return the result
return data
end
def write io, ip
chunk_header = [@type, @flags, @size].pack('CCn')
data_header = [@tsn, @sid, @ssn, @ppid].pack('NnnN')
# Write Chunk header followed by the Data chunk header and payload
io.write(chunk_header)
io.write(data_header)
io.write(@payload_raw)
# Write padding, if necessary
if size < padded_size
(padded_size - size).times do
io.write("\x00")
end
end
end
def ordered?
if 0 == @flags[2]
return true
else
return false
end
end
def first_segment?
if 1 == @flags[1] and 0 == @flags[0]
return true
else
return false
end
end
def last_segment?
if 0 == @flags[1] and 1 == @flags[0]
return true
else
return false
end
end
def complete_segment?
if 1 == @flags[1] and 1 == @flags[0]
return true
else
return false
end
end
def to_s
flags_s = '['
if ordered?
flags_s += 'ordered, '
else
flags_s += 'unordered, '
end
if complete_segment?
flags_s += 'complete segment'
elsif first_segment?
flags_s += 'first segment'
elsif last_segment?
flags_s += 'last segment'
else
flags_s += 'middle segment'
end
flags_s += ']'
return "data(%s, %d, %d, %d, %d, %d, %s)" % [flags_s,
@size,
@tsn,
@sid,
@ssn,
@ppid,
@payload.inspect]
end
end # class Data
end # class Chunk
end # class SCTP
end # class Pcap
end # module Mu
| true
|
02000bd715467436926036988e5f5792d9128b49
|
Ruby
|
ncoe/rosetta
|
/Faulhabers_formula/Ruby/faulhaber.rb
|
UTF-8
| 1,674
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
end
if n == 0 or k == 0 then
return 1
end
num = 1
for i in k+1 .. n do
num = num * i
end
denom = 1
for i in 2 .. n-k do
denom = denom * i
end
return num / denom
end
def bernoulli(n)
if n < 0 then
raise "n cannot be less than zero"
end
a = Array.new(16)
for m in 0 .. n do
a[m] = Rational(1, m + 1)
for j in m.downto(1) do
a[j-1] = (a[j-1] - a[j]) * Rational(j)
end
end
if n != 1 then
return a[0]
end
return -a[0]
end
def faulhaber(p)
print("%d : " % [p])
q = Rational(1, p + 1)
sign = -1
for j in 0 .. p do
sign = -1 * sign
coeff = q * Rational(sign) * Rational(binomial(p+1, j)) * bernoulli(j)
if coeff == 0 then
next
end
if j == 0 then
if coeff != 1 then
if coeff == -1 then
print "-"
else
print coeff
end
end
else
if coeff == 1 then
print " + "
elsif coeff == -1 then
print " - "
elsif 0 < coeff then
print " + "
print coeff
else
print " - "
print -coeff
end
end
pwr = p + 1 - j
if pwr > 1 then
print "n^%d" % [pwr]
else
print "n"
end
end
print "\n"
end
def main
for i in 0 .. 9 do
faulhaber(i)
end
end
main()
| true
|
ef3c86ef48544692906f94cfb786e655d6b98364
|
Ruby
|
JuliaFong/OpenApp
|
/Ruby/Enumerables/enumerable.rb
|
UTF-8
| 7,668
| 4.84375
| 5
|
[] |
no_license
|
#Enumerable Methods
# In Ruby, an object enumerable is when it describes a set of
# items and a method to loop over each of them
# provides collection classes with several traversal and searching methods
# you can mix into your classes
# Enumerable module provides you with methods for
# searching, traversal, and sorting colletions
# you can mix in the enumerable module
# array
# .each
# .each_with_index
# string
# .each_char
# .each_char.with_index
months = ["Jan", "Feb", "Mar", "Apr"]
months.each_with_index do |ele, idx|
puts ele
puts idx
puts "-----"
end
# months.each { |months| puts months}
# i = 0
# while i < months.length
# month = months[i]
# puts month
# i += 1
# end
sentence = "hello world"
sentence.each_char.with_index do |char, idx|
puts char
puts idx
puts "----"
end
# range enumerable
# (start..end).each, iterate from start to end (inclusive)
# (start...end).each, iterate from start to end(excluding end)
arr = ["a", "b", "c"]
arr.each { |ele| puts ele }
arr1 = [1, 2, 3, 4, 5]
arr1.each { |ele| puts ele}
[6, 7, 8, 9, 10].each { |num| puts num }
puts "------"
(0..11).each { |num| puts num }
puts "-----------"
(4...11).each { |num| puts num}
puts "------"
def fizzBuzz(max)
arr = []
(1...max).each do |num|
if num % 3 == 0 && num % 5 != 0
arr << num
end
if num % 3 != 0 && num % 5 == 0
arr << num
end
end
return arr
end
print fizzBuzz(20)
print fizzBuzz(9)
puts"-------"
(0..4).each { puts "hi"}
3.times { puts "hiiiii"}
# Enumerable Methods
people = ["Candace", "Jon", "Jose"]
# iterate over elements of an array using each
people.each { |person| puts person }
# prints
# Candace
# Jon
# Jose
# iterate over elements of an array with index using each_with_index
people.each_with_index do |person, i|
puts person
puts i
puts "-----"
end
# prints
# Candace
# 0
# -----
# Jon
# 1
# -----
# Jose
# 2
# -----
# String Enumerable methods
greeting = "hello"
# iterate over characters of a string using each_char
greeting.each_char { |char| puts char }
#prints
# h
# e
# l
# l
# o
# iterate over characters of a string with index using each_char.with_index
greeting.each_char.with_index do |char, i|
puts char
puts i
puts "-----"
end
# prints
# h
# 0
# ---
# e
# 1
# ---
# l
# 2
# ---
# l
# 3
# ---
# o
# 4
# ---
# OTHER
# repeat a block using times
3.times do
puts "hiiiii"
end
# hi
# hi
# hi
# specify a range of numbers using (start..end) or (start...end)
# including end
(2..6).each {|n| puts n}
puts "-----"
# prints
# 2
# 3
# 4
# 5
# 6
# excluding end
(2...6).each {|n| puts n}
# prints
# 2
# 3
# 4
# 5
# Write a method to_initials that takes in a person's name
# string and returns a string representing their initials.
def to_initials(name)
parts = name.split(" ")
initials = ""
parts.each { |part| initials += part[0] }
return initials
end
puts to_initials("Kelvin Bridges") # => "KB"
puts to_initials("Michaela Yamamoto") # => "MY"
puts to_initials("Mary La Grange") # => "MLG"
puts "-----"
# Write a method first_in_array that takes in an array
# and two elements, the method should return the element
# that appears earlier in the array.
def first_in_array(arr, el1, el2)
if arr.index(el1) < arr.index(el2)
return el1
else
return el2
end
end
puts first_in_array(["a", "b", "c", "d"], "d", "b"); # => "b"
puts first_in_array(["cat", "bird" ,"dog", "mouse" ], "dog", "mouse"); # => "dog"
puts "-------"
# Write a method abbreviate_sentence that takes in a
# sentence string and returns a new sentence where
# every word longer than 4 characters has all of it's
# vowels removed.
def abbreviate_sentence(sent)
words = sent.split(" ")
new_words = []
words.each do |word|
if word.length > 4
new_word = abbreviate_word(word)
new_words << new_word
else
new_words << word
end
end
new_sent = new_words.join(" ")
end
def abbreviate_word(word)
vowels = "aeiouy"
no_vowels = ""
word.each_char do |char|
if !vowels.include?(char)
no_vowels += char
end
end
return no_vowels
end
puts abbreviate_sentence("follow the yellow brick road")
puts abbreviate_sentence("what a wonderful life")
puts "------"
# Write a method format_name that takes in a name string
# and returns the name properly capitalized.
def format_name(str)
parts = str.split(" ")
new_parts = []
parts.each do |part|
new_parts << part[0].upcase + part[1..-1].downcase
end
new_name = new_parts.join(" ")
return new_name
end
puts format_name("chase WILSON") # => "Chase Wilson"
puts format_name("brian CrAwFoRd scoTT") # => "Brian Crawford Scott"
puts "-----------------"
# Write a method is_valid_name that takes in a string and
# returns a boolean indicating whether or not it is a valid name.
def is_valid_name(str)
parts = str.split(" ")
if parts.length < 2
return false
end
parts.each do |part|
if !is_capitalized(part)
return false
end
end
return true
end
def is_capitalized(word)
if word[0] == word[0].upcase && word[1..-1] == word[1..-1].downcase
return true
else
return false
end
end
# puts is_capitalized("Bootcamp")# true
# puts is_capitalized("BootCaMp")# false
puts is_valid_name("Kush Patel") # => true
puts is_valid_name("Daniel") # => false
puts is_valid_name("Robert Downey Jr") # => true
puts is_valid_name("ROBERT DOWNEY JR") # => false
puts "--------"
# Write a method is_valid_email that takes in a string
# and returns a boolean indicating whether or not it is
# a valid email address.
def is_valid_email(str)
parts = str.split("@")
if parts.length != 2
return false
end
left = parts[0]
right = parts[1]
alpha = "abcdefghijklmnopqrstuvwxyz"
left.each_char do |char|
if !alpha.include?(char)
return false
end
end
if right.split(".").length == 2
return true
else
return false
end
end
puts is_valid_email("abc@xy.z") # => true
puts is_valid_email("jdoe@gmail.com") # => true
puts is_valid_email("jdoe@g@mail.com") # => false
puts is_valid_email("jdoe42@gmail.com") # => false
puts is_valid_email("jdoegmail.com") # => false
puts is_valid_email("az@email") # => false
puts "-------"
# Write a method reverse_words that takes in a sentence
# string and returns the sentence with the order of
# the characters in each word reversed.
# Note that we need to reverse the order of characters in
# the words, do not reverse the order of words in the sentence.
def reverse_words(sent)
words = sent.split(" ")
new_words = []
words.each { |word| new_words << word.reverse }
new_sent = new_words.join(" ")
return new_sent
end
puts reverse_words('keep coding') # => 'peek gnidoc'
puts reverse_words('simplicity is prerequisite for reliability') # => 'yticilpmis si etisiuqererp rof ytilibailer'
puts "---------"
# Write a method rotate_array that takes in an array and a
# number. The method should return the array after
# rotating the elements the specified number of times. A
# single rotation takes the last element of the array and moves it to the front.
def rotate_array(arr,num)
num.times do
ele = arr.pop
arr.unshift(ele)
end
return arr
end
print rotate_array([ "Matt", "Danny", "Mashu", "Matthias" ], 1) # => [ "Matthias", "Matt", "Danny", "Mashu" ]
puts
print rotate_array([ "a", "b", "c", "d" ], 2) # => [ "c", "d", "a", "b" ]
puts
| true
|
f37b33a7c13025470ca491c1b5b3b07610af8d42
|
Ruby
|
GIL-GALILEO/alma-user-integration-legacy-converter
|
/lib/classes/user_group.rb
|
UTF-8
| 2,698
| 2.859375
| 3
|
[] |
no_license
|
require './lib/errors/no_group_mapping_error'
# functionality for patron user_group including support for weighting
class UserGroup
attr_accessor :type, :alma_name, :banner_name, :weight, :institution, :exp_days
def initialize(institution, campus, banner_name = nil, fs_codes = nil, class_code = nil)
self.institution = institution
create_group_data banner_name, fs_codes, campus, class_code
copy_config_values
end
def heavier_than?(user_group)
user_group.weight < weight
end
def to_s
alma_name
end
def facstaff?
type == 'facstaff'
end
def student?
type == 'student'
end
private
def copy_config_values
if @data && @data['alma_name'] && @data['weight']
self.alma_name = @data['alma_name']
self.weight = @data['weight'].to_i
self.type = @data['type']
self.exp_days = @data['exp_days']
else
fail NoGroupMappingError, 'Insufficient data to properly map group, using default.'
end
end
def create_group_data(banner_name, fs_codes, campus, class_code)
@data = nil
if banner_name && banner_name != ''
create_from_banner banner_name, campus
elsif fs_codes
fail(
NotImplementedError,
'FS Codes cannot be translated to User Groups if a Campus has been provided.'
) if campus
create_from_fs_codes fs_codes, class_code
end
end
def create_from_banner(banner_name, campus = nil)
groups_settings = if campus
campus.groups_settings
else
institution.groups_settings
end
self.banner_name = banner_name
@data = groups_settings[banner_name]
end
def create_from_fs_codes(fs_codes, class_code)
# ug students who are staff should be set as ug students
if (fs_codes.include?('00') || fs_codes.include?('65')) && fs_codes.include?('02') && class_code == 'U'
@data = institution.groups_settings[institution.groups_data['00']]
elsif (fs_codes.include?('00') || fs_codes.include?('65')) && fs_codes.include?('02') && class_code == 'G'
@data = institution.groups_settings[institution.groups_data['ZZ']]
else
fs_codes.each do |fs_code|
next unless institution.groups_data.key? fs_code
alma_name = institution.groups_data[fs_code]
group_settings = institution.groups_settings[alma_name]
if fs_code == '00' && (class_code == 'G' || class_code == 'P')
group_settings = institution.groups_settings[institution.groups_data['ZZ']]
end
if !@data || group_settings['weight'] > @data['weight']
@data = group_settings
end
end
end
end
end
| true
|
ac14d7a48f57bb451ce14f18a445ab158247bf3e
|
Ruby
|
johnw188/me405
|
/binary_hex_converter.rb
|
UTF-8
| 472
| 2.71875
| 3
|
[] |
no_license
|
filename = ARGV[0]
file = File.open(filename){|file| file.readlines}
re='([01]{8})'
binRegex = Regexp.new(re,Regexp::IGNORECASE);
fullRegex = Regexp.new('(0b[01]{8})')
file.each{|line|
if binRegex.match(line)
number = binRegex.match(line)[1].to_i(2).to_s(16)
if number.length == 1
number = "0" + number
end
line.sub!(/0b[01]{8}/, "0x#{number}")
puts line
end
}
File.open(ARGV[0] + ".out", "wb"){|newfile|
newfile.puts file
}
| true
|
76127d18eb7953f655995ec2eb2c375af0763dc7
|
Ruby
|
Malaber/AdventOfCode2020
|
/code/14.rb
|
UTF-8
| 784
| 3.140625
| 3
|
[] |
no_license
|
require_relative '../input'
require_relative 'handheld/Instruction'
require_relative 'handheld/Computer'
lines = get_lines $PROGRAM_NAME
@bitmask = ""
mem = {}
def apply_bitmask(value)
new_value = value.dup
@bitmask.split("").each_with_index do |char, index|
next if char == "X"
new_value[index] = char
end
new_value.gsub("X", "0")
end
lines.each do |line|
if line.match(/mask/)
@bitmask = line.gsub("mask = ", "").strip
next
end
address_string, value = line.strip.split(" = ")
address = address_string.gsub!("mem[", "").gsub!("]", "").to_i
value_bin = value.to_i.to_s(2)
until value_bin.size == @bitmask.size
value_bin = "X#{value_bin}"
end
mem[address] = apply_bitmask(value_bin).to_i(2)
end
p mem.values.inject(0){|sum,x| sum + x }
| true
|
d2f499bbbdd9d2aebb03fcb5da81ef082dec621d
|
Ruby
|
haruharuharuby/iiita
|
/app/models/article_tagging.rb
|
UTF-8
| 759
| 2.515625
| 3
|
[] |
no_license
|
class ArticleTagging
def initialize(article)
@article = article
end
def register
ActiveRecord::Base.transaction do
@article.save!
update_tags
end
end
def update(article_params)
ActiveRecord::Base.transaction do
@article.update(article_params)
update_tags
end
end
private
def update_tags
new_tag_names = @article.tag_list.split(",")
@article.tags.each do |tag|
rel = @article.article_tag_relations.find_by(tag: tag) unless new_tag_names.include?(tag.name)
rel.destroy! if rel
end
new_tag_names.each do |tag_name|
tag = Tag.find_or_create_by(name: tag_name)
@article.article_tag_relations.find_or_create_by(tag: tag)
end
end
end
| true
|
2771f73ed28055119b298b1ea958b169523f5786
|
Ruby
|
marcolee1107/su-ruby-practice
|
/examples/ex_203.rb
|
UTF-8
| 637
| 2.890625
| 3
|
[] |
no_license
|
# 當SketchUp遇見Ruby - 邁向程式化建模之路(碁峯出版)
# http://books.gotop.com.tw/v_AEC009100
# ex_203.rb - 分別用不同的方法繪出多邊形
mod = Sketchup.active_model # Open model
ent = mod.entities # All entities in model
normal = [0, 0, 1]
radius = 2
# 用add_ngon方法指定6個邊線
ent.add_ngon [0, 0, 0], normal, radius, 6
# 用add_circle方法指定6個線段
ent.add_circle [5, 0, 0], normal, radius, 6
# 用add_ngon方法指定24個邊線
ent.add_ngon [10, 0, 0], normal, radius, 24
# 用add_circle方法指定24個線段(線段數量可省略)
ent.add_circle [15, 0, 0], normal, radius
| true
|
862cac4060ef0ad3ee0cbc1150ad1b2eea26bc44
|
Ruby
|
jss530/playlister-sinatra-v-000
|
/app/models/song.rb
|
UTF-8
| 353
| 2.6875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song < ActiveRecord::Base
belongs_to :artist
has_many :song_genres #going to access these through the join table
has_many :genres, through: :song_genres #can access genres through song_genres table
def slug
name.downcase.gsub(" ","-")
end
def self.find_by_slug(slug)
# binding.pry
Song.all.find{|song| song.slug == slug}
end
end
| true
|
3163843fa9b1309540a53f7f773ddd3357ad3e9d
|
Ruby
|
00s/depot
|
/depot/db/seeds.rb
|
UTF-8
| 4,446
| 2.9375
| 3
|
[] |
no_license
|
# encoding: utf-8
Product.delete_all
Product.create!(title: 'Antologia Front-End',
description:
%{<p>
Esse livro quer ser uma pequena celebração desse sucesso.
Um grupo de 11 autores de renome nacional na comunidade se
juntou para escrever artigos que julgamos relevantes para a Web.
Os capítulos são independentes, cada um com seu autor. A única regra era:
escrever algo memorável, que fizesse a diferença na Web brasileira.
</p>},
image_url: 'Antologia-ebook_capa.png',
price: 36.00)
# . . .
Product.create!(title: 'DevOps 3 na Pratica',
description:
%{<p>
DevOps é um movimento cultural e profissional que está tentando quebrar essas barreiras.
Com o foco em automação, colaboração, compartilhamento de ferramentas e de conhecimento,
DevOps está mostrando que desenvolvedores e engenheiros de sistema têm muito o que
aprender uns com os outros.
</p>},
image_url: 'DevOps-3_capa.png',
price: 49.95)
# . . .
Product.create!(title: 'Rails Test-Driven Development',
description:
%{<p>
Rails Test-Driven Development Prescriptions
Neste livro, você aprenderá sobre TDD, uma das práticas ágeis de desenvolvimento de
software mais populares. TDD faz o desenvolvedor escrever o teste antes mesmo de
implementar o código. Essa simples inversão na maneira de se trabalhar faz com o
que o desenvolvedor escreva código mais testado, com menos bugs, e inclusive
com mais qualidade. Seja profissional, teste seu software!
</p>},
image_url: 'tdd-ruby-ebook_capa.png',
price: 34.95)
Product.create!(title: 'Google Android',
description:
%{<p>
Faça as melhores aplicações Android, com as melhores práticas da área.
Aprenda como publicar a aplicação e tê-la no ar em 1 dia. Saiba como utilizar
o máximo dos aparelhos e crie aplicações extremamente ricas para celulares e tablets!
</p>},
image_url: 'Android-280_capa.png',
price: 34.95)
Product.create!(title: 'O Programador Apaixonado',
description:
%{<p>
Para ter sucesso no mercado de TI atual, é preciso ver sua carreira como se fosse um negócio.
Nesse livro você vai aprender a empreender com a sua carreira e levá-la para o caminho que você
escolheu. O do sucesso. Chad Fowler, famoso desenvolvedor de software e autor de diversos livros,
ensina a construir sua carreira na área de desenvolvimento, passo a passo, seguindo o mesmo
caminho de que se você estivesse criando e vendendo um produto. Afinal de contas, suas habilidades são um produto.
</p>},
image_url: 'Passionate-Programmer-ebook_capa.png',
price: 34.95)
Product.create!(title: 'Java 8 Prático',
description:
%{<p>
Quase 20 anos após sua primeira versão, um novo Java surge com novidades importantes.
Entre os principais recursos, a linguagem recebe default methods, method references e lambdas.
São conceitos simples mas que trazem importantes possibilidades. Durante o livro exploraremos
esses e outros avanços. Sempre com exemplos práticos e apresentando onde utilizá-los, migrando
o código legado do dia a dia para o novo paradigma funcional do Java 8. Com esse tripé de conceitos,
a API conseguiu evoluir de uma maneira interessante. Os pacotes java.util.stream e java.util.function
serão explorados com profundidade, apresentando formas sucintas para trabalhar com coleções e outros
tipos de dados. Streams e Collectors farão parte da sua rotina e serão tão essenciais nas suas
aplicações quanto já são as Collections e o java.io.
</p>},
image_url: 'Java8-ebook_capa.png',
price: 34.95)
Product.create!(title: 'Play Framework',
description:
%{<p>
Nesse livro, Fernando Boaglio ensina como criar uma aplicação do começo ao fim utilizando
o Play Framework na versão Java, passando por situações comuns do dia a dia, indo desde
o tradicional cadastro, até funcionalidades mais avançadas como habilitação de HTTPS,
login integrado com redes sociais e integração com serviços REST. Você vai aprender como
o Play Framework pode te tornar extremamente produtivo.
</p>},
image_url: 'Play-ebooks_capa.png',
price: 34.95)
| true
|
3672dad1328f0d50ae3ee7c2f248813cfd6a1b51
|
Ruby
|
DarkWater666/rubywarrior
|
/rubywarrior.rb
|
UTF-8
| 2,019
| 3.015625
| 3
|
[] |
no_license
|
class Player
attr_accessor :warrior
def initialize()
@max_hp=nil
@current_hp=nil
@prev_hp=nil
@hp_history=[]
@vision=[]
@direction=:forward
@directions=[:forward, :backward]
@reverse_dir=[:backward, :forward]
end
def play_turn(warrior)
@max_hp=warrior.health
self.warrior=warrior
update
return warrior.rescue! @direction if warrior.feel(@direction).captive?
return warrior.attack! @direction if enemy?
return warrior.rest! if hurt? && !range_shot? && !warrior.look(@direction).any?{|elem| elem.enemy?}
action = if (critical? && range_shot?)
look_reverse
elsif !warrior.look(:forward).any?{|elem| elem.captive?} && warrior.look(:forward).any?{|elem| elem.enemy?} && !warrior.look(:backward).any?{|elem| elem.enemy?} && !warrior.feel.enemy?
warrior.shoot!
elsif reverse==true
warrior.pivot!
else
look
end
end
def hurt?
warrior.health<20
end
def critical?
warrior.health<10
end
def enemy?
warrior.feel(@direction).enemy?
end
def empty?
warrior.feel(@direction).empty?
end
def reverse
@directions.each do |dir|
if warrior.feel(dir).wall?
return true
else
return false
end
end
false
end
def need_rest?
warrior.health<@max_hp
end
def range_shot?
warrior.health<@prev_hp
end
def update
@prev_hp=@current_hp
@current_hp=warrior.health
@hp_history<<@current_hp
end
def look
@directions.each do |dir|
if (warrior.feel(dir).stairs?) || (warrior.feel(dir).empty?)
warrior.walk!(dir)
return true
end
end
false
end
def look_reverse
@reverse_dir.each do |dir|
if (warrior.feel(dir).stairs?) || (warrior.feel(dir).empty?)
warrior.walk!(dir)
return true
end
end
false
end
def turn
@direction = (@direction == :forward) ? :backward : :forward
end
end
| true
|
f2765b4f3ba1a26ddb4618174a95b462f3ac4be8
|
Ruby
|
projectblacklight/spotlight
|
/lib/migration/iiif.rb
|
UTF-8
| 3,728
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# frozen_string_literal: true
module Migration
# This migrates FeaturedImages with crop coordinates into IIIF urls which
# are stored in the `iiif_url' field.
class IIIF
def self.run(hostname)
new(hostname).run
end
def initialize(hostname)
@hostname = hostname
end
def run
migrate_featured_images
migrate_contact_avatars
migrate_upload_images
end
attr_reader :hostname
private
def migrate_featured_images
Spotlight::FeaturedImage.all.each do |image|
update_iiif_url(image)
copy_exhibit_thumbnail_from_featured_image(image)
end
end
def migrate_contact_avatars
Spotlight::Contact.all.each do |contact|
avatar = copy_contact_image_to_avatar(contact)
contact.update(avatar: avatar) if avatar
end
end
def migrate_upload_images
Spotlight::Resources::Upload.all.each do |upload|
copy_upload_to_featured_image(upload)
end
end
# Checks if the image was associated as a thumbnail.
# If so, this will update the STI type column of the FeaturedImage as well
# as copy the file over to the correct directory given the new class name
def copy_exhibit_thumbnail_from_featured_image(image)
return unless Spotlight::Exhibit.where(thumbnail_id: image.id).any?
filename = image.read_attribute_before_type_cast('image')
filepath = "public/#{image.image.store_dir}/#{filename}"
image.becomes!(Spotlight::ExhibitThumbnail)
image.save
return unless filename.present? && File.exist?(filepath)
old_file = File.new(filepath)
# AR + STI seems to require that we re-query for this
# otherwise we get an association miss-match
reloaded_image = Spotlight::ExhibitThumbnail.find(image.id)
reloaded_image.image.store!(old_file)
end
# Looks for a file at the old uploader location and copies it to a FeaturedImage
def copy_contact_image_to_avatar(contact)
filename = contact.read_attribute_before_type_cast('avatar')
filepath = "public/uploads/spotlight/contact/avatar/#{contact.id}/#{filename}"
return unless filename.present? && File.exist?(filepath)
old_file = File.new(filepath)
image = contact.create_avatar { |i| i.image.store!(old_file) }
iiif_tilesource = Spotlight::Engine.config.iiif_service.info_url(image)
image.update(iiif_tilesource: iiif_tilesource, iiif_region: avatar_coordinates(contact))
image
end
def copy_upload_to_featured_image(upload)
return unless upload.exhibit # We need exhibit context to re-index, and you can't find an item not in an exhibit
filename = upload.read_attribute_before_type_cast('url')
filepath = "public/uploads/spotlight/resources/upload/url/#{upload.id}/#{filename}"
return unless filename.present? && File.exist?(filepath)
old_file = File.new(filepath)
image = upload.create_upload { |i| i.image.store!(old_file) }
iiif_tilesource = Spotlight::Engine.config.iiif_service.info_url(image)
image.update(iiif_tilesource: iiif_tilesource)
upload.upload_id = image.id
upload.save_and_index
end
def update_iiif_url(image)
image.update(
iiif_tilesource: Spotlight::Engine.config.iiif_service.info_url(image),
iiif_region: coordinates(image)
)
end
def coordinates(image)
return if image.image_crop_x.blank?
[image.image_crop_x, image.image_crop_y, image.image_crop_w, image.image_crop_h].join(',')
end
def avatar_coordinates(contact)
[contact.avatar_crop_x, contact.avatar_crop_y, contact.avatar_crop_w, contact.avatar_crop_h].join(',')
end
end
end
| true
|
3aac0a8448a19d744a6062cf19d00900307bb769
|
Ruby
|
nmgokhale/Ruby-Programming
|
/src/Introduction to Programming/Array Methods & Enumerables/two_dim_arrays.rb
|
UTF-8
| 312
| 4.125
| 4
|
[] |
no_license
|
# Two dimensional arrays
arr = [
["a", "b", "c"],
["d", "e"],
["f", "g", "h"]
]
print arr #[["a", "b", "c"], ["d", "e"], ["f", "g", "h"]]
puts
puts arr[1][1] # e
puts arr[2][0] # f
puts "----------------"
arr.each do |subArr|
print subArr
puts
subArr.each do |element|
puts element
end
end
| true
|
a2a3086b386ca7a23ac981a26c7c8b1d59688f2b
|
Ruby
|
johnktravers/project_euler
|
/problem_10/prime_summation_test.rb
|
UTF-8
| 601
| 3.359375
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
class PrimeSummationTest < Minitest::Test
def prime_summation(max)
max = max - 1 if max.even?
sum = max >= 2 ? 2 : 0
(3..max).step(2) do |num|
prime = true
(2..(num ** 0.5 + 1)).each do |n|
break prime = false if num % n == 0
end
sum += num if prime
end
sum
end
#----------------- Tests -----------------#
def test_prime_summation
assert_equal 17, prime_summation(10)
assert_equal 76127, prime_summation(1000)
assert_equal 142913828922, prime_summation(2000000)
end
end
| true
|
58181ea17adf2045f399fa5127b4076833b7d877
|
Ruby
|
mwagner19446/wdi_work
|
/w01/d05/INSTRUCTOR/objects.rb
|
UTF-8
| 1,435
| 4.21875
| 4
|
[] |
no_license
|
# Song
# - title
# - artist
# - genre
# - play ("Tommy by The Who is playing.")
# Instantiate a few songs to test your class.
class Song
def title=(title)
@title = title
end
def title()
return @title
end
# def title()
# return "Hamburgers"
# end
def artist=(artist)
@artist = artist
end
def artist()
return @artist
end
def genre=(genre)
@genre = genre
end
def genre
return @genre
end
def play
# title = "Shmee"
# artist = "Garbage"
return "#{self.title()} by #{self.artist()} is playing."
end
end
hips_dont_lie = Song.new
hips_dont_lie.title=("Hips Don't Lie")
hips_dont_lie.artist=("Shakira")
hips_dont_lie.genre=("Puhp")
puts hips_dont_lie.title()
puts hips_dont_lie.artist()
puts hips_dont_lie.genre()
puts hips_dont_lie.play()
# Playlist
# - songs
# - start (a random song starts)
# - skip (another random song is played)
# - add songs
# - remove songs
# - currently playing song
class Playlist
def initialize()
@songs = []
end
def add_song(song)
self.songs().push(song)
end
def remove_song(song)
self.songs().delete(song)
end
def start
@current_song = self.songs().sample
puts @current_song.play()
end
def skip
self.start()
end
def current_song
return @current_song
end
def songs
return @songs
end
end
playlist = Playlist.new
playlist.add_song(hips_dont_lie)
playlist.start()
| true
|
989e99c1b38499e6a585f2b27d58a1665c5c97cd
|
Ruby
|
d3chapma/daily_bible
|
/app/models/reference.rb
|
UTF-8
| 419
| 3.203125
| 3
|
[] |
no_license
|
class Reference
def initialize(book_name, chapter, verse)
@book = Book.new(book_name)
@chapter = @book.chapters[chapter.to_i-1]
@verse = verse.to_i
end
def self.parse(ref)
_, book_name, chapter, verse = ref.match(/(.+)\+(\d+):(\d+)/).to_a
new(book_name, chapter, verse)
end
def to_s
"#{@book}+#{@chapter}:#{@verse}"
end
def chunk
@chapter.chunk_containing(@verse)
end
end
| true
|
eead04a1cf5e21fddb6383a75f4a9ade9a474846
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/house/b5cbdd46e0b14c2a894b6753f56bbed4.rb
|
UTF-8
| 1,046
| 3.578125
| 4
|
[] |
no_license
|
class House
def self.recite
new.recite
end
def recite
result = ""
(1..12).each { |i|
phrase = ""
count = 1
while count <= i
phrase = "#{what_it_is(count)}" + phrase
count += 1
end
phrase = "This is " + phrase
result += phrase
}
result.chomp
end
def what_it_is(n)
case(n)
when 1
"the house that Jack built.\n\n"
when 2
"the malt\nthat lay in "
when 3
"the rat\nthat ate "
when 4
"the cat\nthat killed "
when 5
"the dog\nthat worried "
when 6
"the cow with the crumpled horn\nthat tossed "
when 7
"the maiden all forlorn\nthat milked "
when 8
"the man all tattered and torn\nthat kissed "
when 9
"the priest all shaven and shorn\nthat married "
when 10
"the rooster that crowed in the morn\nthat woke "
when 11
"the farmer sowing his corn\nthat kept "
when 12
"the horse and the hound and the horn\nthat belonged to "
end
end
end
| true
|
b9077c4f79676cb92a0245d5a166088bcd765041
|
Ruby
|
jfernapa/sinatra_roman_numerals
|
/roman_numerals.rb
|
UTF-8
| 953
| 3.640625
| 4
|
[] |
no_license
|
class RomanNumerals
ONE_ROMAN = "I"
def convert(number)
begin
roman_number = ONE_ROMAN * Integer(number)
equivalences = {'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5}
equivalences.each do |letter, number|
roman_number = roman_number.gsub(ONE_ROMAN * number, letter)
end
exceptions = { 'DCCCC' => 'CM', 'CCCC' => 'CD', 'LXXXX' => 'XC', 'XXXX' => 'XL', 'VIIII' => 'IX', 'IIII' => 'IV' }
exceptions.each do |wrong, correct|
roman_number = roman_number.gsub(wrong, correct)
end
if roman_number.empty?
"#{number} can not convert to roman numerals"
else
"#{number} is #{roman_number} in roman numerals"
end
rescue ArgumentError
return "'#{number}' can not convert to roman numerals"
end
end
end
| true
|
d35c0f5ff25b341288c4e714dfc5b633c594aed8
|
Ruby
|
28221122/mobileautomatization
|
/features/screens/autorized_whishlist.rb
|
UTF-8
| 1,001
| 2.65625
| 3
|
[] |
no_license
|
class AutorizedWhiwlist
def initialize
@first_item_homescreen = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/banner"]')
@items_to_be_liked = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/tbLove"]')
@wishlist_check_for_brand = Elements.new(:xpath,'//*[@resource-id="com.view9.foreveryng:id/cardview_category_detail"]')
@all_wishlist_buttons = Elements.new(:id , 'cardview_category_detail')
end
def click_first_item_homescreen
@first_item_homescreen.click
end
def click_all_wishlist_items
@items_to_be_liked.click_every_element_in_the_list
end
def check_wishlist_for_one_brand(expected)
all_elements = @wishlist_check_for_brand.get_multiple_elements
all_elements.each_index do |index|
actual = all_elements[index].text
raise "User name is not the same: Expected #{expected} , Actual: #{name}" unless actual == expected
end
end
def click_first_brand_button
@first_brand_button.click
end
end
| true
|
aada2440b6535dd1595ba2b35336032dcc694712
|
Ruby
|
annacarey/oo-relationships-practice-nyc-web-111819
|
/app/models/Location.rb
|
UTF-8
| 634
| 3.265625
| 3
|
[] |
no_license
|
class Location
attr_reader :name
@@all = []
def initialize(name)
@name = name
self.class.all << self
end
def self.all
@@all
end
def sessions
Session.all.select do |session|
session.location == self
end
end
def trainers
sessions.map do |session|
session.trainer
end
end
def clients
sessions.map do |session|
session.client
end
end
def self.least_clients
self.all.min_by do |location|
location.clients.length
end
end
end
| true
|
3cc17904dda0fb30a6929a08badc2e2ceb511044
|
Ruby
|
periode/thesis
|
/code/render.rb
|
UTF-8
| 4,424
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby
require 'kramdown'
require 'erb'
require 'fileutils'
attention = `git diff --name-only --cached`
attention = attention.split("\n")
unless attention.length
puts "nevermind"
exit
end
puts "time to publicize"
the_only = Time.now # to
remember = "#{the_only.year}-#{the_only.month}-#{the_only.day}-#{the_only.hour}#{the_only.min}"
FileUtils.mkdir_p 'docs/' + remember
puts "to set everything up"
everything = []
attention.each do | for_this_fragment |
there_is_a = /^(?!admin)(.*md)$/
if there_is_a.match for_this_fragment
everything << for_this_fragment
puts for_this_fragment
puts "and"
end
end
fashion = %{
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>works in public</title>
<link rel="stylesheet" href="/style.css"/>
</head>
<body>
<div class="way">
<a href="/index.html">cover</a>
</div>
<div class="holding tight">
<%= rest %>
</div>
</body>
</html>
}
everything.each do | it |
# everyone needs a place to stay
es = /(\w*\/?\w*\/?\w*\/?)\w+/
puts it
a_home = it.match(es)
FileUtils.mkdir_p 'docs/'+remember+'/'+a_home.to_s#tay
fond = File.open(it)
form = fond.read
rest = Kramdown::Document.new(form).to_html
finally = ERB.new(fashion).result(binding)
til = it.sub! '.md', '.html'
til = remember + '/' + til
File.write('docs/'+til, finally)
fond.close
end
# i need to find all the years
# and then all the months
# and then all the
all = Hash.new
traces = []
express = /(\d+)-(\d+)-(\d+)-(\d+)\/(.*\.html)/
files = Dir.glob("docs/**/**").sort_by { |f| File.mtime(f) }
chaos = files.reverse
chaos.each do | bit |
deconstruct = bit.match(express)
if deconstruct
year = deconstruct[1]
if !all.has_key? year
all[year] = Hash.new # we create a new array to store all the months, only if that doesn't exist already
end
month = deconstruct[2]
if !all[year].has_key? month
all[year][month] = Hash.new
end
day = deconstruct[3]
if !all[year][month].has_key? day
all[year][month][day] = Hash.new
end
time = deconstruct[4]
if !all[year][month][day].has_key? time
all[year][month][day][time] = Array.new
end
all[year][month][day][time] << deconstruct[5]
end
end
puts "they need to be together"
space = %{
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>the role of aesthetics in source code understandings</title>
</head>
<body>
<style>
@import url('https://rsms.me/inter/inter.css');
body {
background-color: white;
font-family: 'Inter', sans-serif;
}
.holding{
margin: auto;
}
.tight{
width: 70%;
}
</style>
<div class="holding tight">
<h1>the role of aesthetics in the understandings of source code</h1>
<p>what you see here is the automatic rendering of all the notes taken during <a href="https://pierredepaz.net">my</a> phd thesis. since it is a thesis on source code, might as well show its own source code.</p>
<p>the main question i'm asking is: <i>how do aesthetics enable understanding in source code, what kind of understanding(s) might derive from their presence, or absence, and how does this highlight code as textual matter?</i> this touches upon issues of style, clarity, epistemology, psychology, programming and literature.</p>
<p>this doctoral work is being done at the university of sorbonne nouvelle, under the joint direction of alexandre gefen (Paris-3, CNRS) and nick montfort (MIT Comparative Media Studies).</p>
<p>you can start with the <a href="latest.pdf" target="_blank">most recent summary</a>, the current state of the <a href="thesis.pdf" target="_blank">final manuscript</a> or the whole <a href="https://github.com/periode/thesis">github repository</a>.</p>
<hr/>
<% all.each_key do | year | %>
<% all[year].each_key do | month | %>
<% all[year][month].each_key do | day | %>
<h2> <%= year %> - <%= month %> - <%= day %> </h2>
<% all[year][month][day].each_key do | time | %>
<h3> <%= time %> </h3>
<% all[year][month][day][time].each do | trace | %>
<li><a href="<%= year+"-"+month+"-"+day+"-"+time+"/"+trace %>"><%= trace %></a></li>
<% end %>
<% end %>
<% end %>
<% end %>
<% end %>
</div>
</body>
</html>
}
public = ERB.new(space).result(binding)
File.write("docs/index.html", public)
puts "then"
puts "it's done, for now"
| true
|
f852cd437f7b59240838a8ce91e97d8fc5a1e791
|
Ruby
|
jjuarez/jabber_notifier
|
/lib/jabber_notifier/cli.rb
|
UTF-8
| 416
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require 'yaml'
require 'jabber_notifier/options_parser'
require 'jabber_notifier/connection'
module JabberNotifier
class Cli
def self.run(options)
config = YAML.load_file(options[:config])
connection = Connection.new(:username =>config["username"], :password =>config["password"], :delay =>options[:delay].to_f)
connection.notify(options[:to], options[:message])
end
end
end
| true
|
7ad402efc4cbc26cdaddb36171d21e1b3f83bfbe
|
Ruby
|
BlueMeadow/L3
|
/S6/PROJET/Hanjie-master/Generation/Picture.rb
|
UTF-8
| 2,259
| 3.359375
| 3
|
[] |
no_license
|
require 'rmagick'
include Magick
class Magick::Pixel
def isBlack?()
(self.green + self.red + self.blue) / 3 < (QuantumRange / 2)
end
end
class Picture
@origine # Contient l'image original
@indicesH # Groupe d'indices de colonne (array[array])
@indicesV # Groupe d'indices de ligne (array[array])
@precision # Precision souhaité (variation de couleur)
@dimension # Dimension souhaité (5x5, 10x10, 15x15)
private_class_method :new
attr_reader :precision
def Picture.creer(imageName,dimension)
new(imageName,dimension)
end
def initialize(imageName,dimension)
@origine = Image.read(imageName).first.resize_to_fill(dimension,dimension)
@indicesH = []
@indicesV = []
@precision = 1
@dimension = dimension
end
def getIndicesH(i)
return @indicesH[i]
end
def getIndicesV(i)
return @indicesV[i]
end
def toBoolean
# image --> [true,true,false,true] true = blanc
# [false,true,false,false] false = noir
# [true,true,true,true]
grid = []
image = toGrey(@precision)
image.each_pixel{|pixel| grid << !pixel.isBlack?}
grid.each_slice(image.columns).to_a
end
def calcIndice
# [true,true,false,true] [2,1]
# [false,true,false,false] --> [1]
# [true,true,true,false,true] [3,1]
grid = self.toBoolean
@indicesH = groupeIndicesGrid(grid)
@indicesV = groupeIndicesGrid(grid.transpose)
return grid
end
def to_s
toBoolean.map{|ligne| ligne.map{|pix| pix ? "+":" "}.join}.join("\n")
end
def printIndice
afficherIndices(@indicesH)
print "\n\n"
afficherIndices(@indicesV)
end
# PRIVATE CLASS
private
def toGrey(precision)
@origine.quantize(256,GRAYColorspace).edge(precision)
end
def groupeIndicesLigne(ligne)
indices = []
i = 0
ligne.each_with_index{|etat,index|
if etat then
i += 1
end
if (index == ligne.length-1 || !etat) && (i !=0) then
indices << i
i = 0
end
}
return indices
end
def groupeIndicesGrid(grid)
indices = []
grid.each{|ligne| indices << groupeIndicesLigne(ligne)}
return indices
end
def afficherIndices(grid)
i = 1
grid.each{|g|
print i," : ", g, "\n"
i += 1
}
end
end
# i = Picture.creer("apple.bmp",10);
# puts i
# i.calcIndice
# i.printIndice
#p i.getIndicesV(0)
| true
|
b486346a10cd4ec53db5f1f40c885e8e9c962aa6
|
Ruby
|
b-dalton/04_ruby_tutorial
|
/strings_arrays_time/time.rb
|
UTF-8
| 462
| 3.34375
| 3
|
[] |
no_license
|
require 'date'
# s = String.new("A man, a plan, a canal—Panama!")
# t = s.split(", ")
# p t
# a = Array.new
# a << 3 << 4
# puts a
# now = Time.now
# puts now
moon_landing = Time.new(1969, 7, 20, 20, 17, 40)
# puts moon_landing.day
# puts now - moon_landing
# DAYNAMES = Date::DAYNAMES
# DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
# puts DAYNAMES[moon_landing.wday]
# puts DAYNAMES[Time.now.wday]
puts now
| true
|
6e64453d405288e6a5863bca64506cb5cf9d5a20
|
Ruby
|
JimMcL/sampleIt
|
/lib/view_angle.rb
|
UTF-8
| 4,169
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
# Class for working with view angles of photos of specimens.
# The angle is specified by latitude (phi) and longitude (lambda). Photos
# are assumed to be directed towards the centre of the specimen, with
# the top of the specimen facing up or else the front of the specimen
# facing towards the left. Longitude (lamba) is 0 at the middle of the
# face. Units are (integral) degrees.
# Hence, an anterior (frontal) view is (0, 0), a lateral view (taken from the
# specimen's left side) is (0, 90), and a dorsal view is (90, 0).
#
# See also http://insects.oeb.harvard.edu/etypes/specificimages.htm
class ViewAngle
include Comparable
attr_accessor :phi, :lambda
NAMED_ANGLES = {lateral: [0, 90],
dorsal: [90, 0],
ventral: [-90, 0],
anterior: [0, 0],
posterior: [0, 180],
lateral_right_side: [0, -90]
}
SYNONYMS = {frontal: [0, 0],
face: [0, 0],
underside: [-90, 0]}
# Returns the list of named angles
def self.angle_names
NAMED_ANGLES.keys
end
# If params contains a parameter such as {view_angle: 'lateral'}, removes it and
# adds {view_phi: 0, view_lambda: 90}
def self.expand_query_params(params)
if params.key?(:view_angle) && (va = ViewAngle.new(params[:view_angle])) && va.valid?
params = params.merge(view_phi: va.phi, view_lambda: va.lambda)
end
params.except(:view_angle)
end
# Creates a ViewAngle.
# Takes either a view name (a symbol or string), phi and lambda, or a name and relative phi and lambda.
#
# Examples:
# ViewAngle.new(:lateral) # Taken from left side
# ViewAngle.new(0, 90) # Same as :lateral
# ViewAngle.new('0, 90') # Same as :lateral
# ViewAngle(:dorsal) # Taken from above, head towards the left (by convention)
# ViewAngle(:dorsal, -5, 90) # Taken from above by 5 degrees towards dorsal
def initialize(phi_or_name, lambda_or_relative_phi = 0, relative_lambda = 0)
if phi_or_name.is_a?(Numeric) && lambda_or_relative_phi.is_a?(Numeric)
@phi = phi_or_name
@lambda = lambda_or_relative_phi
elsif !phi_or_name.blank?
# Check for 2 angles in a string
phi_or_name = phi_or_name.to_s
if (m = phi_or_name.scan(/[+-]?\d+/)) && m.length == 2
@phi = m[0].to_i
@lambda = m[1].to_i
else
# Check for name of an angle
key = phi_or_name.parameterize(separator: '_').intern
na = NAMED_ANGLES[key]
na = SYNONYMS[key] if na.blank?
raise ArgumentError, "Invalid named view angle '#{phi_or_name}', require one of [#{NAMED_ANGLES.keys.join(', ')}]" if na.blank?
@phi = na[0]
@lambda = na[1]
# Add relative angle if specified
if lambda_or_relative_phi.is_a?(Numeric) && relative_lambda.is_a?(Numeric)
@phi += lambda_or_relative_phi
@lambda += relative_lambda
end
end
end
end
def valid?
!@phi.nil? && !@lambda.nil? && @phi >= -90 && @phi <= 90 && @lambda >= -180 && @lambda <= 180
end
def to_s
valid? ? (name && name.humanize || "#{@phi}, #{@lambda}") : ''
end
def inspect
"ViewAngle(phi: #{@phi}, lambda: #{@lambda}, name: #{name})"
end
def description
valid? ? "#{to_s.humanize} view" : ''
end
def name
nm = false
NAMED_ANGLES.each do |key, value|
nm = key.to_s if value[0] == @phi && value[1] == @lambda
end
nm
end
def hash
[phi, lambda].hash
end
def eql?(other)
self == other || (other.is_a?(ViewAngle) && phi == other.phi && lambda == other.lambda)
end
# Define a somewhat arbitrary ordering, based on how photos should appear
def <=>(other)
if other.is_a? ViewAngle
nm1 = name
nm2 = other.name
# Named angles come first
return -1 if nm1 && !nm2
return 1 if !nm1 && nm2
# String comparison if neither is named
return to_s <=> other.to_s if !nm1
# Named angles use the order defined in NAMED_ANGLES
idx1 = NAMED_ANGLES.keys.index(nm1.to_sym)
idx2 = NAMED_ANGLES.keys.index(nm2.to_sym)
idx1 <=> idx2
end
end
end
| true
|
76e73f4aa830046a84748d275fcbeb31df7e4855
|
Ruby
|
johnantoni/plugin.tweakify
|
/lib/common/active_record.rb
|
UTF-8
| 339
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
class ActiveRecord::Base
def self.to_a_simplify
# takes table object and breaks it down into a simple array
return self.to_enum.map {|e| e::id }
end
def self.simply_paginate(id)
# converts table into array, then finds prev/next/current & returns as hash
return self.to_a_simplify.simply_paginate_array(id)
end
end
| true
|
5ba3b8edfc283490351aad1e5899ca4d7b61cc85
|
Ruby
|
JEG2/ender
|
/test/tc_config.rb
|
UTF-8
| 864
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby -wKU
require "test/unit"
require "tempfile"
require "config"
class TestConfig < Test::Unit::TestCase
def test_config_returns_a_customized_ostruct
assert_instance_of(OpenStruct, config)
end
def test_config_object_is_passed_into_the_file_and_used_to_set_options
c = config(<<-END_SETTINGS)
config.string_setting = "just a String"
config.integer_setting = 41
END_SETTINGS
assert_equal("just a String", c.string_setting)
assert_equal(41, c.integer_setting)
end
def test_exceptions_bubble_up_to_the_caller
assert_raise(RuntimeError) do
config(<<-END_ERROR)
raise "Oops!"
END_ERROR
end
end
private
def config(content = String.new)
cf = Tempfile.new("ender_config_test")
cf << content
cf.flush
Config.load_config_file(cf.path)
end
end
| true
|
094afe2138299494f6f6b683d8471a870e21360b
|
Ruby
|
rayleyva/ArangoDB
|
/3rdParty/mruby/mrblib/struct.rb
|
UTF-8
| 854
| 3.46875
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
##
# Struct
#
# ISO 15.2.18
class Struct
##
# Calls the given block for each element of +self+
# and pass the respective element.
#
# ISO 15.2.18.4.4
def each(&block)
self.class.members.each{|field|
block.call(self[field])
}
self
end
##
# Calls the given block for each element of +self+
# and pass the name and value of the respectiev
# element.
#
# ISO 15.2.18.4.5
def each_pair(&block)
self.class.members.each{|field|
block.call(field.to_sym, self[field])
}
self
end
##
# Calls the given block for each element of +self+
# and returns an array with all elements of which
# block is not false.
#
# ISO 15.2.18.4.7
def select(&block)
ary = []
self.class.members.each{|field|
val = self[field]
ary.push(val) if block.call(val)
}
ary
end
end
| true
|
c249e8b59fccbe7b0efd0be155e1daef95a11585
|
Ruby
|
jparbros/leaderboard
|
/app/models/concerns/input_filters.rb
|
UTF-8
| 2,821
| 2.53125
| 3
|
[] |
no_license
|
module InputFilters
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def search(params)
inputs = self.includes(:user, :departament)
inputs = inputs.by_user(params[:user_id]) if params[:user_id]
inputs = inputs.by_today if params[:period] == 'today'
inputs = inputs.by_week if params[:period] == 'week'
inputs = inputs.by_month if params[:period] == 'month'
inputs = inputs.by_quarter if params[:period] == 'quarter'
inputs = inputs.by_year if params[:period] == 'year'
inputs = inputs.by_departament(params[:departament_id]) if params[:departament_id]
inputs = inputs.group_by_user if params[:group_by_user]
inputs = inputs.paginate(page: params[:page], per_page: 20) if params[:page]
inputs = inputs.get_ordered(params) if params[:order]
inputs
end
def by_today
where(date: Date.today)
end
def by_week
where('date >= ? and date <= ?', Date.today.at_beginning_of_week, Date.today.at_end_of_week)
end
def by_month
where('date >= ? and date <= ?', Date.today.beginning_of_month, Date.today.end_of_month)
end
def by_quarter
where('date >= ? and date <= ?', Date.today.beginning_of_quarter, Date.today.end_of_quarter)
end
def by_year
where('date >= ? and date <= ?', Date.today.beginning_of_year, Date.today.end_of_year)
end
def by_user user_id
where(user_id: user_id)
end
def by_departament(departament_id)
if departament_id == 'all_teams'
joins(:departament)
else
joins(:departament).where(departaments: {id: departament_id})
end
end
def group_by_user
all.group_by {|input| input.user_id}.values.map do |values|
user = values.first.user
{realized: values.map(&:value).inject(0, &:+).round(2), username: user.name, picture: user.avatar.url(:medium), target: user.target}
end.sort {|x,y| y[:realized] <=> x[:realized]}.take(5)
end
def get_leader
all.max
end
def get_ordered(params)
inputs = order_by_name(params[:order_direction]) if params[:order] == 'name'
inputs = order_by_date(params[:order_direction]) if params[:order] == 'date'
inputs = order_by_value(params[:order_direction]) if params[:order] == 'value'
inputs = order_by_team(params[:order_direction]) if params[:order] == 'team'
inputs
end
def order_by_name(direction = 'DESC')
order("users.name #{direction}")
end
def order_by_date(direction = 'DESC')
order("inputs.date #{direction}")
end
def order_by_value(direction = 'DESC')
order("inputs.value #{direction}")
end
def order_by_team(direction = 'DESC')
order("departaments.name #{direction}")
end
end
end
| true
|
5c18ab4b04705437902dc4b522af2e90632ba8fb
|
Ruby
|
szib/oo-relationships-practice-london-web-career-040119
|
/app/models/IMDB/Movie.rb
|
UTF-8
| 132
| 2.5625
| 3
|
[] |
no_license
|
require_relative './VisualProduct'
class Movie < VisualProduct
def self.most_actors
all.max_by(&:number_of_actors)
end
end
| true
|
145fddeecb88889417783957828b40222f2bd4d3
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/bob/2ea7d59f423b4a75b8d2db7c8b796d70.rb
|
UTF-8
| 774
| 3.953125
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
class Bob
@@responses = {
question: "Sure.",
silence: "Fine. Be that way!",
yelling: "Woah, chill out!",
default: "Whatever."
}
def hey(phrase)
result = :default
case
when silence?(phrase)
result = :silence
when yelling?(phrase)
result = :yelling
when question?(phrase)
result = :question
end
@@responses[result]
end
private
def yelling?(phrase)
if phrase.strip.empty?
False
else
phrase.eql? phrase.upcase
end
end
def question?(phrase)
phrase.end_with? "?"
end
def silence?(phrase)
phrase.strip.empty?
end
end
| true
|
bd2c4e21ed88d79a8d95472c1c85de159e66813b
|
Ruby
|
vgelinski/home_sinatra
|
/src/model/user.rb
|
UTF-8
| 687
| 2.796875
| 3
|
[] |
no_license
|
require 'data_mapper'
require 'digest/sha1'
class User
include DataMapper::Resource
property :id, Serial
property :name, String
property :password, String
property :salt, String
def User.create(params)
params[:salt] = (0..8).map{(33 + rand(92)).chr}.join
plain_pass = params[:password]
params[:password] = Digest::SHA1.hexdigest plain_pass + params[:salt]
super(params)
end
def initialize(params)
attribute_set :name, params[:name]
attribute_set :password, params[:password]
attribute_set :salt, params[:salt]
end
def check(m_name, m_password)
name == m_name && (Digest::SHA1.hexdigest(m_password + salt) == password)
end
end
| true
|
41b829cd54c3e872096b4dd560351c1f6d9b1032
|
Ruby
|
Jylia/xyz
|
/xyz.rb
|
UTF-8
| 255
| 3.484375
| 3
|
[] |
no_license
|
def mult(x,y,z)
if (x < y) ?
if ((y < z) || (x < z)) ?
a = [y, z] : a = [y, x]
end
:
if ((x < z) || (y < z))?
a = [x, z] : a = [y, x]
end
end
return a[0]*a[0] + a[1]*a[1]
end
puts mult(-10, -9 ,-22)
| true
|
66f979f8c23ed9f71e0bf491762f564ea05f67e1
|
Ruby
|
alansparrow/learningruby
|
/benchmarkexample2.rb
|
UTF-8
| 236
| 2.8125
| 3
|
[] |
no_license
|
require 'benchmark'
iterations = 1000000
Benchmark.bmbm do |bmbm|
bmbm.report("for:") do
for i in 1..iterations do
x = i
end
end
bmbm.report("times:") do
iterations.times do |i|
x = i
end
end
end
| true
|
71a162184d00779ea2e21462ef19492c3a7aa618
|
Ruby
|
npatel007/Computer-Science-Notes
|
/Ruby/RubyLect9.progs/RubyLect9.14.progs/closure.rb
|
UTF-8
| 2,534
| 2.78125
| 3
|
[] |
no_license
|
#!/opt/local/bin/ruby2.0 -w
# CLOSURE
# Copyright Mark Keane, All Rights Reserved, 2011
arr1 = ["john", "jim","mary", "james"]
arr2 = ["A", "B","C", "D"]
def assign_marks(people, marks, time1 = 0, procs = [])
people.each do |person|
time2 = 0
marks.each do |mark|
fn = lambda {p [person, mark, time1, time2]}
procs << fn
fn.call; time1 += 1; time2 += 1
if (time1 == 10 || time2 == 4)
then puts "Encountered an error at 10/4 seconds, going back to start"
procs.first.call end
end
end
procs
end
fns = assign_marks(arr1, arr2)
p fns
fns.each {|clos| clos.call}
=begin
dhcp-892b3c12:RubyWeek8.progs mkeane$ !!
ruby closure.rb
["john", "A", 0, 0]
["john", "B", 1, 1]
["john", "C", 2, 2]
["john", "D", 3, 3]
Encountered an error at 10/4 seconds, going back to start
["john", "A", 4, 4]
["jim", "A", 4, 0]
["jim", "B", 5, 1]
["jim", "C", 6, 2]
["jim", "D", 7, 3]
Encountered an error at 10/4 seconds, going back to start
["john", "A", 8, 4]
["mary", "A", 8, 0]
["mary", "B", 9, 1]
Encountered an error at 10/4 seconds, going back to start
["john", "A", 10, 4]
["mary", "C", 10, 2]
["mary", "D", 11, 3]
Encountered an error at 10/4 seconds, going back to start
["john", "A", 12, 4]
["james", "A", 12, 0]
["james", "B", 13, 1]
["james", "C", 14, 2]
["james", "D", 15, 3]
Encountered an error at 10/4 seconds, going back to start
["john", "A", 16, 4]
[#<Proc:0x007fdc4384cf20@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384cd68@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384cc28@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384cae8@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c840@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c700@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c5c0@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c480@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c200@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384c0c0@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384be68@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384bd28@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384baa8@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384b968@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384b828@closure.rb:12 (lambda)>, #<Proc:0x007fdc4384b6e8@closure.rb:12 (lambda)>]
["john", "A", 16, 4]
["john", "B", 16, 4]
["john", "C", 16, 4]
["john", "D", 16, 4]
["jim", "A", 16, 4]
["jim", "B", 16, 4]
["jim", "C", 16, 4]
["jim", "D", 16, 4]
["mary", "A", 16, 4]
["mary", "B", 16, 4]
["mary", "C", 16, 4]
["mary", "D", 16, 4]
["james", "A", 16, 4]
["james", "B", 16, 4]
["james", "C", 16, 4]
["james", "D", 16, 4]
dhcp-892b3c12:RubyWeek8.progs mkeane$
=end
| true
|
f11a357e083cf04a3f6889b5e77568d3aa3325f5
|
Ruby
|
parrot-studio/rdgc-dm
|
/lib/rdgc/maker/divide_temp_block.rb
|
UTF-8
| 7,099
| 2.609375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# coding: UTF-8
module RDGC
module Maker
class DivideTempBlock < TempBlock
attr_accessor :divide_direction
attr_writer :depth, :min_size
def depth
@depth ||= 0
@depth
end
def min_size
@min_size = Util::Config.min_block_size if @min_size.to_i < Util::Config.min_block_size
@min_size
end
def min_divide_size
min_size * 2
end
def opposite_direction
case self.divide_direction
when :horizontal
:vertical
when :vertical
:horizontal
else
nil
end
end
def dividable_size?
case self.divide_direction
when :horizontal
height >= min_divide_size ? true : false
when :vertical
width >= min_divide_size ? true : false
else
false
end
end
def dividable(f = true)
@dividable = f
end
def dividable?
@dividable
end
def set_dividable
return unless dividable_size?
dividable
end
def divide_point(val)
range_rand(min_size, val - min_divide_size)
end
def divide
self.divide_direction ||= select_rand({:horizontal => 1, :vertical => 1})
return unless dividable_size?
case self.divide_direction
when :horizontal
divide_horizontal
when :vertical
divide_vertical
end
end
def divide_horizontal
return unless dividable_size?
# 分割幅決定
point = divide_point(height)
upper = DivideTempBlock.create(top, top + point - 1, left, right)
lower = DivideTempBlock.create(top + point, bottom, left, right)
set_next_value(upper, lower)
[upper, lower].shuffle
end
def divide_vertical
return unless dividable_size?
# 分割点決定
point = divide_point(width)
lefter = DivideTempBlock.create(top, bottom, left, left + point - 1)
righter = DivideTempBlock.create(top, bottom, left + point, right)
set_next_value(lefter, righter)
[lefter, righter].shuffle
end
def set_next_value(b1, b2)
[b1, b2].each do |b|
b.depth = self.depth + 1
b.divide_direction = opposite_direction
b.min_size = min_size
end
if bool_rand
b1.set_dividable
b2.set_dividable if bool_rand
else
b2.set_dividable
b1.set_dividable if bool_rand
end
end
# for road ----------------------------------------------------
def road_created(f = true)
@road_created = f
self
end
def road_created?
@road_created
end
def set_road_point(direction, point)
@road_point ||= {}
@road_point[direction] = point
end
def road_point
@road_point ||= {}
@road_point
end
def remain_cling_blocks
@remain_cling_blocks ||= []
@remain_cling_blocks
end
def add_remain_cling_blocks(b)
return if b.has_room?
remain_cling_blocks << b
end
def has_remain_cling_blocks?
remain_cling_blocks.empty? ? false : true
end
def dead_end?
return false if has_room?
return false unless has_cross_point?
road_point.keys.size == 1 ? true : false
end
def remain_direction
[:top, :bottom, :left, :right] - road_point.keys
end
def create_road_to(b)
return unless (has_room? || has_cross_point?)
return unless (b.has_room? || b.has_cross_point?)
# 相手とどこで接しているか調べる
# 接線に向かって道を伸ばす
# 左か上に位置する部屋に接続線を引く
case cling_direction_to(b)
when :top
my_x = create_road_for_direction(:top)
b_x = b.create_road_for_direction(:bottom)
b.create_road_for_adjoin_x(my_x, b_x)
when :bottom
my_x = create_road_for_direction(:bottom)
b_x = b.create_road_for_direction(:top)
create_road_for_adjoin_x(my_x, b_x)
when :left
my_y = create_road_for_direction(:left)
b_y = b.create_road_for_direction(:right)
b.create_road_for_adjoin_y(my_y, b_y)
when :right
my_y = create_road_for_direction(:right)
b_y = b.create_road_for_direction(:left)
create_road_for_adjoin_y(my_y, b_y)
end
end
def create_road_for_direction(d)
# 道を描くポイントを持っている(すでに道がある)ならそれを返す
val = road_point[d]
return val if val
# 新しい道を描く
case
when has_room?
val = create_road_from_room(d)
when has_cross_point?
val = create_road_from_point(d)
end
val
end
def create_road_from_room(d)
return unless has_room?
return if road_point[d]
case d
when :top
x = range_rand(room.left, room.right)
set_road_point(:top, x)
add_road(Map::Road.create(top, room.top-1, x, x))
x
when :bottom
x = range_rand(room.left, room.right)
set_road_point(:bottom, x)
add_road(Map::Road.create(room.bottom+1, bottom, x, x))
x
when :left
y = range_rand(room.top, room.bottom)
set_road_point(:left, y)
add_road(Map::Road.create(y, y, left, room.left-1))
y
when :right
y = range_rand(room.top, room.bottom)
set_road_point(:right, y)
add_road(Map::Road.create(y, y, room.right+1, right))
y
end
end
def create_road_from_point(d)
return unless has_cross_point?
return if road_point[d]
x, y = cross_point
case d
when :top
set_road_point(:top, x)
add_road(Map::Road.create(top, y, x, x))
x
when :bottom
set_road_point(:bottom, x)
add_road(Map::Road.create(y, bottom, x, x))
x
when :left
set_road_point(:left, y)
add_road(Map::Road.create(y, y, left, x))
y
when :right
set_road_point(:right, y)
add_road(Map::Road.create(y, y, x, right))
y
end
end
def create_road_for_adjoin_x(x1, x2)
p_s, p_e = [x1, x2].sort
add_road(Map::Road.create(bottom, bottom, p_s, p_e))
end
def create_road_for_adjoin_y(y1, y2)
p_s, p_e = [y1, y2].sort
add_road(Map::Road.create(p_s, p_e, right, right))
end
end
end
end
| true
|
803967a84198386138106048acacbd1a99502042
|
Ruby
|
SuhaylTFaris/XASJS
|
/XAS Tool HUD 0.1.rb
|
UTF-8
| 23,885
| 2.6875
| 3
|
[] |
no_license
|
#==============================================================================
# ■ +++ MOG - XAS TOOL HUD (v1.0) +++
#==============================================================================
# By Moghunter
# http://www.atelier-rgss.com
#==============================================================================
# Apresenta as huds usadas pelas ferramentas usadas no XAS , mais a hud da
# quantidade de ouro.
#===============================================================================
module XAS_TOOL_HUD
#Ativar a Hud de habilidades.
ENABLE_SKILL_HUD = true
#Ativar a Hud de Item.
ENABLE_ITEM_HUD = true
#Ativar a Hud de Armas.
ENABLE_WEAPON_HUD = true
#Ativar a Hud de Escudo.
ENABLE_SHIELD_HUD = true
#Ativar a Hud de Dinheiro(Gold).
ENABLE_GOLD_HUD = true
#Posição geral da hud de Item.
ITEM_HUD = [220,365]
#Posição geral da hud de Habilidades
SKILL_HUD = [264,365]
#Posição geral da hud de armas.
WEAPON_HUD = [308,365]
#Posição geral da hud de escudo.
SHIELD_HUD = [352,365]
#Posição geral da hud de dinheiro(Gold).
GOLD_HUD = [430,395]
#Posição do numero de dinheiro(Gold).
GOLD_NUMBER = [40,1]
#Posição do Layout.
LAYOUT = [0,0]
#Posição do Ícone.
ICON = [5, 12]
#Posição do numero.
NUMBER = [18, 35]
#Ajuste de espaço entre os numeros.
NUMBER_SPACE = 0
end
#==============================================================================
# ■ Tool Hud
#==============================================================================
class Tool_Hud
include XAS_TOOL_HUD
#--------------------------------------------------------------------------
# ● Initialize
#--------------------------------------------------------------------------
def initialize
@actor = $game_party.members[0]
return if @actor == nil
@icon_image = Cache.system("Iconset")
@number_image = Cache.system("XAS_Tool_Number")
@number_cw = @number_image.width / 10
@number_ch = @number_image.height / 3
@number_sc = @number_cw + NUMBER_SPACE
create_skill if ENABLE_SKILL_HUD
create_item if ENABLE_ITEM_HUD
create_weapon if ENABLE_WEAPON_HUD
create_shield if ENABLE_SHIELD_HUD
create_gold if ENABLE_GOLD_HUD
end
#--------------------------------------------------------------------------
# ● Refresh
#--------------------------------------------------------------------------
def refresh
dispose
initialize
end
#--------------------------------------------------------------------------
# ● Create Gold
#--------------------------------------------------------------------------
def create_gold
@gold = $game_party.gold
@gold_old = @gold
@gold_ref = @gold_old
@gold_refresh = false
# Layout -------------------------------------------------------------------
@gold_layout_sprite = Sprite.new
@gold_layout_sprite.bitmap = Cache.system("XAS_Tool_Gold")
@gold_layout_sprite.z = 151
@gold_layout_sprite.x = GOLD_HUD[0]
@gold_layout_sprite.y = GOLD_HUD[1]
# Gold ---------------------------------------------------------------------
@gold_number_sprite = Sprite.new
@gold_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)
@gold_number_sprite.z = 152
@gold_number_sprite.x = GOLD_HUD[0] + GOLD_NUMBER[0]
@gold_number_sprite.y = GOLD_HUD[1] + GOLD_NUMBER[1]
gold_number_update
end
#--------------------------------------------------------------------------
# ● Create Shield
#--------------------------------------------------------------------------
def create_shield
#LAYOUT ------------------------------------------------------------
@shield_layout_sprite = Sprite.new
@shield_layout_sprite.bitmap = Cache.system("XAS_Tool_Shield")
@shield_layout_sprite.z = 150
@shield_layout_sprite.x = SHIELD_HUD[0] + LAYOUT[0]
@shield_layout_sprite.y = SHIELD_HUD[1] + LAYOUT[1]
@shield = @actor.equips[1]
@old_shield = @shield
if @shield != nil
icon_index = @shield.icon_index
else
icon_index = 0
end
@shield_icon_sprite = Sprite.new
@shield_icon_sprite.bitmap = Bitmap.new(24,24)
bitmap_shield_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
@shield_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_shield_rect)
@shield_icon_sprite.z = 151
@shield_icon_sprite.x = SHIELD_HUD[0] + ICON[0]
@shield_icon_sprite.y = SHIELD_HUD[1] + ICON[1]
#NUMBER ------------------------------------------------------------
@shield_number_sprite = Sprite.new
@shield_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)
@shield_number_sprite.z = 152
refresh_shield_number
end
#--------------------------------------------------------------------------
# ● Refresh Shield Number
#--------------------------------------------------------------------------
def refresh_shield_number
@shield_number = 0
@s_item = 0
@shield_number_sprite.bitmap.clear
return if @shield == nil
if @shield.note =~ /<Action ID = (\d+)>/
action_id = $1.to_i
skill = $data_skills[action_id]
if skill != nil
if skill.note =~ /<Item Cost = (\d+)>/
item_id = $1.to_i
if item_id != nil
@s_item = $data_items[item_id]
@shield_number = $game_party.item_number(@s_item)
end
end
end
end
return if @s_item == 0
cost_split = @shield_number.to_s.split(//)
for r in 0..cost_split.size - 1
number_abs = cost_split[r].to_i
src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)
@shield_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect)
end
xf = ((cost_split.size * @number_sc) / 2)
@shield_number_sprite.x = SHIELD_HUD[0] + NUMBER[0] - xf
@shield_number_sprite.y = SHIELD_HUD[1] + NUMBER[1]
end
#--------------------------------------------------------------------------
# ● Create Weapon
#--------------------------------------------------------------------------
def create_weapon
#LAYOUT ------------------------------------------------------------
@weapon_layout_sprite = Sprite.new
@weapon_layout_sprite.bitmap = Cache.system("XAS_Tool_Weapon")
@weapon_layout_sprite.z = 150
@weapon_layout_sprite.x = WEAPON_HUD[0] + LAYOUT[0]
@weapon_layout_sprite.y = WEAPON_HUD[1] + LAYOUT[1]
#ICON
@weapon = @actor.equips[0]
@old_weapon = @weapon
if @weapon != nil
icon_index = @weapon.icon_index
else
icon_index = 0
end
@weapon_icon_sprite = Sprite.new
@weapon_icon_sprite.bitmap = Bitmap.new(24,24)
bitmap_weapon_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
@weapon_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_weapon_rect)
@weapon_icon_sprite.z = 151
@weapon_icon_sprite.x = WEAPON_HUD[0] + ICON[0]
@weapon_icon_sprite.y = WEAPON_HUD[1] + ICON[1]
#NUMBER ------------------------------------------------------------
@weapon_number_sprite = Sprite.new
@weapon_number_sprite.bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)
@weapon_number_sprite.z = 152
refresh_weapon_number
end
#--------------------------------------------------------------------------
# ● Refresh Weapon Number
#--------------------------------------------------------------------------
def refresh_weapon_number
@weapon_number = 0
@w_item = 0
@weapon_number_sprite.bitmap.clear
return if @weapon == nil
if @weapon.note =~ /<Action ID = (\d+)>/
action_id = $1.to_i
skill = $data_skills[action_id]
if skill != nil
if skill.note =~ /<Item Cost = (\d+)>/
item_id = $1.to_i
if item_id != nil
@w_item = $data_items[item_id]
@weapon_number = $game_party.item_number(@w_item)
end
end
end
end
return if @w_item == 0
cost_split = @weapon_number.to_s.split(//)
for r in 0..cost_split.size - 1
number_abs = cost_split[r].to_i
src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)
@weapon_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect)
end
xf = ((cost_split.size * @number_sc) / 2)
@weapon_number_sprite.x = WEAPON_HUD[0] + NUMBER[0] - xf
@weapon_number_sprite.y = WEAPON_HUD[1] + NUMBER[1]
end
#--------------------------------------------------------------------------
# ● Create Skill
#--------------------------------------------------------------------------
def create_skill
#LAYOUT ------------------------------------------------------------
@skill_layout_sprite = Sprite.new
@skill_layout_sprite.bitmap = Cache.system("XAS_Tool_Skill")
@skill_layout_sprite.z = 150
@skill_layout_sprite.x = SKILL_HUD[0] + LAYOUT[0]
@skill_layout_sprite.y = SKILL_HUD[1] + LAYOUT[1]
#ICON ------------------------------------------------------------
@old_skill = @actor.skill_id
@skill = $data_skills[@actor.skill_id]
if @skill != nil
icon_index = @skill.icon_index
@skill_mp_cost = @skill.mp_cost
else
icon_index = 0
@skill_mp_cost = 0
end
@skill_icon_sprite = Sprite.new
@skill_icon_sprite.bitmap = Bitmap.new(24,24)
bitmap_skill_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
@skill_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_skill_rect)
@skill_icon_sprite.z = 151
@skill_icon_sprite.x = SKILL_HUD[0] + ICON[0]
@skill_icon_sprite.y = SKILL_HUD[1] + ICON[1]
#NUMBER ------------------------------------------------------------
skill_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)
@skill_number_sprite = Sprite.new
@skill_number_sprite.bitmap = skill_number_bitmap
cost_split = @skill_mp_cost.to_s.split(//)
for r in 0..cost_split.size - 1
number_abs = cost_split[r].to_i
src_rect = Rect.new(@number_cw * number_abs, @number_ch, @number_cw, @number_ch)
skill_number_bitmap.blt(@number_sc * r, 0, @number_image, src_rect)
end
@skill_number_sprite.z = 152
xf = ((cost_split.size * @number_sc) / 2)
@skill_number_sprite.x = SKILL_HUD[0] + NUMBER[0] - xf
@skill_number_sprite.y = SKILL_HUD[1] + NUMBER[1]
end
#--------------------------------------------------------------------------
# ● Create Item
#--------------------------------------------------------------------------
def create_item
#LAYOUT ------------------------------------------------------------
@item_layout_sprite = Sprite.new
@item_layout_sprite.bitmap = Cache.system("XAS_Tool_Item")
@item_layout_sprite.z = 150
@item_layout_sprite.x = ITEM_HUD[0] + LAYOUT[0]
@item_layout_sprite.y = ITEM_HUD[1] + LAYOUT[1]
#ICON ------------------------------------------------------------
@old_item = @actor.item_id
@item = $data_items[@actor.item_id]
if @item != nil
icon_index = @item.icon_index
@item_number = $game_party.item_number(@item)
else
icon_index = 0
@item_number = 0
end
@item_icon_sprite = Sprite.new
@item_icon_sprite.bitmap = Bitmap.new(24,24)
bitmap_item_rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24)
@item_icon_sprite.bitmap.blt(0, 0, @icon_image, bitmap_item_rect)
@item_icon_sprite.z = 160
@item_icon_sprite.x = ITEM_HUD[0] + ICON[0]
@item_icon_sprite.y = ITEM_HUD[1] + ICON[1]
#NUMBER ------------------------------------------------------------
item_number_bitmap = Bitmap.new(@number_image.width, @number_image.height / 3)
@item_number_sprite = Sprite.new
@item_number_sprite.bitmap = item_number_bitmap
cost_split = @item_number.to_s.split(//)
for r in 0..cost_split.size - 1
number_abs = cost_split[r].to_i
src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)
@item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect)
end
@item_number_sprite.z = 152
xf = ((cost_split.size * @number_sc) / 2)
@item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf
@item_number_sprite.y = ITEM_HUD[1] + NUMBER[1]
end
#--------------------------------------------------------------------------
# ● Dispose
#--------------------------------------------------------------------------
def dispose
return if @actor == nil
dispose_skill if ENABLE_SKILL_HUD
dispose_item if ENABLE_ITEM_HUD
dispose_weapon if ENABLE_WEAPON_HUD
dispose_shield if ENABLE_SHIELD_HUD
dispose_gold if ENABLE_GOLD_HUD
@icon_image.dispose
@number_image.dispose
end
#--------------------------------------------------------------------------
# ● Dispose Skill
#--------------------------------------------------------------------------
def dispose_skill
@skill_layout_sprite.bitmap.dispose
@skill_layout_sprite.dispose
@skill_icon_sprite.bitmap.dispose
@skill_icon_sprite.dispose
@skill_number_sprite.bitmap.dispose
@skill_number_sprite.dispose
end
#--------------------------------------------------------------------------
# ● Dispose Gold
#--------------------------------------------------------------------------
def dispose_gold
@gold_layout_sprite.bitmap.dispose
@gold_layout_sprite.dispose
@gold_number_sprite.bitmap.dispose
@gold_number_sprite.dispose
end
#--------------------------------------------------------------------------
# ● Dispose Item
#--------------------------------------------------------------------------
def dispose_item
@item_layout_sprite.bitmap.dispose
@item_layout_sprite.dispose
@item_icon_sprite.bitmap.dispose
@item_icon_sprite.dispose
@item_number_sprite.bitmap.dispose
@item_number_sprite.dispose
end
#--------------------------------------------------------------------------
# ● Dispose Weapon
#--------------------------------------------------------------------------
def dispose_weapon
@weapon_layout_sprite.bitmap.dispose
@weapon_layout_sprite.dispose
@weapon_icon_sprite.bitmap.dispose
@weapon_icon_sprite.dispose
@weapon_number_sprite.bitmap.dispose
@weapon_number_sprite.dispose
end
#--------------------------------------------------------------------------
# ● Dispose shield
#--------------------------------------------------------------------------
def dispose_shield
@shield_layout_sprite.bitmap.dispose
@shield_layout_sprite.dispose
@shield_icon_sprite.bitmap.dispose
@shield_icon_sprite.dispose
@shield_number_sprite.bitmap.dispose
@shield_number_sprite.dispose
end
#--------------------------------------------------------------------------
# ● Update
#--------------------------------------------------------------------------
def update
return if @actor == nil
update_visible
refresh if can_refresh_hud?
refresh_item if ENABLE_ITEM_HUD and can_refresh_item_number?
refresh_weapon_number if ENABLE_WEAPON_HUD and can_refreh_weapon_number?
refresh_shield_number if ENABLE_SHIELD_HUD and can_refreh_shield_number?
update_gold if ENABLE_GOLD_HUD
end
#--------------------------------------------------------------------------
# ● Update Gold
#--------------------------------------------------------------------------
def update_gold
gold_number_down if @gold > $game_party.gold
gold_number_up if @gold < $game_party.gold
gold_number_update if @gold_refresh
end
#--------------------------------------------------------------------------
# ● Can Refresh Weapon Number
#--------------------------------------------------------------------------
def can_refreh_weapon_number?
return true if @weapon_number != $game_party.item_number(@w_item)
return false
end
#--------------------------------------------------------------------------
# ● Can Refresh Shield Number
#--------------------------------------------------------------------------
def can_refreh_shield_number?
return true if @shield_number != $game_party.item_number(@s_item)
return false
end
#--------------------------------------------------------------------------
# ● Update Visible
#--------------------------------------------------------------------------
def update_visible
vis = $game_system.enable_hud
if ENABLE_SKILL_HUD
@skill_layout_sprite.visible = vis
@skill_icon_sprite.visible = vis
@skill_number_sprite.visible = vis
end
if ENABLE_ITEM_HUD
@item_layout_sprite.visible = vis
@item_icon_sprite.visible = vis
@item_number_sprite.visible = vis
end
if ENABLE_WEAPON_HUD
@weapon_layout_sprite.visible = vis
@weapon_icon_sprite.visible = vis
@weapon_number_sprite.visible = vis
end
if ENABLE_SHIELD_HUD
@shield_layout_sprite.visible = vis
@shield_icon_sprite.visible = vis
@shield_number_sprite.visible = vis
end
if ENABLE_GOLD_HUD
@gold_layout_sprite.visible = vis
@gold_number_sprite.visible = vis
end
end
#--------------------------------------------------------------------------
# ● Can Refresh Hud
#--------------------------------------------------------------------------
def can_refresh_hud?
if @actor != nil
if ENABLE_SKILL_HUD
return true if @old_skill != @actor.skill_id
end
if ENABLE_ITEM_HUD
return true if @old_item != @actor.item_id
end
if ENABLE_WEAPON_HUD
return true if @old_weapon != @actor.equips[0]
end
if ENABLE_SHIELD_HUD
return true if @old_shield != @actor.equips[1]
end
end
return false
end
#--------------------------------------------------------------------------
# ● Can Refresh Item Number
#--------------------------------------------------------------------------
def can_refresh_item_number?
return true if @item_number != $game_party.item_number(@item)
return false
end
#--------------------------------------------------------------------------
# ● Create Item
#--------------------------------------------------------------------------
def refresh_item
@item_number = $game_party.item_number(@item)
#Item Number ------------------------------------------------------------
@item_number_sprite.bitmap.clear
cost_split = @item_number.to_s.split(//)
for r in 0..cost_split.size - 1
number_abs = cost_split[r].to_i
src_rect = Rect.new(@number_cw * number_abs, 0, @number_cw, @number_ch)
@item_number_sprite.bitmap.blt(@number_sc * r, 0, @number_image, src_rect)
end
xf = ((cost_split.size * @number_sc) / 2)
@item_number_sprite.x = ITEM_HUD[0] + NUMBER[0] - xf
end
#--------------------------------------------------------------------------
# ● gold_number_up
#--------------------------------------------------------------------------
def gold_number_up
@gold_refresh = true
@gold_ref = 20 * (@gold - @gold_old) / 100
@gold_ref = 1 if @gold_ref < 1
@gold += @gold_ref
if @gold >= $game_party.gold
@gold_old = $game_party.gold
@gold = $game_party.gold
@gold_ref = 0
end
end
#--------------------------------------------------------------------------
# ● gold_number_down
#--------------------------------------------------------------------------
def gold_number_down
@gold_refresh = true
@gold_ref = 10 * (@gold_old - @gold) / 100
@gold_ref = 1 if @gold_ref < 1
@gold -= @gold_ref
if @gold <= $game_party.gold
@gold_old = $game_party.gold
@gold = $game_party.gold
@gold_ref = 0
end
end
#--------------------------------------------------------------------------
# ● gold_number_update
#--------------------------------------------------------------------------
def gold_number_update
@gold_number_sprite.bitmap.clear
@gold_number_text = @gold.abs.to_s.split(//)
for r in 0..@gold_number_text.size - 1
@gold_number_abs = @gold_number_text[r].to_i
gold_src_rect = Rect.new(@number_cw * @gold_number_abs, @number_ch * 2, @number_cw, @number_ch)
@gold_number_sprite.bitmap.blt(@number_cw * r, 0, @number_image, gold_src_rect)
end
@gold_refresh = false if @gold == $game_party.gold
end
end
#==============================================================================
# ■ Spriteset_Map
#==============================================================================
class Spriteset_Map
#--------------------------------------------------------------------------
# ● initialize
#--------------------------------------------------------------------------
alias mog_tool_hud_initialize initialize
def initialize
@toolhud = Tool_Hud.new
mog_tool_hud_initialize
end
#--------------------------------------------------------------------------
# ● Dispose
#--------------------------------------------------------------------------
alias mog_tool_hud_dispose dispose
def dispose
@toolhud.dispose
mog_tool_hud_dispose
end
#--------------------------------------------------------------------------
# ● update
#--------------------------------------------------------------------------
alias mog_tool_hud_update update
def update
@toolhud.update
mog_tool_hud_update
end
#--------------------------------------------------------------------------
# ● Refresh Hud
#--------------------------------------------------------------------------
alias mog_tool_hud_refresh_hud refresh_hud
def refresh_hud
mog_tool_hud_refresh_hud
@toolhud.refresh
end
end
$mog_rgss3_xas_tool_hud = true
| true
|
f4b5535ff352b373fab7bd6135e6899b11a5f696
|
Ruby
|
yumidev/memory
|
/game.rb
|
UTF-8
| 572
| 3.453125
| 3
|
[] |
no_license
|
require_relative 'board'
class Game
def initialize
@board = Board.new
@previous_guess
end
def play
@board.populate
while !@board.won?
@board.render
guessed_pos = gets.chomp.to_i
@board.reveal(guessed_pos)
make_guess(guessed_pos)
end
end
def make_guess(pos)
if @previous_guess
unless @board.same_card?(@previous_guess, pos)
@board.hide(pos)
@board.hide(@previous_guess)
end
@previous_guess = nil
else
@previous_guess = pos
end
end
end
game = Game.new
game.play
| true
|
70b9d8386b8cfb199ab330fec129246d54e0d353
|
Ruby
|
jesusmaldonado/primes
|
/lib/primes/prime_parser.rb
|
UTF-8
| 359
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'prime_table'
require_relative 'prime_generator'
module Primes
class PrimeParser
def initialize(opts = {})
@prime_generator = Primes::PrimeGenerator.new(opts)
@prime_table = Primes::PrimeTable.new()
end
def print
@prime_table.primes = @prime_generator.primes
@prime_table.print_table
end
end
end
| true
|
b72bf55a7f445da02360fe482b6e204d707d78c2
|
Ruby
|
nonsensery/ar_validation_sample
|
/test/models/post_test.rb
|
UTF-8
| 1,938
| 2.875
| 3
|
[] |
no_license
|
require 'test_helper'
class PostTest < ActiveSupport::TestCase
test 'duplicate tag is detected when added to new post' do
tag = Tag.first
# Create a new post:
post = Post.new
# Add a tag:
post.post_tags.new tag: tag
# Post should be valid
assert post.valid?
# Add a duplicate tag:
post.post_tags.new tag: tag
# Check validity:
assert (post.valid? == false), 'Post is valid dispite duplicate tags'
end
test 'duplicate tag prevents saving' do
tag = Tag.first
# Create a new post:
post = Post.new
# Add a tag:
post.post_tags.new tag: tag
# Add a duplicate tag:
post.post_tags.new tag: tag
# Check savability:
assert (post.save == false), 'Saved post dispite duplicate tags'
end
test 'saving the post should save all post-tags, or the save should fail' do
tag = Tag.first
# Create a new post:
post = Post.new
# Add a tag:
post.post_tags.new tag: tag
# Add a duplicate tag:
post.post_tags.new tag: tag
# Save the post:
post.save!
# Check whether the first post-tag was saved:
assert (post.post_tags.first.id != nil), 'Saved post, but not first duplicate post-tag'
# Check whether the second post-tag was saved:
assert (post.post_tags.second.id != nil), 'Saved post, but not second duplicate post-tag'
end
test 'saving the post should not change the detection of duplicate tags' do
tag = Tag.first
# Create a new post:
post = Post.new
# Add a tag:
post.post_tags.new tag: tag
# Add a duplicate tag:
post.post_tags.new tag: tag
# Record the validity before saving
was_valid = post.valid?
# Save the post:
post.save!
# Check the validity after saving
is_valid = post.valid?
# Validity should not change!
assert (was_valid == is_valid), "Saving post changed its validity from #{was_valid} to #{is_valid}"
end
end
| true
|
c069811d01e1b47eaed9320fe07c84bf342d4c6c
|
Ruby
|
DavidMcKenzie218/Week_1_Homework
|
/Day_2/functions_practice_lab/ruby_functions_practice.rb
|
UTF-8
| 1,879
| 3.5625
| 4
|
[] |
no_license
|
def return_10()
return 10
end
def add(number1, number2)
result = number1 + number2
return result
end
def subtract(number1, number2)
result = number1 - number2
return result
end
def multiply(number1, number2)
result = number1 * number2
return result
end
def divide(number1, number2)
result = number1/number2
return result
end
def length_of_string(string)
result = string.length
return result
end
def join_string(string1, string2)
result = string1 + string2
return result
end
def add_string_as_number(string1, string2)
result = string1.to_i + string2.to_i
return result
end
def number_to_full_month_name(number)
case number
when 1
return "January"
when 2
return "Febuary"
when 3
return "March"
when 4
return "April"
when 5
return "May"
when 6
return "June"
when 7
return "July"
when 8
return "August"
when 9
return "September"
when 10
return "October"
when 11
return "November"
when 12
return "December"
end
end
def number_to_short_month_name(number)
case number
when 1
return "Jan"
when 2
return "Feb"
when 3
return "Mar"
when 4
return "Apr"
when 5
return "May"
when 6
return "Jun"
when 7
return "Jul"
when 8
return "Aug"
when 9
return "Sep"
when 10
return "Oct"
when 11
return "Nov"
when 12
return "Dec"
end
end
def volume_of_a_cube(side_length)
volume = side_length**3
return volume
end
def volume_of_a_sphere(radius)
pi = Math::PI
volume = (4.0/3) * pi * (radius**3)
return volume.round(2)
end
def fahrenheit_to_celcius(fahrenheit)
celcius = (fahrenheit.to_f - 32) * 5 / 9
return celcius.round(1)
end
def password_generator(name, number)
new_name = name.swapcase
new_number = number*2
new_password = "#{new_name}"+new_number.to_s
return new_password
end
| true
|
fc00a59c5bce5b15c32aaa1dbe92fc331bebb4ad
|
Ruby
|
nkirkus/testing
|
/Game/testloop.rb
|
UTF-8
| 99
| 3
| 3
|
[] |
no_license
|
i = -99
puts "Before : " + i.to_s
(1..10).each{|i| print 1; puts " haha"}
puts "After : " + i.to_s
| true
|
551367efc3da1488541449746a16d92ee11ba24b
|
Ruby
|
mezbahalam/script_quote_city
|
/run.rb
|
UTF-8
| 1,312
| 2.640625
| 3
|
[] |
no_license
|
### Health Leads Lead Type — > 114 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=6
# require 'nokogiri'
# file = File.open('ping.html')
# html = Nokogiri::HTML(file)
# data = html.css("a+ .hilite .left:nth-child(3)")
# #xpath("//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]")
# output = File.new('generator_command.txt', 'w+')
# data.each do |data|
# field = data.text
# File.open('generator_command.txt', 'a') { |f| f.write(field + " ") }
# end
## Medicare Leads Lead Type — > 48 input fields https://leads.usacoverage.com/pingPostSpec.php?TYPE=7
require 'nokogiri'
require 'open-uri'
html = Nokogiri::HTML(open('https://leads.usacoverage.com/pingPostSpec.php?TYPE=7'))
data = html.css("a+ .hilite .left:nth-child(3)")
#xpath("//a+//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'hilite', ' ' ))]//*[contains(concat( ' ', @class, ' ' ), concat( ' ', 'left', ' ' )) and (((count(preceding-sibling::*) + 1) = 3) and parent::*)]")
output = File.new('medicare_generator_command.txt', 'w+')
data.each do |data|
field = data.text
File.open('medicare_generator_command.txt', 'a') { |f| f.write(field + " ") }
end
| true
|
0be33067f6434e405c634ecfea3125a89fc6f56b
|
Ruby
|
salomekbg/prime-ruby-001-prework-web
|
/prime.rb
|
UTF-8
| 286
| 3.734375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(num)
numbers = (2...num).to_a
check = false
numbers.each do |item|
if num < 2
check = false
elsif num == 2
check = true
elsif num % item != 0
check = true
elsif num % item == 0
check = false
break
end
end
check
end
| true
|
8def2db9abea87b94b693b9dcb90bf26c0865b8e
|
Ruby
|
kennym/saas-class
|
/hw1/cartesian_product.rb
|
UTF-8
| 229
| 3.515625
| 4
|
[] |
no_license
|
class CartesianProduct
include Enumerable
attr_accessor :xs, :ys
def initialize(lhs, rhs)
@xs, @ys = lhs, rhs
end
def each
@xs.each do |x|
@ys.each do |y|
yield x, y
end
end
end
end
| true
|
5559f9c6a99d2a2963b74267697b08f00a8dcb12
|
Ruby
|
ShinyVerse/anagram-app
|
/spec/feature/app_spec.rb
|
UTF-8
| 1,037
| 2.796875
| 3
|
[] |
no_license
|
require 'app'
require 'anagram'
describe 'Feature' do
let(:app) { App.new(Anagram.new) }
before(:each) do
app.parse_user_input("era cat rat are pear ear")
end
context 'found anagrams' do
it 'prints expected positive output' do
allow(STDIN).to receive(:gets).and_return("tac\n", "exit\n")
expect { app.start_app }.to output("Enter a word and receive anagrams from the list of your word\n"\
"Write 'exit' to finish\n"\
"Please enter your word to check\n"\
"The anagrams found are: \n"\
"cat\n"\
"Please enter your word to check\n").to_stdout
end
end
context 'no anagram matches' do
it 'prints expected negative output' do
allow(STDIN).to receive(:gets).and_return("wrong\n", "exit\n")
expect { app.start_app }.to output("Enter a word and receive anagrams from the list of your word\n"\
"Write 'exit' to finish\n"\
"Please enter your word to check\n"\
"No matches\n"\
"Please enter your word to check\n").to_stdout
end
end
end
| true
|
63a4e6ebc06ad3c7637b29f90c161244cdb122cf
|
Ruby
|
mcwaller422/Intro_to_Ruby
|
/Arrays/Mutate.rb
|
UTF-8
| 180
| 3.75
| 4
|
[] |
no_license
|
a = [1,2,3,4,5,6]
def mutate(arr)
arr.pop
end
def not_mutate(arr)
arr.select{|i| i >3}
end
a = [1,2,3,4,5,6]
mutate(a)
puts a
a = [1,2,3,4,5,6]
not_mutate(a)
puts a
| true
|
ae72def25a8499bb36f655c78c42ecb8881853c3
|
Ruby
|
robopro/2019-06-14-Cookbook-day-1
|
/controller.rb
|
UTF-8
| 825
| 3.078125
| 3
|
[] |
no_license
|
require_relative 'view'
class Controller
def initialize(cookbook)
@cookbook = cookbook
@view = View.new
end
def list
# first get all recipes from cookbook
recipes = @cookbook.all
# send data to view
@view.display(recipes)
end
def create
# add a new recipe:
# ask user for name
name = @view.ask_for(:name)
# ask user for description
description = @view.ask_for(:description)
# create recipe from name and description
recipe = Recipe.new(name, description)
# pass recipe to cookbook
@cookbook.add_recipe(recipe)
end
def destroy
# display all the recipes
list
# ask the user for which recipe
index = @view.ask_for_index
# delete recipe from cookbook
@cookbook.remove_recipe(index)
# show the new recipe
list
end
end
| true
|
7dcdfc4cbfe1f04524604c3f6474c938cc004deb
|
Ruby
|
rimuhosting/fog
|
/lib/fog/model.rb
|
UTF-8
| 1,971
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
module Fog
class Model
def self.attribute(name, other_names = [])
class_eval <<-EOS, __FILE__, __LINE__
attr_accessor :#{name}
EOS
@attributes ||= []
@attributes |= [name]
for other_name in [*other_names]
aliases[other_name] = name
end
end
def self.identity(name, other_names = [])
@identity = name
self.attribute(name, other_names)
end
def self.aliases
@aliases ||= {}
end
def self.attributes
@attributes ||= []
end
def attributes
attributes = {}
for attribute in self.class.attributes
attributes[attribute] = send("#{attribute}")
end
attributes
end
def collection
@collection
end
def identity
send(self.class.instance_variable_get('@identity'))
end
def initialize(new_attributes = {})
merge_attributes(new_attributes)
end
def inspect
data = "#<#{self.class.name}"
for attribute in self.class.attributes
data << " #{attribute}=#{send(attribute).inspect}"
end
data << ">"
end
def merge_attributes(new_attributes = {})
for key, value in new_attributes
if aliased_key = self.class.aliases[key]
send("#{aliased_key}=", value)
else
send("#{key}=", value)
end
end
self
end
def new_record?
!identity
end
def reload
new_attributes = collection.get(identity).attributes
merge_attributes(new_attributes)
end
private
def collection=(new_collection)
@collection = new_collection
end
def connection=(new_connection)
@connection = new_connection
end
def connection
@connection
end
def remap_attributes(attributes, mapping)
for key, value in mapping
if attributes.key?(key)
attributes[value] = attributes.delete(key)
end
end
end
end
end
| true
|
22a205d2e20118269cad67337cfc3832f979697d
|
Ruby
|
cesartalves/ruby_metaprogramming_as_spec
|
/spec/callables/blocks_spec.rb
|
UTF-8
| 1,392
| 3.359375
| 3
|
[] |
no_license
|
require 'spec_helper'
describe "Ruby Blocks" do
def method_using_block_implicitly
yield
end
def method_using_block_explicity(&block)
block.call
end
it "they will run the code which is passed to the method" do
expect(method_using_block_implicitly { 5 }).to eq 5
end
it "they can be multilined, like a foreach" do
expect(
method_using_block_implicitly do
4
end).to eq 4
end
it "they can receive block explicitly" do
expect(method_using_block_explicity {5} ).to eq 5
end
it "they can raise erros if no blocks are passed" do
expect { method_using_block_implicitly }.to raise_error LocalJumpError
end
it "are a Proc/Closures" do
end
it "Self yield" do
class String
def yield_self
yield self.class
end
end
expect do
"This is a string".yield_self { |x| print x }
end.to output('String').to_stdout
end
it "Symbol.to_proc" do
expect([1, 2, 3].map(&:to_s)).to include("1", "2", "3")
# this is how ruby implements it, sort of
class Symbol
def to_proc
Proc.new { |x| x.send self }
end
end
expect([1, 2, 3].map(&:to_s)).to include("1", "2", "3")
end
end
| true
|
7e3c8b4fd45faabb5021633ee46caa44c3a50580
|
Ruby
|
adambeynon/opal
|
/lib/opal/nodes/if.rb
|
UTF-8
| 1,619
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
require 'opal/nodes/base'
module Opal
module Nodes
class IfNode < Base
handle :if
children :test, :true_body, :false_body
RUBY_ENGINE_CHECK = [:call, [:const, :RUBY_ENGINE],
:==, [:arglist, [:str, "opal"]]]
RUBY_PLATFORM_CHECK = [:call, [:const, :RUBY_PLATFORM],
:==, [:arglist, [:str, "opal"]]]
def compile
truthy, falsy = self.truthy, self.falsy
if skip_check_present?
falsy = nil
end
push "if (", js_truthy(test), ") {"
# skip if-body if no truthy sexp
indent { line stmt(truthy) } if truthy
if falsy
if falsy.type == :if
line "} else ", stmt(falsy)
else
indent do
line "} else {"
line stmt(falsy)
end
line "}"
end
else
push "}"
end
wrap "(function() {", "; return nil; })()" if needs_wrapper?
end
# pre-processing only effects falsy blocks. If engine is
# opal, then falsy block gets generated as normal. Unless
# engine is opal then that code gets generated as the
# falsy block
def skip_check_present?
test == RUBY_ENGINE_CHECK or test == RUBY_PLATFORM_CHECK
end
def truthy
needs_wrapper? ? compiler.returns(true_body || s(:nil)) : true_body
end
def falsy
needs_wrapper? ? compiler.returns(false_body || s(:nil)) : false_body
end
def needs_wrapper?
expr? or recv?
end
end
end
end
| true
|
7c504d0ae57cc77fa63d4b1d70373c7a87e9c3f3
|
Ruby
|
Tim-Feng/learn-to-program
|
/ch12-2.rb
|
UTF-8
| 177
| 3.25
| 3
|
[] |
no_license
|
puts "Please enter the year you born:"
born_y = gets.chomp
puts "Please enter the month you born:"
born_m = gets.chomp
puts "Please enter the date you born:"
born_y = gets.chomp
| true
|
bf00e71275725e61820bbf02d6ffb4dc65ba0a66
|
Ruby
|
hawthornehaus/astronom-web
|
/app/models/nutrient_loss.rb
|
UTF-8
| 2,298
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
class NutrientLoss
include Enumerable
delegate :[], :each,
:to => :loss_table
attr_reader :from, :to, :gender, :duration_in_seconds, :significance
def initialize(from: , to: , gender: , significance: 6)
@gender = gender # currently unused
@from = from.to_time
@to = to.to_time
@duration_in_seconds = ((@to - @from) / 1.seconds).round
@significance = significance
end
def loss_table
@loss_table ||= calculate_losses
end
alias_method :all, :loss_table
def calculate_losses
LOSSES_PER_DAY.each.with_object({}) do |(nutrient, loss_per_day), acc|
acc[nutrient] = (loss_per_day * (duration_in_seconds / SECONDS_IN_DAY)).round(significance)
end
end
SECONDS_IN_DAY = 86400.0
LOSSES_PER_DAY = {
'water' => 3000.0,
'energy' => 3200.0,
'protein' => 202.0,
'total_lipid' => 54.0,
# 'ash' =>
'carbohydrates' => 486.0,
'fiber_td' => 43.0,
'total_sugar' => 38.0,
'calcium' => 1000.0,
'iron' => 8.0,
'magnesium' => 420.0,
'phosphorus' => 700.0,
'potassium' => 3000.0,
'sodium' => 3000.0,
'zinc' => 11.0,
'copper' => 900.0,
'maganese' => 9.0,
'selenium' => 55.0,
'vitamin_c' => 90.0,
'thiamin' => 1.2,
'riboflavin' => 1.3,
'niacin' => 16.0,
'panto_acid' => 5.0,
'vitamin_b6' => 1.3,
'total_folate' => 400.0,
# 'folic_acid' =>
# 'food_folate' =>
# 'folate_dfe' =>
'total_choline' => 550.0,
'vitamin_b12' => 2.4,
'vitamin_a' => 900.0,
'retinol' => 900.0,
'alpha_carotene' => 4.71,
'vitamin_e' => 15.0,
'vitamin_d' => 5.0,
'vitamin_k' => 120.0,
'fat_saturated' => 9.0,
'fat_monounsaturated' => 25.0,
'fat_polyunsaturated' => 20.0,
'cholesterol' => 300.0,
# 'beta_carotene' =>
# 'beta_cryptoxanthin' =>
# 'lycopene' =>
# 'lutein_and_zeaxanthin' =>
}
end
| true
|
7e833c69b16cc89afe8f1795e77dac67d4365856
|
Ruby
|
zauzaj/prime_number_list
|
/lib/concern/prime_number_generator.rb
|
UTF-8
| 451
| 3.390625
| 3
|
[] |
no_license
|
require 'pry-rails'
module PrimeNumberGenerator
def generate starting_value, ending_value
primes_list = []
input_order_changing(starting_value, ending_value).to_a.each do |value|
primes_list << value if isPrime(value)
end
primes_list
end
def isPrime argument
(2..(argument/2)).to_a.all? {|div| argument%div > 0}
end
def input_order_changing num1, num2
num1 if num1 == num2
num1 > num2 ? (num2..num1) : (num1..num2)
end
end
| true
|
ce3568e273896e8872369bb4a204231114444382
|
Ruby
|
chiensiTB/OpenStudio-server-orig
|
/gems/gems/dencity-0.1.0/lib/dencity/client/structure.rb
|
UTF-8
| 4,497
| 2.71875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
module Dencity
# Structure methods
class Structure
include Request
attr_accessor :analysis_id
attr_accessor :user_defined_id
attr_accessor :structure
attr_accessor :measure_instances
# initialize
def initialize(analysis_id = nil, user_defined_id = nil, path = nil, connection)
@analysis_id = analysis_id
@user_defined_id = user_defined_id
@structure = Hashie::Mash.new
@measure_instances = Hashie::Mash.new
@connection = connection
# initialize with json file
unless path.nil?
load_from_file(path)
end
@upload_retries = nil
end
def push
begin
@upload_retries ||= 0
response = post('api/structure', format_structure)
@structure.id = response['id'] if response['id']
return response if response
rescue StandardError => se
# Decide if we should fail based on number of retries
if @upload_retries < 3
raise 'could not upload'
else
# or here: @upload_retries = nil
return se
end
end
rescue => e
@upload_retries += 1
sleep 2
retry
ensure
# always do this
# verify that this is only called if the retry is not triggered
@upload_retries = nil
end
# load structure from json file into a mash
def load_from_file(path)
return unless File.exist?(path)
json_data = File.read(path)
load_raw_json(json_data)
end
# load structure from raw json
def load_raw_json(json_data)
temp = Hashie::Mash.new(MultiJson.load(json_data))
@structure = temp.structure ? temp.structure : Hashie::Mash.new
@measure_instances = temp.measure_instances ? temp.measure_instances : Hashie::Mash.new
# these could be set in the file
@analysis_id = temp.structure.analysis_id if temp.structure.analysis_id
@user_defined_id = temp.structure.user_defined_id if temp.structure.user_defined_id
return true
end
# upload file
def upload_file(path, file_name = nil)
fail 'No Structure ID defined for structure. Can\'t upload file' if @structure.id.nil?
file = File.open(path, 'rb')
the_file = Base64.strict_encode64(file.read)
file.close
# file_data param
file_data = {}
file_data['file_name'] = file_name.nil? ? File.basename(path) : file_name
file_data['file'] = the_file
data = Hashie::Mash.new
data.structure_id = @structure.id
data.file_data = file_data
push_file('api/related_file', MultiJson.dump(data))
end
# delete an uploaded file
# if structure_id is nil, will use @structure.id
def delete_file(file_name)
fail 'No Structure ID defined for structure. Can\'t delete file' if @structure.id.nil?
data = Hashie::Mash.new
data.structure_id = @structure.id
data.file_name = file_name
push_file('api/remove_file', MultiJson.dump(data))
end
# push file w/ retry
def push_file(path, data)
begin
@upload_retries ||= 0
response = post(path, data)
return response if response
rescue StandardError => se
# Decide if we should fail based on number of retries
if @upload_retries < 3
if path.include? 'remove'
raise 'could not delete file'
else
raise 'could not upload file'
end
else
return se
end
end
rescue => e
@upload_retries += 1
sleep 2
retry
ensure
# verify that this is only called if the retry is not triggered
@upload_retries = nil
end
private
# formats structure parameters for posting
def format_structure
# generate name/value pairs for structure metadata
formatted_meta = []
@structure.each do |k, v|
formatted_meta << { name: k, value: v } unless %w(id user_defined_id analysis_id).include?(k)
end
new_struct = Hashie::Mash.new
new_struct.metadata = formatted_meta
# TODO: what if it's already in the structure hash?
# add user_defined_id to structure
new_struct.user_defined_id = @user_defined_id
new_struct.analysis_id = @analysis_id
data_hash = Hashie::Mash.new
data_hash.structure = new_struct
data_hash.measure_instances = @measure_instances ? @measure_instances : []
# convert to json
MultiJson.dump(data_hash)
end
end
end
| true
|
e5bddb0675f89233850d478eb4e152d095de422f
|
Ruby
|
ak061295/Radlibs
|
/mad_libs.rb
|
UTF-8
| 488
| 2.53125
| 3
|
[] |
no_license
|
require 'sinatra'
get '/' do
erb :form
end
get '/upload' do
erb :upload
end
get '/story' do
erb :story
end
post '/' do
@name = "#{params[:post][:first_name]} #{params[:post][:last_name]}"
@fname = "#{params[:post][:first_name]}"
@lname = "#{params[:post][:last_name]}"
if @name == "Brennan Kinney"
erb "Buckets"
elsif @name == "Anthony Kennedy"
erb "Nooo!!! Jimmy!!!"
else
erb "Hello, #{@name}. Welcome to my submarine. It's long and hard and full of seamen."
end
end
| true
|
81d57a9e7ea135b60ab5cb48984c6f4c380b1804
|
Ruby
|
h11z/ruby-oo-relationships-practice-blood-oath-exercise-chi01-seng-ft-080320
|
/app/models/Followers.rb
|
UTF-8
| 841
| 3.140625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Follower
attr_accessor
attr_reader :name, :age, :life_motto
@@all = []
def self.all
@@all
end
def initialize(name,age,life_motto)
@name = name
@age = age
@life_motto = life_motto
@@all << self
end
def cults
cults_im_in = BloodOath.all.filter do |cult_lister|
cult_lister.name.name == self.name
end
just_cults = cults_im_in.map do |cult_map|
cult_map.cult
end
just_cults
end
def join_cult(cult)
BloodOath.new(self,cult,"2020-02-25")
end
def self.of_a_certain_age(num)
follower_map = Follower.all.map do |finder|
if finder.age >= num
finder
end
end
follower_map.compact
end
end #end of follower class
| true
|
b856ed8910a721ee6cea960c5bf55657908a348d
|
Ruby
|
realgam3/ysoserial.rb
|
/lib/ysoserial/gadgets.rb
|
UTF-8
| 637
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'pathname'
module YSoSerial
module Gadgets
def self.load
pattern = File.join(Pathname(__FILE__).dirname, "gadgets", "*.rb")
Dir.glob(pattern).each do |path|
Kernel.load(path)
end
end
def self.table
gadgets = {}
self.load
YSoSerial::Gadgets.constants.select do |const_symbol|
const = YSoSerial::Gadgets.const_get(const_symbol) rescue nil
if not const.nil? and const.is_a? Class
class_name = const.name.split("::")[-1].to_sym
gadgets[class_name] = const
end
end
gadgets
end
end
end
| true
|
7ac9e5ac4bc5ac300000ad92e631310e8fce7800
|
Ruby
|
ministryofjustice/offender-management-allocation-manager
|
/lib/working_day_calculator.rb
|
UTF-8
| 369
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
require 'bank_holidays'
require 'business_time'
class WorkingDayCalculator
def initialize(holidays = BankHolidays.dates)
BusinessTime::Config.holidays = Set.new(holidays)
end
def working_days_between(date1, date2)
date1.business_days_until(date2)
end
def self.working_days_between(date1, date2)
new.working_days_between(date1, date2)
end
end
| true
|
5c092562fb4b50d6fdd4415bbb5ed6257b8d2069
|
Ruby
|
danielevans/gutenberg_text_search_compiler
|
/parse.rb
|
UTF-8
| 7,245
| 2.515625
| 3
|
[] |
no_license
|
require 'rubygems'
require 'stemmify'
require 'fileutils'
require 'shellwords'
require 'json'
require 'benchmark'
require 'pp'
require 'pry'
require 'optionparser'
require 'set'
require 'progressbar'
STOP_WORDS = [ # ripped off from https://github.com/brez/stopwords/blob/master/lib/stopwords.rb
'a','cannot','into','our','thus','about','co','is','ours','to','above',
'could','it','ourselves','together','across','down','its','out','too',
'after','during','itself','over','toward','afterwards','each','last','own',
'towards','again','eg','latter','per','under','against','either','latterly',
'perhaps','until','all','else','least','rather','up','almost','elsewhere',
'less','same','upon','alone','enough','ltd','seem','us','along','etc',
'many','seemed','very','already','even','may','seeming','via','also','ever',
'me','seems','was','although','every','meanwhile','several','we','always',
'everyone','might','she','well','among','everything','more','should','were',
'amongst','everywhere','moreover','since','what','an','except','most','so',
'whatever','and','few','mostly','some','when','another','first','much',
'somehow','whence','any','for','must','someone','whenever','anyhow',
'former','my','something','where','anyone','formerly','myself','sometime',
'whereafter','anything','from','namely','sometimes','whereas','anywhere',
'further','neither','somewhere','whereby','are','had','never','still',
'wherein','around','has','nevertheless','such','whereupon','as','have',
'next','than','wherever','at','he','no','that','whether','be','hence',
'nobody','the','whither','became','her','none','their','which','because',
'here','noone','them','while','become','hereafter','nor','themselves','who',
'becomes','hereby','not','then','whoever','becoming','herein','nothing',
'thence','whole','been','hereupon','now','there','whom','before','hers',
'nowhere','thereafter','whose','beforehand','herself','of','thereby','why',
'behind','him','off','therefore','will','being','himself','often','therein',
'with','below','his','on','thereupon','within','beside','how','once',
'these','without','besides','however','one','they','would','between','i',
'only','this','yet','beyond','ie','onto','those','you','both','if','or',
'though','your','but','in','other','through','yours','by','inc','others',
'throughout','yourself','can','indeed','otherwise','thru','yourselves'
].map(&:stem)
BLANK_LINE_REGEXP = /^$/
START_REGEXP = /^\*+\s*START[^$]*PROJECT GUTENBERG[^\*]*\*{3,}\s*$/im
INITIAL_CHOMP_REGEXP = /\*{3,}[^*]*\*{3,}\s*/
END_REGEXP = /^\*+\s*END[^$]*PROJECT GUTENBERG/im
PUNCTUATION_REGEXP = /\p{Punct}+$/
MINIMUM_WORDS = 2
class Parser
attr_accessor :minimum_words
attr_accessor :directories
attr_accessor :verbose
attr_accessor :progressbar
def initialize dirs="gutenberg_data", min_words=MINIMUM_WORDS
self.directories = Array(dirs)
self.minimum_words = min_words
end
def whitelisted_word? word
@whitelist ||= begin
words = if File.exist? "whitelist.txt"
File.read("whitelist.txt").split
else
generate_whitelist
end
Set.new words
end
@whitelist.include? word
end
def generate_whitelist
words = (File.readlines("/usr/share/dict/words").map { |word| word.chomp.downcase.stem } - STOP_WORDS).uniq
File.open("whitelist.txt", "wb") do |f|
f.write @whitelist.join("\n")
end
words
end
def unzip f
%x{unzip #{Shellwords.shellescape(f)}}
end
def cleanup
Dir.glob("*.txt").each do |f|
FileUtils.rm f
end
Dir.glob("*").each do |f|
FileUtils.rm_r f if File.directory? f
end
end
def paragraphs text
aggregator_hash = Hash.new { |h, k| h[k] = 0 }
text.split(BLANK_LINE_REGEXP).map do |paragraph|
words = paragraph.gsub(/[\s]+/, ' ').split.each_with_object(aggregator_hash.dup) do |word, memo|
sanitary_word = word.gsub(PUNCTUATION_REGEXP, '').downcase.stem
memo[sanitary_word] += 1 if whitelisted_word?(sanitary_word)
end
if words.length >= self.minimum_words
{ text: paragraph.gsub("\n", " ").gsub(/\s+/, ' ').gsub(/^\s+/, '').gsub(/\s$/, ''), words: words }
end
end.compact
end
def write_result dir, results_dir, result
destination_dir = File.join(results_dir, dir)
FileUtils.mkdir_p destination_dir
id = File.split(dir).last
json = JSON.pretty_generate({ id: id, paragraphs: result })
File.open(File.join(destination_dir, "#{id}.json"), "wb") do |f|
f.write(json)
end
end
def get_textfile dir
file = Dir.glob("*.zip").sort.first
return nil if !file
unzip file
Dir.glob("**/*.txt").first
end
def process_directory dir
puts "Processing: #{dir}" if verbose
rt = Benchmark.realtime do
results_dir = File.expand_path('./results')
Dir.chdir dir do
textfile = get_textfile dir
if !textfile
$stderr.puts "Error getting textfile for #{dir}"
return false
end
file_data = nil
File.open(textfile, 'rb') do |f|
file_data = f.read
end
start_index = file_data.index START_REGEXP
end_index = file_data.index END_REGEXP
if start_index.nil? || end_index.nil?
$stderr.puts "#{File.join(dir, textfile)} did not match expected regular expressions (s:#{start_index} e:#{end_index})"
return false
end
file_data = file_data[start_index..end_index]
.encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
.gsub("\r", '')
.gsub(INITIAL_CHOMP_REGEXP, '')
.gsub(/^\s*$/,'')
if file_data.length > 0
write_result dir, results_dir, paragraphs(file_data)
else
$stderr.puts "#{File.join(dir, textfile)} contains no data"
end
ensure
cleanup
end
end
puts "Complete: #{dir} #{rt}s" if verbose
end
def parse!
count = 1
rt = Benchmark.realtime do
whitelisted_word? "foo" # generates the whitelist in the right place
all_files = directories.map do |dir|
Dir.glob(File.join(dir, "**/*.zip"))
end.flatten.uniq
files_by_dir = all_files.group_by { |f| f.gsub(/(.*)\/[^\/]*/, "\\1") }
count = files_by_dir.length
puts "#{count} directories detected"
progressbar.total = count if progressbar
files_by_dir.each_key.sort.each do |dir|
process_directory dir
progressbar.increment if progressbar
end
end
puts "Complete in #{rt}s"
end
end
parser = Parser.new
OptionParser.new do |opts|
opts.banner = "Usage: parse.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
opts.on("-d=dir", "--directory=dir,dir,dir", Array, "directory to parse") do |v|
parser.directories = v
end
opts.on("-p", "show progress") do
parser.progressbar = ProgressBar.create title: "Directories", format: "%t (%c/%C): %w"
end
end.parse!
parser.parse!
| true
|
be653cd5e01d9bf7faeae459adedf0f05a71e694
|
Ruby
|
Steimel/Thomas
|
/lib/thomas/canvas.rb
|
UTF-8
| 910
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
module Thomas
class Canvas
attr_reader :width, :height, :things
def initialize(width, height)
@width = width
@height = height
@things = []
end
def drawable_things
@things.select{|thing| thing.drawable}
end
def place_thing(thing, r, c)
thing.set_position(r,c)
thing.canvas = self
@things.push(thing)
end
def draw(border=false)
self.to_s(border)
end
def to_s(border=false)
output = Util.build_empty_string_box(@width, @height)
drawable_things.each do |thing|
output = thing.draw(output, @width, @height)
end
if border
top_bottom_bar = ('-' * (@width + 2))
return top_bottom_bar + "\n\r" + output.map{|row| '|' + row.join('') + '|'}.join("\n\r") + "\n\r" + top_bottom_bar
else
return output.map{|row| row.join('')}.join("\n\r")
end
end
end
end
| true
|
7191bae7995ed1457716218e7d945de263d3e8c2
|
Ruby
|
soutaro/querly
|
/lib/querly/pattern/kind.rb
|
UTF-8
| 1,603
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
module Querly
module Pattern
module Kind
class Base
attr_reader :expr
def initialize(expr:)
@expr = expr
end
end
module Negatable
attr_reader :negated
def initialize(expr:, negated:)
@negated = negated
super(expr: expr)
end
end
class Any < Base
def test_kind(pair)
true
end
end
class Conditional < Base
include Negatable
def test_kind(pair)
!negated == !!conditional?(pair)
end
def conditional?(pair)
node = pair.node
parent = pair.parent&.node
case parent&.type
when :if
node.equal? parent.children.first
when :while
node.equal? parent.children.first
when :and
node.equal? parent.children.first
when :or
node.equal? parent.children.first
when :csend
node.equal? parent.children.first
else
false
end
end
end
class Discarded < Base
include Negatable
def test_kind(pair)
!negated == !!discarded?(pair)
end
def discarded?(pair)
node = pair.node
parent = pair.parent&.node
case parent&.type
when :begin
if node.equal? parent.children.last
discarded? pair.parent
else
true
end
else
false
end
end
end
end
end
end
| true
|
75136031563b97cec3cbbc1ec40018eee9b8ca04
|
Ruby
|
splashinn/Warmups
|
/main.rb
|
UTF-8
| 1,268
| 3.84375
| 4
|
[] |
no_license
|
# Load in all the shakespeare and remove newline characters
def load_shakespeare
File.read(File.dirname(__FILE__) + '/Shakespeare.txt').delete("\n")
end
shakespeare = load_shakespeare()
# ********************
# REGEX DRILLS
# Use regular expressions to answer the following questions:
# How many words does Shakespeare use?
shakespeare.split(/\w+/).count
# How many different words does Shakespeare use?
shakespeare.scan(/\w+/).uniq.count
# How many times does Shakespeare use the word 'the'?
shakespeare.scan.(/the/i).count
# How many times does Shakespeare write "guildenstern" or "Guildenstern"
shakespeare.scan.(/guildenstern/i).count
# Find the entire "To be, or not to be- that is the question:" with as few regex characters as possible
shakespeare.scan(/To be, or[-: \w+]/)
# ********************
# Write a method that accepts a word and returns all the words in Shakespeare.txt that follow that word.
# In other words, words_after('to') will return an array of words which include 'be'... since Shakespeare writes "to be"
def words_after(word)
shakespeare = File.read(File.dirname(__FILE__) + '/Shakespeare.txt')
shakespeare.scan(Regexp.new(word + ' (\w+)')).uniq.flatten
end
#This should be true:
# words_after('to').include?('be')
#=> true
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.