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 |
---|---|---|---|---|---|---|---|---|---|---|---|
7d502bcf5cb242f8b12ca71d9c7cc4f6efce5bb2
|
Ruby
|
maynkj/valuta
|
/lib/valuta.rb
|
UTF-8
| 860 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
require_relative "valuta/version"
class Valuta
FORMAT = /(\d{3})(?=\d)/
SEPARATOR = ".".freeze
DEFAULTS = {
delimiter: ",",
separator: ".",
suffix: nil,
prefix: nil
}
def self.convert(number, options={})
return new(options).convert(number)
end
def initialize(options = {})
@options = DEFAULTS.merge(options)
end
def convert(number)
return "" if number.to_s.empty?
prefix = @options[:prefix]
suffix = @options[:suffix]
return [prefix, format(number.to_s), suffix].join
end
private
def format(str)
return parts(str.strip).join(@options[:separator])
end
def parts(str)
left, right = str.split(SEPARATOR)
if left.length > 3
left.reverse!
left.gsub!(FORMAT, "\\1#{ @options[:delimiter] }")
left.reverse!
end
return [left, right].compact
end
end
| true |
c1b38e614fd27de36c342eb67291be31270584c8
|
Ruby
|
SSDany/rack-acceptable
|
/lib/rack/acceptable/language_tag.rb
|
UTF-8
| 13,740 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
require 'rack/acceptable/utils'
module Rack #:nodoc:
module Acceptable #:nodoc:
# inspired by the 'langtag' gem (author: Martin Dürst)
# http://rubyforge.org/projects/langtag/
# http://www.langtag.net/
#
class LanguageTag
GRANDFATHERED_TAGS = {
'art-lojban' => 'jbo' ,
'cel-gaulish' => nil ,
'en-gb-oed' => nil ,
'i-ami' => 'ami' ,
'i-bnn' => 'bnn' ,
'i-default' => nil ,
'i-enochian' => nil ,
'i-hak' => 'hak' ,
'i-klingon' => 'tlh' ,
'i-lux' => 'lb' ,
'i-mingo' => nil ,
'i-navajo' => 'nv' ,
'i-pwn' => 'pwn' ,
'i-tao' => 'tao' ,
'i-tay' => 'tay' ,
'i-tsu' => 'tsu' ,
'no-bok' => 'nb' ,
'no-nyn' => 'nn' ,
'sgn-be-fr' => 'sfb' ,
'sgn-be-nl' => 'vgt' ,
'sgn-ch-de' => 'sgg' ,
'zh-guoyu' => 'cmn' ,
'zh-hakka' => 'hak' ,
'zh-min' => nil ,
'zh-min-nan' => 'nan' ,
'zh-xiang' => 'hsn'
}.freeze
attr_accessor :primary, :extlang, :script, :region, :variants, :extensions, :privateuse
attr_reader :length
#--
# RFC 5646, sec. 2.2.2:
# Although the ABNF production 'extlang' permits up to three
# extended language tags in the language tag, extended language
# subtags MUST NOT include another extended language subtag in
# their 'Prefix'. That is, the second and third extended language
# subtag positions in a language tag are permanently reserved and
# tags that include those subtags in that position are, and will
# always remain, invalid.
#++
language = '([a-z]{2,8}|[a-z]{2,3}(?:-[a-z]{3}){0,3})'
script = '(?:-([a-z]{4}))?'
region = '(?:-([a-z]{2}|\d{3}))?'
variants = '(?:-[a-z\d]{5,8}|-\d[a-z\d]{3})*'
extensions = '(?:-[a-wy-z\d]{1}(?:-[a-z\d]{2,8})+)*'
privateuse = '(?:-x(?:-[a-z\d]{1,8})+)?'
LANGTAG_COMPOSITION_REGEX = /^#{language}#{script}#{region}(?=#{variants}#{extensions}#{privateuse}$)/o.freeze
LANGTAG_INFO_REGEX = /^#{language}#{script}#{region}(#{variants})#{extensions}#{privateuse}$/o.freeze
PRIVATEUSE_REGEX = /^x(?:-[a-z\d]{1,8})+$/i.freeze
PRIVATEUSE = 'x'.freeze
class << self
# Checks if the +String+ passed represents a 'privateuse' Language-Tag.
# Works case-insensitively.
#
def privateuse?(tag)
PRIVATEUSE_REGEX === tag
end
# Checks if the +String+ passed represents a 'grandfathered' Language-Tag.
# Works case-insensitively.
#
def grandfathered?(tag)
GRANDFATHERED_TAGS.key?(tag) || GRANDFATHERED_TAGS.key?(tag.downcase)
end
# ==== Parameters
# langtag<String>:: The LangTag snippet.
#
# ==== Returns
# Array or nil::
# It returns +nil+, when the snipped passed:
# * does not conform the Language-Tag ABNF (malformed)
# * represents a 'grandfathered' Language-Tag
# * starts with 'x' singleton ('privateuse').
#
# Otherwise you'll get an +Array+ with:
# * primary subtag (as +String+, downcased),
# * extlang (as +String+, downcased) or +nil+,
# * script (as +String+, capitalized) or +nil+,
# * region (as +String+, upcased) or +nil+
# * downcased variants (+Array+) or nil.
#
# ==== Notes
# In most cases, it's quite enough. Take a look, for example, at
# {'35-character recomendation'}[http://tools.ietf.org/html/rfc5646#section-4.6].
#
def extract_language_info(langtag)
tag = langtag.downcase
return nil if GRANDFATHERED_TAGS.key?(langtag)
return nil unless LANGTAG_INFO_REGEX === tag
primary = $1
extlang = nil
script = $2
region = $3
variants = $4.split(Utils::HYPHEN_SPLITTER)[1..-1]
primary, *extlang = primary.split(Utils::HYPHEN_SPLITTER) if primary.include?(Const::HYPHEN)
script.capitalize! if script
region.upcase! if region
[primary, extlang, script, region, variants]
end
def parse(thing)
return nil unless thing
return thing if thing.kind_of?(self)
self.new.recompose(thing)
end
end
# Checks if self has a variant passed.
# Works case-insensitively.
#
def has_variant?(variant)
return false unless @variants
v = variant.downcase
@variants.any? { |var| v == var || v == var.downcase }
end
# Checks if self has a singleton passed.
# Works case-insensitively.
def has_singleton?(key)
return false unless @extensions
@extensions.key?(key) || @extensions.key?(key.downcase)
end
alias :extension? :has_singleton?
# Builds an ordered list of singletons.
def singletons
return nil unless @extensions
keys = @extensions.keys
keys.sort!
keys
end
def initialize(*components)
@primary, @extlang, @script, @region, @variants, @extensions, @privateuse = *components
end
# Builds the +String+, which represents self.
# Does *not* perform validation or recomposition.
#
def compose
@tag = to_a.join(Const::HYPHEN)
@tag
end
attr_reader :tag # the most recent 'build' of tag
# Returns the number of subtags in self.
# Does *not* perform validation or recomposition.
#
def length
length = 1 #@primary
length += @extlang.length if @extlang
length += 1 if @script
length += 1 if @region
length += @variants.length if @variants
@extensions.each { |_,e| length += e.length+1 } if @extensions # length += @extenstions.to_a.flatten.length if @extensions
length += @privateuse.length+1 if @privateuse
length
end
def nicecased
recompose # we could not conveniently format malformed or invalid tags
@nicecased #.dup #uuuuugh
end
def to_a
ary = [@primary]
ary.concat @extlang if @extlang
ary << @script if @script
ary << @region if @region
ary.concat @variants if @variants
singletons.each { |s| (ary << s).concat @extensions[s] } if @extensions
(ary << PRIVATEUSE).concat @privateuse if @privateuse
ary
rescue
raise "LanguageTag has at least one malformed attribute: #{self.inspect}"
end
#--
# RFC 4647, sec. 3.3.2 ('Extended Filtering')
#
# Much like basic filtering, extended filtering selects content with
# arbitrarily long tags that share the same initial subtags as the
# language range. In addition, extended filtering selects language
# tags that contain any intermediate subtags not specified in the
# language range. For example, the extended language range "de-*-DE"
# (or its synonym "de-DE") matches all of the following tags:
#
# de-DE (German, as used in Germany)
# de-de (German, as used in Germany)
# de-Latn-DE (Latin script)
# de-Latf-DE (Fraktur variant of Latin script)
# de-DE-x-goethe (private-use subtag)
# de-Latn-DE-1996 (orthography of 1996)
# de-Deva-DE (Devanagari script)
#
# The same range does not match any of the following tags for the
# reasons shown:
#
# de (missing 'DE')
# de-x-DE (singleton 'x' occurs before 'DE')
# de-Deva ('Deva' not equal to 'DE')
#++
# Checks if the *extended* Language-Range (in the shortest notation)
# passed matches self.
def matched_by_extended_range?(range)
recompose
subtags = @composition.split(Const::HYPHEN)
subranges = range.downcase.split(Const::HYPHEN)
subrange = subranges.shift
subtag = subtags.shift
while subrange
if subrange == Const::WILDCARD
subrange = subranges.shift
elsif subtag == nil
return false
elsif subtag == subrange
subtag = subtags.shift
subrange = subranges.shift
elsif subtag.size == 1
return false
else
subtag = subtags.shift
end
end
true
rescue
false
end
#--
# RFC 4647, sec. 3.3.1 ('Basic Filtering')
#
# A language range matches a
# particular language tag if, in a case-insensitive comparison, it
# exactly equals the tag, or if it exactly equals a prefix of the tag
# such that the first character following the prefix is "-". For
# example, the language-range "de-de" (German as used in Germany)
# matches the language tag "de-DE-1996" (German as used in Germany,
# orthography of 1996), but not the language tags "de-Deva" (German as
# written in the Devanagari script) or "de-Latn-DE" (German, Latin
# script, as used in Germany).
#++
# Checks if the *basic* Language-Range passed matches self.
#
# ==== Example
# tag = LanguageTag.parse('de-Latn-DE')
# tag.matched_by_basic_range?('de-Latn-DE') #=> true
# tag.matched_by_basic_range?('de-Latn') #=> true
# tag.matched_by_basic_range?('*') #=> true
# tag.matched_by_basic_range?('de-La') #=> false
# tag.matched_by_basic_range?('de-de') #=> false
# tag.matched_by_basic_range?('malformedlangtag') #=> false
#
def matched_by_basic_range?(range)
if range.kind_of?(self.class)
s = range.recompose.tag
elsif range.respond_to?(:to_str)
return true if range.to_str == Const::WILDCARD
s = self.class.parse(range).tag
else
return false
end
recompose
@tag == s || @tag.index(s + Const::HYPHEN) == 0
rescue
false
end
alias :has_prefix? :matched_by_basic_range?
def ==(other)
return false unless other.kind_of?(self.class)
compose
other.compose
@tag == other.tag || @tag.downcase == other.tag.downcase
end
def ===(other)
if other.kind_of?(self.class)
s = other.compose
elsif other.respond_to?(:to_str)
s = other.to_str
else
return false
end
compose
@tag == s || @tag.downcase == s.downcase
end
# Validates self.
#
# ==== Notes
# Validation is deferred by default, because the paranoid
# check & dup of everything is not a good way (in this case).
# So, you may create some tags, make them malformed/invalid,
# and still be able to compare and modify them. Only note, that
# things like 'filtering' and 'lookup' are *not* validation-free.
#
def valid?
!!recompose rescue false
end
alias :langtag? :valid?
# ==== Parameters
# thing<String, optional>::
# The LangTag snippet
#
# ==== Returns
# +self+
#
# ==== Raises
# ArgumentError::
# The snippet passed:
# * does not conform the Language-Tag ABNF (malformed)
# * represents a 'grandfathered' Language-Tag
# * starts with 'x' singleton ('privateuse').
# * contains duplicate variants
# * contains duplicate singletons
#
def recompose(thing = nil)
tag = nil
compose
if thing
raise TypeError, "Can't convert #{thing.class} into String" unless thing.respond_to?(:to_str)
return self if @tag == (tag = thing.to_str) || @tag.downcase == (tag = tag.downcase)
else
return self if @nicecased == (tag = @tag) || @composition == tag || @composition == (tag = tag.downcase)
end
if !GRANDFATHERED_TAGS.key?(tag) && LANGTAG_COMPOSITION_REGEX === tag
@primary = $1
@extlang = nil
@script = $2
@region = $3
components = $'.split(Utils::HYPHEN_SPLITTER)
components.shift
@primary, *@extlang = @primary.split(Utils::HYPHEN_SPLITTER) if @primary.include?(Const::HYPHEN)
@script.capitalize! if @script
@region.upcase! if @region
@extensions = nil
@variants = nil
singleton = nil
while c = components.shift
if c.size == 1
break if c == PRIVATEUSE
@extensions ||= {}
if @extensions.key?(c)
raise ArgumentError, "Invalid langtag (repeated singleton: #{c.inspect}): #{thing.inspect}"
end
singleton = c
@extensions[singleton = c] = []
elsif singleton
@extensions[singleton] << c
else
@variants ||= []
if @variants.include?(c)
raise ArgumentError, "Invalid langtag (repeated variant: #{c.inspect}): #{thing.inspect}"
end
@variants << c
end
end
@privateuse = components.empty? ? nil : components
@nicecased = compose
@composition = @tag.downcase
else
raise ArgumentError, "Malformed, grandfathered or 'privateuse' Language-Tag: #{thing.inspect}"
end
self
end
end
end
end
# EOF
| true |
40ff6bf2033e789220a382c4a55d4d4e25f13f41
|
Ruby
|
christoomey/plugin-ruby
|
/test/class.rb
|
UTF-8
| 840 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Pret
module Tier
# object documentation
class Object; end
# second object
# documentation
class Object
end
# third object
# documentation
class Object
attr_accessor :foo
end
class Object < BasicObject; end
class Object < BasicObject
end
class Object < BasicObject
# inside class documentation
attr_accessor :bar
end
class << self
# method documentation
def method; end
undef method
end
module Prettier; end
module Prettier
end
module Prettier
# inside module documentation
attr_accessor :foo
end
end
end
Pret::Tier::Object # rubocop:disable Lint/Void
Pret::TIER = 'config'.to_s
::Pret::Tier::Object # rubocop:disable Lint/Void
::PRET = 'config'.to_s
| true |
48a015c400f9421f83d35a328e9588e94d6b8c1c
|
Ruby
|
jmchilton/msi_software_accounting
|
/vendor/plugins/flotomatic/lib/flot.rb
|
UTF-8
| 5,236 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
# Author:: Michael Cowden
# Copyright:: MigraineLiving.com
# License:: Distributed under the same terms as Ruby
=begin rdoc
== Flot
This class acts as a ruby wrapper for the flot javascript object. It is the class used in your model / controller to setup your data sets. It is then the object used in the <tt><%= flot_graph %></tt> helper method.
It's primary purpose is to contain the data that is used in the flot graph.
=end
class Flot
CANVAS_DEFAULT_HTML_OPTIONS = {:style => "height: 300px"}
SERIES_OPTIONS = %w(lines points bars shadowSize color)
attr_accessor :data, :options, :placeholder, :html_options
alias :canvas :placeholder
alias :canvas= :placeholder=
=begin rdoc
The flot object can be initialized with either a block or a hash of options. The canvas and placeholder are used interchangeably and is provided as an optional first argument for convenience.
Initialize with a hash:
Flot.new('graph', :options => {:points => {:show => true}},
:data => [
{:label => 'Male', :data => [[1,0], [2,2]], [3,5]},
{:label => 'Female', :data => [[1,1], [2,3]], [3,4]}
])
Initialize with a block:
Flot.new('graph') do |f|
f.bars
f.grid :hoverable => true
f.selection :mode => "xy"
f.filter {|collection| collection.select {|j| j.entry_num > 0}}
f.series_for("Stress", @journals, :x => :entry_num, :y => :stress_rating)
f.series_for("Hours of Sleep", @journals, :x => :entry_num, :y => :hours_of_sleep)
f.series_for("Restful Night?", @journals, :x => :entry_num, :y => lambda {|record| record.restful_night ? 5 : 0 }, :options => {:points => {:show => true}, :bars => {:show => false}})
end
Initialize (and then set data & options later):
f = Flot.new('graph')
f.line
f.series "Red Line", [[0,5], [1,5], [2,5]], :color => '#f00'
=end
def initialize(canvas = nil, html_opts = {})
# TODO: :tick_formatter => enum / hash or a mapping function, also :tick_formatter => {1 => "Mon", 2 => "Tue", ...} OR if an x or y is a string/sym consider auto conversion --> a TotalFlot? or total_for(@collection, x, y)
# TODO: define callbacks - set and clear selection, binding plotselected, etc.
# TODO: custom functions for ticks and such
@collection_filter = nil
tap do |flot|
flot.data ||= []
flot.options ||= {}
flot.html_options = html_opts.reverse_merge(CANVAS_DEFAULT_HTML_OPTIONS)
flot.canvas = canvas if canvas
yield flot if block_given?
end
end
=begin rdoc
== Graph Styles
Convenience methods for defaulting the graph to line, point, or bar. As well as for displaying the legend. These are the defaults for each series added to the flot object, but they can be overridden using the options hash passed to the <tt>series</tt> and <tt>series_for</tt> methods.
Each takes a set of options, which default to :show => true.
Examples:
flot.lines
flot.points
flot.bars :show => true, :bar_width => 5, :align => 'center'
flot.legend :no_columns => 2
flot.[lines|points|bars|legend](opts = {:show => true})
=end
[:lines, :points, :bars, :legend].each do |meth|
define_method(meth) do |*args|
merge_options(meth, arguments_to_options(args))
end
end
# Pass other methods through to the javascript flot object.
#
# For instance: <tt>flot.grid(:color => "#699")</tt>
#
def method_missing(meth, opts = {})
merge_options meth, opts
end
# Setup a filter that will be used to limit all datasets in the graph.
#
# For instance, to limit the graph to positive amounts:
# flot.filter {|collection| collection.select {|record| record.amount > 0 }}
#
def filter(&block)
@collection_filter = block
end
# Create a series based on a collection of objects.
#
# For example:
# # People by age
# people = People.all
# @flot.series_for "Age", people, :x => :id, :y => :age, :options => {:color => '#f00'}
#
def series_for(label, collection, opts)
series label, map_collection(collection, opts[:x], opts[:y], opts[:tooltip], opts[:link_url]), opts[:options] || {}
end
# Add a simple series to the graph:
#
# data = [[0,5], [1,5], [2,5]]
# @flot.series "Horizontal Line", data
# @flot.series "Red Line", data, :color => '#f00' # or is it "'#f00'"
#
def series(label, d, opts = {})
if opts.blank?
@data << series_options.merge(:label => label, :data => d)
else
@data << opts.merge(:label => label, :data => d)
end
end
private
def series_options
@options.reject {|k,v| SERIES_OPTIONS.include?(k.to_s) == false}
end
def map_collection(collection, x, y, tooltip, link_url)
col = @collection_filter ? @collection_filter.call(collection) : collection
col.map {|model| [get_coordinate(model, x), get_coordinate(model, y), get_coordinate(model, tooltip), get_coordinate(model, link_url)]}
end
def merge_options(name, opts)
@options.merge! name => opts
end
def arguments_to_options(args)
if args.blank?
{:show => true}
elsif args.is_a? Array
args.first
else
args
end
end
def get_coordinate(model, method)
unless method.nil?
method.is_a?(Proc) ? method.call(model) : model.send(method)
end
end
end
| true |
25eeef2222dc5fae24efc92f4c0b1512b2f65cf5
|
Ruby
|
hoppergee/algorithm_practice
|
/bubble_sort2.rb
|
UTF-8
| 299 | 3.578125 | 4 |
[] |
no_license
|
def bubble_sort(a)
n = a.size
for i in 0...n-1
swapped = false
for j in 0...n-i-1
if a[j] > a[j+1]
a[j], a[j+1] = a[j+1], a[j]
swapped = true
end
end
if swapped == false
break
end
end
return a
end
p bubble_sort [3,4,65,7,8,4,245,78,23]
| true |
363b70bb8b7d9f72831a27eb515d000933c109b3
|
Ruby
|
EdCrux/Tic-Tac-Toe-game
|
/lib/logic.rb
|
UTF-8
| 568 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
module Logic
def self.winner(arr)
3.times do |ite|
return true if rows(arr, ite)
return true if columns(arr, ite)
end
return true if tl_rb(arr) || tr_lb(arr)
false
end
def self.rows(arr, ite)
(arr[ite * 3] == arr[(ite * 3) + 1]) && (arr[ite * 3] == arr[(ite * 3) + 2])
end
def self.columns(arr, ite)
(arr[ite] == arr[ite + 3]) && (arr[ite] == arr[ite + 6])
end
def self.tl_rb(arr)
((arr[0] == arr[4]) && (arr[0] == arr[8]))
end
def self.tr_lb(arr)
((arr[2] == arr[4]) && (arr[2] == arr[6]))
end
end
| true |
07b0c06546b1861f2f638189d89765e1f9a36797
|
Ruby
|
evgeniy-kunitsa/dip
|
/logical_operations/image.rb
|
UTF-8
| 2,018 | 3.625 | 4 |
[] |
no_license
|
require 'rmagick'
require './pixel'
class Magick::Image
def |(other_image)
rows = min_rows(other_image)
columns = min_columns(other_image)
(0...rows).each do |i|
(0...columns).each do |j|
self_pixel = self.get_pixels(j, i, 1, 1).first
other_image_pixel = other_image.get_pixels(j, i, 1, 1).first
result = self_pixel | other_image_pixel
self.store_pixels(j, i, 1, 1, [result])
end
end
end
def &(other_image)
rows = min_rows(other_image)
columns = min_columns(other_image)
(0...rows).each do |i|
(0...columns).each do |j|
self_pixel = self.get_pixels(j, i, 1, 1).first
other_image_pixel = other_image.get_pixels(j, i, 1, 1).first
result = self_pixel & other_image_pixel
self.store_pixels(j, i, 1, 1, [result])
end
end
end
def ^(other_image)
rows = min_rows(other_image)
columns = min_columns(other_image)
(0...rows).each do |i|
(0...columns).each do |j|
self_pixel = self.get_pixels(j, i, 1, 1).first
other_image_pixel = other_image.get_pixels(j, i, 1, 1).first
result = self_pixel ^ other_image_pixel
self.store_pixels(j, i, 1, 1, [result])
end
end
end
def !
(0...self.rows).each do |i|
(0...self.columns).each do |j|
self_pixel = self.get_pixels(j, i, 1, 1).first
result = !self_pixel
self.store_pixels(j, i, 1, 1, [result])
end
end
end
private
def min_rows(other_image)
self.rows < other_image.rows ? self.rows : other_image.rows
end
def min_columns(other_image)
self.columns < other_image.columns ? self.columns : other_image.columns
end
end
# USING:
# i = Magick::Image::read("1.png")[0]
# i1 = Magick::Image::read("2.png")[0]
# i | i1
# i.write('3.jpg')
# i = Magick::Image::read("1.png")[0]
# i & i1
# i.write('4.jpg')
# i = Magick::Image::read("1.png")[0]
# i ^ i1
# i.write('5.jpg')
# i = Magick::Image::read("1.png")[0]
# !i
# i.write('6.jpg')
| true |
014ecdf51254f2e2801c0e37a94c54659b063cce
|
Ruby
|
karoster/AppAcademy
|
/Data_structs/tictactoe_tree/lib/super_computer_player.rb
|
UTF-8
| 802 | 3.40625 | 3 |
[] |
no_license
|
require_relative 'tic_tac_toe_node'
class SuperComputerPlayer < ComputerPlayer
def move(game, mark)
node = TicTacToeNode.new(game.board, mark)
position = winning_move(node)
position = stall_move(node) if position.nil?
position
end
###Helper Fxns###
def winning_move(node)
pos = nil
node.children.each do |child|
if child.winning_node?(node.next_mover_mark)
pos = child.prev_move_pos
end
end
pos
end
def stall_move(node)
node.children.each do |child|
return child.prev_move_pos unless child.losing_node?(node.next_mover_mark)
end
raise "All moves result in loss"
end
end
if __FILE__ == $PROGRAM_NAME
puts "Play the brilliant computer!"
hp = HumanPlayer.new("Jeff")
cp = SuperComputerPlayer.new
TicTacToe.new(hp, cp).run
end
| true |
f6a5de9bb2045692083ff76c258af3ecd592a9d3
|
Ruby
|
Lilaro/OO-Art-Gallery-dumbo-web-071519
|
/app/models/artist.rb
|
UTF-8
| 827 | 3.296875 | 3 |
[] |
no_license
|
class Artist
attr_reader :name, :years_experience
@@all = []
def initialize(name, years_experience)
@name = name
@years_experience = years_experience
@@all << self
end
def self.all
@@all
end
def paintings
Painting.all.select do |piece|
piece.artist == self
end
end
def galleries
paintings.map do |piece|
piece.gallery
end.uniq
end
def cities
galleries.map do |gallery|
gallery.city
end.uniq
end
def self.total_experience
self.all.map do |artist|
artist.years_experience
end.sum
end
def self.most_prolific
self.all.max do |artist|
artist.paintings.length / artist.years_experience
end
end
def create_painting(title, price, gallery)
Painting.new(title, price, self, gallery)
end
end
| true |
81d3906e4f66406df64a6f3785a6156f2b3bdb3f
|
Ruby
|
akud/mtg_trader
|
/app/models/card_population/generator.rb
|
UTF-8
| 388 | 2.71875 | 3 |
[] |
no_license
|
module CardPopulation
class Generator
def initialize opts={}
@collection = opts[:collection] || GathererCollection.new
@writer = opts[:writer] || SeedWriter.new
@filter = opts[:filter] || ExcludeCommonsFilter.new
end
def generate
@collection.each_card do |card|
@writer.write_card(card) if @filter.include?(card)
end
end
end
end
| true |
3417ea1d0ac0fd296407fc8a4a5b22c798616905
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/cs169/800/spectral_cluster/recluster/cluster_3/13642/21942.rb
|
UTF-8
| 1,056 | 3.671875 | 4 |
[] |
no_license
|
def combine_anagrams(words)
if (words == nil or words.length < 2)
return words
end
results = Hash.new {|h,k| h[k] = Array.new}
words.each do |word|
worddown = word.to_s.downcase.chars.sort.join
results[worddown].push(word)
results[worddown]
end
return results.values
end
p combine_anagrams(nil)
p combine_anagrams([])
p combine_anagrams('a')
p combine_anagrams(["A","a","this","THIS","b"])
p combine_anagrams(['&'])
p combine_anagrams(["a", 100])
p combine_anagrams(["A", "a", "a", "a","b", "b","c", "D", "d"])
p combine_anagrams(['pots', 'spot', 'stop', 'tops', 'tops','spots', 'stops', 'sausage'])
p combine_anagrams(['Cars'])
puts combine_anagrams(['Cars', 'FOR', 'potatoes', 'Cars','racs', 'four', 'screAm', 'scAr', 'Cars','cReams', 'screAm']).inspect
# => output: [["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]]
# HINT: you can quickly tell if two words are anagrams by sorting their
# letters, keeping in mind that upper vs lowercase doesn't matter
puts combine_anagrams(['C', 'C']).inspect
| true |
f9ee22c7f179eb6f881af2fd80b08f0c985c3dbe
|
Ruby
|
kinoppyd/reading-metaprogramming-ruby
|
/04_block/03_simple_bot.rb
|
UTF-8
| 1,974 | 3.421875 | 3 |
[
"WTFPL"
] |
permissive
|
# 次の仕様を満たすSimpleBotクラスとDSLを作成してください
#
# # これは、作成するSimpleBotクラスの利用イメージです
# class Bot < SimpleBot
# setting :name, 'bot'
# respond 'keyword' do
# "response #{settings.name}"
# end
# end
#
# Bot.new.ask('keyword') #=> 'respond bot'
#
# 1. SimpleBotクラスを継承したクラスは、クラスメソッドrespond, setting, settingsを持ちます
# 1. settingsメソッドは、任意のオブジェクトを返します
# 2. settingsメソッドは、後述するクラスメソッドsettingによって渡された第一引数と同名のメソッド呼び出しに応答します
# 2. SimpleBotクラスのサブクラスのインスタンスは、インスタンスメソッドaskを持ちます
# 1. askは、一つの引数をとります
# 2. askに渡されたオブジェクトが、後述するrespondメソッドで設定したオブジェクトと一致する場合、インスタンスは任意の返り値を持ちます
# 3. 2のケースに当てはまらない場合、askメソッドの戻り値はnilです
# 3. クラスメソッドrespondは、keywordとブロックを引数に取ります
# 1. respondメソッドの第1引数keywordと同じ文字列が、インスタンスメソッドaskに渡された時、第2引数に渡したブロックが実行され、その結果が返されます
# 4. クラスメソッドsettingは、引数を2つ取り、1つ目がキー名、2つ目が設定する値です
# 1. settingメソッドに渡された値は、クラスメソッド `settings` から返されるオブジェクトに、メソッド名としてアクセスすることで取り出すことができます
# 2. e.g. クラス内で `setting :name, 'bot'` と実行した場合は、respondメソッドに渡されるブロックのスコープ内で `settings.name` の戻り値は `bot` の文字列になります
| true |
55f739c0d2fa42921527335177d5b67e07ceee54
|
Ruby
|
JuHambre/adiserver
|
/datos/UsuarioDAO.rb
|
UTF-8
| 263 | 2.640625 | 3 |
[] |
no_license
|
require_relative '../dominio/usuario'
class UsuarioDAO
def listar_usuario(login)
Usuario.get(login)
end
def login(email, password)
Usuario.first(:password => password)
end
def registrar_usuario(usuario)
Usuario.create(usuario)
end
end
| true |
59d2d737dde3a213083c9dcaf80010bfd551af79
|
Ruby
|
krschacht/nebel
|
/test/lib/lesson_part_splitter_test.rb
|
UTF-8
| 4,188 | 3.171875 | 3 |
[] |
no_license
|
require "test_helper"
require "lesson_part_splitter"
class LessonPartSplitterTest < ActiveSupport::TestCase
setup do
@string_with_parts = "Part 1. Wash\nWash the dishes\nPart 2. Rinse\nRinse the dishes"
@string_without_parts = "Wash and rinse the dishes"
end
test ".new replaces 'Parts' with 'Part'" do
lesson_part_splitter = LessonPartSplitter.new("Parts 1. Wash")
assert_equal "Part 1. Wash", lesson_part_splitter.instance_variable_get(:@text)
end
test "#split yields for each part" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
count_of_yields = 0
lesson_part_splitter.split { count_of_yields += 1 }
assert_equal 2, count_of_yields
end
test "#split yields with the part number" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
part_numbers = []
lesson_part_splitter.split do |part_number|
part_numbers << part_number
end
assert part_numbers.include? 1
assert part_numbers.include? 2
end
test "#split yields with the part name" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
part_names = []
lesson_part_splitter.split do |part_number, part_name|
part_names << part_name
end
assert part_names.include? "Part 1. Wash"
assert part_names.include? "Part 2. Rinse"
end
test "#split yields with the part text" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
part_texts = []
lesson_part_splitter.split do |part_number, part_name, part_text|
part_texts << part_text
end
assert part_texts.include? "Wash the dishes"
assert part_texts.include? "Rinse the dishes"
end
test "#split yields once if text is not divided into parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_without_parts)
count_of_yields = 0
lesson_part_splitter.split { count_of_yields += 1 }
assert_equal 1, count_of_yields
end
test "#split yields part number as nil if text is not divided into parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_without_parts)
lesson_part_splitter.split do |part_number|
assert_nil part_number
end
end
test "#split yields part name as nil if text is not divided into parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_without_parts)
lesson_part_splitter.split do |part_number, part_name|
assert_nil part_name
end
end
test "#split yields part text if text is not divided into parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_without_parts)
lesson_part_splitter.split do |part_number, part_name, part_text|
assert_equal @string_without_parts, part_text
end
end
test "#split returns an array of the results of each yield" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
results = lesson_part_splitter.split { "result" }
assert_equal 2, results.size
assert "result", results[0]
assert "result", results[1]
end
test "#split fixes incorrectly labled part numbers" do
lesson_part_splitter = LessonPartSplitter.new("Part 1. Wash\nPart 3. Rinse\nPart 5. Repeat")
part_names = []
lesson_part_splitter.split do |part_number, part_name|
part_names << part_name
end
assert_equal "Part 1. Wash", part_names[0]
assert_equal "Part 2. Rinse", part_names[1]
assert_equal "Part 3. Repeat", part_names[2]
end
test "#text_for_part extracts text between two parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
assert_equal "Wash the dishes", lesson_part_splitter.text_for_part(1)
end
test "#text_for_part extracts text from last part" do
lesson_part_splitter = LessonPartSplitter.new(@string_with_parts)
assert_equal "Rinse the dishes", lesson_part_splitter.text_for_part(2)
end
test "#text_for_part extracts all text when not split into parts" do
lesson_part_splitter = LessonPartSplitter.new(@string_without_parts)
assert_equal "Wash and rinse the dishes", lesson_part_splitter.text_for_part(1)
end
end
| true |
2aef611618d537453deecca7c320acd7a809c399
|
Ruby
|
quiteliderally/codeine
|
/examples/flexible.rb
|
UTF-8
| 542 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'
require 'codeine'
module FooModule
class A
codeine_inject :logger
def initialize
puts logger.inspect
end
end
end
module BarModule
class A
codeine_inject :logger
def initialize
puts logger.inspect
end
end
end
Codeine.configure(FooModule) do |c|
c.register(:logger){"the fancy logger for FooModule"}
end
Codeine.configure(BarModule) do |c|
c.register(:logger){"the simple logger for BarModule"}
end
FooModule::A.new
BarModule::A.new
| true |
1bb549cffa2f4d9b043d28936d993928379296d5
|
Ruby
|
annejohnson/euler
|
/28.rb
|
UTF-8
| 171 | 2.828125 | 3 |
[] |
no_license
|
# PROBLEM 28
GRID_SIZE = 1001
sum = 1
inc = 2
next_num = 1
(GRID_SIZE / 2).times do
4.times do
next_num += inc
sum += next_num
end
inc += 2
end
puts sum
| true |
7b9be632d3fa9862cfd65792b506e86d05a6b623
|
Ruby
|
druplar/dotfiles
|
/bin/git-cleanup-remotes
|
UTF-8
| 978 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'shellwords'
puts "=> git fetch --all --prune"
system 'git fetch --all --prune'
branches = `git branch -r --merged master`.lines.map(&:chomp).select{|b| !(b =~ /master$/)}.map{|b| b[2..-1].split('/', 2)}
remotes = branches.reduce(Hash.new{|h, k| h[k] = []}) {|h, b| h[b[0]].push b[1];h }
remotes.each do |remote, branches|
next if `git config --get remote.#{Shellwords.escape remote}.skipcleanup`.chomp == 'true'
print "=> Cleaning remote '#{remote}', continue? [y,n,s] "
input = STDIN.gets.chomp
if input =~ /^y(?:es)?$/i
puts "=> git push --no-verify #{remote} --delete #{branches.join(' ')}"
system 'git', 'push', '--no-verify', remote, '--delete', *branches
elsif input =~ /^no?$/i
puts "=> Skipped."
elsif input =~ /^s(?:kip)?$/i
puts "=> git config remote.#{remote}.skipcleanup true"
system 'git', 'config', "remote.#{remote}.skipcleanup", 'true'
puts "=> Skipped (permanent)."
else
redo
end
end
| true |
2e7910c7563393b25fdf7b587cf72f32ed9e9a9d
|
Ruby
|
Gerula/interviews
|
/CareerCup/up_down_array.rb
|
UTF-8
| 865 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
require 'test/unit'
extend Test::Unit::Assertions
def generate
size = Random.rand(5..12)
return Array.new(size) {
Random.rand(1..30)
}
end
class Array
def up_down?
0.upto(self.size - 2).each { |i|
return false if i % 2 == 0 && self[i] > self[i + 1] || i % 2 == 1 && self[i] < self[i + 1]
}
return true
end
def up_down
0.upto(self.size - 2).each { |i|
if i % 2 == 0 && self[i] > self[i + 1]
self[i], self[i + 1] = self[i + 1], self[i]
end
if i % 2 == 1 && self[i] < self[i + 1]
self[i], self[i + 1] = self[i + 1], self[i]
end
}
return self
end
end
Random.rand(5..15).times {
a = generate
puts a.inspect
puts "#{a.up_down.inspect} #{a.up_down?}"
assert(a.up_down?)
}
| true |
ac02ddc8f44159745f4dd052d52236264f4f9219
|
Ruby
|
envato/event_sourcery
|
/lib/event_sourcery/event_store/subscription.rb
|
UTF-8
| 2,552 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
module EventSourcery
module EventStore
# This allows Event Stream Processors (ESPs) to subscribe to an event store, and be notified when new events are
# added.
class Subscription
#
# @param event_store Event store to source events from
# @param poll_waiter Poll waiter instance used (such as {EventStore::PollWaiter}) for polling the event store
# @param from_event_id [Integer] Start reading events from this event ID
# @param event_types [Array] Optional. If specified, only subscribe to given event types.
# @param on_new_events [Proc] Code block to be executed when new events are received
# @param subscription_master A subscription master instance (such as {EventStore::SignalHandlingSubscriptionMaster}) which orchestrates a graceful shutdown of the subscription, if one is requested.
# @param events_table_name [Symbol] Optional. Defaults to `:events`
def initialize(event_store:,
poll_waiter:,
from_event_id:,
event_types: nil,
on_new_events:,
subscription_master:,
events_table_name: :events,
batch_size: EventSourcery.config.subscription_batch_size)
@event_store = event_store
@from_event_id = from_event_id
@poll_waiter = poll_waiter
@event_types = event_types
@on_new_events = on_new_events
@subscription_master = subscription_master
@current_event_id = from_event_id - 1
@batch_size = batch_size
end
# Start listening for new events. This method will continue to listen for new events until a shutdown is requested
# through the subscription_master provided.
#
# @see EventStore::SignalHandlingSubscriptionMaster
def start
catch(:stop) do
@poll_waiter.poll do
read_events
end
end
end
private
attr_reader :batch_size
def read_events
loop do
@subscription_master.shutdown_if_requested
events = @event_store.get_next_from(@current_event_id + 1, event_types: @event_types, limit: batch_size)
break if events.empty?
EventSourcery.logger.debug { "New events in subscription: #{events.inspect}" }
@on_new_events.call(events)
@current_event_id = events.last.id
EventSourcery.logger.debug { "Position in stream: #{@current_event_id}" }
end
end
end
end
end
| true |
7b3d7155fa8f1cbaf84c75b8aac82592c4d18cac
|
Ruby
|
ericcf/deadbolt
|
/app/models/ability.rb
|
UTF-8
| 633 | 2.515625 | 3 |
[] |
no_license
|
class Ability
include CanCan::Ability
def initialize(user=nil)
if user
if user.admin?
can :manage, :all
end
add_dynamic_abilities user
end
end
private
def add_dynamic_abilities(user)
user.roles.each do |role|
role.role_permissions.each do |role_permission|
permission = role_permission.permission
action = permission.action.to_sym
target_class = permission.target_type.constantize
unless role_permission.target
can action, target_class
else
can action, role_permission.target
end
end
end
end
end
| true |
c288f0a1dff8335990c9cbd5289eec1340b0e623
|
Ruby
|
radiospiel/sinatra-sse
|
/lib/sinatra/sse/marshal.rb
|
UTF-8
| 1,778 | 2.984375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] |
permissive
|
# This file is part of the sinatra-sse ruby gem.
#
# Copyright (c) 2011, 2012 @radiospiel
# Distributed under the terms of the modified BSD license, see LICENSE.BSD
require "expectation"
#
# packing/unpacking SSE events
module Sinatra::SSE::Marshal
FIXED_ORDER = {
:event => 1,
:id => 2,
:data => 3
} #:nodoc:
# converts an object into an event.
#
# The object must be a hash or a String.
def marshal(object)
expect! object => [ String, Hash ]
if object.is_a?(String)
object = { :data => object }
end
# sort all entries in a way, that make sure that event, id, data
# are at the end. This makes sure that confirming clients just
# ignore the extra entries. If we would just send them in random
# order we might produce "bogus" events, when "data", "event",
# and "id" are separated by invalid entries.
entries = object.sort_by { |key, value| FIXED_ORDER[key.to_sym] || 0 }
entries.map do |key, value|
escaped_value = value.gsub(/(\r\n|\r|\n)/, "\n#{key}: ")
"#{key}: #{escaped_value}\n"
end.join + "\n"
end
# Unmarshals a single event in data. The string SHOULD NOT contain
# multipe events, or else the returned hash somehow mangles all these
# events into a single one.
def unmarshal(data)
event = Hash.new { |hash, key| hash[key] = [] }
data.split("\n").each do |line|
key, value = line.split(/: ?/, 2)
next if key =~ /^\s*$/
event[key.to_sym] << value
end
event.inject({}) do |hash, (key, value)|
hash.update key => value.join("\n")
end
end
# Extract all events from a data stream.
def unmarshal_all(data)
data.split(/\n\n/).
map { |event| unpack(event) }.
reject(&:empty?)
end
end
| true |
df166858f2dfd07c411a1612abca1be8dc09a1da
|
Ruby
|
sambeca/phrasepalette
|
/app/models/phrase.rb
|
UTF-8
| 167 | 2.578125 | 3 |
[] |
no_license
|
class Phrase < ApplicationRecord
belongs_to :user
before_save :downcase_phrase
def downcase_phrase
first_word.downcase!
second_word.downcase!
end
end
| true |
e34656e40ec4aa4aa6b9c0fb1b7f48fbdb53034d
|
Ruby
|
micahbales/Launch-Academy
|
/challenges/phase-2/dice-game/advanced_dice.rb
|
UTF-8
| 418 | 3.875 | 4 |
[] |
no_license
|
input = ""
while input != "n" do
puts "How many sides do your dice have?"
sides = gets.chomp.to_i
puts "How many times would you like to roll your dice?"
rolls = gets.chomp.to_i
rolls.times do
die1 = rand(sides) + 1
die2 = rand(sides) + 1
total = die1 + die2
puts "You rolled a #{die1} and a #{die2}"
puts "Total: #{total}"
end
puts "Roll again? (y/n)"
input = gets.strip
end
| true |
48f2d5641577513a06324fec16eab97cd84ffc53
|
Ruby
|
massud/battleships_mvp_sequence
|
/spec/submarine_spec.rb
|
UTF-8
| 1,312 | 3.265625 | 3 |
[] |
no_license
|
require 'submarine'
describe Submarine do
let(:sub){Submarine.new 'A2', :north}
let(:sub_north){Submarine.new 'B2', :north}
let(:sub_east){Submarine.new 'B2', :east}
let(:sub_south){Submarine.new 'B2', :south}
let(:sub_west){Submarine.new 'B2', :west}
it 'has size 2' do
expect(sub.size).to eq 2
end
it 'knows all positions when facing north' do
expect(sub_north.position).to eq ['B2','B1']
end
it 'knows all positions when facing east' do
expect(sub_east.position).to eq ['B2','C2']
end
it 'knows all positions when facing south' do
expect(sub_south.position).to eq ['B2','B3']
end
it 'knows all positions when facing west' do
expect(sub_west.position).to eq ['B2','A2']
end
it 'gets hit in any of the positions it is in' do
expect(sub_north.hit 'B2').to eq :hit
expect(sub_north.hit 'B1').to eq :hit
end
it 'should handle collisions on start position' do
expect(sub.collided? sub).to be true
end
it 'should handle collisions on location other than start position' do
expect(sub.collided? sub_west).to be true
end
it 'should not be able to be hit more than once in the same place' do
sub_north.hit 'B2'
expect(sub_north.hits).to eq ['B2']
sub_north.hit 'B2'
expect(sub_north.hits).to eq ['B2']
end
end
| true |
bfc7db964748a555d0288e6dd1b4c1d8659a9a19
|
Ruby
|
emrekilinc/narsil
|
/lib/helpers/string_helper.rb
|
UTF-8
| 1,825 | 2.984375 | 3 |
[] |
no_license
|
# encoding: utf-8
class StringHelper
def self.generate_code(length)
rand(36**length).to_s(36)
end
def self.generate_safe_string(input)
output = input.strip.downcase
regexes = [
{ regex: /\s*&\s*/, replace: "" },
{ regex: /[\\ş]/i, replace:"s" },
{ regex: /[\\ğ]/i, replace:"g" },
{ regex: /[\\ü]/i, replace:"u" },
{ regex: /[\\ı]/i, replace:"i" },
{ regex: /[\\ö]/i, replace:"o" },
{ regex: /[\\ç]/i, replace:"c" },
{ regex: /\s*[^A-Za-z0-9\.\-]\s*/, replace: "" },
{ regex: /_+/, replace:"" },
{ regex: /\A[_\.]+|[_\.]+\z/, replace: "" },
{ regex: /\./i, replace: "" }
]
regexes.each do |item|
output.gsub!(item[:regex], item[:replace])
end
output
end
def self.generate_slug(input)
output = input.strip.downcase
regexes = [
{ regex: /['`]/, replace: "" },
{ regex: /\s*&\s*/, replace: " ve " },
{ regex: /[\\ş]/i, replace:"s" },
{ regex: /[\\ğ]/i, replace:"g" },
{ regex: /[\\ü]/i, replace:"u" },
{ regex: /[\\ı]/i, replace:"i" },
{ regex: /[\\ö]/i, replace:"o" },
{ regex: /[\\ç]/i, replace:"c" },
{ regex: /\s*[^A-Za-z0-9\.\-]\s*/, replace: "-" },
{ regex: /_+/, replace:"-" },
{ regex: /\A[_\.]+|[_\.]+\z/, replace: "" },
{ regex: /\./i, replace: "" }
]
regexes.each do |item|
output.gsub!(item[:regex], item[:replace])
end
output
end
def self.generate_unique(length=10)
chars = [('a'..'z'), (1..9)].map { |i| i.to_a }.flatten
unique = (0...length).map{ chars[rand(chars.length)] }.join
end
def self.parse_sentences(raw_text)
result = []
sentences = raw_text.split(".")
sentences.each do |item|
result << item.strip + "."
end
result
end
end
| true |
3a82e232159f84a820074698688c76e0b75ec9f0
|
Ruby
|
Xaavvii/Mod-One-Project-
|
/db/seeds.rb
|
UTF-8
| 2,563 | 3.046875 | 3 |
[] |
no_license
|
require_relative "../lib/models/pizza.rb"
require_relative "../lib/models/topping.rb"
#Toppings
beef = Topping.find_or_create_by(name: "Beef".colorize(:brown)) #1
extra_cheese = Topping.find_or_create_by(name: "Extra Cheese".colorize(:yellow))#2
sausage = Topping.find_or_create_by(name: "Sausage".colorize(:brown)) #3
bacone = Topping.find_or_create_by(name: "Bacon".colorize(:red)) #4
onions = Topping.find_or_create_by(name: "Onions".colorize(:white)) #5
mushrooms = Topping.find_or_create_by(name: "Mushrooms".colorize) #6
pepperoni = Topping.find_or_create_by(name: "Pepperoni") #7
black_olives = Topping.find_or_create_by(name: "Black Olives") #8
green_peppers = Topping.find_or_create_by(name: "Green Peppers") #9
red_peppers = Topping.find_or_create_by(name: "Red Peppers") #10
pineapple = Topping.find_or_create_by(name: "Pineapple") #11
spinach = Topping.find_or_create_by(name: "Spinach") #12
ham = Topping.find_or_create_by(name: "Ham") #13
philly_steak = Topping.find_or_create_by(name: "Philly Steak") #14
#Specialty Pizzas
meatzza = Pizza.find_or_create_by(name: "MeatZZa") #1
extravanaganzza = Pizza.find_or_create_by(name: "ExtravaganZZa") #2
philly_cheese = Pizza.find_or_create_by(name: "Philly Cheese") #3
honolulu = Pizza.find_or_create_by(name: "Honolulu") #4
#####PIZZATOPPINGS ASSOCIATIONS#######
#Meatzza
PizzaTopping.find_or_create_by(pizza_id: 1, topping_id: 1)
PizzaTopping.find_or_create_by(pizza_id: 1, topping_id: 3)
PizzaTopping.find_or_create_by(pizza_id: 1, topping_id: 7)
PizzaTopping.find_or_create_by(pizza_id: 1, topping_id: 13)
#ExtravaganZZa
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 5)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 9)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 8)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 6)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 1)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 13)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 7)
PizzaTopping.find_or_create_by(pizza_id: 2, topping_id: 3)
#PhillyCheese
PizzaTopping.find_or_create_by(pizza_id: 3, topping_id: 14)
PizzaTopping.find_or_create_by(pizza_id: 3, topping_id: 5)
PizzaTopping.find_or_create_by(pizza_id: 3, topping_id: 6)
PizzaTopping.find_or_create_by(pizza_id: 3, topping_id: 9)
#Honolulu
PizzaTopping.find_or_create_by(pizza_id: 4, topping_id: 11)
PizzaTopping.find_or_create_by(pizza_id: 4, topping_id: 13)
PizzaTopping.find_or_create_by(pizza_id: 4, topping_id: 4)
PizzaTopping.find_or_create_by(pizza_id: 4, topping_id: 10)
| true |
5fff32d9208ef57448bbde7021a4a41e518b2ebe
|
Ruby
|
cflipse/rom-yaml
|
/lib/rom/yaml/repository.rb
|
UTF-8
| 1,664 | 2.953125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'yaml'
require 'rom/repository'
require 'rom/yaml/dataset'
module ROM
module YAML
# YAML repository
#
# Connects to a yaml file and uses it as a data-source
#
# @example
# ROM.setup(:yaml, '/path/to/data.yml')
#
# rom = ROM.finalize.env
#
# repository = rom.repositories[:default]
#
# repository.dataset?(:users) # => true
# repository[:users] # => data under 'users' key from the yaml file
#
# @api public
class Repository < ROM::Repository
# Registered datasets
#
# @api private
attr_reader :datasets
# @param [String] path The absolute path to yaml file
#
# @api private
def initialize(path)
@datasets = {}
if File.directory?(path)
@connection = Dir["#{path}/*.yml"].each_with_object({}) do |file, h|
name = File.basename(file, '.*')
data = ::YAML.load_file(file)[name]
h[name] = data
end
else
@connection = ::YAML.load_file(path)
end
end
# Return dataset by its name
#
# @param [Symbol]
#
# @return [Array<Hash>]
#
# @api public
def [](name)
datasets.fetch(name)
end
# Register a new dataset
#
# @param [Symbol]
#
# @return [Dataset]
#
# @api public
def dataset(name)
datasets[name] = Dataset.new(connection.fetch(name.to_s))
end
# Return if a dataset with provided name exists
#
# @api public
def dataset?(name)
datasets.key?(name)
end
end
end
end
| true |
7c702d07fb0fd3cb0cd0313c8d1f425fe98ef1b6
|
Ruby
|
learn-co-curriculum/hs-gnomes-v-flamingos
|
/spec/1_garden_gnome_spec.rb
|
UTF-8
| 1,038 | 3 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative './spec_helper'
describe "Garden Gnome" do
before do
@test_gnome = GardenGnome.new
@test_flamingo = LawnFlamingo.new
end
it "can create individual instances of the garden gnome" do
expect(@test_gnome).to be_an_instance_of(GardenGnome)
end
it "has a name attribute" do
@test_gnome.name = "Boris the Brave"
expect(@test_gnome.name).to eq("Boris the Brave")
end
it "has a weapon attribute" do
@test_gnome.weapon = "bazooka"
expect(@test_gnome.weapon).to eq("bazooka")
end
it "initializes without anger" do
expect(@test_gnome.angry).to eq(false)
end
it "can taunt the flamingos" do
output = capture_stdout { @test_gnome.taunt(@test_flamingo) }
expect(output).to eq("I fart in your general direction!\n")
end
it "gets angry when it is taunted" do
@test_flamingo.taunt(@test_gnome)
expect(@test_gnome.angry).to eq(true)
end
it "can attack" do
output = capture_stdout { @test_gnome.attack }
expect(output).to eq("Garden gnomes attack!!!\n")
end
end
| true |
508958740e3ca30f5efa1e2500f99caceaf67a6e
|
Ruby
|
reqshark/commandlinetools
|
/sysadmin/backup/rubycookbook/08-Object-Oriented-Programming/04 - Writing an Inherited Class.rb
|
UTF-8
| 792 | 3.734375 | 4 |
[] |
no_license
|
class String
def scramble
(split //).sort_by { rand }.join
end
end
"I once was a normal string.".scramble
# => "i arg cn lnws.Ioateosma n r"
#---
class UnpredictableString < String
def scramble
(split //).sort_by { rand }.join
end
def inspect
scramble.inspect
end
end
str = UnpredictableString.new("It was a dark and stormy night.")
# => " hsar gsIo atr tkd naaniwdt.ym"
str
# => "ts dtnwIktsr oydnhgi .mara aa"
#---
class Array
def sum(start_at=0)
inject(start_at) { |sum, x| sum + x }
end
end
#---
[79, 14, 2].sum # => 95
['so', 'fa'].sum('') # => "sofa"
[79, 'so'].sum
# TypeError: String can't be coerced into Fixnum
#---
class NumericArray < Array
def sum
inject(0) { |sum, x| sum + x }
end
end
#---
| true |
f6e8de34d8bae4398d65f961b8043bc7980858aa
|
Ruby
|
alejandro-medici/retrospectiva
|
/vendor/plugins/packr/lib/packr/regexp_group.rb
|
UTF-8
| 3,663 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
class Packr
class RegexpGroup
attr_accessor :values
IGNORE = "\\0"
BACK_REF = /\\(\d+)/
ESCAPE_CHARS = /\\./
ESCAPE_BRACKETS = /\(\?[:=!]|\[[^\]]+\]/
BRACKETS = /\(/
KEYS = "~"
def initialize(values, flags = nil)
@values = []
values.each { |key, value| @values << Item.new(key, value) }
if flags && flags.is_a(String)
@ignore_case = !!(flags =~ /i/)
end
end
def union(*args)
values = {}
@values.each { |item| values[item.expression] = item.replacement }
args.each do |arg|
arg.values.each { |item| values[item.expression] = item.replacement }
end
self.class.new(values)
end
def exec(string, &replacement)
string = string.to_s
regexp = value_of
replacement ||= lambda do |match|
return "" if match.nil?
arguments = [match] + $~.captures + [$~.begin(0), string]
offset, result = 1, ""
@values.each do |item|
nxt = offset + item.length + 1
if arguments[offset] # do we have a result?
rep = item.replacement
if rep.is_a?(Proc)
args = arguments[offset...nxt]
index = arguments[-2]
result = rep.call *(args + [index, string])
else
result = rep.is_a?(Numeric) ? arguments[offset + rep] : rep.to_s
end
end
offset = nxt
end
result
end
replacement.is_a?(Proc) ? string.gsub(regexp, &replacement) :
string.gsub(regexp, replacement.to_s)
end
def test(string)
exec(string) != string
end
def to_s
length = 0
"(" + @values.map { |item|
# Fix back references.
ref = item.to_s.gsub(BACK_REF) { |m| "\\" + (1 + $1.to_i + length).to_s }
length += item.length + 1
ref
}.join(")|(") + ")"
end
def value_of(type = nil)
return self if type == Object
flag = @ignore_case ? Regexp::IGNORECASE : nil
Regexp.new(self.to_s, flag)
end
class Item
attr_accessor :expression, :length, :replacement
def initialize(expression, replacement)
@expression = expression.is_a?(Regexp) ? expression.source : expression.to_s
if replacement.is_a?(Numeric)
replacement = "\\" + replacement.to_s
elsif replacement.nil?
replacement = ""
end
# does the pattern use sub-expressions?
if replacement.is_a?(String) and replacement =~ /\\(\d+)/
# a simple lookup? (e.g. "\2")
if replacement.gsub(/\n/, " ") =~ /^\\\d+$/
# store the index (used for fast retrieval of matched strings)
replacement = replacement[1..-1].to_i
else # a complicated lookup (e.g. "Hello \2 \1")
# build a function to do the lookup
q = (replacement.gsub(/\\./, "") =~ /'/) ? '"' : "'"
replacement = replacement.gsub(/\r/, "\\r").gsub(/\\(\d+)/,
q + "+(args[\\1]||" + q+q + ")+" + q)
replacement_string = q + replacement.gsub(/(['"])\1\+(.*)\+\1\1$/, '\1') + q
replacement = lambda { |*args| eval(replacement_string) }
end
end
@length = RegexpGroup.count(@expression)
@replacement = replacement
end
def to_s
@expression
end
end
def self.count(expression)
expression = expression.to_s.gsub(ESCAPE_CHARS, "").gsub(ESCAPE_BRACKETS, "")
expression.scan(BRACKETS).length
end
end
end
| true |
e3393eb1a8d39665bdc84baf82ede641353c0bc2
|
Ruby
|
apomata/tdd
|
/triangle.rb
|
UTF-8
| 981 | 3.71875 | 4 |
[] |
no_license
|
require_relative 'Rectangle'
require 'pry'
class Triangle
attr_accessor :c1, :c2, :c3
def initialize(x, y, z)
if (x.class == Point && y.class == Point && z.class == Point)
@c1 = x
@c2 = y
@c3 = z
else
raise ArgumentError
end
end
def area
#area of outside triangles
#(the triangels made by the sides of the given triangle and the containgin rerctangle)
r1 = Rectangle.new(@c1, @c2).area/2
r2 = Rectangle.new(@c1, @c3).area/2
r3 = Rectangle.new(@c2, @c3).area/2
#fet mins and maxes
xs = [@c1.x, @c2.x, @c3.x]
ys = [@c1.y, @c2.y, @c3.y]
#get area of rectangle that would contain tringle
rt = Rectangle.new(Point.new(xs.min,ys.min), Point.new(xs.max,ys.max)).area
#gets a rectangle that would cntain whole triangle and the triangles
return rt-r1-r2-r3
end
end
=begin
@c1 = Point.new(0.0, 0.0)
@c2 = Point.new(0.0, 1.0)
@c3 = Point.new(2.0, 0.0)
@t = Triangle.new(@c1, @c2, @c3)
@t.area
=end
| true |
335fa25dbea6d72d977734014108f7f649b4e893
|
Ruby
|
pencilcheck/tab-sync-websocket
|
/middlewares/backend.rb
|
UTF-8
| 1,443 | 2.546875 | 3 |
[] |
no_license
|
require 'faye/websocket'
require 'json'
$stdout.sync = true
def symbolize_keys(hash)
hash.inject({}){|result, (key, value)|
new_key = case key
when String then key.to_sym
else key
end
new_value = case value
when Hash then symbolize_keys(value)
else value
end
result[new_key] = new_value
result
}
end
class Backend
def initialize(app)
@clients = {}
@app = app
end
def call(env)
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, {ping: 15}) # secs
ws.on :open do |event|
p "open connection #{ws.object_id}"
@clients[ws.object_id] = ws
ws.send({type: 'onopen', payload: ws.object_id}.to_json)
end
ws.on :message do |event|
data = symbolize_keys(JSON.parse(event.data))
p "on message #{data}"
if data[:type] == 'setup'
@clients[data[:payload][1]] = @clients[data[:payload][0]]
@clients[data[:payload][0]] = nil
else
@clients[data[:dest_id]].send(data.to_json) if @clients[data[:dest_id]]
end
end
ws.on :error do |event|
p 'error client', event
end
ws.on :close do |event|
p "close connection #{ws.object_id}"
@clients.delete(ws)
ws.send('Bye Bye')
ws = nil
end
ws.rack_response
end
end
end
| true |
5166e4251037c6051b31a812c76d9efd107adfce
|
Ruby
|
loschtreality/App_Academy
|
/Algo_Projects/BST_AVL/lib/bst.rb
|
UTF-8
| 4,644 | 3.296875 | 3 |
[] |
no_license
|
require 'byebug'
class BSTNode
attr_accessor :left, :right
attr_reader :value
def initialize(value)
@value = value
@left = left
@right = right
end
end
class BinarySearchTree
def initialize
@root = nil
end
def insert(value)
if @root.nil?
@root = BSTNode.new(value)
else
BinarySearchTree.insert!(@root,value)
end
end
def find(value)
search = BinarySearchTree.find!(@root, value)
return nil if search.nil?
search
end
def inorder
BinarySearchTree.inorder!(@root)
end
def postorder
BinarySearchTree.postorder!(@root)
end
def preorder
BinarySearchTree.preorder!(@root)
end
def height
BinarySearchTree.height!(@root)
end
def min
BinarySearchTree.min(@root)
end
def max
BinarySearchTree.max(@root)
end
def delete(value)
BinarySearchTree.delete!(@node, value)
end
def self.insert!(node, value)
# set new node value if no node is passsed in
node = BSTNode.new(value) if node.nil?
case node.value <=> value
# when the node value is less than the passed value
when -1
if node.right
# recurse if present
self.insert!(node.right, value)
else
# set if not present
node.right = BSTNode.new(value)
end
# when node value is greater than the passed value
when 1
if node.left
self.insert!(node.left, value)
else
node.left = BSTNode.new(value)
end
# when the values are equal, default to the left side
when 0
if node.left
self.insert!(node.left, value)
else
node.left = BSTNode.new(value)
end
end
node
end
def self.find!(node, value)
return nil if node.nil?
case node.value <=> value
when -1
# recurse right when the node value is less than the passed value
return self.find!(node.right, value)
when 1
# recurse left when the node value is greater than the passed value
return self.find!(node.left, value)
when 0
# return node if values are equal
return node
end
nil
end
def self.preorder!(node)
return [] if node.nil?
[node.value] + self.preorder!(node.left) + self.preorder!(node.right)
end
def self.inorder!(node)
return [] if node.nil?
self.inorder!(node.left) + [node.value] + self.inorder!(node.right)
end
def self.postorder!(node)
return [] if node.nil?
self.postorder!(node.left) + self.postorder!(node.right) + [node.value]
end
def self.height!(node)
# if unexistant node
return -1 if node.nil?
# if only child
return 0 if (node.left.nil? && node.right.nil?)
# start count with 1, recursively add left and right sides separately
left_count = 1
right_count = 1
left_count += self.height!(node.left)
right_count += self.height!(node.right)
# return the greater of the left and right
return [left_count, right_count].max
end
def self.max(node)
# return nil if node isn't passed in
return nil if node.nil?
max = node.right
current_node = node.right
# check find the right-most child
until current_node.right.nil?
max = current_node.right
current_node = current_node.right
end
# return right-most child node
max
end
def self.min(node)
# return nil if node isn't passed in
return nil if node.nil?
min = node.left
current_node = node.left
# check find the left-most child
until current_node.left.nil?
min = current_node.left
current_node = current_node.left
end
# return left-most child node
min
end
def self.delete_min!(node)
return nil unless node
# return the right node if the left isn't present
return node.right unless node.left
# left node will be set to nil in the base case, right-side node will be returned if present
node.left = self.delete_min!(node.left)
node
end
def self.delete!(node, value)
return nil if node.nil?
case node.value <=> value
# Recurse right when node value is less than passed value
when -1
node.right = self.delete!(node.right, value)
when 1
# Recurse left when node value is greater than passed value
node.left = self.delete!(node.left, value)
when 0
# Return children if they exist
return node.left unless node.right
return node.right unless node.left
original = node
node = original.right.min
node.right = self.delete_min!(original.right)
node.left = original.left
end
node
end
end
| true |
c526131fcd4d1bb4df46c64d803c6140d94bf25a
|
Ruby
|
andrewlarssen/bitmap_editor
|
/app/bitmap_editor.rb
|
UTF-8
| 2,323 | 3.90625 | 4 |
[] |
no_license
|
# Main program controller
class BitmapEditor
def run
@running = true
puts 'type ? for help'
while @running
print '> '
input = gets.chomp
command, *arguments = input.split(' ')
execute_command(command, arguments)
end
end
def execute_command(command, arguments)
case command
when '?'
show_help
when 'C'
clear
when 'L'
pixel arguments
when 'V'
vertical arguments
when 'H'
horizontal arguments
when 'I'
init arguments
when 'S'
show
when 'X'
exit_console
else
output 'unrecognised command :('
end
rescue NoMethodError
output 'must init an image first' unless @image
end
private
def output(message)
return unless @running
puts message
end
def clear
width = @image.width
height = @image.height
@image = Bitmap.new(width, height)
end
def pixel(arguments)
x = arguments[0].to_i
y = arguments[1].to_i
colour = arguments[2]
@image.set_pixel(x, y, colour)
output_errors
end
def vertical(arguments)
x = arguments[0].to_i
y1 = arguments[1].to_i
y2 = arguments[2].to_i
colour = arguments[3]
@image.set_vertical_segment(x, y1, y2, colour)
output_errors
end
def horizontal(arguments)
x1 = arguments[0].to_i
x2 = arguments[1].to_i
y = arguments[2].to_i
colour = arguments[3]
@image.set_horizontal_segment(x1, x2, y, colour)
output_errors
end
def init(arguments)
width = arguments.first.to_i
height = arguments.last.to_i
@image = Bitmap.new(width, height)
end
def show
output @image.contents
end
def output_errors
output @image.errors.join("\n") if @image.errors.any?
end
def exit_console
output 'goodbye!'
@running = false
end
def show_help
output "? - Help
I M N - Create a new M x N image with all pixels coloured white (O).
C - Clears the table, setting all pixels to white (O).
L X Y C - Colours the pixel (X,Y) with colour C.
V X Y1 Y2 C - Draw a vertical segment of colour C in column X between rows Y1 and Y2 (inclusive).
H X1 X2 Y C - Draw a horizontal segment of colour C in row Y between columns X1 and X2 (inclusive).
S - Show the contents of the current image
X - Terminate the session"
end
end
| true |
cacc3c2d834f6356ab6b9973365030b072a08844
|
Ruby
|
Hareramrai/bowling-game
|
/app/models/games/frame_score.rb
|
UTF-8
| 853 | 3.21875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
class Games::FrameScore
PINS = 10
class << self
def find_scores(frames, frame_number)
frame_score = 0
if strike?(frames, frame_number)
frame_score = score(frames, frame_number, 3)
frame_number += 1
elsif spare?(frames, frame_number)
frame_score = score(frames, frame_number, 3)
frame_number += 2
else
frame_score = score(frames, frame_number, 2)
frame_number += 2
end
[frame_score, frame_number]
end
private
def strike?(frames, frame_number)
frames[frame_number].presence == PINS
end
def spare?(frames, frame_number)
frames[frame_number, 2]&.sum == PINS
end
def score(frames, index, number_of_elements)
frames[index, number_of_elements]&.sum
end
end
end
| true |
90df99ad622f21d6312f0b365bfd2441f935f3cb
|
Ruby
|
PhillipDMorrisJr/babble
|
/tests/tile_group/test_hand.rb
|
UTF-8
| 711 | 2.90625 | 3 |
[] |
no_license
|
require "minitest/autorun"
require_relative "../../tile_group.rb"
class TileGroup::TestHand < Minitest::Test
def setup
@tiles = TileGroup.new
end
def test_convert_empty_group_to_string
assert_equal "", @tiles.hand
end
def test_convert_single_tile_group_to_string
@tiles.append(:Z)
assert_equal "Z", @tiles.hand
end
def test_convert_multi_tile_group_to_string
@tiles.append(:P)
@tiles.append(:D)
@tiles.append(:M)
@tiles.append(:J)
assert_equal "PDMJ", @tiles.hand
end
def test_convert_multi_tile_group_with_duplicates_to_string
@tiles.append(:P)
@tiles.append(:H)
@tiles.append(:I)
@tiles.append(:L)
@tiles.append(:L)
assert_equal "PHILL", @tiles.hand
end
end
| true |
57fbfface3b9a6561364cdef8fd32ccb54749549
|
Ruby
|
mituba38/furima_28356
|
/spec/models/user_spec.rb
|
UTF-8
| 4,102 | 2.625 | 3 |
[] |
no_license
|
require 'rails_helper'
describe User do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
context '新規登録がうまくいくとき' do
it '全てのデータがあれば保存できること' do
expect(@user).to be_valid
end
end
context '新規登録がうまくいかないとき' do
it 'nicknameが空だと登録できない' do
@user.nickname = ''
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'emailが空では登録できない' do
@user.email = ''
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it '重複したemailが存在する場合登録できない' do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include('Email has already been taken')
end
it 'emailに@が含まれていないと登録できない' do
@user.email = 'aaaaaaa.com'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it 'passwordが空では登録できない' do
@user.password = ''
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'passwordが5文字以下であれば登録できない' do
@user.password = 'aaaa'
@user.valid?
expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
end
it 'passwordが半角英数字混合でなければ登録できない' do
@user.password = 'AAAAAあ1'
@user.password_confirmation = @user.password
@user.valid?
expect(@user.errors.full_messages).to include('Password は半角英数字で入力してください。')
end
it 'passwordは確認用を含めて2回入力すること' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include('Password confirmation doesn\'t match Password')
end
it 'first_nameが空だと登録できない' do
@user.first_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("First name can't be blank")
end
it 'first_nameが全角でなければ登録できない' do
@user.first_name = 'aa'
@user.valid?
expect(@user.errors.full_messages).to include('First name は全角で入力してください。')
end
it 'last_nameが空だと登録できない' do
@user.last_name = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last name can't be blank")
end
it 'last_nameが全角でなければ登録できない' do
@user.last_name = 'aa'
@user.valid?
expect(@user.errors.full_messages).to include('Last name は全角で入力してください。')
end
it 'first_name_kanaが空だと登録できない' do
@user.first_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("First name kana can't be blank")
end
it 'first_name_kanaが全角カナでなければ登録できない' do
@user.first_name_kana = 'aa'
@user.valid?
expect(@user.errors.full_messages).to include('First name kana は全角カタカナで入力して下さい。')
end
it 'last_name_kanaが空だと登録できない' do
@user.last_name_kana = ''
@user.valid?
expect(@user.errors.full_messages).to include("Last name kana can't be blank")
end
it 'last_name_kanaが全角カナでなければ登録できない' do
@user.last_name_kana = 'aa'
@user.valid?
expect(@user.errors.full_messages).to include('Last name kana は全角カタカナで入力して下さい。')
end
end
end
end
| true |
53622069862fa5f91ff1daec2418950ca10a7f26
|
Ruby
|
ryanhouston/share-brew
|
/app/models/beer_xml/acts_as_beer_importer.rb
|
UTF-8
| 1,934 | 2.75 | 3 |
[] |
no_license
|
module BeerXml
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_beer_importer_of type
cattr_accessor :beer_importer_type, :attr_map, :method_map
self.beer_importer_type = type
send :include, InstanceMethods
self
end
def translated_as xml_to_model_map
self.attr_map = xml_to_model_map
self
end
def using xml_to_method_map
self.method_map = xml_to_method_map
self
end
def import_from_hash style_hash
beer_style = self.new
beer_style.load_defaults style_hash
beer_style.run_translation_callbacks(style_hash) if self.method_map
beer_style
end
def import_beer_xml filename
@importer ||= BeerXml::Importer.new
@importer.import filename
@importer.send self.beer_importer_type, self
end
end
module InstanceMethods
def load_defaults style_hash
style_hash.each do |attr_key, attr_value|
style_attr = attr_key.downcase
attempt_set_attr style_attr, attr_value
end
end
private
def attempt_set_attr style_attr, attr_value
begin
send "#{style_attr}=", attr_value
rescue NoMethodError
load_override_if_provided(style_attr, attr_value)
end
end
def load_override_if_provided style_attr, attr_value
if self.attr_map && self.attr_map[style_attr.to_sym]
mapped_attr = self.attr_map[style_attr.to_sym]
logger.debug "Mapping beer XML <#{style_attr}> to [#{mapped_attr}]\n"
send "#{mapped_attr}=", attr_value
else
logger.debug "No override mapping for #{style_attr}\n"
end
end
public
def run_translation_callbacks style_hash
self.method_map.each do |model_attr, model_method|
translated_value = send model_method, style_hash
send "#{model_attr}=", translated_value
end
end
end
end
| true |
ed20b1021c7b71b8533aa085be8011978161a3e4
|
Ruby
|
yukiyao119/ruby-objects-belong-to-lab-dumbo-web-82619
|
/lib/song.rb
|
UTF-8
| 239 | 3.171875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song
attr_accessor :title, :artist
def initialize
@title = "7/11"
end
end
# song = Song.new("title")
# I have access to song.artist => instance beyonce
# I also have access to song.artist.name => "Beyonce "
| true |
54988cea9d21b1b9bc3e589fe573c38031f23318
|
Ruby
|
SephoraM/LS-small-problems
|
/easy5/after_midnight2.rb
|
UTF-8
| 479 | 3.390625 | 3 |
[] |
no_license
|
require 'date'
MINS_PER_HR = 60
HRS_PER_DAY = 24
def after_midnight(time)
hrs, mins = time.split(':')
((hrs.to_i % HRS_PER_DAY) * MINS_PER_HR) + mins.to_i
end
def before_midnight(time)
hrs, mins = time.split(':')
-((-(hrs.to_i % HRS_PER_DAY) * MINS_PER_HR) + mins.to_i)
end
p after_midnight('00:00') == 0
p before_midnight('00:00') == 0
p after_midnight('12:34') == 754
p before_midnight('12:34') == 686
p after_midnight('24:00') == 0
p before_midnight('24:00') == 0
| true |
6dc946bc14e6449186fac7aaf1fae39d309838ff
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/filtered-submissions/950ae0c298634aa6841fb346f3667562.rb
|
UTF-8
| 300 | 3.25 | 3 |
[] |
no_license
|
def compute(source, dest)
return nil unless source.kind_of?(String) and dest.kind_of?(String)
distance = 0
max_length = source.length > dest.length ? dest.length : source.length
0.upto(max_length - 1) do |idx|
distance += 1 if source[idx] != dest[idx]
end
distance
end
| true |
e25232364ae948224017ad49ef77ded18bc52206
|
Ruby
|
sunspot82/605.484
|
/project1/test/document_set_test.rb
|
UTF-8
| 2,734 | 2.515625 | 3 |
[] |
no_license
|
require "test/unit"
require "project1/src/document_set"
#****************************************************************
# Test the DocumentSet object.
#****************************************************************
class DocumentSetTest < Test::Unit::TestCase
#****************************************************************
# Setup method.
#****************************************************************
def setup
#setup
@docSet = DocumentSet.new
end
#****************************************************************
# Test the DocmentSet.getOutliers method. (Negative - bad path)
#****************************************************************
def test_neg_get_outliers
@docSet.getOutliers "invalid/path"
assert_equal(@docSet.documentList.length,0)
assert_equal(@docSet.termInDocCountMap.size,0)
end
#****************************************************************
# Test the DocumentSet.getOutliers method.
#****************************************************************
def test_get_outliers
outliers = @docSet.getOutliers "project1/test/resources/data/other"
# A list of terms
assert(outliers)
end
#****************************************************************
# Test the DocumentSet.getSetSimilarity method.
#****************************************************************
def test_get_set_similarity
scores = @docSet.getSetSimilarity "project1/test/resources/data/other"
# A list of similarity scores
assert_equal(scores.length,3)
end
#****************************************************************
# Test the DocumentSet.getSetSimilarity method.
#****************************************************************
def test_get_set_similarity
scores = @docSet.getSetSimilarity "invalid/path"
# A list of similarity scores
assert_equal(scores.length,0)
end
#****************************************************************
# Test the DocumentSet.getSetSimilarityToOwner method.
#****************************************************************
def test_get_set_similarity_to_owner
scores = @docSet.getSetSimilarityToOwner "project1/test/resources/data/other","sunspot82"
# A list of similarity scores.
assert_equal(scores.length,2)
end
#****************************************************************
# Test the DocumentSet.getSetSimilarityToOwner method (Negative).
#****************************************************************
def test_neg_get_set_similarity_to_owner
scores = @docSet.getSetSimilarityToOwner "project1/test/resources/data/other","invalid_user"
# A list of similarity scores.
assert_equal(scores.length,0)
end
end
| true |
c906c50389a572f3faea47c178a9ad40a8e423d8
|
Ruby
|
MI3Guy/Math-Seminar-Project--The-Prime-Detective
|
/prime-analysis.rb
|
UTF-8
| 577 | 3.328125 | 3 |
[] |
no_license
|
require "constants.rb"
primes = File.read("primes.txt").split("\n").collect { |n| n.to_i }
composites = File.read("composite.txt").split("\n").collect { |n| n.to_i }
puts "Prime: #{primes.length}, #{primes.length.to_f/(primes.length + composites.length)}"
part_size = MAX_PRIME/20
parts = []
count = 0
primes.each do |p|
if p > part_size * (parts.length + 1)
parts << count
count = 0
end
count += 1
end
parts << count
count = 0
p parts
p parts.collect { |x| x.to_f / primes.length }
n = 0
while part_size * (n + 1) > MAX_PRIME
puts part_size * (n + 1)
n += 1
end
| true |
383b294bf9c487293efe035d62f5f2fa2f0defc2
|
Ruby
|
Q-Win/battleship
|
/test/guess_test.rb
|
UTF-8
| 1,202 | 3.03125 | 3 |
[] |
no_license
|
require 'simplecov'
SimpleCov.start
require 'minitest/autorun'
require 'minitest/pride'
require './lib/board'
require './lib/ship'
require './lib/guess'
class BoardTest < Minitest::Test
def test_it_exists
guess = Guess.new(4)
assert_instance_of Guess, guess
end
def test_it_has_a_board
guess = Guess.new(3)
expected_3 = [[' ', ' ',' '],[' ', ' ',' '],[' ', ' ',' ']]
assert_equal expected_3, guess.board
end
def test_it_can_record_hit_or_miss
guess = Guess.new(4)
board = Board.new(4,guess)
ship = Ship.new(["A1","A2"])
board.place_ship(ship)
assert_equal " ", guess.board[0][1]
assert_equal " ", guess.board[2][3]
board.record_guess("A2")
board.record_guess("C4")
assert_equal "H", guess.board[0][1]
assert_equal "M", guess.board[2][3]
end
def test_it_can_print_board
guess = Guess.new(4)
board = Board.new(4,guess)
ship = Ship.new(["A1","A2"])
board.place_ship(ship)
assert guess.print_board
end
def test_it_can_build_a_board
guess = Guess.new(4)
board = Board.new(4,guess)
ship = Ship.new(["A1","A2"])
board.place_ship(ship)
assert guess.build_board(4)
end
end
| true |
2934b8838401ee5444451d5599d5d98a204e3057
|
Ruby
|
dojopiaui/conversor-de-moedas
|
/spec/moeda_spec.rb
|
UTF-8
| 1,488 | 2.96875 | 3 |
[] |
no_license
|
require File.dirname(__FILE__) + '/spec_helper'
describe "Moeda" do
it "deve converter de euro para dolar" do
valor = 10
moeda = Moeda.new(valor, "EUR")
moeda2 = moeda.converter("USD")
moeda2.quantia.should == 14.20
moeda2.moeda_base.should == "USD"
moeda2.class.should == Moeda
end
it "deve converter de dolar para euro" do
valor = 14.20
moeda = Moeda.new(valor, "USD")
moeda.converter("EUR").quantia.should == 10.0
end
it "deve converter de euro para real" do
valor = 10
moeda = Moeda.new(valor, "EUR")
moeda.converter("BRL").quantia.should == 26.6
end
it "deve converter de real para euro" do
valor = 26.6
moeda = Moeda.new(valor, "BRL")
moeda.converter("EUR").quantia.should == 10.0
end
it "deve converter de real para dólar" do
valor = 26.60
moeda = Moeda.new(valor, "BRL")
moeda.converter("USD").quantia.should == 14.20
end
it "deve converter de dolar para real" do
valor = 14.20
moeda = Moeda.new(valor, "USD")
moeda.converter("BRL").quantia.should == 26.60
end
it "deve retornar uma moeda" do
valor = 14.20
moeda = Moeda.new(valor, "USD")
moeda.converter("BRL").class.should == Moeda
end
it "deve converter de real para Yene" do
valor = 26.60
moeda = Moeda.new(valor, "BRL")
moeda2 = moeda.converter("JPY")
moeda2.quantia.should == 1343.20
moeda2.moeda_base.should == "JPY"
moeda2.class.should == Moeda
end
end
| true |
21e9e514764b15328587fe3d1e4b282adba50066
|
Ruby
|
mikisvaz/rbbt-util
|
/lib/rbbt/util/simpleopt/parse.rb
|
UTF-8
| 1,808 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
require 'rbbt/util/simpleopt/accessor'
module SOPT
def self.fix_shortcut(short, long)
return short unless short and shortcuts.include?(short)
current = shortcuts.select{|s,l| l == long}.collect{|s,l| s }.first
return current if current
chars = long.chars.to_a
current = [chars.shift]
short = current * ""
if (shortcuts.include?(short) and not shortcuts[short] == long)
if long.index "-" or long.index "_"
parts = long.split(/[_-]/)
acc = parts.collect{|s| s[0] } * ""
return acc unless shortcuts.include? acc
elsif m = long.match(/(\d+)/)
n = m[0]
acc = long[0] + n
return acc unless shortcuts.include? acc
end
end
while shortcuts.include?(short) && shortcuts[short] != long
next_letter = chars.shift
next_letter = chars.shift while %w(. - _).include?(next_letter)
return nil if next_letter.nil?
current << next_letter
short = current * ""
end
return nil if shortcuts.include? short
short
end
def self.register(short, long, asterisk, description)
short = fix_shortcut(short, long)
shortcuts[short] = long if short
inputs << long
input_shortcuts[long] = short
input_descriptions[long] = description
input_types[long] = asterisk ? :string : :boolean
end
def self.parse(opt_str)
info = {}
inputs = []
if opt_str.include? "\n"
re = /\n+/
else
re = /:/
end
opt_str.split(re).each do |entry|
entry.strip!
next if entry.empty?
names, _sep, description = entry.partition /\s+/
short, long, asterisk = names.match(/\s*(?:-(.+))?(?:--(.+?))([*])?$/).values_at 1,2,3
inputs << long
register short, long, asterisk, description
end
inputs
end
end
| true |
34a05007681572c8fe8fc47ea3ed6ad40afa7362
|
Ruby
|
noahskang/Portfolio
|
/w1d2 2/MemoryGame/AIPlayer.rb
|
UTF-8
| 300 | 3.671875 | 4 |
[] |
no_license
|
class AIPlayer
def initialize(name = "Bob")
@name = name
end
def get_guess
puts "Pick a card. e.g. 2, 3: "
user_guess = arr_conversion(gets.chomp)
user_guess
end
def arr_conversion(user_guess)
user_guess.split(", ").map(&:to_i)
end
def to_s
@name
end
end
| true |
66cd8a3fa5dff0c752b84627c756f83965e78429
|
Ruby
|
pombredanne/neo4j-perf
|
/wrapper.rb
|
UTF-8
| 882 | 2.703125 | 3 |
[] |
no_license
|
include Java
require 'model'
DB_PATH = "tmp/neo4j"
class Neo4jTraversal
attr_reader :traversed
def visit_ref_node
@traversed = 1
rel = Neo4j.ref_node._rel(:outgoing, 'root')
root = rel._end_node
traverse(root)
end
def traverse(folder)
size = folder[:size] || 0
folder.incoming(:parent_folder).incoming(:folder).depth(:all).iterator.each do |node|
size += node[:size] if node.property?(:size) #&& node.property?(:file_id)
@traversed += 1
end
size
end
def shutdown
Neo4j.shutdown
end
end
trav = Neo4jTraversal.new
TIMES = 10
total_time = 0
TIMES.times.each do |i|
start_time = Time.now
size = trav.visit_ref_node
delta = Time.now - start_time
puts "#{i+1} -- traversed #{trav.traversed} nodes #{size} bytes, in #{delta} seconds"
total_time += delta
end
trav.shutdown
| true |
96d19769e85d0015b442648704fcfc8426e41e55
|
Ruby
|
mmorast/ha_demoqa
|
/poms/index_page.rb
|
UTF-8
| 904 | 2.546875 | 3 |
[] |
no_license
|
require_relative './account_page'
require_relative './base_page'
class IndexPage < BasePage
def initialize(webdriver)
super()
@driver = webdriver
goto_page
end
def goto_page
@driver.get(@url_base) unless @driver.current_url == "#{@url_base}"
self
end
def login_as(username, password)
@driver.find_element(:id, 'account').find_element(:css, 'a').click
AccountPage.new(driver).login_as(username, password)
self
end
def goto_product_category(product_category)
goto_page
prod_cat_menu_item = @driver.find_element(:id, 'menu-item-33')
@driver.action.move_to(prod_cat_menu_item).perform
Selenium::WebDriver::Wait.new(timeout:2).until do
@driver.find_element(:link_text, product_category).displayed?
end
@driver.find_element(:link_text, product_category).click
ProductCategoryPage.new(driver, product_category)
end
end
| true |
e09107327d3c12b6707231b9f3f31cf4773e3e5c
|
Ruby
|
luca-montaigut/Archives_THP
|
/4.4_morpion/lib/app/game.rb
|
UTF-8
| 2,094 | 3.328125 | 3 |
[] |
no_license
|
# frozen_string_literal: true
# Gestion d'une partie
class Game
attr_accessor :current_player, :status, :board, :players
def initialize(player1, player2)
# cree 2 joueurs, un board, etc...
@players = []
@players << player1
@players << player2
@status = 'on going'
@board = Board.new
@current_player = @players[0]
end
def count_turn
@board.count_turn
end
def turn
# Affiche le plateau,
Show.new.show_board(@board, @players)
# Demande au joueur ce qu'il veut jouer
@board.play_turn(@current_player, players)
# Verifie si le joueur a gagne
print "\n Votre tour est terminé"
gets.chomp
game_end if @board.victory? == true || @board.count_turn == 10
# Passe au joueur suivant
@current_player = if @current_player == @players[0]
@players[1]
else
@players[0]
end
end
def new_round
# Relance une partie : nouveau board mais memes joueurs.
@board = Board.new
@status = 'on going'
puts "\n C'est reparti !"
end
def game_end
# Affiche la fin de partie : vainqueur ou match nul
system('clear')
header
puts '=' * 50
puts ' Fin de la partie'
puts '=' * 50
if @board.victory?
@current_player.victories += 1
Show.new.show_board(@board, @players)
print "\n\n 🏆 #{@current_player.name} a gagné ! Bravo #{@current_player.name} "
gets.chomp
else
Show.new.show_board(@board, @players)
print "\n\n Égalité !\n"
end
@status = 'game end'
end
def header
puts ''
puts "\n"
puts ' ___ ___ _'
puts ' | \\/ | (_)'
puts ' | . . | ___ _ __ _ __ _ ___ _ __'
puts ' | |\\/| |/ _ \\| \'__| \'_ \\| |/ _ \\| \'_ \\'
puts ' | | | | (_) | | | |_) | | (_) | | | |'
puts ' \\_| |_/\\___/|_| | .__/|_|\\___/|_| |_|'
puts ' | |'
puts ' |_|'
puts ''
end
end
| true |
35ff721bcb18d56a6ceb03421dfb10e5f0cafbcb
|
Ruby
|
jamesonbass1987/sql-crowdfunding-lab-v-000
|
/lib/sql_queries.rb
|
UTF-8
| 1,838 | 3.21875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Write your sql queries in this file in the appropriate method like the example below:
#
# def select_category_from_projects
# "SELECT category FROM projects;"
# end
# Make sure each ruby method returns a string containing a valid SQL statement.
def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name
"SELECT projects.title, sum(amount) AS pledge_amount
FROM pledges
JOIN projects
WHERE pledges.project_id = projects.id
GROUP BY project_id
ORDER BY projects.title;"
end
def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name
"SELECT name, age, sum(pledges.amount) AS pledge_amount
FROM users
JOIN pledges
WHERE users.id = pledges.user_id
GROUP BY users.name
ORDER BY users.name"
end
def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal
"SELECT projects.title, sum(amount) - projects.funding_goal AS pledge_amount_difference
FROM pledges
JOIN projects
WHERE pledges.project_id = projects.id
GROUP BY project_id HAVING pledge_amount_difference >= 0
ORDER BY pledge_amount_difference;"
end
def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount_and_users_name
"SELECT name, sum(pledges.amount) AS pledge_amount
FROM users
JOIN pledges
WHERE users.id = pledges.user_id
GROUP BY users.name
ORDER BY pledge_amount"
end
def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category
"SELECT category, pledges.amount AS pledge_amount
FROM projects
JOIN pledges
ON projects.id = pledges.project_id
WHERE projects.category = 'music'"
end
def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category
"SELECT projects.category, SUM(amount)
FROM pledges
JOIN projects
ON pledges.project_id = projects.id
WHERE projects.category = 'books'"
end
| true |
afffaaaf571a925a583aad3c83fa811673ad061d
|
Ruby
|
justingaylor/rng
|
/lib/rng/name_file_loader.rb
|
UTF-8
| 968 | 2.984375 | 3 |
[] |
no_license
|
module Rng
class NameFileLoader
attr_reader :segmenter
def initialize(segmenter=Rng::Segmenters::FantasyNameSegmenter)
reinitialize(segmenter)
end
def load(path)
reinitialize(segmenter)
raise Rng::FileLoadError.new("File '#{path}' does not exist.") unless File.exists?(path)
# Open the file
count = 0
@file = File.new(path, File::RDONLY)
@file.readlines.each do |line|
tokens = line.chomp.strip.split(',')
name = tokens[0]
if name != '' && name != 'Name'
name = Name.new(name.downcase.capitalize, segmenter)
#puts name.syllables.join(" / ")
@names << name
end
end
# Close the file
@file.close
return @names.sort {|a,b| a.name <=> b.name}
end
private
def reinitialize(segmenter)
@names = []
@file = nil
@segmenter = segmenter
end
end
end
| true |
1f411a954e58a5ddc6238303e4c820d2464b4fc6
|
Ruby
|
mikedao/httpyykm
|
/lib/word_search.rb
|
UTF-8
| 270 | 3.109375 | 3 |
[] |
no_license
|
class WordSearch
DICTIONARY = File.read("/usr/share/dict/words").split("\n")
def result(word)
dict = DICTIONARY
dict.include?(word)
if dict.include?(word)
"#{word} is a known word."
else
"#{word} is not a known word."
end
end
end
| true |
4c3fc00b75ad21125f43f9fbe980197068332fc9
|
Ruby
|
seldomatt/playlister-rb
|
/lib/song.rb
|
UTF-8
| 415 | 3.296875 | 3 |
[] |
no_license
|
require_relative 'genre'
class Song
attr_accessor :name, :artist
attr_reader :genre
@@songs = []
def initialize
@@songs << self
end
def self.all
@@songs
end
def genre=(genre)
@genre = genre
genre.songs << self
end
def artist=(artist)
@artist = artist
artist.add_song(self)
end
def self.find(songname)
@@songs.select {|s| s.name == songname}[0]
end
end
| true |
a92035b3b60ee9cb6d1d1fbd3de8edb544d9f67b
|
Ruby
|
poymanov/railswinter2017
|
/np2/lesson31/task-31-01/main.rb
|
UTF-8
| 233 | 3.1875 | 3 |
[] |
no_license
|
# encoding: utf-8
require_relative "lib/hashtags"
puts "Введите строку с хэштегами:"
user_input = STDIN.gets.chomp
result = hashtags(user_input)
puts "Нашли вот такие хэштеги: #{result}"
| true |
6dd3ec9594531969301bc483afcc94a94035c095
|
Ruby
|
ramblex/euler
|
/euler-42.rb
|
UTF-8
| 1,017 | 3.828125 | 4 |
[] |
no_license
|
#
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so
# the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its
# alphabetical position and adding these values we form a word value. For example,
# the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a
# triangle number then we shall call the word a triangle word.
# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file
# containing nearly two-thousand common English words, how many are triangle
# words?
alphabet = ('A'..'Z').to_a
triangle_numbers = (1..100).map {|n| ((0.5 * n) * (n + 1)).to_i }
f = File.open("words.txt")
num_triangle_words = 0
f.read.gsub(/"/, '').split(',').each do |word|
letters = word.split(//)
value = letters.inject(0) { |sum, letter| sum + alphabet.index(letter) + 1 }
num_triangle_words += 1 if triangle_numbers.include? value
end
p num_triangle_words
f.close
| true |
4dea2498f5ae4ae3988e2eb6ac5944264403f42d
|
Ruby
|
TheAlgorithms/Ruby
|
/sorting/merge_sort.rb
|
UTF-8
| 827 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
def merge_sort(array)
return array if array.length <= 1
mid = array.length / 2
first_array = array.slice(0..mid - 1)
second_array = array.slice(mid..-1)
first_array = merge_sort first_array
second_array = merge_sort second_array
# merge
result = []
until first_array.empty? && second_array.empty?
if first_array.empty?
result.concat(second_array)
second_array.clear
elsif second_array.empty?
result.concat(first_array)
first_array.clear
else
result << if first_array.first < second_array.first
first_array.shift
else
second_array.shift
end
end
end
result
end
if $0 == __FILE__
puts 'Enter a list of numbers separated by space'
list = gets.split.map(&:to_i)
p merge_sort(list)
end
| true |
62037dc68e42c044fb511adb76f637e757611d76
|
Ruby
|
aastronautss/ruby-projects
|
/binary-search-tree/binary-search-tree.rb
|
UTF-8
| 2,988 | 3.953125 | 4 |
[] |
no_license
|
class Binary_Search_Tree
attr_accessor :root
def build(ary = [])
shuffled_ary = ary.shuffle
@root = Node.new(shuffled_ary.pop)
until shuffled_ary.empty?
new_node = Node.new(shuffled_ary.pop)
insert(new_node) unless new_node.value.nil?
end
end
def insert(new_node, current_node = @root)
if new_node.value <= current_node.value
if current_node.left.nil?
current_node.left = new_node
new_node.parent = current_node
return
else
insert(new_node, current_node.left)
end
else
if current_node.right.nil?
current_node.right = new_node
new_node.parent = current_node
return
else
insert(new_node, current_node.right)
end
end
end
def breadth_first_search(value)
queue = []
queue.unshift(@root) unless @root.nil?
until queue.empty?
current_node = queue.pop
# puts "CURRENT NODE: #{current_node.value}"
# puts "QUEUE: #{queue.inspect}"
return current_node if current_node.value == value
queue.unshift(current_node.left) unless current_node.left.nil?
queue.unshift(current_node.right) unless current_node.right.nil?
end
nil
end
def depth_first_search(value)
stack = []
stack.push(@root) unless root.nil?
until stack.empty?
current_node = stack.pop
return current_node if current_node.value == value
stack.push current_node.left unless current_node.left.nil?
stack.push current_node.right unless current_node.right.nil?
end
nil
end
def dfs_rec(value, current_node = @root)
return nil if current_node.nil?
result ||= dfs_rec(value, current_node.left)
return current_node if current_node.value == value
result ||= dfs_rec(value, current_node.right)
result
end
def inspect
str = "["
print_node(@root, str)
str = str[0..-3]
str << "]"
str
end
def empty?
@root.nil?
end
private
def print_node(current_node, str)
return str if current_node.nil?
print_node(current_node.left, str)
str << current_node.value.to_s
str << ", "
print_node(current_node.right, str)
end
end
class Node
attr_accessor :value, :parent, :left, :right
def initialize(value = nil, parent = nil, left = nil, right = nil)
@value = value
@parent = parent
@left = left
@right = right
end
def children
ary = []
ary << @left unless @left.nil?
ary << @right unless @right.nil?
ary
end
end
arr = [1, 7, 4, 23, 8, 9, 4, 3, 5, 7, 9, 67, 6345, 324]
tree = Binary_Search_Tree.new
tree.build(arr)
p tree
puts tree.breadth_first_search(1)
p tree.breadth_first_search(10)
puts tree.depth_first_search(1)
puts tree.depth_first_search(324)
p tree.depth_first_search(10)
puts tree.dfs_rec(1)
puts tree.dfs_rec(324)
p tree.dfs_rec(10)
| true |
3cfe2569bbf66fd7f36e26912cfc3f83a564783f
|
Ruby
|
corinneling/apprentice-notes
|
/Project List/pi-to-the-nth.rb
|
UTF-8
| 347 | 4.1875 | 4 |
[] |
no_license
|
# Find PI to the Nth Digit
# Enter a number and have the program generate PI up to that many
# decimal places. Keep a limit to how far the program will go.
def chosen_digit
return gets.chomp.to_i
end
def get_pi
return Math::PI
end
def find_pi_to_digit
p get_pi.round(chosen_digit)
end
print 'Find PI to what number? '
find_pi_to_digit
| true |
5bf4484f28e1f5dd9fcba1ebf746633efb760558
|
Ruby
|
mshopsin/Checkers
|
/player.rb
|
UTF-8
| 756 | 3.609375 | 4 |
[] |
no_license
|
require './board'
require './token'
class Player
attr_reader :color
attr_accessor :board
def initialize(color,board)
@color = color
@board = board
end
def take_turn
raise 'Not implemented'
end
end
class Human < Player
def initialize(color,board)
super(color,board)
end
def take_turn
invalid_move = false
move = []
puts "Player: #{color}"
until invalid_move
puts "please enter:x1,y1,x2,y2"
move_text = gets.chomp
move = move_text.split(',')
move.map!(&:to_i)
invalid_move = move_my_piece(move)
puts "Invalid Move try again" unless invalid_move
end
take_turn if self.board.can_double_jump?(move,self)
end
#[x1,y1,x2,y2]
def move_my_piece(move)
return self.board.move_player_piece(move,self)
end
end
| true |
bd880d0d0d49f2469a66e8715611213cb1363cc3
|
Ruby
|
r-fujiwara/hima-wo-moteamashita-kamigami-no-asobi
|
/clients/multi_client.rb
|
UTF-8
| 581 | 2.890625 | 3 |
[] |
no_license
|
# copy paste from http://morizyun.github.io/blog/parallel-process-ruby-gem/
require "net/http"
require 'open-uri'
require 'thread'
url = "http://localhost:8000"
urls = []
100000.times{|i| urls.push(url) }
urls.push(nil)
q = Queue.new
urls.each { |url| q.push(url) }
max_thread = 8
Array.new(max_thread) do |i|
Thread.new {
begin
while url = q.pop(true)
puts "start request: #{url}\n"
resp = open(url) rescue next
puts resp.read
puts "end request: #{url}\n"
end
q.push nil
end
}
end.each(&:join)
puts "finish process"
| true |
6d9ff7f408c3647cf869ca832203a2b217da8a13
|
Ruby
|
emilianolowe/launch-school-exercises
|
/Ruby/ruby-basic/methods/greeting_through_methods2.rb
|
UTF-8
| 109 | 3.1875 | 3 |
[] |
no_license
|
# Exercise 4
def hello
'Hello'
end
def world
'World'
end
def greet
"#{hello} #{world}"
end
p greet
| true |
53fc28021d00ea68d4ae17832785b449252dd523
|
Ruby
|
urbas/budPage
|
/app/helpers/pages.rb
|
UTF-8
| 2,431 | 2.65625 | 3 |
[] |
no_license
|
module Pages
class Page
def initialize(name, *sub_pages, **options)
@name = name
@sub_pages = Rails.env.production? ? sub_pages.select { |sub_page| !sub_page.is_draft? } : sub_pages
@parent_page = nil
@is_draft = options.fetch(:is_draft, false)
sub_pages.each { |sub_page| sub_page.parent_page = self }
end
def name
@name
end
def sub_pages
@sub_pages
end
def parent_page
@parent_page
end
def is_draft?
@is_draft
end
def path_components
if @path_components.nil?
@path_components = parent_page.nil? ? [name] : parent_page.path_components + [name]
end
@path_components
end
def absolute_path
if @absolute_path.nil?
@absolute_path = path_components.join('/')
end
@absolute_path
end
def find_by_path(absolute_path)
path_to_sub_page[absolute_path]
end
def has_sub_pages?
!@sub_pages.empty?
end
def is_in_path_of?(page)
page == self || !page.parent_page.nil? && is_in_path_of?(page.parent_page)
end
def render_to(renderer)
renderer.render absolute_path
end
protected
def parent_page=(new_parent)
if !new_parent
raise Exception.new('Cannot set the parent to nil.')
elsif parent_page.nil?
@parent_page = new_parent
else
raise Exception.new('Cannot set a parent. The parent has already been set.')
end
end
protected
def path_to_sub_page
if @path_to_sub_page.nil?
@path_to_sub_page = sub_pages.map { |page| page.path_to_sub_page }
.push(sub_pages.map { |page| [page.absolute_path, page] }.to_h)
.reduce({}) { |aggregate, path_to_sub_page| aggregate.merge(path_to_sub_page) }
end
@path_to_sub_page
end
end
class RootPage < Page
def initialize(*sub_pages)
super('root', *sub_pages)
end
def path_components
[]
end
end
class MarkdownPage < Page
def initialize(name, markdown_asset, **options)
super(name, *[], **options)
@markdown_asset = markdown_asset
end
def render_to(renderer)
renderer.render 'markdown_page', locals: {asset_path: @markdown_asset}
end
end
class ContainerPage < Page
def render_to(renderer)
sub_pages[0].render_to(renderer)
end
end
end
| true |
2c837245771bcb9e9910ce6c2d200762be7bc59d
|
Ruby
|
vbsteven/req
|
/lib/req-cli/variable_interpolator.rb
|
UTF-8
| 326 | 3.140625 | 3 |
[] |
no_license
|
class VariableInterpolator
attr_reader :variables
def initialize(variables = {})
@variables = variables.map { |key, value| [key.to_sym, value] }.to_h
end
def interpolate(input)
input.gsub(/\${[a-zA-Z0-9\-_]*}/) do |m|
var = m.scan(/[a-zA-Z0-9\-_]+/).first.to_sym
variables[var]
end
end
end
| true |
c3ad2f62779e2af08935e08df1d73a910ba1a5e4
|
Ruby
|
boldport/boldport-club-community
|
/bin/twitter_harvest/harvest.rb
|
UTF-8
| 3,160 | 2.609375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "twitter"
require "t/rcfile"
require "post"
require 'optparse'
def get_twitter_client
rcfile = T::RCFile.instance
if rcfile.empty?
puts "use `t authorize` to initialize ~/.trc first.."
exit(1)
end
Twitter::REST::Client.new do |config|
config.consumer_key = rcfile.active_consumer_key
config.consumer_secret = rcfile.active_consumer_secret
config.access_token = rcfile.active_token
config.access_token_secret = rcfile.active_secret
end
end
def make_post(tweet)
post = Post.new(nil, nil, tweet.id, tweet.created_at)
post.twitter_id = tweet.id
tweet.media.each do |media|
case media
when Twitter::Media::Photo
post.images << media.media_uri_https
end
end
tweet.uris.each do |uri|
expanded_url = uri.expanded_url.to_s
if expanded_url.include?('/watch?v=')
post.youtube_ids << expanded_url.split('v=').last
end
end
post.source_url = tweet.uri
post.author_name = "@#{tweet.user.screen_name}"
post.author_url = "https://twitter.com/#{tweet.user.screen_name}"
post.title = tweet.full_text.split(' http').first
body = ""
if post.media?
post.youtube_ids.each do |youtube_id|
body += "{% include youtube-embed.html id='#{youtube_id}' %}\n\n"
end
post.images.each do |image|
body += "\n\n"
end
end
body += "{% include twitter-embed.html id='#{post.twitter_id}' %}\n\n"
post.body = body
post
end
def harvest(options)
client = get_twitter_client
if options[:id]
tweets = Array(client.status(options[:id]))
else
tweets = client.search("#BoldportClub", options)
end
tweets.each do |tweet|
print "Processing #{tweet.id} [#{tweet.created_at}] .. "
if tweet.retweet?
puts "skipping: retweet"
next
end
post = make_post(tweet)
if post.exists? && !options[:force]
puts "skipping: post already exists"
next
end
puts "writing: #{post.full_path}"
post.write
end
end
options = {
count: 100, force: false
}
OptionParser.new do |opts|
opts.banner = "Usage: harvest.rb [options]"
opts.on("-c", "--count [COUNT]", "The number of tweets to return per page, up to a maximum of 100.") do |value|
options[:count] = value.to_i
end
opts.on("-u", "--until [YYY-MM-DD]", "Returns tweets generated before the given date. Date should be formatted as YYYY-MM-DD.") do |value|
options[:until] = value
end
opts.on("-s", "--since_id [ID]", "Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.") do |value|
options[:since_id] = value
end
opts.on("-i", "--id [ID]", "Harvest a particular Tweet by ID") do |value|
options[:id] = value
end
opts.on("-f", "--[no-]force", "Force tweet to be harvested even if exists or no media") do |value|
options[:force] = value
end
end.parse!
harvest options
| true |
ebcb573367ef41b0132e14bbc864d5c2d0f26397
|
Ruby
|
KellyPT/betsy
|
/test/models/merchant_test.rb
|
UTF-8
| 2,245 | 2.5625 | 3 |
[] |
no_license
|
require 'test_helper'
class MerchantTest < ActiveSupport::TestCase
test "A new merchant is built with the auth_hash from GitHub" do
merchant = Merchant.build_from_github({ uid: "12345", "info" => { "nickname" => "kelly", "email" => "[email protected]" } })
assert merchant.valid?
end
test "Create a Merchant with valid data" do
merchant = merchants(:one)
assert merchant.valid?
end
test "Merchant must have an email, uid, and provider" do
merchant = Merchant.new
assert_not merchant.valid?
assert_includes merchant.errors, :email
assert_includes merchant.errors, :uid
assert_includes merchant.errors, :provider
end
test "get_merchant_orders will return a collection of all order items associated with that merchant" do
merchant = merchants(:merchant_with_orders)
orders = merchant.get_merchant_orders
assert_kind_of OrderItem::ActiveRecord_Relation, orders
assert_includes orders, order_items(:reduce_quantity1)
assert_includes orders, order_items(:reduce_quantity2)
end
test "get_merchant_orders can be used to filter order collections by order status" do
merchant = merchants(:merchant_with_orders)
orders = merchant.get_merchant_orders
total_orders = orders.count
paid_orders = merchant.get_merchant_orders("paid")
pending_orders = merchant.get_merchant_orders("pending")
completed_orders = merchant.get_merchant_orders("complete")
cancelled_orders = merchant.get_merchant_orders("cancelled")
assert_equal total_orders, paid_orders.count + pending_orders.count + completed_orders.count + cancelled_orders.count
end
test "get_merchant_orders considers a completed order (to the merchant) one that has been shipped, regardless of buyer order_status" do
merchant = merchants(:filter_merchant)
completed_orders = merchant.get_merchant_orders("completed")
assert_includes completed_orders, order_items(:filter_complete_shipped)
assert_includes completed_orders, order_items(:filter_paid_shipped)
# An order shouldn't be able to be marked as complete if order items haven't shipped, but testing for it anyway.
assert_not_includes completed_orders, order_items(:filter_complete_not_shipped)
end
end
| true |
e1ce2bf00547f9ddcab93fe9f63df8febab37e52
|
Ruby
|
mpazcarvacho/Rails_w1_d2
|
/usuario.rb
|
UTF-8
| 534 | 3.609375 | 4 |
[] |
no_license
|
#Desafío 2 - María Paz Carvacho
#Ejercicio 1
class Usuario
attr_accessor :nombre, :cuentas
def initialize(nombre, cuentas = [])
@nombre = nombre
@cuentas = cuentas
if cuentas.empty?
raise RangeError, "El usuario debe tener por lo menos una cuenta bancaria"
end
end
def saldo_total
n = cuentas.length
saldo_total_usuario = 0
n.times do |i|
saldo_total_usuario += cuentas[i].saldo
end
puts "El saldo total del usuario #{self.nombre} es #{saldo_total_usuario.to_s}"
end
end
| true |
19bf4f28fae94c9d97b61f38f00866aef47f79db
|
Ruby
|
dianorlova/Ruby
|
/Ruby_practice/labWork-2/lib/apartment.rb
|
UTF-8
| 1,195 | 3.140625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require_relative '../lib/parameters'
require_relative '../lib/address'
# The class describes the apartment
class Apartment
attr_reader :footage, :number_rooms, :address, :floor, :house_type, :number_of_floors, :cost,
:list_param
include Comparable
def initialize(lst_arg)
footage, number_rooms, address, floor, house_type, number_of_floors, cost, list_param = *lst_arg
@footage = footage.scan(/\d*[.,]?\d+/)[0].to_f
@number_rooms = number_rooms.to_i
@address = Address.new(address.split(','))
@floor = floor.to_i
@house_type = house_type
@number_of_floors = number_of_floors.to_i
@cost = cost.to_f
@list_param = Parameters.new(list_param.split(';'))
end
def to_s
"> #{@footage} кв.м., #{@number_rooms}, #{address}, #{floor}, " \
"#{house_type}, #{number_of_floors}, #{cost} млн#{list_param}"
end
def <=>(other)
[@footage, @number_rooms, @address, @floor, @house_type, @number_of_floors, @cost,
@list_param] <=>
[other.footage, other.number_rooms, other.address, other.floor, other.house_type,
other.number_of_floors, other.cost, other.list_param]
end
end
| true |
b65f6bda25ced4db42b04d987353e15c617cb506
|
Ruby
|
backpackerhh/exercism
|
/ruby/word-count/word_count.rb
|
UTF-8
| 260 | 3.28125 | 3 |
[] |
no_license
|
class Phrase
attr_reader :phrase
def initialize(phrase)
@phrase = phrase.downcase
end
def word_count
phrase.scan(/[\w]+(?:'[\w]+)*/).each_with_object({}) do |word, counter|
counter[word] ||= 0
counter[word] += 1
end
end
end
| true |
f8d7c7ef759dbdd35b828e0432f0a9a26fcde6a2
|
Ruby
|
tbuehlmann/ponder
|
/lib/ponder/user.rb
|
UTF-8
| 1,558 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
module Ponder
class User < Recipient
attr_reader :nick
def initialize(nick, thaum)
super
@nick = nick
end
# Updates the properties of an user.
def whois
connected do
fiber = Fiber.current
callbacks = {}
# User is online.
callbacks[311] = @thaum.on(311) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
@online = true
# TODO: Add properties.
end
end
# User is not online.
callbacks[401] = @thaum.on(401) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
@online = false
fiber.resume
end
end
# End of WHOIS.
callbacks[318] = @thaum.on(318) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
fiber.resume
end
end
raw "WHOIS #{@nick}"
Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
end
self
end
def online?
if @thaum.user_list.find(@nick)
true
else
whois if @online.nil?
@online
end
end
def thaum?
@nick == @thaum.config.nick
end
def message(message)
raw "PRIVMSG #{@nick} :#{message}"
end
def inspect
"#<User nick=#{@nick.inspect}>"
end
end
end
| true |
6eaba3b2c600d1e7b37ea1b30eafb118891074d3
|
Ruby
|
stevielum1/App_Academy_Homeworks
|
/w2d4/big_octopus.rb
|
UTF-8
| 974 | 3.796875 | 4 |
[] |
no_license
|
fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']
# O(n^2)
def sluggish_octopus(fish)
longest_fish = ""
fish.each do |fish1|
fish.each do |fish2|
length1 = fish1.length
length2 = fish2.length
length1 > length2 ? longest_fish = fish1 : longest_fish = fish2
end
end
longest_fish
end
# O(n log n)
def dominant_octopus(fish)
merge_sort(fish).last
end
def merge_sort(arr)
return arr if arr.length <= 1
mid = arr.length / 2
lower = merge_sort(arr[0...mid])
upper = merge_sort(arr[mid..-1])
merge(lower, upper)
end
def merge(left, right)
result = []
until left.empty? || right.empty?
if left.first.length < right.first.length
result << left.shift
else
result << right.shift
end
end
result + left + right
end
# O(n)
def clever_octopus(fish)
longest = ""
fish.each do |fish|
longest = fish if longest.length < fish.length
end
longest
end
| true |
eb71258422bbaf97e9297938677d998e12a17ead
|
Ruby
|
JMoore89/LRubyTHW
|
/ex15.rb
|
UTF-8
| 767 | 4.125 | 4 |
[] |
no_license
|
# Assign the argument from from the cmd line in the ARGV Array
filename = ARGV.first
# Asking for user input.
prompt = "> "
# Assigns a File open call with the variable filename as the argument.
txt = File.open(filename)
# Print a line saying what the filename is.
puts "Here's your file: #{filename}"
# Prints out what is contained in that filename.
puts txt.read()
# Asking you to retype the filename.
puts "I'll also ask you to type it again:"
# Prints out user input.
print prompt
# Assign's the user's input from the cmd line to a variable.
file_again = STDIN.gets.chomp()
# assigns a new variable with a file open call file_again as the argument.
txt_again = File.open(file_again)
# prints content from file to cmd line.
puts txt_again.read()
txt_again.close
| true |
efa826f0ac190ee2c0eaaf34a8bb96c35e6a16df
|
Ruby
|
maksym-bielyshev/rubylearningcom-tutorial
|
/p049instvarinherit.rb
|
UTF-8
| 176 | 3.703125 | 4 |
[
"Apache-2.0"
] |
permissive
|
class C
def initialize
@n = 100
end
def increase_n
@n *= 20
end
end
class D < C
def show_n
puts "n is #{@n}"
end
end
d = D.new
d.increase_n
d.show_n
| true |
a7b3f908a27403f748b53d2c4836ad5c4dfcb91d
|
Ruby
|
JazzyMussels/OO-Auto-Shop-nyc-clarke-web-082619
|
/app/models/mechanic.rb
|
UTF-8
| 356 | 3.3125 | 3 |
[] |
no_license
|
class Mechanic
attr_reader :name, :specialty
@@all = []
def initialize(name, specialty)
@name = name
@specialty = specialty
@@all << self
end
def self.all
@@all
end
def cars
Car.all.select{|car| car.mechanic == self}
end
def clients
cars.map{|car| car.owner}
end
def client_names
clients.map{|client| client.name}.uniq
end
end
| true |
f353da20fed84e7b0f3c47edf74a154dd9846e3a
|
Ruby
|
trottomv/botest
|
/lib/botest.rb
|
UTF-8
| 2,945 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
require 'dotenv'
require 'telegram/bot'
require 'xkcd'
require 'rss'
require 'feed-normalizer'
require 'open-uri'
require 'simple-rss'
require 'open-uri'
# require 'curb'
class Botest
Dotenv.load
token = ENV['TOKEN']
xkcd = FeedNormalizer::FeedNormalizer.parse open('http://xkcd.com/rss.xml')
turnoffus = FeedNormalizer::FeedNormalizer.parse open('http://turnoff.us/feed.xml')
Telegram::Bot::Client.run(token) do |bot|
bot.listen do |message|
case message.text
when '/start'
bot.api.send_message(chat_id: message.chat.id, text: "Hi, #{message.from.first_name}")
when /^\/(xkcd|comics)/
bot.api.send_message(chat_id: message.chat.id, text: XKCD.img)
when '/stop'
bot.api.send_message(chat_id: message.chat.id, text: "Bye bye, #{message.from.first_name}")
when '/feed'
url = 'http://xkcd.com/rss.xml'
open(url) do |rss|
rss = RSS::Parser.parse(rss)
bot.api.send_message(chat_id: message.chat.id, text: "Feed: #{rss.channel.title}")
rss.items.each do |item|
bot.api.send_message(chat_id: message.chat.id, text: "#{item.title} #{item.link}")
end
end
when '/lastxkcd'
bot.api.send_message(chat_id: message.chat.id, text: "#{xkcd.entries.first.url}")
when '/lastturnoffus'
bot.api.send_message(chat_id: message.chat.id, text: "#{turnoffus.entries.first.url}")
def rssCal
rsscal = SimpleRSS.parse open('#{ENV[FEED_CAL]}')
timefeed=rsscal.items.first.pubDate.strftime ("%d-%m-%Y %H")
nowh=Time.now.strftime ("%d-%m-%Y %H")
case timefeed
when nowh
# http = Curl.get("https://api.telegram.org/bot#{ENV['TOKEN']}/sendMessage?chat_id=#{ENV['CHAT_ID']}&text=#{rss.items.first.title}")
bot.api.send_message(chat_id: message.chat.id, text: "#{rsscal.items.first.title}")
end
end
def rssXkcd
rssXcd = SimpleRSS.parse open('http://xkcd.com/rss.xml')
timefeed=rssXkcd.items.first.pubDate.strftime ("%d-%m-%Y")
today=Time.now.strftime ("%d-%m-%Y")
case timefeed
when today
# http = Curl.get("https://api.telegram.org/bot#{ENV['TOKEN']}/sendMessage?chat_id=#{ENV['CHAT_ID']}&text=#{rss.items.first.link}")
bot.api.send_message(chat_id: message.chat.id, text: "#{rssXkcd.items.first.link}")
end
end
def rssturnoffus
rssreturnoffus = SimpleRSS.parse open('http://turnoff.us/feed.xml')
timefeed=rssreturnoffus.items.first.pubDate.strftime ("%d-%m-%Y %H")
nowh=Time.now.strftime ("%d-%m-%Y %H")
case timefeed
when nowh
# http = Curl.get("https://api.telegram.org/bot#{ENV['TOKEN']}/sendMessage?chat_id=#{ENV['CHAT_ID']}&text=#{rss.items.first.link}")
bot.api.send_message(chat_id: message.chat.id, text: "#{rssturnoffus.items.first.link}")
end
end
end
end
end
end
| true |
b0539145525d262b768f202441dab900f729d662
|
Ruby
|
jjb/ruby-gc-heap-growth-factor-benchmark
|
/code.rb
|
UTF-8
| 524 | 2.703125 | 3 |
[] |
no_license
|
require 'get_process_mem'
puts
puts "-------- #{ENV["RUBY_GC_HEAP_GROWTH_FACTOR"]} --------\n"
GET_PROCESS_MEM = GetProcessMem.new
s = []
start = Time.now
GC.compact
50_000_000.times do |i|
# if 0 == i % 1_000_000
# print "[#{i/1_000_000}]"
# # GC.start
# end
s << "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef"
end
finish = Time.now
puts 'GC.stat[:heap_sorted_length]: ' + GC.stat[:heap_sorted_length].to_s
puts "process RSS: #{GET_PROCESS_MEM.bytes}"
puts "seconds elapsed: " + (finish-start).to_s
| true |
4d873682c4ffc712fa862458828dc9ed03e9d5fe
|
Ruby
|
pytong/algorithms
|
/binary_trees/iterative_inorder_traversal.rb
|
UTF-8
| 729 | 3.71875 | 4 |
[] |
no_license
|
def inorder_traversal(root)
# empty tree
if !parent
return
end
# prev = nil
# next = nil
curr = root
while curr
if !prev || prev.left == curr || prev.right == curr # at root or at child nodes
if curr.left # has left nodes
next = curr.left
else
puts curr.value
next = (curr.right ? curr.right : curr.parent) # go to right node if any
end
elsif curr.left == prev # at parent node, just traversed left node
puts curr.value
next = (curr.right ? curr.right : current.parent) # go to right node if any
else # curr.right == prev # at parent node, just traversed right node
next = curr.parent
end
prev = curr
curr = next
end
end
| true |
9f9d93c76d3e8637932bbd5d8bab1affc6f970a5
|
Ruby
|
theodi/content_api
|
/test/unit/fake_pagination_test.rb
|
UTF-8
| 785 | 2.578125 | 3 |
[] |
no_license
|
require "test_helper"
require "pagination"
class FakePaginationTest < MiniTest::Spec
include Pagination
describe "FakePaginatedResultSet" do
it "gives the appropriate response when given an array" do
p = FakePaginatedResultSet.new([1, 2, 3, 4, 5])
assert_equal [1, 2, 3, 4, 5], p.results
assert_equal 5, p.total
assert_equal 1, p.start_index
assert_equal 1, p.pages
assert_equal 5, p.page_size
assert_equal 1, p.current_page
end
it "works with empty arrays" do
p = FakePaginatedResultSet.new([])
assert_equal [], p.results
assert_equal 0, p.total
assert_equal 1, p.start_index
assert_equal 1, p.pages
assert_equal 0, p.page_size
assert_equal 1, p.current_page
end
end
end
| true |
43be18c22bc43f8b7290e8228e3b767b292d290d
|
Ruby
|
baezdiazm/parrot-ruby-onl01-seng-pt-030220
|
/parrot.rb
|
UTF-8
| 132 | 3.390625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot(ph = "Squawk!")
puts ph
return ph
end
| true |
e6b28f5fe5fc65c1a45121600db6c2246ed048fe
|
Ruby
|
anicholson44/dependencies
|
/logger.rb
|
UTF-8
| 336 | 3.109375 | 3 |
[] |
no_license
|
class Logger
def initialize(max_depth = nil, indent = 2)
@max_depth = max_depth
@log = []
@indent = indent
end
def log(string, depth = 0)
log_string = "#{' ' * @indent}#{string}" unless @max_depth && depth > @max_depth
@log << log_string
puts log_string if log_string
end
def read
@log
end
end
| true |
0d1f1f53e3be60a6477636a60994ddb8b477ea06
|
Ruby
|
icanprogram/fedoracoin-irc-bot
|
/plugins/hashrateformatter.helper.rb
|
UTF-8
| 297 | 2.9375 | 3 |
[] |
no_license
|
module HashrateFormatter
def format_hashrate hashrate
prefixes = ["k", "M", "G", "T", "P", "E", "Z", "Y"]
prefix = ""
unit = "h/s"
value = hashrate.to_f
while value > 1000
value = value/1000
prefix = prefixes.shift
end
"#{value.round(2)} #{prefix}#{unit}"
end
end
| true |
e67f21bc3f3cdf0fc750a2f7a7aef5f4af6dd0ae
|
Ruby
|
Rocky-R/battleship_reborn
|
/classes/computerplayer.rb
|
UTF-8
| 712 | 3.53125 | 4 |
[] |
no_license
|
class ComputerPlayer < Player
def initialize
super
@name = "HAL 9000"
end
def ships
board.ships
end
def name
@name
end
def place_ships(lengths)
lengths.each do |l|
ship_placed = false
until ship_placed == true do
ship_placed = place_ship(l)
end
end
puts "HAL 9000 has placed his ships.\n"
true
end
def place_ship(l)
x = rand(1..10)
y = rand(1..10)
across = [true, false].sample
new_ship = Ship.new(l)
ship_placed = new_ship.place(x, y, across)
if ship_placed == true
board.ships << new_ship
end
ship_placed
end
def turn
x = rand(1..10)
y= rand(1..10)
return [x, y]
end
end
| true |
862004e688d65e8bef9a35786ee1b7546b62e2aa
|
Ruby
|
Wizcorp/NagiosForCouchbase
|
/lib/wizcorp/couchbase/connection.rb
|
UTF-8
| 2,827 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
module Wizcorp
module Couchbase
# Class to establish connection and handle communication with
# Couchbase server HTTP API.
#
# This is parent class for all others, they are inheric connection
# setting from this class.
#
class Connection
require 'net/http'
require 'json'
require 'pp'
def initialize connection={}
# Set default values
@connection = {
:hostname => 'localhost',
:port => 8091,
:pool => 'default',
:buckets => ['default'],
:ttl => 60 # Interval in seconds for requesting
# data from HTTP, do not request more
# often than this
}.merge(connection)
c = @connection
@uri = "http://#{c[:hostname]}:#{c[:port]}/pools/"
@resource = nil
@data = { }
@ttl = @connection[:ttl]
@last_update = 0
end
attr_accessor :uri
attr_accessor :data
attr_accessor :connection
# Helper method to access @connection hash attribute
def pool; connection[:pool] end
# Helper method to access @connection hash attribute
def buckets; connection[:buckets] end
# Connect to API and get JSON hash from it.
#
# @param [String] resource String appended to the API endpoint
# URI, pool name, bucket name etc.
#
# @return [Hash] Result of the HTTP GET
#
def get resource=nil
time = Time.now
if @data.empty? || time > @last_update + @ttl
ur = "#{uri}#{resource || @resource}"
begin
@data = JSON.parse Net::HTTP.get URI ur
@last_update = time
rescue => e
print "Cannot retrieve data: #{e.message} (URI: #{ur}) "
end
end
@data
end
# Class level method for the same. If it's only one time
# request, just use it as ::Wizcorp::Subclass.get
#
# @param [Hash] params Same parameters as constructor acccepts.
# @see initialize
def self.get params={ }
self.new(params).get
end
# Re-define standard method to handle all keys returned with
# JSON object, so we can refer to the data by key-name
def method_missing sym, key=nil
get if data.empty?
sym,key = sym.to_s,key.to_s
if data.has_key?(sym)
return data[sym] if key.empty?
if data[sym].is_a?(Hash) && data[sym].has_key?(key)
return data[sym][key]
else
return nil
end
else
super sym.to_sym, key
end
end
end # class Connection
end # module Couchbase
end
| true |
1da0c47aea44f290303c6756cd0b4223bb822ae3
|
Ruby
|
HatAndBread/pleasant_news
|
/models/article.rb
|
UTF-8
| 848 | 3.140625 | 3 |
[] |
no_license
|
require 'nokogiri'
require 'open-uri'
require_relative 'words_list'
require_relative 'emoji'
class Article
@@id = 0
attr_accessor :url, :title, :body, :date, :emoji, :id
def initialize(attributes = {})
@@id += 1
@id = @@id
@url = attributes[:url]
@title = attributes[:title]
@body = attributes[:body]
@date = attributes[:date]
@word_list = WordList.new
@emoji = Emoji.new.emoji
change_words(@body, true)
change_words(@title)
end
def change_words(text, body = false)
copy = text.downcase
@word_list.list.each do |word_set|
result = copy.match(/#{word_set[0]}/)
if result && body
@body.gsub!(/#{word_set[0]}/i, word_set[1])
elsif result && !body
@title.gsub!(/#{word_set[0]}/i, word_set[1].split.map(&:capitalize).join(' '))
end
end
end
end
| true |
8c7a71e08fe513e97849b6359425466d0388b992
|
Ruby
|
dtvthethe/ruby_training
|
/varriable_practice.rb
|
UTF-8
| 1,224 | 4.25 | 4 |
[] |
no_license
|
#Global variables
=begin
$global = 0
class C
puts "in a class: #{$global}"
def my_method
puts "in a method: #{$global}"
$global = $global + 1
$other_global = 3
end
end
C.new.my_method
puts "at top-level, $global: #{$global}, $other_global: #{$other_global}"
=end
#Global variables
=begin
color = "Red"
def method1
color = 192
puts("Color Value in method1 : ", color)
end
def method2
color = 255
puts("Color Value method2: ", color)
end
method1
method2
method1
puts("Color Value outside methods : " + color)
=end
# Instance variable
=begin
class Student
def initialize student_id, student_name
@student_id = student_id
@student_name = student_name
end
def show
puts "Student Name and ID : "
puts @student_id, @student_name
end
end
Student.new(1, "Sara").show
Student.new(2, "Raju").show
=end
# Class variables
=begin
class School
@@no_off_students = 650
end
class V < School
@@no_off_students = 75
end
class VI < School
@@no_off_students = 80
end
puts School.class_eval("@@no_off_students")
puts V.class_eval("@@no_off_students")
puts VI.class_eval("@@no_off_students")
=end
=begin
x = 0
3.times do
x += 1
end
puts x #3
y = 0
3.times do
y += 1
x = y
end
puts x #3
=end
| true |
1c26e5403db1b60163ab86025510a1433331f8b2
|
Ruby
|
fkazgithub/tech_ruby
|
/3.rb
|
UTF-8
| 175 | 3.4375 | 3 |
[] |
no_license
|
fruits_box = ["apple","orange","cherry"]
puts "何がでるかな?取り出したい要素の順番を入力してください"
input = gets.to_i
puts fruits_box[input-1]
| true |
6ea89fc9c345a765267596abf8332474d8861c05
|
Ruby
|
nmarley/rate-service
|
/rate.rb
|
UTF-8
| 2,464 | 2.5625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
require 'sinatra/base'
require 'sinatra/json'
require 'sinatra/cross_origin'
require 'json'
require 'bigdecimal'
require 'bigdecimal/util'
require 'pp'
require 'awesome_print'
require 'byebug'
require File.expand_path('config/application', __dir__)
require 'rate_helpers'
require 'rate_service'
# TODO: class with all this encapsulated
include RateHelpers
# Microservice REST API for Dash price to whatever FIAT currency, and BTC.
#
# Input: FX Pair
# Output: Returns exchange rate
#
def make_payload(h)
payload = {
server_ts: Time.now.getutc.xmlschema,
}
if h.has_key?(:err)
payload.merge!({success: false, error: h[:err]})
else
payload.merge!({success: true, quote: h[:pair], rate: h[:rate].round(8).to_s('8F')})
end
return payload.to_json
end
# fetch the rate info from DB, calculate & return
def get_rates(fxpair)
base, quote = fxpair.split /_/
# standardize any inconsistencies in currency ticker names
base = normalize_ticker_string(base)
quote = normalize_ticker_string(quote)
fxpair = base + '_' + quote
# check validity of base/quote
if (not is_valid_ticker_string($redis, base))
return make_payload(err: "#{base} is not a valid currency ticker string")
end
if (not is_valid_ticker_string($redis, quote))
return make_payload(err: "#{quote} is not a valid currency ticker string")
end
rate = get_rate($redis, base, quote)
return make_payload(pair: fxpair, rate: rate)
end
module RateService
class App < Sinatra::Base
# enable CORS for this API
register Sinatra::CrossOrigin
configure do
enable :cross_origin
end
options '*' do
response.headers['Allow'] = 'HEAD,GET,PUT,POST,DELETE,OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept'
200
end
set :cross_origin, true
before do
content_type :json
end
# /rate/:fxpair(.ext)?
get '/rate/:fxpair.?:format?' do
return get_rates(params[:fxpair].strip.upcase)
end
get '/service/ingest.?:format?' do
begin
RateService.ingest
status 204
rescue StandardError => ex
status 500
body make_payload(err: ex.message)
end
end
get '/*' do
return make_payload(err: "Sorry, that path is not defined.")
end
# $0 is the executed file
# __FILE__ is the current file
run! if __FILE__ == $0
end
end
| true |
a3e239258fb8c8d3447861698382e19d1d517d6c
|
Ruby
|
insoul/dooly
|
/lib/dooly/attachment/base.rb
|
UTF-8
| 2,854 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
module Dooly
module Attachment
class Base < HashWithIndifferentAccess
attr_accessor :body
def add(k, value = nil, options = {})
if key?(k)
warn_duplicated(k); return fetch(k)
end
if value
store(k, value)
if block_given?
self.as_json_procs(k, &Proc.new)
end
elsif block_given?
store(k, Proc.new)
else
warn_unassigned_value(k)
end
if options[:as_json_options]
as_json_options(k, options[:as_json_options])
else
as_json_options(k, options) unless options.empty?
end
end
def as_json_options(k = nil, options = nil)
@as_json_options ||= HashWithIndifferentAccess.new
return @as_json_options if k.nil?
return @as_json_options[k] if options.nil?
@as_json_options[k] = options
end
def as_json_procs(k = nil)
@as_json_procs ||= HashWithIndifferentAccess.new
return @as_json_procs if k.nil?
return @as_json_procs[k] unless block_given?
@as_json_procs[k] = Proc.new
end
def as_json_procs_run(k = nil, value = nil)
@as_json_procs_run ||= HashWithIndifferentAccess.new
return @as_json_procs_run if k.nil?
return @as_json_procs_run[k] if value.nil?
@as_json_procs_run[k] = value
end
alias :to_hash_with_string :to_hash
def to_hash
to_hash_with_string.symbolize_keys
end
def [](key)
value = fetch(key, nil)
return nil if value.nil?
if Proc === value
value = value.call(body)
store(key, value)
end
fetch(key)
end
def as_json
self.each_pair do |k, v|
if self.as_json_procs(k) and !as_json_procs_run(k)
v = self.as_json_procs(k).call(body, v)
self.as_json_procs_run(k, true)
end
if Proc === v
self[k] = v.call(body).as_json
elsif v.respond_to?(:as_json)
if as_json_options(k)
self[k] = v.as_json(as_json_options(k)).as_json
else
self[k] = v.as_json
end
else
self[k] = v.as_json
end
end
self
end
private
def warn_unassigned_value(key)
message = ["Attachment has been tried to add with none value, #{self.class.name}/#{key}"]
message += caller if Rails.env.development?
Configuration.logger.warn(message.join("\n"))
end
def warn_duplicated(key)
message = ["Attachment has been tried to add repeatedly about key, #{self.class.name}/#{key}."]
message += caller if Rails.env.development?
Configuration.logger.warn(message.join("\n"))
end
end
end
end
| true |
7d583f55e92a3c41511aaa16f60ad03f4b28bd79
|
Ruby
|
ymagoon/scraper
|
/imdb_top_250.rb
|
UTF-8
| 2,447 | 3.0625 | 3 |
[] |
no_license
|
require 'nokogiri'
require 'rest-client'
require 'csv'
require 'pry'
def scrape_data
movies = []
puts "starting..."
top_250_url = "https://www.imdb.com/chart/top"
top_250_doc = Nokogiri::HTML(RestClient.get(top_250_url))
puts "finished getting Nokogiri doc..."
cnt = 0
top_250_doc.search('.titleColumn a').each do |element|
sleep(1)
cnt +=1
puts "working on movie #{cnt}/250"
title = element.text
href = element['href']
movie_url = "https://www.imdb.com#{href.split('?')[0]}"
movie_doc = Nokogiri::HTML(RestClient.get(movie_url))
rating = movie_doc.search('.ratingValue strong span').text
content_rating = movie_doc.search('.subtext').first.children[1]['content']
duration = movie_doc.search('.subtext').first.children[5].text.strip
release_year = movie_doc.search('#titleYear').children[1].text
summary = movie_doc.search('.summary_text').text.strip
director = movie_doc.search("span[itemprop='director'] span").text
budget = ""
gross_usa = ""
gross_worldwide = ""
movie_doc.search('.txt-block').each do |element|
text = element.text.strip
if text.include?("Budget:")
budget = text.gsub(/\D/, '')
elsif text.include?("Gross USA:")
gross_usa = text.split[1].gsub(/\D/, '')
elsif text.include?("Cumulative Worldwide Gross:")
gross_worldwide = text.gsub(/\D/, '')
end
end
movie = {
title: title,
href: movie_url,
rating: rating,
summary: summary,
content_rating: content_rating,
duration: duration,
release_year: release_year,
director: director,
# writers: [writers],
# stars: [stars],
budget: budget,
# opening_weekend: opening_weekend,
gross_usa: gross_usa,
gross_worldwide: gross_worldwide
}
p movie
save_to_csv(movie)
movies << movie
end
end
def save_to_csv(movie)
csv_options = { col_sep: ',', force_quotes: true, quote_char: '"' }
filepath = 'movies.csv'
CSV.open(filepath, 'ab', csv_options) do |csv|
# csv << ["Title", "Rating", "Summary", "Content Rating", "Duration", "Release Year", "Director", "Budget", "Gross USA", "Gross Worldwide"]
csv << [movie[:title], movie[:rating], movie[:summary], movie[:content_rating], movie[:duration], movie[:release_year], movie[:director], movie[:budget], movie[:gross_usa], movie[:gross_worldwide]]
end
end
scrape_data
| true |
3f8f66a453bbaef970e1af015419e80bf75b1edc
|
Ruby
|
hvenables/advent_of_code_2019
|
/day_1/day_1_part_1.rb
|
UTF-8
| 104 | 3.125 | 3 |
[] |
no_license
|
input = File.read('./input1.txt').split("\n")
result = input.sum { |i| (i.to_i / 3) - 2 }
puts result
| true |
68358569c11509dcffb5fcf9450f0d884892a77e
|
Ruby
|
Virus-Hunter/Ruby
|
/lib/modules/events/sprits sprits.rb
|
UTF-8
| 2,064 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
module Bot
module DiscordEvents
# Sprits Sprits
# Punish ruby for being dum
module SpritsSprits
extend Discordrb::EventContainer
message(contains: /💦 🐱|💦🐱|sprits sprits|Sprits Sprits|spritssprits|SpritsSprit|Sprits sprits/) do |event|
event.respond ["https://my.mixtape.moe/jbisds.png", '_**HISS**_', '`-Loud cat noises-`', 'WHAT\'S A MATTA WIT YOU?!','ACK', 'WHY?!?', 'THAT _BETTER_ BE PLAIN _WATER_!', 'I\'M DROWNIN\' HERE!', '_ANIMAL ABUSE!_', ].sample
# if moodnum <= 0
# event.respond ['JEEZ LOUISE WAS THAT NECESSARY?', 'GET OVER HERE I\'M GONNA SLAP YA REAL GOOD BUDDY', 'OH MY GOD ***STOP***', 'Have you considered ***NOT SPRAYING ME WITH WATER?***', 'WUNNA THESE DAYS, POW RIGHT IN THE KISSA', "I HAVE JUST ABOUT HAD IT UP TO **HERE** WITH YER SHENANIGANS, _BUDDY_", "`-Loud black panther noises-`", "CAN YOU _NOT?_"].sample
# lashout +=1
# if lashout >= 5
# lashout = 0
# sleep(5)
# event.respond [":triumph: You know what pal? _I'll_ be the adult here and ask nicely. Can you _please_ stop? THANK YOU.", "Alright buddy...you're here...*I'm* here...we're stuck with each other! So can we PLEASE get along?","*SIGH* Can we PLEASE, *PLEASE* just stop all this? I gotta go dry off!", "I'm done. I'm done! I am TOO WET to be mad anymore.", "Congradualtions buddy, you've got yourself a living wet towel. I hope you don't mind me _dragging water everywhere_! BECAUSE I DO.", "Alright, alright. We've had some laughs, I'm completely soaked...let's let bygones be bygones, okay pal?", "_Hahahahahaha let's spray the cat! It'll be **fuuuuun**!_ You're a real piece a work, pal."].sample
# moodnum = 70
# elsif moodnum >= 0
# event.respond ["https://my.mixtape.moe/jbisds.png", '_**HISS**_', '`-Loud cat noises-`', 'WHAT\'S A MATTA WIT YOU?!','ACK', 'WHY?!?', 'THAT _BETTER_ BE PLAIN _WATER_!', 'I\'M DROWNIN\' HERE!', '_ANIMAL ABUSE!_', ].sample
#moodnum += -20
# end
# end
# if moodnum <= 0
# moodnum = 0
#end
end
end
end
end
| true |
76488a09e3ea097f60bd6035beead8e4b5640f23
|
Ruby
|
jonisavo/MK-Starter-Kit
|
/ruby/scripts/tempdebug/tileset4.rb
|
UTF-8
| 1,810 | 2.578125 | 3 |
[] |
no_license
|
# Creates a new tileset (normally loaded from a file)
tileset = MKD::Tileset.new(4)
tileset.name = "Water"
tileset.graphic_name = "water"
# 0 = impassable
# 1 = passable down
# 2 = passable left
# 4 = passable right
# 8 = passable up
# 11 = passable down, left, up
# etc.
# 15 = passable all
tileset.passabilities = [
5, 3, 5, 3, 5, 3, 5, 3,
12, 10, 12, 10, 12, 10, 12, 10,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 0, 0, 0, 0, 0,
15, 15, 15, 0, 0, 0, 0, 0,
15, 15, 15, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
15, 0, 0, 0, 0, 0, 0, 0,
]
tileset.priorities = [
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 1, 1, 1, 1,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, 1, 1, 1, 1, 1, 1,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil,
]
tileset.tags = []
tileset.save
| true |
a7dc3473813f28e97ef930cd6602e7795768cdef
|
Ruby
|
MaxfieldLewin/checkers
|
/game_solver.rb
|
UTF-8
| 1,469 | 3.5 | 4 |
[] |
no_license
|
require_relative 'board.rb'
require_relative 'piece.rb'
class GameSolver
def initialize(board, color, depth=3)
@board = board
@color = color
@depth = depth
end
def solve_n_moves_ahead(gen=0, board=@board)
return {} if gen > @depth
move_table = Hash.new { |h,k| h[k] = 0 }
step_moves, jump_moves = get_legal_moves(board, @color)
all_moves = step_moves + jump_moves
all_moves.each do |move|
next_board = board.deep_dup
next_board[move.first].perform_move(move.drop(1))
if (move[0][0] - move[1][0]).abs == 2
move_table[move] += move.count - 1
end
all_opponent_moves = get_legal_moves(next_board, enemy_color)
all_oponent_moves.each do |e_move|
next_turn_board = next_board.deep_dup
next_turn_board[e_move.first].perform_move(e_move.drop(1))
next_gen_step_vals = solve_n_moves_ahead(gen + 1, next_board)
move_table[step] += next_gen_step_vals.values.inject(:+)
end
end
end
#returns steps, jumps
def get_legal_moves(board, color)
step_moves = []
jump_moves = []
board.color_pieces(color).each do |piece|
piece.legal_steps.each do |step|
step_moves << [piece.position] + [step]
end
piece.legal_jump_sequences.each do |seq|
jump_moves << [piece.position] + seq
end
end
[step_moves, jump_moves]
end
def enemy_color
@color == :red ? :black : :red
end
end
| true |
ff213fe96227b467636093e5f93b44814b8f2cdd
|
Ruby
|
micahmosley/ruby-enumerables-reverse-each-word-lab-atx01-seng-ft-071320
|
/reverse_each_word.rb
|
UTF-8
| 180 | 3.34375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def reverse_each_word(sentence)
sentence_array=sentence.split(" ")
sentence_array=sentence_array.collect do |word|
word.reverse
end
sentence_array.join(" ")
end
| true |
71dc80832ee53fc208b5fadcb65b7166d10ee779
|
Ruby
|
macournoyer/llvmruby
|
/test/test_basic.rb
|
UTF-8
| 9,689 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require 'test/unit'
$:.unshift File.dirname(__FILE__) + "/../ext"
require 'llvm'
include LLVM
class BasicTests < Test::Unit::TestCase
def function_tester(expected)
m = LLVM::Module.new("test_module")
type = Type::function(MACHINE_WORD, [])
f = m.get_or_insert_function("test", type)
yield(f)
ExecutionEngine.get(m);
assert_equal(expected, ExecutionEngine.run_autoconvert(f))
end
def test_module
function_tester(5) do |f|
b = f.create_block.builder
v = b.add(2.llvm, 3.llvm)
b.return(v)
end
end
def bin_op(op, v1, v2, expected)
function_tester(expected) do |f|
b = f.create_block.builder
ret = b.bin_op(op, v1.llvm, v2.llvm)
b.return(ret)
end
end
def test_bin_ops
bin_op(Instruction::Add, 2, 3, 5)
bin_op(Instruction::Sub, 5, 3, 2)
bin_op(Instruction::Mul, 2, 3, 6)
bin_op(Instruction::UDiv, 42, 6, 7)
bin_op(Instruction::SDiv, 42, 6, 7)
#bin_op(Instruction::FDiv, 23.0, 5, 0.23)
bin_op(Instruction::URem, 23, 5, 3)
bin_op(Instruction::SRem, 23, 5, 3)
#bin_op(Instruction::FRem, 23.0, 5, 0.23)
bin_op(Instruction::Shl, 2, 1, 4)
bin_op(Instruction::LShr, 8, 1, 4)
#bin_op(Instruction::AShr, 8, 1, 4)
bin_op(Instruction::And, 8, 15, 8)
bin_op(Instruction::Or, 8, 15, 15)
bin_op(Instruction::Xor, 8, 15, 7)
end
def builder_bin_op(op, v1, v2, expected)
function_tester(expected) do |f|
b = f.create_block.builder
ret = b.send(op, v1.llvm, v2.llvm)
b.return(ret)
end
end
def test_builder_bin_ops
builder_bin_op(:add, 23, 42, 65)
builder_bin_op(:sub, 69, 13, 56)
builder_bin_op(:mul, 23, 5, 115)
builder_bin_op(:udiv, 23, 5, 4)
builder_bin_op(:sdiv, 99, 33, 3)
#builder_bin_op(:fdiv, 23, 42, 65)
builder_bin_op(:urem, 23, 42, 23)
builder_bin_op(:srem, 77, 5, 2)
#builder_bin_op(:frem, 23, 42, 65)
builder_bin_op(:shl, 15, 1, 30)
builder_bin_op(:lshr, 32, 2, 8)
#builder_bin_op(:ashr, 23, 42, 65)
builder_bin_op(:and, 32, 37, 32)
builder_bin_op(:or, 15, 8, 15)
builder_bin_op(:xor, 33, 15, 46)
end
def test_insert_point
function_tester(2) do |f|
b1 = f.create_block
b2 = f.create_block
builder = b1.builder
builder.br(b2)
builder.set_insert_point(b2)
builder.return(2.llvm)
end
end
def test_builder_utils
function_tester(5) do |f|
b = f.create_block.builder
b.write do
ret = add(2.llvm, 3.llvm)
self.return(ret)
end
end
end
def test_cmps
m = LLVM::Module.new("test_cmps")
type = Type.function(MACHINE_WORD, [])
f = m.get_or_insert_function("sgt", type)
entry_block = f.create_block
exit_block_true = f.create_block
exit_block_false = f.create_block
b = entry_block.builder
cmp = b.icmp_sgt(-1.llvm, 1.llvm)
b.cond_br(cmp, exit_block_true, exit_block_false)
b = exit_block_true.builder
b.return(1.llvm)
b = exit_block_false.builder
b.return(0.llvm)
ExecutionEngine.get(m)
result = ExecutionEngine.run_autoconvert(f)
assert_equal(0, result)
end
def test_fcmps
m = LLVM::Module.new('test_fcmps')
type = Type.function(MACHINE_WORD, [])
f = m.get_or_insert_function('ult', type)
entry_block = f.create_block
exit_block_true = f.create_block
exit_block_false = f.create_block
b = entry_block.builder
cmp = b.fcmp_ult(1.0.llvm, 2.0.llvm)
b.cond_br(cmp, exit_block_true, exit_block_false)
b = exit_block_true.builder
b.return(0.llvm)
b = exit_block_false.builder
b.return(1.llvm)
ExecutionEngine.get(m)
result = ExecutionEngine.run_autoconvert(f)
assert_equal(0, result)
end
def test_function_calls
m = LLVM::Module.new('test_module')
type = Type::function(MACHINE_WORD, [])
f_caller = m.get_or_insert_function("caller", type)
type = Type::function(MACHINE_WORD, [MACHINE_WORD, MACHINE_WORD])
f_callee = m.get_or_insert_function("callee", type)
b = f_callee.create_block.builder
x, y = f_callee.arguments
sum = b.add(x, y)
b.return(sum)
b = f_caller.create_block.builder
ret = b.call(f_callee, 2.llvm, 3.llvm)
b.return(ret)
ExecutionEngine.get(m)
result = ExecutionEngine.run_autoconvert(f_caller)
assert_equal(5, result)
end
def test_phi_node
m = LLVM::Module.new('test_module')
type = Type::function(MACHINE_WORD, [])
f = m.get_or_insert_function('phi_node', type)
entry_block = f.create_block
loop_block = f.create_block
exit_block = f.create_block
b = entry_block.builder
b.br(loop_block)
b = loop_block.builder
phi = b.phi(MACHINE_WORD)
phi.add_incoming(0.llvm, entry_block)
count = b.add(phi, 1.llvm)
phi.add_incoming(count, loop_block)
cmp = b.icmp_ult(count, 10.llvm)
b.cond_br(cmp, loop_block, exit_block)
b = exit_block.builder
b.return(phi)
ExecutionEngine.get(m)
result = ExecutionEngine.run_autoconvert(f)
assert_equal(9, result)
end
def test_bitcode_writer
m = LLVM::Module.new('static_module')
# create main function
type = Type.function(Type::Int32Ty, [
Type::Int32Ty,
Type.pointer(Type.pointer(Type::Int8Ty))
])
f = m.get_or_insert_function('main', type)
b = f.create_block.builder
b.return(666.llvm(Type::Int32Ty))
m.write_bitcode("test/static.o")
end
def test_type_errors
m = LLVM::Module.new('type_errors')
ftype = Type.function(Type::Int32Ty, [])
assert_raise(TypeError) { f = LLVM::Module.new(5) }
assert_raise(TypeError) { m.get_or_insert_function(5, ftype) }
assert_raise(TypeError) { m.get_or_insert_function('bad_arg', 5) }
assert_raise(TypeError) { ExecutionEngine.get(5) }
assert_raise(TypeError) { m.external_function(5, ftype) }
assert_raise(TypeError) { m.external_function('fname', 5) }
assert_raise(TypeError) { m.write_bitcode(5) }
assert_raise(ArgumentError) { ExecutionEngine.run_function }
assert_raise(TypeError) { ExecutionEngine.run_function(5) }
assert_raise(TypeError) { ExecutionEngine.run_function(5, 5) }
f = m.get_or_insert_function('test', ftype)
block1 = f.create_block
block2 = f.create_block
b = block1.builder
assert_raise(TypeError) { b.set_insert_point(5) }
assert_raise(TypeError) { b.phi(5) }
phi = b.phi(Type::Int32Ty)
assert_raise(TypeError) { phi.add_incoming(5, 5) }
assert_raise(TypeError) { phi.add_incoming(5.llvm(Type::Int32Ty), 5) }
assert_raise(TypeError) { b.bin_op([], 2.llvm, 3.llvm) }
assert_raise(TypeError) { b.bin_op(Instruction::Add, 5, 3.llvm) }
assert_raise(TypeError) { b.bin_op(Instruction::Add, 3.llvm, 5) }
end
def test_inspectors
m = LLVM::Module.new('example')
ftype = Type.function(Type::Int32Ty, [])
f = m.get_or_insert_function('inspect', ftype)
b = f.create_block.builder
b.return(5.llvm(Type::Int32Ty))
assert_match(/define i32 @inspect\(\)/, m.inspect)
assert_match(/define i32 @inspect\(\)/, f.inspect)
end
def test_global_strings
m = LLVM::Module.new('globalstrings')
ftype = Type.function(Type::Int32Ty, [])
f = m.get_or_insert_function('use_global_strings', ftype)
b = f.create_block.builder
v = b.create_global_string_ptr("SHAKA KHAN")
end
def test_var_arg_ftypes
ftype = Type.function(Type::Int32Ty, [], true)
end
def test_struct_constants
int_t = Type::Int32Ty
struct_type = Type.struct([int_t, int_t, int_t])
struct_const = Value.get_struct_constant(struct_type, 2.llvm(int_t), 3.llvm(int_t), 5.llvm(int_t))
assert_kind_of(Value, struct_const)
m = LLVM::Module.new('globals')
gv = m.global_variable(struct_type, struct_const)
assert_kind_of(Value, gv)
end
def test_malloc_free
function_tester(23) do |f|
b = f.create_block.builder
new_space = b.malloc(MACHINE_WORD, 1)
assert_kind_of(AllocationInst, new_space)
assert(!new_space.array_allocation?)
assert_kind_of(Value, new_space.array_size)
assert_kind_of(Type, new_space.allocated_type)
assert_equal(0, new_space.alignment)
store_inst = b.store(23.llvm(MACHINE_WORD), new_space)
assert(store_inst.may_write_to_memory?)
v = b.load(new_space)
free_inst = b.free(new_space)
assert_kind_of(FreeInst, free_inst)
b.return(v)
end
end
def test_cast
function_tester(5) do |f|
b = f.create_block.builder
b.return(b.cast(Instruction::FPToSI, 5.0.llvm, MACHINE_WORD))
end
end
def test_switch
function_tester(23) do |f|
b = f.create_block.builder
default = f.create_block
on5 = f.create_block
switch = b.switch(5.llvm, default)
switch.add_case(5.llvm, on5)
assert_instance_of(SwitchInst, switch)
assert_equal(2, switch.get_num_cases);
b = default.builder
b.return(7.llvm(MACHINE_WORD))
b = on5.builder
b.return(23.llvm)
end
end
def test_vector
function_tester(666) do |f|
b = f.create_block.builder
vt = Type.vector(MACHINE_WORD, 3)
vp = b.alloca(vt, 0)
v = b.load(vp)
v2 = b.insert_element(v, 666.llvm(MACHINE_WORD), 0.llvm(Type::Int32Ty))
r = b.extract_element(v2, 0.llvm(Type::Int32Ty))
b.return(r)
end
end
def test_pass_manager_run
m = LLVM::Module.new('test')
assert PassManager.new.run(m)
end
def test_type_to_s
assert_equal "i32", 2.llvm.type.to_s
end
def test_type_type_id
assert_equal IntegerTyID, 2.llvm.type.type_id
end
end
| true |
c7170b2285f2c2ec360cce70be1388c9c0d51e37
|
Ruby
|
CGTrader/traceparts
|
/lib/traceparts/part_details.rb
|
UTF-8
| 1,394 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
module Traceparts
class PartDetails
attr_reader :title, :description, :long_description, :big_picture, :manufacturer_id, :manufacturer_name,
:manufacturer_picture, :manufacturer_description, :manufacturer_emails, :manufacturer_websites,
:manufacturer_address, :version
def initialize(data)
global_info = data.fetch('globalInfo')
part_info = global_info.fetch('partInfo')
manufacturer_info = global_info.fetch('manufacturerInfo')
@title = part_info.fetch('titlePart')
@description = part_info.fetch('description')
@long_description = part_info.fetch('longDescription')
@big_picture = part_info.fetch('partPictureUrl')
@version = part_info.fetch('version')
@manufacturer_id = part_info.fetch('manufacturerID')
@manufacturer_name = part_info.fetch('manufacturerName')
@manufacturer_picture= part_info.fetch('manufacturerPictureUrl')
@manufacturer_description = manufacturer_info.key?('description') ? manufacturer_info.fetch('description') : ''
@manufacturer_emails = manufacturer_info.key?('emails') ? manufacturer_info.fetch('emails') : ''
@manufacturer_websites = manufacturer_info.key?('webSites') ? manufacturer_info.fetch('webSites') : ''
@manufacturer_address = manufacturer_info.key?('address') ? manufacturer_info.fetch('address') : ''
end
end
end
| true |
d92b06d6fbf256fa89bc577ab44970c2b3719014
|
Ruby
|
boldport/boldport-club-community
|
/bin/lib/post.rb
|
UTF-8
| 2,313 | 3.015625 | 3 |
[] |
no_license
|
require "pathname"
class Post
attr_accessor :id, :created_at, :title, :date_ymd
attr_accessor :source_url
attr_accessor :author_name, :author_url
attr_accessor :body
attr_accessor :images
attr_accessor :youtube_ids
attr_accessor :twitter_id
def initialize(title=nil, date_ymd=nil, id=nil, created_at=nil)
@id = id
@created_at = created_at || Time.now
@title = title || "New Post"
@date_ymd = date_ymd || @created_at.strftime("%Y-%m-%d")
@images = []
@youtube_ids = []
@twitter_id = nil
end
def images?
images.length > 0
end
def youtube_ids?
youtube_ids.length > 0
end
def media?
images? or youtube_ids?
end
def date_time
actual = created_at.to_s.split
actual[0] = date_ymd
actual.join(" ")
end
def filename
parts = [date_ymd]
parts.concat (id || title).to_s.downcase.split
parts.join("-") + ".md"
end
def root_path
Pathname.new(File.dirname(__FILE__)).join('..', '..')
end
def template_full_path
root_path.join('_drafts', 'template.md')
end
def template
@template ||= File.open(template_full_path, 'rb') { |f| f.read }
end
def full_path
root_path.join('_posts', filename)
end
def text
@text ||= render_text
end
def render_text
text = template.dup
text.gsub!(/title:.*$/, %{title: "#{title}"})
text.gsub!(/date:.*$/, %{date: "#{date_time}"})
if author_name
text.gsub!(/author_name:.*$/, %{author_name: "#{author_name}"})
end
if author_url
text.gsub!(/#?author_url:.*$/, %{author_url: "#{author_url}"})
end
if source_url
text.gsub!(/#?source_url:.*$/, %{source_url: "#{source_url}"})
end
if youtube_ids?
text.gsub!(/#?youtubeid:.*$/, %{youtubeid: "#{youtube_ids.first}"})
end
if twitter_id
text.gsub!(/#?twitterid:.*$/, %{twitterid: "#{twitter_id}"})
end
if images?
image_list = "images:\n"
images.each do |image|
image_list += "- #{image}\n"
end
text.gsub!(/[#]images:.*$/, image_list)
end
if body
text = text[0..text.index('---', 4) + 3] + "\n" + body + "\n"
end
text
end
def write
File.open(full_path, 'w') {|f| f.write(text) }
end
def exists?
File.exists? full_path
end
end
| true |
5a0f05eb606bf466b21b5be43af1713b1e570cf0
|
Ruby
|
bittn/BVM
|
/gem/lib/bittn.rb
|
UTF-8
| 1,252 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require "bittn/version"
require "parslet"
module Bittn
class BaseParser < Parslet::Parser
end
class Version < Gem::Version
end
class BaseLang
attr_reader :name, :version, :kinds, :obj, :type, :finish
def initialize
@name = nil
@version = nil
@parser = nil
@kinds = nil
@obj = nil
@type = nil
end
def parser
return Marshal.dump(@parser.new)
end
#def obj
# return @obj.map do |key,value|
# return [key,Marshal.dump(value)]
# end.to_h
#end
#def type
# return @type.map do |key,value|
# return [key,Marshal.dump(value)]
# end.to_h
#end
end
class BaseNode
def initialize(data)
@data = data
@code = nil
end
def call()
return nil
end
def exec()
return nil
end
def run()
return nil
end
end
class BaseObject < BaseNode
def run(code)
call(code)
end
end
class BaseType < BaseNode
def run(code)
exec(code)
end
end
class ByteCode
def initialize()
@codes = []
end
def add(line)
line.split("\n").map do |p|
@codes.push(p)
end
end
def get()
return @codes
end
end
end
| true |
04086e0d1c81cbc27883fde7e431d2e065fa0048
|
Ruby
|
MattLok/ruby_collection
|
/Euler/specpythag.rb
|
UTF-8
| 265 | 3.34375 | 3 |
[] |
no_license
|
a =1
b = 2
cont = true
while cont #(a < 500)
while b < 500
c = 1000 - b -a
if (a*a) + (b*b) == (c *c)
puts "found #{a} + #{b} + #{c} = 1000!"
cont = false
end
print '.'
b += 1
end
a += 1
b = (a +1)
puts a
end
| true |
becaba8d005ab4b8141b17ac4863687d58bb55a9
|
Ruby
|
jess-alejo/ruby
|
/spec/swap_and_join_strings_spec.rb
|
UTF-8
| 612 | 3.71875 | 4 |
[] |
no_license
|
# frozen_string_literal: true
# For every character in string a swap the casing of every occurrence of the
# same character in string b
def work_on_strings(string1, string2)
[swap_letters(string1, string2), swap_letters(string2, string1)].join
end
def swap_letters(string1, string2)
string1.chars.map { |c| string2.scan(/#{c}/i).size.odd? ? c.swapcase : c }
end
describe 'Swap and join strings' do
it { expect(work_on_strings('abc', 'cde')).to eq 'abCCde' }
it { expect(work_on_strings('XYZ', 'abc')).to eq 'XYZabc' }
it { expect(work_on_strings('step on', 'NO PETS')).to eq 'STEP ONno pets' }
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.