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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
81e0f50f88fbd6b7e0ddf47fbb8ad335f073e18d
|
Ruby
|
namusyaka/mandrake
|
/lib/mandrake/dsl/stringify.rb
|
UTF-8
| 1,978
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
module Mandrake
module DSL
# A class for building an expression by using the method_missing method
# @example
# Oh = Class.new(Mandrake::DSL::Stringify)
# Oh.stringify.Mikey.hello('boy').to_s #=> "oh.Mikey.hello(\"boy\")"
# Oh.stringify.James.goodbye('man').to_s #=> "oh.James.goodbye(\"man\")"
# Oh.stringify.Mikey.hello('boy').and(Oh.stringify.James.goodbye('man')).to_s
# #=> "oh.Mikey.hello(\"boy\") && oh.James.goodbye(\"man\")"
# @!visibility private
class Stringify
# @!visibility private
def stringify
self.class.stringify
end
# @!visibility private
def self.stringify
Stringify::Relation.new(self)
end
# @!visibility private
class Relation
# Defines a method for the relation
# @param [String, Symbol] name
# @yield block on which to base the method
# @!visibility private
def self.chain(name, &block)
define_method(name){|*args| instance_exec(*args, &block); self; }
end
# @param [Class] klass
# @!visibility private
def initialize(klass)
@class = klass
reset_string
end
# Returns a string built by this class
# @!visibility private
def to_s
@string
end
chain(:[]) {|*args| @string << "[#{args.map(&:inspect) * ", "}]" }
chain(:==) {|value| @string << " == #{value.inspect}" }
chain(:and) {|relation| @string << " && " << relation.to_s }
chain(:or) {|relation| @string << " || " << relation.to_s }
chain(:method_missing) {|method_name, *args|
@string << ".#{method_name}"
@string << "(#{args.map(&:inspect) * ", "})" unless args.length.zero? }
chain(:reset_string) { @string = "#{@class.name.downcase.split(/::/).last}" }
alias equal ==
alias eq equal
end
end
end
end
| true
|
22ece5b63a7a2e15c8df662ebd10c393f7068a10
|
Ruby
|
learn-co-students/atl-bonus-lectures
|
/testify-052819/spec/gilded_rose_spec.rb
|
UTF-8
| 4,153
| 2.921875
| 3
|
[] |
no_license
|
require_relative 'spec_helper'
describe "Gilded Rose" do
it "should be able to tick a gilded rose" do
# given a gilded rose
rose = GildedRose.for("example", 20, 30)
# when i tick
rose.tick
# then i expect quality and sell_in to go down by one
expect(rose.sell_in).to eq(19)
expect(rose.quality).to eq(29)
end
it "should decreate quality by two on the sell date" do
rose = GildedRose.for("example", 0, 10)
rose.tick
expect(rose.quality).to eq(8)
expect(rose.sell_in).to eq(-1)
end
it "should decrease quality by two after the sell date" do
rose = GildedRose.for("example", -1, 10)
rose.tick
expect(rose.quality).to eq(8)
expect(rose.sell_in).to eq(-2)
end
it "should never reach negative quality" do
rose = GildedRose.for("example", 20, 0)
rose.tick
expect(rose.quality).to eq(0)
expect(rose.sell_in).to eq(19)
end
it "should lose two quality after the sell by date if it isn't brie" do
rose = GildedRose.for("example", 0, 12)
rose.tick
expect(rose.quality).to eq(10)
expect(rose.sell_in).to eq(-1)
end
it "should increase quality of aged brie when we tick" do
rose = GildedRose.for("Aged Brie", 20, 30)
rose.tick
expect(rose.quality).to eq(31)
expect(rose.sell_in).to eq(19)
end
it "should increase the quality of aged brie after the sell date" do
rose = GildedRose.for("Aged Brie", 0, 10)
rose.tick
expect(rose.quality).to eq(12)
expect(rose.sell_in).to eq(-1)
end
it "should cap quality for brie at 50" do
rose = GildedRose.for("Aged Brie", 20, 50)
rose.tick
expect(rose.quality).to eq(50)
expect(rose.sell_in).to eq(19)
end
it "should cap quality for brie at 50 even after the sell date" do
rose = GildedRose.for("Aged Brie", -1, 49)
rose.tick
expect(rose.quality).to eq(50)
expect(rose.sell_in).to eq(-2)
end
it "should increase quality for backstage passes" do
rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 20, 30)
rose.tick
expect(rose.quality).to eq(31)
expect(rose.sell_in).to eq(19)
end
it "should bump quality by 2 when sell_in is 10 or less for backstage passes" do
rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 10, 20)
rose.tick
expect(rose.quality).to eq(22)
expect(rose.sell_in).to eq(9)
end
it "should bump quality by 3 for passes when sell_in is 5 or less" do
rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 5, 20)
rose.tick
expect(rose.quality).to eq(23)
expect(rose.sell_in).to eq(4)
end
it "should not modify sulfuras, hand of ragnaros for any reason" do
rose = GildedRose.for("Sulfuras, Hand of Ragnaros", 20, 30)
rose.tick
expect(rose.quality).to eq(30)
expect(rose.sell_in).to eq(20)
end
it "should cap quality for passes at 50" do
rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 20, 50)
rose.tick
expect(rose.quality).to eq(50)
expect(rose.sell_in).to eq(19)
end
it "should set quality to zero for passes after their sell date" do
rose = GildedRose.for("Backstage passes to a TAFKAL80ETC concert", 0, 40)
rose.tick
expect(rose.quality).to eq(0)
expect(rose.sell_in).to eq(-1)
end
it "should lower quality by 2 for conjured mana cake" do
rose = GildedRose.for("Conjured Mana Cake", 5, 10)
rose.tick
expect(rose.quality).to eq(8)
expect(rose.sell_in).to eq(4)
end
it "should limit mana cake to a minimum quality of zero" do
rose = GildedRose.for("Conjured Mana Cake", 5, 0)
rose.tick
expect(rose.quality).to eq(0)
expect(rose.sell_in).to eq(4)
end
it "should drop quality by 4 on the sell date for mana cake" do
rose = GildedRose.for("Conjured Mana Cake", 0, 10)
rose.tick
expect(rose.quality).to eq(6)
expect(rose.sell_in).to eq(-1)
end
it "should drop quality by 4 after the sell date for mana cake" do
rose = GildedRose.for("Conjured Mana Cake", -1, 10)
rose.tick
expect(rose.quality).to eq(6)
expect(rose.sell_in).to eq(-2)
end
end
| true
|
9392672c36c6be328a331b73301b72162a3b1223
|
Ruby
|
tnishi/rdf-config
|
/bin/rdf-config
|
UTF-8
| 3,025
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'getoptlong'
require 'rdf-config'
def help
puts DATA.read
exit
end
opts = {
:config_dir => nil,
:mode => nil,
}
args = GetoptLong.new(
[ '--config', '-c', GetoptLong::REQUIRED_ARGUMENT ],
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--senbero', GetoptLong::NO_ARGUMENT ],
[ '--schema', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--sparql', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--query', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--sparqlist', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--grasp', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--stanza', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--stanza_rb', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--shex', GetoptLong::OPTIONAL_ARGUMENT ]
)
begin
args.each_option do |name, value|
case name
when /--config/
opts[:config_dir] = value
when /--senbero/
opts[:mode] = :senbero
when /--schema/
opts[:mode] = :chart
opts[:schema_opt] = value
when /--sparqlist/
opts[:mode] = :sparqlist
when /--sparql/
opts[:mode] = :sparql
opts[:sparql_query_name] = value
when /--query/
# pipe to https://gist.github.com/ktym/3385134 ?
opts[:mode] = :query
when /--grasp/
opts[:mode] = :grasp
when /--stanza_rb/
opts[:mode] = :stanza_rb
opts[:stanza_name] = value
when /--stanza/
opts[:mode] = :stanza_js
opts[:stanza_name] = value
when /--shex/
opts[:mode] = :shex
end
end
rescue
puts
help
exit(1)
end
if opts[:config_dir] and opts[:mode]
begin
rdf_config = RDFConfig.new(opts)
rdf_config.exec(opts)
rescue => e
STDERR.puts e.message
exit(1)
end
else
help
end
__END__
NAME
rdf-config -- RDF model to SPARQL, Schema, Stanza converter
SYNOPSIS
rdf-config --help
rdf-config --config path/to/config/name --sparql [queryname]
rdf-config --config path/to/config/name --schema
rdf-config --config path/to/config/name --senbero
rdf-config --config path/to/config/name --grasp
rdf-config --config path/to/config/name --stanza [stanzaname]
rdf-config --config path/to/config/name --stanza_rb [stanzaname]
rdf-config --config path/to/config/name --shex
DESCRIPTION
Read a RDF data model from config/name/ directory
then generate SPARQL query, exec SPARQL query,
generate Schema chart, and generate Stanza.
Configuration files of a RDF model are written
in the YAML format.
* config/name/model.yaml: RDF deta model structure and variable names
* config/name/endpoint.yaml: SPARQL endpoint
* config/name/prefix.yaml: URI prefixes
* config/name/sparql.yaml: SPARQL definition
* config/name/stanza.yaml: TogoStanza definition
* config/name/metadata.yaml: Metadata compatible with NBRC RDF portal
* config/name/metadata_ja.yaml: Japanese version of Metadata
| true
|
3f674d63b7e56e22080b9acdc71849957b420c49
|
Ruby
|
jgrazulis/1module
|
/Challenges/mid_mod/spec/term_spec.rb
|
UTF-8
| 1,298
| 3.171875
| 3
|
[] |
no_license
|
require './lib/course'
require './lib/student'
require './lib/term'
describe 'Term class' do
it 'exists' do
calculus = Course.new("Calculus", 2)
term = Term.new("Winter 2018", [calculus])
expect(term).to be_an_instance_of(Term)
end
it 'has attributes' do
calculus = Course.new("Calculus", 2)
term = Term.new("Winter 2018", [calculus])
expect(term.name).to eq("Winter 2018")
expect(term.courses).to eq([calculus])
end
end
describe 'courses in term' do
it 'lists open courses' do
calculus = Course.new("Calculus", 2)
coding_101 = Course.new("coding_101", 3)
term = Term.new("Winter 2018", [calculus, coding_101])
student1 = Student.new({name: "Morgan", age: 21})
student2 = Student.new({name: "Jordan", age: 29})
calculus.enroll(student1)
calculus.enroll(student2)
expect(term.open_courses).to eq([coding_101])
end
it 'has a list of students' do
student1 = Student.new({name: "Morgan", age: 21})
student2 = Student.new({name: "Jordan", age: 29})
calculus = Course.new("Calculus", 2)
coding_101 = Course.new("coding_101", 3)
term = Term.new("Winter 2018", [calculus, coding_101])
calculus.enroll(student1)
calculus.enroll(student2)
expect(term.students).to eq([student1, student2])
end
end
| true
|
f13ee1d4948e4e15bc9f229a3f9220f63dbb473b
|
Ruby
|
wuhuizuo/SCTM
|
/tech_demos/sf_parser.rb
|
UTF-8
| 764
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'sf_baidu_parser'
module Sctm
class SfParser
SF_SITES = {
baidu: 'http://rj.baidu.com/'
}
SF_PARSERS = {
baidu: SfBaiduParser
}
# @param [String] sf_center 软件中心类别
def initialize(sf_center = :baidu)
@sf_main_url = SF_SITES[sf_center]
@parser = SF_PARSERS[sf_center].new(@sf_main_url)
end
# 获取软件大类的分类
def get_groups
@parser.get_groups
end
# 获取指定类别下的软件列表
def get_apps(group, limit = -1)
@parser.get_apps(group, limit)
end
# 获取应用信息
# @param [String] app_name 查询应用名称
def get_app_detail(app_name)
@parser.get_app_detail(app_name)
end
end
end
| true
|
ca1a0cd2550e51864aec8fdf493580b1c8c743a6
|
Ruby
|
baggio63446333/mrubyc
|
/examples/ledswitch/ledswitch.rb
|
UTF-8
| 258
| 2.640625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
val = 0
portled = 64
portsw = 33
pin_mode(portsw, 0);
while true
if val == 1
val = 0
else
val = 1
end
if digital_read(portsw) == 0
portled += 1
if portled > 67
break
end
end
digital_write(portled, val)
sleep 1
end
| true
|
13f868dc9a62b82335f818310bde77e227dc2270
|
Ruby
|
jtblow/oxford-comma-chicago-web-career-040119
|
/lib/oxford_comma.rb
|
UTF-8
| 237
| 3.4375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def oxford_comma(array)
if array.length === 1
array.join
elsif array.length === 2
array.join(" and ")
elsif array.length === 3
array[0..1].join(", ") + ", and " + array[2]
else
array[0..-2].join(", ") + ", and " + array[-1]
end
end
| true
|
e9d1f4086f04670e6fc268a8a90938c7b845169e
|
Ruby
|
ttt242242/fx
|
/rubyOkn/EasyGraphMaker.rb
|
UTF-8
| 1,009
| 2.5625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
$LOAD_PATH.push(File::dirname($0)) ;
require "pry"
require "gnuplot"
Gnuplot.open do |gp|
Gnuplot::Plot.new( gp ) do |plot|
plot.output "test.eps"
plot.set 'terminal postscript 16 eps enhanced color ' #必要epsで保存するには
plot.size "1,0.8"
plot.origin "0.0, 0.0"
plot.grid
x = (0..50).collect {|v| v.to_f}
c = 10.0 ;
array = Array.new
array2 = Array.new
x.each do |x1|
# y = (1.0/(1.0+x1/35.0)) ;
# y = (1.0/(1.0+x1/5.0)) ;
y = x1 * Math.exp(-x1/c) ;
array.push(y) ;
if x1 <= c
y = x1
else
y = c * Math.exp(-x1/c) ;
end
array2.push(y) ;
end
plot.data << Gnuplot::DataSet.new( [x,array] ) do |ds|
ds.with = "lp" #line+point
ds.linewidth =1
ds.title = "test" ;
end
plot.data << Gnuplot::DataSet.new( [x,array2] ) do |ds|
ds.with = "lp" #line+point
ds.linewidth =1
ds.title
end
end
end
| true
|
88ee7b0e687ee11fe9db36bd611cad694ff29f2e
|
Ruby
|
jdun10/phase-0
|
/week-5/die-class/my_solution.rb
|
UTF-8
| 1,464
| 4.59375
| 5
|
[
"MIT"
] |
permissive
|
# Die Class 1: Numeric
# I worked on this challenge by myself.
# I spent [] hours on this challenge.
# 0. Pseudocode
# Input: calling the method
# Output: a number 1-6
# Steps: There will be a function that goes from 1-6 and selects a number.
# A random number will be returned.
# 1. Initial Solution
# class Die
# def initialize
# die = Die.new(6) #This creates a new die object with 6 sides
# end
# def sides
# die.sides == 6 # returns 6
# end
# def roll
# die.roll # returns a random number between 1 and 6
# puts rand(6) + 1
# end
# end
# def roll;
# 3. Refactored Solution
def roll
puts rand(6) +1
end
roll
# 4. Reflection
# What is an ArgumentError and why would you use one?
# => I don't understand how to use Classes and how the other methods within a class relate to another method.
# What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
# => The rand method was new to me but pretty simply used to generate a number from 1 to 6.
# What is a Ruby class?
# => Something that stores other methods in a group.
# Why would you use a Ruby class?
# => I don't know.
# What is the difference between a local variable and an instance variable?
# => A local variable is only applicable within its defined method. An instance variable is applicable within its Class.
# Where can an instance variable be used?
# => It can be used within its Class.
| true
|
1f6c762f6bed9414e1115d70732b57dfead768de
|
Ruby
|
escobara/ro_design_patterns
|
/strategy_pattern/strategy_v1.rb
|
UTF-8
| 1,049
| 3.71875
| 4
|
[] |
no_license
|
class Formatter
def output_report(title, text)
raise 'Abstract method called'
end
end
class HTMLFormatter < Formatter
def output_report(title, content)
puts('<html>')
puts(' <head>')
puts(" <title> #{title} </title>")
puts(' </head>')
puts(' </body>')
content.each do |line|
puts(" <p>#{line}</p>")
end
puts(' </body>')
puts('</html>')
end
end
class PlainTextFormatter < Formatter
def output_report(title, text)
puts("***** #{title} *****")
text.each do |line|
puts(line)
end
end
end
class Report
attr_reader :title, :content
attr_accessor :formatter
def initialize(formatter)
@title = 'Monthly Report'
@content = [ 'Things are going', 'really, really well.']
@formatter = formatter
end
def output_report
@formatter.output_report(@title, @content)
end
end
report = Report.new(HTMLFormatter.new)
report.output_report
# <html>
# <head>
# <title> Monthly Report </title>
# </head>
# </body>
# <p>Things are going</p>
# <p>really, really well.</p>
# </body>
# </html>
| true
|
58f12cf64c1adc27327c2b99c035acda9ac9f1de
|
Ruby
|
jinhale/viper
|
/spec/make_bindings_spec.rb
|
UTF-8
| 3,201
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# make_bindings_spec.rb - specs for make_bindings
require_relative 'spec_helper'
describe 'make_bindings returns a key inserter proc for letters' do
let(:buf) { Buffer.new '' }
let(:bind) { make_bindings }
let(:prc) { bind[:key_p] }
subject { prc.call(buf); buf.to_s }
specify { subject.must_equal 'p' }
end
describe 'inserter for caps' do
let(:buf) { Buffer.new '' }
let(:bind) { make_bindings }
let(:prc) { bind[:key_A] }
subject { prc.call(buf); buf.to_s }
specify { subject.must_equal 'A' }
end
describe 'inserter 0' do
let(:buf) { Buffer.new '' }
let(:bind) { make_bindings }
let(:prc) { bind[:key_0] }
subject { prc.call(buf); buf.to_s }
specify { subject.must_equal '0' }
end
describe 'special chars :space' do
let(:buf) { Buffer.new '' }
let(:bind) { make_bindings }
let(:prc) { bind[:space] }
subject { prc.call(buf); buf.to_s }
specify { subject.must_equal ' ' }
end
describe 'ctrl_z cannot undo' do
let(:buf) { ReadOnlyBuffer.new 'yyy' }
let(:bind) { make_bindings }
let(:prc) { bind[:ctrl_z] }
subject { buf.ins 'xxx'; prc.call(buf); buf.to_s }
specify { subject.must_equal 'yyy' }
end
describe 'Can undo insert' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:ctrl_z] }
subject { buf.ins 'xxx'; prc.call(buf); buf.to_s }
specify { subject.must_equal '' }
end
class CannotRecordMe < Buffer
include NonRecordable
end
describe 'ReadOnlyBuffer cannot redo from ctrl_u' do
let(:buf) { CannotRecordMe.new '' }
let(:bind) { make_bindings }
let(:prc) { bind[:ctrl_u] }
subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s }
specify { subject.must_equal 'xxx' }
end
describe 'Can redo undon action from proc in bindings' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:ctrl_u] }
subject { buf.ins 'xxx'; buf.undo; prc.call(buf); buf.to_s }
specify { subject.must_equal 'xxx' }
end
describe 'backspace if mark set' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:backspace] }
subject { buf.ins 'xxxxx'; buf.beg; buf.set_mark; buf.fwd 3; prc.call(buf); $clipboard }
specify { subject.must_equal 'xxx' }
end
describe 'backspace when no mark set' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:backspace] }
subject { buf.ins 'xyz'; prc.call(buf); buf.to_s }
specify { subject.must_equal 'xy' }
end
describe 'fn_4 sets mark when not set' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:fn_4] }
subject { buf.ins 'zzz'; buf.beg; prc.call(buf); buf.mark_set? }
specify { subject.must_equal true }
end
describe 'fn_4 unsets mark when set' do
let(:buf) { ScratchBuffer.new }
let(:bind) { make_bindings }
let(:prc) { bind[:fn_4] }
subject { buf.ins 'zzz'; buf.beg; buf.set_mark; buf.fwd; prc.call(buf); buf.mark_set? }
specify { subject.must_equal false }
end
describe 'ctrl_w move word fwd' do
let(:buf) { Buffer.new '0123 4567' }
let(:bind) { make_bindings }
let(:prc) { bind[:ctrl_w] }
subject { prc.call buf; buf.word_fwd }
specify { subject.must_equal '4567' }
end
| true
|
bbf2df7fd953a34af26d3bd6dcf2081f9997dece
|
Ruby
|
GaronHock/Homework
|
/octopus problems/octopus.rb
|
UTF-8
| 2,094
| 4.3125
| 4
|
[] |
no_license
|
# A Very Hungry Octopus wants to eat the longest fish in an array of fish.
# ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']
# => "fiiiissshhhhhh"
# Sluggish Octopus
# Find the longest fish in O(n^2) time. Do this by comparing all fish lengths to all other fish lengths
def sluggish_octopus(arr)
longest = Hash.new(0)
arr.each_with_index do |ele, i|
longest[ele] = arr[i].length
end
sorted = longest.sort_by{|k,v| v}
sorted[-1][0]
end
# fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']
# p sluggish_octopus(fish)
# Dominant Octopus
# Find the longest fish in O(n log n) time. Hint: You saw a sorting algorithm that runs
# in O(n log n) in the Sorting Complexity Demo. Remember that Big O is classified by the dominant term
class Array
# Write an Array#merge_sort method; it should not modify the original array.
def dominant_octopus_merge_sort(&prc)
prc ||= Proc.new{|a,b| a<=>b}
return self if self.length < 2
mid = self.length / 2
left = self.take(mid)
right = self.drop(mid)
sorted_left = left.dominant_octopus_merge_sort(&prc)
sorted_right = right.dominant_octopus_merge_sort(&prc)
Array.merge(sorted_left,sorted_right, &prc)
end
private
def self.merge(left, right, &prc)
sorted = []
until left.empty? || right.empty?
if prc.call(left.first.length, right.first.length) == -1
sorted << left.shift
else
sorted << right.shift
end
end
sorted + left + right
end
end
fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']
p fish.dominant_octopus_merge_sort
# Clever Octopus
# Find the longest fish in O(n) time.
# The octopus can hold on to the longest fish that you have found so far
# while stepping through the array only once.
def clever_octopus(arr)
longest = ""
arr.each do |ele|
if ele.length > ele.length - 1
longest = ele
end
end
longest
end
p clever_octopus(fish)
| true
|
0db0691ddf25e2d2defd21cdc610a551066fa4ba
|
Ruby
|
nekokat/codewars
|
/8 kyu_1/grasshopper-make-change.rb
|
UTF-8
| 184
| 2.90625
| 3
|
[
"Unlicense"
] |
permissive
|
#Kata: Grasshopper - Make change
#URL: https://www.codewars.com/kata/560dab9f8b50f89fd6000070
money = 10
candy = 1.42
chips = 2.4
soda = 1
change = money - candy - chips - soda
| true
|
c34128da13a2d380e31235d24fd7b329eda8608e
|
Ruby
|
denisson/BibliaSocial
|
/config/initializers/integer.rb
|
UTF-8
| 86
| 2.6875
| 3
|
[] |
no_license
|
class Integer
def quantos()
return self.to_s if self > 0
return ""
end
end
| true
|
2ddeb8f002933e7714a4b2c0a1679aadf627540e
|
Ruby
|
DiegoSalazar/template_parsing_challenge
|
/template_parser.rb
|
UTF-8
| 1,587
| 3.5
| 4
|
[] |
no_license
|
# Given a template and an environment, fill the template with correct values.
class TemplateParser
IF_TAG = ?# # prefix for if tags
UNLESS_TAG = ?^ # prefix for unless tags
NIL_VAR = ''
TAG_CAPTURE = /
{(.+)} # capture an opening tag
(.+) # capture content after opening tag
{(\1)} # capture tag matching first capture
| # or
{(.+)} # capture just a tag
/x
# @param environment
# a hash of values to interpolate into templates
def initialize(environment)
@environment = environment
end
# @param template
# a string template
# @return an interpolated string
def parse(template)
@template = template.dup
interpolate_environment while contains_tags?
@template
end
private
def contains_tags?
@template =~ TAG_CAPTURE
end
def interpolate_environment
match, tag, content, _, variable = TAG_CAPTURE.match(@template).to_a
return if match.nil?
interpolate_variable match, variable if variable
interpolate_tags match, tag, content if tag
end
def interpolate_variable(match, variable)
@template.gsub! match, @environment.fetch(variable.downcase.to_sym, NIL_VAR)
end
def interpolate_tags(match, tag, content)
symbol = tag.sub(/[#{IF_TAG}#{UNLESS_TAG}]/, NIL_VAR).downcase.to_sym
@template.gsub! match, if tag =~ /#{IF_TAG}/
@environment[symbol] ? content : NIL_VAR
elsif tag =~ /#{UNLESS_TAG}/
@environment[symbol] ? NIL_VAR : content
end.strip
end
end
| true
|
d2d00f06487a04f9ba0670fcdddac562085fae68
|
Ruby
|
juanlfr/tests-ruby
|
/lib/03_basics.rb
|
UTF-8
| 484
| 3.390625
| 3
|
[] |
no_license
|
def who_is_bigger(a,b,c)
if a==nil || b==nil || c==nil then return "nil detected"
elsif a==[a,b,c].max then return("a is bigger")
elsif b==[a,b,c].max then return("b is bigger")
else return("c is bigger")
end
end
def reverse_upcase_noLTA(string)
return string.reverse.upcase.delete 'LTA'
end
def array_42(array)
if array.count(42)>0 then return true else return false
end
end
def magic_array(array)
return array.flatten.sort.map{|x| x*=2}.reject{|x| x%3==0}.uniq
end
| true
|
8c307273ee2e549fec139bae0c9ab6e6bcdf8620
|
Ruby
|
narayana1208/git-review
|
/lib/git-review/local.rb
|
UTF-8
| 7,733
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
module GitReview
# The local repository is where the git-review command is being called
# by default. It is (supposedly) able to handle systems other than Github.
# TODO: remove Github-dependency
class Local
include ::GitReview::Internals
attr_accessor :config
# acts like a singleton class but it's actually not
# use ::GitReview::Local.instance everywhere except in tests
def self.instance
@instance ||= new
end
def initialize
# find root git directory if currently in subdirectory
if git_call('rev-parse --show-toplevel').strip.empty?
raise ::GitReview::InvalidGitRepositoryError
else
add_pull_refspec
load_config
end
end
# @return [Array<String>] all existing branches
def all_branches
git_call('branch -a').split("\n").collect { |s| s.strip }
end
# @return [Array<String>] all open requests' branches shouldn't be deleted
def protected_branches
github.current_requests.collect { |r| r.head.ref }
end
# @return [Array<String>] all review branches with 'review_' prefix
def review_branches
all_branches.collect { |branch|
# only use uniq branch names (no matter if local or remote)
branch.split('/').last if branch.include?('review_')
}.compact.uniq
end
# clean a single request's obsolete branch
def clean_single(number, force=false)
request = github.pull_request(source_repo, number)
if request && request.state == 'closed'
# ensure there are no unmerged commits or '--force' flag has been set
branch_name = request.head.ref
if unmerged_commits?(branch_name) && !force
puts "Won't delete branches that contain unmerged commits."
puts "Use '--force' to override."
else
delete_branch(branch_name)
end
end
rescue Octokit::NotFound
false
end
# clean all obsolete branches
def clean_all
(review_branches - protected_branches).each do |branch_name|
# only clean up obsolete branches.
delete_branch(branch_name) unless unmerged_commits?(branch_name, false)
end
end
# delete local and remote branches that match a given name
# @param branch_name [String] name of the branch to delete
def delete_branch(branch_name)
delete_local_branch(branch_name)
delete_remote_branch(branch_name)
end
# delete local branch if it exists.
# @param (see #delete_branch)
def delete_local_branch(branch_name)
if branch_exists?(:local, branch_name)
git_call("branch -D #{branch_name}", true)
end
end
# delete remote branch if it exists.
# @param (see #delete_branch)
def delete_remote_branch(branch_name)
if branch_exists?(:remote, branch_name)
git_call("push origin :#{branch_name}", true)
end
end
# @param location [Symbol] location of the branch, `:remote` or `:local`
# @param branch_name [String] name of the branch
# @return [Boolean] whether a branch exists in a specified location
def branch_exists?(location, branch_name)
return false unless [:remote, :local].include?(location)
prefix = location == :remote ? 'remotes/origin/' : ''
all_branches.include?(prefix + branch_name)
end
# @return [Boolean] whether there are local changes not committed
def uncommitted_changes?
!git_call('diff HEAD').empty?
end
# @param branch_name [String] name of the branch
# @param verbose [Boolean] if verbose output
# @return [Boolean] whether there are unmerged commits on the local or
# remote branch.
def unmerged_commits?(branch_name, verbose=true)
locations = []
locations << '' if branch_exists?(:local, branch_name)
locations << 'origin/' if branch_exists?(:remote, branch_name)
locations = locations.repeated_permutation(2).to_a
if locations.empty?
puts 'Nothing to do. All cleaned up already.' if verbose
return false
end
# compare remote and local branch with remote and local master
responses = locations.collect { |loc|
git_call "cherry #{loc.first}#{target_branch} #{loc.last}#{branch_name}"
}
# select commits (= non empty, not just an error message and not only
# duplicate commits staring with '-').
unmerged_commits = responses.reject { |response|
response.empty? or response.include?('fatal: Unknown commit') or
response.split("\n").reject { |x| x.index('-') == 0 }.empty?
}
# if the array ain't empty, we got unmerged commits
if unmerged_commits.empty?
false
else
puts "Unmerged commits on branch '#{branch_name}'."
true
end
end
# @return [Boolean] whether there are commits not in target branch yet
def new_commits?(upstream=false)
target = upstream ? 'upstream/master' : target_branch
not git_call("cherry #{target}").empty?
end
# @return [Boolean] whether a specified commit has already been merged.
def merged?(sha)
branches = git_call("branch --contains #{sha} 2>&1").split("\n").
collect { |b| b.delete('*').strip }
branches.include?(target_branch)
end
# @return [String] the source repo
def source_repo
github.source_repo
end
# @return [String] the current source branch
def source_branch
git_call('branch').chomp.match(/\*(.*)/)[0][2..-1]
end
# @return [String] combine source repo and branch
def source
"#{source_repo}/#{source_branch}"
end
# @return [String] the name of the target branch
def target_branch
# TODO: Manually override this and set arbitrary branches
ENV['TARGET_BRANCH'] || 'master'
end
# if to send a pull request to upstream repo, get the parent as target
# @return [String] the name of the target repo
def target_repo(upstream=false)
# TODO: Manually override this and set arbitrary repositories
if upstream
github.repository(source_repo).parent.full_name
else
source_repo
end
end
# @return [String] combine target repo and branch
def target
"#{target_repo}/#{target_branch}"
end
# @return [String] the head string used for pull requests
def head
# in the form of 'user:branch'
"#{source_repo.split('/').first}:#{source_branch}"
end
# @return [Boolean] whether already on a feature branch
def on_feature_branch?
# If current and target are the same, we are not on a feature branch.
# If they are different, but we are on master, we should still to switch
# to a separate branch (since master makes for a poor feature branch).
source_branch != target_branch && source_branch != 'master'
end
# add remote.origin.fetch to check out pull request locally
# see {https://help.github.com/articles/checking-out-pull-requests-locally}
def add_pull_refspec
refspec = '+refs/pull/*/head:refs/remotes/origin/pr/*'
fetch_config = "config --local --add remote.origin.fetch #{refspec}"
git_call(fetch_config, false) unless config_list.include?(refspec)
end
def load_config
@config = {}
config_list.split("\n").each do |line|
key, value = line.split(/=/, 2)
if @config[key] && @config[key] != value
@config[key] = [@config[key]].flatten << value
else
@config[key] = value
end
end
@config
end
def config_list
git_call('config --list', false)
end
def github
@github ||= ::GitReview::Github.instance
end
end
end
| true
|
a7bfa377d2cfb9f91d417b9ca3f1e819cfe876ec
|
Ruby
|
awesome/coffeelint-ruby
|
/lib/coffeelint.rb
|
UTF-8
| 2,640
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
require "coffeelint/version"
require 'execjs'
require 'coffee-script'
require 'json'
module Coffeelint
require 'coffeelint/railtie' if defined?(Rails::Railtie)
def self.path()
@path ||= File.expand_path('../../coffeelint/lib/coffeelint.js', __FILE__)
end
def self.colorize(str, color_code)
"\e[#{color_code}m#{str}\e[0m"
end
def self.red(str, pretty_output = true)
pretty_output ? Coffeelint.colorize(str, 31) : str
end
def self.green(str, pretty_output = true)
pretty_output ? Coffeelint.colorize(str, 32) : str
end
def self.context
coffeescriptSource = File.read(CoffeeScript::Source.path)
bootstrap = <<-EOF
window = {
CoffeeScript: CoffeeScript,
coffeelint: {}
};
EOF
coffeelintSource = File.read(Coffeelint.path)
ExecJS.compile(coffeescriptSource + bootstrap + coffeelintSource)
end
def self.lint(script, config = {})
if !config[:config_file].nil?
fname = config.delete(:config_file)
config.merge!(JSON.parse(File.read(fname)))
end
Coffeelint.context.call('window.coffeelint.lint', script, config)
end
def self.lint_file(filename, config = {})
Coffeelint.lint(File.read(filename), config)
end
def self.lint_dir(directory, config = {})
retval = {}
Dir.glob("#{directory}/**/*.coffee") do |name|
retval[name] = Coffeelint.lint_file(name, config)
yield name, retval[name] if block_given?
end
retval
end
def self.display_test_results(name, errors, pretty_output = true)
good = pretty_output ? "\u2713" : 'Passed'
bad = pretty_output ? "\u2717" : 'Failed'
if errors.length == 0
puts " #{good} " + Coffeelint.green(name, pretty_output)
return true
else
puts " #{bad} " + Coffeelint.red(name, pretty_output)
errors.each do |error|
print " #{bad} "
print Coffeelint.red(error["lineNumber"], pretty_output)
puts ": #{error["message"]}, #{error["context"]}."
end
return false
end
end
def self.run_test(file, config = {})
pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true
result = Coffeelint.lint_file(file, config)
Coffeelint.display_test_results(file, result, pretty_output)
end
def self.run_test_suite(directory, config = {})
pretty_output = config.has_key?(:pretty_output) ? config.delete(:pretty_output) : true
success = true
Coffeelint.lint_dir(directory, config) do |name, errors|
result = Coffeelint.display_test_results(name, errors, pretty_output)
success = false if not result
end
success
end
end
| true
|
effb7076c4fbcdc3d9008231e1b1515d0720ca05
|
Ruby
|
Maikon/learn_ruby_hard_zed
|
/ex9.rb
|
UTF-8
| 652
| 4
| 4
|
[] |
no_license
|
# Here's some new strange stuff, remember type it exaxctly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: ", days # will print the list of days in a row
puts "Here are the months: ", months # will print the list of months each one on its own line,
# because of the \n (newline) character
puts <<PARAGRAPH # beginning of the paragraph
There's something going on here.
With the PARAGRAPH thing
We'll be able to type as much as we like. # everything between here gets converted
Even 4 lines if we want, or 5, or 6. # into a string. Correct?
PARAGRAPH # end of the paragraph
| true
|
bc239ddffaa4c0b07f1b9fde83ce53a8e30e0c27
|
Ruby
|
yuta-pharmacy2359/ruby_tutorial
|
/第6章/Sample6_3_2.rb
|
UTF-8
| 1,118
| 3.515625
| 4
|
[] |
no_license
|
text = <<-TEXT
島原の乱は1637年12月11日に発生し、1638年4月12日に終結しました。
TEXT
p text.scan(/\d+年\d+月\d+日/)
# ["1637年12月11日", "1638年4月12日"]
p text.scan(/(\d+)年(\d+)月(\d+)日/)
# [["1637", "12", "11"], ["1638", "4", "12"]]
text = '本能寺の変は1582年6月21日に発生しました。'
m = /(\d+)年(\d+)月(\d+)日/.match(text)
puts m[0]
# 1582年6月21日
puts m[1]
# 1582
puts m[2]
# 6
puts m[3]
# 21
p m[2, 2]
# ["6", "21"]
puts m[-1]
# 21
p m[1..3]
# ["1582", "6", "21"]
p m
# #<MatchData "1582年6月21日" 1:"1582" 2:"6" 3:"21">
p /(\d+)年(\d+)月(\d+)日/.match('honnouji')
# nil
m = text.match(/(\d+)年(\d+)月(\d+)日/)
p m
# #<MatchData "1582年6月21日" 1:"1582" 2:"6" 3:"21">
text1 = 'ペリーは1853年7月8日に浦賀沖に来航しました。'
text2 = '聖徳太子は574年に生まれました。'
def ymd(text)
if m = /(\d+)年(\d+)月(\d+)日/.match(text)
'マッチしました'
else
'マッチしませんでした'
end
end
puts ymd(text1)
# マッチしました
puts ymd(text2)
# マッチしませんでした
| true
|
1ff0aa7efb560a26e4bd3aeb701915f6f27f284d
|
Ruby
|
clone18476/ghibli_cli
|
/lib/api.rb
|
UTF-8
| 1,237
| 3.5
| 4
|
[] |
no_license
|
class API
# NOTE: all of your API methods should be class methods
def self.fetch_films
url = "https://ghibliapi.herokuapp.com/films/"
uri = URI(url)
response = Net::HTTP.get(uri)
films_array = JSON.parse(response)
# each hash represents a film, and we want to initialize a new drink for each hash
# !!!! it's important that we're making objects (instances) with our api data
# access one hash at a time to make an instance out of one hash at a time by ITERATING (as seen below)
films_array.each do |film_hash|
film = Film.new # THIS IS WHERE WE MAKE A NEW 'film' INSTANCE
film.title = film_hash["title"] # assigning the title of the film as a part of our film object
film.director = film_hash["director"] # and so on, and so forth
film.producer = film_hash["producer"]
film.release_date = film_hash["release_date"]
film.run_time = film_hash["running_time"]
film.characters = film_hash["people"]
film.species = film_hash["species"]
film.location = film_hash["location"]
film.vehicles = film_hash["vehicles"]
end
end
end
| true
|
de2951aac31a02c0994cf3ae0c3c48b1e1669b8f
|
Ruby
|
HMJospeh/ruby-gets-input-v-000
|
/bin/greeting
|
UTF-8
| 266
| 3.515625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#!/usr/bin/env ruby
require_relative '../lib/hello_ruby_programmer.rb'
puts "What's happening! Welcome to the wonderful world of Ruby programming."
puts "Let's get this game started!! Type in your name so we can get things going:"
name = gets.strip
greeting(name)
| true
|
c6d5d74f9e4289dbaf42af53dbce87f80124107d
|
Ruby
|
MattStopa/Coding-Casts-Code
|
/modules/2_organizing/modules.rb
|
UTF-8
| 689
| 3.828125
| 4
|
[] |
no_license
|
class Loan
attr_accessor :balance_owed, :maturity_months, :interest_rate
def owed_by_month
balance_owed / maturity_months
end
def print_balance
"Your balance is: #{balance_owed}"
end
def years_left_to_maturity
maturity_months / 12
end
def print_estimated_cost_per_day
"The cost per day of your loan is roughly: $#{owed_by_month / 30}"
end
def cost_of_interest
owed_by_month * interest_rate
end
end
loan = Loan.new
loan.balance_owed = 2000
loan.maturity_months = 10
loan.interest_rate = 0.01
puts loan.owed_by_month
puts loan.years_left_to_maturity
puts loan.cost_of_interest
puts loan.print_balance
puts loan.print_estimated_cost_per_day
| true
|
becf18b0371e36657b66589b78d47bb33a8a557b
|
Ruby
|
thallam/odin_ruby
|
/advanced_building_blocks/lib/bubble_sort.rb
|
UTF-8
| 585
| 3.640625
| 4
|
[] |
no_license
|
require 'pry'
def bubble_sort(arr)
binding.pry
arr.length.times do
arr.each_with_index do |item, index|
next_item = arr[index+1]
if next_item < item
temp = item
item = next_item
next_item = temp
# because a,b = b,a doesn't work
end
end
end
end
=begin
For each element in the list look at the next element.
If it's a lower value, swap them around
Continue until it is ordered
Notes: Idiomatic switch below doesn't work. Next val gets nil.. Why?
next_item, value = value, next_value if next_item < item
=end
| true
|
6157a36f3bbae3622f42217ae9a5909ce5bafb41
|
Ruby
|
justJosh1004/AcademyPGH
|
/Template Engine/Mad Libs.rb
|
UTF-8
| 518
| 2.828125
| 3
|
[] |
no_license
|
require './lib/template_engine'
#require './Star Wars.txt'
mad_lib = Template_reader.new
mad_lib.set_template(File.read('.\Star Wars.txt'))
get_template = []
user_answers = []
get_template = mad_lib.get_template_fields
i = 0
while i < get_template.length
puts "Type in a #{get_template[i]}: "
user_answers << gets.chomp
i += 1
end
p get_template
p user_answers
completed_hash = mad_lib.make_hash(get_template, user_answers)
p completed_hash
madlib_done = mad_lib.run_template(completed_hash)
p madlib_done
| true
|
1b404bb086eacad4bea7e6eb9915d54c469a4dcf
|
Ruby
|
Sancbella/jumpstart-app
|
/Basics/orangetree.rb
|
UTF-8
| 1,841
| 4.03125
| 4
|
[] |
no_license
|
class OrangeTree
def initialize
@height = 120
@age = 0
@name = 'Mr.Orange'
@orangeProduction = 0
puts 'Mr.Orange is born'
end
def oneYearPasses number
if number <= 0
puts 'no time has passed'
elsif
@age = @age + (1*number)
@height = @height + (30*number)
puts 'Orangie is now ' + @age.to_s + ' years old'
if @age >= 15
puts 'Mr. Orange is dead, RIP Mr.Orange, but say hello to Baby Orange'
@age = 0
@height = 0
elsif @age == 2
puts 'Baby Orange is now Mr. Orange and produced 1 orange!'
@orangeProduction = 1
elsif @age >= 3 and @age <= 15
@orangeProduction = @orangeProduction + 1 + rand(6) * number
puts 'This year Mr. Orange produced ' + @orangeProduction.to_s + ' oranges!'
end
end
end
def countTheOranges
if @orangeProduction == 0
puts 'There are no oranges, he\'s just a baby!'
elsif @orangeProduction == 1
puts 'Mr.Orange produced 1 oranges'
elsif @orangeProduction > 1
puts 'There are ' + @orangeProduction.to_s + 'Oranges'
end
end
def pickAnOrange number
puts 'There were ' + @orangeProduction.to_s + ' Oranges. It was super delicious!'
puts 'You\'ve picked ' + number.to_s + ' oranges'
puts 'Now there are ' + (@orangeProduction - number).to_s + ' left'
@orangeProduction - number
end
end
orangie = OrangeTree.new
orangie.oneYearPasses(1)
orangie.oneYearPasses(1)
orangie.oneYearPasses(3)
orangie.oneYearPasses(4)
orangie.oneYearPasses(2)
orangie.oneYearPasses(100)
orangie.oneYearPasses(0)
orangie.oneYearPasses(14)
orangie.pickAnOrange(5)
| true
|
2243b12cf8463297ae639c97f2d7ba15a780e2c3
|
Ruby
|
slague/night_writer
|
/lib/night_reader.rb
|
UTF-8
| 1,322
| 3.59375
| 4
|
[] |
no_license
|
require_relative 'file_reader'
require_relative 'letters'
require 'pry'
class NightReader
attr_reader :file_reader
def initialize
@reader = FileReader.new
end
def decode_file_to_english
braille = @reader.open_the_file
char_count = braille.chomp.length
braille_out = zip_input(scan_input(split_array_at_new_lines(braille)))
message_text = characters_equal_english_letter(braille_out)
File.write(ARGV[1], message_text)
p "Created '#{ARGV[1]}' containing #{char_count} characters"
end
def split_array_at_new_lines(braille)
braille.split("\n")
end
def scan_input(split_array_at_new_lines)
scanned_braille = split_array_at_new_lines.map do |line|
line.scan(/../)
end
scanned_braille
end
def zip_input(scanned_braille)
zipped_input = []
until scanned_braille.empty? do
zipped_input << scanned_braille[0].zip(scanned_braille[1], scanned_braille[2])
scanned_braille.shift(3)
end
zipped_input.flatten(1)
end
def characters_equal_english_letter(zipped_input)
new_line = ""
zipped_input.each do |character|
# binding.pry
english = LETTERS.key(character)
new_line << english.to_s
end
new_line
end
end
if __FILE__==$0
result_1 = NightReader.new
result_1.decode_file_to_english
end
| true
|
e5e0ec2b01e23b428f6b1a809c65374d3d45905f
|
Ruby
|
grimesjm/clean_arch_rb
|
/core/lib/core/gateways/user/fake_user_repository.rb
|
UTF-8
| 257
| 2.8125
| 3
|
[] |
no_license
|
class FakeUserRepository
def initialize
@users = []
end
def save(user)
require 'securerandom'
user.id = SecureRandom.uuid
@users << user
end
def find_by_username(username)
@users.find { |u| u.username == username }
end
end
| true
|
699519c3036ec4ba95f88a6dcc4517832a02e5ff
|
Ruby
|
access-watch/logstash-filter-accesswatch
|
/test.rb
|
UTF-8
| 2,917
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require "manticore"
require "json"
require "digest"
require "lru_redux"
require 'net/http'
class AccessWatchClient
def initialize(api_key, cache_size=10000)
@client = Manticore::Client.new ssl: {ca_file: "cert.pem"}
@api_key = api_key
if cache_size > 0
@cache = LruRedux::ThreadSafeCache.new(cache_size)
end
end
def handle_response(response)
data = JSON.parse(response.body)
if response.code == 200
{:status => :success,
:data => data}
else
{:status => :error,
:code => data["code"],
:message => data["message"]}
end
end
def url(path)
"https://api.access.watch#{path}"
end
def submit(&block)
begin
block.call
rescue => e
{:status => :error,
:error => e,
:message => e.message}
end
end
def get_json(path)
self.submit {
self.handle_response(@client.get(self.url(path),
headers: {"Api-Key" => @api_key,
"Accept" => "application/json",
"User-Agent" => "Access Watch Logstash Plugin/0.2.0"}))
}
end
def post_json(path, data)
self.submit {
self.handle_response(@client.post(self.url(path),
headers: {"Api-Key" => @api_key,
"Accept" => "application/json",
"Content-Type" => "application/json",
"User-Agent" => "Access Watch Logstash Plugin/0.2.0"},
body: JSON.generate(data)))
}
end
def with_cache(id, &block)
if @cache
@cache.getset(id) { block.call }
else
block.call
end
end
def fetch_address(ip)
self.with_cache("ip-#{ip}") {
self.get_json("/1.1/address/#{ip}")
}
end
def fetch_user_agent(user_agent)
self.with_cache("ua-#{Digest::MD5.hexdigest(user_agent)}") {
self.post_json("/1.1/user-agent", {:value => user_agent})
}
end
def fetch_identity(ip, user_agent)
ip = ip || ''
user_agent = user_agent || ''
self.with_cache("identity-#{Digest::MD5.hexdigest(ip)}-#{Digest::MD5.hexdigest(user_agent)}") {
self.post_json("/1.1/identity", {:address => ip, :user_agent => user_agent})
}
end
def test
p self.fetch_address("127.0.0.1")
p "---"
p self.fetch_user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36")
p "---"
p self.fetch_identity("77.123.68.232", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Safari/537.36")
end
end
client = AccessWatchClient.new("94bbc755f5b8aa96cfd40ce97faad568")
p client.fetch_address("127.0.0.1")
| true
|
a4eccd11808ed943efe5f6a2489d45704adacfde
|
Ruby
|
whastings/coding_practice
|
/problems/exponent_rec.rb
|
UTF-8
| 251
| 3.375
| 3
|
[] |
no_license
|
def exponent_rec(base, power)
return 1 if power == 0
return 1.0 / exponent_rec(base, power * -1) if power < 0
return base * exponent_rec(base, power - 1) if power.odd?
# Power is even.
half = exponent_rec(base, power / 2)
half * half
end
| true
|
0bfd318d1bc5197dc4f0dfda4516b70712976cd5
|
Ruby
|
n-flint/brownfield-of-dreams-2
|
/app/services/github_api_service.rb
|
UTF-8
| 721
| 2.6875
| 3
|
[] |
no_license
|
class GithubApiService
def initialize(token)
@token = token
end
def user_email(handle)
parsed_response(conn.get("/users/#{handle}"))
end
def followers
parsed_response(conn.get('/user/followers'))
end
def repos(limit = 5)
response = conn.get('/user/repos')
new_response = parsed_response(response)
new_response.take(limit)
end
def following
parsed_response(conn.get('/user/following'))
end
private
def parsed_response(response)
JSON.parse(response.body, symbolize_names: true)
end
def conn
Faraday.new(url: 'https://api.github.com') do |f|
f.headers['Authorization'] = "token #{@token}"
f.adapter Faraday.default_adapter
end
end
end
| true
|
b91b3ee8e6378a51b1618a16a1464d02f62a76f9
|
Ruby
|
fertech/csv_decision
|
/lib/csv_decision/validate.rb
|
UTF-8
| 3,100
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
# CSV Decision: CSV based Ruby decision tables.
# Created December 2017.
# @author Brett Vickers <brett@phillips-vickers.com>
# See LICENSE and README.md for details.
module CSVDecision
# Parse and validate the column names in the header row.
# These methods are only required at table load time.
# @api private
module Validate
# These column types do not need a name.
COLUMN_TYPE_ANONYMOUS = Set.new(%i[guard if path]).freeze
private_constant :COLUMN_TYPE_ANONYMOUS
# Validate a column header cell and return its type and name.
#
# @param cell [String] Header cell.
# @param index [Integer] The header column's index.
# @return [Array<(Symbol, Symbol)>] Column type and column name symbols.
def self.column(cell:, index:)
match = Header::COLUMN_TYPE.match(cell)
raise CellValidationError, 'column name is not well formed' unless match
column_type = match['type']&.downcase&.to_sym
column_name = column_name(type: column_type, name: match['name'], index: index)
[column_type, column_name]
rescue CellValidationError => exp
raise CellValidationError, "header column '#{cell}' is not valid as the #{exp.message}"
end
# Validate the column name against the dictionary of column names.
#
# @param columns [Symbol=>[false, Integer]] Column name dictionary.
# @param name [Symbol] Column name.
# @param out [false, Integer] False if an input column, otherwise the column index of
# the output column.
# @return [void]
# @raise [CellValidationError] Column name invalid.
def self.name(columns:, name:, out:)
return unless (in_out = columns[name])
return validate_out_name(in_out: in_out, name: name) if out
validate_in_name(in_out: in_out, name: name)
end
def self.column_name(type:, name:, index:)
# if: columns are named after their index, which is an integer and so cannot
# clash with other column name types, which are symbols.
return index if type == :if
return format_column_name(name) if name.present?
return if COLUMN_TYPE_ANONYMOUS.member?(type)
raise CellValidationError, 'column name is missing'
end
private_class_method :column_name
def self.format_column_name(name)
column_name = name.strip.tr("\s", '_')
return column_name.to_sym if Header.column_name?(column_name)
raise CellValidationError, "column name '#{name}' contains invalid characters"
end
private_class_method :format_column_name
def self.validate_out_name(in_out:, name:)
if in_out == :in
raise CellValidationError, "output column name '#{name}' is also an input column"
end
raise CellValidationError, "output column name '#{name}' is duplicated"
end
private_class_method :validate_out_name
def self.validate_in_name(in_out:, name:)
# in: columns may be duped
return if in_out == :in
raise CellValidationError, "output column name '#{name}' is also an input column"
end
private_class_method :validate_in_name
end
end
| true
|
ca5b3e486034511b4a1ef883f7f293755885341a
|
Ruby
|
Fabian-tapia7/ruby
|
/arreglos/sesion_online/aumento_precios.rb
|
UTF-8
| 177
| 3
| 3
|
[] |
no_license
|
def promedio(notas)
n= notas.count
n.times do |i|
if notas[i]=='N.A'
notas[i] = 2
end
end
print notas.sum/notas.count
end
promedio([5, 5, 20])
print "\n"
| true
|
a6f2ba7435c679956e4b574d20eccff8ab983fac
|
Ruby
|
p/lonely_coder
|
/lib/lonely_coder/profile.rb
|
UTF-8
| 7,573
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
# encoding: UTF-8
class OKCupid
def profile_for(username)
Profile.by_username(username, @browser)
end
def visitors_for(username, previous_timestamp = 0)
Profile.get_new_visitors(username, previous_timestamp, @browser)
end
def likes_for(username)
Profile.get_new_likes(username, @browser)
end
def update_section(section, text)
Profile.update_profile_section(section, text, @browser)
end
def upload_pic(file, caption)
Profile.upload_picture(file, caption, @browser)
end
class Profile
attr_accessor :username, :match, :friend, :enemy, :location,
:age, :sex, :orientation, :relationship_status,
:small_avatar_url, :relationship_type
# extended profile details
attr_accessor :last_online, :ethnicity, :height, :body_type, :diet, :smokes,
:drinks, :drugs, :religion, :sign, :education, :job, :income,
:offspring, :pets, :speaks, :profile_thumb_urls, :essays
# Scraping is never pretty.
def self.from_search_result(html)
username = html.search('span.username').text
age, sex, orientation, relationship_status = html.search('p.aso').text.split('/')
percents = html.search('div.percentages')
match = percents.search('p.match .percentage').text.to_i
friend = percents.search('p.friend .percentage').text.to_i
enemy = percents.search('p.enemy .percentage').text.to_i
location = html.search('p.location').text
small_avatar_url = html.search('a.user_image img').attribute('src').value
OKCupid::Profile.new({
username: username,
age: OKCupid.strip(age),
sex: OKCupid.strip(sex),
orientation: OKCupid.strip(orientation),
relationship_status: OKCupid.strip(relationship_status),
match: match,
friend: friend,
enemy: enemy,
location: location,
small_avatar_url: small_avatar_url,
relationship_type: relationship_type,
})
end
def Profile.get_new_likes(username, browser)
html = browser.get("http://www.okcupid.com/who-likes-you")
text = html.search('#whosIntoYouUpgrade .title').text
index = text.index(' people')
likes = text[0, index].to_i
return likes
end
def Profile.get_new_visitors(username, previous_timestamp = 1393545600, browser)
html = browser.get("http://www.okcupid.com/visitors")
visitors = html.search(".user_list .user_row_item")
new_visitors = 0
# previous_timestamp = 1393545600
visitors.each { |visitor|
begin
timestamp_script = visitor.search(".timestamp script")
timestamp_search = timestamp_script.text.match(/FancyDate\.add\([^,]+?,\s*(\d+)\s*,/)
timestamp = timestamp_search[1]
timestamp = timestamp.to_i
rescue
next
end
if (timestamp > previous_timestamp)
new_visitors += 1
end
}
return new_visitors
end
def Profile.by_username(username, browser)
html = browser.get("http://www.okcupid.com/profile/#{username}")
percents = html.search('#percentages')
match = percents.search('span.match').text.to_i
friend = percents.search('span.friend').text.to_i
enemy = percents.search('span.enemy').text.to_i
basic = html.search('#aso_loc')
age = basic.search('#ajax_age').text
sex = basic.search('#ajax_gender').text
orientation = basic.search('#ajax_orientation').text
relationship_status = basic.search('#ajax_status').text
location = basic.search('#ajax_location').text
relationship_type = basic.search('#ajax_monogamous').text
profile_thumb_urls = html.search('#profile_thumbs img').collect {|img| img.attribute('src').value}
essays = []
10.times do |i|
essays[i] = html.search('#essay_text_' + i.to_s).text.strip!
end
attributes = {
username: username,
match: match,
friend: friend,
enemy: enemy,
age: age,
sex: sex,
orientation: orientation,
location: location,
relationship_status: relationship_status,
profile_thumb_urls: profile_thumb_urls,
relationship_type: relationship_type,
essays: essays,
}
details_div = html.search('#profile_details dl')
details_div.each do |node|
value = OKCupid.strip(node.search('dd').text)
next if value == '—'
attr_name = node.search('dt').text.downcase.gsub(' ','_')
attributes[attr_name] = value
end
self.new(attributes)
end
def Profile.update_profile_section(section, text, browser)
section_titles = [
"My self-summary",
"What I’m doing with my life",
"I’m really good at",
"The first things people usually notice about me",
"Favorite books, movies, shows, music, and food",
"The six things I could never do without",
"I spend a lot of time thinking about",
"On a typical Friday night I am",
"The most private thing I’m willing to admit",
"You should message me if"
]
section_titles_hash = {
:self_summary => 0,
:im_doing => 1,
:good_at => 2,
:first_thing => 3,
:favorites => 4,
:six_things => 5,
:think_about => 6,
:private => 7,
:message_me => 8
}
if section.class == Symbol
section = section_titles_hash[section]
end
profile = browser.get('http://www.okcupid.com/profile')
authcode = profile.body.match(/authcode['"]?\s*:\s*['"]([\w,;]+?)['"]/)[1]
section_response = browser.post('http://www.okcupid.com/profileedit2', {
:authcode => authcode,
:essay_body => text,
:essay_id => section,
:change_summary => "[title:start]#{section_titles[section]}[title:end][add:start]#{text}[add:end]",
:okc_api => 1
})
end
def Profile.upload_picture(file, caption, browser)
file_dimensions = Dimensions.dimensions(file)
profile = browser.get('http://www.okcupid.com/profile')
authcode = profile.body.match(/authcode['"]?\s*:\s*['"]([\w,;]+?)['"]/)[1]
userid = profile.body.match(/userid['"]?\s*:\s*['"]?(\d+)['"]?/)[1]
upload_response = browser.post('http://www.okcupid.com/ajaxuploader', {
'file' => File.new(file)
})
picid = upload_response.body.match(/id'\s*:\s*'(\d+)/)[1]
uri = Addressable::URI.parse('http://www.okcupid.com/photoupload')
uri.query_values = {
:authcode => authcode,
:userid => userid,
:picid => picid,
:width => file_dimensions[0],
:height => file_dimensions[1],
:tn_upper_left_x => 0,
:tn_upper_left_y => 0,
:tn_lower_right_x => file_dimensions[0],
:tn_lower_right_y => file_dimensions[1],
:caption => caption,
:albumid => 0,
:use_new_upload => 1,
:okc_api => 1,
:'picture.add_ajax' => 1,
}
uri.to_s
create_photo = browser.get(uri.to_s)
end
def initialize(attributes)
attributes.each do |attr,val|
self.send("#{attr}=", val)
end
end
def ==(other)
self.username == other.username
end
def eql?(other)
self.username == other.username
end
def hash
if self.username
self.username.hash
else
super
end
end
end
end
| true
|
ced90e8a6e3f67406ceab2ebfec2406ab0987fa7
|
Ruby
|
anotherminh/ruby_chess_game
|
/player.rb
|
UTF-8
| 2,114
| 3.71875
| 4
|
[] |
no_license
|
require_relative 'display'
class HumanPlayer
# Reads keypresses from the user including 2 and 3 escape character sequences.
def self.read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
def self.get_key(cursor_pos)
c = read_char
new_pos = cursor_pos.dup
case c
when "\e[A"
# puts "UP ARROW"
new_pos[0] -= 1
when "\e[B"
# puts "DOWN ARROW"
new_pos[0] += 1
when "\e[C"
# puts "RIGHT ARROW"
new_pos[1] += 1
when "\e[D"
# puts "LEFT ARROW"
new_pos[1] -= 1
when "\r"
new_pos = false
when "\e"
Kernel.abort
end
new_pos
end
attr_reader :color
def initialize(color)
@color = color
end
def show_display(display)
@display = display
end
def make_move(board)
@board = board
@selected = false
@moved = false
choose_piece
move_piece
end
def choose_piece
selected_pos = nil
until @selected
display.print_board
new_input = HumanPlayer.get_key(display.cursor_pos)
if new_input
display.update_cursor(new_input) if board.on_board?(new_input)
else
@selected_pos = display.cursor_pos
@selected = true if board.valid_selection?(color, @selected_pos)
end
end
selected_pos
end
def move_piece
until @moved
display.print_board(selected_pos)
new_input = HumanPlayer.get_key(display.cursor_pos)
if new_input
display.update_cursor(new_input) if board.on_board?(new_input)
else
new_pos = display.cursor_pos
if new_pos == @selected_pos
@selected = false
choose_piece
elsif board.valid_move?(@selected_pos, new_pos, color)
@moved = true
board.move_piece(@selected_pos, new_pos)
end
end
end
end
private
attr_accessor :display, :board, :selected_pos
end
| true
|
a52b6da4d4f5193ea16476b80e088d33588a6e9e
|
Ruby
|
tidorisan/ruby
|
/2-8/2-8.rb
|
UTF-8
| 1,660
| 4.03125
| 4
|
[] |
no_license
|
# puts "aaa"
# input_key = gets
# puts "入力された内容は"+input_key
# puts "hello"
# input_key = gets
# puts "入力された内容は"+input_key
# a=gets.to_i
# b=gets.to_i
# puts "a+b=#{a+b}"
# a=gets.to_i
# b=gets.to_i
# puts "a+b=#{a+b}"
# puts "キーボードで数字「2」と数字「3」を入力してください"
# a=gets.to_i
# b=gets.to_i
# puts "a+b=#{a+b}"
# dice = 0 # diceに0を代入し、初期値を設定する
# while dice != 6 do
# dice = rand(1.6)
# puts dic
# end
# dice = 0 # diceに0を代入し、初期値を設定する
# while dice != 6 do #サイコロの目が6ではない間、diceの初期値は0なので条件を満たす。以降はdiceに代入される数によって結果が異なる
# dice = rand(1..6) #1~6の数字がランダムに出力される
# puts dice
# end
# for in do
# for i in 1..10 do
# puts i
# end
# for i in 1..10 do # 1..10は、1~10までの範囲を表す
# puts i
# end
# (範囲、ハッシュ、配列などを指定).each do |変数|
# 実行する処理
# end
# {"apple"=>130,"strawberry"=>180, "orange"=>100} .each do |frute,price|
# puts "#{fruit}は#{price}円です。" #変数展開
# end
# {"apple"=>130, "strawberry"=>180, "orange"=>100}.each do |fruit, price| #ハッシュの内容を順にキーをfruit、値をpriceに代入して繰り返す
# puts "#{fruit}は#{price}円です。" #変数展開
# end
# # 1 = 0
# while i <= 10 do
# if i >5
# break
# end
# puts i
# i += 1
# end
i = 0
while i <= 10 do
if i >5
break #iが5より大きくなると繰り返しから抜ける
end
puts i
i += 1
end
| true
|
85cbd2d91e8e1e56a72765cebb1e897e6e891966
|
Ruby
|
SALIM-UsseF/DEPIC
|
/back-end/app/controllers/questionchoixes_controller.rb
|
UTF-8
| 1,972
| 2.90625
| 3
|
[] |
no_license
|
################################
# Question choix Controller
# #############################
#
# Expose des services REST sous format Json:
# - Afficher la liste des questions choix
# - Afficher une question choix par ID
# - Creer une nouvelle question choix
# - Modifier une question choix
# - Supprimer une question choix par ID
require 'QuestionChoixService'
class QuestionchoixesController < ApplicationController
# Afficher la liste des questions choix
def index
questions = QuestionChoixService.instance.listeDesQuestions
render json: questions, status: :ok
end
# Afficher une QuestionChoix par ID
def show
question = QuestionChoixService.instance.afficherQuestionParId(params[:id])
(question != nil) ? (render json: question, status: :ok) : (render json: nil, status: :not_found)
end
# Creer une nouvelle QuestionChoix
def create
params.permit(:intitule, :estObligatoire, :estUnique, :ordre, :sondage_id)
ajout = QuestionChoixService.instance.creerQuestionChoix(params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre], params[:sondage_id])
(ajout != nil) ? (render json: ajout, status: :ok) : (render json: nil, status: :not_found)
end
# Modifier une QuestionChoix
def update
modifier = QuestionChoixService.instance.modifierQuestion(params[:id], params[:intitule], params[:estObligatoire], params[:estUnique], params[:ordre])
(modifier != nil) ? (render json: modifier, status: :ok) : (render json: nil, status: :not_found)
end
# Supprimer une QuestionChoix par ID
def delete
supprimer = QuestionChoixService.instance.supprimerQuestion(params[:id])
(supprimer) ? (render json: true, status: :ok) : (render json: false, status: :not_found)
end
# Liste des parametres à fournir
private
# parametres d'ajout
def question_params
params.permit(:intitule, :estObligatoire, :estUnique, :nombreChoix, :ordre, :sondage_id)
end
end
| true
|
e7c9018c91fd455d3c8b3dcc676535ecd54ee0f0
|
Ruby
|
TwilioDevEd/api-snippets
|
/quickstart/ruby/autopilot/create-first-task/create_hello_world_task.6.x.rb
|
UTF-8
| 1,068
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'
# Your Account Sid and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)
# Build task actions that say something and listens for a repsonse.
hello_world_task_actions = {
"actions" => [
{ "say": "Hi there, I'm your virtual assistant! How can I help you?" },
{ "listen": true }
]
}
# Create the hello_world task
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
task = @client.autopilot.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.tasks
.create(
unique_name: "hello-world",
actions: hello_world_task_actions
)
puts "Hello-world task has been created!"
puts task.sid
| true
|
dc048a66e078f93adb0e21533d99cb691f8fd371
|
Ruby
|
jordansissel/experiments
|
/ruby/octokit/migrate-issue.rb
|
UTF-8
| 3,235
| 2.65625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# encoding: utf-8
require "clamp"
require_relative "mixins/github"
require_relative "mixins/logger"
require_relative "mixins/cla"
class GithubIssueMigrator < Clamp::Command
include Mixin::GitHub
include Mixin::Logger
include Mixin::ElasticCLA
parameter "SOURCE", "The github issue to migrate."
parameter "DESTINATION", "The destination to migrate to"
def execute
issue = github.issue(source_project, source_issue)
if issue[:pull_request]
migrate_pull(issue)
else
migrate_issue(issue)
end
end
def migrate_issue(issue)
annotated_body = "(This issue was originally filed by @#{issue.user.login} at #{source})\n\n---\n\n" + issue.body
if issue.state == "closed"
puts "This issue is already closed. Nothing to migrate."
return 1
end
# Create the new issue
new_issue = github.create_issue(destination_project, issue.title, annotated_body)
# Comment on the old issue about the migration, and close it.
github.add_comment(source_project, source_issue, "For Logstash 1.5.0, we've moved all plugins to individual repositories, so I have moved this issue to #{new_issue.html_url}. Let's continue the discussion there! :)")
github.close_issue(source_project, source_issue)
puts "Successfully migrated to: #{new_issue.html_url}"
nil
end # def execute
def migrate_pull(issue)
if cla_uri.nil?
puts "Missing --cla-uri. Cannot migrate a PR without this."
return 1
end
comment = <<-COMMENT
For Logstash 1.5.0, we've moved all plugins (and grok patterns) to individual repositories. Can you move this pull request to https://github.com/#{destination_project}?
This sequence of steps _may_ help you do this migration:
1. Fork this repository
2. Clone your fork
```shell
git clone #{issue.user.html_url}/#{source_project.split("/")[1]}.git
```
3. Create a branch:
```shell
git checkout -b my-branch-name
```
4. Apply the patches from this PR into your branch:
```shell
curl -s #{source}.patch | git am
```
This should take your commits from this PR and commit them to your new local branch.
5. Push!
```shell
git push origin my-branch-name
```
6. Open a new PR against https://github.com/#{destination_project}
COMMENT
cla_ok, cla_message = cla_status(source_project, source_issue, cla_uri)
cla_message = cla_message[0,1].downcase + cla_message[1..-1]
if !cla_ok
comment << <<-COMMENT
7. Sign the CLA
Our CLA check indicates that #{cla_message}. See our [contributor agreement](http://www.elasticsearch.org/contributor-agreement/) for more details. :)
COMMENT
end
github.add_comment(source_project, source_issue, comment)
github.close_issue(source_project, source_issue)
puts "Added note to contributor for migration to #{destination_project}"
end
def source_project
@source_project ||= source.gsub(%r{^https?://github.com/}, "").gsub(%r{(issues|pull)/\d+$}, "")
end
def source_issue
@source_issue ||= source[/\d+$/].to_i
end
def destination_project
@destination_project ||= destination.gsub(%r{^https?://github.com/}, "")
end
end # class GithubIssueMigrator
GithubIssueMigrator.run
| true
|
189706c51143988a519b4b309dd2095bc69fd0ab
|
Ruby
|
hirataya/fatechan
|
/lib/google_calc.rb
|
UTF-8
| 718
| 2.84375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
require "uri"
require "cgi"
require "open-uri"
require "nokogiri"
module GoogleCalc
def self.calc(expr, &block)
uri = sprintf("http://www.google.com/search?hl=ja&q=%s", CGI.escape(expr))
#p uri
result = nil
open(uri, "r:utf-8", "User-Agent" => "Mozilla/5.0") do |fp|
content = fp.read
#p content
doc = Nokogiri::HTML(content)
result = doc.xpath("//h2[@class='r']").first
end
return nil if not result
#result = result.text
result = result.inner_html
result.gsub!(%r{<sup>(.*?)</sup>}) { "^#{$1}" }
result.gsub!(%r{<font size="-2"> </font>}, "")
result.strip!
result.gsub!(/\s{2,}/, " ")
block.call(result) if block
result
end
end
| true
|
a20133fe9d6b00be177d6c28e91a9df4606b22ea
|
Ruby
|
tcrane20/AdvanceWarsEngine
|
/Advance Wars Edit/Scripts_Old/[191]Sea.rb
|
UTF-8
| 485
| 2.5625
| 3
|
[] |
no_license
|
class Sea < Tile
def initialize
super
@name = 'sea'
@id = TILE_SEA
end
def move_cost_chart(move_type)
return case move_type
when MOVE_FOOT then return [0]
when MOVE_MECH then return [0]
when MOVE_TIRE then return [0]
when MOVE_TREAD then return [0]
when MOVE_AIR then return [1,2]
when MOVE_TRANS then return [1,2]
when MOVE_SEA then return [1,2]
when MOVE_TIRE_B then return [0]
end
end
end
| true
|
44fa8a998fd2bedd52a5c0cd2c1433880fee6d78
|
Ruby
|
rubenpazch/ruby-algorithms
|
/strings/practice.rb
|
UTF-8
| 1,135
| 3.515625
| 4
|
[] |
no_license
|
# p "abcdef" <=> "abcde" #=> 1
# p "abcdef" <=> "abcdef" #=> 0
# p "abcdef" <=> "abcdefg" #=> -1
# p "abcdef" <=> "ABCDEF" #=> 1
# p "abcdef" <=> 1 #=> nil
# str1 = 'aa'
# str2 = 'bb'
# ar1 = str1.squeeze.each_char.to_a
# ar2 = str2.squeeze.each_char.to_a
#
# p ar1 - ar2
# p ar2 - ar1
#
## str1.each_char{|x| x - }
#
# p str1 <=> str2
#
# puts 3 / 2
# #cantidadACambiar = 1211
# cantidadACambiar = 1000
# cantidadACambiar = 100
# cantidadACambiar = 10
# cantidadACambiar = 1
# cantidadACambiar = 0
# cantidadACambiar = 1123
cantidadACambiar = 15
def totalBilletesMonedas(retirar)
billete200 = 200.0
arr = [100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.5, 0.2, 0.1]
minimo = 0.0
if retirar > billete200
division = retirar / billete200
residuo = retirar % billete200
minimo += division
else
residuo = retirar
end
return minimo if residuo == 0.0
i = 0
while residuo != 0.0
if residuo >= arr[i]
division = residuo / arr[i]
residuo = residuo % arr[i]
minimo += division
end
i += 1
end
minimo
end
p totalBilletesMonedas(cantidadACambiar)
test
| true
|
8ff2fc70915edfa5036c00ea783412436103f2c3
|
Ruby
|
Chrispolanco/debugging-with-pry-online-web-prework
|
/lib/pry_debugging.rb
|
UTF-8
| 53
| 2.546875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def plus_two(num)
num + 2
new_total = num + 2
end
| true
|
c04a746ca13e22a7a5723f1b35cf6d9a68fc2136
|
Ruby
|
vuhailuyen1991/rails
|
/activesupport/lib/active_support/core_ext/date_and_time/compatibility.rb
|
UTF-8
| 601
| 2.640625
| 3
|
[
"MIT",
"Ruby"
] |
permissive
|
module DateAndTime
module Compatibility
# If true, +to_time+ preserves the the timezone offset.
#
# NOTE: With Ruby 2.4+ the default for +to_time+ changed from
# converting to the local system time to preserving the offset
# of the receiver. For backwards compatibility we're overriding
# this behavior but new apps will have an initializer that sets
# this to true because the new behavior is preferred.
mattr_accessor(:preserve_timezone, instance_writer: false) { false }
def to_time
preserve_timezone ? getlocal(utc_offset) : getlocal
end
end
end
| true
|
6d99066e7787e4dc54923f4ed69a22b4e6192fc8
|
Ruby
|
sbasnyat/cosi166b
|
/PA2/MovieData.rb
|
UTF-8
| 6,995
| 3.359375
| 3
|
[] |
no_license
|
class MovieData
# constructor, if one parameter is passed, it takes path to the folder containing the movie data,
# optionally if two arguments are passed, the first is taken as path to folder and second symbol to specify a particular training/test pair
def initialize(*args)
train_test_h = {:u1 => ["u1.base","u1.test"],
:u2 => ["u2.base","u2.test"],
:u3 => ["u3.base","u3.test"],
:u4 => ["u4.base","u4.test"],
:u5 => ["u5.base","u5.test"],
:ua => ["ua.base","ua.test"],
:ub => ["ub.base","ub.test"] }
foldername = args[0]
# @train_umr_h stands for training user movie rating hash and is a hash table that stores each line of data of training set in the form user_id as key and its
# value is another hash table with key movie id and value rating
# @train_mur_h stands for training movie user rating hash and is a hash table that stores each line of data in the training set in the form movie-id as key and its
# value is another hash table with key user_id and value rating
# @test_umr_arr stands for test user movie rating array and is 2D array i.e. an array of arrays in the form [user_id, movie_id, rating] for each line of test data
if args.length == 1
train_filename = File.join(foldername,"u.data")
@test_umr_arr = nil
else
train_test_pair = train_test_h[args[1]]
train_filename = File.join(foldername,train_test_pair[0])
test_filename = File.join(foldername,train_test_pair[1])
@test_umr_arr = load_test(test_filename)
end
@train_umr_h, @train_mur_h = load_train(train_filename)
end
# this method reads the training dataset line by line, stores it in two hash table forms and returns the two hash tables
def load_train(train_filename)
train_data = open(train_filename).read
umr_h = Hash.new
mur_h = Hash.new
train_data.each_line do |line|
data = line.split(" ")
user_id = data[0].to_i
movie_id = data[1].to_i
rate = data[2].to_i
# for a particular key, it checks if it exists, if not creates a new hash table at that key
if !umr_h.has_key?(user_id)
umr_h[user_id] = Hash.new
end
umr_h [user_id] [movie_id] = rate
# for a particular key, it checks if it exists, if not creates a new hash table at that key
if !mur_h.has_key?(movie_id)
mur_h[movie_id] = Hash.new
end
mur_h [movie_id][user_id] = rate
end
return umr_h, mur_h
end
# this method reads the test dataset and stores each line in a 2D array i.e an array of arrays in the form [user_id, movie_id, rating] and returns it
def load_test(test_filename)
test_data = open(test_filename).read
umr_arr = Array.new
test_data.each_line do |line|
data=line.split(" ")
user_id=data[0].to_i
movie_id=data[1].to_i
rate=data[2].to_i
umr_arr.push([user_id, movie_id, rate])
end
return umr_arr
end
# this method returns the rating that user u gave movie m in the training set, and 0 if user u did not rate movie m
def rating(u,m)
if @train_umr_h.has_key?(u) && @train_umr_h[u].has_key?(m)
return @train_umr_h[u][m]
else
return 0
end
end
# this method returns the array of movies that user u has watched and 0 if the user id cannot be found in the dataset
def movies(u)
if @train_umr_h.has_key?(u)
return @train_umr_h[u].keys
else
return 0
end
end
# this method returns the array of users that have seen movie m and 0 if the movie id cannot be found in the dataset
def viewers(m)
if @train_mur_h.has_key?(m)
return @train_mur_h[m].keys
else
return 0
end
end
# this method returns a floating point number between 1.0 and 5.0 as an estimate of what user u would rate movie m
# prediction algorithm sees 10 the users who have watched the movie and checks which of them have watched the most
# common movies among the first 20 movies watched by the users with user u, and then returns the rating the user gave the movie m
def predict(u,m)
hash=Hash.new
viewers_m = viewers(m)
movies_u = movies(u)
if (viewers_m == 0 || viewers_m.length < 20) && (movies_u == 0 || movies_u.length < 20)
return 0
elsif viewers_m == 0 || viewers_m.length < 20
sum = 0
movies(u)[0..29].each do |mov|
sum += rating(u,mov)
end
return sum/20
else
ten_viewers=Array.new(viewers_m[0..9])
ten_viewers.each do |user|
if user!=u && movies(user).length >= 50
num_common_movies=(movies_u & movies(user)[0..49]).length
hash[num_common_movies]=user
end
end
#finds the user out of the viewers who has the maximum number of movies watched in common with our user u and returns the rating that user gave to movie m
return rating(hash[hash.keys.max],m)
end
end
# runs the predict method on the first something number of ratings in the test set as specified in the parameter and returns a MovieTest object containing the results.
# If the parameter is omitted, all of the tests will be run.
def run_test(*args)
if args.length == 1
k = args[0]
ratinglist=Array.new(@test_umr_arr[0...k])
else
ratinglist=Array.new(@test_umr_arr)
end
# now finds the prediction rating from the predict function and pushes it into the array
ratinglist.each do |line|
predicted= predict(line[0],line[1])
line.push(predicted)
end
# creates an instance of class MovieTest and passes the ratinglist as parameter
return MovieTest.new(ratinglist)
end
end
class MovieTest
# takes ratinglist i.e. an array of arrays with each element in the form [user_id, movie_id, rating, predicted rating]
# @error is an array whoese elements are the difference between predicted rating and actual rating for each element on the ratinglist
def initialize(ratinglist)
@ratinglist=ratinglist
@error=find_error
@length=ratinglist.length
end
# this method goes through each element of the rating list i.e. each array and finds the difference between the actual and
# predicted rating for each and stores the value in an array and returns it
def find_error
error=[]
@ratinglist.each do |result|
error.push((result[2]-result[3]).abs)
end
return error
end
# this method returns the average predication error
def mean
summ = @error.inject(0) {|sum, i| sum + i }
return (summ.to_f/@length)
end
# this method returns the standard deviation of the error
def stddev
mean_ = mean
sum=0
@error.each do |error|
sum += ((error - mean_ ) ** 2)
end
return Math.sqrt(sum.to_f/@length)
end
# this method returns the root mean square error of the prediction
def rms
sum=0
@error.each do |error|
sum += (error) ** 2
end
return Math.sqrt(sum.to_f/@length)
end
# this method returns an array of the predictions in the form [u,m,r,p].
def to_a
print @ratinglist
puts
end
end
obj=MovieData.new("ml-100k", :u2)
#puts obj.similarity(1,126)
#puts obj.most_similar(1)
#puts obj.viewers(100)
#t=obj.run_test(2500)
#puts t.mean
#puts t.stddev
#puts t.rms
#t.to_a
#puts t.rms
| true
|
784cddaa14b24afa3245d7908e6aaad22e17de9e
|
Ruby
|
higepon/misc
|
/count-and-say.rb
|
UTF-8
| 507
| 3.609375
| 4
|
[] |
no_license
|
# @param {Integer} n
# @return {String}
def count_and_say(n)
if n == 1
return "1"
end
prev = count_and_say(n - 1)
ret = ''
currentVal = 0
num = 0
for i in 0...prev.size
ch = prev[i]
if num == 0
currentVal = ch
num = 1
elsif ch == currentVal
num = num + 1
else
ret = "#{ret}#{num}#{currentVal}"
num = 1
currentVal = ch
end
if i == prev.size - 1
ret = "#{ret}#{num}#{currentVal}"
num = 0
end
end
return ret
end
| true
|
291f200ff99145d88b75bbab9dd6a581f73fed95
|
Ruby
|
sogbdn/ar-exercises
|
/exercises/exercise_7.rb
|
UTF-8
| 430
| 3.078125
| 3
|
[] |
no_license
|
require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
require_relative './exercise_5'
require_relative './exercise_6'
puts "Exercise 7"
puts "----------"
# Ask the user for a store name (store it in a variable)
puts "What is your store's name?"
a = gets.chomp
store = Store.create(name: a)
puts store.errors.full_messages
| true
|
ce0c2d6b1bff6d2d664dfd0a64711a0346788692
|
Ruby
|
gotar/internship_day_V
|
/lib/model/product.rb
|
UTF-8
| 239
| 3.046875
| 3
|
[] |
no_license
|
module Shop
class Product
attr_reader :id, :name, :price
@@id = 0
def initialize(name, price)
@id = set_id
@name = name
@price = price
end
private
def set_id
@@id += 1
end
end
end
| true
|
b0a7fbb32fb5c86b85e032fe4ad5a5022e29ba9d
|
Ruby
|
toshichanapp/projecteuler
|
/1-10/problem5.rb
|
UTF-8
| 195
| 2.875
| 3
|
[] |
no_license
|
require 'prime'
(1..20).map {|num| Prime.prime_division(num)}.flatten.each_slice(2).group_by{|arr| arr[0]}.map do |_, arr|
arr.max_by{|nums| nums[1] }
end.map do |a, b|
a ** b
end.reduce(:*)
| true
|
95b00a42ea438f4979db6b3d5da53f7d4a09b10a
|
Ruby
|
masayuki038/chienowa
|
/app/helpers/stars_helper.rb
|
UTF-8
| 140
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
module StarsHelper
def starred?(stars)
stars.each do |star|
return true if current_user?(star.user)
end
false
end
end
| true
|
194a25cbe0080c2db9109579d313ce0fb8f3f7d7
|
Ruby
|
pamungkaski/Malkist-Ruby
|
/spec/malkist_spec.rb
|
UTF-8
| 3,166
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
RSpec.describe Malkist do
it 'has a version number' do
expect(Malkist::VERSION).not_to be nil
end
it 'return distance between two coordinate' do
result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592])
expect(result[0].distance).to eq(10423)
end
it 'return distance between one origin with many destinations' do
result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(3)
end
it 'return distance between many origin with one destinations' do
result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592])
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(3)
end
it 'return distance between many origin with one destinations' do
result = Malkist.calculate_distance(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(9)
end
end
RSpec.describe Malkist::Distances do
it 'return distance between two coordinate' do
distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592])
result = distances.calculate_distance
expect(result[0].distance).to eq(10423)
end
it 'return distance between one origin with many destinations' do
distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])
result = distances.calculate_distance
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(3)
end
it 'return distance between many origin with one destinations' do
distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592])
result = distances.calculate_distance
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(3)
end
it 'return distance between many origin with one destinations' do
distances = Malkist::Distances.new(%w[40.6655101,-73.89188969999998 40.6855101,-73.89188969999998 40.6255101,-73.89188969999998], %w[40.6905615,-73.9976592 40.8905615,-73.9976592 40.7905615,-73.9976592])
result = distances.calculate_distance
expect(result[0].distance).to eq(10423)
expect(result.length).to eq(9)
end
end
RSpec.describe Malkist::Distances::Distance do
it 'return the assigned value upon initialization' do
distance = Malkist::Distances::Distance.new('oRigiNaslz Addrewses', 'dWesttwinattizion Addrewses', 65123, 1235123)
expect(distance.origin).to eq('oRigiNaslz Addrewses')
expect(distance.destination).to eq('dWesttwinattizion Addrewses')
expect(distance.distance).to eq(65123)
expect(distance.duration).to eq(1235123)
end
end
| true
|
4ceee98fb56d597ffc2a8385e07adf7f32a2826d
|
Ruby
|
kennyfrc/launch_school
|
/130/anagram.rb
|
UTF-8
| 1,197
| 4
| 4
|
[] |
no_license
|
# 04/23/16 - Challenge: Anagrams
class Anagram
attr_reader :detector
def initialize(detector)
@detector = detector
end
def match(array_of_words)
filtered_words = array_of_words.map(&:downcase).select do |word|
word.chars.all? do |chars|
detector_letters.include?(chars)
end && pass_anagram_checker?(word)
end
return filtered_words.map(&:capitalize) if capitalized?(detector)
filtered_words
end
private
def pass_anagram_checker?(arr)
same_size_as_detector?(arr) && same_char_count_as_detector?(arr) && not_self?(arr)
end
def capitalized?(detector)
capitalized_detector = detector.downcase.capitalize
capitalized_detector == detector
end
def size(arr)
arr.chars.size
end
def detector_letters
detector.downcase.chars
end
def chars_of(str)
hash_of_letters = Hash.new(0)
str.chars.each do |letter|
hash_of_letters[letter] += 1
end
hash_of_letters
end
def same_char_count_as_detector?(arr)
chars_of(arr) == chars_of(detector.downcase)
end
def same_size_as_detector?(arr)
size(arr) == detector.size
end
def not_self?(arr)
arr != detector.downcase
end
end
| true
|
21ef2d477d190f1f0989bcb0d5264d9c5793350e
|
Ruby
|
sksamal/omnetpp-5.0
|
/samples/FatTree/simulations/createIniBorderExp.rb
|
UTF-8
| 1,226
| 2.78125
| 3
|
[] |
no_license
|
# Generating experiment inis
#Execute with ruby createIniBorderExp.rb
data = File.readlines("inputBorders.ini")
upper = [10, 20, 40, 60, 80, 160]
lower = [5, 10, 20, 30, 40, 80]
lower2 = [3, 5, 10, 15, 20, 40]
repeats = (1..5).to_a
upper.zip(lower).each do |upper, lower|
repeats.each do |i|
data_temp = data.dup
data_temp.map! {|line| line.gsub(/%SEED%/, "#{i}")}
data_temp.map! {|line| line.gsub(/%LOW%/, "#{lower}")}
data_temp.map! {|line| line.gsub(/%UP%/, "#{upper}")}
name_temp = "#{upper}-#{lower}-#{i}"
filename = "border#{name_temp}.ini"
File.open(filename, "a") {|f| f.puts data_temp}
puts "Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}."
end
end
=begin
upper.zip(lower2).each do |upper, lower|
repeats.each do |i|
data_temp = data.dup
data_temp.map! {|line| line.gsub(/%SEED%/, "#{i}")}
data_temp.map! {|line| line.gsub(/%LOW%/, "#{lower}")}
data_temp.map! {|line| line.gsub(/%UP%/, "#{upper}")}
name_temp = "#{upper}-#{lower}-#{i}"
filename = "border#{name_temp}.ini"
File.open(filename, "a") {|f| f.puts data_temp}
puts "Created #{filename} with borders up: #{upper}, low: #{lower}, seed: #{i}."
end
end
=end
| true
|
bdd6ee448b1dfae8533e0454f61b12702c51b7b9
|
Ruby
|
kbehnfeldt/RB101
|
/rb101-lesson4/Loops1/exercise6.rb
|
UTF-8
| 76
| 3.140625
| 3
|
[] |
no_license
|
number = []
while number.length < 5
number << rand(100)
end
puts number
| true
|
30b98fcc700dffac0c65bfc92cc84df8af8ad865
|
Ruby
|
ric2b/learning_ruby
|
/ruby/hamming/hamming.rb
|
UTF-8
| 194
| 3.546875
| 4
|
[] |
no_license
|
class Hamming
def self.compute(string_a, string_b)
raise ArgumentError if string_a.length != string_b.length
string_a.chars.zip(string_b.chars).map{|a, b| a != b ? 1 : 0}.sum
end
end
| true
|
091d14e988ba41047519cc89e48d9b15b979ea6c
|
Ruby
|
btazi/rbnd-toycity-part4
|
/lib/analyzable.rb
|
UTF-8
| 891
| 3.09375
| 3
|
[] |
no_license
|
module Analyzable
# Your code goes here!
def average_price(products)
average = products.map(&:price).map(&:to_f).reduce(:+)/products.length
average.round(2)
end
def print_report(products)
report = ""
products.each do |product|
report += "#{product.name}, brand: #{product.brand}, price: #{product.price} \n"
end
report
end
def create_count_by_methods(*attributes)
attributes.each do |attr|
self.class_eval %{def self.count_by_#{attr}(arg)
counts = {}
arg.map(&:#{attr}).each do |#{attr}_value|
counts[#{attr}_value] = Product.where(#{attr}: #{attr}_value).count
end
counts
end}
end
end
def self.method_missing(method_name, arguments)
if method_name.to_s.start_with?("count_by")
attribute = method_name.to_s.gsub!("count_by_", "")
create_count_by_methods(attribute)
self.public_send(method_name, arguments)
end
end
end
| true
|
542558846983f977142894603c5554457c5257e7
|
Ruby
|
roodi/roodi
|
/lib/roodi/checks/abc_metric_method_check.rb
|
UTF-8
| 2,015
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
require 'roodi/checks/check'
module Roodi
module Checks
# The ABC metric method check calculates the number of Assignments,
# Branches and Conditionals in your code. It is similar to
# cyclomatic complexity, so the lower the better.
class AbcMetricMethodCheck < Check
ASSIGNMENTS = [:lasgn]
BRANCHES = [:vcall, :call]
CONDITIONS = [:==, :"!=", :<=, :>=, :<, :>]
OPERATORS = [:*, :/, :%, :+, :<<, :>>, :&, :|, :^]
DEFAULT_SCORE = 10
attr_accessor :score
def initialize
super()
self.score = DEFAULT_SCORE
end
def interesting_nodes
[:defn]
end
def evaluate_start(node)
method_name = node[1]
a = count_assignments(node)
b = count_branches(node)
c = count_conditionals(node)
score = Math.sqrt(a*a + b*b + c*c)
add_error "Method name \"#{method_name}\" has an ABC metric score of <#{a},#{b},#{c}> = #{score}. It should be #{@score} or less." unless score <= @score
end
private
def count_assignments(node)
count = assignment?(node) ? 1 : 0
node.children.each {|child_node| count += count_assignments(child_node)}
count
end
def count_branches(node)
count = branch?(node) ? 1 : 0
node.children.each {|child_node| count += count_branches(child_node)}
count
end
def count_conditionals(node)
count = conditional?(node) ? 1 : 0
node.children.each {|child_node| count += count_conditionals(child_node)}
count
end
def assignment?(node)
ASSIGNMENTS.include?(node.node_type)
end
def branch?(node)
BRANCHES.include?(node.node_type) && !conditional?(node) && !operator?(node)
end
def conditional?(node)
(:call == node.node_type) && CONDITIONS.include?(node[2])
end
def operator?(node)
(:call == node.node_type) && OPERATORS.include?(node[2])
end
end
end
end
| true
|
c303c31408aa672ed882d6950b428899282d7b93
|
Ruby
|
jcquarto/everything-is-a-object-or-method
|
/object_test2.rb
|
UTF-8
| 110
| 3.171875
| 3
|
[] |
no_license
|
# works with classes too!
class Cat
end
puts Cat.class
puts Cat.new.class
cato = Cat.new
puts cato.class
| true
|
104b1567e4d48ca27aa73a2f6510dd5769ca7fc1
|
Ruby
|
magic8baller/the-bachelor-todo-prework
|
/lib/bachelor.rb
|
UTF-8
| 1,482
| 3.828125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#require 'pry'
def get_first_name_of_season_winner(data, season)
data[season].each do |contestant_hash| # {'name'=>'Tessa H'..,}
if contestant_hash['status'] == 'Winner'
return contestant_hash['name'].split.first
#split name into 2 strings, return first name
end
end
end
def get_contestant_name(data, occupation)
data.each do |season, contestant_array| # 'season ', [{..},{..},..]
contestant_array.each do |contestant_hash| #{'name'=>'Ashley..',}
if contestant_hash['occupation'] == occupation
return contestant_hash['name']
end
end
end
end
def count_contestants_by_hometown(data, hometown)
count = 0
data.each do |season, contestant_array|
contestant_array.each do |contestant_hash|
if contestant_hash['hometown'] == hometown #if hometown matches parameter
count += 1 #count it
end
end
end
count
end
def get_occupation(data, hometown)
data.each do |season, contestant_array|
contestant_array.each do |contestant_hash|
if contestant_hash['hometown'] == hometown
return contestant_hash['occupation']
end
end
end
end
def get_average_age_for_season(data, season)
contestant_count = 0
total_ages = 0
data[season].each do |contestant_hash|
total_ages += contestant_hash['age'].to_f #float number => perform average w/ decimals
contestant_count += 1
end
(total_ages/contestant_count).round #from decimal can accurately round average
end
| true
|
978e0b3723d87a83c9b7357b026b6b9f3e8e3461
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/binary/309c0a008dd847918cd61c14010c5f45.rb
|
UTF-8
| 357
| 3.8125
| 4
|
[] |
no_license
|
class Binary
attr_reader :value
def initialize(value)
@value = value
end
def to_decimal
return 0 unless is_decimal?
chars.each_with_index
.map { |digit, index| digit.to_i * (2 ** index) }
.inject(&:+)
end
private
def chars
value.reverse.each_char
end
def is_decimal?
value.match(/^(0|1)+$/)
end
end
| true
|
dfa258b68b1e8e530a1b76762c9461b6a435406d
|
Ruby
|
ajemobile/big
|
/lib/bigmagic/database_object.rb
|
UTF-8
| 634
| 2.859375
| 3
|
[] |
no_license
|
module Bigmagic
class DatabaseObject
def eigen_class
class << self
self
end
end
def add_instance_variables(argv)
hash = {}
if argv.kind_of?(Hash)
hash = argv
elsif argv.kind_of?(Array)
argv.map! {|item| item.to_s.to_sym}
hash = Hash[*argv.zip(Array.new(argv.size)).flatten]
elsif argv.nil?
return nil
else
raise "invalid argument! Use a Hash or Array argument"
end
hash.each_pair do |key,value|
eigen_class.send :attr_accessor, key.to_sym
send("#{key}=".to_sym, value)
end
end
end
end
| true
|
3a0ac8d9f7e32e0792c7b6f472ab3c5f24d64040
|
Ruby
|
sans-pulp/ruby-exercises
|
/ruby_basics/3_conditionals/string_caps.rb
|
UTF-8
| 332
| 4.40625
| 4
|
[
"MIT"
] |
permissive
|
# Write a method that takes a string as an argument and returns a new all caps version of the string only if the string is longer than 10 characters
def upcase_long_string(string)
string.length > 10 ? string.upcase : string
# if string.length > 10
# string.upcase
# end
end
puts upcase_long_string('This is interesting')
| true
|
d6a787429ce11e7b7ed18d6ba4a7041600de7109
|
Ruby
|
mkaushish/quizsite
|
/lib/QuestionGenerator/trig.rb
|
UTF-8
| 2,422
| 3.21875
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require_relative 'questionbase'
require_relative 'tohtml'
include "Math.rb"
PYTHTRIP=[[3,4,5],[5,12,13],[7,24,25],[8,15,17]]
ORD=["a","o","h"]
PYTH=[[1,1,Math.sqrt(2)], [1,Math.sqrt(3),2]]
TRIGF=["sin", "cos", "tan", "cot", "cosec", "sec"]
TRIGDEF={"sin" => ["o","h"], "cos" => ["a","h"], "tan" => ["o","a"], "cot" => ["a","o"], "cosec" => ["h","o"], "sec" => ["h","a"]}
module Trig
class RatiosMissingSide
def initialize
trip=PYTHTRIP.sample
mult=rand(3)+1
for i in 0...trip.length
trip[i]=trip[i]*mult
end
@fun=TRIGF.sample
@trip={"a" => trip[0],
"o" => trip[1],
"h" => trip[2]}
@whmis=TRIGDEF[@fun].sample
end
def solve
rat=Rational(@trip[TRIGDEF[@fun][0]], @trip[TRIGDEF[@fun][1]])
return {"num" => rat.numerator,
"den" => rat.denominator}
end
def text
txt="In a triangle ABC, right angled at B"
txt+=", AB is of length #{@trip["a"]} " if @whmis != "a"
if @whmis == "h"
txt+="and "
else txt+=", "
end
txt+="BC is of length #{@trip["o"]}" if @whmis != "o"
txt+=" and CA is of length #{@trip["h"]}" if @whmis != "h"
txt+=". What is the value of #{@fun}(A) in its lowest form?"
[TextLabel.new(txt), Fraction.new("num", "den")]
end
end
class RatioGivenOther
def initialize
trip=PYTHTRIP.sample
@orig=TRIGF.sample
@fin=TRIGF.sample
while @fin==@orig
@fin=TRIGF.sample
end
mult=rand(3)+1
for i in 0...trip.length
trip[i]=trip[i]*mult
end
@trip={"a" => trip[0],
"o" => trip[1],
"h" => trip[2]}
end
def solve
rat=Rational(@trip[TRIGDEF[@fin][0]], @trip[TRIGDEF[@fin][1]])
return {"num" => rat.numerator,
"den" => rat.denominator}
end
def text
[TextLabel.new("In a triangle ABC, right angled at B, #{@orig}(A)=#{Fraction.new(@trip(TRIGDEF[@orig][0]), @trip(TRIGDEF[@orig][1]))}. What is the value of #{@fin}(A) in its lowest form?"), Fraction.new("num", "den")]
end
end
class RatiosUsingId
def initialize
@fun=TRIGF.sample
@ang=rand(85)+3
end
def solve
end
def text
[TextLabel.new("Find the value of #{Fraction.new("sin(#{@ang})", "sin(#{90-@ang})")} using identities"), TextField.new("ans")]
end
end
end
| true
|
e2772763f491343e97a06dc05dbdb571757704a5
|
Ruby
|
QPC-WORLDWIDE/rubinius
|
/kernel/common/eval.rb
|
UTF-8
| 3,392
| 2.765625
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Kernel
# Names of local variables at point of call (including evaled)
#
def local_variables
locals = []
scope = Rubinius::VariableScope.of_sender
# Ascend up through all applicable blocks to get all vars.
while scope
if scope.method.local_names
scope.method.local_names.each do |name|
name = name.to_s
locals << name
end
end
# the names of dynamic locals is now handled by the compiler
# and thusly local_names has them.
scope = scope.parent
end
locals
end
module_function :local_variables
# Obtain binding here for future evaluation/execution context.
#
def binding
return Binding.setup(
Rubinius::VariableScope.of_sender,
Rubinius::CompiledMethod.of_sender,
Rubinius::StaticScope.of_sender,
self)
end
module_function :binding
# Evaluate and execute code given in the String.
#
def eval(string, binding=nil, filename=nil, lineno=1)
filename = StringValue(filename) if filename
lineno = Type.coerce_to lineno, Fixnum, :to_i
if binding
if binding.kind_of? Proc
binding = binding.binding
elsif binding.respond_to? :to_binding
binding = binding.to_binding
end
unless binding.kind_of? Binding
raise ArgumentError, "unknown type of binding"
end
filename ||= binding.static_scope.active_path
else
binding = Binding.setup(Rubinius::VariableScope.of_sender,
Rubinius::CompiledMethod.of_sender,
Rubinius::StaticScope.of_sender,
self)
filename ||= "(eval)"
end
binding.static_scope = binding.static_scope.dup
be = Rubinius::Compiler.construct_block string, binding,
filename, lineno
be.set_eval_binding binding
be.call_on_instance(binding.self)
end
module_function :eval
private :eval
end
class Module
#--
# These have to be aliases, not methods that call instance eval, because we
# need to pull in the binding of the person that calls them, not the
# intermediate binding.
#++
def module_eval(string=undefined, filename="(eval)", line=1, &prc)
# we have a custom version with the prc, rather than using instance_exec
# so that we can setup the StaticScope properly.
if prc
unless string.equal?(undefined)
raise ArgumentError, "cannot pass both string and proc"
end
# Return a copy of the BlockEnvironment with the receiver set to self
env = prc.block
static_scope = env.repoint_scope self
return env.call_under(self, static_scope, self)
elsif string.equal?(undefined)
raise ArgumentError, 'block not supplied'
end
string = StringValue(string)
filename = StringValue(filename)
# The staticscope of a module_eval CM is the receiver of module_eval
ss = Rubinius::StaticScope.new self, Rubinius::StaticScope.of_sender
binding = Binding.setup(Rubinius::VariableScope.of_sender,
Rubinius::CompiledMethod.of_sender,
ss)
be = Rubinius::Compiler.construct_block string, binding,
filename, line
be.call_under self, ss, self
end
alias_method :class_eval, :module_eval
end
| true
|
40f476049ab8f5f902a18876a02c28e6d5b8c9f7
|
Ruby
|
guspowell/Battleships
|
/spec/board_spec.rb
|
UTF-8
| 812
| 2.984375
| 3
|
[] |
no_license
|
require 'board'
require 'player'
describe Board do
let(:board) { Board.new }
let(:player) { Player.new }
let(:ship) { Ship.new(2) }
it 'should have no ships to start' do
expect(board.ship_count).to eq 0
end
it "should be able to receive ships from the player" do
player.place(board, ship, ['a1','a2'])
player.place(board, ship, ['b1', 'b2'])
expect(board.ship_count).to eq 2
end
it "should be able to receive ships from the player in a position" do
board.receive(ship, 'j2')
expect(board.ship_count).to eq 1
end
it "should be able to fill places given the coordinates" do
player.place(board,player.patrol_boat,['a1','b1'])
board.fill_cells
expect(board.places[:a1]).to eq(:s) #check cell contents =
expect(board.places[:b1]).to eq(:s)
end
end
| true
|
e0f1b00bce3e385cb3e04afe1c861a43c92ffd39
|
Ruby
|
filip373/ruby_algorithms
|
/enumerable.rb
|
UTF-8
| 1,389
| 3.296875
| 3
|
[] |
no_license
|
module Enumerable
def my_each
self.size.times do |time|
yield self.to_a[time]
end
end
def my_each_with_index
self.size.times do |time|
yield self.to_a[time], time
end
end
def my_select
arr = []
self.my_each do |elem|
arr.push elem if yield elem
end
return arr
end
def my_all?
self.my_each do |elem|
return false unless yield elem
end
return true
end
def my_none?
self.my_each do |elem|
return false if yield elem
end
return true
end
def my_count obj = (no_arg = true), &block
unless no_arg
return self.my_select do |elem|
elem == obj
end.size
end
if block_given?
return self.my_select(&block).size
else
return self.size
end
end
def my_map
arr = []
self.each do |elem|
arr.push yield elem
end
return arr
end
def my_inject proc = (no_proc = true), initial = self[0]
memo = initial
return memo if no_proc
self.each do |elem|
memo = proc.call memo, elem
end
if block_given?
memo2 = initial
self.each do |elem|
memo2 = yield memo2, elem
end
return memo, memo2
else
return memo
end
end
end
def multiply_els arr
proc = Proc.new do |memo, elem|
memo *= elem
end
return arr.my_inject(proc, 1) { |m,e| m *= e }
end
| true
|
3c1e17fde955b1619f725c3753be36ad8552f3b8
|
Ruby
|
pedro-ivo-molina/bank-slip-validator
|
/validator.rb
|
UTF-8
| 848
| 2.53125
| 3
|
[] |
no_license
|
class Validator
attr_reader :body_annotations
def initialize
@header_errors = []
@body_errors = []
@body_annotations = []
@footer_errors = []
end
def validate_header(bank_slip:, rules:)
rules.each do |rule|
rule.validate(bank_slip)
@header_errors << rule.error unless rule.error.empty?
end
return @header_errors
end
def validate_body(bank_slip:, rules:)
rules.each do |rule|
rule.validate(bank_slip)
@body_errors << rule.error unless rule.error.empty?
@body_annotations << rule.annotation unless rule.annotation.empty?
end
return @body_errors
end
def validate_footer(bank_slip:, rules:)
rules.each do |rule|
rule.validate(bank_slip)
@footer_errors << rule.error unless rule.error.empty?
end
return @footer_errors
end
end
| true
|
9a5af248af913ef1d60efd2b8a3ec901ba9cd4ab
|
Ruby
|
huyu398/manmenmi
|
/manmenmi.rb
|
UTF-8
| 2,833
| 2.53125
| 3
|
[] |
no_license
|
require 'capybara'
require 'capybara-webkit'
require 'logger'
require 'yaml'
require_relative 'tag_reader'
require_relative 'errors'
MANMENMI_ROOT = File.expand_path(File.dirname(__FILE__))
AUDIO_PREFIX = "#{MANMENMI_ROOT}/voice"
NFCPY_PREFIX = "#{MANMENMI_ROOT}/nfcpy/0.9"
LOG_PREFIX = "#{MANMENMI_ROOT}/log"
config = YAML.load(File.read("#{MANMENMI_ROOT}/config.yml"))
URL = config['url']
USERS = config['users']
logger = Logger.new("#{LOG_PREFIX}/test.log")
logger.level = Logger::INFO
logger.info('Start MANMENMIIIIII!!!!!!!')
nfc = TagReader.new
loop do
begin
logger.info("Start polling")
tag = nfc.read rescue (raise Errors::NFCReadError.new("Can't read a nfc tag", __LINE__))
# manmenmi!!!
`mplayer #{AUDIO_PREFIX}/comeonbaby.wav 2>/dev/null`
logger.info("Read a tag of uid:#{tag}")
user = {}
USERS.each do |_user|
if _user['uid'] == tag
user = _user
end
end
raise Errors::UserRecognizeError.new("No user with uid:#{tag}", __LINE__) if user.empty?
logger.info("Recognize a user with id:#{user['id']} name:#{user['name']}")
session = Capybara::Session.new(:webkit)
# login
session.visit(URL)
session.select(user['name'], from: '_ID')
session.fill_in('Password', with: user['password'])
session.click_button('ログイン')
raise Errors::LoginError.new("Invalid password for user:#{user['name']}", __LINE__) if session.title.match(/エラー/)
logger.info('Success login')
# arrived or left
login_time = Time.now
timecard_table = session.all(:xpath, 'html/body/div/div/div/table/tbody/tr/td/table/tbody/tr/td/div/div/div/form/table/tbody/tr/td')
arrive_cell, leave_cell = [timecard_table.at(0), timecard_table.at(1)]
arrive_time = Time.parse(arrive_cell.text.match(/\d{2}:\d{2}/)[0])
if login_time < arrive_time + 15 * 60 # margin 15min
`mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null`
logger.info("#{user['name']} already logined cybozu")
else
if arrive_cell.has_button?('出社')
leave_cell.click_button('出社')
raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__) if session.title.match(/エラー/)
`mplayer #{AUDIO_PREFIX}/goodmorn.wav 2>/dev/null`
logger.info("#{user['name']} arrived office")
elsif leave_cell.has_button?('退社')
leave_cell.click_button('退社')
raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__) if session.title.match(/エラー/)
`mplayer #{AUDIO_PREFIX}/goodbay.wav 2>/dev/null`
logger.info("#{user['name']} left office")
else
raise Errors::UnexpectedError.new("!!! Unexpeced error !!!", __LINE__)
end
end
rescue => e
`mplayer #{AUDIO_PREFIX}/error.wav 2>/dev/null`
logger.error(e.message)
end
end
| true
|
1b5b5026a1b64b07bdf61d825cfa84fb185f413d
|
Ruby
|
CJStadler/state_machine_checker
|
/lib/state_machine_checker/state_result.rb
|
UTF-8
| 1,115
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
module StateMachineChecker
# The result of checking whether this state satisfies a formula.
class StateResult
# @param [Boolean] satisfied
# @param [Array<Symbol>] path
def initialize(satisfied, path)
@satisfied = satisfied
@path = path
end
# Whether the formula is satisfied from this state.
#
# @return [true, false]
def satisfied?
satisfied
end
# A witness that the formula is satisfied from this state.
#
# @return [Array<Symbol>] an array of the names of transitions.
def witness
if satisfied?
path
end
end
# A counterexample demonstrating that the formula is not satisfied from this
# state.
#
# @return [Array<Symbol>] an array of the names of transitions.
def counterexample
unless satisfied?
path
end
end
def or(other)
if satisfied?
self
else
other
end
end
def and(other)
if !other.satisfied?
other
else
self
end
end
private
attr_reader :satisfied, :path
end
end
| true
|
ee0e187c1f0ab6b5b0b30312ecfcab794440e64b
|
Ruby
|
msomji/bowling_kata
|
/bowl.rb
|
UTF-8
| 3,918
| 3.484375
| 3
|
[
"MIT"
] |
permissive
|
# as a bowler I want to be able to start a new game
# as a bowler I want to be able to bowl
# as a bowler I want to be able to be able to see how many pins I knocked out after each bowl
# as a bowler I want to be able to see if I get a spare or a strike
# as a bowler I want to be able to see my score after every frame
# as a bowloer I would like to get some instructions
#as a bowler I would want to be able to mannuall enter how many pins I knock out
# features
# as a bowler I want to have a name?
class Bowl
attr_reader :score, :frame, :score_board
def initialize
@score = 0
@frame = 0
@score_board = [[0,0,0]]
instructions
end
# sdfg
def instructions
"Instructions:
You have played bowling before! here are a couple methods to help you around this game!
To bowl - bowl(first_try, second_try)
To bowl bonus frames(10th frame) - bonus(first_try, second_try)
To check Score - score
To reset game - reset
To get instructions again - instructions
"
end
def bowl(trial1, trial2)
if trial2 + trial1 <= 10 && trial1 >= 0 && trial2 >= 0
user_updates(trial1,trial2)
else
"try again! you can knock out a max of only 10 pins per turn and positive numbers"
end
end
def bonus(bowl1, bowl2)
if @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] == 10
if bowl1 == 10
update_score_board(bowl1,0)
"SRIKE | One more Bonus roll!"
elsif bowl1 + bowl2 == 10
update_score_board(bowl1,bowl2)
"SPARE! #{bowl1} / #{bowl2} | Game Over"
else
update_score_board(bowl1,bowl2)
"#{bowl1} / #{bowl2} | Game Over"
end
elsif @frame == 10 && bowl2 + bowl1 <= 10 && bowl1 >= 0 && bowl2 >= 0 && @score_board[-2][0] != 10 && @score_board[-2][0] + @score_board[-2][1] == 10
if bowl1 == 10
update_score_board(bowl1,0)
"SRIKE | Game Over"
else
update_score_board(bowl1,0)
"#{bowl1} / 0 | Game Over"
end
elsif @frame == 11 && bowl1 >= 0 && @score_board[-2][0] == 10 && @score_board[-3][0] == 10
update_score_board(bowl1,0)
"SRIKE | Awesome!! | Game Over!"
else
"No bonus rounds for you sir"
end
end
def score
@score = 0
next_frame = 0
@score_board.each do |round|
next_frame +=1
if round[0] == 10
@score += round[0] + @score_board[next_frame][0] + @score_board[next_frame][1]
elsif round[0] + round[1] == 10
@score += 10 + @score_board[next_frame][0]
else
@score += round[0] + round[1]
end
end
@score
end
def reset
@score = 0
@frame = 0
@score_board = [[0,0,0]]
end
private
def update_score_board(trial1, trial2)
@score_board.insert(-2, [trial1, trial2])
@frame += 1
end
def user_updates(trial1,trial2)
if @frame < 9
pre_last_frame_user_updates(trial1,trial2)
elsif @frame == 9
last_frame_user_updates(trial1,trial2)
else
"The Game is over buddy! Make a new Game"
end
end
def pre_last_frame_user_updates(trial1,trial2)
if trial1 == 10
update_score_board(trial1,0)
"STRIKE!"
elsif trial1 + trial2 == 10
update_score_board(trial1,trial2)
"SPARE! #{trial1} / #{trial2}"
else
update_score_board(trial1,trial2)
"#{trial1} / #{trial2}"
end
end
def last_frame_user_updates(trial1,trial2)
if trial1 == 10
update_score_board(trial1,0)
"STRIKE! | You have two more bonus bowl! Use the bonus method to enter your bonus pins"
elsif trial1 + trial2 == 10
update_score_board(trial1,trial2)
"SPARE! #{trial1} / #{trial2} | You have one more bonus bowl! Use the bonus method to enter your bonus pins"
else
update_score_board(trial1,trial2)
"#{trial1} / #{trial2} | Game Over"
end
end
end
Bowl.new
| true
|
502aeccf5aa28e42cc789c26ff40cb8a662e5a13
|
Ruby
|
v9n/proc
|
/study/interviewcake/matching-parens/spec.rb
|
UTF-8
| 462
| 2.796875
| 3
|
[] |
no_license
|
require_relative 'solution.rb'
require 'minitest/spec'
require 'minitest/autorun'
describe InterviewCake::MatchingParens do
it 'returns correct close posstion' do
s = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
solution = InterviewCake::MatchingParens.new
solution.perform(s, 10).must_equal 79
solution.perform(s, 57).must_equal 78
solution.perform(s, 68).must_equal 77
end
end
| true
|
2faaea69eca77e2681b2c2e070515301c5110172
|
Ruby
|
StlMaris123/ruby_tutorials
|
/learn ruby the hard way/ex3.rb
|
UTF-8
| 1,544
| 4.40625
| 4
|
[] |
no_license
|
#mathematics
#use of interpolation is how we insert Ruby computations
#displays the following code
puts "i will now count my hens"
#executes the computations and interpolates it wit Hens and also Roosters
puts "Hens #{25 + 30 / 6}"
puts "Roosters #{100-25*3%4}"
#displays the following code
puts "I will now count my eggs"
#Executes the following computation using PEMDA and displays the answer
puts 3+2+1-5+4%2-1/4%6
#displays the following code
puts "is it true that 3 + 2 < 5 - 7"
#compares the value of 3+2 and 5-7 and returns a boolean value
puts 3 + 2 < 5 - 7
#Executes the code inside the parenthesis and concatenates it with the string
puts "what is 3 + 2? #{3+2}"
puts "what is 5 - 7? #{5-7}"
#Displays the following thhe code
puts "oh thats why its false"
puts "How about some more?"
#executes the code inside the parenthesis and concatenates the boolean value value to the string
puts "is it greater? #{5 > -2}"
puts "is it greater or equal? #{5 >= -2}"
puts "is it less or equal? #{5 <= -2}"
#using floating point numbers
puts "i will now count my hens"
puts "Hens #{25.00 + 30.00 / 6.00}"
puts "Roosters #{100.00 - 25.00 * 3.00 % 4.00}"
puts "I will now count my eggs"
puts 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 % 6.00
puts "is it true that 3 + 2 < 5 - 7"
puts 3 + 2 < 5 - 7
puts "what is 3 + 2? #{3+2}"
puts "what is 5 - 7? #{5-7}"
puts "oh thats why its false"
puts "How about some more?"
puts "is it greater? #{5 > -2}"
puts "is it greater or equal? #{5 >= -2}"
puts "is it less or equal? #{5 <= -2}"
| true
|
4fb73857aa983f0cfc10960b91ccfadff7049233
|
Ruby
|
alrawi90/day_name_displayer
|
/day_name_display.rb
|
UTF-8
| 1,185
| 3.65625
| 4
|
[] |
no_license
|
class Day_name_displayer
def initialize
welcome
menu
end
def welcome
puts ""
puts ""
puts "welcome to ---Day Name Displayer----"
puts ""
end
def msg
puts "Please enter a number from 1-7 OR enter 'exit' to end application ."
end
def menu
msg
input=nil
while(input !="exit")
puts ""
input=gets.strip
if input =="1"
puts "Sunday"
elsif input =="2"
puts "Monday"
elsif input=="3"
puts "Tuesday"
elsif input=="4"
puts "Wednesday"
elsif input=="5"
puts "Thursday"
elsif input=="6"
puts "Friday"
elsif input=="7"
puts "Saturday"
elsif input=="exit"
puts "Thank you for using --Day Name Displayer--"
puts ""
break
else
puts "invalid input"
msg
end
end
end
end
obj=Day_name_displayer.new
| true
|
77fc6c7b8fcc52837b08ba5995e88d34e3ec4746
|
Ruby
|
squareben1/review_12_spellcheck
|
/lib/spellchecker.rb
|
UTF-8
| 818
| 3.75
| 4
|
[] |
no_license
|
class SpellChecker
def initialize(dictionary=[])
@dictionary = homogenise_arr(dictionary)
end
def spellcheck(string)
words = split_string(string)
checked_words = []
words.each do | word |
checked_words.push(word_check(word))
end
checked_words.join(" ")
end
def add_words(string)
new_words = split_string(string)
lower_case_words = homogenise_arr(new_words)
@dictionary.push(*lower_case_words)
end
private
def homogenise_arr(arr)
arr.map!(&:downcase)
end
def split_string(string)
# gives potential for extension when client needs punctuation, etc.
string.split(" ")
end
def word_check(word)
down_case_word = word.downcase
if !@dictionary.include?(down_case_word)
"~#{word}~"
else
word
end
end
end
| true
|
103902ed24dc2e9570dc384f42565e5dedda3a22
|
Ruby
|
johndierks/ruby-intro
|
/vehicles.rb
|
UTF-8
| 306
| 3.609375
| 4
|
[] |
no_license
|
class Vehicle
def go
puts "Pressed Gas Pedal"
end
def stop
puts "Pressed Brake Pedal"
end
end
class Convertible < Vehicle
def lower_top
puts "It's a nice day, so I put the top down"
end
def raise_top
puts "Looks like it's going to rain, so I raised the top."
end
end
| true
|
91f16e625d58019b95a8823cc5b085d82cd43387
|
Ruby
|
Dwein9/ruby-object-initialize-lab-web-1116
|
/lib/person.rb
|
UTF-8
| 73
| 2.765625
| 3
|
[] |
no_license
|
class Person
def initialize(the_name)
@name = the_name
end
end
| true
|
4733d1c6cfce81aa46248e89b7d5bb74a1f1c54e
|
Ruby
|
jordanluce/AdvancedActiveRecord
|
/has_many_activerecord.rb
|
UTF-8
| 5,095
| 3.359375
| 3
|
[] |
no_license
|
#has_many associations activerecord
class Person < ActiveRecord::Base
belongs_to :location
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :people
end
class Location < ActiveRecord::Base
has_many :people
end
____________________________________________________________________________________________________________________
Role.all
id name billable
1 Developer t
2 Manager f
3 Unassigned f
____________________________________________________________________________________________________________________
Location.all
id name billable
1 Boston 1
2 New York 1
3 Denver 2
____________________________________________________________________________________________________________________
People.all
id name role_id location_id
1 Wendell 1 1
2 Christie 1 1
3 Sandy 1 3
4 Eve 2 2
____________________________________________________________________________________________________________________
#First we want to fine all distinct locations with at least one person who belongs to a billable role.
#We can also use joins with has_many just like on belongs_to
Location.joins(:people)
locations | people
id name region_id | id name role_id location_id
1 Boston 1 | 1 Wendell 1 1
1 Boston 1 | 2 Christie 1 1
3 Denver 2 | 3 Sandy 1 3
2 New York 1 | 4 Eve 2 2
____________________________________________________________________________________________________________________
#The use of has_many_through
Location.joins(people: :role)
locations | people | roles
id name region_id | id name role_id location_id | id name billable
1 Boston 1 | 1 Wendell 1 1 | 1 Developer t
1 Boston 1 | 2 Christie 1 1 | 1 Developer t
3 Denver 2 | 3 Sandy 1 3 | 1 Developer t
2 New York 1 | 4 Eve 2 2 | 2 Manager f
#Then now we can filter through with .where
Location.joins(people: :role).where(roles: { billable: true })
#Which then returns something like that:
#
locations | people | roles
id name region_id | id name role_id location_id | id name billable
1 Boston 1 | 1 Wendell 1 1 | 1 Developer t
1 Boston 1 | 2 Christie 1 1 | 1 Developer t
3 Denver 2 | 3 Sandy 1 3 | 1 Developer t
#But now we can notice that we see BOSTON TWICE... We can remiediate to this with the (distinct)method.
#
Location.joins(people: :role).where(roles: { billable: true}).distinct
#Which now returns something like this:
#
locations
id name region_id
3 Denver 2
1 Boston 1
#We can now encapsulate our query in our object and do:
#
class location < ActiveRecord::Base
def self.billable
joins(people: :role).where(roles: { billable: true }).distinct
end
end
Location.billable
____________________________________________________________________________________________________________________
#Now we want to order the billable locations by region name, then by location name.
#
class Location < ActiveRecord::Base
belongs_to :region
end
class Region < ActiveRecord::Base
has_many :locations
end
#So straigth away we can do the following query to get the billable locations to be ordered by region name then by location name:
#
Location.joins(:region).merge(Region.order(:name)).order(:name)
#Which gives us the following:
#
locations | regions
id name region_id | id name
1 Boston 1 | 1 East
2 New York 1 | 1 East
3 Denver 2 | 2 West
#So now we can create our method on the model to scope things:
#
class Location < ActiveRecord::Base
def self.billable
joins(people: :role).where(roles: { billable: true }).distinct
end
def self.by_region_and_location_name
joins(:region).merge(Region.order(:name)).order(:name)
end
end
#Now the problem that we are going to have is we won't be able to join our scopes and do:
#
XXXXXX Location.billable.by_region_and_location_name XXXXXX
#This is because the (distinct) method.
#We need to use a sub-query with the (from) method
#Let's use it to first return distinct billable locations.
#
Location.from(Location.billable, :locations)
#Which returns this:
#
locations
id name region_id
3 Denver 2
1 Boston 1
#So now we can put it all together
#
Location.from(Location.billable, :locations).by_region_and_location_name
locations | regions
id name region_id | id name
1 Boston 1 | 1 East
3 Denver 2 | 2 West
| true
|
3b7653ccbcc67d487eecff3adc342d73d8fcda77
|
Ruby
|
danabo/zhat
|
/_plugins/jumpto.rb
|
UTF-8
| 384
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module Jekyll
class JumpToBlock < Liquid::Block
require "shellwords"
def initialize(tag_name, text, tokens)
super
@text = text.shellsplit
end
def render(context)
contents = super
"<a name='#{@text[0]}'></a>"\
"<span class='jump_to'>#{contents}</span>"
end
end
end
Liquid::Template.register_tag('jumpto', Jekyll::JumpToBlock)
| true
|
2063d534906cb9df672fdfa25f7da4e388116b43
|
Ruby
|
stupergenius/Software-Engineering-for-SaaS
|
/assignment1/part2_spec.rb
|
UTF-8
| 3,078
| 3.265625
| 3
|
[] |
no_license
|
load 'part2.rb'
describe "#rps_game_winner" do
context "fail states" do
it "should raise when number of players is not two" do
expect { rps_game_winner([]) }.to raise_error(WrongNumberOfPlayersError)
expect { rps_game_winner([["Armando", "P"]]) }.to raise_error(WrongNumberOfPlayersError)
expect { rps_game_winner([["Armando", "P"], ["Dave", "S"], ["Ben", "P"]]) }.to raise_error(WrongNumberOfPlayersError)
end
it "should raise when an invalid strategy is given" do
expect { rps_game_winner([["Armando", "P"], ["Dave", "F"]]) }.to raise_error(NoSuchStrategyError
)
end
end
context "ties" do
it "should return the first player in case of a tie" do
p1 = ["Armando", "P"]
p2 = ["Dave", "P"]
rps_game_winner([p1, p2]).should eq(p1)
rps_game_winner([p2, p1]).should eq(p2)
end
end
context "winners" do
it "should return rock beats scissors" do
p1 = ["Armando", "R"]
p2 = ["Dave", "S"]
rps_game_winner([p1, p2]).should eq(p1)
rps_game_winner([p2, p1]).should eq(p1)
end
it "should return paper beats rock" do
p1 = ["Armando", "P"]
p2 = ["Dave", "R"]
rps_game_winner([p1, p2]).should eq(p1)
rps_game_winner([p2, p1]).should eq(p1)
end
it "should return scissors beats paper" do
p1 = ["Armando", "S"]
p2 = ["Dave", "P"]
rps_game_winner([p1, p2]).should eq(p1)
rps_game_winner([p2, p1]).should eq(p1)
end
end
end
describe "#is_single_round" do
game = [ ["Armando", "P"], ["Dave", "S"] ]
tournament =
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ],
]
it "should be able to detect a single round game" do
is_single_round?(game).should be_true
is_single_round?(tournament).should be_false
end
end
describe "#rps_tournament_winner" do
winner = ["Richard", "R"]
tournament1 = [ winner, ["Michael", "S"] ]
tournament4 =
[
[ ["Armando", "P"], ["Dave", "S"] ],
tournament1,
]
tournament8 =
[
tournament4,
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ],
],
]
tournament16 =
[
tournament8,
[
[
[ [ "P1", "P" ], [ "P2", "S" ] ],
[ [ "P3", "R" ] , [ "P4", "P" ] ],
],
[
[ [ "P7", "P" ], [ "P5", "S" ] ],
[ [ "P9", "R" ] , [ "P10", "P" ] ],
],
],
]
it "should return the winner" do
rps_tournament_winner(tournament1)[0].should eq "Richard"
rps_tournament_winner(tournament4)[0].should eq "Richard"
rps_tournament_winner(tournament8)[0].should eq "Richard"
rps_tournament_winner(tournament16)[0].should eq "Richard"
end
end
| true
|
8cad1f79ccd8091f0b35197064bfd57ae7652eef
|
Ruby
|
shoebham/Ruby_Projects_the_odin_project
|
/Project_Tic_Tac_Toe/tic_tac_toe.rb
|
UTF-8
| 3,406
| 3.375
| 3
|
[] |
no_license
|
LINES = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,7],[1,4,7],[2,5,8],[3,6,9]]
class Game
def initialize(player_1_class,player_2_class)
@board = Array.new(10)
@current_player_id=0
@players = [player_1_class.new(self,"X",1),player_2_class.new(self,"O",2)]
puts "#{current_player} goes first"
end
attr_reader :board, :current_player_id
def play
loop do
place_marker(current_player)
if player_won?(current_player)
p "#{current_player} is the winner"
print_board
return
elsif board_full?
p "It's a draw!"
print_board
return
end
switch_player!
end
end
def free_positions
(1..9).select{|pos| @board[pos].nil?}
end
def place_marker(player)
position = player.select_position!
p "#{player} selects #{player.marker} position #{position}"
@board[position] = player.marker
end
def player_won?(player)
LINES.any? do |i|
i.all? {|j| @board[j] == player.marker}
end
end
def board_full?
free_positions.empty?
end
def other_player_id
1-@current_player_id
end
def switch_player!
@current_player_id = other_player_id
end
def current_player
@players[current_player_id]
end
def print_board
col_sep = " | "
row_sep = "--+---+--"
label_pos = ->(pos){ @board[pos] ? @board[pos] : pos}
row_for_display= ->(row){row.map(&label_pos).join(col_sep)}
row_pos = [[1,2,3],[4,5,6],[7,8,9]]
rows_for_display=row_pos.map(&row_for_display)
puts rows_for_display.join("\n"+ row_sep +"\n")
end
end
class Player
attr_reader:marker,:num
def initialize(game,marker,num)
@game = game
@marker =marker
@num = num
end
end
class HumanPlayer < Player
attr_reader:i
def select_position!
@game.print_board
loop do
puts "Select your #{marker} position"
selection = gets.to_i
return selection if @game.free_positions.include?(selection)
puts "position #{selection} position is not available"
end
end
def to_s
"Human #{num}"
end
end
puts players_with_human = [HumanPlayer, HumanPlayer].shuffle
Game.new(*players_with_human).play
| true
|
17a9860a23a7d87cfbb573810d55bf79bf09ccb6
|
Ruby
|
idimitrov07/ruby_ood_book
|
/chapter_five/duck_overlook.rb
|
UTF-8
| 437
| 3.15625
| 3
|
[] |
no_license
|
# overlooking the duck
class Trip
attr_reader :bicycles, :customers, :vehicle
# this 'mechanic' could be of any class..
def prepare(mechanic)
mechanic.prepare_bicycles(bicycles)
end
# ...
end
# 'Mechanic' class in not referenced anywhere in the class above
class Mechanic
def prepare_bicycles(bicycles)
bicycles.each { |bicycle| prepare_bicycle(bicycle) }
end
def prepare_bicycle(bicycle)
#...
end
end
| true
|
fd588b4372f00639f2c3222c062f12d7199a4e30
|
Ruby
|
smainar/backend_prework
|
/day_1/exe3-1.rb
|
UTF-8
| 296
| 3.578125
| 4
|
[] |
no_license
|
puts "I will count my books."
puts "Old text books #{18 - 2 * 3}."
puts "Autobiographies #{3 + 3 % 1}."
puts "Non-fiction #{27 + 14 / 2 - 5}."
puts "Fiction #{56 - 17 % 3}."
# Results:
# I will count my books.
# Old text books 12.
# Autobiographies 3.
# Non-fiction 29.
# Fiction 54.
| true
|
9a2605235dfd8be5f55e327771ce6732dd30a5ed
|
Ruby
|
goyox86/razer
|
/lib/razer.rb
|
UTF-8
| 984
| 3.640625
| 4
|
[
"MIT"
] |
permissive
|
require "razer/version"
module Razer
#
# A small utility class which for flattening nested arrays.
#
class Flattener
# Flattens the input +array+ of arrays into a uni-dimensional one
# preserving the relative order of eelements. If an empty array is
# provided then the exact same empty array objevct will be returned.
#
# The algorithm is guaranteed to flatten the input array in O(n) time
# and O(n) space with +n+ being the sum of the sizes of all involved
# arrays including the top level one.
#
# input_array = [1, [2, 3, [4, 5, [6]]]]
#
# flattener = Flattener.new
# flattener.flatten(input_array) # => [1, 2, 3, 4, 5, 6]
#
def flatten(array, accumulator = [])
return array if array.empty?
array.each do |element|
if element.is_a?(Array)
flatten(element, accumulator)
else
accumulator.push(element)
end
end
accumulator
end
end
end
| true
|
3a371458f69091c787cb7e3bd844db7220ab7ff9
|
Ruby
|
nickfryer21/screw-charlie
|
/app/models/game_player.rb
|
UTF-8
| 745
| 2.65625
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: game_players
#
# id :integer not null, primary key
# game_id :integer
# player_id :integer
# slot_id :integer
#
class GamePlayer < ActiveRecord::Base
belongs_to :game
belongs_to :player
has_one :hand, :dependent => :destroy
has_many :turns, :dependent => :destroy
belongs_to :slot
after_create do
self.hand = Hand.create!
# Make sure newly added players are added to a slot
next_slot = self.game.slots.where(available: true).first
unless next_slot.nil?
self.slot = next_slot
self.save
next_slot.available = false
next_slot.save!
end
end
def draw_card(draw_pile)
self.hand.cards << draw_pile.draw_card
end
end
| true
|
9f55d4455b0328267d0dc466c14056b4f7f75add
|
Ruby
|
fbenevides/conf-algorithm
|
/lib/conferences/track.rb
|
UTF-8
| 904
| 3.265625
| 3
|
[] |
no_license
|
module Conferences
class Track
attr_reader :name
def initialize(name, sessions = [Session.new('Morning', 9, 12), Session.new('Afternoon', 13, 17)])
@name = name
@sessions = sessions
end
def duration
@sessions.map(&:duration).reduce(&:+)
end
def distribute(talks)
talks.sort_by(&:duration)
removed = []
@sessions.each do |session|
sum = 0
talks.each do |talk|
if sum != session.duration
if session.total + talk.duration <= session.duration
session << talk
sum += talk.duration
removed << talk
end
end
end
talks -= removed
end
talks
end
def show
puts "#{name}"
@sessions.each do |session|
puts " #{session.name}"
session.show
puts " "
end
end
end
end
| true
|
babbe9f2186192f1da4a927285d6f42b52e3c223
|
Ruby
|
junyuanxue/learn_to_program
|
/ch14-blocks-and-procs/better_program_logger.rb
|
UTF-8
| 448
| 3.4375
| 3
|
[] |
no_license
|
$indent = 0
def better_log desc, &block
puts " " * $indent + "Beginning \"#{desc}\"..."
$indent += 1
result = block.call
$indent -= 1
puts " " * $indent + "...\"#{desc}\" finished, returning: #{result.to_s}"
end
better_log "outer block" do
better_log "some little block" do
better_log "teeny-tiny block" do
"lots of love"
end
42
end
better_log "yet another block" do
"I like Indian food!"
end
true
end
| true
|
659316aa79719ba729942b2fc657afdaa0fe1e20
|
Ruby
|
CoopTang/module_0_capstone
|
/day_5/ex39.rb
|
UTF-8
| 2,297
| 4.4375
| 4
|
[] |
no_license
|
# Hashes in 'Learn Ruby the Hard way'
# Create a mapping of states to abbreviation
states = {
'Oregon' => 'OR',
'Florida' => 'FL',
'California' => 'CA',
'New York' => 'NY',
'Michigan' => 'MI'
}
# Creat a basic set of states and some cities in them
cities = {
'CA' => 'San Francisco',
'MI' => 'Detroit',
'FL' => 'Jacksonville'
}
# Add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# puts out some cities
puts '-' * 10
puts "NY State has: #{cities['NY']}"
puts "OR State has: #{cities['OR']}"
# puts some states
puts '-' * 10
puts "Michigan's abbreviation is: #{states['Michigan']}"
puts "Florida's abbreviation is: #{states['Florida']}"
# do it using the state then cities dict
puts '-' * 10
puts "Michigan has: #{cities[states['Michigan']]}"
puts "Florida has: #{cities[states['Florida']]}"
# puts every state abbreviation
puts '-' * 10
states.each do |state, abbrev|
puts "#{state} is abbreviated #{abbrev}"
end
# puts every city in state
puts '-' * 10
cities.each do |abbrev, city|
puts "#{abbrev} has the city #{city}"
end
# now do both at the same time
puts '-' * 10
states.each do |state, abbrev|
city = cities[abbrev]
puts "#{state} is abbreviated #{abbrev} and has city #{city}"
end
puts '-' * 10
# by default ruby says "nill" when something isn't in there
state = states['Texas']
if !state
puts "Sorry, no Texas."
end
# default values using ||= with the nill result
city = cities['TX']
city ||= 'Does Not Exist'
puts "The city for the state 'TX' is: #{city}"
# doing some of my own stuff
cities_of_co = ["Boulder", "Denver", "Colorado Springs"]
states['Colorado'] = 'CO'
cities['CO'] = cities_of_co
# let's print out the contents
puts '-' * 10
states.each do |state, abbrev|
city = cities[abbrev]
print "#{state} is abbreviated #{abbrev} and has "
# gotta handle an array differently than the original
if (city.class == Array)
print "cities "
cities_str = ""
city.each do |city|
cities_str += "#{city}, "
end
# remove the final space and comma
puts cities_str[0...-2]
else
puts "city #{city}"
end
end
| true
|
8073b475c3f9cf87336820c2f7437add4a43cc37
|
Ruby
|
arakla/binder-app
|
/app/helpers/application_helper.rb
|
UTF-8
| 1,325
| 2.625
| 3
|
[] |
no_license
|
module ApplicationHelper
def display_base_errors resource
return '' if (resource.errors.empty?) or (resource.errors[:base].empty?)
messages = resource.errors[:base].map { |msg| content_tag(:p, msg) }.join
html = <<-HTML
<div class="alert alert-error alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
#{messages}
</div>
HTML
html.html_safe
end
def time(display_time)
time_zone = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")
display_time.in_time_zone(time_zone).strftime("%I:%M%p")
end
def date(display_date)
time_zone = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")
display_date.in_time_zone(time_zone).strftime("%m/%d/%y")
end
def date_and_time(display_date_and_time)
[date(display_date_and_time), time(display_date_and_time)].compact.join(" ")
end
def format_boolean(bool)
bool ? "Yes" : "No"
end
def currency(display_currency)
number_to_currency(display_currency)
end
def format_downtime(downtime)
downtime = downtime.to_i
if downtime < 0
neg = '-'
downtime *= -1
else
neg = ''
end
hours = downtime / 60 / 60
minutes = downtime / 60 - hours * 60
return neg + ("%02d" % hours) + ":" + ("%02d" % minutes)
end
end
| true
|
bc69eede1366cf4d862db29f1cbd0d2247f0380f
|
Ruby
|
timbeiko/tealeaf-prework
|
/greetings.rb
|
UTF-8
| 177
| 3.90625
| 4
|
[] |
no_license
|
# greetings.rb
def greetings(name)
puts "Hi there, "+ name
end
name = gets.chomp
greetings(name)
x = 2
puts x = 2
p name="Joe"
four = "four"
print something = "nothing"
| true
|
cb186eccb2a05d681feeb207b686282f486dd8a7
|
Ruby
|
mdvincen/tts_projects
|
/unless.rb
|
UTF-8
| 77
| 3.015625
| 3
|
[] |
no_license
|
sum = 50
unless sum ==50
puts 'That is incorrect'
else
puts 'Correct'
end
| true
|
ab65df6218c1465eb922ba6ed8912f6957a0fbf7
|
Ruby
|
mgdelin/operators-online-web-ft-081219
|
/lib/operations.rb
|
UTF-8
| 182
| 2.96875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def unsafe?(speed)
if speed > 60
return true
elsif speed < 40
return true
else return false
end
end
def not_safe?(speed)
speed > 60 or speed < 40 ? true : false
end
| true
|
37823c86fc5e1317850a71e1bd760e3b39919357
|
Ruby
|
bemijonathan/tracker
|
/app/models/transaction.rb
|
UTF-8
| 435
| 2.53125
| 3
|
[] |
no_license
|
require "securerandom"
class Transaction < ApplicationRecord
belongs_to :user
before_save :getvalue
def encode (uuid)
return [uuid.tr('-', '').scan(/../).map(&:hex).pack('c*')].pack('m*').tr('+/', '-_').slice(0..21)
end
def getvalue()
val = SecureRandom.uuid
token = encode(val)
self.tracking_id = token.toUpcase
end
end
| true
|
03a5d9fdb45dbf687cc69a94a7e49a58dfbab955
|
Ruby
|
learn-co-students/houston-web-062419
|
/07-CLI-Application/lib/app.rb
|
UTF-8
| 564
| 3.03125
| 3
|
[] |
no_license
|
$prompt = TTY::Prompt.new
def start
puts 'Welcome to my APP!'
name
end
def name
name = $prompt.ask('What is your name?')
puts name
p = password
puts "Your password is: #{p}"
choices = %w(milk coffee tea orageJuice)
$prompt.multi_select("Select drinks?", choices)
end
# name = prompt.ask('What is your name?')
# puts name
# choice = prompt.yes?('Do you like Ruby?')
# puts choice
# secret = prompt.mask("What is your secret?")
# puts secret
# choice = prompt.select("Choose your destiny?", %w(Scorpion Kano Jax))
# puts choice
| true
|
d360de954a635d4546e2ffc30ece84f0a3b1c210
|
Ruby
|
1powechri2/BikeShare
|
/app/models/cart.rb
|
UTF-8
| 764
| 3.25
| 3
|
[] |
no_license
|
class Cart
attr_reader :contents
def initialize(initial_content)
@contents = initial_content || Hash.new(0)
end
def total_count
@contents.values.sum
end
def add_accessory(accessory_id)
@contents[accessory_id.to_s] ||= 0
@contents[accessory_id.to_s] += 1
end
def accessory_quantity(accessory_id)
@contents[accessory_id.to_s]
end
def subtotal(accessory_id)
accessory_quantity(accessory_id) * Accessory.find(accessory_id).price
end
def total
sub_totals = []
@contents.each do |id, quantity|
sub_totals.push(Accessory.find(id).price * quantity)
end
sub_totals.sum
end
def accessory_ids
ids = []
@contents.each do |id, quantity|
ids.push(id.to_i)
end
ids
end
end
| true
|
c9ab308c2df9f5af1df9e8f4bf2d5985e8660b52
|
Ruby
|
s6ruby/universum
|
/universum-contracts/tokens/token_test.rb
|
UTF-8
| 1,957
| 2.96875
| 3
|
[
"CC0-1.0"
] |
permissive
|
# to test the contract script run:
# $ ruby tokens/token_test.rb
require 'minitest/autorun'
require_relative 'token'
class TestToken < Minitest::Test
def setup
@token = Token.new(
name: 'Your Crypto Token',
symbol: 'YOU',
decimals: 8,
initial_supply: 1_000_000
)
end
def test_transfer
assert_equal 100_000_000_000_000, @token.balance_of( owner: '0x0000' )
assert_equal 0, @token.balance_of( owner: '0x1111' )
assert @token.transfer( to: '0x1111', value: 100 )
assert_equal 100, @token.balance_of( owner: '0x1111' )
assert @token.transfer( to: '0x2222', value: 200 )
assert_equal 200, @token.balance_of( owner: '0x2222' )
assert_equal 99_999_999_999_700, @token.balance_of( owner: '0x0000' )
end
def test_transfer_from
## note: NOT pre-approved (no allowance) - will FAIL
assert !@token.transfer_from( from: '0x1111', to: '03333', value: 30 )
assert_equal 0, @token.allowance( owner: '0x0000', spender: '0x1111' )
assert @token.approve( spender: '0x1111', value: 50 )
assert_equal 50, @token.allowance( owner: '0x0000', spender: '0x1111' )
### change sender to 0x0001
Contract.msg = { sender: '0x1111' }
pp Contract.msg
assert @token.transfer_from( from: '0x0000', to: '0x3333', value: 30 )
assert_equal 30, @token.balance_of( owner: '0x3333' )
assert_equal 99_999_999_999_970, @token.balance_of( owner: '0x0000' )
assert_equal 0, @token.balance_of( owner: '0x1111' )
### change sender back to 0x0000
Contract.msg = { sender: '0x0000' }
pp Contract.msg
assert @token.transfer( to: '0x1111', value: 1 )
assert_equal 99_999_999_999_969, @token.balance_of( owner: '0x0000' )
assert_equal 1, @token.balance_of( owner: '0x1111' )
end
end # class TestToken
| true
|
4275ab528d5840b3c7bc3a859b31bb1482410d28
|
Ruby
|
JDAVEHACKER/RubyLearning
|
/comparacion_combinado.rb
|
UTF-8
| 430
| 4.40625
| 4
|
[] |
no_license
|
puts "Operador de comparación combinada"
#Devuelve 0 si el primero y el segundo son iguales
#Devuelve 1 si el primero es mayor que el segundo
#Devuelve -1 si el primero es menor que el segundo
puts "ingrese dos número"
num1 = gets.chomp.to_i
num2 = gets.chomp.to_i
res= num1 <=> num2
if res == 0
puts "son iguales"
elsif res == 1
puts "#{num1} es mayor que #{num2}"
elsif res == -1
puts "#{num1} es menor que #{num2}"
end
| true
|
f031dba05393c7aa815b60f135c0b7dea604ec81
|
Ruby
|
paulalexrees/learn_to_program
|
/ch14-blocks-and-procs/grandfather_clock.rb
|
UTF-8
| 249
| 3.296875
| 3
|
[] |
no_license
|
def grandfather_clock &block
hours = if Time.new.hour > 12
Time.new.hour - 12
else
Time.new.hour
end
hours.times{
yield
}
end
dong = Proc.new {
puts "DONG!"
}
grandfather_clock &dong
| true
|
55fbbd4186f48f53254d844caa13709ebe04e92e
|
Ruby
|
octosteve/hangman
|
/lib/hangman/boundary/game_server.rb
|
UTF-8
| 1,351
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Boundary
class GameServer
attr_reader :name
def initialize(name:)
@name = name
@ractor = create_ractor
end
def make_guess(guess)
ractor.send([:make_guess, guess])
end
def won?
ractor.send([:won?, Ractor.current])
Ractor.receive
end
def lost?
ractor.send([:lost?, Ractor.current])
Ractor.receive
end
def word
ractor.send([:get_word, Ractor.current])
Ractor.receive
end
def masked_word
ractor.send([:get_masked_word, Ractor.current])
Ractor.receive
end
private
attr_reader :ractor
def create_ractor
words_path = "#{File.expand_path(__dir__)}/../../../assets/words.txt"
word_list = File.readlines(words_path).map(&:strip)
Ractor.new(word_list, name: name) do |word_list|
game = Core::Game.start_game(name, word_list)
loop do
case receive
in [:make_guess, guess]
game.make_guess(guess)
in [:won?, from]
from.send game.won?
in [:lost?, from]
from.send game.lost?
in [:get_word, from]
from.send game.selected_word
in [:get_masked_word, from]
from.send game.masked_word
end
end
end
end
end
end
| true
|
6e1dfe76b3dca4517b9f9f5de59425ebc36d097f
|
Ruby
|
klavinslab/ProtocolsForReview
|
/illumina_ngs/protocol/dilute_total_rna/protocol.rb
|
UTF-8
| 5,823
| 2.515625
| 3
|
[] |
no_license
|
# By Eriberto Lopez
# elopez3@uw.edu
# Production 10/05/18
# C µl
needs "RNA/RNA_ExtractionPrep"
needs "Illumina NGS Libs/RNASeq_PrepHelper"
needs "Illumina NGS Libs/TruSeqStrandedTotalRNAKit"
class Protocol
include RNA_ExtractionPrep
include RNASeq_PrepHelper
include TruSeqStrandedTotalRNAKit
INPUT = "Total RNA"
OUTPUT = "Diluted Total RNA Plate"
INPUT_RNA_CONC = 300#ng # TODO: Find right starting concentration for an input so that the enrich fragment step does not over amplify the cDNA library and make it too concentrated
FINAL_VOL = 10
def main
operations.make
# Retrieve RNA extracts and let thaw at room temp
thaw_rna_etracts
# Get ice for following reagents
get_ice
# Sanatize bench
sanitize
# Retrieve materials for rRNA depletion and Fragmentation
gather_RiboZero_Deplete_Fragment_RNA_materials(operation_type())
normalize_and_fill_rna_plates()
show {note "<b>Put away the following.</b>"}
operations.store
return {}
end # Main
# Caluculates the volume needed from the RNA sample to meet the desired final concentration
#
# @params rna_conc [int] is the concentration of RNA in [ng/ul]
# @returns rna_dil_vol [int] is the volume of RNA required to meet the desired final conc.
def dilute_rna(rna_conc)
r_num = Random.new
(debug) ? rna_conc = r_num.rand(1000) : rna_conc = rna_conc # For testing & debugging
rna_dil_vol = (INPUT_RNA_CONC.to_f/rna_conc.to_f)
return rna_dil_vol
end
# Calculates the volume of MG H2O required to meet the desired final RNA conc
#
# @params rna_dil_vol [int] is the volume of RNA required to meet the desired final conc.
# @returns h2o_dil_vol [int] is the volume of water required to meet the desired final conc.
def dilute_h2o(rna_dil_vol)
h2o_dil_vol = FINAL_VOL - rna_dil_vol
if h2o_dil_vol < 0
return 0
else
return h2o_dil_vol
end
# (h2o_dil_vol < 0) ? (return 0) : (return h2o_dil_vol)
end
# Finds all RNA extractions in the job and directs tech to grab them - TODO: Sort by box/location
def thaw_rna_etracts()
rna_etracts = operations.map {|op| op.input(INPUT).item}
take(rna_etracts, interactive: true)
show do
title "Thawing Samples"
separator
note "Let the RNA Extract(s) thaw at room temperature."
end
end
# Directs tech to fill the output collection with the correct item, rna_vol, and water_vol into the appropriate well
#
# out_colleciions [Array of objs] is an array of collection objs that the RNAs will get diluted into
def normalize_and_fill_rna_plates()
r_num = Random.new
groupby_out_collection = operations.group_by {|op| op.output(OUTPUT).collection}
groupby_out_collection.each {|out_coll, ops|
obj_type = ObjectType.find(out_coll.object_type_id)
ops.each {|op|
rna_item = op.input(INPUT).item
rna_item.get(:concentration).nil? ? rna_conc = r_num.rand(1000) : rna_conc = rna_item.get(:concentration)
op.temporary[:rna_dil_vol] = dilute_rna(rna_conc)
op.temporary[:h2o_dil_vol] = dilute_h2o(op.temporary[:rna_dil_vol])
}
rc_list = ops.map {|op| [op.output(OUTPUT).row, op.output(OUTPUT).column]}
item_matrix = ops.map {|op| op.input(INPUT).item.id}.each_slice(obj_type.columns).map {|slice| slice}
rna_vol_matrix = ops.map {|op| op.temporary[:rna_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice}
h2o_vol_matrix = ops.map {|op| op.temporary[:h2o_dil_vol]}.each_slice(obj_type.columns).map {|slice| slice}
log_info 'rna_vol_matrix',rna_vol_matrix,'h2o_vol_matrix',h2o_vol_matrix
show do
title "Gather Material(s)"
separator
check "Gather a #{obj_type.name} and label <b>#{out_coll.id}</b>"
end
tot_h2o_vol = 0
h2o_vol_matrix.flatten.each {|vol| tot_h2o_vol += vol}
show do
title "Fill #{obj_type.name} #{out_coll} with MG H2O"
separator
check "For the next steps you will need #{(tot_h2o_vol + 20.0).round(2)}#{MICROLITERS}"
end
show do
title "Fill #{obj_type.name} #{out_coll} with MG H2O"
separator
note "Follow the table below to fill the plate:"
table highlight_alpha_rc(out_coll, rc_list) { |r, c| "#{h2o_vol_matrix[r][c].round(1)}#{MICROLITERS}" }
end
fill_by_row = rc_list.group_by {|r,c| r}.sort
fill_by_row.each { |row, rc_list|
show do
title "Fill #{obj_type.name} #{out_coll} with RNA [#{INPUT_RNA_CONC/FINAL_VOL}#{NANOGRAMS}/#{MICROLITERS}]"
separator
table highlight_alpha_rc(out_coll, rc_list) { |r, c| "#{item_matrix[r][c]}\n#{rna_vol_matrix[r][c].round(1)}#{MICROLITERS}" }
end
}
}
show do
title "Centrifuge Plate(s)"
separator
note "Use the large centrifuge with the the plate rotor"
check "Spin plate(s) at <b>500 x g</b> for <b>1 min</b> to collect everything into the well."
end
end
end #Class
| true
|
36c02a112f3c9408455458dbce25c4c33f317c90
|
Ruby
|
Mew-Traveler/mew-api
|
/lib/airbnb_api.rb
|
UTF-8
| 659
| 2.609375
| 3
|
[] |
no_license
|
require 'http'
module Airbnb
# Service for all Airbnb API calls
class AirbnbApi
#Setting the URL and parameters
Airbnb_URL = 'https://api.airbnb.com/'
API_VER = 'v2'
Airbnb_API_URL = URI.join(Airbnb_URL, "#{API_VER}/")
Search_URL = URI.join(Airbnb_API_URL, "search_results")
# attr_reader :airbnb_data
def initialize(airbnb_id:)
@airbnb_id = airbnb_id
end
def rooms_info(location)
rooms_response = HTTP.get(Search_URL,
params: { client_id: @airbnb_id,
location: location
})
roomsinfo = JSON.load(rooms_response.to_s)['search_results']
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.