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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e1251dcf1a4533c31dfeced2ccdb60ec21ae1005 | Ruby | scottzero/pantry_1906 | /lib/ingredient.rb | UTF-8 | 162 | 3.4375 | 3 | [] | no_license | class Ingredient
attr_reader :name, :unit, :calories
def initialize(name,unit,calories)
@name = name
@unit = unit
@calories = calories
end
end
| true |
c166b63f95da31340ed8b3e34a786f07656a5035 | Ruby | sparklemotion/http-cookie | /lib/http/cookie_jar.rb | UTF-8 | 9,811 | 3.046875 | 3 | [
"MIT"
] | permissive | # :markup: markdown
require 'http/cookie'
##
# This class is used to manage the Cookies that have been returned from
# any particular website.
class HTTP::CookieJar
class << self
def const_missing(name)
case name.to_s
when /\A([A-Za-z]+)Store\z/
file = 'http/cookie_jar/%s_store' % $1.downcase
when /\A([A-Za-z]+)Saver\z/
file = 'http/cookie_jar/%s_saver' % $1.downcase
end
begin
require file
rescue LoadError
raise NameError, 'can\'t resolve constant %s; failed to load %s' % [name, file]
end
if const_defined?(name)
const_get(name)
else
raise NameError, 'can\'t resolve constant %s after loading %s' % [name, file]
end
end
end
attr_reader :store
def get_impl(base, value, *args)
case value
when base
value
when Symbol
begin
base.implementation(value).new(*args)
rescue IndexError => e
raise ArgumentError, e.message
end
when Class
if base >= value
value.new(*args)
else
raise TypeError, 'not a subclass of %s: %s' % [base, value]
end
else
raise TypeError, 'invalid object: %s' % value.inspect
end
end
private :get_impl
# Generates a new cookie jar.
#
# Available option keywords are as below:
#
# :store
# : The store class that backs this jar. (default: `:hash`)
# A symbol addressing a store class, a store class, or an instance
# of a store class is accepted. Symbols are mapped to store
# classes, like `:hash` to HTTP::CookieJar::HashStore and `:mozilla`
# to HTTP::CookieJar::MozillaStore.
#
# Any options given are passed through to the initializer of the
# specified store class. For example, the `:mozilla`
# (HTTP::CookieJar::MozillaStore) store class requires a `:filename`
# option. See individual store classes for details.
def initialize(options = nil)
opthash = {
:store => :hash,
}
opthash.update(options) if options
@store = get_impl(AbstractStore, opthash[:store], opthash)
end
# The copy constructor. Not all backend store classes support cloning.
def initialize_copy(other)
@store = other.instance_eval { @store.dup }
end
# Adds a cookie to the jar if it is acceptable, and returns self in
# any case. A given cookie must have domain and path attributes
# set, or ArgumentError is raised.
#
# Whether a cookie with the `for_domain` flag on overwrites another
# with the flag off or vice versa depends on the store used. See
# individual store classes for that matter.
#
# ### Compatibility Note for Mechanize::Cookie users
#
# In HTTP::Cookie, each cookie object can store its origin URI
# (cf. #origin). While the origin URI of a cookie can be set
# manually by #origin=, one is typically given in its generation.
# To be more specific, HTTP::Cookie.new takes an `:origin` option
# and HTTP::Cookie.parse takes one via the second argument.
#
# # Mechanize::Cookie
# jar.add(origin, cookie)
# jar.add!(cookie) # no acceptance check is performed
#
# # HTTP::Cookie
# jar.origin = origin
# jar.add(cookie) # acceptance check is performed
def add(cookie)
@store.add(cookie) if
begin
cookie.acceptable?
rescue RuntimeError => e
raise ArgumentError, e.message
end
self
end
alias << add
# Deletes a cookie that has the same name, domain and path as a
# given cookie from the jar and returns self.
#
# How the `for_domain` flag value affects the set of deleted cookies
# depends on the store used. See individual store classes for that
# matter.
def delete(cookie)
@store.delete(cookie)
self
end
# Gets an array of cookies sorted by the path and creation time. If
# `url` is given, only ones that should be sent to the URL/URI are
# selected, with the access time of each of them updated.
def cookies(url = nil)
each(url).sort
end
# Tests if the jar is empty. If `url` is given, tests if there is
# no cookie for the URL.
def empty?(url = nil)
if url
each(url) { return false }
return true
else
@store.empty?
end
end
# Iterates over all cookies that are not expired in no particular
# order.
#
# An optional argument `uri` specifies a URI/URL indicating the
# destination of the cookies being selected. Every cookie yielded
# should be good to send to the given URI,
# i.e. cookie.valid_for_uri?(uri) evaluates to true.
#
# If (and only if) the `uri` option is given, last access time of
# each cookie is updated to the current time.
def each(uri = nil, &block) # :yield: cookie
block_given? or return enum_for(__method__, uri)
if uri
uri = URI(uri)
return self unless URI::HTTP === uri && uri.host
end
@store.each(uri, &block)
self
end
include Enumerable
# Parses a Set-Cookie field value `set_cookie` assuming that it is
# sent from a source URL/URI `origin`, and adds the cookies parsed
# as valid and considered acceptable to the jar. Returns an array
# of cookies that have been added.
#
# If a block is given, it is called for each cookie and the cookie
# is added only if the block returns a true value.
#
# `jar.parse(set_cookie, origin)` is a shorthand for this:
#
# HTTP::Cookie.parse(set_cookie, origin) { |cookie|
# jar.add(cookie)
# }
#
# See HTTP::Cookie.parse for available options.
def parse(set_cookie, origin, options = nil) # :yield: cookie
if block_given?
HTTP::Cookie.parse(set_cookie, origin, options).tap { |cookies|
cookies.select! { |cookie|
yield(cookie) && add(cookie)
}
}
else
HTTP::Cookie.parse(set_cookie, origin, options) { |cookie|
add(cookie)
}
end
end
# call-seq:
# jar.save(filename_or_io, **options)
# jar.save(filename_or_io, format = :yaml, **options)
#
# Saves the cookie jar into a file or an IO in the format specified
# and returns self. If a given object responds to #write it is
# taken as an IO, or taken as a filename otherwise.
#
# Available option keywords are below:
#
# * `:format`
#
# Specifies the format for saving. A saver class, a symbol
# addressing a saver class, or a pre-generated instance of a
# saver class is accepted.
#
# <dl class="rdoc-list note-list">
# <dt>:yaml</dt>
# <dd>YAML structure (default)</dd>
# <dt>:cookiestxt</dt>
# <dd>Mozilla's cookies.txt format</dd>
# </dl>
#
# * `:session`
#
# <dl class="rdoc-list note-list">
# <dt>true</dt>
# <dd>Save session cookies as well.</dd>
# <dt>false</dt>
# <dd>Do not save session cookies. (default)</dd>
# </dl>
#
# All options given are passed through to the underlying cookie
# saver module's constructor.
def save(writable, *options)
opthash = {
:format => :yaml,
:session => false,
}
case options.size
when 0
when 1
case options = options.first
when Symbol
opthash[:format] = options
else
if hash = Hash.try_convert(options)
opthash.update(hash)
end
end
when 2
opthash[:format], options = options
if hash = Hash.try_convert(options)
opthash.update(hash)
end
else
raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size)
end
saver = get_impl(AbstractSaver, opthash[:format], opthash)
if writable.respond_to?(:write)
saver.save(writable, self)
else
File.open(writable, 'w') { |io|
saver.save(io, self)
}
end
self
end
# call-seq:
# jar.load(filename_or_io, **options)
# jar.load(filename_or_io, format = :yaml, **options)
#
# Loads cookies recorded in a file or an IO in the format specified
# into the jar and returns self. If a given object responds to
# \#read it is taken as an IO, or taken as a filename otherwise.
#
# Available option keywords are below:
#
# * `:format`
#
# Specifies the format for loading. A saver class, a symbol
# addressing a saver class, or a pre-generated instance of a
# saver class is accepted.
#
# <dl class="rdoc-list note-list">
# <dt>:yaml</dt>
# <dd>YAML structure (default)</dd>
# <dt>:cookiestxt</dt>
# <dd>Mozilla's cookies.txt format</dd>
# </dl>
#
# All options given are passed through to the underlying cookie
# saver module's constructor.
def load(readable, *options)
opthash = {
:format => :yaml,
:session => false,
}
case options.size
when 0
when 1
case options = options.first
when Symbol
opthash[:format] = options
else
if hash = Hash.try_convert(options)
opthash.update(hash)
end
end
when 2
opthash[:format], options = options
if hash = Hash.try_convert(options)
opthash.update(hash)
end
else
raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size)
end
saver = get_impl(AbstractSaver, opthash[:format], opthash)
if readable.respond_to?(:write)
saver.load(readable, self)
else
File.open(readable, 'r') { |io|
saver.load(io, self)
}
end
self
end
# Clears the cookie jar and returns self.
def clear
@store.clear
self
end
# Removes expired cookies and returns self. If `session` is true,
# all session cookies are removed as well.
def cleanup(session = false)
@store.cleanup session
self
end
end
| true |
19aabd2d12dd476d7499b4d09ba201a0c7c58527 | Ruby | maxnaxmi/Ruby | /variable.rb | UTF-8 | 139 | 3.34375 | 3 | [] | no_license | a = 4
puts a
# aに1足す
a += 1
puts a
# aから1引く
a -= 1
puts a
# aに2かける
a *= 2
puts a
# aを2で割る
a /= 2
puts a | true |
5128795b299f83ccf02ef32c35ce6644cb24b678 | Ruby | itiswhatitisio/rb101 | /small_problems/easy_7/multiply_lists.rb | UTF-8 | 1,020 | 4.53125 | 5 | [] | no_license | =begin
# Problem
# Requirements:
- product of each pair of numbers with the same index
- arguments contain the same number of elements
# Input:
- two arrays
# Output:
- new array
# Examples:
multiply_list([3, 5, 7], [9, 10, 11]) == [27, 50, 77]
# Data structure/Algorithm:
- array
- iterate over the first array
- iterate over the second array
- if the idex of both elements matches, multiply the elements
- add the product to the new array
=end
def multiply_list(arr1, arr2)
result = []
arr1.each_with_index do |num1, ind1|
arr2.each_with_index do |num2, ind2|
result.push(num1 * num2) if ind1 == ind2
end
end
result
end
multiply_list([3, 5, 7], [9, 10, 11])
# LS solution
def multiply_list(list_1, list_2)
products = []
list_1.each_with_index do |item, index|
products << item * list_2[index]
end
products
end
# Further exploration
def multiply_list_zip(list_1, list_2)
list_1.zip(list_2).map { |list| list.reduce(:*) }
end
p multiply_list_zip([3, 5, 7], [9, 10, 11])
| true |
9a699e56c6537bd973cd23e6900c75d1af1ee73c | Ruby | 8thlight/limelight_docs | /production/documentation/players/run_styles_button.rb | UTF-8 | 1,024 | 2.625 | 3 | [] | no_license | module RunStylesButton
def button_pressed(e)
begin
find_canvas
clear_errors
styles = styles_from_text_area
apply_styles_to_canvas(styles)
rescue Exception => e
add_error(e.message)
end
end
def find_canvas
@canvas = scene.find("canvas")
end
def clear_errors
style_error = @canvas.find_by_name('style_error')
@canvas.remove(style_error[0])
end
def styles_from_text_area
code_area = scene.find("code")
return Limelight.build_styles do
eval(code_area.text)
end
end
def apply_styles_to_canvas(styles)
styles.each_pair do |prop_name, style|
apply_style_to_props(@canvas.find_by_name(prop_name), style) unless prop_name == "canvas"
end
end
def add_error(message)
@canvas << Limelight::Prop.new(:name => "style_error", :text => message)
end
def apply_style_to_props(props, style)
props.each do |prop|
prop.style.clear_extensions
prop.style.add_extension(style)
end
end
end | true |
15f935b8c980bb2e865d6949dd346775c49541a0 | Ruby | Kansei/hitoriGoto | /hitorigoto.rb | UTF-8 | 588 | 3.03125 | 3 | [] | no_license | #! /usr/bin/env ruby
load_path=File.expand_path("../",__FILE__)
require "#{load_path}/bin/command.rb"
def check_argv
file = $0.split("/")[-1]
com = file.split(".")[0]
if ARGV.size != 1
STDERR.print "Usage: #{com} w/v/l (write or view, list)\n"
exit
end
end
def main(argv)
com = Command.new
command = argv[0]
date = argv[1]
case command
when "w"
com.write
when "v"
date ||= Time.now.strftime("%Y%m")
com.view(date)
when "l"
com.list
else
STDERR.puts "command not found"
STDERR.puts "only w/v/l"
end
end
check_argv
main(ARGV)
| true |
e6a74a7a3c17f9438c7e58da74838fdd4c94f32d | Ruby | bhfailor/edibles | /app/services/food/calculator.rb | UTF-8 | 7,022 | 2.984375 | 3 | [] | no_license | ##
# TODO: update this class comment
# This class pulls specific nutrition data for a food that is present in the
# United States Department of Agriculture, Agricultural Research Service,
# National Nutrient Database (https://ndb.nal.usda.gov/ndb/doc/index)
class Food::Calculator
attr_reader :results
def initialize(args = {})
@food = args[:food]
@results = {}
args[:sources].each { |source| find_result_for source } if args[:sources]
end
def find_result_for(s)
return parse_nutrient(s) if /\d{3}/.match s
send(s.to_sym) if respond_to? s.to_sym
end
def parse_nutrient(nutrient_id)
n = nutrient_hash[nutrient_id]
@results[nutrient_id] =
n ? { name: n['name'], unit: n['unit'], value: n['value'] } : nil
end
def nutrient_hash
@nh ||= begin
nhash = {}
@food['nutrients'].each { |n| nhash[n['nutrient_id']] = n }
nhash
end
end
class << self
def define(name, &block) # see ActiveSupport::Testing::Declarative#test
name_sym = name.to_sym
fail "#{name_sym} already defined in #{self}" if method_defined? name_sym
return define_method(name_sym, &block) if block_given?
define_method(name_sym) { flunk "No implementation for #{name}" }
end
end
define('name') { foo(key: __callee__) }
define('dft') { foo(value: '100', key: __callee__) }
define('ndbno') { foo(key: __callee__) }
define('calc omega-3') { foo(value: omega_3_value, key: __callee__) }
define('calc omega-6') { foo(value: omega_6_value, key: __callee__) }
define('calc carb Cal') { foo(value: carb_cals, key: __callee__) }
define('calc fat Cal') { foo(value: fat_cals, key: __callee__) }
define('calc protein Cal') { foo(value: protein_cals, key: __callee__) }
define('calc alcohol Cal') { foo(value: alcohol_cals, key: __callee__) }
define('food price') { foo(value: 'user-specified', key: __callee__) }
define('vegetable grams') { foo(value: 'user-specified', key: __callee__) }
define('fruit grams') { foo(value: 'user-specified', key: __callee__) }
def carb_cals
calories_from[:carbs].to_s
end
def fat_cals
calories_from[:fat].to_s
end
def protein_cals
calories_from[:protein].to_s
end
def alcohol_cals
calories_from[:alcohol].to_s
end
def keys_for_calorie_calcs
{ calories: '208', carbs: '205', fat: '204', protein: '203',
alcohol: '221' }
end
def cals_per_gram
{ carbs: 4.0, fat: 9.0, protein: 4.0, alcohol: 7.0 }
end
def calorie_totals
totals = {}
keys_for_calorie_calcs.each do |k, v|
totals[k] = nutrient_hash[v] ? nutrient_hash[v]['value'].to_f : 0.0
end
totals
end
def calories
@calories ||=
begin
calories = { by_group: {}, sum: 0.0 }
cals_per_gram.each do |k, v|
calories[:by_group][k] = calorie_totals[k]*v
calories[:sum] += calories[:by_group][k]
end
calories
end
end
def calories_from
final_values = {}
largest = 0.0
largest_key = nil
calories[:by_group].each do |k, v|
final_values[k] = (v*calorie_totals[:calories]/calories[:sum]).round(1)
if final_values[k] > largest
largest = final_values[k]
largest_key = k
end
end
final_values[largest_key] = calorie_totals[:calories]
(final_values.keys - [largest_key]).each do |k|
final_values[largest_key] -= final_values[k]
end
final_values
end
def omega_3_value
sum = 0.0
%w(851 627 852 629 857 631 621 619).each do |key|
sum += nutrient_hash[key] ? nutrient_hash[key]['value'].to_f*1000 : 0.0
end
sum.to_s # assume nutrient units are grams
end
def omega_6_value
sum = 0.0
%w(675 685 672 853 855 858 618).each do |key|
sum += nutrient_hash[key] ? nutrient_hash[key]['value'].to_f*1000 : 0.0
end
sum.to_s # assume nutrient units are grams
end
def foo(args = {})
key = args[:key].to_s
indx = Food::SOURCES.index(key)
@results[key] = { name: Food::NAMES[indx],
unit: Food::UNITS[indx], value: args[:value] || @food[key] }
end
end
=begin
attr_reader :errors, :results
UNITS = 'string,,g,,USD,,g,,g,,calorie,,calorie,,calorie,,calorie,,calorie' \
',,g,,g,,g,,g,,g,,,,g,,g,,g,,g,,g,,mg,,mg,,g,,g,,IU,,mg,,mcg,,mg,,' \
'mcg,,mg,,mg,,mg,,mg,,mcg,,mcg,,mg,,mg,,mg,,mg,,mg,,mg,,mg,,mg,,mg' \
',,mg,,mg,,mg,,mcg,,mcg,,mg,,mg,,g,,g,,g,,mg,,mg,,string'.split(',,')
SOURCES = \
'name,,dft,,food price,,vegetable grams,,fruit grams,,208,,calc carb Cal,,' \
'calc fat Cal,,calc protein Cal,,calc alcohol Cal,,205,,291,,209,,269,,204' \
',,606,,645,,646,,605,,693,,695,,calc omega-3,,calc omega-6,,203,,510,,318' \
',,401,,328,,323,,430,,404,,405,,406,,415,,417,,418,,410,,421,,454,,301,,3' \
'03,,304,,305,,306,,307,,309,,312,,315,,317,,313,,601,,636,,221,,255,,207,' \
',262,,263,,ndbno'.split(',,')
NAMES = \
'food,,base mass,,price,,vegetable mass,,fruit mass,,energy (E),,carbohydr' \
'ate E,,fat E,,protein E,,alcohol E,,total carbohydrates,,fiber,,starch,,s' \
'ugars,,total fat,,saturated fat,,monounsaturated fat,,polyunsaturated fat' \
',,total trans fat,,trans-monoeonic,,trans-polyenoic,,omega-3,,omega-6,,pr' \
'otein,,tryptophan,,vitamin A,,vitamin C,,vitamin D,,vitamin E,,vitamin K,' \
',thiamine,,riboflavin,,niacin,,vitamin B6,,folate,,vitamin B12,,pantothen' \
'ic acid,,choline,,betaine,,calcium,,iron,,magnesium,,phosphorus,,potassiu' \
'm,,sodium,,zinc,,copper,,manganese,,selenium,,fluoride,,cholesterol,,phyt' \
'osterols,,alcohol,,water,,ash,,caffeine,,theobromine,,ndb food number'
.split(',,')
def initialize(args = {})
@num = args[:number]
assign_results unless errors_exist
end
private
AUTH = "&api_key=#{ENV['DATA_DOT_GOV_API_KEY']}"
BASE = 'http://api.nal.usda.gov/ndb/reports/?'
def assign_results
# calc = Food::Calculator.new(sources: SOURCES,
# food: body['report']['food']).calculation
@results = {
units: \
'string,,g,,USD,,g,,g,,calorie,,calorie,,calorie,,calorie,,calorie' \
',,g,,g,,g,,g,,g,,,,g,,g,,g,,g,,g,,mg,,mg,,g,,g,,IU,,mg,,mcg,,mg,,' \
'mcg,,mg,,mg,,mg,,mg,,mcg,,mcg,,mg,,mg,,mg,,mg,,mg,,mg,,mg,,mg,,mg' \
',,mg,,mg,,mg,,mcg,,mcg,,mg,,mg,,g,,g,,g,,mg,,mg,,string'.split(',,')
}
end
def errors_exist
@errors = "#{body['errors']['error'].first['message']}: #{@num}" \
if body['errors']
@errors ? true : false
end
def body
@body ||= begin
http = Net::HTTP.new(url.host, url.port)
response = http.request(Net::HTTP::Get.new(url))
JSON.parse(response.read_body)
end
end
def url
@url ||= begin
data = URI
.encode_www_form(ndbno: @num, type: 's', format: 'json')
URI.parse(BASE + data + AUTH)
end
end
end
=end
| true |
3511196b8cbf3f4c7825c2dd4391d7a1e626d21e | Ruby | lolottetheclash/ruby | /exo_08.rb | UTF-8 | 195 | 3.3125 | 3 | [] | no_license | #Écris un programme exo_08.rb qui demande le prénom de l'utilisateur, et qui salue l'utilisateur
puts "Bonjour, quel est ton prénom ?"
user_name = gets.chomp
puts "Bonjour, #{user_name} !"
| true |
4a3d4c88bb0a33f1305442dbf20c1d3b88694196 | Ruby | Flare2B/YEARepo | /Battle/Lunatic_Objects.rb | UTF-8 | 15,674 | 2.765625 | 3 | [
"MIT"
] | permissive | #==============================================================================
#
# ▼ Yanfly Engine Ace - Lunatic Objects v1.02
# -- Last Updated: 2011.12.27
# -- Level: Lunatic
# -- Requires: n/a
#
#==============================================================================
$imported = {} if $imported.nil?
$imported["YEA-LunaticObjects"] = true
#==============================================================================
# ▼ Updates
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# 2011.12.27 - Added "Prepare" step.
# - Moved Common Lunatic Object Effects to occur at the end of the
# effects list per type.
# 2011.12.15 - REGEXP Fix.
# 2011.12.14 - Started Script and Finished.
#
#==============================================================================
# ▼ Introduction
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Lunatic mode effects have always been a core part of Yanfly Engine scripts.
# They exist to provide more effects for those who want more power and control
# for their items, skills, status effects, etc., but the users must be able to
# add them in themselves.
#
# This script provides the base setup for skill and item lunatic effects.
# These lunatic object effects will give leeway to occur at certain times
# during a skill or item's usage, which include before the object is used,
# while (during) the object is used, and after the object is used.
#
#==============================================================================
# ▼ Instructions
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# To install this script, open up your script editor and copy/paste this script
# to an open slot below ▼ Materials/素材 but above ▼ Main. Remember to save.
#
#==============================================================================
# ▼ Compatibility
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# This script is made strictly for RPG Maker VX Ace. It is highly unlikely that
# it will run with RPG Maker VX without adjusting.
#
#==============================================================================
class Scene_Battle < Scene_Base
#--------------------------------------------------------------------------
# ● Welcome to Lunatic Mode
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Lunatic Object Effects allows skills and items allow users with scripting
# knowledge to add in their own unique effects without need to edit the
# base script. These effects occur at three different intervals and are
# marked by three different tags.
#
# <before effect: string>
# <prepare effect: string>
# <during effect: string>
# <after effect: string>
#
# Before effects occur before the skill cost or item consumption occurs,
# but after the spell initiates. These are generally used for skill or item
# preparations.
#
# Prepare effects occur as units are being targeted but before any HP damage
# is dealt. Note that if a skill targets a unit multiple times, the prepare
# effects will also run multiple times.
#
# During effects occur as units are being targeted and after HP damage
# occurs but before moving onto the next target if done in a group. Note
# that if a skill targets a unit multiple times, the during effects will
# also run multiple times.
#
# After effects occur after the targets have all been hit. In general, this
# will occur right before the skill or item's common event runs (if one was
# scheduled to run). These are generally used for clean up purposes.
#
# If multiple tags of the same type are used in the same skill/item's
# notebox, then the effects will occur in that order. Replace "string" in
# the tags with the appropriate flag for the method below to search for.
# Note that unlike the previous versions, these are all upcase.
#
# Should you choose to use multiple lunatic effects for a single skill or
# item, you may use these notetags in place of the ones shown above.
#
# <before effect> <prepare effect>
# string string
# string string
# </before effect> </prepare effect>
#
# <during effect> <after effect>
# string string
# string string
# </during effect> </after effect>
#
# All of the string information in between those two notetags will be
# stored the same way as the notetags shown before those. There is no
# difference between using either.
#--------------------------------------------------------------------------
def lunatic_object_effect(type, item, user, target)
return if item.nil?
case type
when :before; effects = item.before_effects
when :prepare; effects = item.prepare_effects
when :during; effects = item.during_effects
when :after; effects = item.after_effects
else; return
end
line_number = @log_window.line_number
for effect in effects
case effect.upcase
#----------------------------------------------------------------------
# Common Effect: Before
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# This is a common effect that runs before every single skill or item
# consumption even if you place it into the notebox or not. There is
# no need to modify this unless you see fit. In a before effect, the
# target is the user.
#----------------------------------------------------------------------
when /COMMON BEFORE/i
# No common before effects added.
#----------------------------------------------------------------------
# Common Effect: During
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# This is a common effect that runs during each targeting instance for
# every single skill or item even if you place it into the notebox or
# not. The prepare phase occurs before the action has takes place but
# after the target has been selected. There is no need to modify this
# unless you see fit. In a prepare effect, the target is the battler
# being attacked.
#----------------------------------------------------------------------
when /COMMON PREPARE/i
# No common during effects added.
#----------------------------------------------------------------------
# Common Effect: During
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# This is a common effect that runs during each targeting instance for
# every single skill or item even if you place it into the notebox or
# not. The during phase occurs after the action has taken place but
# before the next target is selected. There is no need to modify this
# unless you see fit. In a during effect, the target is the battler
# being attacked.
#----------------------------------------------------------------------
when /COMMON DURING/i
# No common during effects added.
#----------------------------------------------------------------------
# Common Effect: After
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# This is a common effect that runs with every single skill or item
# after targeting is over, but before common events begin even if you
# place it into the notebox or not. There is no need to modify this
# unless you see fit. In an after effect, the target is the user.
#----------------------------------------------------------------------
when /COMMON AFTER/i
# No common after effects added.
#----------------------------------------------------------------------
# Stop editting past this point.
#----------------------------------------------------------------------
else
lunatic_object_extension(effect, item, user, target, line_number)
end # effect.upcase
end # for effect in effects
end # lunatic_object_effect
end # Scene_Battle
#==============================================================================
# ▼ Editting anything past this point may potentially result in causing
# computer damage, incontinence, explosion of user's head, coma, death, and/or
# halitosis so edit at your own risk.
#==============================================================================
module YEA
module REGEXP
module USABLEITEM
BEFORE_EFFECT_STR = /<(?:BEFORE_EFFECT|before effect):[ ](.*)>/i
BEFORE_EFFECT_ON = /<(?:BEFORE_EFFECT|before effect)>/i
BEFORE_EFFECT_OFF = /<\/(?:BEFORE_EFFECT|before effect)>/i
PREPARE_EFFECT_STR = /<(?:PREPARE_EFFECT|prepare effect):[ ](.*)>/i
PREPARE_EFFECT_ON = /<(?:PREPARE_EFFECT|prepare effect)>/i
PREPARE_EFFECT_OFF = /<\/(?:PREPARE_EFFECT|prepare effect)>/i
DURING_EFFECT_STR = /<(?:DURING_EFFECT|during effect):[ ](.*)>/i
DURING_EFFECT_ON = /<(?:DURING_EFFECT|during effect)>/i
DURING_EFFECT_OFF = /<\/(?:DURING_EFFECT|during effect)>/i
AFTER_EFFECT_STR = /<(?:AFTER_EFFECT|after effect):[ ](.*)>/i
AFTER_EFFECT_ON = /<(?:AFTER_EFFECT|after effect)>/i
AFTER_EFFECT_OFF = /<\/(?:AFTER_EFFECT|after effect)>/i
end # USABLEITEM
end # REGEXP
end # YEA
#==============================================================================
# ■ DataManager
#==============================================================================
module DataManager
#--------------------------------------------------------------------------
# alias method: load_database
#--------------------------------------------------------------------------
class <<self; alias load_database_lobj load_database; end
def self.load_database
load_database_lobj
load_notetags_lobj
end
#--------------------------------------------------------------------------
# new method: load_notetags_lobj
#--------------------------------------------------------------------------
def self.load_notetags_lobj
groups = [$data_items, $data_skills]
for group in groups
for obj in group
next if obj.nil?
obj.load_notetags_lobj
end
end
end
end # DataManager
#==============================================================================
# ■ RPG::UsableItem
#==============================================================================
class RPG::UsableItem < RPG::BaseItem
#--------------------------------------------------------------------------
# public instance variables
#--------------------------------------------------------------------------
attr_accessor :before_effects
attr_accessor :prepare_effects
attr_accessor :during_effects
attr_accessor :after_effects
#--------------------------------------------------------------------------
# common cache: load_notetags_lobj
#--------------------------------------------------------------------------
def load_notetags_lobj
@before_effects = []
@prepare_effects = []
@during_effects = []
@after_effects = []
@before_effects_on = false
@during_effects_on = false
@after_effects_on = false
#---
self.note.split(/[\r\n]+/).each { |line|
case line
#---
when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_STR
@before_effects.push($1.to_s)
when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_STR
@prepare_effects.push($1.to_s)
when YEA::REGEXP::USABLEITEM::DURING_EFFECT_STR
@during_effects.push($1.to_s)
when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_STR
@after_effects.push($1.to_s)
#---
when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_ON
@before_effects_on = true
when YEA::REGEXP::USABLEITEM::BEFORE_EFFECT_OFF
@before_effects_on = false
when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_ON
@prepare_effects_on = true
when YEA::REGEXP::USABLEITEM::PREPARE_EFFECT_OFF
@prepare_effects_on = false
when YEA::REGEXP::USABLEITEM::DURING_EFFECT_ON
@during_effects_on = true
when YEA::REGEXP::USABLEITEM::DURING_EFFECT_OFF
@during_effects_on = false
when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_ON
@after_effects_on = true
when YEA::REGEXP::USABLEITEM::AFTER_EFFECT_OFF
@after_effects_on = false
#---
else
@before_effects.push(line.to_s) if @before_effects_on
@prepare_effects.push(line.to_s) if @prepare_effects_on
@during_effects.push(line.to_s) if @during_effects_on
@after_effects.push(line.to_s) if @after_effects_on
end
} # self.note.split
#---
@before_effects.push("COMMON BEFORE")
@prepare_effects.push("COMMON PREPARE")
@during_effects.push("COMMON DURING")
@after_effects.push("COMMON AFTER")
end
end # RPG::UsableItem
#==============================================================================
# ■ Game_Temp
#==============================================================================
class Game_Temp
#--------------------------------------------------------------------------
# public instance variables
#--------------------------------------------------------------------------
attr_accessor :lunatic_item
attr_accessor :targets
end # Game_Temp
#==============================================================================
# ■ Scene_Battle
#==============================================================================
class Scene_Battle < Scene_Base
#--------------------------------------------------------------------------
# alias method: use_item
#--------------------------------------------------------------------------
unless $imported["YEA-BattleEngine"]
alias scene_battle_use_item_lobj use_item
def use_item
item = @subject.current_action.item
lunatic_object_effect(:before, item, @subject, @subject)
scene_battle_use_item_lobj
lunatic_object_effect(:after, item, @subject, @subject)
end
#--------------------------------------------------------------------------
# alias method: apply_item_effects
#--------------------------------------------------------------------------
alias scene_battle_apply_item_effects_lobj apply_item_effects
def apply_item_effects(target, item)
lunatic_object_effect(:prepare, item, @subject, target)
scene_battle_apply_item_effects_lobj(target, item)
lunatic_object_effect(:during, item, @subject, target)
end
end # $imported["YEA-BattleEngine"]
#--------------------------------------------------------------------------
# new method: status_redraw_target
#--------------------------------------------------------------------------
def status_redraw_target(target)
return unless target.actor?
@status_window.draw_item($game_party.battle_members.index(target))
end
#--------------------------------------------------------------------------
# new method: lunatic_object_extension
#--------------------------------------------------------------------------
def lunatic_object_extension(effect, item, user, target, line_number)
# Reserved for future Add-ons.
end
end # Scene_Battle
#==============================================================================
#
# ▼ End of File
#
#============================================================================== | true |
ebd7a012bb5c76de07f4917ef941340afe6a36bb | Ruby | szrharrison/guessing-cli-web-031317 | /guessing_cli.rb | UTF-8 | 528 | 4.25 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Code your solution here!
def get_user_input
puts "Guess a number between 1 and 6."
gets.chomp
end
def generate_number
rand(1..6).to_s
end
def reply_to_user( number, guess )
if number == guess
'You guessed the correct number!'
else
"The computer guessed #{number}."
end
end
def run_guessing_game
input = ''
while input != 'exit'
number = generate_number
input = get_user_input
if input != 'exit'
puts reply_to_user( number, input )
else
puts 'Goodbye!'
end
end
end
| true |
ae4e10d8fbcad0743ae93f33d0dab69fe965eb74 | Ruby | traviscrampton/Library_System | /lib/author.rb | UTF-8 | 1,223 | 2.9375 | 3 | [
"MIT"
] | permissive | class Author
attr_reader(:name, :id)
define_method(:initialize) do |attributes|
@name = attributes.fetch(:name)
@id = attributes.fetch(:id)
end
define_singleton_method(:all) do
returned_authors = DB.exec("SELECT * FROM authors;")
authors = []
returned_authors.each() do |author|
name = author.fetch('name')
id = author.fetch('id').to_i()
authors.push(Author.new({:name => name, :id => id}))
end
authors
end
define_method(:==) do |another_author|
self.name().==(another_author.name()).&(self.id().==(another_author.id()))
end
define_method(:save) do
result = DB.exec("INSERT INTO authors (name) VALUES ('#{@name}') RETURNING id")
@id = result.first().fetch('id').to_i()
end
define_singleton_method(:find) do |id|
found_author = nil
Author.all().each() do |author|
if author.id().==(id)
found_author = author
end
end
found_author
end
define_method(:update) do |attributes|
@name = attributes.fetch(:name)
@id = self.id
DB.exec("UPDATE authors SET name = '#{@name}' WHERE id = #{@id};")
end
define_method(:delete) do
DB.exec("DELETE FROM authors WHERE id = #{self.id};")
end
end
| true |
055af71e269a89015a63dce825209cb994cf9cfd | Ruby | pbrudny/cron-parser | /lib/validator.rb | UTF-8 | 1,338 | 3.03125 | 3 | [] | no_license | require 'pry'
module CronParser
class Validator
def initialize(cron_expression)
self.cron_expression = cron_expression
self.args = cron_expression.split
self.minute = args[0]
self.hour = args[1]
self.day_of_month = args[2]
self.month = args[3]
self.day_of_week = args[4]
end
def call
return false unless cron_expression.length >= 11
return false unless args.count >= 6
return false unless regex_ok?
return false if both_week_month_day?
true
end
def regex_ok?
minute_match(minute) &&
hour_match(hour) &&
day_of_month_match(day_of_month) &&
month_match(month) &&
day_of_week_match(day_of_week)
end
def both_week_month_day?
day_of_month == '*' && day_of_week == '*'
end
def minute_match(value)
value.match(/^[0-9,\-*\/]+$/)
end
def hour_match(value)
value.match(/^[0-9,\-*\/]+$/)
end
def day_of_month_match(value)
value.match(/^[0-9,\-*\/?LW]+$/)
end
def month_match(value)
value.match(/^[0-9,\-*\/]+$/)
end
def day_of_week_match(value)
value.match(/^[0-9,\-*\/L#?]+$/)
end
private
attr_accessor :cron_expression, :args, :minute,
:hour, :day_of_month, :month, :day_of_week
end
end
| true |
d53f1989faa845dc6eac8562fed6e25483d9cf16 | Ruby | Muniek/market | /models/consumer.rb | UTF-8 | 181 | 2.875 | 3 | [] | no_license | class Consumer
def initialize(cash:, salary:)
p @cash = cash
p @salary = salary
end
def pay_salary
@cash += @income
end
def rise_salary
#TODO
end
end
| true |
58a4336ce0cd55f9a136827bd49ffe8e4e466fbb | Ruby | Takafumi-Kondo/WebcampRails | /sample_app/app/controllers/posts_controller.rb | UTF-8 | 2,167 | 2.875 | 3 | [] | no_license | class PostsController < ApplicationController
def new
#空のモデルをビューへ渡す
@post = Post.new #空モデル作成を左へ
end
#送信されたフォーム値をDBに。(postインスタンスを生成しtitle,bodyに値セット後、saveメソッド呼)
def create #privateより上に
#ストロングパラメーター使用
post = Post.new(post_params)#ローカル変数なので@なし。アクション内のみ使用可
#DBへ保存
post.save
#保存後トップ画面へリダイレクト
redirect_to post_path(post.id)#どの投稿かを指定.id
end#↑↑投稿後すぐ内容を観れるよう'/top'を変更(詳細画面へリダイレクト)
def index
@posts = Post.all
end#全てのデータ取って@postsへ。全てなので複数
#URL中のidをコントローラーで受け取るroutes.rbから
def show
@post = Post.find(params[:id])
end#params[:id]で:idにある値を取得。URL/posts/1ならparamsには「{id: 1}」ハッシュがある
#編集するには投稿データ必要。なので保存データ取得
def edit
@post = Post.find(params[:id])
end
def update #投稿の更新
post = Post.find(params[:id])
post.update(post_params)
redirect_to post_path(post.id)
end
#showの削除リンク押すとそこのpostのid含めたURLが送信。それをもとにレコード探しDBから削除する
def destroy
post = Post.find(params[:id])#レコード(データ)を1取得
post.destroy#レコードをDBから削除
redirect_to posts_path#post一覧へリダイレクト
end
#create作成 フォームからのデータ受け取り、そのデータをモデルを介しDBに保存
private #メソッド前に、認識されなくなる。下に
def post_params #投稿ボタンがトリガー、postsコントのcreateアクフォームに入った値が送信される
params.require(:post).permit(:title, :body, :image)
end# モデル名 カラムな gemのImagemagick使う時追加(:image)
end | true |
df11188b0271ea947de3abf05ba0280d1af41727 | Ruby | jenbeckham/weather_report | /conditions.rb | UTF-8 | 1,320 | 3.0625 | 3 | [] | no_license | require './requires.rb'
class Conditions
attr_reader :zipcode, :conditionspage
def initialize(zipcode)
@zipcode = zipcode
@conditionspage = get_data
end
private def get_data
HTTParty.get("http://api.wunderground.com/api/#{ENV["WUNDERGROUND_KEY"]}/conditions/q/CA/#{zipcode}.json")
end
def location_name
@conditionspage["current_observation"]["display_location"]["full"]
end
def temp
@conditionspage["current_observation"]["temp_f"]
end
def weather
@conditionspage["current_observation"]["weather"]
end
def wind_speeds
if @conditionspage["current_observation"]["wind_gust_mph"] == "0.0"
return "Winds are #{@conditionspage["current_observation"]["wind_mph"]}mph"
else
return "Winds are #{@conditionspage["current_observation"]["wind_mph"]}mph with gusts of #{@conditionspage["current_observation"]["wind_gust_mph"]}mph"
end
end
def humidity
@conditionspage["current_observation"]["relative_humidity"]
end
def feels_like
@conditionspage["current_observation"]["feelslike_f"]
end
def current_info
"The current temperature is " + self.temp.to_s + "F in " + self.location_name + ", but feels like "+ self.feels_like + "F. Its " + self.weather + " with a humidity of " + self.humidity + ". "+ self.wind_speeds
end
end
| true |
1db59ffc7dd49a6bc36b845a0f6c459ecaef122e | Ruby | KevinKansanback/LS-101-Lesson2 | /lesson3/Easy1.rb | UTF-8 | 1,471 | 4.1875 | 4 | [] | no_license | # 1
# I would expect it to print [1,2,2,3] as "uniq" doesn't mutate the caller
#2
# the difference is ? is a ternary operator when part of Ruby syntax and ! is
# the bang operator which converts true to false etc.
# Else both characters used to potentially communicate information.
## 1 - != == "is not" or "not equal to" -- if x != 5 (when x =3)
## 2 changes the object to opposite of boolean value
## 3 describes an existing method as a destructive action (mutates the caller)
## 4 just a nameing convention
## 5 could be a ternary operator if followed by ":"
## 6 changes object to boolean equivalent
# # 3
# advice = "Few things in life are as important as house training your pet dinosaur."
# advice.gsub!('important', 'urgent')
# puts advice
# 4
# numbers.delete_at(1) = mutating the caller and deleting and returning whatever element was stored at index[1] so numbers becomes [1,3,4,5]
# numbers.delete(1) = mutating the caller and deleting and returning any element that == 1 so numbers become [2,3,4,5]
# 5
# (10..100).include?(42)
# # 6
# famous_words = "seven years ago.."
# famous_words.prepend("four score and ")
# OR
# famous_words.insert(0, "four score and ")
# 7
# 42
# # 8
# flintstones = ["Fred", "Wilma"]
# flintstones << ["Barney", "Betty"]
# flintstones << ["BamBam", "Pebbles"]
# flintstones.flatten!
# 9
flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 }
flintstones.assoc("Barney") | true |
f2751bde68bd962ed9c54ee12f5117e62da4b4f5 | Ruby | FernandaFranco/book-intro-programming | /flow_control/ternary.rb | UTF-8 | 115 | 3.296875 | 3 | [] | no_license | def cond(parameter)
parameter.length < 3 ? "less than 3 words" : "more than 3 words or equal"
end
puts cond("hey") | true |
cedd8e9c17f0efcbbaeafa7d99ff246f7b956cce | Ruby | jollopre/mps | /api/app/models/suppliers/csv_importer.rb | UTF-8 | 852 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'csv'
module Suppliers
module CSVImporter
def csv_importer(path_file)
logger = Logger.new(STDOUT)
CSV.foreach(path_file, headers: :first_row) do |row|
reference = row.field('Reference')
supplier = Supplier.new(
reference: reference,
company_name: row.field('Company / Name'),
contact: row.field('Contact') || '',
email: row.field('Email'),
telephone: row.field('Telephone'),
address: row.field('Address'),
city: row.field('Town'),
postcode: row.field('Postcode'),
country: row.field('Country')
)
if supplier.valid?
supplier.save
else
p 'else'
logger.debug("#{supplier.errors.messages}, for supplier reference: #{reference}")
end
end
end
end
end
| true |
89d07a4692b3a7589de388308eff208d15d84aba | Ruby | schneider2100/exo_ruby | /lib/03_stairway.rb | UTF-8 | 1,140 | 3.71875 | 4 | [] | no_license |
def lancer_des
puts "Lance les dès !"
i= rand(1..6)
puts "@|*_*@| ~>#{i}<~"
puts
return i
end
def jeu
tour = 0
marche = 0
while marche <10
i = lancer_des
if i == 5 || i == 6
marche +=1
puts " :) Tu as avancé d'une case, tu es maintenant dans la case #{marche}."
elsif i == 1
marche -=1
puts " :( Tu dois descendre d'une case, tu es maintenant dans la case #{marche}."
else
puts " ~.~ Tu es dans la case #{marche}, tu restes où tu es."
end
tour += 1
puts
end
puts"========================================="
puts "Bravo ! Tu as atteint la 10ème étage !"
puts "Le nombre de tours est #{tour}."
puts"========================================="
return tour
end
def average_finish_time
partie=0
all_tour=0
while partie<100
tour=jeu
all_tour+=tour
partie+=1
end
moyenne=all_tour/100
return moyenne
end
puts"Le nombre de tour moyen pour arriver aux 10ème étage : #{average_finish_time}"
| true |
49de02fa002e83640222dbfb0b5babe0e710d6a2 | Ruby | innervisions/RB101 | /03_practice_problems/02_medium_1/04.rb | UTF-8 | 644 | 3.484375 | 3 | [] | no_license | def rolling_buffer1(buffer, max_buffer_size, new_element)
buffer << new_element
buffer.shift if buffer.size > max_buffer_size
buffer
end
def rolling_buffer2(input_array, max_buffer_size, new_element)
buffer = input_array + [new_element]
buffer.shift if buffer.size > max_buffer_size
buffer
end
# rolling_buffer_1 is an implementation that mutates the buffer
# being sent to it. rolling_buffer_2 creates a new buffer on line 8
# and this is the buffer being shifted on line 9. In order to use
# this method the caller would have to assign the return value to a
# variable because the original buffer object would remain unchanged.
| true |
52f7a6e01b757cb91c540e7517ddd10ee05886c7 | Ruby | qaz442200156/project-euler | /euler014.rb | UTF-8 | 1,242 | 3.453125 | 3 | [] | no_license | # coding: utf-8
=begin
Problem 14 「最長のコラッツ数列」 †
正の整数に以下の式で繰り返し生成する数列を定義する.
n → n/2 (n が偶数)
n → 3n + 1 (n が奇数)
13からはじめるとこの数列は以下のようになる.
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
13から1まで10個の項になる. この数列はどのような数字からはじめても最終的には 1 になると考えられているが, まだそのことは証明されていない(コラッツ問題)
さて, 100万未満の数字の中でどの数字からはじめれば最長の数列を生成するか.
注意: 数列の途中で100万以上になってもよい
http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2014
=end
def euler014
index = 0
index_value = 0
tag = 1000_000
((tag/2).to_i..tag).select{|v| v % 2 != 0 }.map{ |x|
cacu_value = x
counter = 0
loop do
if cacu_value % 2 == 0
cacu_value /= 2
counter += 1
else
cacu_value = (cacu_value*3+1)
counter += 1
end
if cacu_value <= 1
if index_value <= counter
index = x
index_value = counter
end
break
end
end
break if x < tag / 2
}
index
end | true |
26fd93239446d522b4c6ecf1d0e5cd8e6c72754c | Ruby | lumoslabs/txgh | /queue/spec/backends/sqs/history_sequence_spec.rb | UTF-8 | 1,937 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'helpers/sqs/sqs_test_message'
describe TxghQueue::Backends::Sqs::HistorySequence do
let(:message) { SqsTestMessage.new('abc123', '{}', attributes_hash) }
let(:attributes_hash) do
{
'history_sequence' => {
'string_value' => [{
'status' => 'retry_without_delay'
}].to_json
}
}
end
describe '.from_message' do
it 'extracts the correct attributes from the given hash' do
sequence = described_class.from_message(message)
expect(sequence.sequence).to eq([
{ status: 'retry_without_delay' }
])
end
end
describe '.from_h' do
it 'extracts the correct attributes from the given hash' do
sequence = described_class.from_h(attributes_hash)
expect(sequence.sequence).to eq([
{ status: 'retry_without_delay' }
])
end
end
context 'with a sequence' do
let(:sequence) { described_class.from_message(message) }
describe '#add' do
it 'adds the given object to the sequence' do
expect { sequence.add('abc') }.to(
change { sequence.sequence.size }.by(1)
)
expect(sequence.sequence.last).to eq('abc')
end
end
describe '#to_h' do
it 'serializes the sequence into a hash' do
expect(sequence.to_h).to eq(
string_value: [{'status' => 'retry_without_delay'}].to_json,
data_type: 'String'
)
end
end
describe '#dup' do
it 'deep copies the sequence' do
copied_sequence = sequence.dup
expect(sequence.object_id).to_not eq(copied_sequence.object_id)
expect(sequence.sequence.object_id).to_not(
eq(copied_sequence.sequence.object_id)
)
end
end
describe '#current' do
it 'returns the last element in the sequence' do
expect(sequence.current).to eq(status: 'retry_without_delay')
end
end
end
end
| true |
2bba6b099d93ffd07743099d0989cf032cbe2584 | Ruby | N-Ibrahimi/launch-school-ruby-book | /07_loops/practice_each.rb | UTF-8 | 222 | 4.03125 | 4 | [] | no_license | # practice_each.rb
names = ['Bob', 'Joe','Steve','Susan','Helen','Jane']
names.each { |name| puts name }
puts "now we do the same loop with do end block"
x = 0
names.each do |name|
puts "#{x}. #{name}"
x += 1
end
| true |
1fec886bc018f5416e947c21af1f52f85cd5c175 | Ruby | jonesk79/AddressBookRuby | /lib/addressbook.rb | UTF-8 | 615 | 3.125 | 3 | [] | no_license | class Contact
@@all_contacts == []
def Contact.all
@@all_contacts
end
def Contact.clear
@@all_contacts = []
end
def Contact.create name
new_contact = Contact.new name
new_contact.save
new_contact
end
def initialize name
@name = name
end
def name
@name
end
def save
@@all_contacts << self
end
end
class Phone
def initialize number
@number = number
end
def number
@number
end
end
class Email
def initialize email
@email = email
end
def email
@email
end
end
class Address
def initialize address
@address = address
end
def address
@address
end
end
| true |
e44bca3be02e05a0b8962d36b1ee6104f6a37dbd | Ruby | ShanaLMoore/array-CRUD-lab-v-000 | /lib/array_crud.rb | UTF-8 | 605 | 3.890625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def create_an_empty_array
array = []
end
def create_an_array
household = ["Eddie", "Diego", "Alex", "Shana"]
end
def add_element_to_end_of_array(array, element)
array.push(element)
end
def add_element_to_start_of_array(array, element)
array.unshift(element)
end
def remove_element_from_end_of_array(array)
array.pop
end
def remove_element_from_start_of_array(array)
array.shift
end
def retreive_element_from_index(array, index_number)
array[index_number]
end
def retreive_first_element_from_array(array)
array[0]
end
def retreive_last_element_from_array(array)
array.last
end | true |
6d224882e57559d6c07b34817398dcea37aa0ae7 | Ruby | robert-laws/learning-apr-2019-ruby-files-formats-templates | /file-system/types-of-paths.rb | UTF-8 | 962 | 3.453125 | 3 | [] | no_license | # Types of File Paths
# absolute path - from root of harddrive /path/to/file.txt
# relative path - location relative to current location ../../files/file.txt
# __FILE__
# File.expand_path(__FILE__) - absolute path to file
# File.dirname(__FILE__)
# File.expand(File.dirname(__FILE__))
# __dir__ - same as above
file = File.join('..', 'files', 'info.txt')
puts file
puts "This file (relative): " + __FILE__
puts "This file (absolute): " + File.expand_path(__FILE__)
puts "----------------------------------"
puts "This dir (relative): " + File.dirname(__FILE__)
puts "This dir (absolute): " + File.expand_path(File.dirname(__FILE__))
puts "This dir (absolute): " + __dir__
puts "----------------------------------"
this_dir = File.dirname(__FILE__)
puts "Relative path to a new directory: " + File.join(this_dir, '..', "files")
puts "Absolute path to a new directory: " + File.expand_path(File.join(this_dir, '..', "files")) | true |
66a5b184f0e8b20a1231c8843e69ed3d2dbb5c2c | Ruby | enspirit/wlang | /spec/unit/dialect/test_render.rb | UTF-8 | 878 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
module WLang
describe Dialect, "render" do
U = Upcasing
let(:expected){ "Hello WHO!" }
it 'works as expected' do
U.render(hello_tpl).should eq(expected)
end
it 'do not eat extra blocks' do
U.render("Hello ${who}{world}").should eq("Hello WHO{world}")
end
it "accepts an optional scope" do
U.render(hello_tpl, {}).should eq(expected)
end
it "accepts multiple scope objects" do
U.render(hello_tpl, 12, {}).should eq(expected)
end
it 'accepts a :to_path object' do
U.render(hello_path).should eq(expected)
end
it 'accepts an IO instance' do
hello_io{|io| U.render(io)}.should eq(expected)
end
it 'supports specifying the buffer' do
U.render(hello_tpl, {}, []).should eq(["Hello ", "WHO", "!"])
end
end # describe Dialect
end # module WLang
| true |
404f543d241c16e84484b8b42b9e6d06d4247a17 | Ruby | zhouruisong/elk | /logstash-all-2.4.0/vendor/bundle/jruby/1.9/gems/logstash-filter-elasticsearch-2.1.1/lib/logstash/filters/elasticsearch.rb | UTF-8 | 3,864 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | # encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require_relative "elasticsearch/client"
# Search elasticsearch for a previous log event and copy some fields from it
# into the current event. Below is a complete example of how this filter might
# be used. Whenever logstash receives an "end" event, it uses this elasticsearch
# filter to find the matching "start" event based on some operation identifier.
# Then it copies the `@timestamp` field from the "start" event into a new field on
# the "end" event. Finally, using a combination of the "date" filter and the
# "ruby" filter, we calculate the time duration in hours between the two events.
# [source,ruby]
# if [type] == "end" {
# elasticsearch {
# hosts => ["es-server"]
# query => "type:start AND operation:%{[opid]}"
# fields => [["@timestamp", "started"]]
# }
#
# date {
# match => ["[started]", "ISO8601"]
# target => "[started]"
# }
#
# ruby {
# code => "event['duration_hrs'] = (event['@timestamp'] - event['started']) / 3600 rescue nil"
# }
# }
#
class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
config_name "elasticsearch"
# List of elasticsearch hosts to use for querying.
config :hosts, :validate => :array, :default => [ "localhost:9200" ]
# Comma-delimited list of index names to search; use `_all` or empty string to perform the operation on all indices
config :index, :validate => :string, :default => ""
# Elasticsearch query string. Read the Elasticsearch query string documentation
# for more info at: https://www.elastic.co/guide/en/elasticsearch/reference/master/query-dsl-query-string-query.html#query-string-syntax
config :query, :validate => :string
# Comma-delimited list of `<field>:<direction>` pairs that define the sort order
config :sort, :validate => :string, :default => "@timestamp:desc"
# Array of fields to copy from old event (found via elasticsearch) into new event
config :fields, :validate => :array, :default => {}
# Basic Auth - username
config :user, :validate => :string
# Basic Auth - password
config :password, :validate => :password
# SSL
config :ssl, :validate => :boolean, :default => false
# SSL Certificate Authority file
config :ca_file, :validate => :path
# Whether results should be sorted or not
config :enable_sort, :validate => :boolean, :default => true
# How many results to return
config :result_size, :validate => :number, :default => 1
# Tags the event on failure to look up geo information. This can be used in later analysis.
config :tag_on_failure, :validate => :array, :default => ["_elasticsearch_lookup_failure"]
def register
options = {
:ssl => @ssl,
:hosts => @hosts,
:ca_file => @ca_file,
:logger => @logger
}
@client = LogStash::Filters::ElasticsearchClient.new(@user, @password, options)
end # def register
def filter(event)
begin
query_str = event.sprintf(@query)
params = { :q => query_str, :size => result_size, :index => @index }
params[:sort] = @sort if @enable_sort
results = @client.search(params)
@fields.each do |old_key, new_key|
if !results['hits']['hits'].empty?
set = []
results["hits"]["hits"].to_a.each do |doc|
set << doc["_source"][old_key]
end
event[new_key] = ( set.count > 1 ? set : set.first)
end
end
rescue => e
@logger.warn("Failed to query elasticsearch for previous event", :index => @index, :query => query_str, :event => event, :error => e)
@tag_on_failure.each{|tag| event.tag(tag)}
end
filter_matched(event)
end # def filter
end # class LogStash::Filters::Elasticsearch
| true |
6d8c37a7b32673ad346bfd999ff703be93a1e037 | Ruby | elitenomad/email-delivery | /lib/email/delivery/sendgrid_client.rb | UTF-8 | 2,083 | 2.6875 | 3 | [
"MIT"
] | permissive | =begin
This class acts like a interface.
It will
- initialize default mail-client(MailGun)
- call 'do' method to send the emails.
- provide fail-over mechanism
=end
require 'net/http'
require 'uri'
require 'json'
module Email
module Delivery
class SendgridClient
def dispatch(from, to, cc, bcc, subject, body)
response = RestClient.post("#{ENV['SENDGRID_API_URL']}", JSON.dump(payload(from, to, cc, bcc, subject, body)), headers=headers_hash)
{
status: response.code,
message: response.description
}
end
# This method helps to include all recipients defined within the to, cc, and bcc parameters,
# across each object that you include in the personalizations array.
def personalizations(to, cc, bcc)
personalizations_hash = {
"to" => recepient_list(to)
}
unless cc.nil?
personalizations_hash.merge!({ "cc" => recepient_list(cc) })
end
unless bcc.nil?
personalizations_hash.merge!({ "bcc" => recepient_list(cc) })
end
[
personalizations_hash
]
end
def from(from)
{
"email" => from
}
end
def content(body)
[
{
"type" => "text/plain",
"value" => body
}
]
end
def payload(from, to, cc, bcc, subject, body)
{
"personalizations" => personalizations(to, cc, bcc) ,
"from" => from(from) ,
"subject" => subject,
"content" => content(body)
}
end
def headers_hash
{
"Authorization" => "Bearer #{ENV['SENDGRID_API_KEY']}",
"content-type" => "application/json"
}
end
def recepient_list(lst)
if lst.is_a?(Array)
lst.map {|elem| {"email" => elem } }
else
[
{
"email" => lst
}
]
end
end
end
end
end
| true |
6cb3f80820e198fb4cd3a2bee2caf219b8e9a8c1 | Ruby | dmbf29/super_character | /lib/tasks/character.rake | UTF-8 | 1,024 | 2.578125 | 3 | [] | no_license | require 'open-uri'
require 'nokogiri'
namespace :character do
desc "Try to steal the photo form the wiki"
task find_photos: :environment do
Character.find_each do |character|
next if character.photo.present?
url = URI.encode("https://simpsons.fandom.com/wiki/#{character.name.gsub("\"", "'").gsub(" ", "_")}")
begin
html_doc = Nokogiri.HTML(open(url).read)
if html_doc
photo_div = html_doc.search('.pi-item')[1]
if photo_div
photo_url = photo_div.search('img').first.attributes['src'].value
if photo_url
character.remote_photo_url = photo_url
character.save
end
puts "Photo added for #{character.name}"
else
puts "Photo not found for #{character.name}"
end
else
puts "HTML not found for #{character.name}"
end
rescue OpenURI::HTTPError => ex
puts "#{character.name} has a 404 page"
end
end
end
end
| true |
234a4a82e2b7bdc858ac173e2b9c188dc42b4b2c | Ruby | jhawthorn/mpvctl | /lib/mpvctl/mpv.rb | UTF-8 | 1,649 | 2.625 | 3 | [
"MIT"
] | permissive | require "mpvctl/socket"
require "mpvctl/playlist_item"
module MpvCtl
class Mpv
attr_reader :socket
def initialize
@socket = Socket.new('/tmp/mpvsocket')
end
def play(path, mode=:replace)
command 'loadfile', path, 'replace'
end
def add(path, mode=:replace)
command 'loadfile', path, 'append-play'
end
def seek(seconds, type)
type =
case type
when :relative then 'relative'
when :absolute then 'absolute'
else raise ArgumentError, "unknown seek type"
end
osd_command 'seek', seconds, type
end
def next(force=false)
command 'playlist-next', (force ? 'force' : 'weak')
end
def prev(force=false)
command 'playlist-prev', (force ? 'force' : 'weak')
end
def stop
command 'stop'
end
def playlist
get_property('playlist').map.with_index do |item, index|
PlaylistItem.new(self, index+1, item)
end
end
def toggle_property(prop)
set_property(prop, !get_property(prop))
end
def get_property(prop)
command 'get_property', prop
end
def get_property(prop)
command 'get_property', prop
end
def set_property(prop, value)
command 'set_property', prop, value
end
def wait_for_idle
until get_property('idle')
sleep 0.1
end
end
def wait_for_event(*events)
socket.wait_for_event(*events)
end
def osd_command(*args)
socket.command 'osd-msg-bar', *args
end
def command(*args)
socket.command *args
end
def close
socket.close
end
end
end
| true |
fc00070184163607442cbb320b611c64256c5090 | Ruby | jsblaisdell/powerrangers | /powerranger.rb | UTF-8 | 1,567 | 3.90625 | 4 | [] | no_license | require 'modules.rb'
class Person
attr_accessor :name, :caffeine_level
def initialize(name)
@name = name
@caffeine_level = 0
end
def run
"#{@name} ran away."
end
def scream(string)
"#{string.upcase}!!!"
end
def drink_coffee
@caffeine_level += 1
end
end
class PowerRanger < Person
include Fight
def initialize(name, strength, color)
super(name)
@strength = strength
@color = color
end
def rest
"zzzzzzzzzzzzzzzzzzz..."
end
def self.use_megazord(target)
puts target.scream("ow")
puts target.run
puts target.scream("ow")
puts target.run
target.caffeine_level -= 1
end
end
class EvilNinja < Person
include Fight
def initialize(name, strength, evilness)
super(name)
@strength = strength
@evilness = evilness
end
def cause_mayhem(target)
target.caffeine_level = 0
puts "mayhem caused"
end
end
def fight_scene(person1, person2, pr1, pr2, ninja1, ninja2)
person1.drink_coffee
person2.drink_coffee
person1.drink_coffee
ninja1.cause_mayhem(person1)
ninja2.cause_mayhem(person2)
pr1.punch(ninja1)
pr2.punch(ninja2)
ninja1.punch(pr1)
ninja2.punch(pr2)
pr1.rest
pr2.rest
PowerRanger.use_megazord(ninja1)
PowerRanger.use_megazord(ninja2)
end
bob = Person.new("Bob")
phil = Person.new("Phil")
red = PowerRanger.new("John", 5, "red")
green = PowerRanger.new("Sean", 4, "green")
ninja1 = EvilNinja.new("Evil Ninja 1", 10, 10)
ninja2 = EvilNinja.new("Evil Ninja 1", 15, 30)
fight_scene(bob, phil, red, green, ninja1, ninja2)
| true |
91a4ee4f0468d2fc1dd13adcdf4567b0303916da | Ruby | Zacharae/spring16ruby | /rps.rb | UTF-8 | 847 | 4.25 | 4 | [] | no_license | # ROCK PAPER SCISSORS
require "pry"
class RockPaperScissors
PLAYS = ['rock', 'paper', 'scissors']
WINS = [
['rock', 'scissors'],
['paper', 'rock'],
['scissors', 'paper']]
def play
human_move = human_selection
computer_move = computer_selection
get_winner(human_move, computer_move)
#binding.pry
end
def human_selection
puts " rock, paper, or scissors?"
gets.chomp.downcase
end
def computer_selection
PLAYS.sample
end
def get_winner(input1, input2)
if input1 == input2
puts "it's a tie, play again"
else
if WINS.include?([input1, input2])
puts "computer plays #{input2.capitalize}, and you shot #{input1.capitalize}, you win!!!"
else
puts "computer shoots #{input2.capitalize} and you played #{input1.capitalize}, you lose"
end
end
end
end
game = RockPaperScissors.new
game.play | true |
89b3d46dda3100c3a1a72b231ed4fa7bda1b652b | Ruby | Ank13/socrates_prep | /letter_grade.rb | UTF-8 | 364 | 3.671875 | 4 | [] | no_license | def get_grade(scores)
sum = 0
scores.each do |score|
sum += score
end
average = sum/scores.length
case average
when 90..100
'A'
when 80..89
'B'
when 70..79
'C'
when 60..69
'D'
when 50..59
'E'
when 0..49
'F'
else
'Error'
end
end
grades =[100,90,95]
puts get_grade(grades) | true |
828c1e03a68952f285f4359887ad3bd1027b1c4e | Ruby | hightowercorporation/voter_sim | /spec/records_spec.rb | UTF-8 | 3,283 | 2.921875 | 3 | [] | no_license | require './records.rb'
describe Records do
it "can create a voter and add it to a voter's array" do
records = Records.new
records.create_voter("Darth Vader", "Liberal")
expect(records.voters.count).to eq(1)
end
it "can create a politician and add it to a politician's array" do
records = Records.new
records.create_politician("George Jetson", "Republican")
expect(records.politicians.count).to eq(1)
end
it "can list all voters and politicians" do
records = Records.new
records.create_voter("Darth Vader", "Liberal")
records.create_politician("George Jetson", "Republican")
expected_result = "Voter, Darth Vader, Liberal\nPolitician, George Jetson, Republican\n"
expect(records.list).to eq(expected_result)
end
it "can search for a voter by name" do
records = Records.new
records.create_voter("Darth Vader", "Liberal")
records.create_voter("Joe Mancuso", "Socialist")
records.create_voter("Libby Anderson", "Green Party")
index_for_existing_voter = records.search_voter("Darth Vader")
index_for_nonexisting_voter = records.search_voter("Q")
expect(index_for_existing_voter).to eq(0)
expect(index_for_nonexisting_voter).to eq(nil)
end
it "can search for a politician by name" do
records = Records.new
records.create_politician("Snidely Whiplash", "Democrat")
records.create_politician("Henry Fonda", "Republican")
records.create_politician("Ken Tirunda", "Independent")
index_for_existing_politician = records.search_politician("Ken Tirunda")
index_for_nonexisting_politician = records.search_politician("Bobby Henderson")
expect(index_for_existing_politician).to eq(2)
expect(index_for_nonexisting_politician).to eq(nil)
end
it "can update a voter" do
record = Records.new
record.create_voter("Kyle Jin", "Liberal")
record.create_voter("Kimberly June", "Conservative")
# record.create_voter("Kyle Jin", "Liberal")
record.update_voter("Kyle Jin", "Joseph Green", "Socialist")
expect(record.voters[0].name).to eq("Joseph Green")
expect(record.voters[0].politics).to eq("Socialist")
# expect(record.voters[2].name).to eq("Joseph Green")
# expect(record.voters[2].politics).to eq("Socialist")
end
it "can update a politician" do
record = Records.new
record.create_politician("Sander Van Doorn", "Republican")
record.create_politician("Pablo Finduval", "Democrat")
# record.create_voter("Kyle Jin", "Liberal")
record.update_politician("Pablo Finduval", "Orlando Mustaffah", "Republican")
expect(record.politicians[1].name).to eq("Orlando Mustaffah")
expect(record.politicians[1].party).to eq("Republican")
# expect(record.voters[2].name).to eq("Joseph Green")
# expect(record.voters[2].politics).to eq("Socialist")
end
it "can delete a voter" do
records = Records.new
records.create_voter("Darth Vader", "Liberal")
records.create_voter("Lindsay Lohan", "Socialist")
expect(records.voters.count).to eq(2)
records.delete_voter("Lindsay Lohan")
expect(records.voters.count).to eq(1)
expect(records.search_voter("Lindsay Lohan")).to eq(nil)
end
it "can delete a politician" do
records = Records.new
records.create_politician("Darth Vader", "Liberal")
records.create_politician("Lindsay Lohan", "Socialist")
expect(records.politicians.count).to eq(2)
records.delete_politician("Lindsay Lohan")
expect(records.politicians.count).to eq(1)
expect(records.search_politician("Lindsay Lohan")).to eq(nil)
end
end
| true |
f5e27b1492d72ff0f7f83f2e154e555e35652d09 | Ruby | percolator-io/percolator | /app/helpers/categories_helper.rb | UTF-8 | 519 | 2.796875 | 3 | [] | no_license | module CategoriesHelper
def categories_for_select
@_categories_for_select ||= _categories_array_from_tree(Category.hash_tree)
end
private
def _category_name_for_select(name, depth)
['-' * depth, name].select(&:present?).join(' ')
end
def _categories_array_from_tree(tree, depth = 0)
result = []
tree.each do |node, children|
result << [_category_name_for_select(node.name, depth), node.id]
result += _categories_array_from_tree(children, depth + 1)
end
result
end
end
| true |
d40b42dab884bd4616a84e65d53367bf5ab54cc0 | Ruby | MURATKAYMAZ56/RUBY | /3_OOP_Ruby_Fundamentals/ExerciseFile_ruby-object-oriented-fundamentals/05/demos/mixin.rb | UTF-8 | 1,135 | 4.15625 | 4 | [] | no_license | module Tagged
def tag(tag)
@tags ||= []
@tags << tag
end
def untag(tag)
@tags.delete(tag) if !@tags.nil?
end
attr_reader :tags
end
class Book
attr_reader :name
def initialize(name)
@name = name
end
# The spaceship operator in order to use Enumerable methods
# to sort books in a collection
def <=>(other)
name <=> other.name
end
end
class Collection
include Tagged
include Enumerable # It's fine to mix in multiple modules
def initialize()
@books = []
end
# Custom append operator to add a book to collection
def <<(book)
@books << book
end
# Enumerable module requires the class to provide `each`
# so that Enumerable methods can access items in the collection
def each(&block)
@books.each {|book| block.call(book) }
end
end
c = Collection.new
c.tag("ruby")
c.tag("testing")
puts "Collection tags: #{c.tags}"
c.untag("ruby")
puts "Collection tags without \"ruby\": #{c.tags}"
# Add tagging to books
class Book
include Tagged
end
# Now a book can also be tagged
b = Book.new("Code")
b.tag("ruby")
puts "Book tags: #{b.tags}" | true |
39162adda9c627b558ec3d0ef3cac540800976ce | Ruby | Claytonboyle/RubyPokerSim | /main.rb | UTF-8 | 696 | 3.5625 | 4 | [] | no_license | require './evaluate.rb'
# Each program being simulated
# will give out an input dependant
# on what is happening
# Any misunderstood input will
# be interpreted as a fold.
# To start a round each program
# will be given the input of their
# hand with standard format, i.e:
# H10 C1
# on each round of betting, if they
# are still playing they will be given
# how much they need to play to stay
# in the game
# They must then return a number,
# the amount they wish to bet. If this
# is lower then the amount they need to
# play it will be interpreted as a fold
# They may also output F is they wish to
# fold
# If a player has folded they will recieve
# no other input until the next round.
| true |
db27680540971874abd7fdca781636e8a1fa4cae | Ruby | Tsutomu19/StudyingAlgorithms | /0630.rb | UTF-8 | 82 | 3.25 | 3 | [] | no_license | D140:N番目の単語
num = gets.to_i
alf = gets.chomp.split(" ")
puts alf[num-1]
| true |
d55c65e29dfe15990dbb41b6e13fdac9ab7a97d9 | Ruby | westlakedesign/pbxproject | /lib/pbxproject/pbxtypes.rb | UTF-8 | 8,116 | 2.71875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'digest/sha1'
module PBXProject
module PBXTypes
class BasicValue
attr_accessor :value, :comment
def initialize(args = {})
@value = args[:value]
@comment = args[:comment]
end
def to_pbx ind = 0
pbx = ''
pbx += "#{@value}"
pbx += " /* #{@comment} */" if @comment
pbx
end
end
class ISAType
attr_accessor :guid, :isa, :comment
def initialize args = {}
@isa = basic_value(self.class.name.split("::").last)
@guid = hashify(self)
args.each do |k,v|
instance_variable_set("@#{k}", basic_value(v)) unless v.nil?
end
end
def basic_value(value = nil, comment = nil)
# { :value => value, :comment => comment }
BasicValue.new :value => value, :comment => comment
end
def hashify to_hash
# example
ex = 'C01713D713462F35007665FA'
"OEF" + (Digest::SHA1.hexdigest to_hash.to_s).upcase[4..ex.length]
end
def self.has_fields(*fields)
_fields = []
fields.each do |f|
_fields.push f.id2name
define_method(f) do
instance_variable_get("@#{f}")
end
define_method("#{f}=") do |val|
instance_variable_set("@#{f}", val)
end
end
define_method("pbxfields") do
_fields
end
end
def self.has_format(format)
_format = format
define_method("format") do
_format
end
end
def _pbx_indent(ind = 0)
"\t" * ind
end
def _pbx_format
return nil unless defined? format
format
end
def _pbx_newline
case _pbx_format
when :oneline
nil
else
"\n"
end
end
def to_pbx(ind = 0)
pbx = ''
pbx += _pbx_indent(ind) + "#{@guid}"
pbx += " /* #{@comment} */" if @comment
pbx += " = {%s" % _pbx_newline
ind += 1
# PBX fields
pbxfields.each do |fld|
field = self.instance_variable_get("@#{fld}")
case field.class.name
when "String"
pbx += (_pbx_format == :multiline ? _pbx_indent(ind) : "") + "%s = %s;%s%s" % [fld, field, (_pbx_newline == nil ? " " : ""),_pbx_newline]
when 'PBXProject::PBXTypes::BasicValue'
pbx += (_pbx_format == :multiline ? _pbx_indent(ind) : "") + "%s = %s;%s%s" % [fld, field.to_pbx, (_pbx_newline == nil ? " " : ""), _pbx_newline]
when "Array"
pbx += _pbx_indent(ind) + "%s = (%s" % [fld, _pbx_newline]
ind += 1
field.each do |item|
pbx += _pbx_indent(ind) + "%s,%s" % [item.to_pbx, _pbx_newline]
end
ind -= 1
pbx += _pbx_indent(ind) + ");%s" % _pbx_newline
when "NilClass"
when "Hash"
pbx += _pbx_indent(ind) + "%s = {%s" % [fld, _pbx_newline]
ind += 1
field.each do |name, d|
case d.class.name
when "PBXProject::PBXTypes::BasicValue"
pbx += _pbx_indent(ind) + "%s = %s;%s%s" % [name, d.to_pbx, (_pbx_newline == nil ? " " : ""), _pbx_newline]
when "Array"
pbx += _pbx_indent(ind) + "%s = (%s" % [name, _pbx_newline]
ind += 1
d.each do |item|
pbx += _pbx_indent(ind) + "%s,%s" % [item.to_pbx, _pbx_newline]
end
ind -= 1
pbx += _pbx_indent(ind) + ");%s" % _pbx_newline
end
end
ind -= 1
pbx += _pbx_indent(ind) + "};%s" % _pbx_newline
else
puts "WHAT? #{field.class}"
puts "#{field}"
end
end
ind -= 1
# ind.times{print"\t"}; pbx += "};%s" % _pbx_newline
if (_pbx_newline)
pbx += "\t" * ind + "};\n"
else
pbx += "};\n"
end
pbx
end
end
class PBXBuildFile < ISAType
has_fields :isa, :fileRef, :settings
has_format :oneline
end
class PBXReferenceProxy < ISAType
has_fields :isa, :fileType, :path, :remoteRef, :sourceTree
has_format :multiline
end
class PBXHeadersBuildPhase < ISAType
has_fields :isa, :buildActionMask, :files, :runOnlyForDeploymentPostprocessing
has_format :multiline
end
class PBXLegacyTarget < ISAType
has_fields :isa, :buildArgumentsString, :buildConfigurationList, :buildPhases, :buildToolPath, :dependencies, :name, :passBuildSettingsInEnvironment, :productName
has_format :multiline
end
class PBXContainerItemProxy < ISAType
has_fields :isa, :containerPortal, :proxyType, :remoteGlobalIDString, :remoteInfo
has_format :multiline
end
class PBXFileReference < ISAType
has_fields :isa, :fileEncoding, :explicitFileType, :lastKnownFileType, :lineEnding, :includeInIndex, :name, :path, :plistStructureDefinitionIdentifier, :sourceTree, :xcLanguageSpecificationIdentifier
has_format :oneline
end
class PBXFrameworksBuildPhase < ISAType
has_fields :isa, :buildActionMask, :files, :runOnlyForDeploymentPostprocessing
has_format :multiline
end
class PBXGroup < ISAType
has_fields :isa, :children, :name, :path, :sourceTree
has_format :multiline
def add_children(fileref)
@children.push BasicValue.new(:value => fileref.guid, :comment => fileref.comment)
fileref.guid
end
end
class PBXNativeTarget < ISAType
has_fields :isa, :buildConfigurationList, :buildPhases, :buildRules, :dependencies, :name,
:productName, :productReference, :productType
has_format :multiline
def add_build_phase build_phase, position = -1
@buildPhases.insert(position, BasicValue.new(:value => build_phase.guid, :comment => build_phase.comment))
end
end
class PBXProject < ISAType
has_fields :isa, :attributes, :buildConfigurationList, :compatibilityVersion, :developmentRegion,
:hasScannedForEncodings, :knownRegions, :mainGroup, :productRefGroup, :projectDirPath, :projectRoot,
:targets
has_format :multiline
end
class PBXResourcesBuildPhase < ISAType
has_fields :isa, :buildActionMask, :files, :runOnlyForDeploymentPostprocessing
has_format :multiline
end
class PBXShellScriptBuildPhase < ISAType
has_fields :isa, :buildActionMask, :files, :inputPaths, :name, :outputPaths, :runOnlyForDeploymentPostprocessing,
:shellPath, :shellScript, :showEnvVarsInLog
has_format :multiline
def initialize args = {}
super
# Defaults
@comment = "ShellScript"
@buildActionMask = basic_value(2147483647)
@files = []
@inputPaths = []
@outputPaths = []
@runOnlyForDeploymentPostprocessing = basic_value(0)
end
end
class PBXSourcesBuildPhase < ISAType
has_fields :isa, :buildActionMask, :files, :runOnlyForDeploymentPostprocessing
has_format :multiline
end
class PBXTargetDependency < ISAType
has_fields :isa, :target, :targetProxy
has_format :multiline
end
class PBXVariantGroup < ISAType
has_fields :isa, :children, :name, :sourceTree
has_format :multiline
end
class XCBuildConfiguration < ISAType
has_fields :isa, :baseConfigurationReference, :buildSettings, :name
has_format :multiline
end
class XCConfigurationList < ISAType
has_fields :isa, :buildConfigurations, :defaultConfigurationIsVisible, :defaultConfigurationName
has_format :multiline
end
class XCVersionGroup < ISAType
has_fields :isa, :children, :currentVersion, :name, :path, :sourceTree, :versionGroupType
has_format :multiline
end
end
end
| true |
d832ecbdf6e3762fa64a6649ce89f343a387a445 | Ruby | pioneertrack/rails-challenge-quiz-back-end | /app/models/user.rb | UTF-8 | 1,176 | 2.53125 | 3 | [] | no_license | class User < ApplicationRecord
has_secure_password
has_many :calendars
has_many :events
# TODO validate the presence of name and email
################################################
# TODO validate the format of the email with
# this regex
#
# /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
#
# and ensure it is unique and not case sensitive
################################################
# TODO validate that there are at least
# two words in the name column
before_validation :format_email
after_create :create_calendar
def access_token(user_agent)
# TODO flesh out the JsonWebToken encode
# method in the lib/util/json_web_token.rb
# file
Util::JsonWebToken.encode(self, user_agent)
end
class << self
def authenticate(email, password)
# TODO authenticate the user via the email
# and password passed in
#
# If the user exists and the password is
# valid respond with the user
#
# Else respond with nil
end
end
private
def create_calendar
Calendar.create!(title: name, user_id: id)
end
def format_email
self.email = email.downcase
end
end
| true |
ef0569a01cbc580b3c81ede1a580250ef3752847 | Ruby | JamieReid1/week_03_weekend_homework_codeclan_cinema | /console.rb | UTF-8 | 2,840 | 2.703125 | 3 | [] | no_license |
require('pry')
require_relative('models/customer')
require_relative('models/film')
require_relative('models/ticket')
require_relative('models/screening')
Customer.delete_all()
Film.delete_all()
Screening.delete_all()
customer1 = Customer.new({ 'name' => 'Woody', 'funds' => 100 })
customer1.save()
customer2 = Customer.new({ 'name' => 'Buzz Lightyear', 'funds' => 100 })
customer2.save()
customer3 = Customer.new({ 'name' => 'Rex', 'funds' => 90 })
customer3.save()
customer4 = Customer.new({ 'name' => 'Hamm', 'funds' => 90 })
customer4.save()
customer5 = Customer.new({ 'name' => 'Little Bo Peep', 'funds' => 90 })
customer5.save()
customer6 = Customer.new({ 'name' => 'Mr Potato Head', 'funds' => 90 })
customer6.save()
film1 = Film.new({ 'title' => 'The Magnificent Seven', 'price' => 9 })
film1.save()
film2 = Film.new({ 'title' => 'Transformers', 'price' => 10 })
film2.save()
film3 = Film.new({ 'title' => 'Jurassic Park', 'price' => 8 })
film3.save()
film4 = Film.new({ 'title' => 'Babe', 'price' => 7 })
film4.save()
screening1 = Screening.new({ 'film_id' => film4.id, 'show_time' => '14:00' })
screening1.save
screening2 = Screening.new({ 'film_id' => film1.id, 'show_time' => '16:30' })
screening2.save
screening3 = Screening.new({ 'film_id' => film1.id, 'show_time' => '18:00' })
screening3.save
screening4 = Screening.new({ 'film_id' => film3.id, 'show_time' => '18:30' })
screening4.save
screening5 = Screening.new({ 'film_id' => film2.id, 'show_time' => '19:00' })
screening5.save
customer6.name = 'Mrs Potato Head'
customer5.funds = 100
customer6.update()
customer5.update()
film4.title = 'Peppa Pig'
film3.price = 7
film4.update()
film3.update()
customer1.buy_ticket(screening2)
customer1.buy_ticket(screening3)
customer2.buy_ticket(screening2)
customer2.buy_ticket(screening5)
customer3.buy_ticket(screening4)
customer4.buy_ticket(screening1)
customer5.buy_ticket(screening3)
customer6.buy_ticket(screening5)
customer6.buy_ticket(screening2)
# ticket1 = Ticket.new({ 'customer_id' => customer1.id, 'screening_id' => screening1.id })
# ticket1.save()
# ticket2 = Ticket.new({ 'customer_id' => customer2.id, 'screening_id' => screening2.id })
# ticket2.save()
# ticket3 = Ticket.new({ 'customer_id' => customer3.id, 'screening_id' => screening3.id })
# ticket3.save()
# ticket4 = Ticket.new({ 'customer_id' => customer4.id, 'screening_id' => screening4.id })
# ticket4.save()
# ticket5 = Ticket.new({ 'customer_id' => customer5.id, 'screening_id' => screening1.id })
# ticket5.save()
# ticket6 = Ticket.new({ 'customer_id' => customer6.id, 'screening_id' => screening2.id })
# ticket6.save()
# ticket5.film_id = film3.id
# ticket5.update()
# customer2.ticket_count()
# customer2.films()
# film1.customer_count()
# screening1.film()
# screening1.customers()
# film1.customers()
# film1.screenings()
# film1.show_times()
# binding.pry
# nil
| true |
6b8e99ab9fd26844036bf29e7342564380e7a687 | Ruby | mdhernandez/basic-games | /mastermind.rb | UTF-8 | 5,497 | 3.875 | 4 | [] | no_license | class Mastermind
@pegs
@solution
@colors
@player
@white
def initialize( player = true)
@pegs = { "Colored" => 0, "White" => 0 }
@colors = ["RED", "YELLOW", "WHITE", "PURPLE", "ORANGE", "GREEN"]
@solution = color_rand
@player = player
@white = Hash.new
end
def get_white
return @white
end
def reset_white
@white = Hash.new
end
def set_solution(arr)
@solution = arr
end
def color_rand
i = 0
arr = Array.new(4)
while i < 4
arr[i] = @colors[rand(6)]
i+=1
end
return arr
end
def get_colors
return @colors
end
def get_player
return @player
end
def right_spots(arr)
i = 0
skip = []
while i < 4
if arr[i] == @solution[i]
skip.push(i)
end
i+=1
end
return skip
end
def check (arr)
correct = true
i = 0
skip = []
while i < 4
if arr[i] == @solution[i]
skip.push(i)
@pegs["Colored"] = @pegs["Colored"] + 1
else
correct = false
end
i+=1
end
r = 0
while r < 4
if (!skip.include?(r))
q = 0
while q < 4
if arr[r] == @solution[q] && (!skip.include?(q))
@pegs["White"] = @pegs["White"]+1
skip.push(q)
@white[arr[r]] = r
#puts @white.inspect#debug
break
end
q+=1
end
end
r+=1
end
return correct
end
def print_solution
puts @solution.inspect
end
def print_pegs
puts
puts "Pegs:"
puts @pegs.inspect
puts
end
def reset_pegs
@pegs["Colored"] = 0
@pegs["White"] = 0
end
end#end of Mastermind
def guesser_instructions
puts "In this game you are the code-breaker."
puts "When prompted enter four colors out of six options: Red, Yellow, White, Purple, Orange, and Green."
puts "Please type all four colors on one line, each seperated by one space."
puts "You may put a color more than once."
puts
puts "After you guess you will see something called Pegs pop up"
puts "A colored peg means you got a color correct in the right spot"
puts "A white peg means you guessed a correct color, but it is in a wrong spot."
puts "Use the pegs to help you crack the code!"
puts
end
def master_instructions
puts "In this game you are the code-maker."
puts "To make your solution, enter four colors out of six options: Red, Yellow, White, Purple, Orange, and Green."
puts "Please type all four colors on one line, each seperated by one space."
puts "You may use a color more than once."
puts
end
def play (master, guesses = 10)
if(master.class == Mastermind)
i = 1
correct = false
if(master.get_player)#human player
guesser_instructions
while((!correct) && i <= guesses)
puts "Make your guess!"
guess = gets.chomp
guess.upcase!
guess_arr = guess.split(" ")
correct = master.check(guess_arr)
if correct
puts "Congratulations! You've Won!"
else
master.print_pegs
master.reset_pegs
end
i += 1
end
if i == 11 && (!correct)
puts "I'm Sorry. You Lose."
print "The solution was: "
puts master.print_solution
end
else#computer player
cols = master.get_colors
hr = [0,1,2,3]
stank = Hash.new
wer = 0
while wer < 4
stank[hr[wer]] = cols
wer += 1
end
# puts stank.inspect
master_instructions
sol = gets.chomp
sol.upcase!
sole = sol.split(" ")
master.set_solution(sole)
right_spots = []
puts
puts "Computer Guesses:"
comp_guess = master.color_rand
correct = master.check(comp_guess)
almost = master.get_white
while(!correct && i <= guesses)
r = 0
taken = []
puts comp_guess.inspect#debug
right_spots = master.right_spots(comp_guess)
while r < 4
if !(right_spots.include?(r))
stank[r] = stank[r] - [comp_guess[r]]
stank_size = stank[r].size
if (!almost.empty?)
almost.each do |key, value|
if (value != r) && (!taken.include?(r))
comp_guess[r] = key
taken.push(r)
end
end
end
if (!taken.include?(r))
comp_guess[r] = stank[r][rand(stank_size)]
end
end
r+=1
end
#puts stank.inspect
master.reset_white
correct = master.check(comp_guess)
almost = master.get_white
i+=1
end
if(correct)
puts comp_guess.inspect#debug
puts "The Computer guessed the solution in #{i} guesses."
puts
else
puts "The Computer failed to guess the solution after #{i-1} guesses."
puts
end
end#end player if
end#end master class if
end
def intro
puts "Mastermind is a code-breaking game where you can play as either the code-breaker or the code-maker."
puts "As code-breaker, you must break a code consisting of four colors created by a computer player."
puts "As code-maker, you create the four-color code and the computer player tries to guess the code you created."
puts "The code-breaker will have ten attempts to crack the code."
puts
puts "Welcome to Mastermind!"
puts
end
def game
puts
intro
choice = -1
playing = true
while playing
puts "To play Mastermind as the code-breaker enter 1. To play as the code-maker enter 2\nTo quit enter any other number."
choice = gets.chomp.to_i
puts
case choice
when 1
test = Mastermind.new(true)
play(test)
when 2
test = Mastermind.new(false)
play(test)
else
puts "Thank you for playing Mastermind!"
playing = false
end
end
end
game | true |
85603d8ab062422e23e00235f9bdecfa32fa3664 | Ruby | shawnewallace/TheAlgorithmsStillCount | /src/ruby/spec/fibonacci_spec.rb | UTF-8 | 710 | 3.546875 | 4 | [] | no_license | require 'fibonacci'
describe Fibonacci do
@values = [
[0, 0],
[1, 1],
[2, 1],
[3, 2],
[4, 3],
[5, 5],
[17, 1597],
[45, 1134903170],
[83, 99194853094755497]
]
@values.each do |fib, expected|
it "is #{expected} for fib(#{fib}) computed iteratively" do
Fibonacci.ofIterative(fib).should == expected
end
end
# @values.each do |fib, expected|
# it "is #{expected} for fib(#{fib}) computed recursively" do
# Fibonacci.ofRecursion(fib).should == expected
# end
# end
@values.each do |fib, expected|
it "is #{expected} for fib(#{fib}) computed using O(1) calculation" do
Fibonacci.of(fib).should == expected
end
end
end
| true |
e21ff8be9e80ad1677fbf6e13395d15168f13ab0 | Ruby | UpAndAtThem/practice_kata | /titleize.rb | UTF-8 | 365 | 4.03125 | 4 | [] | no_license | def titleize(str)
str.split.map {|word| word.capitalize}.join" "
end
def titleize!(str)
counter = 0
str[0] = str[0].capitalize
loop do
str[counter + 1] = str[counter + 1].capitalize if str[counter] == ' '
counter += 1
break if counter == str.size
end
str
end
book = "the shinning"
titleize book
puts book
titleize! book
puts book
| true |
2fe63dfb781001024796046cc9ee0487da1be51c | Ruby | Digory/week_3_day_3 | /db/console.rb | UTF-8 | 783 | 2.8125 | 3 | [] | no_license | require_relative('../models/album.rb')
require_relative('../models/artist.rb')
#
# Album.delete_all()
# Artist.delete_all()
#
artist1 = Artist.new({
'name' => 'Digory'
})
artist2 = Artist.new({
'name' => 'Emil'
})
artist1.save()
artist2.save()
album1 = Album.new({
'title' => 'Digory\'s greatest hits',
'genre' => 'Acid Jazz',
'artist_id' => artist1.id
})
album2 = Album.new({
'title' => 'Digory Volume 2',
'genre' => 'Psychedelic Pop',
'artist_id' => artist1.id
})
album1.save()
album2.save()
album1.genre = 'Trip Hop'
album1.update()
artist2.name = 'Emilia'
artist2.update()
# album1.delete()
# artist2.delete()
p Album.find(43)
p Artist.find(55)
# p album1
# p artist1.albums()
# p album1.artist()
# p album2.artist()
# p Artist.all()
# p Album.all()
| true |
f1dbbada2fe98a289ac46c7b030d0dffc4325c14 | Ruby | kamihiro0626/furima_28797 | /spec/models/user_spec.rb | UTF-8 | 4,502 | 2.625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
it "nicknameとemail、passwordとpassword_confirmation、famiy_nameとfirst_name、family_name_kanaとfirst_name_kana、birthdayが存在すれば登録できる" do
expect(@user).to be_valid
end
it "nicknameが空では登録できないこと" do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include("ニックネームを入力してください")
end
it "emailが空では登録できないこと" do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Eメールを入力してください")
end
it "emailの@が存在しない場合は登録できないこと" do
@user.email = "kami.kami"
@user.valid?
expect(@user.errors.full_messages).to include("Eメールは不正な値です")
end
it "重複したemailがある場合は登録できないこと" do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Eメールはすでに存在します")
end
it "passwordが空では登録できないこと" do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include("パスワードを入力してください")
end
it "passwordが存在しても確認用がなければ登録できない" do
@user.password_confirmation = ""
@user.valid?
expect(@user.errors.full_messages).to include("パスワード(確認用)とパスワードの入力が一致しません")
end
it "passwordが6文字以上であれば登録できること" do
@user.password = "123abc"
@user.password_confirmation = "123abc"
expect(@user).to be_valid
end
it "passwordが5文字以下であれば登録できないこと" do
@user.password = "12345"
@user.password_confirmation = "12345"
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは6文字以上で入力してください")
end
it "passwordが半角英数字混合でなければ登録できないこと" do
@user.password = "000000"
@user.password_confirmation = "000000"
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは不正な値です")
end
it "ユーザー本名の名字が空では登録できないこと" do
@user.family_name = nil
@user.valid?
expect(@user.errors.full_messages).to include("名字を入力してください")
end
it "ユーザー本名の名前が空では登録できないこと" do
@user.first_name = nil
@user.valid?
expect(@user.errors.full_messages).to include("名前を入力してください")
end
it "ユーザー本名が半角であれば登録できないこと" do
@user.family_name = "takahashi"
@user.first_name = "tarou"
@user.valid?
expect(@user.errors.full_messages).to include("名字は不正な値です")
end
it "ユーザー本名のフリガナの名字が空では登録できないこと" do
@user.family_name_kana = nil
@user.valid?
expect(@user.errors.full_messages).to include("名字(フリガナ)を入力してください")
end
it "ユーザー本名のフリガナの名前が空では登録できないこと" do
@user.first_name_kana = nil
@user.valid?
expect(@user.errors.full_messages).to include("名前(フリガナ)を入力してください")
end
it "ユーザー本名のフリガナが半角(カタカナ)であれば登録できないこと" do
@user.family_name_kana = "タカハシ"
@user.first_name_kana = "タロウ"
@user.valid?
expect(@user.errors.full_messages).to include("名字(フリガナ)は不正な値です")
end
it "生年月日がなければ登録できないこと" do
@user.birthday = nil
@user.valid?
expect(@user.errors.full_messages).to include("生年月日を入力してください")
end
end
end | true |
0a0a584d87c4f6e8722eef921e63aac810bdaa38 | Ruby | bajunio/phase_0_unit_2 | /week_6/1_assert_statements/my_solution.rb | UTF-8 | 2,307 | 4.375 | 4 | [] | no_license | # U2.W6: Testing Assert Statements
# I worked on this challenge by myself.
# 1. Review the simple assert statement
# method assert is attempting to yeild to blocks
=begin
def assert
raise "Assertion failed!" unless yield
end
name = "bettysue"
assert { name == "bettysue" }
assert { name == "billybob" }
=end
# 2. Pseudocode what happens when the code above runs
=begin
var name is set to "bettysue"
assert method is called and passed block of name == "bettysue" and does not raise message as its true
assert method is called and passed block of name == "billybob" and does raise message as its false
=end
# 3. Copy your selected challenge here
class CreditCard
def initialize(number)
raise ArgumentError, "Must be 16 digits!" unless number.to_s.length == 16
@number = number
end
def check_card
arr = Array.new(@number.to_s.split(""))
arr.map! {|x| x.to_i}
(0...arr.length).step(2) {|every_other| arr[every_other] *= 2}
arr.map! {|x| x.to_s}
arr2 = Array.new(arr.join.split(""))
arr2.map! {|x| x.to_i}
arr2.inject(:+) % 10 == 0
end
end
# 4. Convert your driver test code from that challenge into Assert Statements
#p CreditCard.instance_method(:initialize).arity == 1
#p CreditCard.instance_method(:check_card).arity == 0
#card = CreditCard.new(4408041234567893).check_card == true
#card = CreditCard.new(4408041234567892).check_card == false
def assert
raise "Assertion failed!" unless yield
p "Assertion passed!"
end
assert {card = CreditCard.new(4408041234567893).check_card == true}
assert {card = CreditCard.new(4408041234567892).check_card == false}
assert {CreditCard.instance_method(:initialize).arity == 1}
assert {CreditCard.instance_method(:check_card).arity == 0}
# 5. Reflection
=begin
Feels like I could have simply written out my regular driver test code
and accomplished the same thing as this. I do understand that this is
just prep work to get you in the mindset for understanding rspec a bit
better.
I'm glad to have had a chance to work with yield again. The last time I
had even seen the syntax was ages ago when I was working my way through
Codecademy. I figure there must have already been instances of problems
I had been trying to solve that I could have leveraged blocks and yeild
to make things easier.
=end | true |
b75c6fa7f2b9e2de770493ffdc36311077346634 | Ruby | albertosaurus/power_enum_2 | /lib/generators/enum/enum_generator_helpers/migration_number.rb | UTF-8 | 782 | 2.578125 | 3 | [
"MIT"
] | permissive | # Helper logic for the enum generator
module EnumGeneratorHelpers
# Helper methods to figure out the migration number.
module MigrationNumber
# Returns the next upcoming migration number. Sadly, Rails has no API for
# this, so we're reduced to copying from ActiveRecord::Generators::Migration
# @return [Integer]
def next_migration_number(dirname)
# Lifted directly from ActiveRecord::Generators::Migration
# Unfortunately, no API is provided by Rails at this time.
next_migration_number = current_migration_number(dirname) + 1
if ActiveRecord::Base.timestamped_migrations
[Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
else
"%.3d" % next_migration_number
end
end
end
end
| true |
7ea16841c1c3c22e424a4a14c5671d9a02371422 | Ruby | dmateos/scratch | /code-tests/toy-robot/spec/toy_robot_integration_spec.rb | UTF-8 | 2,351 | 2.625 | 3 | [] | no_license | require_relative 'spec_helper'
describe "ToyRobot Integration" do
let(:stdin) { FakeStdin.new }
let(:toy_robot) { ToyRobot.new(stdin: stdin) }
it "runs example a in the PDF" do
stdin << "PLACE 0,0,NORTH" << "MOVE" << "REPORT"
toy_robot.run
expect(toy_robot.robot.report(false)).to eq("0,1,NORTH")
end
it "runs example b in the PDF" do
stdin << "PLACE 0,0,NORTH" << "LEFT" << "REPORT"
toy_robot.run
expect(toy_robot.robot.report(false)).to eq("0,0,WEST")
end
it "runs example c in the PDF" do
stdin << "PLACE 1,2,EAST" << "MOVE" << "MOVE" << "LEFT" << "MOVE" << "REPORT"
toy_robot.run
expect(toy_robot.robot.report(false)).to eq("3,3,NORTH")
end
it "wont place over the edge of the table" do
stdin << "PLACE 5,5,NORTH"
toy_robot.run
expect(toy_robot.robot.position).to_not eq(Position.new(5,5,:north))
end
it "ignores place with invalid orientation" do
stdin << "PLACE 0,0,NOTHR" << "RIGHT" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to be_a(NilPosition)
end
it "will place multiple times" do
stdin << "PLACE 0,0,NORTH" << "PLACE 1,1,SOUTH"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(1, 1, :south))
end
it "will place then ignore invalid place" do
stdin << "PLACE 0,0,NORTH" << "PLACE 0,1,NOTHR" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(0, 1, :north))
end
it "wont go over edge of table" do
stdin << "PLACE 0,3,NORTH" << "MOVE" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(0, 4, :north))
end
it "turns and moves north" do
stdin << "PLACE 0,0,EAST" << "LEFT" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(0, 1, :north))
end
it "turns and moves east" do
stdin << "PLACE 0,0,NORTH" << "RIGHT" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(1, 0, :east))
end
it "turns and moves south" do
stdin << "PLACE 0,1,WEST" << "LEFT" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(0, 0, :south))
end
it "turns and moves west" do
stdin << "PLACE 1,0,SOUTH" << "RIGHT" << "MOVE"
toy_robot.run
expect(toy_robot.robot.position).to eq(Position.new(0, 0, :west))
end
end
| true |
74135ca415c6a350006d85a83c424abda2888add | Ruby | Flipez/blumentopf | /lib/menu.rb | UTF-8 | 1,269 | 2.9375 | 3 | [] | no_license | # frozen_string_literal: true
require_relative './pot_manager'
class Blumentopf
class Menu
attr_accessor :active_item
attr_reader :display, :pot_manager
def initialize(display, pot_manager)
@active_item = 0
@display = display
@pot_manager = pot_manager
draw
end
def items
[
{ long: 'Overview', short: '#' },
pots_to_menu,
{ long: 'Settings', short: '*' }
].flatten
end
def current
draw_order = []
items.each_with_index do |item, index|
draw_order << if index == active_item
"[#{item[:long]}]"
else
" #{item[:short]} "
end
end
draw_order.join(' ')
end
def next
return unless active_item < (items.size - 1)
@active_item += 1
draw
end
def back
return unless active_item.positive?
@active_item -= 1
draw
end
def draw
display.oled.write_line 1, 0, ' ' * 22
display.oled.write_line 1, 0, current
end
private
def pots_to_menu
pot_manager.pots.to_enum.with_index.map do |_pot, index|
{ long: "Pot #{index}", short: index }
end
end
end
end
| true |
8412d2d753c806033c06f41387b08ddb75916561 | Ruby | learn-co-students/nyc-web-students-021819 | /29-async-js/sync.rb | UTF-8 | 527 | 3.3125 | 3 | [] | no_license | require 'rest-client'
require 'json' #JavaScript Object Notation
require 'pry'
puts "brb"
# begin
# this_is_not_a_variable
# rescue NameError
# puts 'saved u'
# end
sleep(3)
puts "im back"
puts "Making an HTTP GET request with RestClient"
response = RestClient.get('https://swapi.co/api/planets')
puts "Request is complete"
puts response.inspect
puts "Parsing the JSON from the response"
planets = JSON.parse(response.body)
puts 'printing some results'
puts planets["results"].map { |planet| "* #{planet["name"]}"}
| true |
099b0080ece20c15100322a766470a9da70776db | Ruby | PBODR/E6CP1A1 | /3 ciclos anidados/ejercicio3.rb | UTF-8 | 341 | 3.8125 | 4 | [] | no_license | # Construir un programa que permita ingresar un número por teclado e imprimir
# la tabla de multiplicar del número ingresado. Debe repetir la operación hasta
#que se ingrese un 0 (cero).
# Ingrese un número (0 para salir): _
num = gets.chomp.to_i
if num != 0
10.times do |i|
i +=1
puts i*num
end
else
puts 'ya saliste'
end
| true |
55ebdb86b5642c763721bf454311830dd823ad37 | Ruby | TSimpson768/Chess | /lib/board.rb | UTF-8 | 5,327 | 3.21875 | 3 | [] | no_license | # frozen_string_literal: true
# The board class stores the current state of the board.
require_relative 'place'
require_relative 'constants'
require_relative 'pieces/piece'
require_relative 'pieces/king'
require_relative 'pieces/queen'
require_relative 'pieces/rook'
require_relative 'pieces/bishop'
require_relative 'pieces/knight'
require_relative 'pieces/pawn'
require_relative 'strategy/move'
require_relative 'strategy/promote'
require_relative 'strategy/enpassant'
require_relative 'strategy/castle'
require_relative 'board_output'
require_relative 'board_logic'
require_relative 'board_builder'
require 'pry'
# Might need a module to take the print_methods
class Board
include Constants
include BoardOutput
include BoardLogic
include BoardBuilder
ROWS = 8
COLUMNS = 8
def initialize(white, black, board = initialize_board(white, black), en_passant_target = nil, fifty_move_count = 0)
# An array of 64 piece objects. Needs to be created in the starting possition for chess.
@board = board
# [array, array] Location of a piece that can be captured via en-passant
@en_passant_target = en_passant_target
@fifty_move_count = fifty_move_count
end
attr_reader :en_passant_target, :board
def ==(other)
@board == other.board && @en_passant_target == other.en_passant_target
end
# Return true if in check
def check?(player)
attacked_spaces = list_unsafe_spaces(player).compact
attacked_spaces.each do |space|
piece = locate_piece(space)
return true if piece && piece.owner == player && piece.instance_of?(King)
end
false
end
# Return true if player is in checkmate
def checkmate?(player)
return false unless check?(player)
starts, destinations = list_moves(player, true)
destinations.each_with_index do |move, index|
next unless valid_move(starts[index], move, player)
return false unless check_after_move?([starts[index], move], player)
end
true
end
# Return true if player is in stalemate (no legal moves)
def stalemate?(player)
return false if check?(player)
moves = list_moves(player, true)[1]
return unless moves.empty?
true
end
# [[int,int],[int,int]]-> boolean
# Retrun true if the move from start_place to end place is legal. Else, return false
# Plan 1 - is start place owned by the current player? return false if false
# 2 - Starting from the start_place, perform a search (Depth or breath first? idk)
# return true if an unobstructed path to end place is found.
def legal?(move, player)
start = move[0]
destination = move[1]
piece = locate_piece(start)
return false unless valid_move(start, destination, player)
possible_moves = piece.possible_moves(start, self)
possible_moves.any? { |reachable_coord| reachable_coord == destination }
end
# Returns true if a piece can move from start to destination without causing check or moving an opponents piece
def valid_move(start, destination, player)
return false unless valid_pos?(destination, player) && locate_piece(start)&.owner == player
return false if check_after_move?([start, destination], player)
return false unless safe_path_for_king?(start, destination, player)
true
end
def safe_path_for_king?(start, destination, player)
piece = locate_piece(start)
return false if piece.instance_of?(King) && (start[1] - destination[1]).abs == 2 && check_after_move?(
[start, [start[0], (start[1] + destination[1]) / 2]], player
)
true
end
# Return true if moving from start to end will leave player in check
# This needs move piece to not check legality
def check_after_move?(move, player)
board_clone = clone
strategy = get_strategy(move)
strategy = Move.new if strategy.instance_of?(Promote)
board_clone.move_piece(move, strategy)
board_clone.check?(player)
end
# Move the piece on start_place to end place
def move_piece(move, strategy = get_strategy(move))
@board = strategy.make_move(move, @board)
@en_passant_target = ep_target(move)
end
# [Int, int] -> Piece or nil gets a pointer to the piece at the given co-ordinates, if it exists
def locate_piece(coords)
place = locate_place(coords)
place&.piece
end
# Return true if a piece belonging to owner can leagally occupy pos. Else, return false
def valid_pos?(pos, owner)
piece = locate_piece(pos)
return true if piece.nil? || piece.owner != owner
false
end
private
# I don't like a 4 pronged conditional here. Is there a better way to do this?
def get_strategy(move)
if (move[0][1] - move[1][1]).abs == 2 && locate_piece(move[0]).instance_of?(King)
Castle.new
elsif (move[0][0] - move[1][0]).abs == 1 && (move[0][1] - move[1][1]).abs == 1 &&
locate_piece(move[0]).instance_of?(Pawn) && locate_piece(move[1]).nil?
EnPassant.new
elsif (move[1][0] == 0 || move[1][0] == 7) && locate_piece(move[0]).instance_of?(Pawn)
Promote.new
else
Move.new
end
end
def ep_target(move)
possible_target = locate_piece(move[1])
return nil unless possible_target.instance_of?(Pawn) && (move[0][0] - move[1][0]).abs == 2
move[1]
end
def out_of_bounds?(next_pos)
next_pos.any? { |coord| coord.negative? || coord > 7 }
end
end
| true |
f351fa14f67c759d71af3a24257829ad9a86f4c1 | Ruby | jennyjean8675309/module-one-final-project-guidelines-dc-web-100818 | /spec/trivia_game_spec.rb | UTF-8 | 2,920 | 3.515625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
require_relative '../lib/question.rb'
require_relative '../lib/category.rb'
require_relative '../lib/choice.rb'
require_relative '../lib/user.rb'
require_relative '../lib/user_question.rb'
#Question class tests
describe Question do
cat1 = Category.new(name: "Movies")
cat2 = Category.new(name: "Science")
q1 = Question.new(question: "How many Jaws movies are there?", category: cat1, difficulty: "easy")
q2 = Question.new(question: "What is the name of Annie's dog in Annie?", category: cat1, difficulty: "hard")
q3 = Question.all[0]
choice1 = Choice.new(name: "a gazillion", question: q1, correct: true)
choice2 = Choice.new(name: "not that many", question: q1, correct: false)
q1.choices << choice1
q1.choices << choice2
it "belongs to a category" do
expect(q1.category).to eq(cat1)
end
it "has a difficulty level" do
expect(q2.difficulty).to eq("hard")
end
it "can find its correct answer" do
expect(q1.correct_answer).to eq(choice1)
end
end
#Choice class tests
describe Choice do
cat4 = Category.new(name: "Geography")
q1 = Question.new(question: "What is the capital of Venezuela?", category: cat4, difficulty: "medium")
choice1 = Choice.new(name: "London", question: q1, correct: "false")
choice2 = Choice.new(name: "Caracas", question: q1, correct: "true")
it "belongs to a question" do
expect(choice1.question).to eq(q1)
end
it "returns a boolean for whether or not it is the correct choice" do
expect(choice1.correct).to eq(false)
end
end
#Instantiating users and questions for UserQuestion class
cat1 = Category.new(name: "Movies")
cat2 = Category.new(name: "Science")
q1 = Question.new(question: "What is the lightest element?", category: cat2, difficulty: "easy")
q2 = Question.new(question: "What is the name of Jack Nicholson's character in The Shining?", category: cat2, difficulty: "easy")
mike = User.new(name: "Mike")
jenny = User.new(name: "Jenny")
#User class tests
describe User do
it "instantiates a user with a score of 0" do
expect(mike.score).to eq(0)
end
end
#UserQuestion class tests
describe UserQuestion do
uq3 = UserQuestion.all[0]
it "belongs to a question" do
uq1 = UserQuestion.new(question: q1, user: mike)
expect(uq1.question).to eq(q1)
end
it "belongs to a user" do
uq2 = UserQuestion.new(question: q2, user: jenny)
expect(uq2.user).to eq(jenny)
end
it "validates the user input (answer) for a particular question and returns true if the answer is correct and false if the answer is incorrect" do
correct = Choice.all.find { |choice| choice.name == "George Washington" }
choices = uq3.question.connect_letter_to_choice
random = uq3.question.randomized_choices
user_input = random.select { |letter, answer| answer.name == "George Washington"}
user_input_final = user_input.keys[0]
expect(uq3.validate_user_input(user_input_final)).to eq(true)
end
end
| true |
751f436830003c2afc4df81a769c0f90148b898c | Ruby | shaina33/bloc_record | /lib/bloc_record/utility.rb | UTF-8 | 1,746 | 2.96875 | 3 | [] | no_license | module BlocRecord
module Utility
extend self
def underscore(camel_cased_word)
string = camel_cased_word.gsub(/::/, '/')
string.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
string.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
string.tr!("-", "_")
string.downcase
end
# written for assignment #2
# example: bloc_record/snake_case => BlocRecord::SnakeCase
def camelCase(snake_cased_word)
string = snake_cased_word.gsub(/\//, '::')
string.gsub!(/\A[a-z]|[_|:][a-z]/) {|match| match.upcase}
string.gsub!(/([_])([A-Z])/, '\2')
end
def sql_strings(value)
case value
when String
"'#{value}'"
when Numeric
value.to_s
else
"null"
end
end
# takes an options hash and converts all the keys to string keys
# allows usage of strings or symbols as hash keys
def convert_keys(options)
options.keys.each { |k| options[k.to_s] = options.delete(k) if k.kind_of?(Symbol) }
options
end
def instance_variables_to_hash(obj)
Hash[obj.instance_variables.map{ |var| ["#{var.to_s.delete('@')}", obj.instance_variable_get(var.to_s)]}]
end
def reload_obj(dirty_obj)
persisted_obj = dirty_obj.class.find_one(dirty_obj.id)
dirty_obj.instance_variables.each do |instance_variable|
dirty_object.instance_variable_set(instance_variable, persisted_obj.instance_variable_get(instance_variable))
end
end
end
end
| true |
1b95cc9184eb1089736c15edaa53be57dcf4b03f | Ruby | daydreamboy/HelloRuby | /ruby_task/06_subcommand.rb | UTF-8 | 652 | 2.8125 | 3 | [
"MIT"
] | permissive | #encoding: utf-8
require 'optparse'
require_relative '../ruby_tool/dump_tool'
<<-DOC
The example for parsing multiple subcommands
@see https://stackoverflow.com/a/2737822
DOC
global = OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} subcommand [-options] argument"
end
subcommands = {
'foo' => OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} foo [-options] argument"
end,
# ...
'baz' => OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} baz [-options] argument"
end
}
if ARGV.empty?
puts global.help
return
end
global.order!
subcommands[ARGV.shift].order!
dump_object(ARGV)
| true |
ef85524ff5baa755ce268435151396a53bd2b900 | Ruby | athonlab/peopletantra | /utilities/indigov_parser.rb | UTF-8 | 1,272 | 3.203125 | 3 | [] | no_license | # encoding: UTF-8
require 'rubygems'
require 'hpricot'
require 'net/http'
require 'uri'
class Parser
def self.extract_links_to_members stream
doc = Hpricot(stream)
doc.search('.middleColumn>ul li a').collect{|link| link.attributes['href'] }
end
# parse members biodata
def self.extract_member stream
member = {}
doc = Hpricot stream
header = nil
doc.search('.table1 tr td').each{|table_data|
unless table_data.search('strong').empty? # even
# collecting header
header = table_data.search('strong').inner_html
else # odd
member[header] = table_data.inner_text
#puts table_data.inspect
end
}
member
end
end
# extract links to members
url = URI.parse('http://india.gov.in/govt/loksabha.php')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
Parser.extract_links_to_members(res.body).each do |link|
# extracting mp_code
mp_code = link.split('=').last
url = URI.parse("http://india.gov.in/govt/loksabhampbiodata.php?mpcode=#{mp_code}")
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts Parser.extract_member(res.body).inspect
break
end
| true |
39c9e5435c6e34bf0cdc3ee75f026963dabbe80d | Ruby | amcaplan/project_euler | /21/problem_21.rb | UTF-8 | 163 | 2.859375 | 3 | [] | no_license | require_relative 'amicable_numbers_generator'
gen = AmicableNumbersGenerator.generator
nums = gen.take_while{|pair| pair[0] < 10_000}.flatten
puts nums.inject(:+) | true |
2bf2c8d01573abc5009dff9937277c7cd00fbca7 | Ruby | athurman/fetch | /models/shelter.rb | UTF-8 | 705 | 2.671875 | 3 | [] | no_license | class Shelter < ActiveRecord::Base
default_scope { order("name ASC") }
def self.calculate_popular_breed id
results = Shelterdog.find_by_sql("select shelterdogs.breed, Count(*) as total from shelterdogs where shelterdogs.shelter = '#{id}' group by shelterdogs.breed order by total desc")
results
end
def self.calculate_total_dogs id
results = Shelterdog.where(shelter: id).count
end
def self.calculate_rate(id, status)
results = Shelterdog.where(shelter: id).where(status: status).count
status_total = results
total_amt_of_dogs = Shelter.calculate_total_dogs(id)
rate = status_total.to_f / total_amt_of_dogs.to_f
rate = (rate * 100).round.to_s + '%'
end
end | true |
3a487ca937059832d151824a989e038c7f4fe90a | Ruby | eduardopoleo/algorithm_1 | /week_4/scc_spec.rb | UTF-8 | 606 | 2.546875 | 3 | [] | no_license | require 'rspec'
require_relative './scc.rb'
describe Vertex do
describe '#push_edge' do
it 'stores other vertes in the edge attribute' do
vertex1 = described_class.new(1)
vertex2 = described_class.new(2)
vertex3 = described_class.new(3)
vertex1.push_edge(vertex2)
vertex1.push_edge(vertex3)
expect(vertex1.edges.size).to eq(2)
end
end
end
describe Graph do
describe '#add_edge' do
it 'instantiate a new vertex if there is not existing vertex with that id' do
graph = Graph.new
graph.add_adge(1)
expect()
end
end
end
| true |
f96ade3e0f039df5b5ef985c972b207a040409a1 | Ruby | jamgar/oo-cash-register-cb-000 | /lib/cash_register.rb | UTF-8 | 898 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class CashRegister
attr_accessor :total, :discount, :quantity, :message, :items
def initialize(discount = 0)
@total = 0
@discount = discount
@list = {}
end
def add_item(title, price, quantity = 1)
self.total += price * quantity
@list["#{title}"] = {
:price => price,
:quantity => quantity
}
end
def apply_discount
if discount > 0
percentage = self.discount.to_f / 100
@total -= (@total * percentage).to_i
@message = "After the discount, the total comes to $#{@total}."
else
@message = "There is no discount to apply."
end
end
def items
titles = []
@list.each do |item|
item[1][:quantity].times {titles << item[0]}
end
titles
end
def void_last_transaction
last_key = @list.keys.last
@total -= @list[last_key][:price] * @list[last_key][:quantity]
end
end
| true |
ed202a5c8102672d4ba55e76375ebfd68fbb46f2 | Ruby | txus/gametheory | /ipdsim/lib/year.rb | UTF-8 | 506 | 2.96875 | 3 | [] | no_license | class Year
attr_reader :number
attr_reader :composition
attr_reader :food_level
def initialize
@number = World.current_year ? World.current_year.number + 1 : 1
@composition = {}
@food_level = nil
@growing_rate = {}
end
def consolidate
Strategy.types.each do |strategy|
@composition[strategy.name.to_sym] = strategy.population.count
end
@food_level = World.food_level
puts "Year #{@number} consolidated. Composition is #{@composition.inspect}"
end
end
| true |
601741f4266e1b4df7e6097a9541c9a54fb7679e | Ruby | KGan/railslite | /lib/finalized/01_sql_object.rb | UTF-8 | 2,629 | 2.84375 | 3 | [] | no_license | require_relative 'db_connection'
require 'active_support/inflector'
class SQLObject
def self.columns
result = DBConnection.execute2(<<-SQL)
SELECT
*
FROM
#{table_name}
LIMIT
1
SQL
sym_arr = result.first.map do |arr|
arr.to_sym
end
sym_arr
end
def self.finalize!
columns.each do |col|
define_method("#{col}") do
@attributes[col.to_sym]
end
define_method("#{col}=") do |new_value|
@attributes[col.to_sym] = new_value
end
end
end
def self.table_name=(table_name)
@table_name = table_name
end
def self.table_name
@table_name ||= self.to_s.tableize
end
def self.all
results = DBConnection.execute(<<-SQL)
SELECT
*
FROM
#{table_name}
SQL
parse_all(results)
end
def self.parse_all(results)
[].tap do |arr|
results.each do |r|
arr << new(r)
end
end
end
def self.find(id)
result = DBConnection.execute(<<-SQL, id)
SELECT
*
FROM
#{table_name}
WHERE
id = ?
SQL
parse_all(result).first
end
def initialize(params = {})
@attributes ||= {}
params.keys.each do |key|
raise "unknown attribute '#{key}'" unless self.class.columns.include?(key.to_sym)
@attributes[key.to_sym] = params[key]
end
end
def attributes
@attributes ||= {}
end
def attribute_values
@attributes.values
end
def insert
_, insert_string, insert_values = self.class.build_strings(@attributes)
DBConnection.execute(<<-SQL, **attributes)
INSERT INTO
#{self.class.table_name}(#{insert_string})
VALUES
(#{insert_values})
SQL
@attributes[:id] = DBConnection.last_insert_row_id
end
def update
set_string, _, _ = self.class.build_strings(@attributes)
DBConnection.execute(<<-SQL, **attributes)
UPDATE
#{self.class.table_name}
SET
#{set_string}
WHERE
id = :id
SQL
end
def save
attributes[:id] ? update : insert
end
private
def self.build_strings(opts)
return_string_keys = ""
insert_values = ""
return_string = ""
opts.keys.each_with_index do |key, index|
next if key == :id
return_string_keys += "#{key}"
insert_values += ":#{key}"
return_string += "#{key} = :#{key}"
if (index + 1) < opts.keys.length
return_string_keys += ', '
return_string += ', '
insert_values += ', '
end
end
return return_string, return_string_keys, insert_values
end
end
| true |
65e60e6122572af49548fd15487f5357aa089f37 | Ruby | IceDragon200/dragontk | /spec/dragontk/thread_pool_spec.rb | UTF-8 | 932 | 2.578125 | 3 | [] | no_license | require 'spec_helper'
require 'dragontk/thread_pool'
describe DragonTK::ThreadPool do
context "#spawn/0" do
it "should spawn and complete all threads" do
result = {}
10.times do |j|
result[j] = {}
subject.spawn do
5.times do |i|
result[j][i] = j * i
end
end
end
subject.await
10.times do |j|
5.times do |i|
expect(result[j][i]).to eq(j * i)
end
end
end
it "should spawn a new sub thread" do
subject.spawn do
5.times do
puts "Hello World"
sleep 0.01
end
end
subject.spawn do
5.times do
puts "On other news"
sleep 0.01
end
end
subject.spawn do
5.times do
puts "if anything, I'd say he's crazy"
sleep 0.01
end
end
subject.await
end
end
end
| true |
62c5a24af31f2f0a5c05fac576534029a744b93c | Ruby | khanhhuy288/Ruby-Aufgaben | /A5-Vertiefung/a5_3/matrix_methoden.rb | UTF-8 | 3,102 | 3.75 | 4 | [] | no_license | def matrix?(mat)
# make sure matrix is an Array of rows
return false unless mat.is_a?(Array) && mat[0].is_a?(Array)
cols = mat[0].size
# make sure all rows are Arrays and have same cols
(0...mat.size).all? {|z| mat[z].is_a?(Array) && mat[z].size == cols }
end
def gewichtet(mat)
# calculate sizes of mat
rows = mat.size
cols = mat[0].size
# create new matrix filled with 0
result = Array.new(rows){Array.new(cols,0)}
(0...rows).each {|i|
(0...cols).each {|j|
(-1..1).each { |nb_i| # corridor for rows
(-1..1).each { |nb_j| # corridor for cols
result[i][j] += mat[(i+nb_i)%mat.size][(j+nb_j)%mat[0].size]
}
}
result[i][j] /= 9.0
}
}
result
end
# gegeben
def pp_mat(mat)
mat.each { |zeile|
zeile.each { |wert|
printf('%3f ', wert)
}
puts
}
puts
end
puts matrix?(Array.new) # false
puts matrix?(Array.new(4){|zeile| Array.new(zeile +1)}) # false
puts matrix?(Array.new(4,17)) # false
puts matrix?([[1]]) # true
puts matrix?([[]]) # true
puts matrix?(Array.new(4){Array.new(3,1)}) # true
zeilen_laenge = 10
spalten_laenge = 6
puts -1%zeilen_laenge
puts 11%zeilen_laenge
#
### Ergebnisse fuer gewichtet
#
orig0 = Array.new(4){Array.new(3,1)}
pp_mat(orig0)
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
pp_mat(gewichtet(orig0))
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
#1.000000 1.000000 1.000000
orig1 = Array.new(4){|zeile| Array.new(3,zeile+1)}
pp_mat(orig1)
#1.000000 1.000000 1.000000
#2.000000 2.000000 2.000000
#3.000000 3.000000 3.000000
#4.000000 4.000000 4.000000
pp_mat gewichtet(orig1)
#2.333333 2.333333 2.333333
#2.000000 2.000000 2.000000
#3.000000 3.000000 3.000000
#2.666667 2.666667 2.666667
orig2 = Array.new(4){|zeile| Array.new(3) {|spalte| zeile +spalte +1}}
pp_mat(orig2)
#1.000000 2.000000 3.000000
#2.000000 3.000000 4.000000
#3.000000 4.000000 5.000000
#4.000000 5.000000 6.000000
pp_mat(gewichtet(orig2))
#3.333333 3.333333 3.333333
#3.000000 3.000000 3.000000
#4.000000 4.000000 4.000000
#3.666667 3.666667 3.666667
orig3 = Array.new(7){|zeile| Array.new(5) {|spalte| zeile +spalte +1}}
pp_mat(orig3)
#1.000000 2.000000 3.000000 4.000000 5.000000
#2.000000 3.000000 4.000000 5.000000 6.000000
#3.000000 4.000000 5.000000 6.000000 7.000000
#4.000000 5.000000 6.000000 7.000000 8.000000
#5.000000 6.000000 7.000000 8.000000 9.000000
#6.000000 7.000000 8.000000 9.000000 10.000000
#7.000000 8.000000 9.000000 10.000000 11.000000
pp_mat(gewichtet(orig3))
#5.000000 4.333333 5.333333 6.333333 5.666667
#3.666667 3.000000 4.000000 5.000000 4.333333
#4.666667 4.000000 5.000000 6.000000 5.333333
#5.666667 5.000000 6.000000 7.000000 6.333333
#6.666667 6.000000 7.000000 8.000000 7.333333
#7.666667 7.000000 8.000000 9.000000 8.333333
#6.333333 5.666667 6.666667 7.666667 7.000000
| true |
0297d5b255204b758d3f86dc384f208809bf388d | Ruby | jluong214/ProjectEuler | /problem23.rb | UTF-8 | 1,580 | 4.1875 | 4 | [] | no_license | #A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
#A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
#As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
#Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
def sum_of_divisors(num)
return 1 if num == 1
array = []
(1...num).each do |div|
array.push div if num % div == 0
end
return array.reduce(:+)
end
def find_all_int()
result = []
abundant_numbers = []
(12..28123).each do |num|
abundant_numbers.push(num) if sum_of_divisors(num) > num
result.push num
end
abundant_numbers.each_with_index do |i, idx|
j = idx + 1
(j...abundant_numbers.size).each do |y|
sum = i + abundant_numbers[j]
break if sum >= 28123
result.delete(sum) if result.include? sum
j += 1
end
end
return result.reduce(:+)
end
find_all_int | true |
d885d4db226d9521c4cd31f33681d059535e3b33 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/1b5373b1a765460c9ab0992ea734e4fe.rb | UTF-8 | 504 | 3.71875 | 4 | [] | no_license | class Bob
def hey(message)
s = Statement.new(message)
case
when s.silent? then "Fine. Be that way!"
when s.forceful? then "Woah, chill out!"
when s.query? then "Sure."
else
"Whatever."
end
end
end
class Statement
def initialize(message)
@message = message
end
def forceful?
@message =~ /[A-Z]/ && @message.upcase == @message
end
def query?
@message.end_with?("?")
end
def silent?
@message.strip.empty? || nil
end
end
| true |
9b59d922f2cb5ca686996e4811f08277ec80e482 | Ruby | kojix2/charty | /test/vector/vector_equality_test.rb | UTF-8 | 2,845 | 2.765625 | 3 | [
"MIT"
] | permissive | class VectorEqualityTest < Test::Unit::TestCase
include Charty::TestHelpers
data(:adapter_type, [:array, :daru, :narray, :nmatrix, :numpy, :pandas], keep: true)
data(:other_adapter_type, [:array, :daru, :narray, :nmatrix, :numpy, :pandas], keep: true)
def test_equality(data)
vector = setup_vector(data[:adapter_type])
other_vector = setup_vector(data[:other_adapter_type])
assert_equal(vector, other_vector)
end
def test_equality_with_different_names(data)
vector = setup_vector(data[:adapter_type], name: "foo")
other_vector = setup_vector(data[:other_adapter_type], name: "bar")
assert_equal(vector, other_vector)
end
def test_unequality_by_values(data)
vector = setup_vector(data[:adapter_type])
other_vector = setup_vector(data[:other_adapter_type], [2, 3, 4, 5, 1])
assert_not_equal(vector, other_vector)
end
def test_unequality_by_index(data)
vector = setup_vector(data[:adapter_type])
other_vector = setup_vector(data[:other_adapter_type], index: [10, 20, 30, 40, 50])
assert_not_equal(vector, other_vector)
end
def setup_vector(adapter_type, data=nil, dtype=nil, index: nil, name: nil)
send("setup_vector_with_#{adapter_type}", data, dtype, index: index, name: name)
end
def setup_vector_with_array(data, _dtype, index:, name:)
data ||= default_data
Charty::Vector.new(data, index: index, name: name)
end
def setup_vector_with_daru(data, _dtype, index:, name:)
data ||= default_data
data = Daru::Vector.new(data)
Charty::Vector.new(data, index: index, name: name)
end
def setup_vector_with_narray(data, dtype, index:, name:)
numo_required
data ||= default_data
dtype ||= default_dtype
data = numo_dtype(dtype)[*data]
Charty::Vector.new(data, index: index, name: name)
end
def setup_vector_with_nmatrix(data, dtype, index:, name:)
nmatrix_required
data ||= default_data
dtype ||= default_dtype
data = NMatrix.new([data.length], data, dtype: dtype)
Charty::Vector.new(data, index: index, name: name)
end
def setup_vector_with_numpy(data, dtype, index:, name:)
numpy_required
data ||= default_data
dtype ||= default_dtype
data = Numpy.asarray(data, dtype: dtype)
Charty::Vector.new(data, index: index, name: name)
end
def setup_vector_with_pandas(data, dtype, index:, name:)
numpy_required
data ||= default_data
dtype ||= default_dtype
data = Pandas::Series.new(data, dtype: dtype)
Charty::Vector.new(data, index: index, name: name)
end
def default_data
[1, 2, 3, 4, 5]
end
def default_dtype
:int64
end
def numo_dtype(type)
case type
when :bool
Numo::Bit
when :int64
Numo::Int64
when :float64
Numo::DFloat
when :object
Numo::RObject
end
end
end
| true |
c3569de28407305dd8ee80a82922ea5e674f1e2e | Ruby | tiy-dc-ror-2016-oct/notes | /3/1 monday/cli.rb | UTF-8 | 339 | 2.859375 | 3 | [] | no_license | require_relative "cohort"
require_relative "student"
oct_16 = Cohort.new
oct_16.add_student(Student.new("Ben"))
oct_16.add_student(Student.new("Allie"))
oct_16.add_student(Student.new("Alex"))
oct_16.add_student(Student.new("Farimah"))
picked_student = oct_16.fairly_pick_a_student!
puts picked_student.name
# lambda {}
# -> do end
| true |
81f1e71f123e92e95a826d4693771d83b733cd93 | Ruby | zachchao/hw-ruby-intro | /lib/ruby_intro.rb | UTF-8 | 1,508 | 4 | 4 | [] | no_license | # When done, submit this entire file to the autograder.
# Part 1
def sum arr
arr.sum
end
def max_2_sum arr
if arr.length <= 1
return arr.sum
end
m1 = arr.max
arr.delete_at(arr.index(m1))
m1 + arr.max
end
def sum_to_n? arr, n
if arr.length <= 1
return false
end
for i in 0..arr.length - 1
for j in 0..arr.length - 1
if i != j and arr[i] + arr[j] == n
return true
end
end
end
false
end
# Part 2
def hello(name)
"Hello, #{name}"
end
def starts_with_consonant? s
if s.length == 0
return false
end
"bcdfghjklmnpqrstvwxyz".split(//).include? s.downcase[0]
end
def binary_multiple_of_4? s
if s.length == 0
return false
end
as_array = s.split(//)
total = 0
for i in 0..as_array.length - 1
if !['0', '1'].include? as_array[i]
return false
end
if as_array[i] == '0'
total *= 2
elsif as_array[i] == '1'
total = total * 2 + 1
end
end
total % 4 == 0
end
# Part 3
class BookInStock
def initialize(isbn, price)
if isbn == "" or price <= 0
raise ArgumentError, "invalid"
end
@isbn = isbn
@price = price
end
def isbn
@isbn
end
def price
@price
end
def isbn=(isbn)
@isbn = isbn
end
def price=(price)
@price = price
end
def price_as_string
res = @price.to_s.split(/\./)
if res[1] == nil
cents = "00"
else
cents = res[1].ljust(2, '0')
end
res = res[0] + "." + cents
"$#{res}"
end
end
| true |
4eeaf6d265d9865cc6ac82b403b835f8200f9957 | Ruby | ckib16/drills | /z_past_practice/2017-09/2017-09-04.rb | UTF-8 | 454 | 3.09375 | 3 | [] | no_license | class Board
def initialize(board)
puts "-#{board[0]}-|-#{board[1]}-|-#{board[2]}-"
puts "-#{board[3]}-|-#{board[4]}-|-#{board[5]}-"
puts "-#{board[6]}-|-#{board[7]}-|-#{board[8]}-"
end
def update_board(board)
puts "-#{board[0]}-|-#{board[1]}-|-#{board[2]}-"
puts "-#{board[3]}-|-#{board[4]}-|-#{board[5]}-"
puts "-#{board[6]}-|-#{board[7]}-|-#{board[8]}-"
end
end
board = []
board << 'x'
board << 'x'
Board.new(board) | true |
c556b299c20ac6b8122ba7ea47211df26d021cb7 | Ruby | aspose-imaging/Aspose.Imaging-for-Java | /Plugins/Aspose_Imaging_Java_for_Ruby/lib/asposeimagingjava/images/convertingrasterimages.rb | UTF-8 | 2,484 | 3.0625 | 3 | [
"MIT"
] | permissive | module Asposeimagingjava
module ConvertingRasterImages
def initialize()
# Binarization with Fixed Threshold
binarization_with_fixed_threshold()
# Binarization with Otsu Threshold
binarization_with_otsu_threshold()
# Transform image to its grayscale representation
transform_image_to_grayscale()
end
def binarization_with_fixed_threshold()
data_dir = File.dirname(File.dirname(File.dirname(File.dirname(__FILE__)))) + '/data/'
# Load an existing image
image = Rjb::import('com.aspose.imaging.Image').load(data_dir + "test.jpg")
# Check if image is cached
if !image.isCached()
# Cache image if not already cached
image.cacheData()
end
# Binarize image with predefined fixed threshold
image.binarizeFixed(100)
# Save the image to disk
image.save(data_dir + "binarization_with_fixed_threshold.jpg")
# Display Status.
puts "Binarization image with Fixed Threshold successfully!"
end
def binarization_with_otsu_threshold()
data_dir = File.dirname(File.dirname(File.dirname(File.dirname(__FILE__)))) + '/data/'
# Load an existing image
image = Rjb::import('com.aspose.imaging.Image').load(data_dir + "test.jpg")
# Check if image is cached
if !image.isCached()
# Cache image if not already cached
image.cacheData()
end
# Binarize image with Otsu Thresholding
image.binarizeOtsu()
# Save the image to disk
image.save(data_dir + "binarization_with_otsu_threshold.jpg")
# Display Status.
puts "Binarization image with Otsu Threshold successfully!"
end
def transform_image_to_grayscale()
data_dir = File.dirname(File.dirname(File.dirname(File.dirname(__FILE__)))) + '/data/'
# Load an existing image
image = Rjb::import('com.aspose.imaging.Image').load(data_dir + "test.jpg")
# Check if image is cached
if !image.isCached()
# Cache image if not already cached
image.cacheData()
end
# Transform image to its grayscale representation
image.grayscale()
# Save the image to disk
image.save(data_dir + "transform_image_to_grayscale.jpg")
# Display Status.
puts "Transform image to its grayscale representation successfully!"
end
end
end
| true |
cefe9a9f186588566af8c1584292ece2b2668e16 | Ruby | markhyams/coding-fun | /leetcode/0082_remove_dups2.rb | UTF-8 | 968 | 3.46875 | 3 | [] | no_license | # Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @return {ListNode}
# DH->1->1
# p
# c
#
#
#
# 3 pointers, prev, current
# add a dummy head, since head can change
# while next
# prev = dh
# current = head
#
# is current.val == current.next.val?
# store val
# move current until val != stored val
# prev points to current
def delete_duplicates(head)
return nil if head.nil?
dummy = ListNode.new('dummy')
dummy.next = head
prev = dummy
current = head
while current && current.next
if current.val != current.next.val
prev = prev.next
current = current.next
else
dup = current.val
while current && current.val == dup
current = current.next
end
prev.next = current
end
end
dummy.next
end | true |
780e9a6d58a70efbcbcaca2a5cc5a7f6b749c882 | Ruby | vladutclp/Depot_Application | /app/models/concerns/current_cart.rb | UTF-8 | 440 | 2.84375 | 3 | [] | no_license | module CurrentCart
private
'The set_cart method starts by getting the :cart_id from the session object and then attempts
to find a cart corresponding to this ID. If the cart is not found, this method will create a new Cart
and then store the ID of the created cart into the session'
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
end | true |
48dd9a5400371b5fa31d38055830443b3a1b3d55 | Ruby | madmax/ruby_php_session | /spec/php_session/encoder_spec.rb | UTF-8 | 3,270 | 2.5625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
require 'spec_helper'
require 'date'
describe PHPSession::Encoder do
describe ".encode" do
context "when given string value" do
it "should return 'KEY|SERIALIZED_STRING'" do
expect(
PHPSession::Encoder.encode({:hoge => "nyan"})
).to eq('hoge|s:4:"nyan";')
end
end
context "when given multi string value" do
it "should return 'KEY|SERIALIZED_STRING'" do
expect(
PHPSession::Encoder.encode({:hoge => "テスト"})
).to eq('hoge|s:9:"テスト";')
end
end
context "when given multi string value with external encoding" do
it "should return 'KEY|SERIALIZED_STRING'" do
expect(
PHPSession::Encoder.encode({:hoge => "テスト🍣"}, "EUC-JP", {:undef => :replace})
).to eq('hoge|s:7:"テスト?";'.encode('EUC-JP'))
end
end
context "when given int value" do
it "should return 'KEY|SERIALIZED_INT" do
expect(
PHPSession::Encoder.encode({:hoge => 1})
).to eq ('hoge|i:1;')
end
end
context "when given double value" do
it "should return 'KEY|DOUBLE|'" do
expect(
PHPSession::Encoder.encode({:hoge => 1.1})
).to eq('hoge|d:1.1;')
end
end
context "when given nil value" do
it "should return 'KEY|N;'" do
expect(
PHPSession::Encoder.encode({:hoge => nil})
).to eq('hoge|N;')
end
end
context "when given boolean value" do
it "should return 'KEY|b:(0|1);'" do
expect(
PHPSession::Encoder.encode({:hoge => true})
).to eq('hoge|b:1;')
expect(
PHPSession::Encoder.encode({:hoge => false})
).to eq('hoge|b:0;')
end
end
context "when given hash value" do
it "should return 'KEY|a:SIZE:ARRAY'" do
expect(
PHPSession::Encoder.encode({:hoge => {:a => 1,:b => 2,:c => 3}})
).to eq('hoge|a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";i:3;}')
end
end
context "when given array value" do
it "should return 'KEY|a:SIZE:ARRAY'" do
expect(
PHPSession::Encoder.encode({:hoge => [1, 2, 3]})
).to eq('hoge|a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}')
end
end
context "when given Struct" do
it "should return 'KEY|o:CLASSNAME_SIZE:PROPERTIES_SIZE:{PROPERTIES_AND_VALUES}'" do
piyo = Struct.const_defined?(:Test) ? Struct.const_get(:Test) : Struct.new("Test", :p1, :p2)
expect(
PHPSession::Encoder.encode(:hoge => piyo.new(1, 2))
).to eq('hoge|o:4:"Test":2:{s:2:"p1";i:1;s:2:"p2";i:2;}')
end
end
context "when given nested value" do
it "should return nested serialized string" do
hash = {
:key => {
:hoge => {
:fuga => "nyan"
}
}
}
expect(
PHPSession::Encoder.encode(hash)
).to eq('key|a:1:{s:4:"hoge";a:1:{s:4:"fuga";s:4:"nyan";}}')
end
end
context "when given other types" do
it "should raise EncodeError" do
expect {
PHPSession::Encoder.encode({:key => Date.today})
}.to raise_error PHPSession::Errors::EncodeError
end
end
end
end
| true |
473988b14cb4459f0d790905d4886dcddb998302 | Ruby | Proskurina/inject-challenge | /lib/my_inject.rb | UTF-8 | 1,519 | 3.546875 | 4 | [] | no_license | class MyArray < Array
def my_inject(initial = nil, sym=nil, &block)
dup = self.dup
if initial == nil
initial = dup.shift
#When there is no block and only one argument,
#this argument is assigned to initial.
#but I need it to be symbol.
#The next 4 lines is the only way I could find to deal with it.
#Any advise is highly appreciated
elsif !block && (initial.is_a? Symbol)
sym = initial
initial = dup.shift
end
if block
dup.each {|el| initial = block.call(initial, el)}
initial
elsif sym
dup.each {|el| initial = initial.send(sym, el)}
initial
else
fail "ERROR!"
end
end
def my_inject_rec(initial=nil,sym=nil,index=0,&block)
if initial == nil
initial = self[0]
index+=1
elsif !block && (initial.is_a? Symbol)
sym = initial
initial = self[0]
index+=1
end
if block
inject_with_block_rec(initial, index, &block)
elsif sym
inject_with_sym_rec(initial, sym, index)
else
fail "ERROR!"
end
end
private
def inject_with_block_rec(initial,index=0,&block)
if size == index
initial
else
initial = block.call(initial, self[index])
inject_with_block_rec(initial,index+1, &block)
end
end
def inject_with_sym_rec(initial, sym, index=0)
if size == index
initial
else
initial = initial.send(sym, self[index])
inject_with_sym_rec(initial, sym, index+1)
end
end
end
| true |
1e49432a6e112e30506cb017796040e5a02919b4 | Ruby | evansenter/wrnap | /lib/wrnap/package/heat.rb | UTF-8 | 365 | 2.578125 | 3 | [
"MIT"
] | permissive | module Wrnap
module Package
class Heat < Base
attr_reader :specific_heats
def post_process
@specific_heats = response.split(/\n/).map { |line| line.split(/\s+/).map(&:to_f) }.inject({}) do |hash, (temp, specific_heat)|
hash.tap do
hash[temp] = specific_heat
end
end
end
end
end
end
| true |
cf1e3409f9a4e8e0a79258d114f3f34b5b85c1a4 | Ruby | redfit/hiki | /hiki/repos/plain.rb | UTF-8 | 2,411 | 2.5625 | 3 | [] | no_license | require 'hiki/repos/default'
require 'fileutils'
module Hiki
class HikifarmReposPlain < HikifarmReposBase
def setup
Dir.mkdir(@root) if not File.exists?(@root)
end
def imported?(wiki)
File.directory?("#{@root}/#{wiki}")
end
def import(wiki)
FileUtils.mkdir("#{@root}/#{wiki}")
Dir.glob("#{@data_root}/#{wiki}/text/*") do |orig|
orig.untaint
FileUtils.mkdir("#{@root}/#{wiki}/#{File.basename(orig)}")
FileUtils.cp(orig, "#{@root}/#{wiki}/#{File.basename(orig)}/1")
end
File.open("#{@data_root}/#{wiki}/text/.wiki", 'w') do |f|
f.print wiki
end
end
def update(wiki)
raise NotImplementedError
end
end
class ReposPlain < ReposBase
include Hiki::Util
def commit(page, log = nil)
wiki = File.read("#{@data_path}/text/.wiki")
dir = "#{@root}/#{wiki.untaint}/#{escape(page).untaint}"
Dir.mkdir(dir) if not File.exists?(dir)
FileUtils.rm("#{dir}/.removed", {:force => true})
rev = last_revision(page) + 1
FileUtils.cp("#{@data_path}/text/#{escape(page).untaint}", "#{dir}/#{rev}")
end
def delete(page, log = nil)
wiki = File.read("#{@data_path}/text/.wiki")
File.open("#{@root}/#{wiki.untaint}/#{escape(page).untaint}/.removed", 'w'){|f|}
end
def rename(old_page, new_page)
wiki = File.read("#{@data_path}/text/.wiki")
old_dir = "#{@root}/#{wiki.untaint}/#{escape(old_page).untaint}"
new_dir = "#{@root}/#{wiki.untaint}/#{escape(new_page).untaint}"
# TODO raise custom exception
raise if File.exist?(new_dir)
FileUtils.mv(old_dir, new_dir)
end
def get_revision(page, revision)
wiki = File.read("#{@data_path}/text/.wiki")
File.read("#{@root}/#{wiki.untaint}/#{escape(page).untaint}/#{revision.to_i}")
end
def revisions(page)
wiki = File.read("#{@data_path}/text/.wiki")
revs = []
Dir.glob("#{@root}/#{wiki.untaint}/#{escape(page).untaint}/*").each do |file|
revs << [File.basename(file).to_i, File.mtime(file.untaint).localtime.to_s, '', '']
end
revs.sort_by{|e| -e[0]}
end
private
def last_revision(page)
wiki = File.read("#{@data_path}/text/.wiki")
Dir.glob("#{@root}/#{wiki.untaint}/#{escape(page).untaint}/*").map{|f| File.basename(f)}.sort_by{|f| -f.to_i}[0].to_i
end
end
end
| true |
b9a18183b486f2423a7229f91174a6ad2c090d25 | Ruby | ChristopherDurand/Exercises | /ruby/small-problems/medium2/e05.rb | UTF-8 | 589 | 3.796875 | 4 | [
"MIT"
] | permissive |
def valid_triangle?(a, b, c)
a, b, c = [a, b, c].sort
a > 0 && b > 0 && c > 0 && a + b > c
end
def triangle(a, b, c)
if valid_triangle?(a, b, c)
sides = Hash.new(0)
[a, b, c].each { |n| sides[n] += 1 }
num_same = sides.max_by { |length, ct| ct }[1]
case num_same
when 1 then :scalene
when 2 then :isosceles
when 3 then :equilateral
end
else
:invalid
end
end
puts triangle(3, 3, 3) == :equilateral
puts triangle(3, 3, 1.5) == :isosceles
puts triangle(3, 4, 5) == :scalene
puts triangle(0, 3, 3) == :invalid
puts triangle(3, 1, 1) == :invalid | true |
00e67b23d68df7dc16abe205270aafe3ab0492f0 | Ruby | chi-grasshoppers-2015/StackOverthrow | /app/helpers/users_helper.rb | UTF-8 | 1,197 | 2.640625 | 3 | [] | no_license | helpers do
def logged_in?
session[:uid]
end
def current_user
User.find(session[:uid])
end
def user_is_author(user_id)
current_user.id == user_id
end
def ad_generator
ad_num = [*1..6].sample
case ad_num
when 1
"<h5>Nickle ads</h5>
<p>Need to spend extra money?</p>
<p>Email at nbkincaid@gmail.com for ways to get rid of excess cash.</p>"
when 2
"<h5>Jasmine ads</h5>
<p>Have extra cute puppies?</p>
<p>Email at Jasmine@heroforhire.com for ways to get rid of excess pups.</p>"
when 3
"<h5>Spencer FOR HIRE</h5>
<p>Need to win an ultimate epic tournament of sorts?</p>
<p>Email at Spencer@netscape.net for ways to destroy the competition. BROTHER!</p>"
when 4
"<h5>Matt ads</h5>
<p>Bad shoulders?</p>
<p>Email at MATT@gmail.com for ways to drunkenly pop that arm back in the socket.</p>"
when 5
"<h5>Connor ads</h5>
<p>Got chicken brah?</p>
<p>Email at connor@chickens4lyfe.com for eggselent ways to give up those chickens brahhhhh.</p>"
when 6
"<h5>Connorle ads</h5>
<p>Need to spend extra money on misspellings</p>
<p>Email at ccring@gmail.com for ways to get rid of excess spell checks.</p>"
end
end
end
| true |
272c6d3fee6db268c034d9d475eaf9f157416f5c | Ruby | jacobdmartin/RoleModel_Prep_Work | /Intro-to-Ruby/ping-pong/lib/ping_pong.rb | UTF-8 | 238 | 3.21875 | 3 | [] | no_license | class ChangeNum
def ping_pong
arr = []
c=1
self.times do
if c%3 == 0
arr.push('ping')
elsif c%5 == 0
arr.push('pong')
else
arr.push(c)
end
c+=1
end
arr
end
end
| true |
594c528ab5eb49edf67d7804fec898e23c7934f2 | Ruby | 1debit/json_api_client | /lib/json_api_client/utils.rb | UTF-8 | 852 | 2.734375 | 3 | [
"MIT"
] | permissive | module JsonApiClient
module Utils
def self.compute_type(klass, type_name)
# If the type is prefixed with a scope operator then we assume that
# the type_name is an absolute reference.
return type_name.constantize if type_name.match(/^::/)
# Build a list of candidates to search for
candidates = []
klass.name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
candidates << type_name
candidates.each do |candidate|
begin
constant = candidate.constantize
return constant if candidate == constant.to_s
rescue NameError => e
# We don't want to swallow NoMethodError < NameError errors
raise e unless e.instance_of?(NameError)
end
end
raise NameError, "uninitialized constant #{candidates.first}"
end
end
end | true |
9975c4a42c94aa6af64f5022166126251f00181c | Ruby | FedericoEsparza/after_11_pm | /spec/models/trigonometry/functions/sine_spec.rb | UTF-8 | 783 | 3.59375 | 4 | [] | no_license | describe Sine do
describe '#initialize' do
it 'initialise with angle in degrees' do
exp = sin(60)
expect(exp.angle).to eq 60
end
it 'can init with array' do
exp = sin([60])
expect(exp.angle).to eq 60
end
end
describe 'setters for angle' do
it 'setter for angle' do
exp = sin(60)
exp.angle = 70
expect(exp.angle).to eq 70
end
end
describe '#evaluate_numeral' do
it 'evaluates sin(30)' do
expect(sin(30).evaluate_numeral).to eq 0.5
end
it 'evaluates sin(60) to 0.86603 (we make surds later!)' do
expect(sin(60).evaluate_numeral).to eq 0.86603
end
end
describe '#~' do
it 'return true' do
exp = sin('x')
expect(exp.~(sin('x'))).to be true
end
end
end
| true |
6c62a592259ad3db46aa5537dd6165dd71998e0d | Ruby | rossmari/AccordionMan | /lib/message/processor.rb | UTF-8 | 879 | 2.734375 | 3 | [] | no_license | class Message::Processor
class << self
def process(message)
parsed_message = message(message)
parsed_message.user = Message::UserParser.parse(message.from)
links = Message::LinkParser.parse(message.text)
# check links on accordion alert and save them if all is safe
check_links(links, message.from)
# attach links to parsed message in db
parsed_message.links << links
parsed_message.save
end
private
def message(message)
Message.new(content: message.text, posted_at: message.date)
end
# todo : move save to another place
def check_links(links, user)
links.each do |link|
matches = Link::AccordionChecker.find_matches(link)
unless matches.empty?
Link::AccordionMessenger.send(link, user, matches)
end
link.save
end
end
end
end | true |
34fa97784b02d7fbcabcf88163f19ef67dd03050 | Ruby | gouf/pry-theme | /spec/rgb_spec.rb | UTF-8 | 2,625 | 3.171875 | 3 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'helper'
describe PryTheme::RGB do
RGB = PryTheme::RGB
it "accepts Array as an argument" do
lambda { RGB.new([0, 0, 0]) }.should.not.raise
end
it "doesn't accept malformed Arrays" do
lambda { RGB.new([0, 0, 0, 0]) }.should.raise ArgumentError
lambda { RGB.new([256, 256, 256]) }.should.raise ArgumentError
lambda { RGB.new([:one, 256, 256]) }.should.raise ArgumentError
end
it "accepts String as an argument" do
lambda { RGB.new('0, 0, 0') }.should.not.raise
end
it "doesn't accept malformed Strings" do
lambda { RGB.new('0, 0, 0, 0') }.should.raise ArgumentError
lambda { RGB.new('256, 256, 256') }.should.raise ArgumentError
lambda { RGB.new('256, heaven, 256') }.should.raise ArgumentError
end
it "raises error if gibberish is given as an argument" do
lambda { RGB.new('jeyenne') }.should.raise ArgumentError
lambda { RGB.new(:jeyenne) }.should.raise TypeError
end
it "converts itself to term 256" do
RGB.new([0, 0, 0]).to_term.to_i.should == 0
RGB.new('255, 255, 255').to_term.to_i.should == 15
end
it "converts itself to term 256 and determines the nearest term colour" do
RGB.new('21, 24, 205').to_term.to_i.should == 20
RGB.new('210, 240, 20').to_term.to_i.should == 191
end
it "converts itself to term 16" do
RGB.new([0, 0, 0]).to_term(16).to_i.should == 0
RGB.new([255, 255, 255]).to_term(16).to_i.should == 15
RGB.new([255, 0, 255]).to_term(16).to_i.should == 13
end
it "converts itself to and determines the nearest term colour" do
RGB.new([0, 101, 69]).to_term(16).to_i.should == 1
end
it "converts itself to term 8" do
RGB.new([0, 0, 0]).to_term(8).to_i.should == 0
RGB.new([255, 255, 255]).to_term(8).to_i.should == 0
RGB.new([255, 0, 255]).to_term(8).to_i.should == 0
end
it "converts itself to and determines the nearest term colour" do
RGB.new([0, 101, 69]).to_term(16).to_i.should == 1
RGB.new([122, 122, 122]).to_term(8).to_i.should == 3
RGB.new([176, 127, 30]).to_term(8).to_i.should == 4
end
it "converts itself to hex" do
RGB.new([0, 0, 0]).to_hex.to_s.should == '#000000'
RGB.new([255, 255, 255]).to_hex.to_s.should == '#ffffff'
end
it "represents itself as a String" do
RGB.new([0, 0, 0]).to_s.should == '0, 0, 0'
RGB.new('0, 0, 0').to_s.should == '0, 0, 0'
end
it "represents itself as an Array" do
RGB.new([0, 0, 0]).to_a.should == [0, 0, 0]
RGB.new('0, 0, 0').to_a.should == [0, 0, 0]
end
it "represents itself in CSS format" do
RGB.new([0, 0, 0]).to_css.should == 'rgb(0, 0, 0)'
end
end
| true |
c31a24dcaa66bd36dcc0c001c0b7980b1b711b3e | Ruby | telefactor/telefactor-fam-sourcerer-two | /spec/fam/family_spec.rb | UTF-8 | 6,727 | 2.65625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Fam::Family do
let(:family) { described_class.new }
before do
family.add_person(person_name: 'Bobby')
family.add_person(person_name: 'Hank')
family.add_person(person_name: 'Peggy')
family.add_person(person_name: 'Bill')
end
context '.add_parents' do
subject { family.add_parents(child_name: child_name, parent_names: parent_names) }
describe 'no inputs' do
let(:child_name) { }
let(:parent_names) { }
it 'errors with NoSuchPerson' do
expect { subject }.to raise_error(::Fam::Family::Errors::NoSuchPerson)
end
end
describe 'add child with too many parents' do
let(:child_name) { 'Bobby' }
let(:parent_names) { ['Hank', 'Peggy', 'Bill'] }
it 'errors with TooManyParents' do
expect { subject }.to raise_error(::Fam::Family::Errors::TooManyParents)
end
end
describe 'add child with 2 parents' do
let(:child_name) { 'Bobby' }
let(:parent_names) { ['Hank', 'Peggy'] }
it 'adds child with 2 parents' do
subject
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => ['Hank', 'Peggy'],
'Hank' => [],
'Peggy' => [],
}
)
end
end
describe 'add child with 1 parents' do
let(:child_name) { 'Bobby' }
let(:parent_names) { ['Hank'] }
it 'adds child with 1 parent' do
subject
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => ['Hank'],
'Hank' => [],
'Peggy' => [],
}
)
end
end
describe 'add child with no parents' do
let(:child_name) { 'Bobby' }
let(:parent_names) { [] }
it 'does not add parent' do
subject
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => [],
'Hank' => [],
'Peggy' => [],
}
)
end
end
describe 'add child with 1 parent and then add 2nd parent' do
subject do
family.add_parents(child_name: child_name, parent_names: first_parent_name)
family.add_parents(child_name: child_name, parent_names: second_parent_name)
end
let(:child_name) { 'Bobby' }
let(:first_parent_name) { ['Hank'] }
let(:second_parent_name) { ['Peggy'] }
it 'adds child with 2 parents' do
subject
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => ['Hank', 'Peggy'],
'Hank' => [],
'Peggy' => [],
}
)
end
end
end
context '.get_parents' do
subject { family.get_parents(child_name: child_name, generations: generations) }
describe 'no inputs' do
let(:child_name) {}
let(:generations) {}
it 'errors with NoSuchPerson' do
expect { subject }.to raise_error(::Fam::Family::Errors::NoSuchPerson)
end
end
describe 'get parents of child with 2 parents' do
let(:child_name) { 'Bobby' }
let(:generations) { 0 }
before do
family.add_parents(child_name: 'Bobby', parent_names: ['Hank', 'Peggy'])
end
it 'gets 2 parents' do
expect(subject).to eq(['Hank', 'Peggy'])
end
end
describe 'get parents of child with 1 parents' do
let(:child_name) { 'Bobby' }
let(:generations) { 0 }
before do
family.add_parents(child_name: 'Bobby', parent_names: ['Hank'])
end
it 'gets 1 parent' do
expect(subject).to eq(['Hank'])
end
end
describe 'get parents of child with no parents' do
let(:child_name) { 'Bobby' }
let(:generations) { 0 }
before do
family.add_parents(child_name: 'Bobby', parent_names: [])
end
it 'gets no parent' do
expect(subject).to eq([])
end
end
describe 'get 2st generation parents of child with 2 parents' do
let(:child_name) { 'Bobby' }
let(:generations) { 1 }
before do
family.add_person(person_name: 'Cotton')
family.add_person(person_name: 'Peggy\'s dad')
family.add_person(person_name: 'Hank\'s mom')
family.add_person(person_name: 'Peggy\'s mom')
family.add_parents(child_name: 'Hank', parent_names: ['Cotton', 'Hank\'s mom'])
family.add_parents(child_name: 'Peggy', parent_names: ['Peggy\'s dad', 'Peggy\'s mom'])
family.add_parents(child_name: 'Bobby', parent_names: ['Hank', 'Peggy'])
end
it 'gets 2nd generation of parents' do
expect(subject).to eq(['Cotton', "Hank's mom", "Peggy's dad", "Peggy's mom"])
end
end
end
context '.add_person' do
subject { family.add_person(person_name: person_name) }
describe 'no inputs' do
let(:person_name) { }
it 'adds nil' do
expect(subject).to eq(nil)
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => [],
'Hank' => [],
'Peggy' => [],
nil => [],
}
)
end
end
describe 'add existing person' do
let(:person_name) { 'Bobby' }
it 'errors with DuplicatePerson' do
expect { subject }.to raise_error(::Fam::Family::Errors::DuplicatePerson)
end
end
describe 'add new person' do
let(:person_name) { 'Luanne' }
it 'adds Luanne' do
expect(subject).to eq(person_name)
expect(family.to_hash).to eq(
{
'Bill' => [],
'Bobby' => [],
'Hank' => [],
'Luanne' => [],
'Peggy' => [],
}
)
end
end
end
context '.get_person' do
subject { family.get_person(person_name: person_name) }
describe 'no inputs' do
let(:person_name) { }
it 'errors with NoSuchPerson' do
expect { subject }.to raise_error(::Fam::Family::Errors::NoSuchPerson)
end
end
describe 'get existing person' do
let(:person_name) { 'Bobby' }
it 'returns Bobby' do
expect(subject).to eq(person_name)
end
end
describe 'get person no in family' do
let(:person_name) { 'Sarah' }
it 'errors with NoSuchPerson' do
expect { subject }.to raise_error(::Fam::Family::Errors::NoSuchPerson)
end
end
end
context '.to_hash' do
subject { family.to_hash }
it 'displays family as hash' do
expect(subject).to eq(
{
'Bill' => [],
'Bobby' => [],
'Hank' => [],
'Peggy' => [],
}
)
end
end
end
| true |
458d10026d4daf9948b4b42f247c56df70f866e2 | Ruby | SOWMYANARAYANA/ruby-practice | /file.rb | UTF-8 | 301 | 2.625 | 3 | [] | no_license | # aFile = File.new("input.txt", "r+")
# if aFile
# content = aFile.syswrite("niki")
# aFile.each_byte {|ch| putc ch; putc ?. }
# puts content
# else
# puts "Unable to open file!"
# end
a=[1,2,3,4]
h=Hash[*a]
puts h
a=[1,2,3,4]
p a=Array.new(5){Array.new(10){|index|}.map if{|i|i=even}} | true |
1c3f55e99eb3763bec5eaf5d61799f7dcfcd6bbe | Ruby | mdbhuiyan/w2d1 | /Chess/piece.rb | UTF-8 | 441 | 3.203125 | 3 | [] | no_license | require_relative 'board.rb'
require 'colorize'
class Piece
attr_reader :name, :color, :board
# def initialize(name, color)
def initialize(color, board, position)
@color = color
@board = board
@position = board.add_piece(self, position)
end
def to_s
symbol.colorize(color)
end
def symbol
end
# def to_s
# @name.colorize(color)
# end
def inspect
@name.inspect
end
def moves
end
end
| true |
0c81b256344f4c2f231d383df89227f7f8fb864d | Ruby | qbl/electives-solid-exercise | /ocp/shape_calculator.rb | UTF-8 | 269 | 3.28125 | 3 | [] | no_license | class ShapeCalculator
def initialize
end
def calculate_area(shape)
area = 0
if shape.name == "rectangle"
area = shape.width * shape.length
elsif shape.name == "triangle"
area = shape.base * shape.height * 0.5
end
area
end
end
| true |
210b72a15e840164341b80e49728872667854900 | Ruby | jtmr/lifecrawler | /lifecrawler.rb | UTF-8 | 1,801 | 2.609375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
require 'mechanize'
require 'httpclient'
sleep_sec = 5
agent = Mechanize.new
page = agent.get('http://www.tbsradio.jp/life/themearchive.html')
page.search('h5>a').each do |themes_link|
theme_dir = themes_link.text.gsub('/', '_')
FileUtils.mkdir(theme_dir) unless Dir.exist?(theme_dir)
puts 'テーマ: ' + theme_dir
current_theme = themes_link.attr('href')
theme = agent.get(current_theme)
theme.search('div.entry').each do |entry|
title = entry.search('h3').text.gsub('/', '_')
url = ''
entry.search('div.entry-body a').each do |link|
if link.attr('href') =~ /mp3$/
url = link.attr('href')
break
end
end
next if url.empty?
# download mp3
puts '次のパートをダウンロード: ' + title
hc = HTTPClient.new
hc.receive_timeout = 3000
local_mp3 = File.join(theme_dir, title + '.mp3')
start_time = Time.now
content_length = hc.head(url).header['Content-Length'][0].to_i
local_length = 0
local_length = File.size(local_mp3) if File.exist?(local_mp3)
puts " ファイルサイズ(ローカル/サーバ): #{local_length} / #{content_length}"
if File.exist?(local_mp3) and local_length == content_length then
puts 'ダウンロード済: ' + title
else
File.open(local_mp3, 'w+b') do |file|
begin
hc.get_content(url) do |chunk|
file << chunk
end
rescue HTTPClient::BadResponseError
nil
end
end
download_sec = Time.now - start_time
puts 'ダウンロード完了: ' + title
puts "経過秒数: #{download_sec}秒"
puts "待機: #{sleep_sec}秒"
sleep sleep_sec
end
end
puts "待機: #{sleep_sec}秒"
sleep sleep_sec
puts
end
| true |
1569c711804fb901ca0f8e7da3dabf2a9ad8cec7 | Ruby | mcdermottjesse/Ruby-Exercises | /pig_latin.rb | UTF-8 | 246 | 4.03125 | 4 | [] | no_license | def pigLatin(string)
vowels = ["a", "e", "i", "o", "u"]
if vowels.include? string[0]
string + 'ay'
else
consonant = string[0]
new_word = string[1..-1]
"#{new_word}#{consonant}ay"
end
end
puts pigLatin("apple")
puts pigLatin("jesse") | true |
d7ab0bb80ab7883cbd08853c6e23343520934aea | Ruby | cappetta/CyberCloud | /puppet/modules/stdlib/spec/functions/join_keys_to_values_spec.rb | UTF-8 | 1,494 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | #! /usr/bin/env ruby -S rspec
require 'spec_helper'
describe "the join_keys_to_values function" do
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
it "should exist" do
expect(Puppet::Parser::Functions.function("join_keys_to_values")).to eq("function_join_keys_to_values")
end
it "should raise a ParseError if there are fewer than two arguments" do
expect { scope.function_join_keys_to_values([{}]) }.to raise_error Puppet::ParseError
end
it "should raise a ParseError if there are greater than two arguments" do
expect { scope.function_join_keys_to_values([{}, 'foo', 'bar']) }.to raise_error Puppet::ParseError
end
it "should raise a TypeError if the first argument is an array" do
expect { scope.function_join_keys_to_values([[1,2], ',']) }.to raise_error TypeError
end
it "should raise a TypeError if the second argument is an array" do
expect { scope.function_join_keys_to_values([{}, [1,2]]) }.to raise_error TypeError
end
it "should raise a TypeError if the second argument is a number" do
expect { scope.function_join_keys_to_values([{}, 1]) }.to raise_error TypeError
end
it "should return an empty array given an empty hash" do
result = scope.function_join_keys_to_values([{}, ":"])
expect(result).to eq([])
end
it "should join hash's keys to its values" do
result = scope.function_join_keys_to_values([{'a'=>1,2=>'foo',:b=>nil}, ":"])
expect(result).to match_array(['a:1','2:foo','b:'])
end
end
| true |
3222ea8f12dc70a29fb70b26445c801ee4d0fa61 | Ruby | meranly8/cartoon-collections-onl01-seng-pt-090820 | /cartoon_collections.rb | UTF-8 | 448 | 3.328125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(names)
names.each_with_index do |name, position|
puts "#{position + 1} #{name}"
end
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.collect {|element| element.capitalize + "!"}
end
def long_planeteer_calls(calls)
calls.any? { |call| call.length > 4}
end
def find_the_cheese(array)
cheese_types = ["cheddar", "gouda", "camembert"]
array.detect { |cheese| cheese_types.include?(cheese) }
end
| true |
b3389b96a51e020ad3f72c12311d7c4c9eb39602 | Ruby | rsupak/appacademy2020 | /SoftwareEngineeringFundamentals/rspec_exercise_4/lib/part_1.rb | UTF-8 | 480 | 3.375 | 3 | [] | no_license | def my_reject(arr, &prc)
new_arr = []
arr.each { |el| new_arr << el unless prc.call(el) }
new_arr
end
def my_one?(arr, &prc)
arr.count(&prc) == 1
end
def hash_select(hash, &prc)
new_hash = {}
hash.each { |k, v| new_hash[k] = v if prc.call(k, v) }
new_hash
end
def xor_select(arr, prc1, prc2)
arr.select do |el|
(prc1.call(el) || prc2.call(el)) && !(prc1.call(el) && prc2.call(el))
end
end
def proc_count(val, arr)
arr.count { |prc| prc.call(val) }
end
| true |
984596786996ef810ae4be10132a980cf71d62c2 | Ruby | elsonli/aA-classworks | /W6D5/ninety_nine_cats_project/app/models/cat.rb | UTF-8 | 530 | 2.609375 | 3 | [] | no_license | class Cat < ApplicationRecord
COLORS = [
"black",
"white",
"gray",
"hairless",
"blue",
"gold",
"red",
"rainbow",
"pizza",
"macandcheeseorange"
]
validates :birth_date, :color, :name, :sex, :description, presence: true
validates :color, inclusion: { in: COLORS }
validates :sex, inclusion: { in: ["M", "F"] }
def age
date = Date.today
birth_date = self.birth_date
year = date.year - birth_date.year
end
has_many :cat_rental_requests, dependent: :destroy
end
| true |
66dc101e3589c39e43799e05a975eb9791a66233 | Ruby | bramsey/euler-ruby | /prob40.rb | UTF-8 | 868 | 3.28125 | 3 | [] | no_license | #!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby
# problem: http://projecteuler.net/problem=40
def brute
str = '0'
1.upto(1000000) {|i| str += i.to_s}
prod = 1
mult = 1
while mult <= 1000000
prod *= str[mult].to_i
mult *= 10
end
prod
end
# start of optimization:
#1 * 1 * 5 * 3 * 7 * 2
def solve
str = ''
mult = 1
prod = 1
count = 0
1.upto(189555) do |i|
#str += i.to_s
if i > 100000
count += 6
elsif i > 10000 && i <= 100000
count += 5
elsif i > 1000 && i <= 10000
count += 4
elsif i > 100 && i <= 1000
count += 3
elsif i > 10 && i <= 100
count += 2
else
count += 1
end
puts "#{i}: #{count}"
if count >= mult
prod *= i
puts "#{mult}: #{prod} | #{i} | #{count}"
#mult *= 10
end
end
prod
end
puts brute
#puts solve | true |
3245dadc92ede9b59076755eed433e45ef15be43 | Ruby | wing-888/MOR_X5_FROM_VM | /upgrade/x4/sipchaning.rb | UTF-8 | 2,816 | 2.625 | 3 | [] | no_license | # Script by -Aurimas. S.- //2013//
require 'active_record'
require 'ipaddr'
require 'yaml'
# Configuration
ENV_DB = '/home/mor/config/database.yml'
DEBUG = ARGV.member?('-v')
FORCE = ARGV.member?('-f')
COLUMNS = %w{ peerip recvip sipfrom uri useragent peername t38passthrough }
# Exit handler
EXIT = Proc.new do |code, e, msg|
if DEBUG and (e or msg)
output = [msg, (e.message if e.respond_to? :message)].join
STDERR.puts "-- " << output
end
ActiveRecord::Base.remove_connection if ActiveRecord::Base.connected?
Kernel::exit! code
end
# network layer
begin
# Reading database config
DB = YAML::load(File.open(ENV_DB))
# Connecting to production database
ActiveRecord::Base.establish_connection(DB['production'])
rescue Exception => e
EXIT[1, e]
end
begin
# adding columns to call_details table
class Migrate < ActiveRecord::Migration; end
Migrate.verbose = DEBUG
Migrate.class_eval do
change_table :call_details do |t|
t.column :peerip, 'INT(10) unsigned '
t.column :recvip, 'INT(10) unsigned '
t.column :sipfrom, 'varchar(255)'
t.column :uri, 'varchar(255)'
t.column :useragent, 'varchar(255)'
t.column :peername, 'varchar(255)'
t.column :t38passthrough, 'tinyint(4)'
end
end
rescue Exception => e
e.message.include?("Duplicate column name") ? (EXIT[0] unless FORCE) : EXIT[1, e]
end
# DB integrity check
begin
# Creating models
class Call < ActiveRecord::Base
has_one :call_detail
end
class CallDetail < ActiveRecord::Base
belongs_to :call
end
# provoking exception
Call.first.blank?
CallDetail.first.blank?
rescue Exception => e
EXIT[1, e]
end
# moving data
begin
SIZE = Call.where("sipfrom != ''").count
index = 0
Call.where("sipfrom != ''").find_in_batches do |calls|
calls.each do |call|
details = call.call_detail
if details.blank?
details = CallDetail.new
details.call_id = call.id
end
COLUMNS.each do |column|
value = call[column.to_sym]
details[column.to_sym] = ['peerip','recvip'].member?(column) ? (IPAddr.new(value).to_i rescue nil) : value
end
details.save
perc = ((100.0/SIZE)*index).to_i
print "\r[#{['+','x'][index%2]}] #{perc}% call_details\r"
index = index.next
end
end
rescue Exception => e
e.message.include?('Unknown column') ? (EXIT[0, nil, "nothing changed"] unless FORCE) : EXIT[1, e]
end
# dropping columns from calls
#begin
# Migrate.class_eval do
# change_table(:calls) do |t|
# COLUMNS.each {|col| t.remove col.to_sym }
# end
# end
EXIT[0, nil, "done, #{SIZE} call_details updated/created"]
#rescue Exception => e
# e.message.include?('column/key exists') ? EXIT[0, nil, "nothing changed"] : EXIT[1, e]
#end
| true |
24444d8fd7fb8e770898c361fb0885326e3e21a0 | Ruby | postmodern/scm | /lib/scm/scm.rb | UTF-8 | 1,617 | 2.984375 | 3 | [
"MIT"
] | permissive | require 'scm/git'
require 'scm/hg'
require 'scm/svn'
require 'uri'
module SCM
# SCM control directories and the SCM classes
DIRS = {
'.git' => Git,
'.hg' => Hg,
'.svn' => SVN
}
# Common URI schemes used to denote the SCM
SCHEMES = {
'git' => Git,
'hg' => Hg,
'svn' => SVN,
'svn+ssh' => SVN
}
# Common file extensions used to denote the SCM of a URI
EXTENSIONS = {
'.git' => Git,
'.hg' => Hg,
'.svn' => SVN
}
#
# Determines the SCM used for a repository.
#
# @param [String] path
# The path of the repository.
#
# @return [Repository]
# The SCM repository.
#
# @raise [ArgumentError]
# The exact SCM could not be determined.
#
def SCM.new(path)
path = File.expand_path(path)
DIRS.each do |name,repo|
dir = File.join(path,name)
return repo.new(path) if File.directory?(dir)
end
raise(ArgumentError,"could not determine the SCM of #{path.dump}")
end
#
# Determines the SCM used for a repository URI and clones it.
#
# @param [URI, String] uri
# The URI to the repository.
#
# @param [Hash] options
# Additional SCM specific clone options.
#
# @return [Repository]
# The SCM repository.
#
# @raise [ArgumentError]
# The exact SCM could not be determined.
#
def SCM.clone(uri,options={})
uri = URI(uri) unless uri.kind_of?(URI)
scm = (SCHEMES[uri.scheme] || EXTENSIONS[File.extname(uri.path)])
unless scm
raise(ArgumentError,"could not determine the SCM of #{uri}")
end
return scm.clone(uri,options)
end
end
| true |
5c79214de472cf5d997b2d0d8ff70cf7f302452e | Ruby | jdaig/Maraton | /Online Store/Model.rb | UTF-8 | 609 | 2.578125 | 3 | [] | no_license |
class Store
def initialize
index_users
inventary
end
def inventary
CSV.foreach("Products.csv") do |product|
@list << Producto.new(product[0],product[1])
end
end
def index_users
CSV.foreach("User_Registrer.csv") do |usuario|
@list << User.new(usuario[0],usuario[1],usuario[2])
end
end
end
end
class User
attr_accessor :such, :email, :password
def initialize(such,email,password)
@such = such
@email = email
@password = password
end
end
class Administrator < User
end
class SalesMan < User
end
class Client < User
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.