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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
daaa5ca25a98b0287ce276cb0f53a96f91a0f7fa | Ruby | Seonghoegu/coderbyte | /LetterCapitalize.rb | UTF-8 | 323 | 3.4375 | 3 | [] | no_license | def LetterCapitalize(str)
array = str.split
flag = 0
while flag < array.length
array[flag].capitalize!
flag += 1
end
# code goes here
return array.join(" ")
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
LetterCapitalize(STDIN.gets)
| true |
a1971c4440fd983f8bd26d446f55e580618a6a06 | Ruby | seanlilmateus/browser | /app/controllers/browser_delegate.rb | UTF-8 | 4,700 | 2.78125 | 3 | [
"BSD-3-Clause"
] | permissive | class BrowserDelegate2
TITLES = ["Class Methods", "Instance Methods"]
NUMBER_OF_COLUMNS = 3
def rootItemForBrowser(browser)
@collection ||= begin
klasses = Module.constants.reject { |c| c.to_s =~ /^[A-Z]+$/ || c.to_s[0..3] =~ /^[A-Z]+$/ }
.select {|c| Module.const_get(c).is_a?(Class) rescue nil }
.map(&Module.method(:const_get))
# @collection = klasses.map { |klass| Node.new(klass) } #.sort_by(&:kind)
klasses.map do |klass|
Hash[
'Ancestors' => klass.ancestors[1..-1],
'Class' => klass,
'Kind' => klass.class,
TITLES.first => klass.methods(false, true),
TITLES.last => klass.instance_methods(false, true),
]
end
end
end
=begin
def browser(browser, numberOfChildrenOfItem:item)
if item.is_a?(Hash)
@collection.count
elsif item.is_a?(Array)
item.count
# elsif TITLES.include?(item)
# c1 = browser.selectedRowInColumn(0)
# @collection[c1][item].count
else
0
end
end
def browser(browser, child:index, ofItem:item)
NSLog("browser(%@, child:%@, ofItem:%@)", browser, index, item.class)
if item.is_a?(Array)
item[index]
elsif item.is_a?(Hash)
TITLES
else
puts "item: #{item}"
item
end
end
def browser(browser, isLeafItem:item)
# not item.is_a?(Array)
false
end
def browser(browser, objectValueForItem:item)
item.to_s rescue nil
end
def browser(browser, numberOfRowsInColumn:column)
if column.zero?
NSLog("numberOfRowsInColumn: [%@] 0", column)
@collection.count
elsif column == 1
NSLog("numberOfRowsInColumn: [%@] 1", column)
TITLES.count
elsif column == 2
NSLog("numberOfRowsInColumn: [%@] 2", column)
@collection[@row][@key].count
else
@collection[@row][@key].count
end
end
def browser(sender, selectRow:row, inColumn:column)
@row = row
puts "selectRow:#{row} - inColumn:#{column}"
true
end
def browser(browser, willDisplayCell:cell, atRow:row, column:column)
cell.title = if column == 0
@row = row
@collection[row]['Class'].to_s
elsif column == 1
@key = TITLES[row].to_s
elsif column == 2
# puts "atRow:#{row} - column:#{browser.selectionIndexPath.description}"
"XXXX"
else
@collection[row]['Class'].to_s
end
end
def browser(browser, createRowsForColumn:column, inMatrix:matrix)
if column == 0
puts "column == 0 #{matrix}"
elsif column == 1
puts "column == 1 #{matrix}"
elsif column == 2
puts "column == 2 #{matrix}"
end
end
def browser(browser, titleOfColumn:column)
TITLES[column]
end
def browser(browser, isColumnValid:column)
NUMBER_OF_COLUMNS >= column
end
=end
end
class BrowserDelegate
TITLES = ['Ancestors', 'Constants', 'Methods', 'Instance Methods']
KEYS = [:ancestors, :konstants, :selectors, :instances_selectors]
def collection
@collection ||= begin
# klasses = Module.constants.reject { |c| c.to_s =~ /^[A-Z]+$/ || c.to_s[0..3] =~ /^[A-Z]+$/ || c.to_s[0] == '_'}
# .select {|c| Module.const_get(c).is_a?(Class) rescue nil }
# .map(&Module.method(:const_get))
klasses = CBKlasses.klasses
klasses.map { |klass| Node.new(klass)}.sort_by(&:klass)
end
end
def browser(sender, isColumnValid:column)
return true if column == 0 or column == 1
false
end
def browser(sender, createRowsForColumn:column, inMatrix:matrix)
if column == 0
collection.each_with_index do |node, index|
matrix.addRow
cell = matrix.cellAtRow(index, column:column)
cell.stringValue = node.klass
cell.leaf = false
cell.loaded = true
end
elsif column == 1
KEYS.each_with_index do |title, index|
matrix.addRow
cell = matrix.cellAtRow(index, column:0)
cell.stringValue = TITLES[index]
cell.leaf = false
cell.loaded = false
end
elsif column == 2
idx = sender.selectedRowInColumn(0)
row = sender.selectedRowInColumn(1)
key = KEYS[row]
collection[idx].send(key).each_with_index do |title, index|
matrix.addRow
cell = matrix.cellAtRow(index, column:0)
cell.stringValue = title.to_s
cell.leaf = true
cell.loaded = true
end
end
end
end | true |
5c8ef57d0e2ec8c91c2363627ba8366ea80812ab | Ruby | CTAnthny/Launch-Academy | /Phase3 - Hashes & Data Structs/space-jams/album.rb | UTF-8 | 1,616 | 3.6875 | 4 | [] | no_license | # object state: Album.new(track[:album_id], track[:album_name], track[:artists])
# CSV format: album_id,track_id,title,track_number,duration_ms,album_name,artists
class Album
attr_accessor :album_id, :album_title, :album_artists, :tracks, :tracks_duration, :duration_min
def initialize(album_id = nil, album_title = nil, album_artists = nil, tracks = [], tracks_duration = [], duration_min = 0)
@album_id, @album_title, @album_artists, @tracks, @tracks_duration, @duration_min = album_id, album_title, album_artists, tracks, tracks_duration, duration_min
end
# returns the ID of the album
def id
@album_id
end
# returns the title of the album
def title
@album_title
end
#returns the name of the artist(s) on the album
def artists
@album_artists
end
# returns an array of hashes representing each track on the album
def tracks
@tracks
end
def tracks_duration
@tracks_duration
end
# returns the duration of the album in minutes (duration_ms in the CSV is duration in milliseconds)
def duration_min
album_duration = 0
@tracks_duration.each do |track|
album_duration += track.to_i
end
@duration_min = ((album_duration / 1000).to_f / 60).to_f.round(2)
end
# returns a string of summary information about the album
def summary
summary = "\n"
summary << "Name: #{@album_title}\n"
summary << "Artist(s): #{album_artists}\n"
summary << "Duration (min.): #{duration_min}\n"
summary << "Tracks: \n"
@tracks.each { |track| summary << "- #{track.instance_variable_get("@title")}\n" }
summary
end
end
| true |
818c5f4065d91d0b38740a6d7f42a4a3c4daff5a | Ruby | notalex/experiments | /ruby/design_patterns/decorator_problem.rb | UTF-8 | 554 | 3.234375 | 3 | [] | no_license | class EnhancedWriter
def initialize(path)
@file = File.open(path, 'w')
@line_number = 1
end
def write_line(line)
@file.print(line)
@file.print("\n")
end
def timestamping_write_line(data)
write_line("#{ Time.new }: #{ data }")
end
def numbering_write_line(data)
write_line("#@line_number: #{ data }")
@line_number += 1
end
def close
@file.close
end
end
writer = EnhancedWriter.new('out.txt')
writer.write_line("A plain line")
writer.close
# Cannot write data with both line number and time stamp
| true |
5536bc3d51e47c57f1a5bb261056cfefac2081aa | Ruby | ministryofjustice/cloud-platform-helloworld-ruby-app | /app.rb | UTF-8 | 139 | 2.515625 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'sinatra'
require 'sinatra/base'
class App < Sinatra::Base
get '/' do
'<h1>Hello, World!</h1>'
end
end | true |
76888e69e588049aa47c7e73ada823db55b26ddb | Ruby | Lykos/SquirrelDB | /lib/compiler/type_annotator.rb | UTF-8 | 8,651 | 2.953125 | 3 | [] | no_license | require 'ast/sql/from_clause'
require 'ast/common/scoped_variable'
require 'ast/common/variable'
require 'ast/common/column'
require 'ast/common/pre_linked_table'
require 'ast/common/renaming'
require 'ast/common/expression'
require 'ast/sql/values'
require 'ast/iterators/dummy_iterator'
require 'ast/visitors/transform_visitor'
require 'schema/expression_type'
require 'schema/schema'
require 'errors/name_error'
require 'errors/type_error'
require 'errors/internal_error'
require 'compiler/link_helper'
module SquirrelDB
module Compiler
# Creates the type annotations for the expressions
# and the schemas for tables and raises errors in case of type errors or unresolvable symbols.
class TypeAnnotator
include AST
include TransformVisitor
include LinkHelper
def initialize(schema_manager, function_manager, table_manager)
@schema_manager = schema_manager
@function_manager = function_manager
@table_manager = table_manager
end
def process(statement)
column_stack = [{}]
ast = visit(statement, column_stack)
raise InternalError, "Column Stack not empty." unless column_stack.length == 1
ast
end
# Reads type information from the tables in the from clause.
def visit_from_clause(from_clause, column_stack)
tables = from_clause.tables.map do |c|
if c.kind_of?(Renaming)
raise InternalError, "#{c.expression.inspect} is not supported yet in a from clause." unless c.expression.variable?
var = c.expression
names = [c.name]
elsif c.variable?
var = c
names = [c]
else
raise InternalError, "#{c.inspect} is not supported yet in a from clause."
end
if var.kind_of?(ScopedVariable)
names << var.variable
end
raise NameError, "Table #{var} does not exist." unless @schema_manager.has?(var)
schema = @schema_manager.get(var)
each_link_info(names, schema) do |name, column|
type = column.type.expression_type
if column_stack.last.has_key?(name)
column_stack.last[name] = :ambiguous
else
column_stack.last[name] = type
end
end
PreLinkedTable.new(schema, names, @table_manager.variable_id(var))
end
FromClause.new(tables)
end
def visit_where_clause(where_clause, column_stack)
expression = visit(where_clause.expression, column_stack)
raise TypeError, "The expression of a where clause has to return a boolean value." unless expression.type == ExpressionType::BOOLEAN
WhereClause.new(expression)
end
def type(variable, column_stack)
if !column_stack.empty? && column_stack.last.has_key?(variable)
raise NameError, "#{variable} is ambiguous." if column_stack.last[variable] == :ambiguous
column_stack.last[variable]
else
raise NameError, "Variable #{variable} cannot be resolved."
end
end
def visit_variable(variable, column_stack)
Variable.new(variable.name, type(variable, column_stack))
end
def visit_scoped_variable(scoped_variable, column_stack)
ScopedVariable.new(scoped_variable.scope, scoped_variable.variable, type(scoped_variable, column_stack))
end
def visit_select_statement(select_statement, column_stack)
column_stack << column_stack.last.dup
from_clause = visit(select_statement.from_clause, column_stack)
where_clause = visit(select_statement.where_clause, column_stack)
select_clause = visit(select_statement.select_clause, column_stack)
column_stack.pop
SelectStatement.new(select_clause, from_clause, where_clause)
end
def visit_expression(expression, column_stack)
if expression.is_a?(Expression)
visit(expression, column_stack)
elsif expression.is_a?(SelectStatement)
select = visit(expression, column_stack)
schema = select.schema
raise TypeError, "A select statement inside an expression has to return exactly one column." if select.schema.length != 1
SelectExpression.new(select, schema.columns[0].type)
else
raise InternalError, "Unkown expression #{expression.inspect}."
end
end
def visit_function_application(fun_app, column_stack)
arguments = fun_app.arguments.map { |arg| visit_expression(arg, column_stack) }
f = @function_manager.function(fun_app.variable, arguments.map { |arg| arg.type })
case f
when :no_candidates then raise NameError, "Function #{fun_app.variable} cannot be resolved."
when :none then raise TypeError, "Function #{fun_app.arguments} is not defined for types #{fun_app.arguments.collect { |t| t.to_s }.join(", ")}."
when :ambiguous_fitting, :ambiguous_convertible then raise TypeError, "Function #{fun_app} is ambiguous for types #{fun_app.arguments.collect { |t| t.to_s }.join(", ")}}."
else
FunctionApplication.new(fun_app.variable, arguments, f.return_type)
end
end
def visit_create_table(create_table, column_stack)
raise NameError, "Table #{create_table.variable} exists." if @schema_manager.has?(create_table.variable)
names = []
columns = create_table.columns.collect do |c|
if names.include? c.name
raise NameError, "Column name #{c.name} appears more than once."
end
names << c.name
visit(c, column_stack)
end
CreateTable.new(create_table.variable, columns)
end
def visit_column(column, column_stack)
if column.has_default?
default = visit(column.default)
raise TypeError, "The default value of column #{column.name} has type #{default.type} which does not fit into a #{column.type}." unless column.type.converts_from?(default.type)
Column.new(column.name, column.type, default)
else
column
end
end
def visit_unary_operation(unop, column_stack)
inner = visit_expression(unop.inner, column_stack)
f = @function_manager.function(unop.operator, [inner.type])
case f
when :no_candidates then raise InternalError, "Invalid operator #{binop.operator}"
when :none then raise TypeError, "No operator #{unop.operator} defined for types #{inner.type}."
when :ambiguous_fitting, :ambiguous_convertible then raise TypeError, "Operator #{unop.operator} is ambiguous for types #{inner.type}."
else
UnaryOperation.new(unop.operator, inner, f.return_type)
end
end
def visit_binary_operation(binop, column_stack)
left = visit_expression(binop.left, column_stack)
right = visit_expression(binop.right, column_stack)
f = @function_manager.function(binop.operator, [left.type, right.type])
case f
when :no_candidates then raise InternalError, "Invalid operator #{binop.operator}"
when :none then raise TypeError, "No operator #{binop.operator} defined for types #{left.type}, #{right.type}."
when :ambiguous_fitting, :ambiguous_convertible then raise TypeError, "Operator #{binop.operator} is ambiguous for types #{left.type}, #{right.type}."
else
BinaryOperation.new(binop.operator, left, right, f.return_type)
end
end
def visit_values(values, column_stack)
vals = values.expressions.collect { |v| visit_expression(v, column_stack) }
types = vals.collect { |v, i| v.type }
DummyIterator.new(types, vals)
end
def visit_insert(insert, column_stack)
schema = @schema_manager.get(insert.variable)
pre_linked_table = PreLinkedTable.new(schema, insert.variable.to_s, @table_manager.variable_id(insert.variable))
columns = insert.columns.collect { |c| schema.column(c.name) }
inner = visit(insert.inner, column_stack)
if inner.length != columns.length
raise TypeError, "Insert for #{columns.length} columns has #{inner.length} values."
end
columns.zip(inner.types).each do |arg|
raise TypeError, "Value of type #{arg[1]} cannot be inserted into a column of type #{arg[0]}." unless arg[0].type.converts_from?(arg[1])
end
Insert.new(pre_linked_table, columns, inner)
end
end
end
end
| true |
9a5c5170710e2f79e804a76e36111d9ff6d1c01f | Ruby | jonathonnordquist/basic-compression | /basic_compression | UTF-8 | 1,277 | 3.671875 | 4 | [] | no_license | #!/usr/bin/ruby
class BasicCompression
def build_compressed_string(input_str)
raise(ArgumentError, "Input must be of type 'String'") unless input_str.class == String
raise(ArgumentError, "Input must consist of only lower case letters") if input_str =~ /[^a-z]/
output = ''
pointer = 0
while pointer < input_str.length
result = if input_str[pointer] == input_str[pointer + 1]
read_string_sequence(input_str[pointer..input_str.length])
else
[input_str[pointer], 1]
end
output += result[0]
pointer += result[1]
end
output
end
private
def read_string_sequence(repeating_string)
count = 1
count += 1 while repeating_string[count - 1] == repeating_string[count]
["#{repeating_string[0]}#{count}", count]
end
end
# Simple test sequences, uncomment to run
# basic = BasicCompression.new
# p basic.build_compressed_string('abcdefg') == 'abcdefg'
# p basic.build_compressed_string('abbcccdddd') == 'ab2c3d4'
# p basic.build_compressed_string('abcaaabbb') == 'abca3b3'
# p basic.build_compressed_string('aaabaaaaccaaaaba') == 'a3ba4c2a4ba'
begin
p BasicCompression.new.build_compressed_string(ARGV[0])
rescue ArgumentError => e
p e.message
end
| true |
d98a635b31a0c9f735c978e8e6f7abc1d282f2ae | Ruby | linkenneth/code-jam | /2013/qual/b/b.rb | UTF-8 | 716 | 3.46875 | 3 | [] | no_license | def check(lawn, h, x, y)
possible = true
$m.times do |x0|
possible &&= h >= lawn[y][x0]
end
return possible if possible
possible = true
$n.times do |y0|
possible &&= h >= lawn[y0][x]
end
return possible
end
T = gets.chomp.to_i
T.times do |t|
$n, $m = gets.chomp.split.map &:to_i
lawn = Array.new
$n.times do |i|
lawn << gets.chomp.split.map(&:to_i)
end
possible = true
lawn.each_with_index do |row, y|
row.each_with_index do |h, x|
if not check(lawn, h, x, y)
possible = false
end
if not possible
break
end
end
if not possible
break
end
end
puts (possible ? "Case ##{t+1}: YES" : "Case ##{t+1}: NO")
end
| true |
1efb3259b4e6268d9b5bed9a43f13c4ad87143b2 | Ruby | dougsko/projecteuler.net | /294/solution.rb | UTF-8 | 949 | 3.515625 | 4 | [] | no_license | #!/usr/bin/env ruby
#
# projecteuler.net
# problem 294
#
# For a positive integer k, define d(k) as the sum of the digits of k in
# its usual decimal representation. Thus d(42) = 4+2 = 6.
#
# For a positive integer n, define S(n) as the number of positive
# integers k < 10^n with the following properties :
#
# k is divisible by 23 and
# d(k) = 23.
# You are given that S(9) = 263626 and S(42) = 6377168878570056.
# Find S(11^12) and give your answer mod 10^9.
#
require 'gmp'
require 'ruby-progressbar'
require 'parallel'
def d(n)
n.to_s.chars.map(&:to_i).reduce(:+)
end
def divisible?(n)
return true if n % 23 == 0
return false
end
@count = 0
def inc
@count += 1
end
def s(n)
count = 0
max = GMP::Z.pow(10, n)
#max = 10**n
#1.upto(max) do |k|
Parallel.map((1..max), :in_processes => 6, :progress => "Working"){|k| (divisible?(k) and d(k) == 23) ? 1 : 0}.reduce(:+)
end
#puts s(6)
puts s(11**12) % 10**9
| true |
70426fb63a969c7050feba7cbeba963c3210c0c0 | Ruby | doskaf/sinatra-basic-routes-lab-online-web-ft-090919 | /app.rb | UTF-8 | 294 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative 'config/environment'
class App < Sinatra::Base
get '/name' do
"My name is Dominique"
end
get '/hometown' do
"My hometown is El Paso, TX"
end
get '/favorite-song' do
"My favorite song is 1999 Wildfire - BROCKHAMPTON"
end
end
| true |
d098fb5b81de551832171bc9b0bf2ff818fc5788 | Ruby | marcwright/WDI_ATL_1_Instructors | /REPO - DC - Students/w02/d03/Gabe/water_bottle/lib/water_bottle.rb | UTF-8 | 295 | 3.21875 | 3 | [] | no_license |
class WaterBottle
def initialize
@is_empty = true
@drinks_containing = 0
end
def is_empty?
return @is_empty
end
def fill
if @is_empty == true
@drinks_containing = 3
@is_empty = false
return "filled!"
else
false
end
end
def dispense
return "Water"
end
end | true |
0f8afc23f3bb066822884ea41ab7f60200b7690f | Ruby | TheJhyde/advent_2018 | /day17/day17.rb | UTF-8 | 1,278 | 3.203125 | 3 | [] | no_license | input = File.read("test_input.txt" ).scan(/([xy])\=(\d+), [xy]\=(\d+)\.{2}(\d+)/)
clay = []
input.each do |line|
(line[2]..line[3]).to_a.map do |i|
c = line[0] == "x" ? [line[1].to_i, i.to_i] : [i.to_i, line[1].to_i]
clay << c
end
end
p clay
lowest_point = clay.max_by {|c| c[1]}[1]
p lowest_point
def print_ground
end
def check_filled(pos, clay, water)
clay.any? {|c| c == pos} && water.any? {|c| c == pos}
end
water = [500, 0]
path = []
while water[1] >= lowest_point
if !check_filled([water[0], water[1]+1], clay, path)
path << water.dup
water[1] += 1
next
end
spread = 1
hit_right = false
hit_left = false
loop do
right = [water[0]+spread, water[1]]
if !hit_right && !check_filled(right, clay, path)
path << right
if !check_filled([water[0]+spread, water[1]+1], clay, path)
water = right
next
end
else
hit_right = true
end
left = [water[0]-spread, water[1]]
if !hit_left && !check_filled(left, clay, path)
path << left
if !check_filled([water[0]-spread, water[1]+1], clay, path)
water = left
next
end
else
hit_left = true
end
if hit_left && hit_right
water[1] -= 1
end
end
end
p path.length
p path | true |
f19cb07702ed920faeb210441716220d1cadbc59 | Ruby | Timcev1/ttt-with-ai-project-v-000 | /bin/tictactoe.rb | UTF-8 | 1,046 | 3.375 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'pry'
require_relative '../config/environment'
puts "Welcome to TicTacToe"
puts "Please select game mode
Enter 0 for Computer vs Computer
Enter 1 for Player vs Computer
enter 2 for Player vs Player"
input = gets.strip
if input == "0"
puts "Computer vs Computer"
game = Game.new(Players::Computer.new("X"), Players::Computer.new("O"), Board.new)
game.play
game.board.reset!
elsif input == "1"
puts "Computer vs Player"
puts "Do you want to be 'X' or 'O'?"
token = gets.strip.upcase
if token == "X"
game = Game.new(Players::Human.new("X"), Players::Computer.new("O"), Board.new)
elsif
game = Game.new(Players::Computer.new("X"), Players::Human.new("O"), Board.new)
elsif input == "2"
puts "Player vs Player"
game = Game.new(Players::Human.new("X"), Players::Human.new("O"), Board.new)
end
game.play
game.board.reset!
end
while game.over?
puts "Play Again?
Y = yes
N = no"
input = gets.strip.upcase
if input == "Y"
game.play
else input == "N"
exit
end
end
| true |
0605e6c744122727f184e65a225a68561eff7a5e | Ruby | dimanyc/github-markup-preview | /app.rb | UTF-8 | 3,155 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'sinatra'
require 'sinatra/assetpack'
require 'github/markup'
require 'redcarpet/compat'
module Preview
class WordpressReadmeParser
HEADERS = {
'contributors'=>'Contributors',
'donate_link'=>'Donate link',
'tags'=>'Tags',
'requires_at_least'=>'Requires at least',
'tested_up_to'=>'Tested up to',
'stable_tag'=>'Stable tag',
'license'=>'License',
'license_uri'=>'License URI'
}
def self.prerender data
data = full_strip data
headers_parsed=''
regex = /(.*\=\=\=)$(.*?)^(\=\=.*)/m
matches = data.match regex
short_desc = ''
if matches
headers = matches[2]
headers.each_line do |line|
parts = line.split(':')
header_name = HEADERS[parts[0].to_s.gsub(/\s/,'_').downcase]
if(header_name)
headers_parsed << "<strong>#{header_name}:</strong> #{parts[1,999].join(':')}<br>"
short_desc = ''
else
short_desc << line+" " unless line.empty?
end
end
data = matches[1]+"\n#{headers_parsed}\n\n\n#{short_desc}\n"+matches[3]
end
data.gsub! /^\=\=\=([^\=]*)\=\=\=$/, '#\1'
data.gsub! /^\=\=([^\=]*)\=\=$/, '##\1'
data.gsub! /^\=([^\=]*)\=$/, '###\1'
data
end
protected
def self.full_strip data
tmp = ''
data.each_line do |s|
tmp << s.strip+"\n"
s
end
tmp
end
end
class Renderer
TYPES = {
markdown: {
ext: "md",
name: "Simple Markdown"
},
wp: {
ext: "wp",
name: "WordPress Flavored Readme"
},
rdoc: {
ext: "rdoc",
name: "RDoc"
},
textile: {
ext: "textile",
name: "Textile"
},
mediawiki: {
ext: "wiki",
name: "MediaWiki"
},
gfm: {
ext: "md",
name: "Github Flavored Markdown"
},
org: {
ext: "org",
name: "Org"
},
creole: {
ext: "creole",
name: "Creole"
}
}
def render type, data
data ||= ""
case type
when :gfm
GitHub::Markdown.render_gfm(data)
when :wp
data = WordpressReadmeParser.prerender data
RedcarpetCompat.new(data).to_html
when :md
RedcarpetCompat.new(data).to_html
else
filename = "no-file.#{TYPES[type.to_sym][:ext]}"
GitHub::Markup.render(filename, data)
end
end
end
class App < Sinatra::Base
register Sinatra::AssetPack
assets {
js :application, '/assets/application.js', [
'/js/vendor/*','/js/application.js'
]
css :application, '/assets/application.css', [
'/css/vendor/*','/css/*'
]
}
get '/' do
@example_url = params[:example_url] || 'example.md';
@markup_type = params[:markup_type] || 'md';
erb :index
end
renderer = Renderer.new
post '/render' do
type = params[:type] || :gfm
return renderer.render(type.to_sym, params[:markup])
end
end
end | true |
f8a012539b9099e0c79bcf28ba28f826c6ac46b1 | Ruby | RicciFlowing/NaiveText | /lib/NaiveText/ExamplesGroup.rb | UTF-8 | 704 | 3.171875 | 3 | [
"MIT"
] | permissive | class ExamplesGroup
def initialize(args)
@examples = args[:examples].to_a || []
@language_model = args[:language_model] || ->(str) { str }
load_text
split_text_into_words
format_words
fail 'Empty_Trainingsdata' if @words.length == 0
end
def count(word)
@words.count(@language_model.call(word.downcase))
end
def word_count
@words.count
end
private
def load_text
@text = ''
@examples.each do |example|
@text += ' ' + example.text
end
end
def split_text_into_words
@words = @text.split(/\W+/)
end
def format_words
@words.map!(&:downcase)
@words.map! { |word| @language_model.call(word) }
@words
end
end
| true |
966ddb41e54e844a8f74b0fdc8b38c6fd42b1ef3 | Ruby | mario21ic/POO | /Ruby/Transacciones/tests.rb | UTF-8 | 1,042 | 2.703125 | 3 | [] | no_license | require_relative "Empresa"
require "test/unit"
class TestCalcularPago < Test::Unit::TestCase
def setup
@empresa = Empresa.new("UPC", "333666777")
end
def test_calcular_pagos_500
@empresa.registrar_pasos(1)
assert_equal(500.0, @empresa.calcular_pago())
@empresa.registrar_pasos(900)
assert_equal(500.0, @empresa.calcular_pago())
@empresa.registrar_pasos(1000)
assert_equal(500.0, @empresa.calcular_pago())
end
def test_calcular_pagos_520
@empresa.registrar_pasos(1001)
assert_equal(520.0, @empresa.calcular_pago())
@empresa.registrar_pasos(1010)
assert_equal(520.0, @empresa.calcular_pago())
@empresa.registrar_pasos(1100)
assert_equal(520.0, @empresa.calcular_pago())
end
def test_calcular_pagos_540
@empresa.registrar_pasos(1101)
assert_equal(540.0, @empresa.calcular_pago())
@empresa.registrar_pasos(1198)
assert_equal(540.0, @empresa.calcular_pago())
end
end
| true |
73504b3cadab3ecc79b756a05068a1fcc5ee6a92 | Ruby | chad/rubinius | /mspec/spec/runner/example_spec.rb | UTF-8 | 2,672 | 2.59375 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/../spec_helper'
require 'mspec/matchers/base'
require 'mspec/runner/mspec'
require 'mspec/mocks/mock'
require 'mspec/runner/example'
describe ExampleState do
it "is initialized with the describe and it strings" do
ExampleState.new("This", "does").should be_kind_of(ExampleState)
end
end
describe ExampleState, "#describe" do
before :each do
@state = ExampleState.new("describe", "it")
end
it "returns the arguments to the #describe block stringified and concatenated" do
@state.describe.should == "describe"
end
end
describe ExampleState, "#it" do
before :each do
@state = ExampleState.new("describe", "it")
end
it "returns the argument to the #it block" do
@state.it.should == "it"
end
end
describe ExampleState, "#unfiltered?" do
before :each do
MSpec.store :include, nil
MSpec.store :exclude, nil
@state = ExampleState.new("describe", "it")
@filter = mock("filter")
end
it "returns true if MSpec include filters list is empty" do
@state.unfiltered?.should == true
end
it "returns true if MSpec include filters match this spec" do
@filter.should_receive(:===).and_return(true)
MSpec.register :include, @filter
@state.unfiltered?.should == true
end
it "returns false if MSpec include filters do not match this spec" do
@filter.should_receive(:===).and_return(false)
MSpec.register :include, @filter
@state.unfiltered?.should == false
end
it "returns true if MSpec exclude filters list is empty" do
@state.unfiltered?.should == true
end
it "returns true if MSpec exclude filters do not match this spec" do
@filter.should_receive(:===).and_return(false)
MSpec.register :exclude, @filter
@state.unfiltered?.should == true
end
it "returns false if MSpec exclude filters match this spec" do
@filter.should_receive(:===).and_return(true)
MSpec.register :exclude, @filter
@state.unfiltered?.should == false
end
it "returns false if MSpec include and exclude filters match this spec" do
@filter.should_receive(:===).twice.and_return(true)
MSpec.register :include, @filter
MSpec.register :exclude, @filter
@state.unfiltered?.should == false
end
end
describe ExampleState, "#filtered?" do
before :each do
@state = ExampleState.new("describe", "it")
end
it "returns true if #unfiltered returns false" do
@state.should_receive(:unfiltered?).and_return(false)
@state.filtered?.should == true
end
it "returns false if #unfiltered returns true" do
@state.should_receive(:unfiltered?).and_return(true)
@state.filtered?.should == false
end
end
| true |
716e23894a19191eafaebfbcc639db70947aebb1 | Ruby | lukebri/citadel | /lib/match_seeder/common.rb | UTF-8 | 982 | 2.6875 | 3 | [
"MIT"
] | permissive | module MatchSeeder
module Common
extend self
def get_roster_pool(target)
rosters = target.approved_rosters
rosters << nil if rosters.size.odd?
rosters.to_a
end
def create_match_for(home_team, away_team, options)
# Swap home and away team to spread out home/away matches
if home_team && away_team &&
(home_team.home_team_matches.size > home_team.away_team_matches.size ||
away_team.away_team_matches.size > away_team.home_team_matches.size) ||
!home_team
home_team, away_team = away_team, home_team
end
match_options = get_opts(home_team, away_team, options)
CompetitionMatch.create!(match_options)
end
private
def get_opts(home_team, away_team, options)
match_options = options.merge(home_team: home_team, away_team: away_team)
match_options[:sets] = match_options[:sets].map(&:dup) if match_options.key? :sets
match_options
end
end
end
| true |
de71c924c3314bac8e4aa218ca658131d6ba137f | Ruby | DouglasDDo/Data-Structures-and-Algorithms | /practice_problems/strings/ruby/caesar_cypher.rb | UTF-8 | 935 | 4.46875 | 4 | [] | no_license | # Objective: Given a str and a positive integer n, construct a Caesar cipher
# that shifts any letters in the string by n spaces in the alphabet. Retain case
# for any letter-chars and do not alter any non-letter chars, including spaces.
def caesar_cypher(str, n)
# Use ranges to build arrays of lower and upper case letters
lowers = ("a".."z").to_a
uppers = ("A".."Z").to_a
# Go through each char in the original string
result = str.chars.map { |char|
# Check to see if the char is a letter or not by seeing if it's included in
# one of the letter arrays.
if lowers.include?(char)
new_idx = (lowers.index(char) + n) % 26
lowers[new_idx]
elsif uppers.include?(char)
new_idx = (uppers.index(char) + n) % 26
uppers[new_idx]
else
# If the char is not a letter char, leave it alone but add it to the result
char
end
}.join
result
end
p caesar_cypher('helloZ', 1)
| true |
bbae32d95038d11c6968cf5744fae16ba23f6f38 | Ruby | doulighan/ttt-8-turn-bootcamp-prep-000 | /lib/turn.rb | UTF-8 | 719 | 4.25 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def valid_move?(board, i)
(position_taken?(board, i) || i < 0 || i > 8) ?
false : true
end
def position_taken?(board, i)
(board[i] == " " || board[i] == "" || board[i] == nil) ?
false : true
end
def move(board, i, char = "X")
board[i] = char
end
def input_to_index(i)
i.to_i - 1
end
def turn(board)
puts "Please enter 1-9:"
i = gets.strip
i = input_to_index(i)
if valid_move?(board, i)
move(board, i)
display_board(board)
else
turn(board)
end
end
| true |
9d43cdaa6d966bbaa50830674e3aaafe1b552d8d | Ruby | aust-store/aust-platform | /lib/store/company_statistics.rb | UTF-8 | 182 | 2.546875 | 3 | [] | no_license | module Store
class CompanyStatistics
def initialize(company)
@company = company
end
def statistics
{ total_items: @company.items.count }
end
end
end
| true |
0a27778c9cd5e135ad86c40ae0a1e2c8ccf8fa5c | Ruby | rails/rails | /actionview/lib/action_view/helpers/capture_helper.rb | UTF-8 | 8,349 | 3.203125 | 3 | [
"MIT",
"Ruby"
] | permissive | # frozen_string_literal: true
require "active_support/core_ext/string/output_safety"
module ActionView
module Helpers # :nodoc:
# = Action View Capture \Helpers
#
# \CaptureHelper exposes methods to let you extract generated markup which
# can be used in other parts of a template or layout file.
#
# It provides a method to capture blocks into variables through #capture and
# a way to capture a block of markup for use in a layout through #content_for.
#
# As well as provides a method when using streaming responses through #provide.
# See ActionController::Streaming for more information.
module CaptureHelper
# The capture method extracts part of a template as a string object.
# You can then use this object anywhere in your templates, layout, or helpers.
#
# The capture method can be used in \ERB templates...
#
# <% @greeting = capture do %>
# Welcome to my shiny new web page! The date and time is
# <%= Time.now %>
# <% end %>
#
# ...and Builder (RXML) templates.
#
# @timestamp = capture do
# "The current timestamp is #{Time.now}."
# end
#
# You can then use that variable anywhere else. For example:
#
# <html>
# <head><title><%= @greeting %></title></head>
# <body>
# <b><%= @greeting %></b>
# </body>
# </html>
#
# The return of capture is the string generated by the block. For Example:
#
# @greeting # => "Welcome to my shiny new web page! The date and time is 2018-09-06 11:09:16 -0500"
#
def capture(*args, &block)
value = nil
@output_buffer ||= ActionView::OutputBuffer.new
buffer = @output_buffer.capture { value = yield(*args) }
case string = buffer.presence || value
when OutputBuffer
string.to_s
when ActiveSupport::SafeBuffer
string
when String
ERB::Util.html_escape(string)
end
end
# Calling <tt>content_for</tt> stores a block of markup in an identifier for later use.
# In order to access this stored content in other templates, helper modules
# or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
#
# Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
# <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
#
# <% content_for :not_authorized do %>
# alert('You are not authorized to do that!')
# <% end %>
#
# You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
#
# <%= content_for :not_authorized if current_user.nil? %>
#
# This is equivalent to:
#
# <%= yield :not_authorized if current_user.nil? %>
#
# <tt>content_for</tt>, however, can also be used in helper modules.
#
# module StorageHelper
# def stored_content
# content_for(:storage) || "Your storage is empty"
# end
# end
#
# This helper works just like normal helpers.
#
# <%= stored_content %>
#
# You can also use the <tt>yield</tt> syntax alongside an existing call to
# <tt>yield</tt> in a layout. For example:
#
# <%# This is the layout %>
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
# <head>
# <title>My Website</title>
# <%= yield :script %>
# </head>
# <body>
# <%= yield %>
# </body>
# </html>
#
# And now, we'll create a view that has a <tt>content_for</tt> call that
# creates the <tt>script</tt> identifier.
#
# <%# This is our view %>
# Please login!
#
# <% content_for :script do %>
# <script>alert('You are not authorized to view this page!')</script>
# <% end %>
#
# Then, in another view, you could to do something like this:
#
# <%= link_to 'Logout', action: 'logout', remote: true %>
#
# <% content_for :script do %>
# <%= javascript_include_tag :defaults %>
# <% end %>
#
# That will place +script+ tags for your default set of JavaScript files on the page;
# this technique is useful if you'll only be using these scripts in a few views.
#
# Note that <tt>content_for</tt> concatenates (default) the blocks it is given for a particular
# identifier in order. For example:
#
# <% content_for :navigation do %>
# <li><%= link_to 'Home', action: 'index' %></li>
# <% end %>
#
# And in another place:
#
# <% content_for :navigation do %>
# <li><%= link_to 'Login', action: 'login' %></li>
# <% end %>
#
# Then, in another template or layout, this code would render both links in order:
#
# <ul><%= content_for :navigation %></ul>
#
# If the flush parameter is +true+ <tt>content_for</tt> replaces the blocks it is given. For example:
#
# <% content_for :navigation do %>
# <li><%= link_to 'Home', action: 'index' %></li>
# <% end %>
#
# <%# Add some other content, or use a different template: %>
#
# <% content_for :navigation, flush: true do %>
# <li><%= link_to 'Login', action: 'login' %></li>
# <% end %>
#
# Then, in another template or layout, this code would render only the last link:
#
# <ul><%= content_for :navigation %></ul>
#
# Lastly, simple content can be passed as a parameter:
#
# <% content_for :script, javascript_include_tag(:defaults) %>
#
# WARNING: <tt>content_for</tt> is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
def content_for(name, content = nil, options = {}, &block)
if content || block_given?
if block_given?
options = content if content
content = capture(&block)
end
if content
options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
end
nil
else
@view_flow.get(name).presence
end
end
# The same as +content_for+ but when used with streaming flushes
# straight back to the layout. In other words, if you want to
# concatenate several times to the same buffer when rendering a given
# template, you should use +content_for+, if not, use +provide+ to tell
# the layout to stop looking for more contents.
#
# See ActionController::Streaming for more information.
def provide(name, content = nil, &block)
content = capture(&block) if block_given?
result = @view_flow.append!(name, content) if content
result unless content
end
# <tt>content_for?</tt> checks whether any content has been captured yet using <tt>content_for</tt>.
#
# Useful to render parts of your layout differently based on what is in your views.
#
# <%# This is the layout %>
# <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
# <head>
# <title>My Website</title>
# <%= yield :script %>
# </head>
# <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
# <%= yield %>
# <%= yield :right_col %>
# </body>
# </html>
def content_for?(name)
@view_flow.get(name).present?
end
# Use an alternate output buffer for the duration of the block.
# Defaults to a new empty string.
def with_output_buffer(buf = nil) # :nodoc:
unless buf
buf = ActionView::OutputBuffer.new
if output_buffer && output_buffer.respond_to?(:encoding)
buf.force_encoding(output_buffer.encoding)
end
end
self.output_buffer, old_buffer = buf, output_buffer
yield
output_buffer
ensure
self.output_buffer = old_buffer
end
end
end
end
| true |
fdf260915577fdf1c879072bfd78c3ecba27f0a9 | Ruby | dgokman/blackjack | /blackjack.rb | UTF-8 | 3,227 | 4.1875 | 4 | [] | no_license | require 'pry'
class Card
attr_reader :value, :suit
def initialize(value, suit)
@value = value
@suit = suit
end
def create_card
"#{@value}#{@suit}"
end
end
class Deck
attr_reader :cards
def initialize
@cards = []
['A','2','3','4','5','6','7','8','9','10','J','Q','K'].each do |value|
['♣','♥','♦','♠'].each do |suit|
card = Card.new(value, suit)
@cards << card.create_card
@shuffled_cards = @cards.shuffle
end
end
end
def deal(num)
@player_cards = []
num.times do
@player_cards << @shuffled_cards.pop
end
puts "Player was dealt #{@player_cards[0]}"
puts "Player was dealt #{@player_cards[1]}"
end
def player_score
player_score = 0
@player_cards.each do |card|
if card[0] == 'J' || card[0] == 'Q' || card[0] == 'K' || card[0] == '1'
score = 10
elsif card[0] == 'A'
score = 11
else
score = card[0].to_i
end
player_score += score
end
player_score
end
def dealer_score
dealer_score = 0
@dealer_cards.each do |card|
if card[0] == 'J' || card[0] == 'Q' || card[0] == 'K' || card[0] == '1'
score = 10
elsif card[0] == 'A'
score = 11
else
score = card[0].to_i
end
dealer_score += score
end
dealer_score
end
def hit_or_stand(hit_or_stand)
@dealer_cards = []
player_index = 2
if player_score > 21 && hit_or_stand == 'h'
puts "Dealer wins!"
elsif player_score < 21 && hit_or_stand == 'h'
@player_cards << @shuffled_cards.pop
puts "Player was dealt #{@player_cards[player_index]}"
puts "Player score: #{player_score}"
player_index += 1
puts "Hit or stand (h/s):"
hit_or_stand = gets.chomp
elsif player_score < 21 && hit_or_stand == 's'
2.times do
@dealer_cards << @shuffled_cards.pop
end
puts "Dealer was dealt #{@dealer_cards[0]}"
puts "Dealer was dealt #{@dealer_cards[1]}"
puts "Dealer score: #{dealer_score}"
else
puts "Hit or stand (h/s):"
hit_or_stand = gets.chomp
end
while dealer_score < 17
dealer_index = 0
@dealer_cards << @shuffled_cards.pop
puts "Dealer was dealt #{@dealer_cards[dealer_index]}"
puts "Dealer score: #{dealer_score}"
dealer_index += 1
#binding.pry
end
end
end
class Hand
attr_reader :player_score, :dealer_score
def initialize(player_score, dealer_score)
@player_score = player_score
@dealer_score = dealer_score
end
def winner
if (@player_score > @dealer_score) || @dealer_score > 21
puts "Player wins!"
elsif (@dealer_score > @player_score) || @player_score > 21
puts "Dealer wins!"
else
puts "Player pushes!"
end
end
end
deck = Deck.new
puts "Welcome to Blackjack!\n\n"
deck.deal(2)
puts "Player score: #{deck.player_score}"
if deck.player_score == 21
puts "Blackjack!"
else
puts "Hit or stand (h/s):"
hit_or_stand = gets.chomp
end
deck.hit_or_stand(hit_or_stand)
hand = Hand.new(deck.player_score, deck.dealer_score)
hand.winner
| true |
0685626834216a9a11c681f173d2e69f3aad3d2c | Ruby | johnson/graph | /test/base_test.rb | UTF-8 | 2,089 | 3 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'graph/base'
class TestBase < Test::Unit::TestCase
def setup
@gr = Graph::Base.new
@gr.add_edge("1", "2", 7)
@gr.add_edge("1", "3", 9)
@gr.add_edge("1", "6", 14)
@gr.add_edge("2", "3", 10)
@gr.add_edge("2", "4", 15)
@gr.add_edge("3", "4", 11)
@gr.add_edge("3", "6", 2)
@gr.add_edge("4", "5", 6)
@gr.add_edge("5", "6", 9)
end
def test_add_edge
expected_hash = {"1"=>{"2"=>7, "3"=>9, "6"=>14}, "2"=>{"1"=>7, "3"=>10, "4"=>15}, "3"=>{"1"=>9, "2"=>10, "4"=>11, "6"=>2}, "6"=>{"1"=>14, "3"=>2, "5"=>9}, "4"=>{"2"=>15, "3"=>11, "5"=>6}, "5"=>{"4"=>6, "6"=>9}}
assert_equal expected_hash, @gr.instance_variable_get(:"@vertices")
end
def test_length_of_u_v
assert_equal 7, @gr.length("1", "2")
assert_equal 9, @gr.length("1", "3")
assert_equal 14, @gr.length("1", "6")
assert_equal 10, @gr.length("2", "3")
assert_equal 15, @gr.length("2", "4")
assert_equal 11, @gr.length("3", "4")
assert_equal 2, @gr.length("3", "6")
assert_equal 6, @gr.length("4", "5")
assert_equal 9, @gr.length("5", "6")
end
def test_neighbor_v_of_u
assert_equal ["2", "3", "6"].sort, @gr.neighbor_v_of("1").sort
assert_equal ["1", "3", "4"].sort, @gr.neighbor_v_of("2").sort
assert_equal ["1", "2", "4", "6"].sort, @gr.neighbor_v_of("3").sort
assert_equal ["2", "3", "5"].sort, @gr.neighbor_v_of("4").sort
assert_equal ["4", "6" ].sort, @gr.neighbor_v_of("5").sort
assert_equal ["1", "3", "5"].sort, @gr.neighbor_v_of("6").sort
end
def test_dijkstra_shortest_path
dist, prev = @gr.dijkstra("1")
expected_dist = {"1"=>0, "2"=>7, "3"=>9, "6"=>11, "4"=>20, "5"=>20}
expected_prev = {"1"=> "UNDEFINED", "2"=>"1", "3"=>"1", "6"=>"3", "4"=>"3", "5"=>"6"}
assert_equal expected_dist, dist
assert_equal expected_prev, prev
end
def test_not_allow_negative_edge
new_gr = Graph::Base.new
assert_raise(RuntimeError) do
new_gr.add_edge("a", "b", -1)
end
end
end | true |
f344b8ce0ac4f13bdd331d30e92cc004ebfb624b | Ruby | mblack/gitimmersion | /lib/hello.rb | UTF-8 | 140 | 3.203125 | 3 | [] | no_license | require 'greeter'
# Author: mtb (mtblack@alum.mit.edu)
# Default is "World"
name = ARGV.first || "World"
greeter = Greeter.new(name)
puts greeter.greet
| true |
d7618546bff738c6e03497c2037f80616de12b59 | Ruby | kevinmarvin/d.rb-cell-demo | /reeler.rb | UTF-8 | 2,193 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'reel'
require 'lib/testier'
require 'websocket_parser'
require 'json'
require 'symboltable'
class Socketeer
include Celluloid
def initialize(socket, neighbors)
@remote_ip = socket.remote_ip
@testier = Testier.new
@neighbors = neighbors
@socket = socket
@neighbors[@remote_ip] = @socket
@socket.on_close do |a,m|
@socket.close
end
@socket.on_message do |m|
@socket.cancel_timer!
process(m)
@socket.read_every(1)
end
@socket.on_ping do |payload|
@socket.write ::WebSocket::Message.pong(payload).to_data
end
@socket.read_every(1)
end
def process(message)
command = SymbolTable.new(JSON.load(message))
case command.work.to_sym
when :linear
send_off @testier.linear(command.pages)
when :parallel
send_off @testier.parallel(command.pages)
when :pool
send_off @testier.pooly(5, command.pages)
end
end
def send_off(results)
highest=results.sort_by {|letter, ct| ct}.last
text = "#{@remote_ip} had a high of #{highest}<br/>"
@neighbors.keys.each {|socket_key| @neighbors[socket_key].write text}
end
end
class Reeler < Reel::Server
MY_IP="172.16.0.235"
MY_PORT=3100
def initialize
puts "Starting server at #{MY_IP}:#{MY_PORT}"
@sockets = {}
super(MY_IP, MY_PORT, &method(:on_connection))
end
def on_connection(connection)
while request = connection.request
if !request.websocket?
handle_homepage connection, request
return
else
connection.detach
handle_socket request.websocket
return
end
end
end
def handle_homepage(connection, request)
if request.url == "/"
connection.respond :ok, ::IO.read("public/index.html").split("|host|").join("#{MY_IP}:#{MY_PORT}")
else
puts "BAD PAGE"
connection.respond :not_found, "No Mr Peter... No... try /"
end
end
def handle_socket(socket)
i = Socketeer.new(socket, @sockets)
@sockets.delete(socket.remote_ip) if @sockets.keys.include?(socket.remote_ip)
@sockets[socket.remote_ip] = socket
end
end
Reeler.supervise_as :reelerer
sleep | true |
b5b09ce0f678fdcaa6008de71dd522f48d11d05c | Ruby | paologianrossi/chivas | /spec/cpu_spec.rb | UTF-8 | 2,514 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require 'highline/simulate'
describe "Cpu" do
let(:memory) { mock(Memory) }
let(:cpu) { Cpu.new }
let(:io) { mock(HighLine) }
describe "execute" do
it "should add with code 0" do
memory.should_receive(:read).and_return(30)
cpu.ram = memory
cpu.acc = 12
cpu.exec(0, 100)
cpu.acc.should be 42
end
it "should subtract with code 1" do
memory.should_receive(:read).and_return(12)
cpu.ram = memory
cpu.acc = 42
cpu.exec(1, 100)
cpu.acc.should be 30
end
it "should read with code 2" do
$terminal = cpu.io
HighLine::Simulate.with('9999') do
cpu.exec(2, 123)
end
cpu.acc.should eq(9999)
end
it "should write with code 3" do
io.should_receive(:say).with("--> 100")
cpu.io = io
cpu.acc = 100
cpu.exec(3,0)
end
it "should store with code 4" do
memory.should_receive(:store).with(100)
cpu.ram = memory
cpu.exec(4, 100)
end
it "should load with code 5" do
memory.should_receive(:read).with(100).and_return(123)
cpu.ram = memory
cpu.exec(5, 100)
cpu.acc.should eq(123)
end
it "should jump with code 6" do
cpu.exec(6, 123)
cpu.pc.should eq(123)
end
it "should jzer with code 7" do
cpu.acc = 0
cpu.exec(7, 123)
cpu.pc.should eq(123)
cpu.acc = 55
cpu.exec(7, 99)
cpu.pc.should eq(123)
end
it "should stop with code 8" do
cpu.instance_variable_set('@running', true)
cpu.exec(8, 99)
cpu.should_not be_running
end
it "should fail with any other code" do
expect { cpu.exec(42, 192) }.to raise_error
end
it "should run a short program" do
memory.should_receive(:read).with(0).and_return(5010)
memory.should_receive(:read).with(1).and_return(11)
memory.should_receive(:read).with(2).and_return(8000)
memory.should_receive(:read).with(10).and_return(30)
memory.should_receive(:read).with(11).and_return(12)
cpu.ram = memory
cpu.run
cpu.acc.should eq(42)
end
end
describe "inspection" do
let(:cpu) { Cpu.new() }
it "should show all registry data in the right format" do
memory.should_receive(:read).with(0).and_return(8123)
cpu.ram = memory
cpu.acc=10
cpu.run
cpu.inspect.should eq("<CPU: [acc: 10] [PC: 1] [IR[8, 123]] STOPPED]>")
end
end
end
| true |
7fbe9dd3ac44984c207235971a7954238209effb | Ruby | xababafr/RubyPFE | /tests/semaine1/a-parser.rb | UTF-8 | 119 | 3.171875 | 3 | [
"MIT"
] | permissive | class Animal
attr_accessor :nom
def initialize(nom)
@nom = nom
end
def parler
puts "je suis #{nom}"
end
end
| true |
c2ff282bed86f545e03487d4525941dc3aefd147 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/fe37429c67ca417c9e829124486d8ad2.rb | UTF-8 | 534 | 3.765625 | 4 | [] | no_license | class Bob
def hey(message)
inquirer = MessageInquirer.new(message)
if inquirer.shouting?
'Woah, chill out!'
elsif inquirer.question?
'Sure.'
elsif inquirer.blank?
'Fine. Be that way.'
else
'Whatever.'
end
end
class MessageInquirer
def initialize(message)
@message = message
end
def question?
@message.end_with?('?')
end
def shouting?
!blank? and @message.upcase == @message
end
def blank?
@message.empty?
end
end
end
| true |
193ef66cfc004ec693287850a9f1eaaceeef8a77 | Ruby | dtomasiewicz/rbrowse | /r_browse/form.rb | UTF-8 | 2,803 | 2.8125 | 3 | [] | no_license | module RBrowse
class Form
attr_accessor :method, :action
def initialize(page, form_node)
@page = page
@method = (form_node['method'] || 'GET').upcase
@action = form_node['action'] || page.uri
# fields are stored as an array to preserve form ordering
@fields = []
form_node.css('input,select,textarea,button').each do |node|
next unless node['name'] && (value = self.class.node_value node)
case node.name
when 'select', 'textarea'
rel = true
when 'input'
case (node['type'] || 'text').downcase
when 'submit', 'button', 'reset', 'image'
rel = false
when 'checkbox', 'radio'
rel = node.matches?('[@checked="checked"]')
else
rel = true
end
else
rel = false
end
@fields << Field.new(node['name'], value, rel)
end
end
def extend(field, value)
@fields << Field.new(field, value.to_s, true) unless value == nil
end
def set(field, value)
@fields.delete_if {|f| f.name == field}
extend field, value
end
alias_method :[]=, :set
# if only_relevant is true, submission inputs and unchecked checkboxes/radio
# buttons will be ignored
def get_all(field, only_relevant = false)
@fields.select do |f|
f.name == field && (!only_relevant || f.relevant)
end.map &:value
end
# will return a string, or nil iff node is a SELECT with no OPTION selected
def self.node_value(node)
case node.name
when 'input'
case (node['type'] || 'text').downcase
when 'checkbox', 'radio'
node['value'] || 'on'
else
node['value']
end
when 'button'
node['value']
when 'textarea'
node.inner_text
when 'select'
sel = node.at_css 'option[@selected="selected"]'
sel ? (sel['value'] || '') : nil
else
nil
end
end
def get(field, only_relevant = false)
get_all(field, only_relevant).last
end
alias_method :[], :get
def submit(activator = nil, params = {}, &block)
data = @fields.select{|f| f.relevant || f.name == activator}.map do |f|
"#{CGI::escape f.name}=#{CGI::escape f.value}"
end.join '&'
if @method == 'GET'
return @page.browser.get(@action, params.merge(:data => data), &block)
else
return @page.browser.post(@action, data, params, &block)
end
end
end
class Field
attr_reader :name, :value, :relevant
def initialize(name, value, relevant)
@name = name
@value = value
@relevant = relevant
end
end
end
| true |
7018ec53e572a570fc06bff25f4df21ce7905a32 | Ruby | UpAndAtThem/practice_kata | /isogram.rb | UTF-8 | 181 | 2.96875 | 3 | [] | no_license | # Isogram class
class Isogram
def self.isogram?(test_string)
word_chars_only = test_string.gsub(/\W/, '').downcase.chars
word_chars_only.uniq == word_chars_only
end
end
| true |
f6edbce6451c06d5d0993694dcc5b8776221814f | Ruby | UmbertoMoioli/Lesson_1 | /TicTacToe.rb | UTF-8 | 2,284 | 4.1875 | 4 | [] | no_license | # 1. Bisogna comprendere le specifiche del programma, capire la portata del programma
# 2. Quindi serve la logica dell'applicazione, la sequenza di azioni che vanno prese
# 3. Quindi tradurre questi passi in codice
# 4. Testare il programma per verificare la logica
# Passaggi
# 1. Draw a board
# 2. Assign Player "X" e Computer "O"
# 3. Loop until a winner or all squares are taken
# 4. Player picks a empty square
# 5. Check for winner
# 6. Computer picks a empty square
# 7. Check for winner
# 8. If there is a winner
# 9. show the winner
# 10. or else
# 11. It's a tie
require "pry"
def initialize_board
board = {}
(1..9).each {|position| board[position] = " "}
board
end
def empty_position(board)
board.keys.select {|position| board[position] == ' '}
end
def player_picks_square(board)
begin
puts "Pick a square (1 - 9):"
position = gets.chomp.to_i
end until empty_position(board).include?(position)
board[position] = "X"
end
###
def computer_picks_square(board)
if board.values.count("O") == 2
position = board.select{|k,v| v == ' '}.keys.first
board[position] = "O"
else
position = empty_position(board).sample
board[position] = "O"
end
end
###
def check_winner(board)
winning_lines = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]]
winning_lines.each do |line|
return "Player" if board.values_at(*line).count('X') == 3
return "Computer" if board.values_at(*line).count('O') == 3
end
nil
end
def draw_board(b)
system "clear"
puts " #{b[1]} | #{b[2]} | #{b[3]} "
puts " - - - - - "
puts " #{b[4]} | #{b[5]} | #{b[6]} "
puts " - - - - - "
puts " #{b[7]} | #{b[8]} | #{b[9]} "
end
def check_winner(board)
winning_lines = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
winning_lines.each do |line|
return "Player" if board.values_at(*line).count("X") == 3
return "Computer" if board.values_at(*line).count("O") == 3
end
nil
end
board = initialize_board
draw_board(board)
begin
player_picks_square(board)
computer_picks_square(board)
draw_board(board)
winner = check_winner(board)
end until winner || empty_position(board).empty?
if winner
puts "#{winner} won!"
else
puts "It's a tie!"
end
| true |
b2a958f9e2b906f31e4a83eea1c9da4ac42a9cee | Ruby | robbles/RainbowXMPP | /vendor/drb_scripts/basic_receive.rb | UTF-8 | 1,194 | 2.671875 | 3 | [] | no_license | #!/bin/env ruby
##
# Simple IM client that receives a message.
require 'rubygems'
require 'xmpp4r'
require 'yaml'
# Jabber::debug = true
config = YAML.load_file('config.yml')
username = config['from']['jid']
password = config['from']['password']
#########
jid = Jabber::JID.new(username)
client = Jabber::Client.new(jid)
client.connect
client.auth(password)
sent = []
mainthread = Thread.current
# Initial presence
client.send(Jabber::Presence.new.set_status("XMPP4R at #{Time.now.utc}"))
client.add_message_callback do |m|
if m.type != :error
if !sent.include?(m.from)
msg = Jabber::Message.new(m.from, "I am a robot. You are connecting for the first time.")
msg.type = :chat
client.send(msg)
sent << m.from
end
case m.body
when 'exit'
msg = Jabber::Message.new(m.from, "Exiting ...")
msg.type = :chat
client.send(msg)
mainthread.wakeup
else
msg = Jabber::Message.new(m.from, "You said #{m.body} at #{Time.now.utc}")
msg.type = :chat
client.send(msg)
puts "Received: " + m.body
end
else
puts [m.type.to_s, m.body].join(": ")
end
end
Thread.stop
client.close
| true |
11906aec8205496f4758c0ed8be771ea9ac1ad70 | Ruby | BarbaraPruz/activerecord-validations-lab-v-000 | /app/models/post.rb | UTF-8 | 833 | 3 | 3 | [] | no_license | require 'pry'
class Post < ActiveRecord::Base
validates :title, presence: true
validates :content, { :length => { minimum: 250 } }
validates :summary, { :length => { maximum: 250 } }
validates :category, inclusion: ['Fiction', 'Non-Fiction']
validate :is_clickbait?
# def is_clickbait?
# if self.title
# found = ["Won't Believe", "Secret", "Top ", "Guess"].any? { |click|
# self.title.include?(click)
# }
# if !found
# errors.add(:title,"Not clickbait-y")
# end
# end
# end
# Better solution
CLICKBAIT_PATTERNS = [
/Won't Believe/i,
/Secret/i,
/Top [0-9]*/i,
/Guess/i
]
def is_clickbait?
if CLICKBAIT_PATTERNS.none? { |pat| pat.match title }
errors.add(:title, "Not clickbait-y")
end
end
end
| true |
75453f7d5ef25297465b78e8049ea1f63b6d120b | Ruby | kwojc/Ruby-Implementations-Performance-Test | /app/classes/my_math.rb | UTF-8 | 216 | 3.671875 | 4 | [
"MIT"
] | permissive | class MyMath
def self.fibonacci(n)
return n if (0..1).include? n
(self.fibonacci(n - 1) + self.fibonacci(n - 2))
end
def self.factorial(n)
return 1 if n <= 1
n * self.factorial(n - 1)
end
end | true |
33004c2fa9a81a2aa2c26357a6fc3eed3f9baa0f | Ruby | caelum/patternie | /patternie.rb | UTF-8 | 2,707 | 3.21875 | 3 | [] | no_license | require 'hashie' # TODO use a simpler version instead of hashie
module Patternie
def fields(*fields)
@pattern = fields
fields.each do |f|
self.send :attr_accessor, f
end
end
def [](*args) # todo: change to ()
PatternieMatcher.new(args, @pattern, self)
end
end
class MatchBlock
def initialize(to_match)
@to_match = to_match
end
def caso(matcher, &block)
begin
extra = matcher =~ @to_match
extra.instance_eval(&block)
rescue
# todo should only ignore MatchError
end
end
end
class Object
include Patternie
def match(&lambda)
MatchBlock.new(self).instance_eval(&lambda)
end
end
class Option
end
class Some < Option
fields :value
def initialize(value)
@value = value
end
def is_defined?
true
end
def get
@value
end
end
class None < Option
def is_defined?
false
end
def get
raise "None has no value"
end
end
class PatternieMatcher
def initialize(left, fields, type)
if left.size != fields.size
raise "Cannot match due to partial matching (#{left} #{pattern})"
end
@left = left
@pattern = fields
@type = type
end
def =~(value)
if !value.kind_of? @type
raise "Cannot match a #{value} because it is not a #{@type}"
end
object = Hashie::Mash.new
(0..@pattern.size-1).each do |i|
field = "@#{@pattern[i].to_s}".to_sym
to_match = @left[i]
apply_to(to_match, object, value, field)
end
# puts "returning #{object}"
object
end
private
def apply_to(to_match, object, right, field)
return if to_match == :_
value = right.instance_variable_get field
if to_match.kind_of? Symbol
object[to_match] = value
elsif to_match.kind_of? Class
if !value.kind_of?(to_match)
raise "Cannot match #{value} to class type #{to_match}"
end
elsif to_match.kind_of?(PatternieMatcher)
extra = to_match =~ value
object.merge! extra
else
if value != to_match
raise "Cannot match #{value} to #{to_match}"
end
end
end
end
# nasttyyyyyy, make it optional?
class Object
def method_missing(name)
if(name.to_s[0]=='_')
type = eval(name.to_s[1..name.size-1])
MatcherWrapper.new(type, self)
else
super
end
end
end
# only required for 'simple matching'
class MatcherWrapper
def initialize(t, scope)
@type = t
@scope = scope
end
def [](*args)
@matcher = @type[*args]
self
end
def =~(value)
extra = @matcher =~ value
extra.each do |k, v|
@scope.define_singleton_method k.to_sym do
v # TODO something cuter, please
end
end
end
end
| true |
e37ba3f46ae5dddaa64dd0d7db3a7f061ca31d9d | Ruby | davidqhr/gezi_craft | /heros/david.rb | UTF-8 | 1,514 | 2.9375 | 3 | [] | no_license | # coding: utf-8
require 'set'
class David < Programmer
def initialize
@name = "David"
@skill_name = "又改需求啦?/恐吓"
@skill_description = "对方产品经理 3回合不能移动"
super
end
# def skill player
# opponent = player.opponent
# game = player.game
# pms = opponent.heros.select { |id, h| h.is_a? PM }
# pm = pms.sample
# if game.turn == 1
# game.events[game.round] ||= {}
# game.events[game.round][:cannot_move] ||= Set.new
# game.events[game.round][:cannot_move] << pm.id
# game.events[game.round+1] ||= {}
# game.events[game.round+1][:cannot_move] ||= Set.new
# game.events[game.round+1][:cannot_move] << pm.id
# game.events[game.round+2] ||= {}
# game.events[game.round+2][:cannot_move] ||= Set.new
# game.events[game.round+2][:cannot_move] << pm.id
# else
# game.events[game.round+1] ||= {}
# game.events[game.round+1][:cannot_move] ||= Set.new
# game.events[game.round+1][:cannot_move] << pm.id
# game.events[game.round+2] ||= {}
# game.events[game.round+2][:cannot_move] ||= Set.new
# game.events[game.round+2][:cannot_move] << pm.id
# game.events[game.round+3] ||= {}
# game.events[game.round+3][:cannot_move] ||= Set.new
# game.events[game.round+3][:cannot_move] << pm.id
# end
# "【david】咆哮到:竟然又改需求了!对方改需求的#{pm.name}吓破了胆,将3回合不能移动"
# end
record
end | true |
76c3ca3dce6ab9aff8a61b35e99ac3f02727d776 | Ruby | johnkim97/Restaurant | /app/models/review.rb | UTF-8 | 644 | 2.578125 | 3 | [] | no_license | class Review < ActiveRecord::Base
belongs_to :user
belongs_to :item
validates :user_id, :item_id, :presence => true
validate :user_can_only_review_once_per_item, :user_can_only_review_two_times
def user_can_only_review_once_per_item
matched_reviews = Review.where(:user_id => self.user_id, :item_id => self.item_id)
if matched_reviews.empty? == false
errors.add(:number_of_reviews, "is limited to one per movie per user")
end
end
def user_can_only_review_two_times
num_reviews = Review.where(:user_id => self.user_id)
if num_reviews.length >= 2
errors.add(:number_of_reviews, "cannot exceed past two")
end
end
end
| true |
3e4d9bacbd2faa8247100cedfba3cd159303ae2e | Ruby | Dhrubajyotic/athena_csv | /lib/athena_csv/output.rb | UTF-8 | 467 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'csv'
module AthenaCsv; class Output;
attr_reader :query, :file_path
def initialize(query, file_path)
@query = query
@file_path = file_path
end
def query_results
@query_result_rows ||= Client.new.run(query)
end
def values(row)
row.data.map {|cell| cell.var_char_value}
end
def generate_csv
CSV.open(file_path, "wb") do |csv|
query_results.each do |row|
csv << values(row)
end
end
end
end; end
| true |
b0b7174f87f6300a914e5b2b195419b444a6d8a8 | Ruby | DanWizard/ruby_dec_2018 | /first_vagrant_box/fundementals/basic123.rb | UTF-8 | 1,010 | 3.84375 | 4 | [] | no_license | def to255
1.upto(255) {|i| print i, " "}
end
def oddIn255
p (1..255).select {|a| a%2 != 0}
end
def countAndSum
sum = 0
a = 1.upto(255) do |i|
sum += i
p "count: #{i} sum: #{sum}", " "
end
end
def eachElement arr
arr.each {|e| print e, " "}
end
def maxElement arr
p arr.max
end
def avgElement arr
sum = 0
arr.each { |e| sum+=e }
p sum.to_f/arr.length.to_f
end
def greaterThan arr, y
sumOfGreater = 0
arr.each do |e|
if e > y
sumOfGreater+=1
end
end
p sumOfGreater
end
def squareValues arr
a = []
arr.each do |e|
e*=e
a<<e
end
p a
end
def removeNeg arr
arr.each_index do |e|
if arr[e] < 0
arr[e] = 0
end
end
p arr
end
def maxMinAndAverage arr
sum = 0
arr.each { |e| sum+=e }
p "max: #{arr.max} min: #{arr.min} average: #{sum.to_f/arr.length.to_f}"
end
def shiftToFront arr
arr[arr.length] = 0
arr.delete_at(0)
p arr
end
def changeNeg arr
arr.each_index do |e|
if arr[e] < 0
arr[e] = "dojo"
end
end
p arr
end
changeNeg [-1,-2,1,1,1] | true |
922d4b16377e3832230d33d8e9f6d8a1633a7cc0 | Ruby | heedwiner1106/baitapRuby | /Array/bai2.rb | UTF-8 | 277 | 3.3125 | 3 | [] | no_license | def sumInput
interger = true
arr = []
while(interger)
input = gets.chomp
if (input == "0" || input.to_i != 0)
arr.push(input.to_i)
else
interger = false
end
end
p sum = arr.sum
end
p "Sum: #{sumInput}" | true |
beffd99ffcff666a03770e80e05fb7ae3248fec6 | Ruby | mgarriss/scrapes | /lib/scrapes/crawler.rb | UTF-8 | 3,794 | 2.59375 | 3 | [
"MIT"
] | permissive | ################################################################################
#
# Copyright (C) 2006 Peter J Jones (pjones@pmade.com)
# Copyright (C) 2010 Michael D Garriss (mgarriss@gmail.com)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################
require 'net/http'
require 'pathname'
require 'scrapes/cache'
################################################################################
module Scrapes
################################################################################
# Try to suck down a URI
class Crawler
################################################################################
# The cache object that this crawler is using
attr_accessor :cache
################################################################################
# The optional log object that this crawler is using
attr_accessor :log
################################################################################
# Create a new crawler for the given session
def initialize (session)
@session = session
@log = nil
@verbose = 0
@delay = 0.5
@cache = Cache.new
end
################################################################################
# Fetch a URI, using HTTP GET unless you supply <tt>post</tt>.
def fetch (uri, post={}, headers={})
@session.refresh
uri = URI.parse(@session.absolute_uri(uri))
post.empty? and cached = @cache.check(uri)
@log.info((cached ? 'C ' : 'N ') + uri.to_s) if @log
return cached if cached # FIXME
sleep(@delay) if @delay != 0
path = uri.path.dup
path << "/" if path.empty?
path << "?" + uri.query if uri.query
req = post.empty? ? Net::HTTP::Get.new(path) : Net::HTTP::Post.new(path)
req.set_form_data(post) unless post.empty?
req['Cookie'] = @session.cookies.to_header
headers.each {|k,v| req[k] = v}
res = Net::HTTP.new(uri.host, uri.port).start {|http| http.request(req)}
if @verbose >= 2
STDERR.puts "-----------------------------------------------"
STDERR.puts res.class
res.each_header {|k,v| STDERR.puts "#{k}: #{v}"}
end
# FIXME, what to do about more than one cookie
@session.cookies.from_header(res['set-cookie']) if res.key?('set-cookie')
case res
when Net::HTTPRedirection
@session.base_uris[-1] = @session.absolute_uri(res['location'])
res = fetch(res['location'], {}, headers)
end
post.empty? and @cache.update(uri, res.body)
res
end
end
################################################################################
end
################################################################################
| true |
eb40a1a82f43f49f251ffe22624f5d35aca02b1d | Ruby | Meowcenary/Codewars | /iterative_fibonacci_sum.rb | UTF-8 | 271 | 3.28125 | 3 | [] | no_license | def perimeter(n)
4*fib(n+1, {}).values.sum
end
# iteratation avoids recursion which stops the stack from blowing up
def fib(end_key, sequence)
(0..end_key).each do |i|
i < 2 ? sequence[i] = i : (sequence[i] = sequence[i-1] + sequence[i-2])
end
sequence
end
| true |
aab70ddfb3475c4dd9505adebd760464d5e6f595 | Ruby | baloi/morpheus | /app.rb | UTF-8 | 563 | 2.671875 | 3 | [] | no_license | require 'sinatra'
require './model'
get '/' do
"hello world"
end
get '/therapists' do
#therapists = Therapist.find(:all)
#ret = ""
#therapists.each do |t|
# ret += "Welcome #{t.name}<br/>"
#end
#
#ret
end
#post '/therapist' do
# name = "#{params[:therapist_name].strip}"
#
# @therapist = Therapist.new(:name => name)
# @errors = []
#
# if @therapist.save
# redirect '/therapist/list'
# else
# @therapist.errors.each do |e|
# @errors << e
# puts ">>>#{e}<<<"
# end
#
# redirect '/therapist/error'
# end
#end
#
| true |
38a227330b13f14703d8f8f6dcf566b7d4a8c01e | Ruby | phamtoanthang/ruby | /openfile.rb | UTF-8 | 107 | 2.65625 | 3 | [] | no_license | filename = ARGV.first
txt = open(filename)
puts "you just open a file named #{filename}"
puts txt.read | true |
1830a33dd2a315f89ba72637abc2da2a6cfa0dd2 | Ruby | sandagolcea/makers-reboot | /w1-airport/spec/airport_spec.rb | UTF-8 | 906 | 3.015625 | 3 | [] | no_license | require 'airport'
MAX_CAPACITY = 20
class Planes; def land; end; end
describe Airport do
let(:airport) { Airport.new(MAX_CAPACITY) }
let(:plane) { double(:plane) }
before(:each) do
allow(airport).to receive(:good_weather?).and_return(true)
end
it 'should have no planes to begin with' do
expect(airport.plane_count).to eq 0
end
it 'should be able to dock a plane' do
airport.dock(plane)
expect(airport.plane_count).to eq 1
end
it 'should raise an error if it is full and can\'t dock a plane' do
MAX_CAPACITY.times { airport.dock(Planes.new) }
expect(airport.dock(plane)).to eq false
end
it 'can\'t dock the same plane twice' do
airport.dock(plane)
airport.dock(plane)
expect(airport.plane_count).to eq 1
end
it 'can release a plane' do
airport.dock(plane)
airport.release(plane)
expect(airport.plane_count).to eq 0
end
end
| true |
52ce1b59e4afbb558c0c1d39aee06de3cd8680a3 | Ruby | sebrose/mutation-web-service | /client-ruby/lib/checkout/cli.rb | UTF-8 | 2,102 | 2.65625 | 3 | [] | no_license | module Checkout
# CLI client
class CLI
include Concord.new(:client, :arguments)
ACTIONS = %w(requirements score register advance)
# Run cli
#
# @return [self]
#
# @api private
#
def run
unless arguments.length == 1
usage_error
end
argument = arguments.first
if ACTIONS.include?(argument)
send(argument)
else
usage_error
end
self
end
private
# Raise error with specific message
#
# @param [String] message
#
# @raise [Error]
#
# @return [undefined]
#
# @api private
#
def error(message)
raise Error, message
end
# Advance team
#
# @return [undefined]
#
# @api private
#
def advance
batch = client.basket_batch
result = Calculator.new(client, batch).result
client.submit_batch(result)
end
# Print current score
#
# @return [undefined]
#
# @api private
#
def score
puts client.current_score.fetch('score')
end
# Print current requirements
#
# @return [undefined]
#
# @api private
#
def requirements
puts client.current_requirements.fetch('requirements')
end
# Perform registration
#
# @return [undefined]
#
# @api private
#
def register
client.register
end
# Raise usage error
#
# @raise [Error]
#
# @return [undefined]
#
# @api private
#
def usage_error
error("Usage: #{$0} [#{ACTIONS.join('|')}]")
end
EXIT_FAILURE = 1
EXIT_SUCCESS = 0
# Call command line interface
#
# @param [Array<String>] arguments
#
# @return [Fixnum]
# the exit status
#
# @api private
#
def self.run(arguments)
client = Client.from_config_file(Pathname.new(__FILE__).parent.parent.parent.join('config.yml'))
new(client, arguments).run
EXIT_SUCCESS
rescue Error => exception
$stderr.puts(exception.message)
EXIT_FAILURE
end
end # CLI
end # Checkout
| true |
65b06136cec2d6d23082bbebc0c7c8b8afb482eb | Ruby | ayjlee/grocery-store | /specs/customer_spec.rb | UTF-8 | 2,791 | 2.8125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/reporters'
require 'minitest/skip_dsl'
require_relative '../lib/customer'
describe "Customer" do
describe "#initialize" do
it "Takes an ID, email and address info" do
id = 5
email = "testemail.com"
address = "Drury Lane"
customer = Grocery::Customer.new(id,email,address)
customer.must_respond_to :id
customer.id.must_equal id
customer.id.must_be_kind_of Integer
customer.must_respond_to :email
customer.email.must_be_kind_of String
customer.email.must_equal email
customer.must_respond_to :address
customer.address.must_be_kind_of String
customer.address.must_equal address
end
end
describe "Customer.all" do
it "Returns an array of all customers" do
Grocery::Customer.all.must_be_instance_of Array
Grocery::Customer.all.each do |customer|
customer.must_be_instance_of Grocery::Customer
end
end
it "Can be called" do
Grocery::Customer.must_respond_to :all
end
it "Includes all customers in the csv file" do
Grocery::Customer.all.count.must_equal CSV.read("support/customers.csv", "r").count
end
it "Creates a customer object with ID and email address that matches the information of the first customer in the csv" do
first_customer = Grocery::Customer.all[0]
csv_first_customer = CSV.read("support/customers.csv", "r")[0]
first_customer.id.must_equal csv_first_customer[0].to_i
first_customer.email.must_equal csv_first_customer[1]
end
it "Creates a customer object with ID and email address that matches the information of the last customer in the csv" do
last_customer = Grocery::Customer.all[-1]
csv_last_customer = CSV.read("support/customers.csv", "r")[-1]
last_customer.id.must_equal csv_last_customer[0].to_i
last_customer.email.must_equal csv_last_customer[1]
end
end
describe "Customer.find" do
it "Can find the first customer from the CSV" do
customer1 = CSV.read("support/customers.csv", "r")[0]
Grocery::Customer.find(1).must_be_instance_of Grocery::Customer
Grocery::Customer.find(1).id.must_equal customer1[0].to_i
Grocery::Customer.find(1).email.must_equal customer1[1]
end
it "Can find the last customer from the CSV" do
lastcustomer = CSV.read("support/customers.csv", "r")[-1]
Grocery::Customer.find(35).must_be_instance_of Grocery::Customer
Grocery::Customer.find(35).id.must_equal lastcustomer[0].to_i
Grocery::Customer.find(35).email.must_equal lastcustomer[1]
end
it "Raises an error for a customer that doesn't exist" do
proc { Grocery::Customer.find(800) }.must_raise ArgumentError
end
end
end
| true |
8e87b7d3bec62df9e3990f978939f7c76aedf63f | Ruby | wheeskers/gp_edu_experiments | /generate_test_data.rb | UTF-8 | 689 | 2.9375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/ruby
require 'time'
data_files = [ 'some_data0.csv',
'some_data1.csv',
'some_data2.csv',
'some_data3.csv',
'some_data4.csv' ]
time_stamp = Time::new
time_stamp_start = Time::parse("2016-10-20 08:15:30")
time_stamp_stop = Time::parse("2016-10-20 16:45:00")
data_files.each do |out_file|
time_stamp = time_stamp_start
some_value = rand(-100..100)
File::open("./#{out_file}",'w+') do |f|
while time_stamp <= time_stamp_stop
f.write "#{time_stamp.strftime('%Y-%m-%d %H:%M:%S')};#{some_value}\n"
some_value += rand(50)
some_value -= rand(50)
time_stamp += 60
end
end
end
| true |
6fe356db786f9ea8d1a2e2f7ce8e2b8eba8bf28c | Ruby | jgnagy/rffdb | /lib/rffdb/index.rb | UTF-8 | 2,089 | 2.5625 | 3 | [
"MIT"
] | permissive | module RubyFFDB
class Index
def initialize(type, column)
@type = type
@column = column
FileUtils.mkdir_p(File.dirname(file_path))
GDBM.open(file_path, 0664, GDBM::WRCREAT) do
# Index initialized
end
end
def file_path
File.join(
DB_DATA,
@type.to_s.gsub('::', '__'),
'indexes',
@column.to_s + '.index'
)
end
def get(key)
GDBM.open(file_path, 0664, GDBM::READER) do |index|
Marshal.load index.fetch(key.to_s, Marshal.dump([]))
end
end
def put(key, value)
previous = get(key)
GDBM.open(file_path, 0664, GDBM::WRCREAT) do |index|
index[key.to_s] = Marshal.dump((previous + [value]).uniq)
end
end
# Remove a specific Document association with a key
def delete(key, value)
previous = get(key)
GDBM.open(file_path, 0664, GDBM::WRCREAT) do |index|
index[key.to_s] = Marshal.dump((previous - [value]).uniq)
end
end
# Remove all associations with a specific key (column data)
def truncate(key)
GDBM.open(file_path, 0664, GDBM::WRCREAT) do |index|
index.delete(key.to_s)
end
end
# All keys (column data) in the index
# @return [Array] An array of object ids
def keys
GDBM.open(file_path, 0664, GDBM::READER) do |index|
index.keys
end
end
# Complex queries of the index can be done with this method
# @return [Array] An array of object ids matching the query
def query(q, operator = '==')
datum = []
GDBM.open(file_path, 0664, GDBM::READER) do |index|
index.each_pair do |key, value|
datum += Marshal.load(value) if key.send(operator.to_sym, q)
end
end
datum.uniq.compact
end
# Evict keys (column data) with no associated Documents
def prune
GDBM.open(file_path, 0664, GDBM::WRCREAT) do |index|
index.delete_if { |key, value| Marshal.load(value).empty? }
index.reorganize # clear up wasted disk space
end
end
end
end
| true |
a206e66e7e9049df7450d941a849f7b80985d136 | Ruby | toshimaru/Study | /10-problems/7.rb | UTF-8 | 1,493 | 3.515625 | 4 | [] | no_license | # frozen_string_literal: true
def slow_gas_station(gas, cost)
traversed_i = gas.size.times.find { |i| can_traverse?(gas, cost, i) }
traversed_i || -1
end
def my_gas_station(gas, cost)
return - 1 if cost.sum > gas.sum
i, n = 0, gas.size
while i <= n
remaining = 0
gas.size.times.with_index(1) do |j, idx|
j = (i + j) % n
remaining += gas[j] - cost[j]
if remaining < 0
i = j
break
elsif idx == n
return i
end
end
i += 1
end
-1
end
def gas_station(gas, cost)
remaining = prev_remaining = candidate = 0
n = gas.size
n.times do |i|
remaining += gas[i] - cost[i]
if remaining < 0
candidate = i + 1
prev_remaining += remaining
remaining = 0
end
end
return -1 if candidate == n || remaining + prev_remaining < 0
candidate
end
def can_traverse?(gas, cost, start)
n, i, remaining = gas.size, start, 0
started = false
while i != start || !started
started = true
remaining += gas[i] - cost[i]
return false if remaining < 0
i = (i + 1) % n
end
true
end
gas = [1,5,3,3,5,3,1,3,4,5]
cost = [5,2,2,8,2,4,2,5,1,2]
p slow_gas_station(gas, cost)
p my_gas_station(gas, cost)
p gas_station(gas, cost)
gas = [2,2,2,2,2,2]
cost = [1,1,1,1,1,50]
p slow_gas_station(gas, cost)
p my_gas_station(gas, cost)
p gas_station(gas, cost)
gas = [1,1,1,10]
cost = [2,2,2,2]
p slow_gas_station(gas, cost)
p my_gas_station(gas, cost)
p gas_station(gas, cost)
| true |
dbbf47c9225e3c1dd81fa2db91ade364a77226be | Ruby | nassersala/binary-clock | /binary_clock.rb | UTF-8 | 2,510 | 3.625 | 4 | [] | no_license | class Clock
def convert_time(time)
time_strings = [time.hour, time.min, time.sec].map(&:to_s)
######
#time_strings = ["10", "1", "59"]
#####
prepended_zero = prepend_zero_for(time_strings)
whole_time = ''
prepended_zero.each do |time_part| #h m s
whole_time << convert_first_digit(time_part)
whole_time << convert_second_digit(time_part)
end
whole_time
end
def prepend_zero_for(time_strings)
prepended_zero = []
time_strings.each do |number|
if number.to_i < 10
prepended_zero << '0' + number
else
prepended_zero << number
end
end
prepended_zero
end
def convert_first_digit(time_part)
convert(time_part[0].to_i)
end
def convert_second_digit(time_part)
convert(time_part[1].to_i)
end
CONVERSIONS = [
[9, '1001'],
[8, '1000'],
[7, '0111'],
[6, '0110'],
[5, '0101'],
[4, '0100'],
[3, '0011'],
[2, '0010'],
[1, '0001'],
[0, '0000']
]
def conversion_factors_for(number)
CONVERSIONS.find { |base_ten, _| base_ten <= number }
end
def convert(number)
real, binary = conversion_factors_for(number)
binary
end
end
class BinaryClockDrawer
def initialize(clock)
@clock = clock
end
def draw_time
loop do
time_in_binary = @clock.convert_time(Time.now)
tm_array = time_in_binary.scan(/..../)
# tm_array.each do |time_part|
# time_part.scan(/./).each_with_index do |digit, index|
# puts time_part
# end
# end
hour_coulmn1 = tm_array[0]
hour_coulmn2 = tm_array[1]
minute_coulmn1 = tm_array[2]
minute_coulmn2 = tm_array[3]
seconds_coulmn1 = tm_array[4]
seconds_coulmn2 = tm_array[5]
puts hour_coulmn1[0] + " " + hour_coulmn2[0] + " " + minute_coulmn1[0] + " " + minute_coulmn2[0] + " " + seconds_coulmn1[0] + " " + seconds_coulmn2[0]
puts hour_coulmn1[1] + " " + hour_coulmn2[1] + " " + minute_coulmn1[1] + " " + minute_coulmn2[1] + " " + seconds_coulmn1[1] + " " + seconds_coulmn2[1]
puts hour_coulmn1[2] + " " + hour_coulmn2[2] + " " + minute_coulmn1[2] + " " + minute_coulmn2[2] + " " + seconds_coulmn1[2] + " " + seconds_coulmn2[2]
puts hour_coulmn1[3] + " " + hour_coulmn2[3] + " " + minute_coulmn1[3] + " " + minute_coulmn2[3] + " " + seconds_coulmn1[3] + " " + seconds_coulmn2[3]
sleep(1)
system "clear"
end
end
end
BinaryClockDrawer.new(Clock.new).draw_time
| true |
44f5cacd83687d8258a806a310c7c2d7f67c659c | Ruby | BranLiang/project_cli_blackjack | /lib/player.rb | UTF-8 | 120 | 2.609375 | 3 | [] | no_license | class Player < Human
attr_accessor :bank, :bet
def initialize
super
@bank = 2000
@bet = 100
end
end
| true |
cb8e887a9d6d7ba9e1009a4157c543fe423923c5 | Ruby | darren9897/programming-univbasics-4-array-simple-array-manipulations-part-1-nyc04-seng-ft-041920 | /lib/intro_to_simple_array_manipulations.rb | UTF-8 | 378 | 3.578125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def using_push(array, string)
array.push(string)
end
def using_unshift(array, string)
array.unshift(string)
end
def using_pop(array)
woah = array.pop
return woah
end
def pop_with_args(array)
yup = array.pop(2)
return yup
end
def using_shift(array)
love = array.shift
return love
end
def shift_with_args(array)
hate = array.shift(2)
return hate
end
| true |
335dfcb2f24797bce3d3acdd097fac8927889fc0 | Ruby | caioandrademota/Misc_Codes | /rubyzão/desafio4.rb | UTF-8 | 1,502 | 4.03125 | 4 | [] | no_license | result = ' '
loop do
puts result
puts "---CALCULADORA---"
puts 'selecione a opção desejada: '
puts '1 - Adição.'
puts '2 - Subtração.'
puts '3 - Multiplicação.'
puts '4 - Divisão.'
puts '0 - Sair do programa.'
puts 'Opção: '
option = gets.chomp.to_i
if option == 1
puts "Digite dois valores: "
value_1 = gets.chomp.to_f
value_2 = gets.chomp.to_f
x = value_1 + value_2
result = "o resultado da soma entre #{value_1} e #{value_2} é de #{x}."
elsif option == 2
puts "Digite dois valores: "
value_1 = gets.chomp.to_f
value_2 = gets.chomp.to_f
x = value_1 - value_2
result = "o resultado da subtração entre #{value_1} e #{value_2} é de #{x}."
elsif option == 3
puts "Digite dois valores: "
value_1 = gets.chomp.to_f
value_2 = gets.chomp.to_f
x = value_1 * value_2
result = "o resultado da multiplicação entre #{value_1} e #{value_2} é de #{x}."
elsif option == 4
puts "Digite dois valores: "
value_1 = gets.chomp.to_f
value_2 = gets.chomp.to_f
x = value_1 / value_2
resto = value_1 % value_2
result = "o quociente da divisão entre #{value_1} e #{value_2} é de #{x}. O resto é #{resto}."
elsif option == 0
puts "O programa será parado."
break
else
puts "Opção Inválida! Tente novamente."
end
system "clear"
end | true |
c42390c7476665186a55d937e281fceba1e7e3f5 | Ruby | ufeanei/challenges | /robotsim.rb | UTF-8 | 2,197 | 4.15625 | 4 | [] | no_license | require 'pry'
class Robot
attr_accessor :xcor, :ycor, :orientation
def at(x,y)
@xcor = x
@ycor = y
end
def orient(direction)
if [:north, :east, :west, :south].include?(direction.to_sym)
@orientation = direction.to_sym
else
raise "Drection must be east, west, south, north"
end
end
def bearing
orientation
end
def coordinates
[xcor, ycor]
end
def turn_right
self.orientation = :north if bearing == :west
self.orientation = :east if bearing == :north
self.orientation = :south if bearing == :east
self.orientation = :west if bearing == :south
end
def turn_left
self.orientation = :north if bearing == :east
self.orientation = :east if bearing == :south
self.orientation = :south if bearing == :west
self.orientation = :west if bearing == :north
end
def advance
self.xcor += 1 if bearing == :east
self.xcor -= 1 if bearing == :west
self.ycor += 1 if bearing == :north
self.ycor -= 1 if bearing == :south
end
end
class Simulator
def place(rob, x, y, direction )
rob.at(x,y)
rob.orient(direction)
end
def wrong_command_message(let)
puts "#{let.upcase} is not a valid robot command" if !['L', 'A', 'R'].include?(let.upcase)
end
def evaluate(rob, instruct)
inst = instruct.upcase.split(//)
inst.each do |letter|
wrong_command_message(letter) # robot throws an error for invalid commands and execute valid commands
rob.turn_left if letter == 'L'
rob.turn_right if letter == 'R'
rob.advance if letter == 'A'
end
end
def instruction(input)
commands = []
n = input.size
for i in 0...n
commands << :turn_right if input[i].upcase == 'R'
commands << :turn_letf if input[i].upcase == 'L'
commands << :advance if input[i].upcase == 'A'
wrong_command_message(input[i])
end
commands
end
end
robot1 = Robot.new
simulator = Simulator.new
simulator.place(robot1, 0, 0, 'west')
puts " enter your robot instruction"
answer = gets.chomp
puts "#{simulator.instruction(answer)}"
simulator.evaluate(robot1, answer)
puts "#{robot1.bearing}"
puts "#{robot1.coordinates}"
| true |
1d6cb4d179d61d61b869abb2e9aba4dced4f56f5 | Ruby | cyclingzealot/vovi | /lpPerBeds.rb | UTF-8 | 1,247 | 2.890625 | 3 | [
"Unlicense"
] | permissive | #!/usr/bin/ruby
require 'nokogiri'
require 'open-uri'
require 'uri'
require 'byebug'
require 'set'
#require 'getoptlong'
dataPath=ARGV[0]
doc = Nokogiri::HTML(open(dataPath))
tbodies = doc.xpath("//tr")
puts tbodies.count
listings = {}
tbodies.each { |tbodyNode|
tdNodes = tbodyNode.xpath("./td")
dataColumnIndex = {
'address' => 10,
'lp' => 11,
'beds' => 16,
'status' => 8
}
if tdNodes.count >= 16+1
status = tdNodes[dataColumnIndex['status']].text
if not ['Sold', 'Conditional'].include?(status)
lpStr = tdNodes[dataColumnIndex['lp']]
bedsStr = tdNodes[dataColumnIndex['beds']]
address = tdNodes[dataColumnIndex['address']]
if (not lpStr.nil? and not lpStr.text.empty?) and (not bedsStr.nil? and not bedsStr.text.empty?) then
beds = bedsStr.text.to_i
lp = lpStr.text.gsub(/\D/, '').to_i/100
address = address.text
#debugger
listings[address] = (lp/beds).round if beds > 0
end
end
end
}
listings.sort_by {|_key, value| value}.reverse.each {|address, lpPerBeds| puts "#{address} #{lpPerBeds}"}
| true |
ce4fcc0f7df835f36ba64a7f4e3feb333116470f | Ruby | MadBomber/experiments | /system_v_ipc_shm/worker.rb | UTF-8 | 2,150 | 3.15625 | 3 | [] | no_license | require 'SysVIPC'
require 'debug_me'
include DebugMe
# All IPC objects are identified by a key. SysVIPC includes a
# convenience function for mapping file names and integer IDs into a
# key:
key = SysVIPC.ftok(ARGV.shift, 0)
# Get (create if necessary) a message queue:
mq = SysVIPC::MessageQueue.new(key, SysVIPC::IPC_CREAT | 0600)
# Get (create if necessary) an 8192-byte shared memory region:
sh = SysVIPC::SharedMemory.new(key, 8192, SysVIPC::IPC_CREAT | 0660)
#
# Attach shared memory:
shmaddr = sh.attach
debug_me(tag: "worker:#{Process.pid}", header: false){[ :key, :mq, :sh, :shmaddr ]}
# Receive up to 100 bytes from the first message of type 0:
# NOTE: this will block until it has collected all of the message or
# until 100 characters have been received. I don't know what
# tyoe == 0 does because it was type == 1 that was sent.
msg = mq.receive(0, 100)
debug_me(tag: "worker:#{Process.pid}", header: false){[ :msg ]}
until false
rand(100_000)
end
=begin
my_pid = Process.pid.to_s
# NOTE: Lets monitor some shared memory.
# The shared memory block is in a static location; but,
# Ruby doesn't care about memory addresses. THe GC can move
# objects around all over the memory map. This makes it much
# harder in Ruby over a traditional 'C' approach using offsets
# from an anchored position. Wish there werw a way to
# anchor a Ruby object to a specific address and make it
# immune from GC. Why would anyone want to do this? Now-a-days
# all the stuff for which we once had to access bare metal are
# covered by SDK's API's and such. Accessing memory is not
# a "modern" requirement ... until its needed ... after all who
# in their right mind would ever write a device driver in Ruby?
# I mean besides me.
msg = []
until msg.first == my_pid && msg.last == 'quit'
data = shmaddr.read(my_pid.size + ',quit'.size)
debug_me(tag: "worker:#{Process.pid}", header: false){[ :data ]}
msg = data.split(',')
end
shmaddr.write('okay')
# Detach shared memory:
sh.detach(shmaddr)
debug_me(tag: "worker:#{Process.pid} ending")
=end
| true |
af1d347fd45db2fc4bc327bcdb18f10fe0df92d8 | Ruby | dapi/courier-notifier | /lib/courier/template/base.rb | UTF-8 | 1,143 | 2.671875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
class Courier::Template::Base
AvailableValues = [:on, :off, :disabled]
attr_accessor :name, :defaults
def initialize(args)
self.name = args[:name].to_sym or raise 'no template name defined'
self.defaults={}
end
def get_text(service, args)
args[:scope]=[:courier, :services, service.to_s, :templates] unless args[:scope]
args[:cascade]=true unless args.has_key? :cascade
I18n::translate(name, args )
end
def get(service)
service = Courier.service(service) if service.is_a?(Symbol)
name = service.name.to_sym
raise "Not defined default value for #{service} in template #{self}" unless defaults.has_key? name
defaults[name]
end
def set(service, val)
service = Courier.service(service) if service.is_a?(Symbol)
defaults[service.name.to_sym] = check_val(val)
end
def to_s
name.to_s
end
def to_label
I18n::translate(name, :scope=>[:courier,:templates] )
end
def key
name
end
private
def check_val(val)
raise "Value must be one of #{AvailableValues.join(', ')}" unless AvailableValues.include? val
val
end
end
| true |
0d7d04237eeeaefbe03e15b1d089c48290f11dbf | Ruby | lovecosma/my_all-onl01-seng-ft-052620 | /lib/my_all.rb | UTF-8 | 282 | 3.21875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def my_all?(collection)
if collection.length > 0
i = 0
new_collection = []
while i < collection.length
new_collection << yield(collection[i])
i+=1
end
if new_collection.include?(false)
return false
else
return true
end
else
puts "nothing in array"
end
end
| true |
70de2817b56ae904cec0637f59268ce3d7e1446c | Ruby | cenit-io/cenit | /lib/cenit/liquidfier.rb | UTF-8 | 897 | 2.625 | 3 | [
"MIT"
] | permissive | require 'liquid/drop'
module Cenit
module Liquidfier
def to_liquid
@cenit_liquid_drop ||= Cenit::Liquidfier::Drop.new(self)
end
class Drop < Liquid::Drop
def initialize(object)
@object = object
end
def invoke_drop(method_or_key)
if Capataz.instance_response_to?(@object, method_or_key)
@object.send(method_or_key)
else
before_method(method_or_key)
end
end
def [](method_or_key)
invoke_drop(method_or_key)
end
def respond_to?(*args)
((args[0] == :each) && Capataz.instance_response_to?(@object, :each)) || super
end
def method_missing(symbol, *args, &block)
if symbol == :each && Capataz.instance_response_to?(@object, :each)
@object.send(symbol, *args, &block)
else
super
end
end
end
end
end | true |
dad5a097bf38e4c9adacdba167679b60b33d74ab | Ruby | hfaulds/adventofcode2020 | /day-17b.rb | UTF-8 | 1,366 | 3.578125 | 4 | [] | no_license | require 'pry'
string = "...#..#.
#..#...#
.....###
##....##
......##
........
.#......
##...#.."
state = string.split("\n").map(&:strip).map(&:chars).reverse.each_with_index.reduce({}) do |h, (row, y)|
row.each_with_index do |cell, x|
h[[x,y,0,0]] = true if cell == "#"
end
h
end
def nearby_count(state,x,y,z,w)
(-1..1).sum do |dx|
(-1..1).sum do |dy|
(-1..1).sum do |dz|
(-1..1).count do |dw|
unless dx == 0 && dy == 0 && dz == 0 && dw == 0
state[[x+dx,y+dy,z+dz,w+dw]]
end
end
end
end
end
end
def next_state(state)
xs = state.keys.map { |x| x[0] }
ys = state.keys.map { |y| y[1] }
zs = state.keys.map { |z| z[2] }
ws = state.keys.map { |w| w[3] }
new_state = {}
(xs.min-1..xs.max+1).each do |x|
(ys.min-1..ys.max+1).each do |y|
(zs.min-1..zs.max+1).each do |z|
(ws.min-1..ws.max+1).each do |w|
active_neighbours = nearby_count(state,x,y,z,w)
if state[[x,y,z,w]]
if active_neighbours == 2 || active_neighbours == 3
new_state[[x,y,z,w]] = true
end
else
if active_neighbours == 3
new_state[[x,y,z,w]] = true
end
end
end
end
end
end
new_state
end
6.times do |i|
state = next_state(state)
end
p state.keys.size
| true |
f9a9756696bd2420d1d218709ab941b7391395ad | Ruby | Zirak/YuelaBot | /commands/source_command.rb | UTF-8 | 1,044 | 2.71875 | 3 | [] | no_license | module Commands
class SourceCommand
class << self
def name
:source
end
def attributes
{
max_args: 1,
min_args: 1,
description: "Show the source for a command",
usage: "source <command>"
}
end
def command(e, *args)
return if e.from_bot?
command_str = args.first.to_sym
command = Commands.constants.find do |c|
command = Commands.const_get(c)
command.is_a?(Class) && [command.name, *command.attributes[:aliases]].include?(command_str)
end
if command
command_class = Commands.const_get(command)
location = command_class.method(:name).source_location.first
result = "```ruby\n"
result << File.read(location).gsub('```') { "```" } # The replacement here has zero-width spaces between the tildes
result << "\n```"
result
else
"No command found for #{command_str}"
end
end
end
end
end | true |
855ef91f9985bd483cfeb121e6a386ce5b8afe21 | Ruby | doridoridoriand/twitter-F-3 | /helper/validator.rb | UTF-8 | 382 | 2.9375 | 3 | [] | no_license | module Validator
# @param contents
# @return boolean
def less_than_140?
unless self.length.to_i <= 140
false
else
true
end
end
def has_problems?
false
end
def only_character
match = Regexp.new(ALPHABET_INTEGER_MATCHER)
result = match =~ self
if result === 0
true
elsif result == nil
false
end
end
end
| true |
d22b254f9f421915be5f12a3df9da140384977d5 | Ruby | ewintram/learn-to-program | /chap-10/ex5.rb | UTF-8 | 1,800 | 4.28125 | 4 | [] | no_license | # Ninety-nine bottles of beer
def english_number(number)
numString = ""
onesPlace = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teenagers = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tensPlace = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
if number == 0
return "zero"
end
right = number
left = right/1000
right = right - left*1000
if left > 0
thousands = english_number(left)
numString = numString + thousands + " thousand"
if right > 0
numString = numString + ", "
end
end
left = right/100
right = right - left*100
if left > 0
hundreds = english_number(left)
numString = numString + hundreds + " hundred"
if right > 0
numString = numString + " and "
end
end
left = right/10
right = right - left*10
if left > 0
if ((left == 1) and (right > 0))
numString = numString + teenagers[right-1]
right = 0
else
numString = numString + tensPlace[left-1]
end
if right > 0
numString = numString + "-"
end
end
left = right
right = 0
if left > 0
numString = numString + onesPlace[left-1]
end
numString
end
bottles_i = 895
while bottles_i > 1
bottles = english_number(bottles_i)
puts "#{bottles.capitalize} bottles of beer on the wall,"
puts "#{bottles.capitalize} bottles of beer."
bottles = english_number(bottles_i -= 1)
puts "Take one down, pass it around,"
if bottles_i == 1
puts "One bottle of beer on the wall."
else
puts "#{bottles.capitalize} bottles of beer on the wall."
end
if bottles_i == 1
puts "One bottle of beer on the wall,"
puts "One bottle of beer."
puts "Take one down, pass it around,"
puts "No more bottles of beer on the wall."
end
end
| true |
6ea39248e950a841c8f85fd378b4ecbba8f1cf69 | Ruby | wwood/finishm | /lib/assembly/coverage_based_graph_filter.rb | UTF-8 | 2,594 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'set'
module Bio::AssemblyGraphAlgorithms
class CoverageBasedGraphFilter
include Bio::FinishM::Logging
# Remove all nodes from the graph that do not have sufficient coverage
# (i.e. possibly are sequencing error artefacts)
#
# Options:
# :whitelisted_sequences: provide an enumerable of sequence IDs, don't remove any nodes that have reads tracked to any of these IDs
#
# Returns nodes_removed, arcs_removed (as objects, in particular order)
def remove_low_coverage_nodes(graph, threshold, options = {})
graph.delete_nodes_if do |node|
deleting = false
if node.coverage and (node.coverage < threshold)
deleting = true
end
if deleting and options[:whitelisted_sequences] and !node.short_reads.nil?
options[:whitelisted_sequences].each do |seq_id|
if node.short_reads.collect{|r| r.read_id}.include?(seq_id)
deleting = false
log.debug "Preserving low coverage but whitelisted node: #{node.node_id}" if log.debug?
end
end
end
deleting
end
end
end
class ConnectivityBasedGraphFilter
include Bio::FinishM::Logging
# Remove parts of the graph that are unconnected to any whitelisted nodes
#
# options:
# :leash_length: don't explore more than this length away from each of the whitelisted_nodes. Defualt nil, no bounds
def remove_unconnected_nodes(graph, whitelisted_nodes, options={})
# Copy the whitelist
all_whitelisted_nodes = Set.new whitelisted_nodes
dij = Bio::AssemblyGraphAlgorithms::Dijkstra.new
dij_options = {:ignore_directions => true}
dij_options[:leash_length] = options[:leash_length]
# Depth-first search of all the connected parts looking for nodes to keep
whitelisted_nodes.each do |originally_whitelisted_node|
onode = Bio::Velvet::Graph::OrientedNodeTrail::OrientedNode.new
onode.node = originally_whitelisted_node
onode.first_side = Bio::Velvet::Graph::OrientedNodeTrail::START_IS_FIRST #irrelevant which is first because :ignore_directions => true
log.debug "Testing for connectivity from #{onode.node.node_id}" if log.debug?
min_distances = dij.min_distances(graph, onode, dij_options)
min_distances.each do |key, distance|
all_whitelisted_nodes << graph.nodes[key[0]]
end
end
# Delete all nodes that aren't in the
graph.delete_nodes_if do |node|
!all_whitelisted_nodes.include?(node)
end
end
end
end
| true |
ff9bce44cf11c8c7ae6771bedb1a1cf34a0c362f | Ruby | digideskio/infoboxer | /lib/infoboxer/parser/inline.rb | UTF-8 | 4,699 | 2.734375 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
module Infoboxer
class Parser
module Inline
include Tree
def inline(until_pattern = nil)
start = @context.lineno
nodes = Nodes[]
guarded_loop do
chunk = @context.scan_until(re.inline_until_cache[until_pattern])
nodes << chunk
break if @context.matched_inline?(until_pattern)
nodes << inline_formatting(@context.matched) unless @context.matched.empty?
if @context.eof?
break unless until_pattern
@context.fail!("#{until_pattern} not found, starting from #{start}")
end
if @context.eol?
nodes << "\n"
@context.next!
end
end
nodes
end
def short_inline(until_pattern = nil)
nodes = Nodes[]
guarded_loop do
# FIXME: quick and UGLY IS HELL JUST TRYING TO MAKE THE SHIT WORK
if @context.inline_eol_sign == /^\]/
chunk = @context.scan_until(re.short_inline_until_cache_brackets[until_pattern])
elsif @context.inline_eol_sign == /^\]\]/
chunk = @context.scan_until(re.short_inline_until_cache_brackets2[until_pattern])
else
chunk = @context.scan_until(re.short_inline_until_cache[until_pattern])
end
nodes << chunk
break if @context.matched_inline?(until_pattern)
nodes << inline_formatting(@context.matched)
break if @context.inline_eol?(until_pattern)
end
nodes
end
def long_inline(until_pattern = nil)
nodes = Nodes[]
guarded_loop do
chunk = @context.scan_until(re.inline_until_cache[until_pattern])
nodes << chunk
break if @context.matched?(until_pattern)
nodes << inline_formatting(@context.matched) unless @context.matched.empty?
if @context.eof?
break unless until_pattern
@context.fail!("#{until_pattern} not found")
end
if @context.eol?
@context.next!
paragraphs(until_pattern).each do |p|
nodes << p
end
break
end
end
nodes
end
private
def inline_formatting(match)
case match
when "'''''"
BoldItalic.new(short_inline(/'''''/))
when "'''"
Bold.new(short_inline(/'''/))
when "''"
Italic.new(short_inline(/''/))
when '[['
if @context.check(re.file_namespace)
image
else
wikilink
end
when /\[(.+)/
external_link($1)
when '{{'
template
when /<nowiki([^>]*)>/
nowiki($1)
when /<ref([^>]*)\/>/
reference($1, true)
when /<ref([^>]*)>/
reference($1)
when /<math>/
math
when '<'
html || Text.new(match) # it was not HTML, just accidental <
else
match # FIXME: TEMP
end
end
# http://en.wikipedia.org/wiki/Help:Link#Wikilinks
# [[abc]]
# [[a|b]]
def wikilink
link = @context.scan_continued_until(/\||\]\]/)
if @context.matched == '|'
@context.push_eol_sign(/^\]\]/)
caption = inline(/\]\]/)
@context.pop_eol_sign
end
Wikilink.new(link, caption)
end
# http://en.wikipedia.org/wiki/Help:Link#External_links
# [http://www.example.org]
# [http://www.example.org link name]
def external_link(protocol)
link = @context.scan_continued_until(/\s+|\]/)
if @context.matched =~ /\s+/
@context.push_eol_sign(/^\]/)
caption = short_inline(/\]/)
@context.pop_eol_sign
end
ExternalLink.new(protocol + link, caption)
end
def reference(param_str, closed = false)
children = closed ? Nodes[] : long_inline(/<\/ref>/)
Ref.new(children, parse_params(param_str))
end
def math
Math.new(@context.scan_continued_until(/<\/math>/))
end
def nowiki(tag_rest)
if tag_rest.end_with?('/')
Text.new('')
else
Text.new(@context.scan_continued_until(/<\/nowiki>/))
end
end
end
require_relative 'image'
require_relative 'html'
require_relative 'template'
include Infoboxer::Parser::Image
include Infoboxer::Parser::HTML
include Infoboxer::Parser::Template
end
end
| true |
710eb0bb3c24aa1d0717488399aae17f28612356 | Ruby | rvedotrc/advent-of-code-2019 | /lib/arcade_game.rb | UTF-8 | 1,423 | 3.46875 | 3 | [] | no_license | require 'machine'
class ArcadeGame
RENDERED = [' ', '#', '.', '=', 'o']
def initialize
@grid = {}
end
def run(program)
buffer = []
on_output = proc do |n|
buffer << n
if buffer.count == 3
x, y, type = buffer
@grid[ [x, y] ] = RENDERED[type]
buffer = []
end
end
machine = Machine.new(program, on_output: on_output)
machine.run
end
def run_interactive(program)
score = nil
ball_x = nil
bat_x = nil
buffer = []
on_output = proc do |n|
buffer << n
if buffer.count == 3
x, y, type = buffer
if x == -1 and y == 0
score = type
else
@grid[ [x, y] ] = RENDERED[type]
ball_x = x if type == 4
bat_x = x if type == 3
end
buffer = []
end
end
on_input = proc do
# puts
# puts *draw
# puts score
if ball_x > bat_x
+1
elsif ball_x < bat_x
-1
else
0
end
end
machine = Machine.new(
program,
on_input: on_input,
on_output: on_output,
)
machine.run
score
end
def draw
x_values = @grid.keys.map(&:first).sort
y_values = @grid.keys.map(&:last).sort
(y_values.min .. y_values.max).map do |y|
(x_values.min .. x_values.max).map do |x|
@grid[ [x,y] ] || ' '
end.join('')
end
end
end
| true |
c97b388b3a13c0977b3703852d496c333e8e6b38 | Ruby | andrewn/bbcboxbot | /rb/twitter_helpers.rb | UTF-8 | 7,178 | 3.046875 | 3 | [] | no_license | # Get the latest post for the user's
# timeline in the account credentials
# given.
#
def get_latest_post_from_twitter(un, pw)
# Create the twitter object
twit = Twitter::Base.new(un, pw)
# What's the last message posted to the box's timeline?
timeline = twit.timeline(:user)
if timeline.empty?
return nil
else
return timeline.first
end
end
def post_box_update(un, pw, msg)
if not DEBUG
@logger.info "LIVE: Post message to twitter (#{un})"
@logger.info msg
@logger.info
twit = Twitter::Base.new(un, pw)
twit.update(msg)
else
@logger.debug "DEBUG: #{msg}"
end
end
# Create a twitter message
# with the given lat, lon, time
# to the twitter account given.
#
def create_box_update(opts)
ok = check_options_exist_in_obj(opts, :lat, :lon, :time)
if opts[:msg_length].nil?
max_msg_length = DEFAULT_MAX_MSG_LENGTH
else
max_msg_length = opts[:msg_length]
end
@logger.error "Not enough data to create an update..." unless ok
if ok
lat = opts[:lat].to_s
lon = opts[:lon].to_s
time = opts[:time].to_s
machine_location = "L:#{lat},#{lon}:"
machine_time = "#{time}"
relative_time = convert_to_relative_time_string(time) + " ago"
loc = fetch_descriptive_location(lat,lon)
descriptive_location_with_country_name = nil
if loc[:place] and loc[:country]
@logger.info "Create message: using place and country"
descriptive_location_with_country_name = "near #{loc[:place]}, #{loc[:country]}"
end
if loc[:place] and loc[:country_code]
@logger.info "Create message: using place and country code"
descriptive_location_with_country_code = "near #{loc[:place]}, #{loc[:country_code]}"
end
if descriptive_location_with_country_name.nil? and descriptive_location_with_country_code.nil?
@logger.info "Create message: using lat,lon"
descriptive_location_with_country_name = descriptive_location_with_country_code = "near coordinates #{lat},#{lon}"
end
msg_short = "BBC Box spotted near #{machine_location} at #{machine_time}"
msg_medium = "BBC Box spotted #{descriptive_location_with_country_code} (#{machine_location} #{machine_time})"
msg_long = "BBC Box spotted #{descriptive_location_with_country_name} (#{machine_location} #{machine_time})"
msg = msg_long
# Calculate how long message will be
# with full descriptive location
if msg.length > max_msg_length
msg = msg_medium
end
if msg.length > max_msg_length
msg = msg_short
end
if msg.length > max_msg_length
@logger.fatal "Shortest message is longer than #{max_msg_length}. Quitting"
Kernel.exit
end
return msg
end
end
require 'actionpack'
require 'action_controller'
def convert_to_relative_time_string(time)
helper_proxy = ActionController::Base.helpers
return helper_proxy.time_ago_in_words(time)
#return distance_of_time_in_words(time)
end
require 'net/http'
require 'uri'
def fetch_descriptive_location(lat, lon)
location = { :country => nil,
:country_code => nil,
:place => nil }
# This returns XML --- boring!
reverse_geocode_url = "http://ws.geonames.org/findNearbyPlaceName?lat=#{lat}&lng=#{lon}"
raw_data = Net::HTTP.get URI.parse(reverse_geocode_url)
@logger.info "Finding from... #{reverse_geocode_url}"
place_name_pattern = /<name>(.+)<\/name>/i
country_name_pattern = /<countryName>(.+)<\/countryName>/i
country_code_pattern = /<countryCode>(.+)<\/countryCode>/i
country = raw_data.match(country_name_pattern)
place = raw_data.match(place_name_pattern)
code = raw_data.match(country_code_pattern)
if DEBUG
@logger.debug "Cty: " + country[1] if country
@logger.debug "(Code:) " + code[1] if code
@logger.debug "Plc: " + place[1] if place
end
location[:country] = country[1] if country and country[1]
location[:place] = place[1] if place and place[1]
location[:country_code] = code[1] if code and code[1]
return location
end
require 'net/http'
require 'uri'
require 'json'
def get_latest_box_update_from_bbc(url)
@logger.info "Fetching data from BBC: #{url}"
raw_data = Net::HTTP.get URI.parse(url)
# Remove whitespace and other invalid nonsense
raw_data = remove_invalid_json_nonsense(raw_data)
data = JSON.parse(raw_data)
if data.nil? or data["points"].nil? then
@logger.warn "Data from BBC source is nil, can't process latest update (returning nil)"
return nil
end
@logger.info "Parsed JSON points " + data["points"].length.to_s
sortable_data = parse_strings_in_array_to_datetime(data["points"], "time", "lat", "lon")
@logger.info "Sortable data points " + sortable_data.length.to_s
sortable_data.sort! do |a,b|
if a["time"].nil? or b["time"].nil?
0
else
a["time"] <=> b["time"]
end
end
latest = sortable_data.last #sortable_data[0]
return { :time => latest["time"], :lat => latest["lat"], :lon => latest["lon"] }
end
def parse_strings_in_array_to_datetime(array, time_ref, *other_refs)
output = []
array.each do |e|
o = {}
if[ e[time_ref] ]
d = DateTime.parse( e[time_ref] )
o[time_ref] = d
other_refs.each do |ref|
o[ref] = e[ref]
end
output.push(o)
else
@logger.warn "Time not found in object: #{o}. Skipping."
end
end
return output
end
def remove_invalid_json_nonsense(raw_data)
# Tidy curly braces between objs
raw_data.gsub!(/\s*\{\s*/m, "{")
raw_data.gsub!(/\s*\}\s*,\s*/m, "},") # },
raw_data.gsub!(/\s*\}\s*\}\s*/m, "} }") # } }
raw_data.gsub!(/\s*\}\s*\]\s*/m, "} ]")
# Sort out array square brackets
raw_data.gsub!(/\s*\[\s*/m, "[") # [
raw_data.gsub!(/\s*\]\s*,\s*/m, "],") # ],
# Collapse properties
raw_data.gsub!(/\s*,\s*/m, ",")
# Remove anything at start and end that's
# not an array or object identifier
raw_data.slice!(0) unless raw_data.first == "[" or raw_data.first == "{"
raw_data.slice!(raw_data.length - 1) unless raw_data.last == "]" or raw_data.last == "}"
return raw_data
end
def extract_box_data_from_message(msg)
obj = {}
found_loc = false
found_time = false
location_nanoformat_pattern = /L:([+-]?\d*(.?\d*)),([+-]?\d*(.?\d*)):/i
time_nanoformat_pattern = /(\d+-\d+-\d+T\d+:\d+:\d+[+-]?\d+:\d+)/i
loc_match = msg.match(location_nanoformat_pattern)
time_match = msg.match(time_nanoformat_pattern)
unless loc_match.nil?
obj[:lat] = loc_match[1]
obj[:lon] = loc_match[3]
found_loc = true
end
unless time_match.nil?
obj[:time] = DateTime.parse(time_match[0])
found_time = true
end
if found_loc and found_time
return obj
else
return nil
end
end
# Returns true if all keys exist
# as properties of object
# false if not.
def check_options_exist_in_obj(obj, *keys)
keys.each do |k|
return false if obj[k].nil?
end
return true
end | true |
2b9fd7df91b43befecf5aeae0ce0af5de6ada38e | Ruby | landroide13/Ruby-Exce | /hash.rb | UTF-8 | 223 | 3.546875 | 4 | [] | no_license |
putos={"name"=>"fofo","age"=>18,[]=>"array"}
puts putos
puts putos[[]]
staff={name:"fofo",age:"18",profesion:"putito"}
puts staff
puts staff[:profesion]
staff.each do |sing,value|
puts "On #{sing} is #{value}"
end
| true |
53730fe82341765a4673734a9afd818e613d77a6 | Ruby | zmack/ruby-things | /meta-4.rb | UTF-8 | 197 | 3.296875 | 3 | [] | no_license | class Foo
attr_accessor :bar
end
def pick
p self
end
def moo
puts @bar
puts self
end
bar = lambda do
@bar
end
a = Foo.new
a.bar = 10
method(:moo).unbind.bind(a)
a.send(:moo)
p self
| true |
0a7bbf8348bf443c09fe9db5e1788ac5a7335df1 | Ruby | mstolbov/robotanks_bot | /s_server.rb | UTF-8 | 718 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'em-websocket'
class MainServer
attr_accessor :data, :connect
def initialize(host, port)
@connect = TCPSocket.new host, port
end
end
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 5555) do |ws|
server = nil
ws.onopen do |handshake|
server = MainServer.new("192.168.30.188", 4444)
server.connect.write "{\"role\":\"observer\"}\n"
puts "connected"
ws.send "Hello Client, you connected to #{handshake.path}"
end
timer = EM.add_periodic_timer(0.01) do
if server
data = server.connect.gets
puts "data from server #{data}"
ws.send data
end
end
ws.onclose do
puts "WebSocket server closed"
EM.cancel_timer timer
end
end
| true |
03d42ca252e99427960ad830d802a8bab2f2757c | Ruby | bootstraponline/page_object_stubs | /lib/page_object_stubs/page_object_stubs.rb | UTF-8 | 3,241 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | module PageObjectStubs
class << self
# Creates stubs from target Ruby files in output folder with the format
# target_filename_stub.rb
#
# Note the output folder is **DELETED** each time stubs are generated.
#
# ```ruby
# targets = Dir.glob(File.join(__dir__, '..', 'page', '*_page.rb'))
# output = File.join(__dir__, '..', 'stub')
# exclude = /#{Regexp.escape('base_page.rb')}/
# PageObjectStubs.generate targets: targets, output: output, exclude: exclude
# ```
#
# @param [Hash] opts
# @option opts [Array<File>] :targets Array of target files to create stubs from (required)
# @option opts [Dir] :output Folder to create stubs in (required)
# @option opts [Regexp] :exclude Exclusion regex use to reject targets (optional)
def generate opts={}
targets = opts.fetch(:targets)
targets = targets.select do |target|
File.file?(target) && File.readable?(target)
end
regex = opts.fetch(:exclude, false)
targets.reject! { |t| t.match regex } if regex
output_folder = File.expand_path(opts.fetch(:output))
FileUtils.rm_rf output_folder
FileUtils.mkdir_p output_folder
targets.each do |f|
ast = Parser::CurrentRuby.parse File.read f
page_objects = ProcessPageObjects.new
page_objects.process ast
file_name = File.basename(f, '.*')
file_module_name = file_name.split('_').map(&:capitalize).join
file_method_name = file_name.downcase
output_prefix = <<R
module Stub
module #{file_module_name}
class << self
R
data = ''
def wrap method_name
' ' * 6 + "def #{method_name}; fail('stub called!'); end" + "\n"
end
page_objects.name_type_pairs.each do |pair|
# process custom methods that aren't defined in page_object
if pair.length == 1
data += wrap "#{pair.first}(*args)"
next
end
element_type = pair.first
# if 'page_url' exists, then we need `def goto`
# for all others, we need the name of the element to generate the remaining methods.
if element_type == 'page_url'
data += wrap 'goto'
next
end
element_name = pair.last
data += wrap "#{element_name}"
data += wrap "#{element_name}_element"
data += wrap "#{element_name}?"
data += wrap "#{element_name}=" if element_type == 'text_field'
end
stub_file = File.join(output_folder, file_name + '_stub.rb')
# Note that the page method is defined as a singleton method on the
# top level 'main' object. This ensures we're not polluting the global
# object space by defining methods on every object which would happen
# if Kernel was used instead.
output_postfix = <<R
end
end
end
module RSpec
module Core
class ExampleGroup
def #{file_method_name}
Stub::#{file_module_name}
end
end
end
end
R
data = output_prefix + data + output_postfix
File.open(stub_file, 'w') do |file|
file.write data
end
end
end
end
end
| true |
cd72112f4574e8e8ad736a0e495897a35db0d00b | Ruby | tondol/DivaDotNet | /sample.rb | UTF-8 | 660 | 2.921875 | 3 | [] | no_license | #!/usr/local/bin/ruby
# -*- encoding: utf-8 -*-
require 'kconv'
require 'divadotnet'
ACCESS_CODE = "YOUR_ACCESS_CODE"
PASSWORD = "YOUR_PASSWORD"
# get instance and login
diva = DivaDotNet.login(ACCESS_CODE, PASSWORD)
sleep 1
# get user data
puts "get user data..."
user = diva.get_user
puts user.to_s.tosjis
sleep 1
# you have to get song summaries before getting song data
puts "get song summaries..."
summaries = diva.get_song_summaries
sleep 1
# you have to specify the summary to get song data
summaries.each {|summary|
name = summary['name']
puts "get song data (#{name})..."
puts diva.get_song(summary).to_s
sleep 1
}
| true |
49913da2bb7f0af036cd92941876c9c0f8a8f7f4 | Ruby | rinostar/video-store-api | /test/models/customer_test.rb | UTF-8 | 1,631 | 2.609375 | 3 | [] | no_license | require "test_helper"
describe Customer do
before do
@valid_customer = customers(:customer1)
end
describe "validation" do
it "is avlid when all fields are present" do
result = @valid_customer.valid?
expect(result).must_equal true
end
it "is invalid without a name" do
@valid_customer.name = nil
result = @valid_customer.valid?
expect(result).must_equal false
end
it "is invalid with a duplicate name" do
@valid_customer.name = customers(:customer2).name
result = @valid_customer.valid?
expect(result).must_equal false
end
it "is invalid without a registered date" do
@valid_customer.registered_at = nil
result = @valid_customer.valid?
expect(result).must_equal false
end
it "is invalid without a postal code" do
@valid_customer.postal_code = nil
result = @valid_customer.valid?
expect(result).must_equal false
end
it "is invalid without a phone number" do
@valid_customer.phone = nil
result = @valid_customer.valid?
expect(result).must_equal false
end
end
describe "relationship" do
before do
@rental = Rental.new(
checkout_date: Date.today,
due_date: Date.today + 7,
movie_id: movies(:movie2).id,
customer_id: @valid_customer.id
)
end
it "can have many movies through rental" do
@rental.save
customer = Customer.find_by(id: @valid_customer.id)
expect(customer.movies.count).must_be :>=, 0
expect(customer.movies).must_include movies(:movie2)
end
end
end
| true |
b9de747fa6aea9b90bd1bc3db86d569860aef83f | Ruby | jxandery/cc-histogram | /test/histogram_test.rb | UTF-8 | 1,791 | 3.015625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/histogram'
class HistogramTest < Minitest::Test
def test_it_exists
assert Histogram
end
def test_hash_setup
example = Histogram.new([3,1])
assert_equal [], example.rectangles[2]
end
def test_adjacent_one_column
example = Histogram.new([3,1,2])
example.rectangle_size(['x', ' ', ' '])
assert_equal [1], example.rectangles[3]
end
def test_adjacent_two_column
example = Histogram.new([3,3,1])
example.rectangle_size(['x', 'x', ' '])
assert_equal [2], example.rectangles[3]
end
def test_adjacent_three_column
example = Histogram.new([3,3,3])
example.rectangle_size(['x', 'x', 'x'])
assert_equal [3], example.rectangles[3]
end
def test_adjacent_single_column
example = Histogram.new([3,1,3])
example.rectangle_size(['x', ' ', 'x'])
assert_equal [1,1], example.rectangles[3]
end
def test_multiple_adjacent_single_column
example = Histogram.new([3,3,1,3])
example.rectangle_size(['x', 'x', ' ', 'x'])
assert_equal [2,1], example.rectangles[3]
end
def test_multiple_adjacent_multiple_column
example = Histogram.new([3,3,1,3,3])
example.rectangle_size(['x', 'x', ' ', 'x', 'x'])
assert_equal [2,2], example.rectangles[3]
end
def test_find_width_for_multiple_levels
example = Histogram.new([2,2,1,2,2])
example.all_rectangles
assert_equal({2=>[2,2], 1=>[5]}, example.rectangles)
end
def test_find_width_for_multiple_levels2
example = Histogram.new([3,2,1,2,3])
example.all_rectangles
assert_equal({3=> [1,1], 2=>[2,2], 1=>[5]}, example.rectangles)
end
def test_find_max_rectangle
example = Histogram.new([3,2,1,2,3])
assert_equal 5, example.max_retangle
end
end
| true |
aaa69e52566cdfc48e9cf19135cb5d9739711c70 | Ruby | kdtestaccount/ruby-intro-to-hashes-lab-v-000 | /intro_to_ruby_hashes_lab.rb | UTF-8 | 1,620 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def new_hash
empty_hash = { }
end
def actor
actor = {:name => "Dwayne The Rock Johnson"}
end
def monopoly
monopoly = {:railroads => {}}
end
def monopoly_with_second_tier
monopoly = {:railroads => {:pieces => 4, :names=> {}, :rent_in_dollars=> {} }}
end
def monopoly_with_third_tier
monopoly = {:railroads =>
{:pieces => 4,
:names=> {
:reading_railroad => {},
:pennsylvania_railroad => {},
:b_and_o_railroad => {},
:shortline => {},
},
:rent_in_dollars=>
{:one_piece_owned => 25,
:two_pieces_owned => 50,
:three_pieces_owned => 100,
:four_pieces_owned => 200}
}
}
end
def monopoly_with_fourth_tier
monopoly = {:railroads =>
{:pieces => 4,
:names=> {
:reading_railroad => {"mortgage_value" => "$100"},
:pennsylvania_railroad => {"mortgage_value" => "$200"},
:b_and_o_railroad => {"mortgage_value" => "$400"},
:shortline => {"mortgage_value" => "$800"},
},
:rent_in_dollars=>
{:one_piece_owned => 25,
:two_pieces_owned => 50,
:three_pieces_owned => 100,
:four_pieces_owned => 200}
}
}
end
# monopoly_with_second_tier
# puts monopoly
# contacts["Jon Snow"][:address] = "The Lord Commander's Rooms, The Wall, Westeros"
# puts contacts
# # >
# {
# "Jon Snow" => {
# :name=>"Jon",
# :email=>"jon_snow@thewall.we",
# :favorite_ice_cream_flavors=>["chocolate", "vanilla", "mint chip"],
# :address=>"The Lord Commander's Rooms, The Wall, Westeros"
# },
# "Freddy Mercury"=> {
# :name=>"Freddy",
# :email=>"freddy@mercury.com",
# :favorite_ice_cream_flavors=> ["cookie dough", "mint chip"]
# }
# } | true |
9f048728215eadfcadd267dd68e9eedb538e4623 | Ruby | Acidknight/array-CRUD-lab-onl01-seng-pt-090820 | /lib/array_crud.rb | UTF-8 | 1,152 | 3.671875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def create_an_empty_array
[]
end
def create_an_array
video_game_character = ["Link", "Samus", "Mario", "Luigi"]
end
def add_element_to_end_of_array(array, element)
video_game_character = ["Link", "Samus", "Mario", "Luigi"]
video_game_character << "arrays!"
end
def add_element_to_start_of_array(array, element)
video_game_character = ["Link", "Samus", "Mario", "Luigi"]
video_game_character.unshift("wow")
end
def remove_element_from_end_of_array(array)
video_game_character = ["Link", "Samus", "Mario", "Luigi", "arrays!"]
luigi = video_game_character.pop
end
def remove_element_from_start_of_array(array)
video_game_character = ["wow", "Link", "Samus", "Mario", "Luigi"]
wow = video_game_character.shift
end
def retrieve_element_from_index(array, index_number)
video_game_character = ["Link", "Samus", "am", "Luigi"]
video_game_character[2]
end
def retrieve_first_element_from_array(array)
video_game_character = ["wow", "Samus", "Mario", "Luigi"]
video_game_character[0]
end
def retrieve_last_element_from_array(array)
video_game_character = ["Link", "Samus", "Mario", "arrays!"]
video_game_character[-1]
end
| true |
f2ef045ea71f7570b004dc2243a47c26165c8be3 | Ruby | chendo/mongoid | /lib/mongoid/associations.rb | UTF-8 | 3,401 | 2.765625 | 3 | [
"MIT"
] | permissive | require "mongoid/associations/decorator"
require "mongoid/associations/accessor"
require "mongoid/associations/belongs_to"
require "mongoid/associations/has_many"
require "mongoid/associations/has_one"
module Mongoid # :nodoc:
module Associations #:nodoc:
def self.included(base)
base.class_eval do
include InstanceMethods
extend ClassMethods
end
end
module InstanceMethods
def associations
self.class.associations
end
end
module ClassMethods
def associations
@associations ||= {}.with_indifferent_access
end
# Adds the association back to the parent document. This macro is
# necessary to set the references from the child back to the parent
# document. If a child does not define this association calling
# persistence methods on the child object will cause a save to fail.
#
# Options:
#
# name: A +Symbol+ that matches the name of the parent class.
#
# Example:
#
# class Person < Mongoid::Document
# has_many :addresses
# end
#
# class Address < Mongoid::Document
# belongs_to :person
# end
def belongs_to(name, options = {})
@embedded = true
add_association(Associations::BelongsTo, Options.new(options.merge(:association_name => name)))
end
# Adds the association from a parent document to its children. The name
# of the association needs to be a pluralized form of the child class
# name.
#
# Options:
#
# name: A +Symbol+ that is the plural child class name.
#
# Example:
#
# class Person < Mongoid::Document
# has_many :addresses
# end
#
# class Address < Mongoid::Document
# belongs_to :person
# end
def has_many(name, options = {})
add_association(Associations::HasMany, Options.new(options.merge(:association_name => name)))
end
# Adds the association from a parent document to its child. The name
# of the association needs to be a singular form of the child class
# name.
#
# Options:
#
# name: A +Symbol+ that is the plural child class name.
#
# Example:
#
# class Person < Mongoid::Document
# has_many :addresses
# end
#
# class Address < Mongoid::Document
# belongs_to :person
# end
def has_one(name, options = {})
add_association(Associations::HasOne, Options.new(options.merge(:association_name => name)))
end
private
# Adds the association to the associations hash with the type as the key,
# then adds the accessors for the association.
def add_association(type, options)
associations[options.association_name] = type
name = options.association_name
define_method(name) do
return instance_variable_get("@#{name}") if instance_variable_defined?("@#{name}")
proxy = Associations::Accessor.get(type, self, options)
instance_variable_set("@#{name}", proxy)
end
define_method("#{name}=") do |object|
proxy = Associations::Accessor.set(type, self, object, options)
instance_variable_set("@#{name}", proxy)
end
end
end
end
end
| true |
2f15ce86e77ef80177b3f67df09aac80028b6ef5 | Ruby | djoverbeatz29/ruby-oo-relationships-practice-art-gallery-exercise-chicago-web-021720 | /app/models/gallery.rb | UTF-8 | 530 | 3.171875 | 3 | [] | no_license | class Gallery
attr_reader :name, :city
@@all = []
def self.all
@@all
end
def most_expensive_painting
self.paintings.max_by { |pa| pa.price }
end
def initialize(name, city)
@name = name
@city = city
@@all << self
end
def paintings
Painting.all.find_all { |pa| pa.gallery == self }
end
def artists
self.paintings.map { |pa| pa.artist }.uniq
end
def artist_names
self.artists.map { |ar| ar.name }
end
end | true |
8d7eb10c65853a2a7bf1562606cc17b0e4c63663 | Ruby | falyhery/mini_jeu_POO | /app_2.rb | UTF-8 | 1,969 | 3.8125 | 4 | [] | no_license | require 'bundler'
Bundler.require
require_relative 'lib/game'
require_relative 'lib/player'
#------------------------------------------------
#Bienvenue sur 'POO POO POO POO POOOOOO' ! |
#Last player standing takes it all ! Good luck !|
#------------------------------------------------
#Initialisation du joueur
puts "Quel est ton prénom ?"
print "> "
first_name = gets.chomp
human_player = HumanPlayer.new(first_name)
#Initialisation des ennemis
player1 = Player.new("Josiane")
player2 = Player.new("José")
enemies = [player1, player2]
#Le combat
while human_player.life_points > 0 && (player1.life_points > 0 || player2.life_points > 0)
puts "Voici l'état de ton joueur: "
human_player.show_state
puts "\n"
#Menu
puts "Quelle action veux-tu effectuer ?"
puts "\n"
puts " a - chercher une meilleure arme "
puts " s - chercher à se soigner"
puts "\n"
puts " attaquer un joueur en vue :"
puts " 0 - tu choisis d'attaquer le robot Josiane"
puts " 1 - tu choisis d'attaquer le robot José"
puts "---"*10
print "> "
player_choice = gets.chomp
if player_choice == "a" #cherche une meilleure arme
human_player.search_weapon
elsif player_choice == "s" #cherche à se soigner
human_player.search_health_pack
elsif player_choice == "0" #lance une attaque sur le robot Josiane
human_player.attacks(player1)
player1.show_state
elsif player_choice == "1" #lance une attaque sur le robot José
human_player.attacks(player2)
player2.show_state
else
puts "Choisis parmi les options proposées"
end
#Riposte des robots joueurs
puts "Les autres joueurs t'attaquent !"
enemies.each do |enemy|
if enemy.life_points > 0
break if human_player.life_points <= 0
enemy.attacks(human_player)
end
end
end
#Fin du jeu
puts "\n"
puts "La partie est finie"
if human_player.life_points > 0
puts "BRAVO ! TU ES LE DERNIER DEBOUT !"
else puts "C'est trop la lose. Mais tu peux toujours recommencer..."
end
#binding.pry | true |
d5bfd086cb1b7e109dc8b2b4b0335c1b17071a4a | Ruby | mrobock/ruby_rspec_day4 | /anniversary.rb | UTF-8 | 1,226 | 3.6875 | 4 | [] | no_license | require_relative 'date_task'
class Anniversary < Task
def initialize(title, year, month, day)
super(title)
@year = year
@month = month
@day = day
#if the supplied date is equal to or later than today then it's set. Otherwise we add a year to the date, representing the next instance of your anniversary.
if (Date.strptime("#{@year}-#{@month}-#{@day}", '%Y-%m-%d') >= Date.today)
@date = Date.strptime("#{@year}-#{@month}-#{@day}", '%Y-%m-%d')
else
@date = Date.strptime("#{Date.today.year+1}-#{@month}-#{@day}", '%Y-%m-%d')
# puts "You are an idiot. Stop living in the past. Luckily for you, I'm smarter than you and fixed your date!"
end
end
#this method is called at the beginning of every following method. It confirms that your anniversary is still in the future. If not, it adds a year to your anniversary, which represents the next time it will be your anniversary!
def checkDate
if @date == Date.today
"Congrats! Its your anniversary"
elsif
@date < Date.today
@date = Date.strptime("#{@year+1}-#{@month}-#{@day}", '%Y-%m-%d')
end
end
#returns the date of your anniversary task
def date
checkDate
@date
end
end
| true |
afe259956a350ca5786ce4bd6a005d5d8924027b | Ruby | TacOnTac/KarelRTuesday | /tasks/tris.rb | UTF-8 | 1,684 | 3.984375 | 4 | [] | no_license | def tri_bulles(matrice)
len = matrice.length
i = 0
j = 1
tmp = 0
while i < len
j = 1
while j < (len - i)
if matrice[j-1] > matrice[j]
tmp = matrice[j]
matrice[j] = matrice[j-1]
matrice[j-1] = tmp
end
j = j + 1
end
i = i+1
end
return matrice
end
def tri_selection(matrice)
len = matrice.length
i = 0
j = 1
tmp = 0
while i < len -1
j = i+1
plus_petit = i
while j < (len)
if matrice[plus_petit] > matrice[j]
plus_petit = j
end
j = j + 1
end
tmp = matrice[i]
matrice[i] = matrice[plus_petit]
matrice[plus_petit] = tmp
i = i+1
end
return matrice
end
def tri_fusion(matrice)
num_elements = matrice.length
if num_elements <= 1
return matrice
end
half_of_elements = (num_elements / 2).round
left = matrice.take(half_of_elements)
right = matrice.drop(half_of_elements)
sorted_left = tri_fusion(left)
sorted_right = tri_fusion(right)
merge(sorted_left, sorted_right)
end
def merge(left_array, right_array)
if right_array.empty?
return left_array
end
if left_array.empty?
return right_array
end
smallest_number = if left_array.first <= right_array.first
left_array.shift
else
right_array.shift
end
recursive = merge(left_array, right_array)
[smallest_number].concat(recursive)
end
arr = []
9.times do
arr << rand(1..100)
end
puts "array before"
puts arr
puts "_______________"
puts tri_bulles(arr)
puts "tri_bulles"
puts "_______________"
puts "array before"
puts arr
puts "_______________"
puts tri_selection(arr)
puts "tri_selection"
puts "_______________"
puts arr
puts "_______________"
puts tri_fusion(arr)
puts "fusion"
puts "_______________"
| true |
22b56a08010dc9d2d29c8ffddae573215eae5a18 | Ruby | MastersAcademy/ruby-course-2018 | /objects/session/objects/1.rb | UTF-8 | 295 | 3.546875 | 4 | [] | no_license | class Fish
attr_accessor :speed
end
Fish.class_eval do
def time(distance)
"#{distance/speed} seconds"
end
end
a = Fish.new
a.instance_eval do
def time(distance)
"#{distance/speed} hours"
end
end
a.speed=5
puts a.time(500) | true |
92fd7254789899ea51dc40c9a41fd03d4c0b403f | Ruby | Mikeyheu/durham-2014-march | /house/lib/house.rb | UTF-8 | 640 | 3.5625 | 4 | [] | no_license | class House
attr_reader :song_parts
def initialize song_parts
@song_parts = song_parts
end
def verse number
"This is " + song_parts.last(number).join(" ") + ".\n\n"
end
def sing
song_parts.length.times.map {|number| verse(number+1)}.join
end
end
class HouseRandom < House
def initialize song_parts
@song_parts = song_parts.shuffle
end
end
class HouseSuperRandom < House
def initialize song_parts
subjects = song_parts.map { |part| part[0] }.shuffle
actions = song_parts.map { |part| part[1] }.shuffle
@song_parts = song_parts.length.times.map { |i| [subjects[i], actions[i]] }
end
end | true |
7032dd1bacba41594507ff5a58f979ae3905f383 | Ruby | Jowits/OO-Art-Gallery-london-web-051319 | /tools/console.rb | UTF-8 | 567 | 2.625 | 3 | [] | no_license | require_relative '../config/environment.rb'
artist1 = Artist.new("Artist1", 2)
artist2 = Artist.new("Artist2", 5)
artist3 = Artist.new("Artist3", 23)
gallery1 = Gallery.new("Gallery1", "London")
gallery2 = Gallery.new("Gallery2", "Paris")
gallery3 = Gallery.new("Gallery3", "London")
painting1 = Painting.new("Painting1", 1340, gallery1, artist3)
painting2 = Painting.new("Painting2", 140, gallery2, artist1)
painting3 = Painting.new("Painting3", 340, gallery3, artist2)
painting4 = Painting.new("Painting4", 40, gallery3, artist2)
binding.pry
puts "Bob Ross rules."
| true |
eed6644de673a706086f498bc143d6ef1f4c309c | Ruby | Tkam13/atcoder-problems | /abc030/b.rb | UTF-8 | 116 | 2.640625 | 3 | [] | no_license | n,m = gets.chomp.split.map(&:to_i)
n -= 12 if n >= 12
rad = (n * 30 + 0.5 * m - m * 6).abs
puts [rad,360 - rad].min | true |
ce90644bc565132084ff9e00b3c57b8eb9ae6ec2 | Ruby | walshification/tolarian_registry | /lib/tolarian_registry.rb | UTF-8 | 2,286 | 2.828125 | 3 | [
"MIT"
] | permissive | require "tolarian_registry/version"
require 'unirest'
module TolarianRegistry
class Card
attr_accessor :multiverse_id, :card_name, :editions, :text, :flavor, :colors, :mana_cost, :converted_mana_cost, :card_set_name, :card_type, :card_subtype, :power, :toughness, :loyalty, :rarity, :artist, :card_set_id, :image_url, :rulings, :formats
def initialize(hash)
@multiverse_id = hash[:multiverse_id]
deckbrew_hash = Unirest.get("https://api.deckbrew.com/mtg/cards?multiverseid=#{@multiverse_id}").body.first
# mtgdb_hash = Unirest.get("http://api.mtgdb.info/cards/#{@multiverse_id}").body
@card_name = deckbrew_hash["name"]
@editions = deckbrew_hash["editions"]
@text = deckbrew_hash["text"]
@flavor = deckbrew_hash["editions"][0]["flavor"]
@colors = deckbrew_hash["colors"]
@mana_cost = deckbrew_hash["cost"]
@converted_mana_cost = deckbrew_hash["cmc"]
@card_set_name = deckbrew_hash["editions"][0]["set"]
# @card_type = mtgdb_hash["type"]
# @card_subtype = mtgdb_hash["subType"]
@power = deckbrew_hash["power"]
@toughness = deckbrew_hash["toughness"]
@loyalty = deckbrew_hash["loyalty"]
@rarity = deckbrew_hash["editions"][0]["rarity"]
@artist = deckbrew_hash["editions"][0]["artist"]
@card_set_id = deckbrew_hash["editions"][0]["set_id"]
@image_url = deckbrew_hash["editions"][0]["image_url"]
# @rulings = mtgdb_hash["rulings"]
# @formats = mtgdb_hash["formats"]
end
def self.find_by_name(name)
card = Unirest.get("https://api.deckbrew.com/mtg/cards?name=#{name}").body.first
if card
multiverse_id = card["id"]
return Card.new(:multiverse_id => multiverse_id)
else
return nil
end
end
def low_price
@price = get_price("low")
end
def median_price
@price = get_price("median")
end
def high_price
@price = get_price("high")
end
private
def get_price(level)
@card = Unirest.get("https://api.deckbrew.com/mtg/cards?multiverseid=#{@multiverse_id}").body
@card[0]["editions"].each do |edition|
@price = edition["price"][level] if edition["multiverse_id"] == @multiverse_id
end
@price
end
end
end
| true |
22b805d257b99780f1bfd259c4d1aaab769d2aaa | Ruby | DeclanBU/OOP2-Project-2014 | /vendor/bundle/ruby/2.3.0/gems/attic-0.5.3/try/X2_extending.rb | UTF-8 | 389 | 3.171875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | $:.unshift './lib'
require 'attic'
class A
extend Attic
attic :andy
end
class B < A
attic :size
end
class C
extend Attic
attic :third
end
a, b, c = A.new, B.new, C.new
a.andy, b.andy = 1, 2
p [a.respond_to?(:andy), b.respond_to?(:andy)] # true, true
p [a.andy, b.andy] # 1, 2
p [a.class.attic_vars, b.class.attic_vars, c.class.attic_vars]
| true |
3c441b0a38a6b80c918a2382c3200c244b9e3fb0 | Ruby | saumyamehta17/algorithm_and_system_design | /linkedlist/flatten_multilevel_linkedlist.rb | UTF-8 | 1,101 | 3.578125 | 4 | [] | no_license | def flatten_using_queue(head)
q = Queue.new
q.enq(head)
while(!q.empty?)
curr = q.deq
while(!curr.nil?)
print "#{curr.data} --> "
q.enq(curr.child) if !curr.child.nil?
curr = curr.next
end
end
end
def flatten(head)
tail = head
while(!tail.next.nil?)
tail = tail.next
end
curr = head
while(curr != tail)
if(curr.child)
tail.next = curr.child
tmp = curr.child
while(!tmp.next.nil?)
tmp = tmp.next
end
tail = tmp
end
curr = curr.next
end
curr = head
while(!curr.nil?)
print "#{curr.data} --> "
curr = curr.next
end
end
Node = Struct.new(:data, :next, :child)
head = Node.new(10)
head.next = Node.new(5)
head.next.next = Node.new(12)
head.next.next = Node.new(7)
head.next.next.next = Node.new(11)
head.child = Node.new(4)
head.child.next = Node.new(20)
head.child.next.next = Node.new(13)
head.next.next.next.child = Node.new(17)
head.next.next.next.child.next = Node.new(6)
puts "--------"
flatten_using_queue(head)
puts "--------"
flatten(head)
puts "--------" | true |
8235db6e3672d50bfc2d661a9425b0dbfdbf3c75 | Ruby | ferambot/phase-0 | /week-5/nums-commas/my_solution.rb | UTF-8 | 1,846 | 4.40625 | 4 | [
"MIT"
] | permissive | # Numbers to Commas Solo Challenge
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# 0. Pseudocode
# What is the input?
# What is the output? (i.e. What should the code return?)
# What are the steps needed to solve the problem?
# 1. Initial Solution
def separate_comma(num)
stringform = num.to_s
commas = stringform.length / 3 # how many commas to add to our string
(1..commas).each do |i|
stringform.insert(i*-4, ',')
end
if stringform[0] == ','
stringform[0] = ''
stringform
else
stringform
end
end
# 2. Refactored Solution
def separate_comma(num)
stringform = num.to_s
commas = stringform.length / 3 # how many commas to add to our string
(1..commas).each do |i|
stringform.insert(i*-4, ',')
end
if stringform[0] == ','
stringform[0] = ''
stringform
else
stringform
end
end
# 3. Reflection
=begin
What was your process for breaking the problem down? What different approaches did you consider?
-The approach was to find out how many digits I had so I can find out how many commas there are, Then I inserted the commas via a code block iteration
Was your pseudocode effective in helping you build a successful initial solution?
-Yes it was. This was not a easy one. I wrote it all down on paper.
What Ruby method(s) did you use when refactoring your solution? What difficulties did you have implementing it/them? Did it/they significantly change the way your code works? If so, how?
How did you initially iterate through the data structure?
I didn't refactor.
I just deleted index[0] if index[0] was a comma
Do you feel your refactored solution is more readable than your initial solution? Why?
=end
| true |
211e9bba5f8bf705337f21b81fe3315ec89e0680 | Ruby | kanglicheng/tutoring_work | /oddball_sum.rb | UTF-8 | 404 | 3.921875 | 4 | [] | no_license | def oddball_sum(array)
i = 0
odds = []
while i < array.length
if array[i]%2 != 0
odds.push(array[i])
end
i +=1
end
if odds.length > 0
j = 0
summed = 0
while j < odds.length
summed = summed + odds[j]
j +=1
end
end
if odds == []
return 0
end
return summed
end
puts oddball_sum([1, 2, 3, 4, 5]) == 9
puts oddball_sum([0, 6, 4, 4]) == 0
puts oddball_sum([1, 2, 1]) == 2
| true |
54eaeefa73abc954917c2f17e3f841b0b6c8b86a | Ruby | thestokkan/RB100 | /exercises_ruby_basics/debugging/confucius_says.rb | UTF-8 | 2,253 | 4.71875 | 5 | [] | no_license | #
# Confucius Says
#
# You want to have a small script delivering motivational quotes, but with the following code you run into a very common error message: no implicit conversion of nil into String (TypeError). What is the problem and how can you fix it?
#
# def get_quote(person)
# if person == 'Yoda'
# 'Do. Or do not. There is no try.'
# end
#
# if person == 'Confucius'
# 'I hear and I forget. I see and I remember. I do and I understand.'
# end
#
# if person == 'Einstein'
# 'Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.'
# end
# end
#
# puts 'Confucius says:'
# puts '"' + get_quote('Confucius') + '"'
#
# Answer (CORRECT): The method returns the value of the last expression evaluated, which in this case is the last if statement.
# Since the statement does not evaluate to true unless 'Einstein' is passed as an argument, it will return nil, as will the method.
# Since the return value of the method is nil, which cannot be used in string concatenation, an error is raised when the last line is evaluated.
# This can be fixed by assigning each string to a variable and then implicitly or explicitly return this at the end of the method definition. Another option is to use the explicit 'return' statement in front of each string.
# Alt. 1
def get_quote(person)
if person == 'Yoda'
q = 'Do. Or do not. There is no try.'
end
if person == 'Confucius'
q = 'I hear and I forget. I see and I remember. I do and I understand.'
end
if person == 'Einstein'
q = 'Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.'
end
q
end
puts 'Confucius says:'
p puts '"' + get_quote('Confucius') + '"'
# Alt. 2
def get_quote(person)
if person == 'Yoda'
return 'Do. Or do not. There is no try.'
end
if person == 'Confucius'
return 'I hear and I forget. I see and I remember. I do and I understand.'
end
if person == 'Einstein'
return 'Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.'
end
end
puts 'Confucius says:'
p puts '"' + get_quote('Confucius') + '"'
# Solution: My alternative 2, or using if/elsif instead of multiple if statements.
| true |
1729b583b2d29aeb2853cb76753072a1a277a8ad | Ruby | pabco84/Arreglos | /filtro_procesos.rb | UTF-8 | 248 | 2.734375 | 3 | [] | no_license | filter = ARGV[0].to_i
input = File.open('./procesos.data.txt','r') #lee eñ archivo
output = File.open('procesos_filtrados.data', 'w') #escribe el archivo
input.each do |i|
output.puts(i.to_i) if i.to_i > filter
end
input.close
output.close | true |
9aad93cd3582c88a2d08658ee616c3666a054206 | Ruby | p-eduardo-medina/Programacion_en_Ruby_y_Python | /P21.rb | UTF-8 | 4,288 | 3.25 | 3 | [] | no_license | def mystery_func(str)
s = ""
(str.length()/2).times do |index|
((str[2*index+1]).to_i).times do |dindex|
s += str[2*index]
end
end
return s
end
def numbers_sum(arr)
v = 0
arr.each {|element| if element.is_a? Integer
v+=element
end }
return v
end
# p numbers_sum([1, 2, "13", "4", "645"])
def add_letters(a)
v = 0
alphabet = ("a".."z").to_a
if a.empty?
z = "z"
else
a.each do |element|
v += alphabet.index(element)+1
end
r,v = v.divmod(26)
z = alphabet[v-1]
end
return z
end
#p add_letters(["a", "b", "c", "d", "e", "c","a"])
def make_title(str)
str = str.split(/ /)
str = str.map {|element| element.capitalize()}
return str.join(" ")
end
# p make_title("This is a title")
def duplicates(str)
letters={}
count = 0
str.each_char {|chara| letters.store(chara, str.count(chara))}
letters.each {|k,v| count += (v-1) }
return count
end
#p duplicates("Hello World!")
def scale_tip(arr)
v=[0,0]
i=0
arr.each {|element| if element.is_a? String
i+=1
else
v[i]+=element
end
}
if v[0]==v[1]
puts "balanced"
else
v.index(v.max) == 0 ? (puts "Left") : (puts "Right")
end
end
#scale_tip([0, 0, "I", 1, 1])
def palindrome(s)
b = 1
s[0] == s[(s.length-1)] ? (b*=1):(b*=0)
s1 = s[1..(s.length-2)]
if s1.length==1 or s1.length==0
return !b.zero?
elsif s1.length<=0
puts "Invalid input"
return false
else
palindrome(s1)
end
end
# p palindrome("abcba")
def fact(n)
if n<= 1
1
else
n * fact( n - 1 )
end
end
#p fact(5)
def product_pair(arr, k)
if k > arr.length
return nil
else
values=[0,0]
ret=[]
fact(arr.length+2).times do |i|
si = []
if (i.to_s(arr.length+1)).length==k
si = (i.to_s(arr.length+1)).each_char.map(&:to_i)
c = 1
if ((si.uniq).length == si.length) and !(si.include? (arr.length))
si.each {|element| c*=arr[element]}
if values[0]<= c
values[0] = c
elsif values[1]>= c
values[1] = c
end
end
end
end
end
return values
end
#p product_pair([1, -2, -3, 4, 6, 7], 3)
def map_letters(word)
h = Hash[]
(0 ... word.length).each do |i|
if (h.keys).include?((word[i]).to_sym)
h[(word[i]).to_sym].append(i)
else
h[(word[i]).to_sym] = [word.index((word[i]))]
end
end
return h
end
#p map_letters("susana gonzakez marquez")
def build_staircase(height, block)
z=Array.new(height) { Array.new(height, 0) }
height.times do |i|
height.times do |j|
if i<j
z[i][j] = "_"
else
z[i][j]=block
end
end
end
z.each do |element|
p element
end
end
def total_sales(sales_table, product)
v = 0
if !(sales_table[0]).include?(product)
return "Product not found"
else
a = sales_table[0].index(product)
sales_table.shift
(sales_table).each do |element|
v += element[a]
end
return v
end
end
#total_sales([
# ["A", "B", "C"],
# [ 2 , 7 , 1 ],
# [ 3 , 6 , 6 ],
# [ 4 , 5 , 5 ]], "C")
def mirror_cipher(message)
if message.length == 1
a0 = (message.join("")).downcase
a1 = (("a".."z").to_a).join("")
else
a1 = message[1].downcase
a0 = message[0].downcase
end
h = Hash[]
(a1.length).times do |i|
if !(h.keys).include?((a1[i]).to_sym)
h[(a1[a1.length-i-1]).to_sym] = (a1[i])
end
end
(a0.length).times do |i|
if (h.keys).include?((a0[i]).to_sym)
a0[i]= h[(a0[i]).to_sym]
elsif (h.values).include?((a0[i]))
a0[i] = (h.key((a0[i]))).to_s
end
end
return a0
end
#p mirror_cipher(["Mubashir Hassan", "edabitisamazing"])
def validate_subsets(subsets, set)
v = 1
subsets.each{|element| element.each {|elem|(set.include?(elem))?(v*=1):(v*=0)} }
return !v.zero?
end
def possible_palindrome(str)
h = Hash[]
v = 1
str.each_char do |element|
if (h.keys).include?(element.to_sym)
h[element.to_sym] +=1
else
h[element.to_sym] = 1
end
end
(h.values).each do |element|
((h.values).count(1)>1)?(v*=0):(v*=1)
if element%2 == 0
v*=1
else
if element>=3
v*=0
end
end
end
return !v.zero?
end
# p possible_palindrome("acabbaa")
# XD
| true |
50de42d977221d1a9320bc7e73c8ee52d1feac6d | Ruby | pogin503/online-judge | /aizu-online-judge/ruby/10002.rb | UTF-8 | 223 | 3.140625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#解法1
str = STDIN.gets.split(" ")
# p str
a = str[0].to_i;b = str[1].to_i
puts "#{a*b} #{a*2 + b*2}"
#解法2
STDIN.gets.split.map(&:to_i).tap { |i| a = i[0];b = i[1];puts "#{a*b} #{a*2 + b*2}" }
| true |
c8bec5688ee3711e58468b107c5c0e3f61c19172 | Ruby | SilverMaiden/Udacity-Nanodegree | /Nanodegree/CheckProfanity/check_profanity_rb/check_profanity.rb | UTF-8 | 591 | 3.078125 | 3 | [] | no_license | require 'net/http'
require 'json'
def read_text()
movie_quotes = File.read('/Volumes/Macintosh HD/Users/SilverMaiden/Downloads/movie_quotes.txt')
check_profanity(movie_quotes)
end
def check_profanity(text_to_check)
query = "select *"
url = "http://www.purgomalum.com/service/containsprofanity?text=" + text_to_check
response = Net::HTTP.get_response(URI.parse(url))
output = response.body
if output == "true"
puts "Profanity Alert!!!"
elsif output == "false"
puts "No Profanity Detected."
else
puts "Could Not Properly Check Document."
end
end
read_text | true |
6141c4cbeb2bc45841aef15ff829729a7a0cdfac | Ruby | calacademy-research/antcat | /app/services/taxt/cleanup.rb | UTF-8 | 608 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
module Taxt
class Cleanup
include Service
attr_private_initialize :taxt
def call
return if taxt.nil?
raise unless taxt.is_a?(String)
taxt.
gsub(/ +:/, ': '). # Spaces before colons.
gsub(/:(?!= )/, ': '). # Colons not followed by a space.
gsub(/(; +;)+/, ';'). # Double semicolons separated by spacing.
gsub(/(: +:)+/, ':'). # Double colons separated by spacing.
gsub(/(::)+/, ':'). # Double colons.
squish # Consecutive, and leading/trailing spaces.
end
end
end
| true |
3e55ac1acee5820aeb1f469213e62e98c4bd9209 | Ruby | alicht9/hangar_door_notifier | /garage.rb | UTF-8 | 2,005 | 2.9375 | 3 | [] | no_license | #!/usr/bin/ruby
#
# Copyright (c) Adam Licht alicht@gmail.com 2013
# All rights resereved
#
#
require 'pi_piper'
require 'mail'
require 'yaml'
require 'time'
include PiPiper
class Garage
def initialize config
@config_file=config
raise "You have to give me a config yml" unless @config_file
@config = YAML.load(File.read(@config_file))
$to = @config['TO']
mail_options = { :address => "smtp.gmail.com",
:port => 587,
:domain => 'localhost',
:user_name => @config['USER'],
:password => @config['PASSWORD'],
:authentication => 'plain',
:enable_starttls_auto => true }
Mail.defaults do
puts "Setting up E-Mail service"
delivery_method :smtp, mail_options
end
end
def setup_radio pin, led
watch ({:pin => pin, :trigger => :rising}) do
time = Time.now.localtime
puts "Pin #{pin} Changed from #{last_value} to #{value} at #{time}"
led.off
puts "Sending Emails"
$to.each do |email|
Mail.deliver do
to email
from 'Your_Garage_Door'
subject 'Hangar door'
body "Hangar door activated via radio. At #{time}"
end
end
sleep 5
led.on
end
end
def setup_internal pin, led
watch ({:pin => pin, :trigger => :rising}) do
time = Time.now.localtime
puts "Pin #{pin} Changed from #{last_value} to #{value} at #{time}"
led.off
puts "Sending Emails"
email = $to[0]
Mail.deliver do
to email
from 'Your_Garage_Door'
subject 'Hangar door'
body "Hangar door activated via INSIDE switch at #{time}."
end
sleep 5
led.on
end
end
def run
pins = {:led => 24, :radio => 18, :internal =>15}
pins.each do |key, value|
puts "#{key} is on pin #{value}"
end
led = PiPiper::Pin.new(:pin => pins[:led].to_i, :direction => :out)
led.on
setup_radio pins[:radio], led
setup_internal pins[:internal], led
puts 'watching input'
PiPiper.wait
end
end
g = Garage.new ARGV[0]
g.run
| true |
e71a6be29c4f56ac5a0c1c957dbd2f3d5d2b4c0e | Ruby | YaoZhang0916/Ruby | /oop/hash.rb | UTF-8 | 352 | 2.921875 | 3 | [] | no_license |
user = {first_name: "Coding", last_name: "Dojo"}
puts user[:first_name]
puts user[:last_name]
user.delete :last_name
puts user
user1 = {first_name: "Coding", last_name: "Dojo"}
puts user1.has_key? :first_name
user2 = {first_name: "Coding", last_name: "Dojo"}
puts user2.has_value? "Coding"
puts user2.has_value? "Bootcamp" | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.