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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5ef2fe5d0cd761075ac7a1f8cfffab70c488e46f
|
Ruby
|
vidriloco/MosaicsBackend
|
/app/models/exports/meta_questions.rb
|
UTF-8
| 948
| 2.578125
| 3
|
[] |
no_license
|
module Exports::MetaQuestions
# Recovers the data of this meta question for postprocessing to plist
def preprocess_to_plist
plist_hash = %w(title instruction type_of).each.inject({}) do |last, attr|
last[attr.to_sym] = self.send(attr)
last
end
%w(meta_answer_items meta_answer_options).each do |assoc|
plist_hash=plist_hash.merge(preprocess_end_chain_with(assoc))
end
{order_identifier => plist_hash.merge(:meta_question_id => identifier.to_s)}
end
protected
# continues execution of tasks for the method: preprocess_to_plist
def preprocess_end_chain_with(items_or_options)
preprocessed_chain = self.send(items_or_options).each.inject({}) do |last, item_or_option|
last[item_or_option.human_value] = { :id => item_or_option.identifier.to_s, :order_number => item_or_option.order_identifier }
last
end
{items_or_options.to_sym => preprocessed_chain}
end
end
| true
|
6a9373b53386c304e01f954698257a2a5b8a3b21
|
Ruby
|
forest-zjx/simplehotel
|
/HotalTest1/app/models/hotal.rb
|
UTF-8
| 912
| 2.65625
| 3
|
[] |
no_license
|
class Hotal < ActiveRecord::Base
attr_accessible :address, :is_admin, :lat, :lon, :name, :password, :status, :tel, :username
validates_presence_of :address, :message => '请输入地址。'
validates_presence_of :is_admin, :message => '请输入0或1。'
validates_presence_of :lon, :message => '请输入0~180数字。'
validates_presence_of :lat, :message => '请输入0~180数字。'
validates_presence_of :name, :message => '请输入店名。'
validates_presence_of :password, :message => '请输入密码。'
validates_presence_of :status, :message => '请输入0或1。'
validates_presence_of :tel, :message => '请输入电话号码。'
validates_presence_of :username, :message => '请输入用户名。'
def self.login(name, password)
password = md5(password || "")
end
def self.md5(pass)
Digest::MD5.hexdigest("--my-salt--#{pass}")
end
end
| true
|
6c5affac46ba61b003c17318ebff28a036c00f58
|
Ruby
|
Omosofe/Play
|
/implement-map-in-lisp-in-ruby/implement-map-in-lisp-in-ruby.rb
|
UTF-8
| 2,643
| 3.71875
| 4
|
[
"MIT"
] |
permissive
|
# === booleans ===
t = ->(first, second) { first } # true
f = ->(first, second) { second } # false
n = ->() { n } # nil
_if = ->(bool, consequent, alternative) { bool[consequent, alternative][] }
do_if = ->(bool, consequent) { _if[bool, consequent, n] }
do_unless = ->(bool, consequent) { _if[bool, n, consequent] }
are_equal = ->(lhs, rhs) { lhs == rhs ? t : f } # <-- cheating here
define_singleton_method :assert do |bool|
do_unless[bool, -> { raise }]
end
define_singleton_method :refute do |bool|
do_if[bool, -> { raise }]
end
define_singleton_method :assert_equal do |lhs, rhs|
assert are_equal[lhs, rhs]
end
# tests
assert t
refute f
assert _if[t, ->{t}, ->{f}]
refute _if[f, ->{t}, ->{f}]
assert are_equal[f, f]
assert are_equal[t, t]
assert are_equal[1, 1]
refute are_equal[0, 1]
refute are_equal[t, f]
refute are_equal[n, f]
refute are_equal[f, n]
assert_equal t, do_if[t, ->{t}]
assert_equal n, do_if[f, ->{t}]
assert_equal n, do_unless[t, ->{t}]
assert_equal t, do_unless[f, ->{t}]
# === numeric ===
is_zero = ->(num) { are_equal[num, 0] }
subtract = ->(minuend, subtrahend) { minuend - subtrahend }
# tests
assert is_zero[0]
assert is_zero[0.0]
refute is_zero[1]
assert_equal 3, subtract[4, 1]
# === lists ===
cons = ->(first, second=n) {
# returns a lambda that will return first element if given t, rest if given f
->(bool) {
_if[ bool,
-> { first },
-> { second }]}}
car = ->(list) { list[t] }
cdr = ->(list) { list[f] }
is_empty = ->(list) { are_equal[list, n] }
map = ->(list, function ) {
_if[ is_empty[list],
-> { n },
-> { cons[ function[car[list]],
map[cdr[list],
function]]}]}
# tests
assert_equal 1, car[cons[1, 2]]
assert_equal 2, cdr[cons[1, 2]]
assert_equal 1, car[cons[1]]
assert_equal n, cdr[cons[1]]
assert is_empty[n]
refute is_empty[cons[1, n]]
double = ->(num) { num + num }
identity = ->(element) { element }
one_to_five = cons[1, cons[2, cons[3, cons[4, cons[5]]]]]
assert_equal n, map[n, identity]
assert_equal 2, car[map[cons[1], double]]
assert_equal 2, car[ map[one_to_five, double] ]
assert_equal 4, car[cdr[ map[one_to_five, double] ]]
assert_equal 6, car[cdr[cdr[ map[one_to_five, double] ]]]
assert_equal 8, car[cdr[cdr[cdr[ map[one_to_five, double] ]]]]
assert_equal 10, car[cdr[cdr[cdr[cdr[ map[one_to_five, double] ]]]]]
assert_equal n, cdr[cdr[cdr[cdr[cdr[ map[one_to_five, double] ]]]]]
| true
|
b5c68e33d05b1b6fc7104c8019e7557bedf91f80
|
Ruby
|
kewpiedoll/RubyWinter2014
|
/week4/exercises/code_timer_spec.rb
|
UTF-8
| 637
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require './code_time'
describe CodeTimer do
it "should run our code" do
flag = false
CodeTimer.time_code do
flag = true
end
flag.should be_true
end
it "should time our code" do
Time.stub(:now).and_return(0,3)
time = CodeTimer.time_code do
end
time.should be_within(0.1).of(3.0)
end
it "should run our code multiple times" do
count = 0
CodeTimer.time_code 100 do
count += 1
end
count.should eq 100
end
it "should give us the average time to run" do
Time.stub(:now).and_return(0,300)
time = CodeTimer.time_code 100 do
end
time.should be_within(0.1).of(3.0)
end
end
| true
|
12cb53822dcb3e3f36b30999ec80c344819f85e3
|
Ruby
|
gooch/RDialogy
|
/lib/rdialogy/checklist.rb
|
UTF-8
| 1,412
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
require File.dirname(__FILE__) + '/base'
require File.dirname(__FILE__) + '/menu_item'
module RDialogy
# From dialog(1)
# A checklist box is similar to a menu box; there are multiple entries presented in the form of a menu.
# Instead of choosing one entry among the entries, each entry can be turned on or off by the user. The initial
# on/off state of each entry is specified by status.
class Checklist < Base
# Valid options are:
# * :text - Title of the widget
# * :width
# * :height
# * :list_height - Number of items to display in the list
# * :items - Array of MenuItem
#
# Returns <b>Array</b>
def self.run(options={})
super options, true do |input|
items = input.split(' ')
items.map{|e| e.scan(/^"(.*)"$/).flatten.first }
end
end
private
# Formats the hash into an ordered list, valid options are:
# * :text - Title of the widget
# * :width
# * :height
# * :list_height - Number of items to display in the list
# * :items - Array of MenuItem
def self.args(options={})
options[:items] ||= []
options[:list_height] ||= options[:items].count
options[:items].map! do |item|
[item.tag, item.item, item.status ? 'on' : 'off']
end
super + [options[:list_height]] + options[:items].flatten
end
# Maps to the appropriate dialog argument
def self.command
'checklist'
end
end
end
| true
|
b518b102302762f274fd65aaf3af457923b7c44e
|
Ruby
|
dreadheaddreamz/hash-iteration-onl01-seng-pt-012120
|
/lib/birthday.rb
|
UTF-8
| 830
| 3.765625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# birthday_kids = {
# "Timmy" => 9,
# "Sarah" => 6,
# "Amanda" => 27
# }
def happy_birthday(birthday_kids)
birthday_kids.each do |kids_name, age|
puts "Happy Birthday #{kids_name}! You are now #{age} years old!"
end
end
#def age_appropriate_birthday
# birthday_kids.each do |kids_name, age|
# if age <= 12
# puts "Happy Birthday #{kids_name}! You are now #{age} years old!"
# elsif age >= 12
# puts "Happy Birthday #{kids_name}! but you're too old for this message."
#end
#end
#def happy_birthday_under_12(birthday_kid)
# birthday_kid.each do |kids_name, age|
#if birthday_kid age <= 12
# puts "Happy Birthday #{kids_name}! You are now #{age} years old!"
#elsif birthday_kid age >= 12
# puts "Happy Birthday #{kids_name}! but you're too old for this message."
#end
| true
|
0a9d4230ae025b0ede7508c40ae09847ff251bcc
|
Ruby
|
Shopify/vcr
|
/lib/vcr/cassette/serializers.rb
|
UTF-8
| 2,006
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module VCR
class Cassette
# Keeps track of the cassette serializers in a hash-like object.
class Serializers
autoload :YAML, 'vcr/cassette/serializers/yaml'
autoload :Syck, 'vcr/cassette/serializers/syck'
autoload :Psych, 'vcr/cassette/serializers/psych'
autoload :JSON, 'vcr/cassette/serializers/json'
autoload :Compressed, 'vcr/cassette/serializers/compressed'
# @private
def initialize
@serializers = {}
end
# Gets the named serializer.
#
# @param name [Symbol] the name of the serializer
# @return the named serializer
# @raise [ArgumentError] if there is not a serializer for the given name
def [](name)
@serializers.fetch(name) do |_|
@serializers[name] = case name
when :yaml then YAML
when :syck then Syck
when :psych then Psych
when :json then JSON
when :compressed then Compressed
else raise ArgumentError.new("The requested VCR cassette serializer (#{name.inspect}) is not registered.")
end
end
end
# Registers a serializer.
#
# @param name [Symbol] the name of the serializer
# @param value [#file_extension, #serialize, #deserialize] the serializer object. It must implement
# `file_extension()`, `serialize(Hash)` and `deserialize(String)`.
def []=(name, value)
if @serializers.has_key?(name)
warn "WARNING: There is already a VCR cassette serializer registered for #{name.inspect}. Overriding it."
end
@serializers[name] = value
end
end
# @private
module EncodingErrorHandling
def handle_encoding_errors
yield
rescue *self::ENCODING_ERRORS => e
e.message << "\nNote: Using VCR's `:preserve_exact_body_bytes` option may help prevent this error in the future."
raise
end
end
end
end
| true
|
4de780bbbdfdc9df166375f3c2d3eabc66c4a0b2
|
Ruby
|
MilesHeise/WikiSmarts
|
/db/seeds.rb
|
UTF-8
| 915
| 2.78125
| 3
|
[] |
no_license
|
require 'faker'
# Create Users
5.times do
User.create!(
email: Faker::Internet.email,
password: Faker::Internet.password,
confirmed_at: DateTime.now
)
end
users = User.all
# Create Wikis
15.times do
Wiki.create!(
title: Faker::Book.title,
body: Faker::Lovecraft.paragraphs(rand(2..8)).join("\n\n"),
private: false,
user: users.sample
)
end
wikis = Wiki.all
# Create an admin user
admin = User.create!(
email: 'admin@example.com',
password: 'helloworld',
confirmed_at: DateTime.now,
role: 'admin'
)
# Create a premium user
premium = User.create!(
email: 'premium@example.com',
password: 'helloworld',
confirmed_at: DateTime.now,
role: 'premium'
)
# Create a standard member
member = User.create!(
email: 'member@example.com',
password: 'helloworld',
confirmed_at: DateTime.now
)
puts 'Seed finished'
puts "#{User.count} users created"
puts "#{Wiki.count} wikis created"
| true
|
15f43b822af83528cf79077e509c4f379df3f2d2
|
Ruby
|
prg-titech/ikra-ruby
|
/lib/types/inference/command_inference.rb
|
UTF-8
| 4,296
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module Ikra
module TypeInference
class CommandInference < Symbolic::Visitor
def self.process_command(command)
return command.accept(CommandInference.new)
end
# Processes a parallel section, i.e., a [BlockDefNode]. Performs the following steps:
# 1. Gather parameter types and names in a hash map.
# 2. Set lexical variables on [BlockDefNode].
# 3. Perform type inference, i.e., annotate [BlockDefNode] AST with types.
# 4. Return result type of the block.
def process_block(
block_def_node:,
lexical_variables: {},
block_parameters:)
# Build hash of parameter name -> type mappings
block_parameter_types = {}
for variable in block_parameters
block_parameter_types[variable.name] = variable.type
end
parameter_types_string = "[" + block_parameter_types.map do |id, type| "#{id}: #{type}" end.join(", ") + "]"
Log.info("Type inference for block with input types #{parameter_types_string}")
# Add information to block_def_node
block_def_node.parameters_names_and_types = block_parameter_types
# Lexical variables
lexical_variables.each do |name, value|
block_def_node.lexical_variables_names_and_types[name] = value.ikra_type.to_union_type
end
# Type inference
type_inference_visitor = TypeInference::Visitor.new
return_type = type_inference_visitor.process_block(block_def_node)
return return_type
end
# Processes all input commands. This is similar to `translate_entire_input`, but it
# performs only type inference and does not generate any source code.
def process_entire_input(command)
input_parameters = command.input.each_with_index.map do |input, index|
input.get_parameters(
parent_command: command,
# Assuming that every input consumes exactly one parameter
start_eat_params_offset: index)
end
return input_parameters.reduce(:+)
end
# Process block and dependent computations. This method is used for all array
# commands that do not have a separate Visitor method.
def visit_array_command(command)
return process_block(
block_def_node: command.block_def_node,
lexical_variables: command.lexical_externals,
block_parameters: process_entire_input(command))
end
def visit_array_in_host_section_command(command)
return command.base_type
end
def visit_array_identity_command(command)
return command.base_type
end
def visit_array_index_command(command)
num_dims = command.dimensions.size
if num_dims > 1
# Build Ikra struct type
zipped_type_singleton = Types::ZipStructType.new(
*([Types::UnionType.create_int] * command.dimensions.size))
return zipped_type_singleton.to_union_type
else
return Types::UnionType.create_int
end
end
def visit_array_zip_command(command)
input_types = command.input.each_with_index.map do |input, index|
input.get_parameters(
parent_command: command,
# Assuming that every input consumes exactly one parameter
start_eat_params_offset: index).map do |variable|
variable.type
end
end.reduce(:+)
# Build Ikra struct type
zipped_type_singleton = Types::ZipStructType.new(*input_types)
return zipped_type_singleton.to_union_type
end
end
end
end
| true
|
fe54e1efbfc3b8a52ecccb47ad645fdc60641f0c
|
Ruby
|
jessesbyers/programming-univbasics-4-intro-to-hashes-lab-online-web-prework
|
/intro_to_ruby_hashes_lab.rb
|
UTF-8
| 539
| 3.078125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def new_hash
new_hash = {}
end
def my_hash
my_hash = {name: "Jesse", age:40}
end
def pioneer
pioneer = {name: "Grace Hopper"}
end
def id_generator
id_generator = {id: 7}
end
def my_hash_creator(key, value)
hash = {key => value}
end
def read_from_hash(hash, key)
read_from_hash = {key => a_value}
read_from_hash[:key]
a_value
end
def update_counting_hash(hash, key)
update_hash = {key => a_value}
if update_hash["key"]
update_hash["key"] += 1
else update_hash["key"] = 1
end
update_hash[key]
end
| true
|
83ae0cdbbea641c539f4e3d6458a74fb9db368ce
|
Ruby
|
Hawatel/hawatel_tlb
|
/lib/hawatel_tlb/mode/ratio.rb
|
UTF-8
| 2,406
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
module HawatelTlb::Mode
##
# = Ratio algorithm
#
# Thease are static load balancing algorithm based on ratio weights.
# Algorithm explanation:
# 1. divide the amount of traffic (requests) sent to each server by weight (configured in the Client)
# 2. Sort by ratio (result from 1. point) from smallest to largest
# 3. Get node with smallest ratio
# If you want to see how it works you can set client.mode.debug to 1 and run ratio_spec.rb.
# @!attribute [rw] debug
class Ratio
attr_accessor :debug
def initialize(group)
@traffic = 0
@debug = 0
group.each do |node|
node.ratio = Hash.new
node.ratio[:traffic] = 0
node.ratio[:value] = 0
node.weight = 1 if node.weight.to_i < 1
end
@group = group
end
# Refresh group table after delete or add host
#
# @param group [Array<Hash>]
def refresh(group)
@group = group
end
# Description
# @param name [Type] description
# @option name [Type] :opt description
# @example
# mode = Ratio.new(nodes)
# p mode.node
# @return [Hash] :host and :port
def node
node = get_right_node
return {:host => node.host, :port => node.port} if node
false
end
private
def get_right_node
nodes = sort_nodes_by_ratio_asc
node = get_first_online_node(nodes)
debug_log(nodes)
if node
set_ratio(node)
return node
else
false
end
end
def get_first_online_node(nodes)
nodes.each do |node|
return node if node.status[:state] == 'online' && node.state == 'enable'
end
false
end
def sort_nodes_by_ratio_asc
@group.sort_by {|node| node.ratio[:value]}
end
def set_ratio(node)
@traffic += 1
node.ratio[:traffic] += 1
node.ratio[:value] = calc_ratio(node.ratio[:traffic], node.weight)
end
def calc_ratio(traffic, weight)
if weight.zero?
0
else
traffic.to_f / weight.to_f
end
end
def debug_log(nodes)
if @debug > 0
puts ">> request: #{@traffic} | selected #{nodes[0].host}"
nodes.each do |node|
puts "\t" "#{node.host} - ratio: #{node.ratio}, weight: #{node.weight}\n"
end
puts "------------------------------------------------------------"
end
end
end
end
| true
|
68b51b057a94c2ffe99069a71e75ee28372262c9
|
Ruby
|
PickleBanquet/collatz
|
/collatz.rb
|
UTF-8
| 419
| 3.6875
| 4
|
[] |
no_license
|
def collatz_value(n)
n = n.to_i
if n <= 0
puts "Undefined value"
else
i = 1
while (n != 1)
i = i + 1
if (n % 2 == 0)
n = n /2
else
n = 3 * n + 1
end
end
return i
end
end
high_value = 0
high_collatz = 0
for i in (1..1000000)
current_value = collatz_value(i)
if (current_value > high_value)
high_value = current_value
high_collatz = i
end
end
puts high_collatz
puts high_value
| true
|
bc277282f1e402a7721aa03b64bbf9b6f406d528
|
Ruby
|
davidsiaw/minazuki
|
/main.rb
|
UTF-8
| 8,708
| 2.65625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'active_support/inflector'
require 'date'
require 'fileutils'
require 'erubis'
require 'bunny/tsort'
# Global generator
class GlobalGenerator
attr_reader :resources
def initialize(file, resources)
@resources = resources
@file = file
end
def filename
@file
.sub(%r{^generators/}, './')
.sub(/.erb$/, '')
end
end
# Resource generator
class ResourceGenerator
attr_reader :name, :resource, :index
def initialize(file, name, resource, index)
@name = name
@resource = resource
@index = index
@file = file
end
def id_of(index)
# date = Time.now
# year = date.year
# month = date.month.to_s.rjust(2, '0')
# day = date.day.to_s.rjust(2, '0')
count = index.to_s.rjust(6, '0')
"20342034#{count}"
end
def filename
@file
.sub(%r{^generators/}, './')
.sub(/.erb$/, '')
.sub('-id-', id_of(index))
.sub('-resourcename-plural-', name.to_s.pluralize)
.sub('-resourcename-', name.to_s)
end
end
# Expands collections to a nominal class structure
class ResourceExpander
attr_reader :expanded, :deptree, :owners
def initialize(resources)
@resources = resources
@expanded = {}
@deptree = {}
@owners = {}
expand!
end
private
def expand!
cur_collections = @resources.dup
# Expand collections
loop do
collections = blow_up(cur_collections)
break if collections.count.zero?
cur_collections = collections
end
end
def blow_up(cur_collections)
collections = {}
cur_collections.each do |k, r|
expanded[k] = r
add_dependencies(k, r)
r.collections.each do |ck, cr|
collections[:"#{k}_#{ck}"] = cr
end
end
collections
end
def add_dependencies(resource_name, resource)
@deptree[resource_name] = [] unless @deptree.key? resource_name
@deptree[resource_name] << resource.parent if resource.parent
resource.collections.each do |ck, _|
@owners[:"#{resource_name}_#{ck}"] = resource_name
@deptree[:"#{resource_name}_#{ck}"] = [resource_name]
end
end
end
# generator
class Generator
def initialize(dsl)
@dsl = dsl
end
def generate
prepare_program!
generate_resources!
generate_globals!
system 'cd rails-zen && rubocop --auto-correct'
end
def basic_types
%i[string integer boolean]
end
def basic?(type)
basic_types.include? type
end
def indexable?(type)
%i[string integer].include? type
end
private
def expander
@expander ||= ResourceExpander.new(@dsl.resources)
end
# Expand collections
def expanded_resources
expander.expanded
end
def resource_deptree
expander.deptree
end
def resources_in_order
@resources_in_order ||= Bunny::Tsort.tsort(resource_deptree)
end
def prepare_resources
result = {}
# Prepare main resource classes
resources_in_order.each do |arr|
arr.each do |resourcename|
r = expanded_resources[resourcename]
result[resourcename] = make_prepared_resource(resourcename, r, result)
end
end
{ **result }
end
def make_prepared_resource(resource_name, resource, result)
PreparedResourceClass.new(
resource.fields,
resource.parent,
result[resource.parent],
resource.collections.map { |k, _| [k, { type: :"#{resource_name}_#{k}" }] }.to_h,
expander.owners[resource_name]
)
end
def resources
@resources ||= prepare_resources
end
def generator_files
Dir['generators/**/*.erb']
end
def general_files
generator_files.reject { |x| x.include? '-resourcename-' }
end
def resource_files
generator_files.select { |x| x.include? '-resourcename-' }
end
def generate_resources!
resource_files.each do |file|
template = File.read(file)
resources.each_with_index do |(name, resource), index|
generate_file!(template, file, name, resource, index)
end
end
end
def generate_file!(template, file, name, resource, index)
generator = Erubis::Eruby.new(template, filename: file)
rg = ResourceGenerator.new(file, name, resource, index)
FileUtils.mkdir_p File.dirname(rg.filename)
result = generator.result(rg.send(:binding)).gsub(/\n\n+/, "\n\n")
File.write(rg.filename, result)
end
def generate_globals!
general_files.each do |file|
gen = GlobalGenerator.new(file, resources)
template = File.read(file)
generator = Erubis::Eruby.new(template)
FileUtils.mkdir_p File.dirname(gen.filename)
File.write(gen.filename, generator.result(gen.send(:binding)))
end
end
def prepare_program!
repo = ENV['REPO'] || 'git@github.com:davidsiaw/rails-zen'
`rm -rf rails-zen`
`git clone #{repo}`
files = Dir['rails-zen/**/*']
files.each do |file|
next unless File.file?(file)
content = File.read(file)
content = content.gsub('rails_zen', 'meowery').gsub('RailsZen', 'Meowery')
File.write(file, content)
end
end
def owners_of(resource)
result = []
cur_owner_name = resource.owner
loop do
break if cur_owner_name.nil?
result << cur_owner_name
cur_owner_name = @resources[cur_owner_name].owner
end
result
end
def base_owners_of(resource)
arr = owners_of(resource)
arr.count.times do |index|
word = arr[-1 - index]
(arr.count - index - 1).times do |i|
arr[i] = arr[i].to_s[word.length + 1..-1].to_sym
end
end
arr
end
end
# resource used for generation
class PreparedResourceClass
attr_reader :fields,
:parent_name,
:parent_resource,
:collections,
:owner
def initialize(fields,
parent_name = nil,
parent_resource = nil,
collections = {},
owner = nil)
@fields = fields
@parent_name = parent_name
@parent_resource = parent_resource
@collections = collections
@owner = owner
end
def parent_fields
@parent_fields ||= compile_fields
end
private
def compile_fields
return [] if @parent_name.nil?
result = {}
result[parent_name] = parent_resource.fields.dup
parent_resource.parent_fields.each do |_gparent_name, gparent_fields|
result[parent_name].merge! gparent_fields
end
result
end
end
# resource
class ResourceClass
attr_reader :fields, :parent, :collections
def initialize(parent_class:)
@fields = {}
@parent = parent_class
@collections = {}
end
private
def field(name, options = {})
raise 'fields cannot start with underscore' if name.to_s.start_with?('_')
@fields[name] = options
end
def collection(name, &block)
crc = ResourceClass.new(parent_class: nil)
crc.instance_eval(&block)
@collections[name] = crc
end
end
# meow
class DSL
attr_reader :resources
def initialize
@resources = {}
end
private
def resource_class(name, extends: nil, &block)
rc = ResourceClass.new(parent_class: extends)
rc.instance_eval(&block)
@resources[name] = rc
end
end
dsl = DSL.new
dsl.instance_eval do
resource_class :song do
field :name, type: :string
end
end
gen = Generator.new dsl
gen.generate
if ENV['REPO']
exec <<~START
cd rails-zen
bundle install
ls
docker-compose -f .circleci/compose-unit.yml up -d
START
else
exec <<~START
cd rails-zen
docker-compose up --build -d
docker logs -f rails
docker-compose down -v
START
end
# resource_class :band do
# field :name, type: :string
# # has_many :artist
# end
# resource_class :artist do
# field :name, type: :string
# end
# resource_class :album do
# field :name, type: :string
# # has_many :song
# end
# resource_class :song do
# field :name, type: :string
# field :url, type: :string
# field :length_seconds, type: :integer
# # has_many :artist
# collection :lyric do
# field :timestamp_seconds, type: :integer
# collection :line do
# field :content, type: :string
# field :lang_code, type: :string
# collection :annotation do
# field :content, type: :string
# field :tag, type: :string
# end
# end
# end
# end
# resource_class :derivation, extends: :song do
# field :original, type: :song
# end
# resource_class :remix, extends: :derivation do
# end
# resource_class :cover, extends: :derivation do
# end
# resource_class :instrumental, extends: :derivation do
# end
# resource_class :arrange, extends: :derivation do
# end
| true
|
c65066b4aff4e3b5ab22c6432f610f71941c2787
|
Ruby
|
tkbrigham/pronto
|
/lib/pronto_summarizer.rb
|
UTF-8
| 601
| 2.5625
| 3
|
[] |
no_license
|
class ProntoSummarizer
def initialize(timestamp)
@timestamp = timestamp
end
def stats
StationStat.where(timestamp: @timestamp)
end
def summarize
stats.each do |stat|
StatSummarizer.new(stat).summarize
end
end
def clean
StationStat.where('created_at <= ?', Time.now - 1.hour).destroy_all
Station.where('updated_at <= ?', Time.now - 24.hours).update_all(status: 0)
disabled_station_ids = Station.where.not(status: 1).collect(&:id)
StationStat.where(station_id: disabled_station_ids).destroy_all
end
def update
summarize && clean
end
end
| true
|
f8886b97c6a5fbbee257c5b1350d7511ed6ed5e1
|
Ruby
|
suzuki211/ruby
|
/numeric.rb
|
UTF-8
| 64
| 2.796875
| 3
|
[] |
no_license
|
puts 1100
puts 100+3
puts 100-3
puts 100*3
puts 100/3
puts 100%3
| true
|
f3c69c2a139c5a5b233d9f498de61f780acfb845
|
Ruby
|
bnix/pdf417-rb
|
/lib/pdf417/text_compactor.rb
|
UTF-8
| 3,561
| 3.078125
| 3
|
[] |
no_license
|
module PDF417
class TextCompactor
PAD_CODEPOINT = 29
SUBMODE_UPPER = 'UPP'
SUBMODE_LOWER = 'LOW'
SUBMODE_MIXED = 'MIX'
SUBMODE_PUNCT = 'PUN'
# Generate mappings of PDF417 submode codepoints to ASCII characters
CODEPOINTS = {
SUBMODE_UPPER => "ABCDEFGHIJKLMNOPQRSTUVWXYZ\s",
SUBMODE_LOWER => "abcdefghijklmnopqrstuvwxyz\s",
SUBMODE_MIXED => "0123456789&\r\t,:#-.$/+%*=^",
SUBMODE_PUNCT => ";<>@[\\]_`~!\r\t,:\n-.$/\"|*()?{}'"
}.transform_values! do |submode_chars|
submode_chars.chars.each_with_object({}).with_index do |(char, acc), i|
acc[char] = i
acc
end
end
CODEPOINT_SUPERSET = CODEPOINTS.values.reduce(Set.new) do |set, codepoints|
set.merge(codepoints.keys)
end
# Codepoint sequences for changing submode
JUMP_COMMANDS = {
SUBMODE_UPPER => {
SUBMODE_LOWER => [27],
SUBMODE_MIXED => [28],
SUBMODE_PUNCT => [28, 25]
},
SUBMODE_LOWER => {
SUBMODE_UPPER => [28, 28],
SUBMODE_MIXED => [28],
SUBMODE_PUNCT => [28, 25]
},
SUBMODE_MIXED => {
SUBMODE_LOWER => [27],
SUBMODE_UPPER => [28],
SUBMODE_PUNCT => [25]
},
SUBMODE_PUNCT => {
SUBMODE_LOWER => [29, 27],
SUBMODE_UPPER => [29],
SUBMODE_MIXED => [29, 28]
}
}
attr_reader :message
def initialize(message)
@message = message
end
def compact(start, length)
compact_text(start, length).each_slice(2).map do |left, right|
(left * 30) + (right || PAD_CODEPOINT)
end
end
# Encode each char as a submode codepoint, changing submode only
# when current char cannot be mapped to a codepoint in current submode.
def compact_text(start = 0, length = @message.length)
codepoints = []
current_submode = SUBMODE_UPPER
message[start, length].each_char do |char|
submode = next_submode(char, current_submode)
if current_submode != submode
codepoints.concat(jump_submode(current_submode, submode))
current_submode = submode
end
codepoints << codepoint(char, current_submode)
end
codepoints
end
def compactable_length(start)
pos = start
consecutive_text_count = 0
consecutive_number_count = 0
while pos < message.length
char = message[pos]
if char >= '0' && char <= '9'
consecutive_number_count += 1
consecutive_text_count += 1
if consecutive_number_count == 13
consecutive_text_count -= consecutive_number_count
break
end
elsif CODEPOINT_SUPERSET.include?(char)
consecutive_number_count = 0
consecutive_text_count += 1
else
break
end
pos += 1
end
# TODO byte compaction would be used for < 5 characters
# consecutive_text_count >= 5 ? consecutive_text_count : 0
consecutive_text_count
end
def next_submode(char, preferred_submode)
submode_options = CODEPOINTS.reduce([]) do |acc, (submode, codepoints)|
acc << submode if codepoints.key?(char)
acc
end
if submode_options.include?(preferred_submode)
preferred_submode
else
submode_options.first
end
end
def codepoint(char, submode)
CODEPOINTS[submode][char]
end
def jump_submode(from_submode, to_submode)
JUMP_COMMANDS[from_submode][to_submode]
end
end
end
| true
|
4b19ec08c8f2ee48ae7019a6b5c1334865a34c04
|
Ruby
|
ilyakogan/tahanot
|
/ruby-website/app/models/stop.rb
|
UTF-8
| 794
| 2.546875
| 3
|
[] |
no_license
|
class Stop < ActiveRecord::Base
include HasAddress
self.primary_key = "stop_code"
has_many :stop_times, primary_key: "stop_id"
has_many :trips, through: :stop_times
after_find { |stop| stop.fill_address }
def self.find_last_in_trip(trip_id)
joins(:trips).where(stop_times: {trip_id: trip_id}).order("stop_sequence").last
end
def find_closest(max_dist_meters)
d_lon = max_dist_meters / 111320.0 / Math.cos(self.stop_lat / 180 * Math::PI)
d_lat = max_dist_meters / 110540.0
from_lon, to_lon = self.stop_lon - d_lon, self.stop_lon + d_lon
from_lat, to_lat = self.stop_lat - d_lat, self.stop_lat + d_lat
Stop.where(stop_lon: Float(from_lon)..Float(to_lon),
stop_lat: Float(from_lat)..Float(to_lat)).where.not(stop_id: self.stop_id)
end
end
| true
|
619049d20e7af343479cf95ebf3e6f514d6c7521
|
Ruby
|
ajengs/kolla-go-food
|
/spec/models/voucher_spec.rb
|
UTF-8
| 4,268
| 2.65625
| 3
|
[] |
no_license
|
require 'rails_helper'
describe Voucher do
it 'has a valid factory' do
expect(build(:voucher)).to be_valid
end
it 'is valid with code, amount, unit, valid_from, valid_through, max_amount' do
expect(build(:voucher)).to be_valid
end
it 'is invalid without a code' do
voucher = build(:voucher, code: nil)
voucher.valid?
expect(voucher.errors[:code]).to include("can't be blank")
end
it 'saves code in all capital letters' do
voucher = create(:voucher, code: 'code')
expect(voucher.code).to eq('CODE')
end
it 'is invalid with duplicate code' do
voucher = create(:voucher, code: 'DISC5K')
voucher2 = build(:voucher, code: 'DISC5K')
voucher2.valid?
expect(voucher2.errors[:code]).to include("has already been taken")
end
it 'is invalid with case insensitive duplicate code' do
voucher = create(:voucher, code: 'DISC5K')
voucher2 = build(:voucher, code: 'disc5k')
voucher2.valid?
expect(voucher2.errors[:code]).to include("has already been taken")
end
it 'is invalid without amount' do
voucher = build(:voucher, amount: nil)
voucher.valid?
expect(voucher.errors[:amount]).to include("can't be blank")
end
it 'is invalid with non-numeric amount' do
voucher = build(:voucher, amount: '1ooo')
voucher.valid?
expect(voucher.errors[:amount]).to include("is not a number")
end
it 'is invalid with negative or 0 amount' do
voucher = build(:voucher, amount: -100)
voucher.valid?
expect(voucher.errors[:amount]).to include("must be greater than 0")
end
it 'is invalid without unit' do
voucher = build(:voucher, unit: nil)
voucher.valid?
expect(voucher.errors[:unit]).to include("can't be blank")
end
it 'is invalid with unit other than percent or rupiah' do
expect{ build(:voucher, unit: 'dollar') }.to raise_error(ArgumentError)
end
it 'is invalid without max_amount' do
voucher = build(:voucher, max_amount: nil)
voucher.valid?
expect(voucher.errors[:max_amount]).to include("can't be blank")
end
it 'is invalid with non-numeric max_amount' do
voucher = build(:voucher, max_amount: 'dollar')
voucher.valid?
expect(voucher.errors[:max_amount]).to include("is not a number")
end
it 'is invalid with negative or 0 max_amount' do
voucher = build(:voucher, max_amount: -100)
voucher.valid?
expect(voucher.errors[:max_amount]).to include("must be greater than 0")
end
context 'with unit value rupiah' do
it 'is invalid with max_amount less than amount' do
voucher = build(:voucher, unit:'Rupiah', amount:10000, max_amount:5000)
voucher.valid?
expect(voucher.errors[:max_amount]).to include("must be greater than or equal to amount")
end
end
it 'is invalid without valid_from' do
voucher = build(:voucher, valid_from: nil)
voucher.valid?
expect(voucher.errors[:valid_from]).to include("can't be blank")
end
it 'is invalid without valid_through' do
voucher = build(:voucher, valid_through: nil)
voucher.valid?
expect(voucher.errors[:valid_through]).to include("can't be blank")
end
it 'is invalid if valid_from > valid_through' do
voucher = build(:voucher, valid_from: 1.day.from_now, valid_through: 2.days.ago)
voucher.valid?
expect(voucher.errors[:valid_through]).to include("must be greater than or equal to valid from")
end
describe 'calculates discount' do
it 'returns the amount of discount if unit is rupiah' do
voucher = create(:voucher, amount: 20000, unit: 'Rupiah', max_amount: 30000)
expect(voucher.discount(100000)).to eq(20000)
end
it 'returns discount amount in rupiah if unit is percent' do
voucher = create(:voucher, amount: 15, unit: 'Percent', max_amount: 10000)
expect(voucher.discount(20000)).to eq(3000)
end
it 'returns max amount of discount if discount > max_amount' do
voucher = create(:voucher, amount: 50, unit: 'Percent', max_amount: 30000)
expect(voucher.discount(100000)).to eq(30000)
end
end
it "can't be destroyed while it has order(s)" do
voucher = create(:voucher)
order = create(:order, voucher: voucher)
expect{ voucher.destroy }.not_to change(Voucher, :count)
end
end
| true
|
95c80c5499522ff162434136f69d1925169c4cd2
|
Ruby
|
Phabibi/Agile
|
/app/models/player.rb
|
UTF-8
| 1,200
| 2.703125
| 3
|
[] |
no_license
|
require 'bcrypt'
class Player < ApplicationRecord
attr_accessor :remember_token
# Territory records will be cleared with the respective player.
has_many :territory, dependent: :destroy
# Attribute restrictions before saving to database.
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
validates :password, presence: true, length: { minimum: 4}
validates :password, confirmation: { case_sensitive: true }
def Player.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def Player.new_token
SecureRandom.urlsafe_base64
end
# Save remember_token to database:
def remember
self.remember_token = Player.new_token
update_attribute(:remember_digest, Player.digest(remember_token))
end
# Verify logged in users:
def authenticate(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# Remove remember_token from database:
def forget
update_attribute(:remember_digest, nil)
end
end
| true
|
f73cc6c56d782bdd80d3aa059d57ee3c5e1a81ed
|
Ruby
|
el-mark/ruby_course
|
/oop/authenticator.rb
|
UTF-8
| 859
| 3.546875
| 4
|
[] |
no_license
|
require 'bcrypt'
class User
attr_accessor :name, :email, :password
def initialize(name, email, password)
@name = name
@email = email
@password = set_password(password)
end
def set_password(password)
BCrypt::Password.create(password)
end
def get_password
BCrypt::Password.new(@password)
end
def log_in(email, password)
b_password = get_password
if (@email == email && b_password == password)
'Login successful'
else
'Login failed'
end
end
end
mark = User.new('Mark', 'mharmsenr@example.com', 'secretword')
# puts mark.password
# puts mark.name
# puts mark.email
puts 'First login attempt (should fail)'
puts mark.log_in('mharmsenr@example.com', 'secretword2')
puts 'First login attempt (should work)'
puts mark.log_in('mharmsenr@example.com', 'secretword')
| true
|
32ac778735a752cabeaefd602ff2a66db9c8863d
|
Ruby
|
debzow/ruby_exercices_week_0
|
/exo_17.rb
|
UTF-8
| 405
| 3.390625
| 3
|
[] |
no_license
|
currentYear = Time.now.strftime("%Y").to_i
puts "Donnes moi ton année de naissance !!!!"
print ">"
userBirthYear = gets.chomp.to_i
y = userBirthYear
while (y <= currentYear) do
puts "Il y a #{currentYear-y} ans, tu avais #{y-userBirthYear} ans .."
puts "Et! Il y a #{currentYear-y} tu avais la moitié de l'age que tu as aujourd'hui !!!!" if ((currentYear-y) == (y-userBirthYear))
y += 1
end
| true
|
c22bf2ffafb1df8f946dd82e022d28596f723601
|
Ruby
|
iwaseasahi/design_pattern_with_ruby
|
/Proxy/printer_proxy.rb
|
UTF-8
| 432
| 2.9375
| 3
|
[] |
no_license
|
require_relative 'printable'
require_relative 'printer'
class PrinterProxy < Printable
def initialize(name)
@name = name
@real = nil
end
def set_printer_name(name)
@real.set_print_name(name) unless @real.nil?
@name = name
end
def get_printer_name
@name
end
def print_out(string)
realize
@real.print_out(string)
end
private
def realize
@real ||= Printer.new(@name)
end
end
| true
|
edecf4b06d3b2bf49d4ddb8a757bac5fa7439378
|
Ruby
|
anfurion/tn-ruby
|
/oop/validation.rb
|
UTF-8
| 1,438
| 2.765625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module Validation
def self.included(base)
base.extend ClassMethods
base.include InstanceMethods
end
module ClassMethods
attr_reader :validations
def validate(attr_name, check, options = nil)
@validations ||= []
@validations << { attr_name: attr_name, check: check, options: options }
end
end
module InstanceMethods
def validate!
self.class.validations.each do |validation|
method_name = "check_#{validation[:check]}!"
send(method_name, validation[:attr_name], validation[:options])
end
end
def valid?
validate!
true
rescue StandardError
false
end
def check_presence!(attr_name, _options)
var_name = "@#{attr_name}".to_sym
var = instance_variable_get(var_name)
message = "#{attr_name} must be present"
raise ArgumentError, message if var.nil? || var.empty?
end
def check_type!(attr_name, options)
var_name = "@#{attr_name}".to_sym
var = instance_variable_get(var_name)
message = "#{attr_name} must be a #{options}"
raise ArgumentError, message unless var.is_a? options
end
def check_format!(attr_name, options)
var_name = "@#{attr_name}".to_sym
var = instance_variable_get(var_name)
message = "#{attr_name} must be in correct format"
raise ArgumentError, message if var !~ options
end
end
end
| true
|
0ff4fd090535e10664d264124a9efb866a45ffae
|
Ruby
|
weyewe/parking
|
/app/models/price_rule.rb
|
UTF-8
| 3,365
| 2.53125
| 3
|
[] |
no_license
|
class PriceRule < ActiveRecord::Base
validates_presence_of :price , :vehicle_case # , :is_base_price
validate :valid_vehicle_case
validate :no_overlap_for_non_base_rule
validate :hour_must_present_if_non_base_case
validate :valid_price
def valid_vehicle_case
return if not vehicle_case.present?
if not [
VEHICLE_CASE[:car],
VEHICLE_CASE[:motor]].include?( vehicle_case )
self.errors.add(:vehicle_case , "Harus ada jenis kendaraan")
return self
end
end
def no_overlap_for_non_base_rule
return if not vehicle_case.present?
return if not is_base_price.present?
return if is_base_price.present? and is_base_price == true
return if not hour.present?
ordered_detail_count = PriceRule.where(
:vehicle_case => vehicle_case,
:is_base_price => false ,
:is_deactivated => false ,
:hour => hour
).count
ordered_detail = PriceRule.where(
:vehicle_case => vehicle_case,
:is_base_price => false ,
:is_deactivated => false,
:hour => hour
).first
if self.persisted? and ordered_detail.id != self.id and ordered_detail_count == 1
self.errors.add(:hour, "Sudah ada rule di jam parkir ke #{hour}")
return self
end
# there is item with such item_id in the database
if not self.persisted? and ordered_detail_count != 0
self.errors.add(:hour, "Sudah ada rule di jam parkir ke #{hour}")
return self
end
end
def hour_must_present_if_non_base_case
return if not is_base_price.present?
return if is_base_price? == true
if ( not hour.present? ) ||
( hour.present? and hour.length == 0 ) ||
( hour.present? and hour.length != 0 and not hour.is_a? Numeric ) ||
( hour.present? and hour.length != 0 and hour.is_a? Numeric and hour <= 0 )
self.errors.add(:hour, "Harus ada informasi jam parkir, dimulai dari angka 1")
return self
end
end
def valid_price
return if not price.present?
if price < BigDecimal(0)
self.errors.add(:generic_errors, "Harga tidak boleh negative")
return self
end
end
def self.create_object( params )
new_object = self.new
new_object.is_base_price = params[:is_base_price]
new_object.vehicle_case = params[:vehicle_case]
new_object.hour = params[:hour ]
new_object.price = BigDecimal( params[:price] || '0')
new_object.save
return new_object
end
def update_object(params)
if self.price_rule_usages.count != 0
self.errors.add(:generic_errors, "Sudah ada ticket yang menggunakan harga ini")
return self
end
self.is_base_price = params[:is_base_price]
self.vehicle_case = params[:vehicle_case]
self.hour = params[:hour ]
self.price = BigDecimal( params[:price] || '0')
self.save
return self
end
def delete_object
if self.price_rule_usages.count != 0
self.errors.add(:generic_errors, "Sudah ada penggunaan price rule ini")
return self
end
self.destroy
end
def self.active_objects
self.where(:is_deactivated => false)
end
end
| true
|
384dab749a2ef37215eb11459bc98cf8b2f197ac
|
Ruby
|
endoflife-date/endoflife.date
|
/_plugins/end-of-life-filters.rb
|
UTF-8
| 4,401
| 2.921875
| 3
|
[
"MIT",
"CC-BY-SA-3.0",
"CC-BY-SA-4.0"
] |
permissive
|
require 'nokogiri'
# Various custom filters used by endoflife.date.
#
# All the filters has been gathered in the same module to avoid module name clashing
# (see https://github.com/endoflife-date/endoflife.date/issues/2074).
module EndOfLifeFilter
# Enables Liquid templating in front-matter.
# See https://fettblog.eu/snippets/jekyll/liquid-in-frontmatter/.
def liquify(input)
Liquid::Template.parse(input).render(@context)
end
# Parse a URI and return a relevant part
#
# Usage:
# {{ page.url | parse_uri:'host' }}
# {{ page.url | parse_uri:'scheme' }}
# {{ page.url | parse_uri:'userinfo' }}
# {{ page.url | parse_uri:'port' }}
# {{ page.url | parse_uri:'registry' }}
# {{ page.url | parse_uri:'path' }}
# {{ page.url | parse_uri:'opaque' }}
# {{ page.url | parse_uri:'query' }}
# {{ page.url | parse_uri:'fragment' }}
def parse_uri(uri_str, part='host')
URI::parse(uri_str).send(part.to_s)
end
# Extract the elements of the given kind from the HTML.
def extract_element(html, element)
entries = []
@doc = Nokogiri::HTML::DocumentFragment.parse(html)
@doc.css(element).each do |node|
entries << node.to_html
end
entries
end
# Removes the first element of the given kind from the HTML.
def remove_first_element(html, element)
doc = Nokogiri::HTML::DocumentFragment.parse(html)
e = doc.css(element)
e.first.remove if e&.first
doc.to_html
end
# Remove the '.0' if the input ends with '.0', else do nothing.
#
# Usage:
# {{ '2.1.0' | drop_zero_patch }} => '2.1'
# {{ '2.1.1' | drop_zero_patch }} => '2.1.1'
def drop_zero_patch(input)
input.delete_suffix(".0")
end
# Collapse the given cycles according to the given field.
#
# Cycle fields are transformed to a cycle range using the given range_separator. For example if
# cycles are [1, 2, 3] and the separator is " -> ", the cycle range will be "1 -> 3".
#
# Usage:
# cycles = [
# {releaseCycle:'1', java:'8', other:'a'},
# {releaseCycle:'2', java:'8', other:'b'},
# {releaseCycle:'3', java:'11', other:'c'},
# {releaseCycle:'4', java:'11', other:'d'},
# {releaseCycle:'5', java:'11', other:'d'},
# {releaseCycle:'6', java:'17', other:'e'}
# ]
#
# {{ cycles | collapse:'java',' -> ' }}
# => [{releaseCycle:'1 -> 2', java:'8'}, {releaseCycle:'3 -> 5', java:'11'}, {releaseCycle:'6', java:'17'}]
def collapse_cycles(cycles, field, range_separator)
cycles
.to_h { |e| [e['releaseCycle'], e[field]] }
.group_by { |releaseCycle, value| value } # see https://stackoverflow.com/a/18841831/374236
.map { |value, entries|
cycles = entries.map { |e| e[0] }.sort_by { |cycle| Gem::Version.new(cycle) }
cycles.length() == 1 ? [cycles.first.to_s, value] : [cycles.first.to_s + range_separator + cycles.last.to_s, value]
}
.map { |cycleRange, value| Hash['releaseCycle', cycleRange, field, value] }
end
# Compute the number of days from now to the given date.
#
# Usage (assuming now is '2023-01-01'):
# {{ '2023-01-10' | days_from_now }} => 9
# {{ '2023-01-01' | days_from_now }} => 0
# {{ '2022-12-31' | days_from_now }} => -1
def days_from_now(from)
from_timestamp = Date.parse(from.to_s).to_time.to_i
to_timestamp = Date.today.to_time.to_i
return (from_timestamp - to_timestamp) / (60 * 60 * 24)
end
# Compute the color according to the given number of days until the end.
#
# Usage:
# {{ true | end_color }} => bg-green-000
# {{ false | end_color }} => bg-red-000
# {{ -1 | end_color }} => bg-green-000
# {{ 1 | end_color }} => bg-yellow-200
# {{ 365 | end_color }} => bg-red-000
# {{ '2025-01-01' | days_from_now | end_color }} => bg-green-000
# {{ '2023-01-02' | days_from_now | end_color }} => bg-yellow-200
# {{ '2021-01-01' | days_from_now | end_color }} => bg-red-000
# {{ '2025-01-01' | end_color }} => bg-green-000
def end_color(input)
if input == true
return 'bg-green-000'
elsif input == false
return 'bg-red-000'
elsif input.is_a? Integer
if input < 0
return 'bg-red-000'
elsif input < 120
return 'bg-yellow-200'
else
return 'bg-green-000'
end
else
# Assuming it's a date
return end_color(days_from_now(input))
end
end
end
Liquid::Template.register_filter(EndOfLifeFilter)
| true
|
9e8ed6d71f8ac73d9d4870ece6f5a930a6bfc635
|
Ruby
|
davidrf/curriculum
|
/lessons/sum-of-integers/examples/002/sum_of_integers.rb
|
UTF-8
| 109
| 3.15625
| 3
|
[] |
no_license
|
def sum(file_path)
numbers = File.read(file_path).split
numbers.inject(0) { |sum, n| sum += n.to_i }
end
| true
|
672d8382742c404f72867298f3c98fac555136a4
|
Ruby
|
FelipeUrtubia/desafio_objeto_3
|
/ejer-5.rb
|
UTF-8
| 1,404
| 4.4375
| 4
|
[] |
no_license
|
# Agregar un método de instancia llámado lados en ambas clases. El método debe imprimir un string con las medidas de los lados.
# Crear un método llamado perimetro que reciba dos argumentos (lados) y devuelva el perímetro.
# Crear un método llamado area que reciba dos argumentos (lados) y devuelva el área.Instanciar un Rectangulo y un Cuadrado.
# Imprimir el área y perímetro de los objetos instanciados utilizando los métodos implementados.
class Rectangulo
attr_reader :largo, :ancho
def initialize(largo, ancho)
@largo = largo
@ancho = ancho
end
def lado
puts "La medida del rectangulo son de largo: #{@largo}cm, y #{@ancho}cm de ancho"
end
def perimetro
perimetro = @largo*2 + @ancho*2
puts "el perimetro del rectangulo es #{perimetro}cm"
end
def area
area = @largo*@ancho
puts "el area del rectangulo es #{area}cm²"
end
end
class Cuadrado
attr_reader :lado
def initialize(lado)
@lado = lado
end
def lado
puts "la medida del lado del cuadrado es: #{@lado}cm"
end
def perimetro
perimetro = @lado*4
puts "el perimetro del cuadrado es #{perimetro}cm"
end
def area
area = @lado*2
puts "el area del cuadrado es #{area}cm²"
end
end
cuadrado1 = Cuadrado.new(5)
rectangulo1 = Rectangulo.new(5,7)
cuadrado1.lado
cuadrado1.perimetro
cuadrado1.area
rectangulo1.lado
rectangulo1.perimetro
rectangulo1.area
| true
|
8bdd13c9094afdcea25ba221e4f69a8ff3c79ab7
|
Ruby
|
jmc27/TeachBack
|
/app/models/sentiment_manager.rb
|
UTF-8
| 700
| 2.65625
| 3
|
[] |
no_license
|
class sentiment_manager
def self.getAvailableSentiments(lecture)
[:engaged, :confused]
end
def SM.recordSentiment(u_id, timestamp, lecture_sentiment_id)
SentimentRecord.create(u, t, lecture_sentiment_id)
end
def SM.getSentHist(lecture, from_t, to_t, int)
# database work to look records in sentiment_history db, aggregate by times
# dasdasdasd
s = SentHistValue.new(:happy)
s.addHistVal(3, 10)
end
end
class SentHistValue
def getSentiment
:engaged
end
def getStartTime
100
end
def getValues
[100,200,300]
end
end
SM.getAvailableSentiments(lecture_id) # => [:bored, :confused]
SM.recordSentimentObservation(user_id, sent_id, lect_id)
#url
/lecture/id/feedback
| true
|
9ab5974db94c9c52a325dfe4f4608e5666908e4c
|
Ruby
|
seblindberg/texico
|
/lib/texico/cli/command/init.rb
|
UTF-8
| 3,757
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require 'tty-tree'
module Texico
module CLI
module Command
class Init < Base
def run
# Show welcome text
welcome
# As for configuration options for this session
config = ask_config
# Indicate that the config was accepted
prompt.say "#{ICON} Creating new project\n", color: :bold
# Copy the template project
copy_template config
# Save the other config options to file
ConfigFile.store config, target, opts
Git.init(target, true) unless opts[:no_git]
# We are done
prompt.say "#{ICON} Done!", color: :bold
rescue TTY::Reader::InputInterrupt
prompt.error 'Aborting'
exit
end
private
def target
File.expand_path('', opts[:args][0] || '.')
end
def welcome
if ConfigFile.exist?(opts)
if opts[:force]
prompt.warn "#{ICON} Reinitializeing existing project."
else
prompt.say "#{ICON} Hey! This project has already been setup " \
"with #{opts[:title]}!", color: :bold
prompt.say ' Use -f to force me to reinitialize it.'
exit
end
else
prompt.say "#{ICON} I just need a few details", color: :bold
end
prompt.say "\n"
end
def ask_config
folder_name = File.basename target
template_choices =
Hash[Template.list.map { |p| [File.basename(p).capitalize, p] }]
answers =
prompt.collect do
key(:name).ask( 'What should be the name of the output PDF?',
default: folder_name.downcase.gsub(' ', '-'))
key(:title).ask( 'What is the title of your document?',
default: folder_name.gsub('_', ' ').capitalize)
key(:author).ask('What is your name?',
default: ConfigFile.default[:author])
key(:email).ask( 'What is your email address?',
default: ConfigFile.default[:email])
key(:template).select("Select a template", template_choices)
end
ConfigFile.new answers, ConfigFile::DEFAULT_CONFIG
end
def copy_template(config)
params = config.to_hash
template_path = params.delete :template
template = Template.load template_path
template_structure =
template.copy(target, params, opts) do |status|
file = status.file.basename
case status.status
when :successful then prompt.decorate(file, :green)
when :target_exist then prompt.decorate(file, :red)
when :replaced_target then prompt.decorate(file, :yellow)
when :template_error then prompt.decorate(file, :blue)
end
end
tree = TTY::Tree.new template_structure
prompt.say tree.render + "\n"
file_copy_legend
end
def file_copy_legend
prompt.say \
format("%s Did copy %s Replaced existing %s File existed %s Template Error\n\n",
prompt.decorate("∎", :green),
prompt.decorate("∎", :yellow),
prompt.decorate("∎", :red),
prompt.decorate("∎", :blue)
)
end
class << self
def match?(command)
command == 'init'
end
end
end
end
end
end
| true
|
c572e512c0451e8c690a6bff482efe8d29df685a
|
Ruby
|
parisestmagique/Exercices_du_vendredi
|
/exo_20.rb
|
UTF-8
| 113
| 3.046875
| 3
|
[] |
no_license
|
print "Combien d'étage voulez-vous ?"
n = gets.chomp.to_i
a = 0
b = ' '
n.times do puts b = b + "#"
a +=1
end
| true
|
53e3fb1c69a47e566224c352119e941af3c65a01
|
Ruby
|
yiweihuang/Keyword-Cloud
|
/services/kmap_to_discussion.rb
|
UTF-8
| 765
| 2.640625
| 3
|
[] |
no_license
|
require 'csv'
# require 'json'
class KmapToDiscussion
def self.call(course_id:, chapter_id:, tfidf:)
kmap_info = Hash.new
kmap_point = JSON.parse(tfidf).keys
db = Mysql2::Client.new(host: ENV['HOSTNAME'], username: ENV['USERNAME'],
password: ENV['PASSWORD'], database: ENV['DATABASE'])
sql = "SELECT id, title FROM #{ENV['DISCUSSION']} WHERE cid = #{course_id}"
result = db.query(sql)
kmap_point.map do |word|
temp_arr = []
result.each do |discuss|
temp_hash = Hash.new
if discuss["title"].include? word
temp_hash[discuss["title"]] = discuss["id"]
temp_arr.push(temp_hash)
end
end
kmap_info[word] = temp_arr
end
kmap_info
end
end
| true
|
0a9c18836490ab63fa10c3335200a04fac21bdc1
|
Ruby
|
geoiq/geojoin-ruby
|
/fuzzy/example/spell.rb
|
UTF-8
| 672
| 3.015625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#!/usr/bin/ruby
$LOAD_PATH.push '..'
require 'fuzzymatch'
if ARGV.empty?
puts "Usage: spell.rb [<dictionary>] <word>"
exit
elsif ARGV.length == 1
dictionary = "/usr/share/dict/words"
lookup = ARGV[0]
lookup = 'café'
else
dictionary, lookup = ARGV[0..1]
end
idx = Fuzzymatch::Index.new()
line = 0
File.new(dictionary).each_line {|word|
line += 1
idx.insert(word.chomp, line)
}
puts "Looking up possible spellings for \"#{lookup}\"..."
dist, matches = idx.match(lookup)
if matches.any?
puts "#{matches.size} word(s) found at distance #{dist}."
matches.each {|word|
puts "#{word} (line #{idx.find(word)})"
}
else
puts "0 matches found."
end
| true
|
9303b7cb4b65eb36f0e2db3c3158d4e34aead9d6
|
Ruby
|
GAierken/programming-univbasics-4-crud-lab-dumbo-web-102819
|
/lib/array_crud.rb
|
UTF-8
| 1,226
| 3.609375
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def create_an_empty_array
[]
end
def create_an_array
toddler_toys=["crayons","playdoh","train","bear"]
end
def add_element_to_end_of_array(array, element)
toddler_toys=["crayons","playdoh","train","bear"]
toddler_toys<<"arrays!"
p toddler_toys
end
def add_element_to_start_of_array(array, element)
toddler_toys=["crayons","playdoh","train","bear"]
toddler_toys.unshift"wow"
p toddler_toys
end
def remove_element_from_end_of_array(array)
toddler_toys=["crayons","playdoh","train","arrays!"]
bear_toy=toddler_toys.pop
p toddler_toys
p bear_toy
end
def remove_element_from_start_of_array(array)
toddler_toys=["wow","playdoh","train","arrays!"]
bear_toy=toddler_toys.shift
p toddler_toys
p bear_toy
end
def retrieve_element_from_index(array, index_number)
toddler_toys=["wow","playdoh","am","arrays!"]
toddler_toys[2]
end
def retrieve_first_element_from_array(array)
toddler_toys=["wow","playdoh","am","arrays!"]
toddler_toys[0]
end
def retrieve_last_element_from_array(array)
toddler_toys=["wow","playdoh","am","arrays!"]
toddler_toys[-1]
end
def update_element_from_index(array, index_number, element)
toddler_toys=["wow","playdoh","am","arrays!"]
toddler_toys[2]= "totally"
end
| true
|
54af0564bca950e26eaa64b277bc1ea3e918de5d
|
Ruby
|
plutokid/if
|
/lib/if/repl.rb
|
UTF-8
| 1,687
| 3.09375
| 3
|
[] |
no_license
|
require "if"
module IF
class REPL
attr_reader :story
def initialize(config={}, &block)
@input = config[:input] || STDIN
@output = config[:output] || STDOUT
if config[:file]
@story = IF::Story.load config[:file], config
elsif block
@story = IF::Story.new config, &block
end
end
def run
catch :quit do
step until false
end
end
def write(text)
@story.write text
end
def write_room(room_context)
write room_context.description
room_context.objects.each do |object_context|
next if object_context.moved?
object = object_context._entity
case object.initial
when String
write object.initial
when Proc
object_context.instance_eval &object.initial
end
end
end
def read
print "> "
input = @input.gets.chop
end
def step
player_context = @story.get_context(@story.player)
if player_context && player_context.room && player_context.room != @last_room
write_room(player_context.room)
@last_room = player_context.room
end
input = read
matchers = @story.verbs.map do |v|
v.get_matcher objects: @story.objects
end
match = nil
matchers.find { |m| match = m.match input }
if match
context = IF::Context.new(@story, nil)
context.instance_exec(*match.args, &match.proc)
else
write "What do you mean?"
end
end
end
end
| true
|
afad0ddb7b1a1eab3a1f44fcb047822faee05fab
|
Ruby
|
rajat-11223/aprroveforme
|
/app/services/payment_gateway/set_default_card.rb
|
UTF-8
| 389
| 2.546875
| 3
|
[] |
no_license
|
module PaymentGateway
class SetDefaultCard
def initialize(user)
@user = user
end
def call(token:)
customer = user.payment_customer
raise "Don't have a customer" unless customer.present?
raise "Didn't provide token" unless token.present?
customer.default_source = token
customer.save
end
private
attr_reader :user
end
end
| true
|
9c1564d34eac39a092d5dc5c4a45a97449ad9117
|
Ruby
|
maksar/equation_builder
|
/lib/equation_builder.rb
|
UTF-8
| 1,753
| 3.375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
class EquationBuilder
def initialize _numbers, _result, _operators
@numbers = _numbers
@result = _result
@operators = Array(_operators)
@matcher = proc { |numbers, operators, result| numbers.zip(operators).flatten.join if eval(make_float(numbers).zip(operators).flatten.join) == result }
end
def solve
solve_simple || solve_with_parentheses || nil
end
private
def solve_simple
with_permutations do |numbers, operators|
result = @matcher.call(numbers, operators, @result)
return result if result
end
nil
end
def solve_with_parentheses
with_permutations do |numbers, operators|
with_parentheses(@numbers.length.div(2), numbers, (0..@numbers.length).to_a) do |numbers_with_parentheses|
result = @matcher.call(numbers_with_parentheses, operators, @result)
return result if result
end
end
nil
end
def with_parentheses number, numbers, parentheses_options, &block
return if number == 0
parentheses_options.combination(2) do |positions|
block.call add_parentheses numbers.dup, positions
end
parentheses_options.combination(2) do |positions|
with_parentheses number - 1, add_parentheses(numbers.dup, positions), parentheses_options, &block
end
end
def with_permutations &block
@numbers.permutation do |numbers|
@operators.repeated_permutation @numbers.length - 1 do |operators|
block.call(numbers, operators)
end
end
end
def make_float numbers
numbers.map { |element| "#{element}*1.0" }
end
def add_parentheses numbers, position
numbers[position.first] = "(#{numbers[position.first]}"
numbers[position.last] = "#{numbers[position.last]})"
numbers
end
end
| true
|
39d4d1aecb86a00e4824262eadb83763560e2bd0
|
Ruby
|
bguest/blinky
|
/spec/models/sign_spec.rb
|
UTF-8
| 4,593
| 2.8125
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: signs
#
# id :integer not null, primary key
# phrase :text
# letter_order :text
# created_at :datetime
# updated_at :datetime
# effects :integer
# color :string(255)
# background_color :string(255)
# fade_time :float
#
# Indexes
#
# index_signs_on_effects (effects)
#
require 'spec_helper'
describe Sign do
let(:sign){Sign.new}
describe 'relations and properties' do
it{ should serialize(:color).as ColorSerializer }
it{ should serialize(:background_color).as ColorSerializer}
it{ should serialize(:letter_order).as Array}
it{ should have_many(:letters)}
end
it 'should be able to have letters' do
letter = Letter.new
sign.letters << letter
expect(sign.letters.first).to eq(letter)
end
it 'should have color attribute' do
sign.color = Color::RGB::Red
expect(sign.color).to eq(Color::RGB::Red)
end
describe '#add_letters' do
let(:l1){Letter.new}
let(:l2){Letter.new}
before {sign.add_letters(l1,l2)}
it{expect(l1.number).to eq(0)}
it{expect(l2.number).to eq(1)}
it{expect(sign.letters.size).to eq(2)}
it "should have the correct letter order" do
expect(sign.letter_order).to eq([0,1])
end
end
describe '#fade_time' do
it 'should default to 72 seconds' do
expect(sign.fade_time).to eq(72)
end
end
describe '#init' do
describe 'sets defaults' do
it 'should have default background color' do
expect(Sign.new.background_color).to eq(Color::RGB::Black)
end
it 'should have default color' do
expect(Sign.new.color).to eq(Color::RGB::White)
end
end
context 'when adding letters directly' do
let(:l1){Letter.new}
let(:l2){Letter.new}
before do
@sign = Sign.new(letters:[l1,l2])
end
it{expect(l1.number).to eq(0)}
it{expect(l2.number).to eq(1)}
it{expect(@sign.letter_order).to eq([0,1])}
end
end
describe '#letter_order' do
it 'should not overwrite existing order' do
s = Sign.new(letter_order:[1,2])
expect(s.letter_order).to eq([1,2])
end
it 'should be able to store letter order' do
l = Sign.new
l.letter_order = [1,2,4,5]
expect(l.letter_order).to eq([1,2,4,5])
end
end
describe '#ordered_segments' do
context 'should return segments in order specified by segment_order' do
let(:ordered){Sign.new(letter_order:[2,5,4,1,3]).ordered_letters}
it{expect(ordered[0].number).to eq(2)}
it{expect(ordered[2].number).to eq(4)}
it{expect(ordered[4].number).to eq(3)}
end
end
describe '#phrase' do
it 'should store phrase' do
sign.phrase = 'Hello there Guy'
expect(sign.phrase).to eq('HELLO THERE GUY')
end
end
describe '#remove_letters' do
%i(l1 l2 l3 l4).each do |ll|
let(ll){Letter.new}
end
before do
sign.add_letters(l1,l2,l3,l4)
sign.set_letter_order(3,1,2,0)
sign.remove_letters(l1,l3)
end
it{expect(l2.number).to eq(1)}
it{expect(l4.number).to eq(3)}
it{expect(sign.letters.size).to eq(2)}
it "should have the correct letter order" do
expect(sign.letter_order).to eq([3,1])
end
end
describe '#set_letter_order' do
context 'when letters are added' do
let(:sign) do
s = Sign.new(letter_order:[1,4])
s.set_letter_order(1,2,3,4)
s
end
it 'should have the right number of letters' do
expect(sign.letters.size).to eq(4)
end
(1..4).to_a.each do |n|
it{expect(sign.letter_number(n).number).to eq(n)}
end
end
context 'when letters are subtracted' do
let(:sign) do
s = Sign.new(letter_order:[1,2,3,4])
s.set_letter_order [1,4]
s
end
it 'should have the right number of letters' do
expect(sign.letters.size).to eq(2)
end
[1,4].each do |n|
it{expect(sign.letter_number(n).number).to eq(n)}
end
[2,3].each{|n| it{ expect(sign.letter_number(n)).to be_nil}}
end
end
describe '#tempo' do
it 'should default to 60' do
expect(Sign.new.tempo).to eq(60)
end
end
describe '#push' do
it 'should save and push to LedString' do
sign = Sign.new(phrase:'Hi Mom', letter_order:[0,1,2,3])
LedString.new.add_sign(sign)
Effects::Manager.expects(:run).with(sign)
sign.expects(:save).returns true
expect(sign.push).to eq(true)
end
end
end
| true
|
650602cc4147a187592591bcc66be4f219fdb74d
|
Ruby
|
arosswilson/auction
|
/app/models/item.rb
|
UTF-8
| 423
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
class Item < ActiveRecord::Base
# Remember to create a migration!
belongs_to :user
has_many :bids
def list_of_winning_items(array_of_items, user)
items_won = []
array_of_items.each do |item|
if item.stop < Time.now
item.winning_bidder_id = item.bids.order(:amount).last.user_id
if item.winning_bidder_id == user.id
items_won << item
end
end
end
end
end
| true
|
e12068e3266fc972fc7953204bb895eecc0b1f55
|
Ruby
|
RSchaubeck/ttt-with-ai-project-v-000
|
/lib/players/computer.rb
|
UTF-8
| 1,479
| 3.109375
| 3
|
[] |
no_license
|
module Players
class Computer < Player
def move(board)
if start(board)
start(board)
elsif block_or_win(board)
block_or_win(board)
else
corners_and_sides(board)
end
end
def start(board)
board.taken?(5) ? false : "5"
end
def block_or_win(board)
cpu = self.token
opp = ""
cpu == "X" ? opp = "O" : opp = "X"
Game::WIN_COMBINATIONS.each do |combo|
a = combo.select{|x| board.cells[x] == cpu}
b = combo.select{|x| board.cells[x] == opp}
if a.count == 0 && b.count == 2
block = combo.detect{|x| board.cells[x] == " "}
return block + 1
elsif a.count == 2 && b.count == 0
win = combo.detect{|x| board.cells[x] == " "}
return win + 1
end
end
false
end
def corners_and_sides(board)
cpu = self.token
opp = ""
cpu == "X" ? opp = "O" : opp = "X"
sides = [1,3,5,7]
corners = [0,2,6,8]
if board.cells[0] == opp && board.cells[8] == opp
a = sides.detect{|s| board.cells[s] == " "}
return a + 1
elsif board.cells[2] == opp && board.cells[6] == opp
b = sides.detect{|s| board.cells[s] == " "}
return b + 1
else
c = corners.detect{|c| board.cells[c] == " "}
s = sides.detect{|s| board.cells[s] == " "}
return c + 1 if c != nil
return s + 1 if s != nil
end
end
end
end
| true
|
0983168ceb1c56c68f1e61e23523dc7915fc14dc
|
Ruby
|
dvberkel/letter-soup
|
/adjacency.rb
|
UTF-8
| 896
| 3.03125
| 3
|
[] |
no_license
|
#! /usr/bin/env ruby
def in_agreement(word, candidate)
word_letters = word.split("")
for first_index in (0..(word_letters.length-2)) do
first = word_letters[first_index]
for second_index in (first_index .. (word_letters.length-1)) do
second = word_letters[second_index]
if (first != second) then
first_location = candidate.index(first)
second_location = candidate.index(second)
if (first_location and second_location and first_location > second_location) then
return false
end
end
end
end
true
end
words = []
File.open('words.txt').each_line do |line|
words << line.chomp
end
f = File.open('adjacency.txt', 'w+')
for word in words do
f.write("#{word}:#{word}")
for candidate in words do
if in_agreement(word, candidate) then
f.write(",#{candidate}")
end
end
f.write("\n")
f.flush()
end
| true
|
367c0c12f88402ca08c3277c67ab95d0757e3efd
|
Ruby
|
kthatoto/automanation
|
/resources/object_list.rb
|
UTF-8
| 487
| 3.21875
| 3
|
[] |
no_license
|
class ObjectList
def initialize
@objects = {}
end
def [](key)
@objects[key]
end
def all_objects
@objects.map{|_, objects| objects}.flatten
end
def push(key, object)
raise unless Object === object
@objects[key] = @objects[key].to_a << object
end
def clear(key)
@objects[key] = []
end
def clear_all
@objects = {}
end
def get_object_by_coordinate(y, x)
all_objects.find{|object|
object.y == y && object.x == x
}
end
end
| true
|
e4da4a4524e4e1c550456b8c94be1134dca886f3
|
Ruby
|
dipto0321/datastructures-and-algorithm
|
/ruby/learneroo/Sorting_Challeneges/find_duplicates.rb
|
UTF-8
| 297
| 3.25
| 3
|
[] |
no_license
|
def do_stuff(ar1, ar2)
ar1.each do |el|
ar2.delete_at(ar2.index(el))
end
puts ar2.sort.join(" ")
end
t = gets.to_i
inputs = []
(1..t).each do |_i|
n1 = gets
ar1 = gets.strip.split.map(&:to_i)
n2 = gets
ar2 = gets.strip.split.map(&:to_i)
do_stuff(ar1, ar2)
end
| true
|
901a79cd3ae652b30b955a70f9ef3ae7d8e3f81f
|
Ruby
|
wangjoc/betsy
|
/app/helpers/application_helper.rb
|
UTF-8
| 773
| 2.90625
| 3
|
[] |
no_license
|
module ApplicationHelper
def render_rating(rating)
rating = rating.to_i
filled_star = '<i class="fas fa-star"></i>'
empty_star = '<i class="far fa-star"></i>'
# make a list of all the filled stars
star_list = []
until rating == 0
star_list << filled_star
rating -= 1
end
# fill out the rest of the list with empty stars
until star_list.length == 5
star_list << empty_star
end
# convert star list to string
stars = star_list.join("")
return (
stars.html_safe
)
end
def cart_num_items
count = 0
if !session[:shopping_cart].nil?
session[:shopping_cart].each do |key, value|
count += value
end
end
return count
end
end
| true
|
1e9a241be7383f95b0d71dbe3280950a8cd8ba50
|
Ruby
|
warcraft23/RubyExp
|
/exp6/until.rb
|
UTF-8
| 247
| 2.96875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
$i=0
$num=3
puts "begin until"
until $i==$num do
puts ("inside loop(until) i = #$i")
$i +=1
end
puts "end until"
$i=0
puts "begin do until"
begin
puts ("inside loop(until) i = #$i")
$i +=1
end until $i==$num
puts "end do until"
| true
|
c7c2061d8ab4a56b13386e422d808113a250098a
|
Ruby
|
Soleone/chat-server
|
/lib/chat-server/room.rb
|
UTF-8
| 197
| 2.59375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Chat
class Room < EM::Channel
attr_accessor :log
def initialize
@log = []
super
end
def say(msg)
@log << msg
push(msg)
end
end
end
| true
|
9bbb0aa5c485728feb95a5ee1f8398bcec2bdb30
|
Ruby
|
peter-miklos/mercury-5
|
/api/lib/omniauth/facebook.rb
|
UTF-8
| 1,642
| 2.515625
| 3
|
[] |
no_license
|
require 'httparty'
require_relative './response_error'
module Omniauth
class Facebook
include HTTParty
base_uri "https://graph.facebook.com/v2.9"
def self.authenticate(access_token)
provider = self.new
user_info = provider.get_user_profile(access_token)
return user_info
end
def self.deauthorize(access_token)
options = { query: { access_token: access_token } }
response = self.delete('/me/permissions', options)
# Something went wrong most propably beacuse of the connection.
unless response.success?
Rails.logger.error 'Omniauth::Facebook.deauthorize Failed'
fail Omniauth::ResponseError, 'errors.auth.facebook.deauthorization'
end
response.parsed_response
end
def get_user_profile(access_token)
options = { query: { access_token: access_token } }
response = self.class.get('/me?fields=id,name,first_name,middle_name,last_name,short_name,name_format,gender,email,picture{url,height,width}', options)
# Something went wrong most propably beacuse of the connection.
unless response.success?
Rails.logger.error 'Omniauth::Facebook.get_user_profile Failed'
fail Omniauth::ResponseError, 'errors.auth.facebook.user_profile'
end
response.parsed_response
end
# private
# def query(code)
# {
# query: {
# code: code,
# redirect_uri: "http://localhost:4200/",
# client_id: Rails.application.secrets.facebook_app_id,
# client_secret: Rails.application.secrets.facebook_app_secret
# }
# }
# end
end
end
| true
|
22800e14e602345589303ca87b967eba59c5ff21
|
Ruby
|
southbambird/sandbox
|
/ruby/minitsuku/clever_print.rb
|
UTF-8
| 716
| 3.5
| 4
|
[] |
no_license
|
# coding: utf-8
def clever_print(*args)
args.each do |item|
case item
when Array
item.each do |value|
print value, " "
end
when Hash
item.each do |key, value|
print key, " ", value, " "
end
when String
print item, " "
end
end
print "\n"
end
=begin
def clever_print_kai(*args)
list = []
args.each {|item| list << item.to_a}
# Ruby1.9 で String クラスから to_aメソッドは廃止された
puts list.join(' ')
end
=end
clever_print(["Ruby"], "the", ["Programming", "Language"])
#=> Ruby the Programming Language
clever_print(["Agile", "Web", "Development"], "with", { :Rails => 3.0 })
#=> Agile Web Development with Rails 3.0
| true
|
be26c210df5fac508f463e926c744024808dce72
|
Ruby
|
guiman/adventofcode
|
/mining_elf/lib/checker.rb
|
UTF-8
| 289
| 2.984375
| 3
|
[] |
no_license
|
require 'digest'
class Checker
TEMPLATE = "%{key}%{number}"
def initialize(key)
@key = key
end
def match?(number)
test = TEMPLATE % { number: number, key: @key }
if Digest::MD5.hexdigest(test).to_s[0..5] == "000000"
number
else
nil
end
end
end
| true
|
6f9cb5b1b282d0e962e08f60ac0326330315f3d4
|
Ruby
|
Phitherek/repoto
|
/memo.rb
|
UTF-8
| 902
| 2.578125
| 3
|
[] |
no_license
|
require 'yaml'
require 'singleton'
module Repoto
class Memo
include Singleton
def initialize
reload
end
def reload
if File.exists?("memodata.yml")
@memodata = YAML.load_file("memodata.yml")
else
@memodata = {}
end
if !@memodata
@memodata = {}
end
end
def create to, from, memo
@memodata[to.to_s] ||= []
@memodata[to.to_s] << {:time => Time.now.to_s, :from => from.to_s, :message => memo.to_s}
end
def for_user user
@memodata[user]
end
def delete_user_memos user
@memodata[user] = []
end
def dump
File.open("memodata.yml", "w") do |f|
f << YAML.dump(@memodata)
end
end
end
end
| true
|
412839765d172248fe4ff4c32b4c4bb500e0a886
|
Ruby
|
marat00/Ruby-Code
|
/threads.cgi
|
UTF-8
| 1,114
| 3.34375
| 3
|
[] |
no_license
|
#!/usr/local/bin/ruby
# Name: Marat Pernabekov
# CRN: 73157
# Assignment: Lab 5
# File: threads.cgi
# encoding: utf-8
$:.unshift(File.dirname(__FILE__))
# Boilerplate
require 'cgi_helper.rb'
include CGI_Helper
require 'cgi'
cgi = CGI.new('html4')
http_header
# End of boilerplate
# Create an array of alphabetical characters
letters = ("a".."z").to_a + ("A".."Z").to_a
puts <<HTML
<!doctype html>
<html>
<head>
<meta name=charset value=utf-8>
<link rel='stylesheet' type='text/css' href='../css/threads.css'
<body>
HTML
# Create an array of threads
threads = []
# Create 10 threads and let them individually go through each
# letter of the alphabet, displaying the result on the screen
10.times do |count|
thread = Thread.new do
letters.each do |char|
print '<span class=thread' + count.to_s + '>' + char +
'<sub class=thread' + count.to_s+ '>' + count.inspect +
'</sub></span>'; $stdout.flush; sleep rand(6)
end
end
threads << thread # pass the result into the threads array
end
# Join the threads
threads.each {|thread| thread.join}
# End html
puts '</body><html>'
| true
|
8661330f2eacea1c1d3ca655c1da9cab1367b5db
|
Ruby
|
logoso321/ruby-testing
|
/02_calculator/calculator.rb
|
UTF-8
| 131
| 3.578125
| 4
|
[] |
no_license
|
def add(x,y)
x + y
end
def subtract(x,y)
x - y
end
def sum(num)
total = 0
num.each do |x|
total += x
end
return total
end
| true
|
2dacbe0c73e747e5342569f39bab3862322b5dc3
|
Ruby
|
dommichalec/launch_school
|
/testing/car.rb
|
UTF-8
| 159
| 3.109375
| 3
|
[] |
no_license
|
# Car class
class Car
attr_accessor :model
attr_reader :wheels
def initialize
@wheels = 4
end
def ==(other)
model == other.model
end
end
| true
|
1faf497efb5ee63450a8351d3131e5244453ac65
|
Ruby
|
matthewbussa/netrepobuilder
|
/appveyor.rb
|
UTF-8
| 2,138
| 2.640625
| 3
|
[] |
no_license
|
require 'json'
require 'net/http'
require 'net/https'
require 'json'
require 'uri'
class AppVeyor
def initialize(project_url, build_path, email)
@project_url = project_url
@build_path = build_path.to_s.empty? ? '.' : build_path
@email = email
@api_token = ENV['APPVEYOR_API_KEY']
@base_url = 'https://ci.appveyor.com/api'
@header = {"Authorization" => "Bearer #{@api_token}",
"Content-type" => "application/json"
}
@header_text = {
"Authorization" => "Bearer #{@api_token}",
"Content-type" => "plain/text"
}
end
def add_project()
project_url = @base_url + '/projects'
uri = URI.parse(project_url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Post.new(uri.path, @header)
request.body = {"repositoryProvider" => "git",
"repositoryName" => @project_url
}.to_json
response = https.request(request)
response
end
def update_project(project_slug, account_name)
project_url = @base_url + "/projects/#{account_name}/#{project_slug}/settings/yaml"
uri = URI.parse(project_url)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Put.new(uri.path, @header_text)
request.body = File.read('appveyor_template.yml')
.gsub!('<<EMAIL_IS_REPLACED_HERE>>', @email)
.gsub!('<<BUILD_PATH_IS_REPLACED_HERE>>', @build_path)
https.request(request)
end
def add_build(project_slug, account_name)
uri = URI.parse(@base_url + '/builds')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request = Net::HTTP::Post.new(uri.path, @header)
request.body = {
'accountName' => account_name,
'projectSlug' => project_slug,
'branch' => 'master'
}.to_json
https.request(request)
end
def setup_new_build()
project = add_project
project_response = JSON.parse(project.body)
slug = project_response["slug"]
account_name = project_response["accountName"]
update_project(slug, account_name)
add_build(slug, account_name)
end
end
| true
|
98e7d60b829e173330c4b1d747e739309c81ae1b
|
Ruby
|
TahirKalim/Learn_Ruby_with_Boris
|
/string/bangmethod.rb
|
UTF-8
| 127
| 2.796875
| 3
|
[] |
no_license
|
word = "hello"
word.capitalize!
p word
word.upcase!
p word
word.downcase!
p word
word.reserve!
p word
word.swapcase!
p word
| true
|
49b42e08a3ed9d2feaa619e757cba6a5f1f1e1fb
|
Ruby
|
coopdevs/katuma_reports
|
/app/models/measurement_unit.rb
|
UTF-8
| 1,147
| 3.140625
| 3
|
[] |
no_license
|
# This class replicates the logic contained in OFN's
# app/assets/javascripts/admin/products/services/variant_unit_manager.js.coffee
#
# It goes one step further and by decoupling from variant and product it builds
# and abstraction of a measurement unit. For weight and volume only.
class MeasurementUnit
class Error < StandardError; end
CONVERSIONS = {
'weight' => {
1.0 => 'g',
1000.0 => 'kg',
1_000_000.0 => 'T'
},
'volume' => {
0.001 => 'mL',
1.0 => 'L',
1000.0 => 'kL'
}
}.freeze
# Constructor
#
# @param type [Symbol]
# @param scale [Numeric]
# @param name [String] name of the custom unit
def initialize(type, scale, name = nil)
@type = type
@scale = scale.to_f
@name = name
end
# Returns the appropriate unit name (g, kg, L, mL, etc) for the given type
# and scale
#
# @return [String]
def to_s
if type == 'items'
name
else
CONVERSIONS.fetch(type, {}).fetch(scale)
end
rescue KeyError
raise Error, "No conversion for type '#{type}' and scale '#{scale}'"
end
private
attr_reader :scale, :type, :name
end
| true
|
557c69395e484f1f04d334acfe13f5d32c3c8399
|
Ruby
|
onlyskin/ruby-ttt
|
/lib/board.rb
|
UTF-8
| 1,503
| 3.390625
| 3
|
[] |
no_license
|
class Board
MARKERS = %w[O X]
attr_reader :cells
def initialize(cells: :no_cells_passed, size: 3)
if cells == :no_cells_passed
@cells = ['-'] * size * size
else
@cells = cells
end
@paths = paths(size)
end
def available_moves
@cells.map
.with_index(1) { |cell, i| cell == '-' ? i : nil }
.compact
end
def current_marker
MARKERS[(@cells.length - available_moves.length - 1) % 2]
end
def winner?(marker)
@paths.any? do |path|
path.all? do |cell|
@cells[cell] == marker
end
end
end
def tie?
full? && !winner?(MARKERS[1]) && !winner?(MARKERS[0])
end
def game_over?
winner?(MARKERS[1]) || winner?(MARKERS[0]) || tie?
end
def winner
if winner?(MARKERS[1])
MARKERS[1]
elsif winner?(MARKERS[0])
MARKERS[0]
end
end
def play(move)
cells = @cells.clone
cells[move - 1] = current_marker
Board.new(cells: cells, size: size)
end
def to_matrix
(0..size-1).each.map do |n|
@cells[n*size..n*size+size-1]
end
end
def size
Math.sqrt(@cells.length).to_i
end
private
def full?
available_moves.empty?
end
def paths(size)
rows = Array.new(size){|i| Array.new(size){|j| size*i+j } }
columns = rows.transpose
diagonal_1 = rows.map.with_index { |row, index| row[index] }
diagonal_2 = rows.reverse.map.with_index { |row, index| row[index] }
[*rows, *columns, diagonal_1, diagonal_2]
end
end
| true
|
a1e7080830bb92c971c4bf99535fd3bca6d667ed
|
Ruby
|
BBerastegui/foo
|
/wdg.rb
|
UTF-8
| 1,366
| 3.046875
| 3
|
[] |
no_license
|
require 'socket'
require 'digest/sha1'
def init()
receivefile()
end
def receivefile()
# Server starts
server = TCPServer.new("localhost", 2000)
puts "Server running..."
# Run 4ever
loop do
Thread.start(server.accept) do |client|
# Notify the client that party is going to start
client.puts "[/!\\] Hi. Reading..."
file = client.read
puts Time.now.to_f.to_s
tempname = Time.now.to_f.to_s + ".bin"
puts "The tempname is: "+tempname
filehandler = File.open('/tmp/'+tempname, 'w')
filehandler.write(file)
# Close client connection
client.puts "Bye bye."
client.close
# Close file handler
filehandler.close
puts "Temp. name: "+tempname
handlefile(tempname)
end
end
end
def handlefile(tempname)
hash = Digest::SHA1.hexdigest(File.read(File.open('/tmp/'+tempname,'r')))
puts hash
if (checkduplicate(hash))
puts "DUPLICATED !"
File.delete('/tmp/'+tempname)
else
puts "Not duplicated, renaming..."
File.rename('/tmp/'+tempname, '/tmp/'+hash+'.bin')
end
end
def checkduplicate(hash)
puts "I'm into checkduplicate()"
puts "Looking for " + hash + ".bin"
puts Dir.entries("/tmp/").class
Dir.entries("/tmp/").each do |e|
puts e.class
puts "File: " + e
if e.eql? hash+".bin"
puts "checkduplicate() says: DUPLICATED. Returning true."
return true
end
end
return false
end
def craftconfig()
end
#var1 = "testvar1"
#system *%W(echo -n #{var1})
init()
| true
|
05346943b924df140ecc669f40bef99796a0227a
|
Ruby
|
henryCraig/the-pokemans-clone
|
/pokemonClone/lib/pokeapi.rb
|
UTF-8
| 164
| 2.59375
| 3
|
[] |
no_license
|
require 'poke-api-v2'
(1..151).each do |n|
poke = PokeApi.get(pokemon: n)
puts poke.name
puts poke.id
puts poke.types[0].type.name
puts n
end
| true
|
8db2016f0699478e815b1bf53c58e39c007747e2
|
Ruby
|
cristianames92/Portal
|
/script/lib/build_time_profiler.rb
|
UTF-8
| 2,815
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
require 'ostruct'
require_relative 'build_time_log_parser'
class BuildTimeProfiler
attr_reader :outliers_deviation
attr_reader :warn_threshold
attr_reader :fail_threshold
attr_reader :build_log_file
attr_reader :filter_block
def initialize(outliers_deviation:, warn_threshold:, fail_threshold:, build_log_file:, &filter_block)
@outliers_deviation = outliers_deviation
@warn_threshold = warn_threshold
@fail_threshold = fail_threshold
@build_log_file = build_log_file
@filter_block = filter_block
end
def build_time_outliers
@build_time_outliers ||= begin
parser = BuildTimeLogParser.new(build_log_file)
result = parser.outliers(deviation: outliers_deviation, build_time_threshold: warn_threshold)
result = result.select(&filter_block) if filter_block
result
end
end
def build_time_outliers_count
@build_time_outliers_count ||= begin
initial = OpenStruct.new({over_threshold: 0, within_threshold: 0})
build_time_outliers.reduce(initial) do |counters, outlier|
if outlier.time >= fail_threshold
counters.over_threshold += 1
else
counters.within_threshold += 1
end
counters
end
end
end
def outliers_markdown_table(current_git_branch)
table_header = <<EOS
## Compilation time outliers
Time | File | Line | Function |
-----|------|------|----------|
EOS
table_body = build_time_outliers.map { |outlier| table_row_for(outlier, current_git_branch) }
table_header + table_body.join("\n")
end
def analysis_output(current_git_branch)
output = []
outliers = build_time_outliers_count
if outliers.over_threshold > 0
output << [:fail, "There are #{outliers.over_threshold} functions over #{fail_threshold}ms build time threshold"]
end
if outliers.within_threshold > 0
output << [:warn, "There are #{outliers.within_threshold} functions within #{warn_threshold}ms to #{fail_threshold}ms build time threshold"]
end
unless build_time_outliers.empty?
output << [:markdown, outliers_markdown_table(current_git_branch)]
end
output
end
private
def table_row_for(outlier, current_git_branch)
filename = File.basename(outlier.file_path)
github_location = outlier.file_path.gsub(Dir.pwd, "/guidomb/Portal/tree/#{current_git_branch}")
github_location += "#L#{outlier.line_number}"
"#{outlier.time}ms | [#{filename}](#{github_location}) | #{outlier.line_number} | `#{outlier.function_signature}`"
end
end
if __FILE__== $0
profiler = BuildTimeProfiler.new(
outliers_deviation: 3,
warn_threshold: 100.0,
fail_threshold: 500.0,
build_log_file: ARGV[0]
)
profiler.analysis_output('fake_git_branch').each do |type, message|
puts message
end
end
| true
|
19b9ba2cd369fa590e8465ba47a6d13b8db246c2
|
Ruby
|
AllySco/Wk_4_Dy_1
|
/specs/game_specs.rb
|
UTF-8
| 474
| 2.703125
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/rg'
require_relative '../models/game.rb'
class TestGame < Minitest::Test
def setup
@game1 = Game.new('rock', 'scissors')
@game2 = Game.new('rock', 'paper')
@game3 = Game.new('scissors', 'paper')
@game4 = Game.new('scissors', 'scissors')
@game5 = Game.new('rock', 'rock')
@game6 = Game.new('paper', 'paper')
end
def test_play
assert_equal("Player1 wins with rock", @game1.play)
end
end
| true
|
1196e94a2fc0ccdab92f61aee438b0d127f28dd9
|
Ruby
|
avv8401/wordpress
|
/modules/oski/lib/puppet/parser/functions/delete_key_with_value.rb
|
UTF-8
| 1,301
| 3.203125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#
# delete_key_with_value.rb
#
module Puppet::Parser::Functions
newfunction(:delete_key_with_value, :type => :rvalue, :doc => <<-EOS
When passed a hash table, and a match string/regex/boolean (or an array of),
this function will delete any key-value pairs it matches against.
EOS
) do |arguments|
if arguments.size != 2
raise( Puppet::ParseError,
"delete_key_with_value(): invalid arg count. must be 2." )
end
ht = arguments[0]
val = arguments[1]
if ! ht.is_a?(Hash)
fail("delete_key_with_value(): you must pass a hash as argument #1")
end
# We'll allow a strings, regexes and booleans
if val.is_a?(String) or val.is_a?(Regexp) or
val.is_a?(TrueClass) or val.is_a?(FalseClass)
val = Array.new.push(val)
elsif val.is_a?(Array) and val.size > 0
val = val.dup
else
fail("delete_key_with_value(): you must provide a string/boolean/regex " +
"or an array made up of any combination of those types" )
end
bool = [ TrueClass, FalseClass ]
ht.each do |k,v|
val.each do |m|
ht.delete(k) if m.is_a?(Regexp) and v =~ m
ht.delete(k) if ( m.is_a?(String) or bool.include?(m.class) ) and v == m
end
end
return ht
end
end
# vim: set ts=2 sw=2 et :
| true
|
cca786bce38fb7080d9fd5f356c0ed362ec2a4f5
|
Ruby
|
dotslash/dotslash.github.io
|
/_plugins/converters.rb
|
UTF-8
| 1,228
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
# https://github.com/txt2tags/plugins
# by Aurelio Jargas, MIT Licensed
# Instructions:
# Save this file inside the _plugins folder for your Jekyll site
module Jekyll
class Txt2tagsConverter < Converter
safe true
priority :low
def matches(ext)
ext =~ /^\.t2t$/i
end
def output_ext(ext)
".html"
end
# content => post/page contents (text only, no Front Matter)
# return => contents converted to HTML by txt2tags
def convert(content)
# Save contents to a temporary file, and run txt2tags on it.
# Note: added a leading blank line to mean "Empty Headers".
# http://txt2tags.org/userguide/HeaderArea.html
temp_file = '/tmp/jekyll.t2t'
File.open(temp_file, 'w') { |f| f.write("\n" + content) }
# Customize the txt2tags command line options as you wish.
# You can also use %!options on pages/posts.
`txt2tags -t html --no-headers --css-sugar -i #{temp_file} -o -`
end
end
end
# Other converter plugins
# Asciidoc: https://github.com/asciidoctor/jekyll-asciidoc
# HAML: https://gist.github.com/dtjm/517556
# Jade: https://github.com/snappylabs/jade-jekyll-plugin
# Org: https://gist.github.com/abhiyerra/7377603
# Rst: https://github.com/xdissent/jekyll-rst
| true
|
3005b408ac8a53911419d915e27c2ee03cc6e878
|
Ruby
|
lukehorak/coolMathGamesRuby
|
/Match.rb
|
UTF-8
| 1,260
| 4.28125
| 4
|
[] |
no_license
|
require './Player'
require './Problem'
require './Round'
class Match
def initialize
p1 = new_player 1
p2 = new_player 2
@players = [p1, p2]
@problems = [
Problem.new("1 + 2", 3),
Problem.new("3 * 4", 12),
Problem.new("12 - 7", 5),
Problem.new("47 + 3", 50),
Problem.new("127 * 3", 381)
].shuffle!
end
def new_player count
puts "Player #{count}, enter your name"
name = gets.chomp
Player.new name
end
def list_scores()
puts "==========================="
puts "Scores:"
@players.each do |p|
puts "#{p.name} => #{p.health.to_s} health"
end
puts "==========================="
end
def setup
puts "Ready..."
sleep 0.5
puts "Set..."
sleep 0.5
puts "MATH!"
sleep 0.5
end
def game_over?
@players.select{ |player| player.health == 0}.length > 0
end
def play
setup
turn = 0
while not game_over? do
active_player = @players.rotate![1]
this_problem = @problems.rotate![1]
turn += 1
round = Round.new(turn, active_player, this_problem)
round.ask active_player
list_scores
end
puts "#{@players.select{ |player| player.health > 0}[0].name} has won the game!"
end
end
| true
|
283a7a78aad59f090942787c84b7a13e61c2797a
|
Ruby
|
INOS-soft/knuckles
|
/lib/knuckles/active/hydrator.rb
|
UTF-8
| 2,068
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Knuckles
module Active
# The active hydrator converts minimal objects in a prepared collection
# into fully "hydrated" versions of the same record. For example, the
# initial `model` may only have the `id` and `updated_at` timestamp
# selected, which is ideal for fetching from the cache. If the object
# wasn't in the cache then all of the fields are needed for a complete
# rendering, so the hydration call will use the passed relation to fetch
# the full model and any associations.
#
# This `Hydrator` module is specifically designed to work with
# `ActiveRecord` relations. The initial objects can be anything that
# responds to `id`, but the relation should be an `ActiveRecord` relation.
module Hydrator
extend self
# Convert all uncached objects into their full representation.
#
# @param [Enumerable] prepared The prepared collection for processing
# @option [#Relation] :relation An ActiveRecord::Relation, used to
# hydrate uncached objects
#
# @example Hydrating missing objects
#
# relation = Post.all.preload(:author, :comments)
# prepared = relation.select(:id, :updated_at)
#
# Knuckles::Active::Hydrator.call(prepared, relation: relation) #=>
# # [{object: #Post<1>, cached?: false, ...
#
def call(prepared, options)
mapping = id_object_mapping(prepared)
if mapping.any?
relation = relation_without_pagination(options)
relation.where(id: mapping.keys).each do |hydrated|
mapping[hydrated.id][:object] = hydrated
end
end
prepared
end
private
def relation_without_pagination(options)
options.fetch(:relation).offset(false).limit(false)
end
def id_object_mapping(objects)
objects.each_with_object({}) do |hash, memo|
next if hash[:cached?]
memo[hash[:object].id] = hash
end
end
end
end
end
| true
|
12ea23bfe6e191efe6e25b134ece5ace4cb895bf
|
Ruby
|
waleritf/riq
|
/app/services/meta_extractor.rb
|
UTF-8
| 520
| 2.65625
| 3
|
[] |
no_license
|
require 'taglib'
class MetaExtractor
attr_reader :track_file
def initialize(track_file)
@track_file = track_file
end
def perform
TagLib::FileRef.open(track_file) do |fileref|
unless fileref.null?
tag = fileref.tag
properties = fileref.audio_properties
{
title: tag.title,
artist: tag.artist,
album: tag.album,
year: tag.year,
genre: tag.genre,
duration: properties.length
}
end
end
end
end
| true
|
16c86f4a071ecbb4ab6c09224cae2301a3471925
|
Ruby
|
artekdrzyzga/BBD
|
/vendor/bundle/gems/scrypt-3.0.7/lib/scrypt/engine.rb
|
UTF-8
| 5,745
| 2.65625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# frozen_string_literal: true
require 'ffi'
require 'openssl'
module SCrypt
module Ext
# rubocop:disable Style/SymbolArray
# Bind the external functions
attach_function :sc_calibrate,
[:size_t, :double, :double, :pointer],
:int,
blocking: true
attach_function :crypto_scrypt,
[:pointer, :size_t, :pointer, :size_t, :uint64, :uint32, :uint32, :pointer, :size_t],
:int,
blocking: true # todo
# rubocop:enable
end
class Engine
# rubocop:disable Style/MutableConstant
DEFAULTS = {
key_len: 32,
salt_size: 32,
max_mem: 16 * 1024 * 1024,
max_memfrac: 0.5,
max_time: 0.2,
cost: nil
}
# rubocop:enable
class Calibration < FFI::Struct
layout :n, :uint64,
:r, :uint32,
:p, :uint32
end
class << self
def scrypt(secret, salt, *args)
if args.length == 2
# args is [cost_string, key_len]
n, r, p = args[0].split('$').map { |x| x.to_i(16) }
key_len = args[1]
__sc_crypt(secret, salt, n, r, p, key_len)
elsif args.length == 4
# args is [n, r, p, key_len]
n, r, p = args[0, 3]
key_len = args[3]
__sc_crypt(secret, salt, n, r, p, key_len)
else
raise ArgumentError, 'invalid number of arguments (4 or 6)'
end
end
# Given a secret and a valid salt (see SCrypt::Engine.generate_salt) calculates an scrypt password hash.
def hash_secret(secret, salt, key_len = DEFAULTS[:key_len])
raise Errors::InvalidSecret, 'invalid secret' unless valid_secret?(secret)
raise Errors::InvalidSalt, 'invalid salt' unless valid_salt?(salt)
cost = autodetect_cost(salt)
salt_only = salt[/\$([A-Za-z0-9]{16,64})$/, 1]
if salt_only.length == 40
# Old-style hash with 40-character salt
salt + '$' + Digest::SHA1.hexdigest(scrypt(secret.to_s, salt, cost, 256))
else
# New-style hash
salt_only = [salt_only.sub(/^(00)+/, '')].pack('H*')
salt + '$' + scrypt(secret.to_s, salt_only, cost, key_len).unpack('H*').first.rjust(key_len * 2, '0')
end
end
# Generates a random salt with a given computational cost. Uses a saved
# cost if SCrypt::Engine.calibrate! has been called.
#
# Options:
# <tt>:cost</tt> is a cost string returned by SCrypt::Engine.calibrate
def generate_salt(options = {})
options = DEFAULTS.merge(options)
cost = options[:cost] || calibrate(options)
salt = OpenSSL::Random.random_bytes(options[:salt_size]).unpack('H*').first.rjust(16, '0')
if salt.length == 40
# If salt is 40 characters, the regexp will think that it is an old-style hash, so add a '0'.
salt = '0' + salt
end
cost + salt
end
# Returns true if +cost+ is a valid cost, false if not.
def valid_cost?(cost)
cost.match(/^[0-9a-z]+\$[0-9a-z]+\$[0-9a-z]+\$$/) != nil
end
# Returns true if +salt+ is a valid salt, false if not.
def valid_salt?(salt)
salt.match(/^[0-9a-z]+\$[0-9a-z]+\$[0-9a-z]+\$[A-Za-z0-9]{16,64}$/) != nil
end
# Returns true if +secret+ is a valid secret, false if not.
def valid_secret?(secret)
secret.respond_to?(:to_s)
end
# Returns the cost value which will result in computation limits less than the given options.
#
# Options:
# <tt>:max_time</tt> specifies the maximum number of seconds the computation should take.
# <tt>:max_mem</tt> specifies the maximum number of bytes the computation should take. A value of 0 specifies no upper limit. The minimum is always 1 MB.
# <tt>:max_memfrac</tt> specifies the maximum memory in a fraction of available resources to use. Any value equal to 0 or greater than 0.5 will result in 0.5 being used.
#
# Example:
#
# # should take less than 200ms
# SCrypt::Engine.calibrate(:max_time => 0.2)
#
def calibrate(options = {})
options = DEFAULTS.merge(options)
'%x$%x$%x$' % __sc_calibrate(options[:max_mem], options[:max_memfrac], options[:max_time])
end
# Calls SCrypt::Engine.calibrate and saves the cost string for future calls to
# SCrypt::Engine.generate_salt.
def calibrate!(options = {})
DEFAULTS[:cost] = calibrate(options)
end
# Computes the memory use of the given +cost+
def memory_use(cost)
n, r, p = cost.split('$').map { |i| i.to_i(16) }
(128 * r * p) + (256 * r) + (128 * r * n)
end
# Autodetects the cost from the salt string.
def autodetect_cost(salt)
salt[/^[0-9a-z]+\$[0-9a-z]+\$[0-9a-z]+\$/]
end
private
def __sc_calibrate(max_mem, max_memfrac, max_time)
result = nil
calibration = Calibration.new
ret_val = SCrypt::Ext.sc_calibrate(max_mem, max_memfrac, max_time, calibration)
raise "calibration error #{result}" unless ret_val.zero?
[calibration[:n], calibration[:r], calibration[:p]]
end
def __sc_crypt(secret, salt, n, r, p, key_len)
result = nil
FFI::MemoryPointer.new(:char, key_len) do |buffer|
ret_val = SCrypt::Ext.crypto_scrypt(
secret, secret.bytesize, salt, salt.bytesize,
n, r, p,
buffer, key_len
)
raise "scrypt error #{ret_val}" unless ret_val.zero?
result = buffer.read_string(key_len)
end
result
end
end
end
end
| true
|
74167a39e78ec36f9a8611d746c327cc65ef447f
|
Ruby
|
terminalnode/codewars
|
/ruby/6k-are-they-the-same/comp.rb
|
UTF-8
| 1,008
| 4.0625
| 4
|
[] |
no_license
|
# Are they the "same"?
# https://www.codewars.com/kata/550498447451fbbd7600041c
# Given two arrays of whole numbers, return true if the
# second array is the same as the first array squared
# regardless of order. Otherwise return false.
#
# If either of the arrays are nil, return false.
def comp(a1, a2)
return false if (a1.nil? or a2.nil?)
a1 = a1.sort.map { |i| i**2 }
a2 = a2.sort
a1 == a2
end
# ---------------------- #
# Tests
# ---------------------- #
def test(a1, a2, expected)
puts "Testing with inputs:\n a1: #{a1}\n a2: #{a2}"
result = comp a1, a2
if result == expected
puts " => Test passed with #{result.inspect}!\n\n"
else
puts " => Test failed. :("
puts " Got: #{result.inspect}"
puts " Expected: #{expected.inspect}\n\n"
end
end
test [121, 144, 19, 161, 19, 144, 19, 11],
[11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19],
true
test [1, 1, 2], [1, 4, 4], false
test nil, [1, 2, 3], false
test [1, 2, 3], nil, false
| true
|
fdfc29ab7df3cd6522e7586e6f32dfe3d446fe40
|
Ruby
|
Kartstig/nfl_draft
|
/app/models/player.rb
|
UTF-8
| 315
| 2.546875
| 3
|
[] |
no_license
|
class Player < ActiveRecord::Base
# Relations
has_one :draft
has_one :team, through: :draft
# Validations
validates_presence_of :name
#validates_uniqueness_of :name
def self.available
players = Player.all.delete_if { |p| p if p.team }
if players
return players
else
return false
end
end
end
| true
|
cdb54993b8f2be38e54680d7671c50f64c80b31e
|
Ruby
|
Universe-Man/cartoon-collections-prework
|
/cartoon_collections.rb
|
UTF-8
| 636
| 3.5
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def roll_call_dwarves(dwarves)
numberedDwarves = []
i = 0
until i == dwarves.length
numberedDwarves.push("#{i + 1}. #{dwarves[i]}")
i += 1
end
puts numberedDwarves
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.collect do |call|
call.capitalize + "!"
end
end
def long_planeteer_calls(calls)
calls.any? { |call| call.length > 4}
end
def find_the_cheese(foods)
cheeseFound = foods.find {|cheese| cheese == "cheddar" || cheese == "gouda" || cheese == "camembert"}
if cheeseFound == "cheddar" || cheeseFound == "gouda" || cheeseFound == "camembert"
return cheeseFound
else
end
end
| true
|
a64264864478913399a57e5b103ee35961db8133
|
Ruby
|
webdestroya/uci-scheduler
|
/lib/modules/possible_schedule.rb
|
UTF-8
| 3,919
| 3.046875
| 3
|
[] |
no_license
|
class PossibleSchedule
def initialize(search, classes)
@classes = classes
@search = search
end
def ccodes
@ccodes ||= @classes.map(&:ccode)
end
def pretty_ccodes
@pretty_ccodes ||= self.classes.map(&:pretty_ccode)
end
def classes
@classes
end
def teachers
@teachers ||= @classes.map(&:teacher).uniq.reject{|t|t.eql?('STAFF')}.sort
end
def statuses
@statuses ||= @classes.map(&:status).uniq.sort
end
def has_full?
self.has_status? "FULL"
end
def has_newonly?
self.has_status? "NewOnly"
end
def has_waitlist?
self.has_status? "Waitl"
end
def has_status?(status)
self.statuses.include? status
end
def has_time_collisions?
temp_days = {}
%w(M Tu W Th F Sa Su).each do |day|
temp_days[day] = []
temp_days[day].fill false, 0, 145
end
@classes.each do |course|
start_time = (course.start_time.to_i - course.start_time.beginning_of_day.to_i) / 600
end_time = (course.end_time.to_i - course.end_time.beginning_of_day.to_i) / 600
course.day_list.each do |day|
(start_time...end_time).each do |i|
return true if temp_days[day][i]
end
(start_time...end_time).each do |i|
temp_days[day][i] = true
end
end # /daylist
end # /courses
false
end
# This calculates a ranking of how good this schedule is
# We can then sort the schedules based on this ranking
def calc_ranking
points = [0.0]
points << 500.0 if self.has_full?
points << 400.0 if self.has_newonly?
points << 300.0 if self.has_waitlist?
# add a point value for the day length
points << ((self.longest_day[:duration]/3600.0))
points.inject(:+)
end
def ranking
@ranking ||= calc_ranking
end
# Calculate the start/end/duration of each day
def calc_day_lengths
tmp_day_lengths = []
%w(M Tu W Th F Sa Su).each do |day|
day_courses = @classes.select{|c|c.day_list.include?(day)}
next if day_courses.empty?
tmp_day_length = {
day: day,
start_time: day_courses.sort{|a,b| a.start_time <=> b.start_time}.first.start_time,
end_time: day_courses.sort{|a,b| a.end_time <=> b.end_time}.last.end_time,
duration: nil
}
tmp_day_length[:duration] = tmp_day_length[:end_time] - tmp_day_length[:start_time]
tmp_day_lengths << tmp_day_length
end
tmp_day_lengths
end
def calc_longest_day
day_lengths = self.calc_day_lengths.sort{|a,b|a[:duration] <=> b[:duration]}
longest = day_lengths.last
# Find all the other days that are this long, and show them as well
longest[:days] = %w(M Tu W Th F Sa Su) & day_lengths.select{|d|d[:duration] == longest[:duration]}.map{|d|d[:day]}
longest
end
def longest_day
@longest_day ||= calc_longest_day
end
# This will return a code to determine WHY something is invalid
def validity_response
@validity_response ||= calc_validty_response
end
def valid?
self.validity_response == :valid
end
def calc_validty_response
# Required sections
if @search.req_sections.size > 0
return :required_sections if (@search.req_sections & self.ccodes).size == 0
end
# Required statuses
unless @search.status_list.nil?
return :statuses if (@classes.map(&:status) - @search.status_list).size > 0
end
# Required days
if @search.days.size > 0
return :days if (@classes.map(&:day_list).flatten - @search.days).size > 0
end
# Start time
if @search.start_time
return :start_time if @classes.select {|c| c.start_time < @search.start_time}.size > 0
end
# end time
if @search.end_time
return :end_time if @classes.select {|c| c.end_time > @search.end_time}.size > 0
end
if self.has_time_collisions?
return :time_collisions
end
return :valid
end
end
| true
|
4499ab4a108f2b3d5dbcdc08777e9c8ab68e5c30
|
Ruby
|
albertbahia/wdi_june_2014
|
/w02/d05/ASSIGNMENT_FILES/morning_ex/lib/rejector.rb
|
UTF-8
| 364
| 3.375
| 3
|
[] |
no_license
|
def rejector(array_of_values)
array_of_values.reject{ |string| string.to_i % 2 == 1 }
.map { |string| string.to_i}
.reduce(:+)
end
def rejector(array_of_values)
array_of_values.reject { |string| string.to_i.odd? }
.reduce(0) { |sum, n| sum + n.to_i }
end
# def rejector(array)
# array.map {|num| num.to_i.even? ? num.to_i : 0 }
# .reduce(:+)
# end
| true
|
bc83668f8a270ea3f1e8658d27b43cf1dd75207e
|
Ruby
|
NaokiOouchi/ruby-cherry
|
/section4/until.rb
|
UTF-8
| 85
| 2.921875
| 3
|
[] |
no_license
|
a = [10, 20, 30, 40, 50]
until a.size <= 3
a.delete_at(-1)
end
a # => [10, 20, 30]
| true
|
f32ab417c8edf46ae2947d0235e560c6bcc6aa5a
|
Ruby
|
JeffreyCheng92/appacademy_prep
|
/prep work/week 2/day 5/bubble_sort.rb
|
UTF-8
| 382
| 3.390625
| 3
|
[] |
no_license
|
def bubble_sort(array = [])
sorted = false
until sorted
sorted = true
array.each_index do |idx|
next if idx == array.length - 1
if array[idx] > array[idx + 1]
array[idx], array[idx + 1] = array[idx + 1], array[idx]
sorted = false
end
end
end
array
end
if __FILE__ == $PROGRAM_NAME
p bubble_sort([3, 2, 1])
p bubble_sort([10,15,19,66,55])
end
| true
|
413603ef215420e0b28bf19589760d958bdc8598
|
Ruby
|
JeremyOttley/ruby-learn
|
/calculate
|
UTF-8
| 612
| 4.1875
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
def calculate
prompt = <<EOF
Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
EOF
puts prompt
operation = gets.chomp
puts "Enter your first number: "
number_1 = gets.chomp.to_i
puts "Enter your second number "
number_2 = gets.chomp.to_i
case operation
when "+"
puts number_1 + number_2
when "-"
puts number_1 - number_2
when "*"
puts number_1 * number_2
when "/"
puts number_1 / number_2
else
puts "You have not typed a valid operator, please run the program again."
end
end
# again
calculate
| true
|
1e67080a6003b229ab8a264bb917f8e7b258c573
|
Ruby
|
Joseph-Burke/Icebreaker
|
/lib/program.rb
|
UTF-8
| 2,316
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
require 'nokogiri'
require 'open-uri'
require_relative '../lib/string'
require_relative '../lib/webpage'
require_relative '../lib/printable'
class Program
include Printable
attr_accessor :current_page, :active
def initialize
@current_page = nil
@active = true
end
def display_content
page = current_page
content = page.content
type = page.type_of_page
case type
when :search
content.map(&:inner_text)
when :artist
arr = []
content.each do |key, value|
arr.push("\n")
arr.push(key)
arr.push("\n")
value.each { |element| arr.push(element.inner_text) }
arr.push("\n")
end
arr
when :lyrics
title = "\n" << current_page.content[:lyrics_title] << "\n"
content[:lyrics_text].unshift(title)
end
end
def process_input(input)
page_type = @current_page.type_of_page if @current_page
process_search_terms(input) if page_type.nil?
process_link_selection(input) if %i[search artist].include?(page_type)
process_onward_path(input) if page_type == :lyrics
end
private
def follow_link(string_input)
input = string_input.clean
current_page.links.each do |key, val|
song_title = key.clean
if input == song_title
change_page(val)
break
end
end
end
def change_page(web_address)
@current_page = WebPage.new(web_address)
end
def go_to_search_page(search_terms_arr)
new_address = WebPage::TYPES[:search][:prefix]
new_address += search_terms_arr.join('+')
change_page(new_address)
end
def return_to_artist_page
return unless current_page.type_of_page == :lyrics
artist_page_anchor = current_page.nokogiri.css('.col-xs-12 > .lyricsh > h2 > a')[0]
artist_web_address = artist_page_anchor['href'].prepend('https:')
change_page(artist_web_address)
end
def process_search_terms(input)
go_to_search_page(input.make_search_term_array)
end
def process_link_selection(input)
follow_link(input)
end
def process_onward_path(input)
input = input.clean.to_i
valid = [1, 2, 3]
return unless valid.include?(input)
case input
when 1
@current_page = nil
when 2
return_to_artist_page
when 3
self.active = false
end
end
end
| true
|
1cd0a7915db067255019cc759190886fad95e30b
|
Ruby
|
damianp63/kolejka_ruby
|
/queue.rb
|
UTF-8
| 1,135
| 3.28125
| 3
|
[] |
no_license
|
#require 'rspec/autorun'
class Queue
def initialize(tab=[])
@table=tab
end
def push(object)
@table.push(object)
end
def pop
@table.pop(@table.size-1)
end
def size
@table.size
end
def to_s
@table
end
def process(activity)
@table.each do |i|
i.activity
end
end
end
source_queue = Queue.new([1,2,3])
target_queue = Queue.new
target_queue.push(source_queue.pop)
print target_queue.to_s
=begin
describe Queue do
describe "#push" do
it "dodaje element na koniec kolejki" do
obj=Queue.new([])
obj.push(5)
expect(obj.to_s).to eq([5])
obj.push(4)
obj.push(1233)
expect(obj.to_s).to eq([5,4,1233])
end
end
describe "#pop" do
it "usuwa pierwszy element z kolejki" do
obj=Queue.new([2])
obj.push(54)
obj.pop
expect(obj.to_s).to eq([54])
end
end
describe "#size" do
it "podaje rozmiar kolejki" do
obj=Queue.new([2])
obj.push(54)
expect(obj.size).to eq(2)
obj.push(8475)
expect(obj.size).to eq(3)
obj.pop
expect(obj.size).to eq(2)
end
end
end
=end
| true
|
7abccb61b432783119e908a88a54f5d032861ab6
|
Ruby
|
Mancini1/coursework
|
/w01d02/classes/bananashop.rb
|
UTF-8
| 586
| 2.9375
| 3
|
[] |
no_license
|
class BananaShop
attr_accessor :name, :opened_in, :staff
attr_reader :current_balance
def initialize name, opened_in
@name = name
@opened_in = opened_in
@staff = []
@current_balance = 0.0
end
def buy_banana
@current_balance = @current_balance + 0.10
end
# set name
# def set_name new_name
# @name = new_name
# end
# # get name
# def get_name
# @name
# end
# def name
# "Mancini Banana Shop"
# end
# def set_opened_in new data
# @opened_in = new_data
# end
# def get_opened_in
# @opened_in
# end
# def opened_in
# "2016"
# end
end
| true
|
3dc010c29b71e1c399dd85be7879a83eb844f511
|
Ruby
|
taggartj1985/Cinema
|
/models/screening.rb
|
UTF-8
| 1,726
| 3.25
| 3
|
[] |
no_license
|
#new class will need CRUD will need time and film_id also may need tickets! starting tickets
# with zero tickets sold and maybe a capcity limit.
# don't forget to add it into sql as a table will need to drop before films
# if its using its ID. IF you get screening done can add snacks as new table/class
require_relative("../db/sql_runner")
require_relative("films")
require_relative("tickets")
class Screening
attr_reader :id
attr_accessor :times, :film_id
def initialize(options)
@id = options['id'].to_i if options['id']
@times = options['times']
@film_id = options['film_id']
# @ticket_id = options['film_id']
end
def save()
sql = "INSERT INTO screenings (times, film_id) VALUES ($1, $2) RETURNING id"
values = [@times, @film_id]
times = SqlRunner.run(sql, values)[0];
@id = times['id'].to_i
end
def delete()
sql = "DELETE FROM screenings WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def Screening.select_all()
sql = "SELECT * FROM screenings"
times = SqlRunner.run(sql)
return times.map{|time| Screening.new(time)}
end
def Screening.delete_all()
sql = "DELETE FROM screenings"
SqlRunner.run(sql)
end
def update()
sql = "UPDATE screenings SET (times, film_id) = ($1, $2) WHERE id = $3"
values = [@times, @film_id, @id]
SqlRunner.run(sql,values)
end
# write a function that shows the most popular time(most tickets sold) try use
# tickets sold function from the customer class or sql.
# def pop_time()
# sql = "SELECT * FROM tickets WHERE id = $1"
# values = [@id]
# pop_time = SqlRunner.run(sql, values)
# return pop_time.map{|movie|Screening.new(movie)}
# end
end
| true
|
3d41af76ba01716641bfdcbe175abe0812b71317
|
Ruby
|
codewithirene567/debugging-with-pry-onl01-seng-ft-050420
|
/lib/pry_debugging.rb
|
UTF-8
| 53
| 2.890625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def plus_two(num)
num + 2
num
return (num + 2)
end
| true
|
53303e9e8d2b29ebe10b3ea366d6c618d7996d89
|
Ruby
|
AlejandroFrndz/PDOO
|
/Civitas_Ruby/lib/casilla_calle.rb
|
UTF-8
| 981
| 2.65625
| 3
|
[] |
no_license
|
require_relative "titulo_propiedad.rb"
require_relative "sorpresa.rb"
require_relative "mazo_sorpresas"
module Civitas
class Casilla_Calle < Casilla
attr_reader :tituloPropiedad
def initialize (titulo)
super(titulo.nombre)
@tituloPropiedad = titulo
@importe = titulo.precioCompra
end
def recibeJugador(actual, todos)
if(jugadorCorrecto(actual,todos))
informe(actual,todos)
jugador = Jugador.new(todos[actual])
if(!@tituloPropiedad.tienePropietario)
jugador.puedeComprarCasilla
else
@tituloPropiedad.tramitarAlquiler(todos[actual])
end
end
end
def to_s()
cadena = "#{@nombre} Precio: #{@importe}"
return cadena
end
def informe(actual, todos)
if(jugadorCorrecto(actual,todos))
Diario.instance.ocurre_evento(todos[actual].nombre.to_s + " ha caido en la casilla " + to_s)
end
end
end
end
| true
|
d051e49903e63b9a5aa23d32985dd385e97979e4
|
Ruby
|
UltimateCoder00/Codility-Challenges
|
/spec/Lesson 4 Counting Elements/MissingInteger/missing_integer_spec.rb
|
UTF-8
| 2,908
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
require "./lib/Lesson 4 Counting Elements/MissingInteger/missing_integer"
describe 'MissingInteger' do
describe 'Example Tests' do
it 'example (without minus) - [1, 3, 6, 4, 1, 2] to 5' do
expect(missing_integer([1, 3, 6, 4, 1, 2])).to eq 5
end
end
describe 'Correctness Tests' do
context 'extreme_single' do
it 'a single element' do
expect(missing_integer([0])).to eq 1
expect(missing_integer([-1])).to eq 1
expect(missing_integer([1])).to eq 2
expect(missing_integer([-2147483647])).to eq 1
expect(missing_integer([2147483647])).to eq 1
end
end
context 'simple' do
it 'simple test' do
array = [2]
expect(missing_integer(array)).to eq 1
array = [1, 1, 3]
expect(missing_integer(array)).to eq 2
array = [3, 4, 2, 7]
expect(missing_integer(array)).to eq 1
array = [3, 1, 2, 5, 6]
expect(missing_integer(array)).to eq 4
end
end
context 'extreme_min_max_int' do
it 'MININT and MAXINT (with minus)' do
array = Array.new(1000) { rand(-1000..1000) }
array << -2147483647
array << 2147483647
array.shuffle
expect(missing_integer(array)).to be_a Integer
end
end
context 'positive_only' do
it 'shuffled sequence of 0...100 and then 102...200' do
array = [*0..100, *102..200]
array.shuffle
expect(missing_integer(array)).to eq 101
end
end
context 'negative_only' do
it 'shuffled sequence -100 ... -1' do
array = [*-100..-1]
array.shuffle
expect(missing_integer(array)).to eq 1
end
end
end
describe 'Performance Tests' do
context 'medium' do
it 'chaotic sequences length=10005 (with minus)' do
array = Array.new(10005) { rand(-100000..100000) }
array.shuffle
expect(missing_integer(array)).to be_a Integer
end
end
context 'large_1' do
it 'chaotic + sequence 1, 2, ..., 40000 (without minus)' do
array1 = Array.new(50000) { rand(0..1000000) }
array2 = [*1..40000]
array = array1 + array2
array.shuffle
expect(missing_integer(array)).to be_a Integer
end
end
context 'large_2' do
it 'shuffled sequence 1, 2, ..., 100000 (without minus)' do
array1 = Array.new(50000) { rand(0..1000000) }
array2 = [*1..100000]
array = array1 + array2
array.shuffle
expect(missing_integer(array)).to be_a Integer
end
end
context 'large_3' do
it 'chaotic + many -1, 1, 2, 3 (with minus)' do
array1 = Array.new(100000) { rand(-2147483647..2147483647) }
array2 = [-1, 1, 2, 3]*rand(1000)
array = array1 + array2
array.shuffle
expect(missing_integer(array)).to be_a Integer
end
end
end
end
| true
|
bdffae801672d0e3bc6299ae38ee5dd50c8cddbc
|
Ruby
|
BenRKarl/WDI_work
|
/w03/d03/Rebecca_Strong/morning/caws/app.rb
|
UTF-8
| 1,076
| 2.59375
| 3
|
[] |
no_license
|
require 'bundler'
Bundler.require
require_relative 'models/user'
require_relative 'models/caw'
require_relative 'config.rb'
#index
get '/' do
@users = User.all
erb :index
end
# new
get '/users' do
@users = User.all
erb :index
end
get '/users/new' do
erb :'users/new'
end
#create
post'/users' do
username = params[:username]
new_user = User.create({username: username})
redirect "/users/#{new_user.id }"
end
#show
get '/users/:id' do
@user = User.find(params[:id])
erb :'users/show'
end
# show
get'/users/:id/caws/new' do
# @user_id = params[:id]
@user = User.find(params[:id])
erb :'caws/new'
end
#CREATE
post '/users:id/caws' do
user = User.find(params[:id])
message = params[:message]
new_caw = Caw.create({message: message})
user.caws << new_caw
# above means UPDATE caws SET user_id=#{user.id} WHERE id=#{new_caw.id}
redirect "/users/#{params[:id]}"
end
#DELETE
delete '/users/:user_id/caws/:caw_id' do
Caw_id = params[:caw_id]
Caw.delete(caw_id)
redirect "/users/#{params[:user_id]}"
end
get '/console' do
binding.pry
end
| true
|
26e88cab0106aed7b7119d1eef3af74d4102e61d
|
Ruby
|
jordanpoulton/ruby_kickstart
|
/session2/1-notes/18-class-instance-variables.rb
|
UTF-8
| 1,264
| 4.1875
| 4
|
[
"MIT"
] |
permissive
|
# Lets say we wanted to know what planet people are from.
# Well, that information is the same across every person
# so we can keep it in an instance variable on the class.
class Person
# When we define methods here, they get defined for
# instances of Person, so we need to either store
# them in Person's class or singleton class. It doesn't
# make sense to give EVERY class a home_planet, so
# lets put it on the singleton_class
self # => Person
class << self
attr_accessor 'home_planet'
end
# remember, self is Person, so @home_planet
# is defined on the Person class itself
@home_planet = 'Erth'
Person.home_planet # => "Erth"
Person.home_planet = 'Earth'
@home_planet # => "Earth"
attr_accessor 'name'
def initialize(name)
# self is now an instance of person, so @name
# is defined for this particular person
@name = name
end
# This one is for instances
def home_planet
Person.home_planet
end
end
Person.home_planet
kate = Person.new 'Kate Beckinsale'
josh = Person.new 'Josh Cheek'
kate.home_planet # => "Earth"
josh.home_planet # => "Earth"
kate.name # => "Kate Beckinsale"
josh.name # => "Josh Cheek"
Person.instance_variables # => [:@home_planet]
josh.instance_variables # => [:@name]
| true
|
e3edded5ee94d9f3ae1554e1f614d40f36e98565
|
Ruby
|
itggot-ida-franzen-karlsson/standard-biblioteket
|
/lib/is_negative.rb
|
UTF-8
| 164
| 3.15625
| 3
|
[] |
no_license
|
# tar ett heltal som input och avgör om talet är negativt
def is_negative(n)
is_neg = false
if n < 0
is_neg = true
end
return is_neg
end
| true
|
2b26a369952f0bef22762f56964d3d57fb3d6d7b
|
Ruby
|
kkuivenhoven/kjvVerseCount
|
/lib/verse_count.rb
|
UTF-8
| 1,396
| 3.453125
| 3
|
[] |
no_license
|
require 'csv'
require 'open-uri'
class KjvVerseCount
@wholeBible = Hash.new
def initialize(name, chapter, verseTotal)
@name = name
@chapter = chapter
@verseTotal = verseTotal
end
def self.init
puts "inside init"
@wholeBible = Hash.new
CSV.new(open("https://raw.githubusercontent.com/kkuivenhoven/kjvVerseCount/master/lib/kjvVerseCount.csv")).each do |bookChapterLine|
if @wholeBible.has_key?(bookChapterLine[0])
tmpHash = { bookChapterLine[1] => bookChapterLine[2] }
@wholeBible[bookChapterLine[0]] << tmpHash
else
@wholeBible[bookChapterLine[0]] = Hash.new
@wholeBible[bookChapterLine[0]] = []
tmpHash = { bookChapterLine[1] => bookChapterLine[2] }
@wholeBible[bookChapterLine[0]] << tmpHash
end
end
end
def self.getBooksOfBible
return @wholeBible.keys
end
def self.getNumberOfChapters(bookTitle)
return @wholeBible[bookTitle].last.keys
end
def self.getVerseCountForChapter(bookTitle, chapNum)
@wholeBible[bookTitle].each do |chapVerse|
if chapVerse.keys.first.to_i == chapNum
return chapVerse.values.first
end
end
end
def self.getTotalBookVerseCount
@allChapters = Hash.new
@wholeBible.each do |wb|
@allChapters[wb[0]] = {}
wb[1].each do |chapterVerseArray|
@allChapters[wb[0]].merge!(chapterVerseArray.keys.first => chapterVerseArray.values.first)
end
end
return @allChapters
end
end
| true
|
d8bafef7ce90652974b766a72627de298f571054
|
Ruby
|
Apollo50/testGuru
|
/app/services/badge_service.rb
|
UTF-8
| 1,415
| 2.53125
| 3
|
[] |
no_license
|
class BadgeService
def initialize(test_passage)
@test_passage = test_passage
end
def check_rule
return unless Badge.exists?
Badge.all.each do |badge|
add_badge_to_user(badge) if self.send("#{badge.rule_name}_rule", badge)
end
end
private
def add_badge_to_user(badge)
@test_passage.user.badges << badge
@test_passage.badges << badge
end
def first_passing_rule(options={})
(UsersPassedTest.
where(user_id: @test_passage.user_id).
where(completed: true).
where(test_id: @test_passage.test_id).count == 1)
end
def all_levels_rule(badge)
tests_ids= Test.test_by_level(@test_passage.test.level).pluck(:id)
return passed_tests_count(tests_ids, badge)
end
def all_categories_rule(badge)
tests_ids= Test.test_by_category(@test_passage.test.category.title).pluck(:id)
return passed_tests_count(tests_ids, badge)
end
def passed_tests_count(tests_ids, badge)
tests_count = tests_ids.count
tests_count_confirm = UsersPassedTest.
where(test_id: tests_ids, user_id: @test_passage.user.id, completed: true).
distinct.pluck(:test_id).count
return true if tests_count == tests_count_confirm && badge_been_gotten?(badge, tests_ids)
end
def badge_been_gotten?(badge, test_ids)
!badge.users_passed_tests.where(test_id: test_ids).any?
end
end
| true
|
f0f6be7e4ad631c80624fb39afdac4bac86ac813
|
Ruby
|
dunphyben/to-do-list-refactored
|
/lib/to_do_lists.rb
|
UTF-8
| 3,169
| 3.734375
| 4
|
[] |
no_license
|
require './lib/to_do'
require './lib/list_class'
def main_menu
puts "\nPress 'n' to create a new list"
puts "Press 'v' to view all of your to-do lists"
puts "Press 'ex' to exit"
main_choice = gets.chomp
if main_choice == 'n'
new_list
elsif main_choice == 'v'
view_lists
elsif main_choice == 'ex'
puts "Bye!"
else
puts "Sorry, that wasn't a valid options."
main_menu
end
end
def new_list
puts "Enter your list name:"
list_name = gets.chomp
new_list = List.create(list_name)
puts "\nList was added successfully. Yay!\n\n"
puts "Press 'y' to add tasks now. Press 'm' for main menu\n\n"
task_choice = gets.chomp
if task_choice == "y"
add_task(new_list)
elsif task_choice == "m"
main_menu
else
puts "\n\nDude whatchu tryin to do? Das not valid.\n\n"
new_list
end
main_menu
end
def view_lists
puts "Here are all your dumb lists:"
# puts "#{List.list_name}"
# list.tasks.each_with_index do |task, index|
# puts "#{index+1}: #{task.description}"
# end
List.all.each_with_index do |list, index|
puts "#{index + 1}. #{list}"
Task.all.each_with_index do |task, index|
puts "#{index + 1}. #{task.description}\n"
end
end
# List.all.each_with_index do |list, index|
# puts "\n" + "\n\n#{index + 1}. #{list.list_name}\n" + "----------------------\n"
# Task.all.each_with_index do |task, index|
# puts "#{index+1}: #{task.description}\n\n"
# break
# puts "hi, I will be a task someday"
# end
# end
# puts "Enter the number of the list you wish to add tasks"
# selected_list = gets.chomp
# List.all[selected_list - 1].marked_list
end
def sub_menu
puts "Press 'a' to add a task, 'l' to list all of your tasks, or 'd' to mark task done."
puts "Press 'x' to exit."
main_choice = gets.chomp
case main_choice
when 'a'
add_task
when 'l'
list_tasks
when 'd'
delete_task
when 'x'
puts "Good-bye!"
else
puts "Sorry, that wasn't a valid option."
main_menu
end
end
def add_task(list)
puts "\nEnter a description of the new task:"
user_description = gets.chomp
list.add_task(user_description)
puts "Task added.\n\n"
puts "#{list.list_name}"
list.tasks.each_with_index do |task, index|
puts "#{index+1}: #{task.description}\n\n"
end
puts "What else you got? New task enter 'y' - back to main menu enter 'n'."
user_input = gets.chomp
case user_input
when 'y'
add_task(list)
when 'n'
main_menu
# break
end
end
# def list_tasks
# puts "Here are all of your tasks:"
# Task.all.each_with_index do |task, index|
# puts "#{index + 1}. #{task.description}\n"
# end
# puts "\n"
# main_menu
# end
def delete_task
puts "Which task would you like to delete? \n"
Task.all.each_with_index do |task, index|
puts "#{index + 1}. #{task.description}\n"
end
task_to_delete = gets.chomp.to_i
Task.all[task_to_delete - 1].marked_done
Task.all.delete(Task.all[task_to_delete - 1])
puts "\n\nTask #{task_to_delete} has been deleted.\n\n"
main_menu
end
# def completed_tasks
# puts "hello"
# end
main_menu
| true
|
19be116c5e46162e1cedba50a0a4cec35a348798
|
Ruby
|
frsyuki/fluentd11-old-very-old
|
/lib/fluentd/config/element.rb
|
UTF-8
| 3,245
| 2.53125
| 3
|
[] |
no_license
|
#
# Fluentd
#
# Copyright (C) 2011-2013 FURUHASHI Sadayuki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Fluentd
module Config
class Element < Hash
def initialize(name, arg, attrs, elements, used=[])
@name = name
@arg = arg
@elements = elements
super()
attrs.each {|k,v|
self[k] = v
}
@used = used
end
attr_accessor :name, :arg, :elements, :used
def new_element(name, arg)
e = clone # clone copies singleton methods
e.instance_eval do
clear
@name = name
@arg = arg
@elements = []
@used = []
end
e
end
def add_element(name, arg='')
e = Element.new(name, arg, {}, [])
@elements << e
e
end
def +(o)
Element.new(@name.dup, @arg.dup, o.merge(self), @elements+o.elements, @used+o.used)
end
def each_element(*names, &block)
if names.empty?
@elements.each(&block)
else
@elements.each {|e|
if names.include?(e.name)
block.yield(e)
end
}
end
end
def has_key?(key)
@used << key
super
end
def [](key)
@used << key
super
end
def check_not_used(&block)
each_key {|key|
unless @used.include?(key)
block.call(key, self)
end
}
@elements.each {|e|
e.check_not_used(&block)
}
end
def to_s(nest=0)
unless nest
disable_recursive = true
nest = 0
end
indent = " "*nest
nindent = " "*(nest+1)
out = ""
if @arg.empty?
out << "#{indent}<#{@name}>\n"
else
out << "#{indent}<#{@name} #{@arg}>\n"
end
each_pair {|k,v|
a = LiteralParser.nonquoted_string?(k) ? k : {"_"=>k}.to_json[5..-2]
#b = LiteralParser.nonquoted_string?(v) ? v : {"_"=>v}.to_json[5..-2]
b = {"_"=>v}.to_json[5..-2]
out << "#{nindent}#{a} #{b}\n"
}
if disable_recursive
unless @elements.empty?
out << "#{nindent}...\n"
end
else
@elements.each {|e|
out << e.to_s(nest+1)
}
end
out << "#{indent}</#{@name}>\n"
out
end
def inspect
to_s
end
end
def self.read(path)
Parser.read(path)
end
def self.parse(str, fname, basepath=Dir.pwd)
Parser.parse(str, fname, basepath)
end
def self.new(name='')
Element.new('', '', {}, [])
end
end
end
| true
|
fce85a6241761327cdfca74435015b90f14cac06
|
Ruby
|
shamsbhuiyan/topfind4
|
/topfind4.1/app/models/graph/mapMouseHuman.rb
|
UTF-8
| 603
| 3.375
| 3
|
[] |
no_license
|
#
class MapMouseHuman
def initialize()
@map = []
File.open("databases/paranoid8_many2many.txt").readlines.each do |line|
l = line.split("\t")
@map << {:h => l[0].strip(), :m => l[1].strip()}
end
end
def mouse4human(proteins)
return proteins.collect{|p| m4h(p)}.flatten
end
def human4mouse(proteins)
return proteins.collect{|p| h4m(p)}.flatten
end
def m4h(prot)
return @map.find_all{|hash| hash[:h] == prot}.collect{|x| x[:m]}
end
def h4m(prot)
return @map.find_all{|hash| hash[:m] == prot}.collect{|x| x[:h]}
end
end
| true
|
91eecce3d7ddd6013f7cdd773389b61a2a15799c
|
Ruby
|
plkujaw/makers-bnb
|
/lib/booking_received.rb
|
UTF-8
| 1,814
| 2.78125
| 3
|
[] |
no_license
|
class BookingReceived
def self.all(owner_id)
@bookings_received = ActiveRecord::Base.connection.execute("SELECT s.name, s.price, s.description, s.street_address, s.city, s.country, s.postcode, b.id booking_id, b.confirmation, b.booking_start, b.booking_end FROM spaces s INNER JOIN bookings b ON s.id = b.space_id WHERE s.owner_id = #{owner_id}")
@bookings_received.map do |request|
# p request
BookingReceived.new(
space_name: request['name'],
space_price: request['price'],
space_description: request['description'],
space_street_address: request['address'],
space_city: request['city'],
space_country: request['country'],
space_post_code: request['postcode'],
booking_confirmation: request['confirmation'],
booking_start_date: request['booking_start'],
booking_end_date: request['booking_end'],
booking_id: request['booking_id']
)
end
end
attr_reader :space_name, :space_price, :space_description, :space_street_address, :space_city, :space_country, :space_post_code, :booking_confirmation, :booking_start_date, :booking_end_date, :booking_id
def initialize(space_name:, space_price:, space_description:, space_street_address:, space_city:, space_country:, space_post_code:, booking_confirmation:, booking_start_date:, booking_end_date:, booking_id:)
@space_name = space_name
@space_price = space_price
@space_description = space_description
@space_street_address = space_street_address
@space_city = space_city
@space_country = space_country
@space_post_code = space_post_code
@booking_confirmation = booking_confirmation
@booking_start_date = booking_start_date
@booking_end_date = booking_end_date
@booking_id = booking_id
end
end
| true
|
d8d790815bf9cfec1c4422001cae1a8ed5545cc9
|
Ruby
|
nBobrov/education_ror
|
/Lesson_3/accessors.rb
|
UTF-8
| 1,315
| 3.09375
| 3
|
[] |
no_license
|
module Accessors
def attr_accessor_with_history(*attr_names)
attr_names.each do |attr_name|
add_attr_getter(attr_name)
add_attr_setter(attr_name)
end
end
def strong_attr_accessor(attr_name, attr_class)
add_attr_getter(attr_name)
add_attr_setter_strong(attr_name, attr_class)
end
private
def add_attr_getter(attr_name)
self.class.class_eval do
define_method(attr_name) { instance_variable_get("@#{attr_name}") }
end
end
def add_attr_setter(attr_name)
attr_name_history = "#{attr_name}_history"
instance_variable_set("@#{attr_name_history}", [])
self.class.class_eval do
define_method("#{attr_name}=") do |value|
instance_variable_get("@#{attr_name_history}").push(value)
instance_variable_set("@#{attr_name}", value)
end
define_method(attr_name_history) { instance_variable_get("@#{attr_name_history}") }
end
end
def add_attr_setter_strong(attr_name, attr_class)
self.class.class_eval do
define_method("#{attr_name}=") do |value|
raise ArgumentError, 'Тип переменной отличается от типа присваемого значения!' unless value.instance_of?(attr_class)
instance_variable_set("@#{attr_name}", value)
end
end
end
end
| true
|
975f8f64df90b1be2d2edfd55ec6384861fbc743
|
Ruby
|
hector2-cloud/my-collect-onl01-seng-pt-012220
|
/lib/my_collect.rb
|
UTF-8
| 119
| 3.171875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def my_collect(array)
new_array=[]
i=0
while i<array.length
new_array.push(yield array[i])
i += 1
end
new_array
end
| true
|
bacf00abe5f4ef24d483f3120df175493d6ea082
|
Ruby
|
koziscool/Ruby-E83
|
/e83.rb
|
UTF-8
| 1,882
| 3.359375
| 3
|
[] |
no_license
|
require './e83_data.rb'
require './graph.rb'
VertexInfo = Struct.new( :key, :min_path_weight, :min_path, :weight ) do
def to_s
"key: #{key} weight: #{weight} min path weight: #{min_path_weight}"
end
def min_path_string
ret_string = "[ "
min_path.each do | point |
ret_string = ret_string + "#{point} "
end
ret_string = ret_string + " ]"
ret_string
end
end
class PathFinder
SOME_BIG_NUMBER = 10000000000
def initialize( graph, origin_key, terminal_key )
@graph = graph
@our_vertex_hash = {}
build_vertex_info
@origin = @our_vertex_hash[ origin_key ]
@origin.min_path_weight = @origin.weight
@improved_path_nodes = [ origin_key ]
@terminal = @our_vertex_hash[ terminal_key ]
end
def build_vertex_info
@graph.nodes.each do |key, node|
v_info = VertexInfo.new( node.key, SOME_BIG_NUMBER, [], node.weight )
@our_vertex_hash[ node.key ] = v_info
end
end
def find_min_path
until @improved_path_nodes.empty?
main_loop
end
puts @terminal.min_path_string
puts @terminal.min_path_string.length
@terminal.min_path_weight
end
def main_loop
updates = []
@improved_path_nodes.each do | node_key |
node = @our_vertex_hash[ node_key ]
node_neighbors = @graph.nodes[ node_key ].neighbors
node_neighbors.each do | neighbor_key |
neighbor = @our_vertex_hash[ neighbor_key ]
new_path_weight = node.min_path_weight + neighbor.weight
if new_path_weight < neighbor.min_path_weight
neighbor.min_path_weight = new_path_weight
neighbor.min_path = node.min_path + [ neighbor.weight ]
updates << neighbor_key
end
end
end
@improved_path_nodes = updates
end
end
g = EulerGraph.new( )
pf = PathFinder.new( g, g.origin.key, g.terminal.key )
puts pf.find_min_path
| true
|
6d99fc92595d92db5c736aa2f9cdbca27f5c484f
|
Ruby
|
Atar97/aA-Alpha-Course-completed
|
/Austin_Cotant_rspec/lib/02_calculator.rb
|
UTF-8
| 337
| 3.734375
| 4
|
[] |
no_license
|
def add(num1, num2)
num1 + num2
end
def subtract(num1, num2)
num1-num2
end
def sum(arr)
ans = 0
arr.each {|el| ans += el}
ans
end
def multiply(num1, num2)
num1*num2
end
def power(num1, num2)
num1**num2
end
def factorial(num)
if num < 1
return 0
end
answer = 1
(1..num).each {|el| answer*=el }
answer
end
| true
|
af70f25f28c98f6f583b4a6673d466002846fd74
|
Ruby
|
matpa/ttt-6-position-taken-rb-q-000
|
/lib/position_taken.rb
|
UTF-8
| 306
| 3.65625
| 4
|
[] |
no_license
|
# code your #position_taken? method here!
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def position_taken?(board, int)
if (board[int]==" ") || (board[int]=="")
return false
elsif (board[int]=="X") || (board[int]=="O")
return true
elsif (board[int]==nil)
return false
end
end
| true
|
44dfcc408b8f8e43d04ee9b8b1718a81fb2a7000
|
Ruby
|
jcald/dojo
|
/string_calculator/ruby/lib/string_calculator.rb
|
UTF-8
| 589
| 3.34375
| 3
|
[] |
no_license
|
class StringCalculator
def self.add(str)
params = StringParams.new(str)
params.scan_delimiter!
params.sum_delimited
end
private
class StringParams
def initialize(params)
@params = params
@delimiters = ",\n"
end
def scan_delimiter!
if delimiter = @params[/\[(.*?)\]/, 1]
@delimiters << delimiter
@params.sub!("//[#{delimiter}]", "")
end
end
def sum_delimited
delimited.map(&:to_i).reduce(&:+)
end
private
def delimited
@params.split(/[#{@delimiters}]/)
end
end
end
| true
|
731cdf4e172de5585ed4468c4db39f6d26348926
|
Ruby
|
AndriyK/timer
|
/app/helpers/works_helper.rb
|
UTF-8
| 2,000
| 3.25
| 3
|
[] |
no_license
|
module WorksHelper
include RoutinesHelper
# Function return the amount of days in defined month
#
# * *Args* :
# - +date+ date object-> date for which month amount of days is required
# * *Returns* :
# integer amount of days in month
def get_days_in_month date
months = { 1=>31, 2=>(Date.leap?(date.year) ? 29 :28), 3=>31, 4=>30, 5=>31, 6=>30, 7=>31, 8=>31, 9=>30, 10=>31, 11=>30, 12=>31}
months[date.mon]
end
# Function extract time part from date
#
# * *Args* :
# - +date+ date object-> current date
# * *Returns* :
# string representation of the time = "9:00"
def get_time_part date
date.strftime("%k:%M")
end
# Function humanize duration of the work for the report
#
# * *Args* :
# - +duration+ integer-> amount of minutes spent for work
# * *Returns* :
# string representation of the spent time = "1 h 20 min"
def humanize_duration duration
if duration < 60
return duration.to_s + ' min'
else
hour = duration/60
min = duration - 60*hour
return hour.to_s + ' h ' + (( min > 0 ) ? (min.to_s + ' min') : '')
end
end
# Function return the date for previous day of provided date
#
# * *Args* :
# - +date+ date object-> current date
# * *Returns* :
# string representation of date = "2012-06-12"
def day_before( date )
(date - 1.day).strftime("%Y-%m-%d")
end
# Function return the date for next day of provided date
#
# * *Args* :
# - +date+ date object-> current date
# * *Returns* :
# string representation of date = "2012-06-12"
def day_after( date )
(date + 1.day).strftime("%Y-%m-%d")
end
# Function return the name for cell of the time line builded from date (time is used)
#
# * *Args* :
# - +date+ date object-> current date
# * *Returns* :
# integer value (amount of minuted from midnight, for time 1:20 it would be 80)
def get_name_for_timeline date
date.hour*60 + date.min
end
end
| true
|
2052bc302dfc65ea824d67f1d04ead50d64b86cb
|
Ruby
|
telegramstudio/mvc-parser
|
/app.rb
|
UTF-8
| 450
| 2.546875
| 3
|
[] |
no_license
|
require 'nokogiri'
require 'open-uri'
require 'net/https'
res = ''
# Fetch and parse HTML document
doc = Nokogiri::HTML(open('https://www.avito.ru/ussuriysk/bytovaya_elektronika?p=1', :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))
doc.css('h3.item-description-title a').each do |link|
link = 'https://www.avito.ru' + link.attributes["href"].value
res += link
end
File.open('result.txt', 'w') { |file| file.write(res) }
| true
|
e0dde698d20d76e04f4dbb040c3120d8ecd2e42c
|
Ruby
|
datu925/rulecoder
|
/rulecoder.rb
|
UTF-8
| 1,940
| 3.28125
| 3
|
[] |
no_license
|
#rulecoder
#rule file looks like this:
#target fields, target phrase, outcome label, outcome column, active status
#financial data looks like this:
#some number of data columns with descriptions of the transaction, a transaction amount in final column
#for each line in data,
#for each rule in file,
#skip if rule is not active
#concatenate fields that are identified by an array with column names
#if concatenate contains the target string, put outcome label in outcome column
require 'csv'
def get_headers(file_name)
#get headers from our file
headers = []
File.open(file_name) do |x|
headers = CSV.parse(x.readline).flatten
end
#add the coding columns
return headers
end
def read_line_to_array(line)
read_line = line.inject([]) do |array, index|
array << index[1]
end
read_line += ["Uncoded","Uncoded"]
return read_line
end
header_line = get_headers('example_data.csv')
header_line += ["Position Type", "Function Type"]
CSV.open('new_file.csv','w') do |csv|
csv << header_line
#read rule line-by-line
CSV.foreach('example_data.csv', headers:true) do |line|
line_array = read_line_to_array(line)
CSV.foreach('example_rules.csv', headers:true) do |rule|
#skip if inactive
next if rule['Rule Active?'] == "No"
#determine the valid column #s to search in for the rule
valid_columns = rule["Target Columns"].split(",")
#test each cell in each valid column to see if it contains our target string; if so, let's make the change
phrase_in_data = false
valid_columns.each do |index|
cell = line[index.to_i]
cell = "" if cell.nil?
if cell.downcase.include? rule["Target Phrase"].downcase
#phrase_in_data
index_num = header_line.index(rule["Outcome Column"])
line_array[index_num] = rule["Outcome Label"]
break
end
end
end
csv << line_array
end
end
| true
|
2e205b30d532f87cfebf9a9193f1e552fe362911
|
Ruby
|
jlblcc/mdTranslator
|
/lib/adiwg/mdtranslator/writers/iso19115_2/classes/class_polygon.rb
|
UTF-8
| 4,516
| 2.515625
| 3
|
[
"Unlicense"
] |
permissive
|
# ISO <<Class>> Polygon
# writer output in XML
# History:
# Stan Smith 2013-11-18 original script.
# Stan Smith 2014-05-30 modified for version 0.5.0
# Stan Smith 2014-07-08 modify require statements to function in RubyGem structure
# Stan Smith 2014-12-12 refactored to handle namespacing readers and writers
# Stan Smith 2015-06-22 replace global ($response) with passed in object (responseObj)
# Stan Smith 2015-07-14 refactored to make iso19110 independent of iso19115_2 classes
# Stan Smith 2015-07-14 refactored to eliminate namespace globals $WriterNS and $IsoNS
# Stan Smith 2015-07-16 moved module_coordinates from mdJson reader to internal
module ADIWG
module Mdtranslator
module Writers
module Iso19115_2
class Polygon
def initialize(xml, responseObj)
@xml = xml
@responseObj = responseObj
end
def writeXML(hGeoElement)
# gml:Polygon attributes
attributes = {}
# gml:Polygon attributes - gml:id - required
lineID = hGeoElement[:elementId]
if lineID.nil?
@responseObj[:writerMissingIdCount] = @responseObj[:writerMissingIdCount].succ
lineID = 'polygon' + @responseObj[:writerMissingIdCount]
end
attributes['gml:id'] = lineID
# gml:Polygon attributes - srsDimension
s = hGeoElement[:elementGeometry][:dimension]
if !s.nil?
attributes[:srsDimension] = s
end
# gml:Polygon attributes - srsName
s = hGeoElement[:elementSrs][:srsName]
if !s.nil?
attributes[:srsName] = s
end
@xml.tag!('gml:Polygon', attributes) do
# polygon - description
s = hGeoElement[:elementDescription]
if !s.nil?
@xml.tag!('gml:description', s)
elsif @responseObj[:writerShowTags]
@xml.tag!('gml:description')
end
# polygon - name
s = hGeoElement[:elementName]
if !s.nil?
@xml.tag!('gml:name', s)
elsif @responseObj[:writerShowTags]
@xml.tag!('gml:name')
end
# polygon - exterior ring
# convert coordinate string from geoJSON to gml
aCoords = hGeoElement[:elementGeometry][:geometry][:exteriorRing]
if !aCoords.empty?
s = AdiwgCoordinates.unpack(aCoords, @responseObj)
@xml.tag!('gml:exterior') do
@xml.tag!('gml:LinearRing') do
@xml.tag!('gml:coordinates', s)
end
end
else
@xml.tag!('gml:exterior')
end
# polygon - interior ring
# convert coordinate string from geoJSON to gml
# XSDs do not all gml:interior to be displayed empty
aRings = hGeoElement[:elementGeometry][:geometry][:exclusionRings]
unless aRings.empty?
aRings.each do |aRing|
s = AdiwgCoordinates.unpack(aRing, @responseObj)
@xml.tag!('gml:interior') do
@xml.tag!('gml:LinearRing') do
@xml.tag!('gml:coordinates', s)
end
end
end
end
end
end
end
end
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.