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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29ce09599beabf990cc2e65ab4d505eda3ffe8f1 | Ruby | Mattens15/Inline-LASESI | /vendor/bundle/gems/bcrypt-3.1.7/spec/bcrypt/engine_spec.rb | UTF-8 | 3,373 | 2.78125 | 3 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper"))
describe "The BCrypt engine" do
specify "should calculate the optimal cost factor to fit in a specific time" do
first = BCrypt::Engine.calibrate(100)
second = BCrypt::Engine.calibrate(400)
second.should > first
end
end
describe "Generating BCrypt salts" do
specify "should produce strings" do
BCrypt::Engine.generate_salt.should be_an_instance_of(String)
end
specify "should produce random data" do
BCrypt::Engine.generate_salt.should_not equal(BCrypt::Engine.generate_salt)
end
specify "should raise a InvalidCostError if the cost parameter isn't numeric" do
lambda { BCrypt::Engine.generate_salt('woo') }.should raise_error(BCrypt::Errors::InvalidCost)
end
specify "should raise a InvalidCostError if the cost parameter isn't greater than 0" do
lambda { BCrypt::Engine.generate_salt(-1) }.should raise_error(BCrypt::Errors::InvalidCost)
end
end
describe "Autodetecting of salt cost" do
specify "should work" do
BCrypt::Engine.autodetect_cost("$2a$08$hRx2IVeHNsTSYYtUWn61Ou").should eq 8
BCrypt::Engine.autodetect_cost("$2a$05$XKd1bMnLgUnc87qvbAaCUu").should eq 5
BCrypt::Engine.autodetect_cost("$2a$13$Lni.CZ6z5A7344POTFBBV.").should eq 13
end
end
describe "Generating BCrypt hashes" do
class MyInvalidSecret
undef to_s
end
before :each do
@salt = BCrypt::Engine.generate_salt(4)
@password = "woo"
end
specify "should produce a string" do
BCrypt::Engine.hash_secret(@password, @salt).should be_an_instance_of(String)
end
specify "should raise an InvalidSalt error if the salt is invalid" do
lambda { BCrypt::Engine.hash_secret(@password, 'nino') }.should raise_error(BCrypt::Errors::InvalidSalt)
end
specify "should raise an InvalidSecret error if the secret is invalid" do
lambda { BCrypt::Engine.hash_secret(MyInvalidSecret.new, @salt) }.should raise_error(BCrypt::Errors::InvalidSecret)
lambda { BCrypt::Engine.hash_secret(nil, @salt) }.should_not raise_error(BCrypt::Errors::InvalidSecret)
lambda { BCrypt::Engine.hash_secret(false, @salt) }.should_not raise_error(BCrypt::Errors::InvalidSecret)
end
specify "should call #to_s on the secret and use the return value as the actual secret data" do
BCrypt::Engine.hash_secret(false, @salt).should == BCrypt::Engine.hash_secret("false", @salt)
end
specify "should be interoperable with other implementations" do
# test vectors from the OpenWall implementation <http://www.openwall.com/crypt/>
test_vectors = [
["U*U", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"],
["U*U*", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK"],
["U*U*U", "$2a$05$XXXXXXXXXXXXXXXXXXXXXO", "$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a"],
["", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.", "$2a$05$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy"],
["0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "$2a$05$abcdefghijklmnopqrstuu", "$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui"]
]
for secret, salt, test_vector in test_vectors
BCrypt::Engine.hash_secret(secret, salt).should eql(test_vector)
end
end
end
| true |
fde0377f96b7b40ff01a828928836003e86f5a25 | Ruby | saramic/learning | /workshop/fp_patterns/tail_recursion/lib/demo.rb | UTF-8 | 213 | 3.203125 | 3 | [
"Unlicense"
] | permissive | module Demo
def sum_recursive(up_to)
up_to == 0 ? 0 : up_to + sum_recursive(up_to - 1)
end
def sum_tail_recursive(up_to, acc)
up_to == 0 ? acc : sum_tail_recursive(up_to - 1, acc + up_to)
end
end
| true |
b7e3aa6bd107af659308ae5ae41d5f8fc36d92e9 | Ruby | felipegruoso/spotify-api | /lib/spotify/models/track.rb | UTF-8 | 1,540 | 2.96875 | 3 | [
"MIT"
] | permissive | module Spotify
module Models
class Track
attr_reader :artists, :available_markets, :disc_number, :duration_ms,
:explicit, :external_urls, :href, :id, :is_playable, :linked_from,
:name, :preview_url, :track_number, :type, :uri
#
# Sets the arguments to its variables.
#
# @param [Hash] args the arguments that will be placed on each variable.
#
# @return [Track] a track object.
#
def initialize(args = {})
args = Hash(args).with_indifferent_access
# Arrays
artist = Spotify::Models::Simplified::Artist
artists = Array(args[:artists]).map { |a| artist.new(a) }
# Objects
external_urls = Spotify::Models::ExternalURL.new(args[:external_urls])
track_link = Spotify::Models::TrackLink.new(args[:linked_from])
@artists = artists
@available_markets = args[:available_markets]
@disc_number = args[:disc_number]
@duration_ms = args[:duration_ms]
@explicit = args[:explicit]
@external_urls = external_urls
@href = args[:href]
@id = args[:id]
@is_playable = args[:is_playable]
@linked_from = track_link
@name = args[:name]
@preview_url = args[:preview_url]
@track_number = args[:track_number]
@type = args[:type]
@uri = args[:uri]
end
end
end
end | true |
39001b52d3bd28054ca482b3f7e82d10d2c2f414 | Ruby | apoex/squid | /lib/squid/settings.rb | UTF-8 | 911 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'squid/config'
module Squid
# @private
module Settings
# For each key, create an attribute reader with a settings value.
# First, check if an option with the key exists.
# For example: {formats: [:currency]} ->> [:currency]
# Then, check is an option with the singular version of the key exists.
# For example: {format: :currency} ->> [:currency]
# Finally, check whether the key has a value in Squid configuration.
# For example: config.formats = [:currency] ->> [:currency]
def has_settings(*keys)
keys.each do |key|
define_method(key) do
singular_key = key.to_s.singularize.to_sym
if @settings.key? key
@settings[key]
elsif @settings.key? singular_key
[@settings[singular_key]]
else
Squid.configuration.public_send key
end
end
end
end
end
end
| true |
8a610f1320810deece7f545440a07d4be7743550 | Ruby | thebmo/ruby_junk | /assert_test.rb | UTF-8 | 359 | 2.609375 | 3 | [] | no_license | # Assertion Tests
require "test/unit"
require_relative "dragons"
include Test::Unit::Assertions
d = Dragon.new("BMO")
b = BlueDragon.new("Juju")
assert_equal("blue", b.color, failure_message = "first dragon color")
assert_equal("non -", d.color, failure_message = "second dragon color")
assert(b.armor > 0, failure_message = "armor test: #{b.armor} < 0")
| true |
6778d3c3fcbf774f7d61edf2b44670b74f991668 | Ruby | vuxe/codility | /GenomicRangeQuery_62.rb | UTF-8 | 562 | 3.375 | 3 | [] | no_license | # you can write to stdout for debugging purposes, e.g.
# puts "this is a debug message"
def solution(s, p, q)
# write your code in Ruby 2.2
factor = nil
arr = []
i = 0
res = []
for i in 0...s.length do
case s[i]
when 'A'
arr << 1
when 'C'
arr << 2
when 'G'
arr << 3
when 'T'
arr << 4
end
end
#puts "#{arr.to_s} #{s} #{p.to_s} #{q.to_s}"
i = 0
for i in 0...p.size do
tmp = arr.slice(p[i],q[i] - p[i] + 1)
#puts "#{tmp}"
res << tmp.min
end
#puts "#{res}"
res
end | true |
881970914742200f86d0a33f32e8bcbf72de7970 | Ruby | RuffWorksTech/RB101-Programming-Foundations | /lesson_4/selection_and_transformation.rb | UTF-8 | 2,258 | 4.34375 | 4 | [] | no_license | ### Given the produce hash, write a method `select_fruit` that selects the key-value pairs whose value is `'Fruit'` ###
# def select_fruit(produce_hash)
# produce_hash.select { |k, v| v == 'Fruit' }
# end
# produce = {
# 'apple' => 'Fruit',
# 'carrot' => 'Vegetable',
# 'pear' => 'Fruit',
# 'broccoli' => 'Vegetable'
# }
# p select_fruit(produce) # => {"apple"=>"Fruit", "pear"=>"Fruit"}
# -------------------------------------------------------------------------------------------------------------------
### Write a method that doubles the integers in an array and mutates the caller ###
# def double_numbers!(numbers)
# tick = 0
# until tick == numbers.size
# numbers[tick] *= 2
# tick += 1
# end
# numbers
# end
# arr = [1, 2, 3, 4, 5]
# double_numbers!(arr)
# p arr
# -------------------------------------------------------------------------------------------------------------------
### Write a method that doubles an integer if it has an odd index, does not mutate the caller ###
# def double_odd_indices(numbers)
# doubled_numbers = []
# numbers.each_with_index do | num, idx |
# num *= 2 if idx.odd?
# doubled_numbers << num
# end
# doubled_numbers
# end
# arr = [1, 2, 3, 4, 5]
# p double_odd_indices(arr)
# -------------------------------------------------------------------------------------------------------------------
### Modify the select_fruit method to be more flexible and select anything ###
# def general_select(produce_hash, selection_criteria)
# produce_hash.select { |k, v| v == selection_criteria }
# end
# p general_select(produce, 'Vegetable')
# -------------------------------------------------------------------------------------------------------------------
### Modify the double_numbers method to multiply by any number
### Write a method that doubles the integers in an array and mutates the caller ###
# def double_numbers!(numbers, operator)
# tick = 0
# until tick == numbers.size
# numbers[tick] *= operator
# tick += 1
# end
# numbers
# end
# arr = [1, 2, 3, 4, 5]
# double_numbers!(arr, 5)
# p arr
# ------------------------------------------------------------------------------------------------------------------- | true |
23b8cf6b6db62d8d1e98ce6cc09d45f12055c743 | Ruby | fantasygame/dungeon_explorer | /spec/models/character_spec.rb | UTF-8 | 877 | 2.515625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Character, type: :model do
subject(:character) { build(:character) }
describe '#level' do
context 'character has 0 experience' do
it 'returns 1st level' do
character.experience = 0
expect(character.level).to eq 1
end
end
context 'character has exp between 1st and 2nd level' do
it 'returns 1st level' do
character.experience = 500
expect(character.level).to eq 1
end
end
context 'character has exp equal to second level cap' do
it 'returns 2st level' do
character.experience = 1000
expect(character.level).to eq 2
end
end
context 'character has exp exceeding 20th level' do
it 'returns 20th level' do
character.experience = 999999999
expect(character.level).to eq 20
end
end
end
end
| true |
5a9cd7d898df75c009abc0a7c8584471aaf97741 | Ruby | tom-james-watson/voyagefound | /data_converter/page_hierarchy.rb | UTF-8 | 2,693 | 2.984375 | 3 | [] | no_license | class PageHierarchy
# Expects an xml filename. The xml doc should have one child, and that child
# should have all pages as immediate children.
def self.from_xml_file(xml_doc)
@whatever
doc = File.open('enwikivoyage-latest-pages-articles.xml') { |f| Nokogiri::XML(f) }
page_hierarchy = new(doc.children.first)
page_hierarchy.build_map
page_hierarchy
end
def build_map
@root.children.each { |node| add_page(Page.new(node)) }
end
def add_page(page)
return if page.tag == 'siteinfo'
# Skip empty text nodes
return if page.text =~ /\A\s*\Z/
# We need to store redirects because sometimes a good page will have, as its
# parent, a redirect page.
if page.redirect
@redirects[normalize(page.title)] = normalize(page.redirect)
return
end
return if page.bad_title? || page.bad_body?
unless page.top_level? || page.parent
raise "No parent found for non-top-level page: #{page.title}"
end
@pages[normalize(page.title)] = page
end
# Get a map of each page to an ordered list of its ancestors. Eg:
# {
# "Aalborg"=>["North Jutland", "Jutland", "Denmark", "Nordic countries", "Europe"],
# "Aalst"=>["East Flanders", "Flanders", "Belgium", "Benelux", "Europe"],
# etc
# }
def to_ancestor_map
ancestor_map = {}
@pages.each do |normalized_title, page|
ancestor_map[page.title] = ancestor_list = []
while page
parent = @pages[normalize(page.parent)]
parent ||= @pages[@redirects[normalize(page.parent)]]
ancestor_list << parent.title if parent
page = parent
end
end
ancestor_map
end
# A page hierarchy is considered valid if every page is either a known top
# level page or has a parent. If this is not the case, we probably accidentally
# let through some weird non-location page or otherwise didn't clean the data
# enough.
def validate!
@pages.each do |normalized_title, page|
while page
parent = @pages[normalize(page.parent)]
parent ||= @pages[@redirects[normalize(page.parent)]]
if parent.nil? && !page.top_level?
binding.pry
raise "Page #{page.title} had an invalid page chain"
end
page = parent
end
end
end
private
def initialize(root)
@root = root
# A map of normalized page titles to page objects
@pages = {}
# A map of normalized page titles to their redirected page titles (also
# normalized)
@redirects = {}
end
def normalize(title)
title
&.gsub('_', ' ')
&.gsub('','') # remove special character space
&.strip
&.downcase
end
end
| true |
3425c05db311046753b44d4d28eb8775b04fc40f | Ruby | daifu/CodeEval | /angry_children/angry_children.rb | UTF-8 | 1,500 | 3.96875 | 4 | [
"MIT"
] | permissive | # Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has N packets of candies and would like to distribute one packet to each of the K children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick K out of N packets such that the unfairness is minimized.
#
# Suppose the K packets have (x1, x2, x3,….xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as
#
# max(x1,x2,…xk) - min(x1,x2,…xk)
#
# where max denotes the highest value amongst the elements and min denotes the least value amongst the elements. Can you figure out the minimum unfairness and print it?
class AngryChildren
def subset_length(list, k)
list.inject([[]]) do |powerset, element|
powerset +
powerset.map do |old_element|
if old_element.length < k
old_element + [element]
else
Array.new(k + 1) #will be rejected and it will not disturb when creating new subsets
end
end
end.reject { |solution| solution.length != k }
end
def minimum_unfairness(numbers, cap)
subset_length(numbers, cap).map {|nums| calculate(nums)}.min
end
def calculate(ary)
(ary.max - ary.min).to_i
end
def solve
lines = gets
cap = gets
numbers = []
1.step(lines.to_i, 1) do
num = gets
numbers << num.to_i
end
puts minimum_unfairness(numbers, cap.to_i)
end
end
| true |
3d850c29495601c605e92fa922c9c34fe3032e7d | Ruby | andriiginting/Line-distance-ruby | /lib/square.rb | UTF-8 | 231 | 2.90625 | 3 | [] | no_license | module Geometry
class Square < Rectangle
def initialize(x_offset, y_offset,length)
super(x_offset,y_offset,length,length)
@x_offset = x_offset
@y_offset = y_offset
@length = length
end
end
end | true |
912cf21aebe0e2800b1f4f8bf1f09a185d9da659 | Ruby | ck3g/nevermissyourmovie | /app/services/create_movie.rb | UTF-8 | 250 | 2.515625 | 3 | [] | no_license | class CreateMovie
attr_reader :movie
def initialize(options = {})
@movie = Movie.new options
end
def save
save_result = @movie.save
if save_result
MovieInfoWorker.perform_async @movie.id
end
save_result
end
end
| true |
6c3b21eb799d733b245dd47c9e9140e28d78bbb6 | Ruby | AlabushevEvgeniy/viselitsa | /viselitsa.rb | UTF-8 | 652 | 2.703125 | 3 | [] | no_license | if Gem.win_platform?
Encoding.default_external = Encoding.find(Encoding.locale_charmap)
Encoding.default_internal = __ENCODING__
[STDIN, STDOUT].each do |io|
io.set_encoding(Encoding.default_external, Encoding.default_internal)
end
end
require_relative "lib/game.rb"
require_relative "lib/result_printer.rb"
require_relative "lib/word_reader.rb"
file_name = "#{File.dirname(__FILE__)}/data/words.txt"
reader = WordReader.new
slovo = reader.read_from_file(file_name)
game = Game.new(slovo)
printer = ResultPrinter.new(slovo)
while game.status == 0 do
printer.print_status(game)
game.ask_next_letter
end
printer.print_status(game)
| true |
9e27067486093de1a942e2b07172110153f50f9d | Ruby | RubyGameCode/Text-Based-Rpg | /Testing chunks of code.rb | UTF-8 | 795 | 3.296875 | 3 | [] | no_license | require "Part 2, after character creation"
require "Page that has some methods to be used frequently"
two_way_dialogue("option 1: prepare to attack whomever may be on the other side of that door", "option 2: Cower in the corner")
cell_action_option_2 = gets.chomp
if cell_action_option_2.include?("1")
dialogue_2("the door slowly opens and you spring at the burly guard")
dialogue_2("you sucker punch the guard and grab a knife from his belt as he reels from the blow")
dagger = Weapon.new()
dagger.attack_val = 10
dagger.name = dagger
dialogue_2("You have obtained a #{dagger.name}!")
attack("Dickhead_guard", "Dagger")
elsif cell_action_option_2.include?("2")
dialogue_2("you hide in the corner as the guard walks into the small cell")
end | true |
d04fa8af86a113b62a4af961c8cd38070789d928 | Ruby | jasminenoack/in-progress | /Minesweeper_rails-master/app/models/board.rb | UTF-8 | 1,088 | 2.796875 | 3 | [] | no_license | class Board < ActiveRecord::Base
has_many(
:tiles,
class_name: "Tile",
foreign_key: :board_id,
primary_key: :id
)
def self.setup_beginner!
board = Board.create(alive: true, columns: 9, rows: 9, bombs: 10)
num_tiles = board.rows * board.columns
num_tiles.times do |i|
Tile.create(
bombed: false,
revealed: false,
flagged: false,
location: i,
board_id: board.id
)
end
(0...num_tiles).to_a.sample(board.bombs).each do |index|
tile = Tile.where(board_id: board.id, location: index).first
tile.bombed = true
tile.save
end
self
end
def commandline_display
display_string = ""
tiles = find_tiles_in_order
rows = self.rows
columns = self.columns
tiles.each_slice(9) do |row|
row.each do |tile|
display_string << tile.commandline_display(tiles, rows, columns)
display_string << " "
end
display_string << "\n"
end
display_string
end
def find_tiles_in_order
self.tiles.order(:location)
end
end
| true |
906061c6a7c8fe31902e928317e55ee62954427a | Ruby | takumirie/log-note | /logging.rb | UTF-8 | 855 | 3.15625 | 3 | [] | no_license | # ver 1.0.0
# instruction.
#
# Please use this program with 'ruby'! not 'pry' or 'irb'.
#
# Developed by Takumi irie.
# https://github.com/takumirie.
#
# Please make sure this program is my practice of studying Ruby.
# If you have a time? give me a advice or comment!
#
# Feel free to edit, and share.
require 'date'
p "enter the file name. (e,g. idea1.md. or blank to be 'date')(automatically, make new one or open)"
@toSaveFile = gets.chomp
if @toSaveFile.empty?
p "error"
exit(0)
end
def theTime
getNow = Time.now.strftime("%H:%M %b %d, %Y")
end
def userInput
print "now logging! in #{@toSaveFile} \nexit is 2 times of'ctrl + d' \n\n"
lines = $stdin.read
$stdin.close
formattedLines = <<~EOS
###[#{theTime}]
#{lines}
******\n
EOS
end
toSaveLines = userInput
File.open(@toSaveFile, "a") do |file|
file.puts toSaveLines
end
p 'saved.' | true |
c34e937a5e4fccb7a367c61ed4fa86afa3fe9716 | Ruby | alonhartal/payday | /lib/payday/line_itemable.rb | UTF-8 | 418 | 2.890625 | 3 | [
"MIT"
] | permissive | # Include this module into your line item implementation to make sure that Payday stays happy
# with it, or just make sure that your line item implements the amount method.
module Payday::LineItemable
# Returns the total amount for this {LineItemable}, or +price * quantity+
def amount_no_tax
price * quantity
end
def item_tax
tax * quantity
end
def amount
amount_no_tax + item_tax
end
end
| true |
b4efc0ee396134b260ca09a1a2c504be8784dd12 | Ruby | obrie/neptune | /lib/neptune/partitioner/hashed.rb | UTF-8 | 489 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'zlib'
module Neptune
module Partitioner
# Partitions keys using a consistent hash function based on the total
# number of partitions
class Hashed
# Generates the hashed partition index. This will use all partitions
# even if some are not available to ensure that those messages are
# always published to the same partition.
# @return [Fixnum]
def call(key, available, total)
Zlib.crc32(key) % total
end
end
end
end | true |
b1fa4aef19f2c75730076b1bc7eca904f29a60f4 | Ruby | katiekeel/job-tracker-base | /spec/models/tag_spec.rb | UTF-8 | 1,463 | 2.640625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Tag, type: :model do
describe "validations" do
context "invalid attributes" do
it "is invalid without a name" do
tag = Tag.new()
expect(tag).to be_invalid
end
it "has a unique name" do
tag_1 = Tag.create(name: "Tag 1")
tag_2 = Tag.new(name: "Tag 1")
expect(tag_2).to be_invalid
end
end
context "valid attributes" do
it "is valid with a name" do
tag = Tag.new(name: "Tag")
expect(tag).to be_valid
end
end
end
describe "relationships" do
it "has many jobs" do
tag = Tag.new(name: "Tag")
expect(tag).to respond_to(:jobs)
end
end
describe "methods" do
it "its jobs have an average salary" do
tag = Tag.new(name: "Tag")
company = Company.create!(name: "ESPN")
company_2 = Company.create!(name: "Sports Authority")
company_3 = Company.create!(name: "FedEx")
job = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver", salary: 70000)
job_2 = company_2.jobs.create!(title: "Engineer", level_of_interest: 40, city: "Longmont", salary: 75000)
job_3 = company_3.jobs.create!(title: "QA", level_of_interest: 75, city: "Loveland", salary: 80000)
job.tags << tag
job_2.tags << tag
job_3.tags << tag
# tag.jobs << [job, job_2, job_3]
expect(tag.average_salary).to eq 75000
end
end
end
| true |
0fc68205c98ec68c44072a0e59ad03c4c8ab44b4 | Ruby | CareGuide/ramparts | /lib/ramparts/parsers/phone_parser.rb | UTF-8 | 3,575 | 3.109375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative '../helpers'
# Parses text and attempts to locate phone numbers
class PhoneParser
# Counts the number of phone number instances that occur within the block of text
def count_phone_number_instances(text, options)
raise ArgumentError, ARGUMENT_ERROR_TEXT unless text.is_a? String
parsed_text = parse_phone_number(text, options)
# Uses the map reduce algorithm
phone_number_instances(MR_ALGO, parsed_text, options).length
end
# Replaces phone number instances within the block of text with the insertable
def replace_phone_number_instances(text, options, &block)
raise ArgumentError, ARGUMENT_ERROR_TEXT unless text.is_a? String
instances = find_phone_number_instances(text, options)
replace(text, instances.reverse!, &block)
end
# Finds phone number instances within the block of text
def find_phone_number_instances(text, options)
raise ArgumentError, ARGUMENT_ERROR_TEXT unless text.is_a? String
text = text.downcase
# Finds the phone number instances using the glorified regex algorithm
phone_number_instances(GR_ALGO, text, options)
end
private
# Phonetic versions of numbers
PHONETICS = %w[
one
two
three
four
five
six
seven
eight
nine
oh
zero
].freeze
# L33t speak versions of numbers
LEET_SPEAK = %w[
w0n
too
thr33
f0r
f1v3
s3x
sex
s3v3n
at3
nin3
].freeze
# Handles multiple spaces
MULTI_SPACE = '( )*'
# Regex for phonetics, both with spaces and otherwise
REGEX_PHONETICS = PHONETICS.join('|')
REGEX_PHONETICS_SPACED = PHONETICS.map { |word| word.split('').join(MULTI_SPACE) }.join('|')
# Regex for l33t, both with spaces and otherwise
REGEX_LEET_SPEAK = LEET_SPEAK.join('|')
REGEX_LEET_SPEAK_SPACED = LEET_SPEAK.map { |word| word.split('').join(MULTI_SPACE) }.join('|')
# Base matching for a possible phone number digit
BASE_MATCHING = "#{REGEX_PHONETICS}|#{REGEX_LEET_SPEAK}|#{REGEX_PHONETICS_SPACED}|#{REGEX_LEET_SPEAK_SPACED}"
# The final regex used to match phone numbers for GR
GR_REGEX =
Regexp.new(/(\()?(\d|#{BASE_MATCHING}){1}([^\w]*(\d|#{BASE_MATCHING}){1}[^\w]*){5,}(\d|#{BASE_MATCHING}){1}/)
# The final regex used to match phone numbers for MR
MR_REGEX = Regexp.new(/(\-*\.?\d{1}\.?\-?){7,}/)
# Replacements used for phonetics for MR
REPLACEMENTS = {
'one' => '1',
'two' => '2',
'three' => '3',
'four' => '4',
'five' => '5',
'six' => '6',
'seven' => '7',
'eight' => '8',
'nine' => '9',
'oh' => '0',
'zero' => '0'
}.freeze
# Replacements used for l33t for MR
LEET_REPLACEMENTS = {
'w0n' => '1',
'too' => '2',
'thr33' => '3',
'f0r' => '4',
'f1v3' => '5',
's3x' => '6',
'sex' => '6',
's3v3n' => '7',
'at3' => '8',
'nin3' => '9'
}.freeze
# Parses the phone number for MR, uses a variety of options
def parse_phone_number(text, options)
text = text.delete(' ') if options.fetch(:remove_spaces, true)
text = text.downcase.gsub(/#{REGEX_PHONETICS}/, REPLACEMENTS)
text = text.gsub(/#{REGEX_LEET_SPEAK}/, LEET_REPLACEMENTS) if options.fetch(:parse_leet, true)
text.gsub(/[^\w]/, '-').gsub(/[a-z]/, '.')
end
# Returns the phone number instances using the specified algorithm
def phone_number_instances(algo, text, _options)
# Determines which algorithm to use
regex = algo == MR_ALGO ? MR_REGEX : GR_REGEX
instances = scan(text, regex, :phone)
instances
end
end
| true |
ffcf418dc72b73f29d1ee7c5c0a7debf093d8e86 | Ruby | jfdelaluz/LearningRuby | /Variables.rb | UTF-8 | 330 | 3.828125 | 4 | [] | no_license | class Variables
def initialize()
end
def tipo_variables()
#Variables Strings en Ruby
saludo = "Hola Mundo desde Ruby"
#Variables Int en Ruby
valorUno = 1
valorDos = 2
#Variables Float en Ruby
valorTres = 2.2
puts valorUno + valorDos + valorTres
end
end
objeto = Variables.new()
objeto.tipo_variables
gets() | true |
0463d1800fa5571ffbbe9e4dc951447a1e289f27 | Ruby | aleksanderbrymora/sei-36 | /harish_ramesh/4week/9march/class/rough/games.rb | UTF-8 | 676 | 4.0625 | 4 | [] | no_license | def magic_question
print "Ask me a question: "
@question = gets.chomp
end
@answers = [" It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it."]
def magic_eight
magic_question()
if @question.size > 5
puts @answers[rand(@answers.length)]
else
puts "That's invalid question"
end
end
# magic_eight()
def num_prompt
print "Give me a Integer bw 1 to 10: "
@number = gets.to_i
end
@my_num = rand(1..10)
def guess_num
num_prompt()
if @number > 10 || @number < 1
puts "num shld be bw 1 and 10"
elsif
@my_num == @number
puts "congrats!"
else
puts "you lost!"
end
end
guess_num()
| true |
414ba248d04908629f88a4235c88cd44bf37d9f0 | Ruby | ahmedelmahalawey/sablon | /lib/sablon/context.rb | UTF-8 | 962 | 2.6875 | 3 | [
"MIT"
] | permissive | module Sablon
# A context represents the user supplied arguments to render a
# template.
#
# This module contains transformation functions to turn a
# user supplied hash into a data structure suitable for rendering the
# docx template.
module Context
class << self
def transform_hash(hash)
Hash[hash.map { |k, v| transform_pair(k.to_s, v) }]
end
private
def transform_standard_key(key, value)
case value
when Hash
[key, transform_hash(value)]
else
[key, value]
end
end
def transform_pair(key, value)
if key =~ /\A([^:]+):(.+)\z/
if value.nil?
[Regexp.last_match[2], value]
else
key_sym = Regexp.last_match[1].to_sym
[Regexp.last_match[2], Content.make(key_sym, value)]
end
else
transform_standard_key(key, value)
end
end
end
end
end
| true |
8d5f3d6bc5dffbb82f054ee6052a89cb674847fb | Ruby | tekt8tket/back_to_the_timezone | /lib/back_to_the_timezone.rb | UTF-8 | 1,436 | 2.828125 | 3 | [
"MIT"
] | permissive | module BackToTheTimezone
extend ActiveSupport::Concern # This loads the methods in ClassMethods and InstanceMethods sub modules into any class that includes this class
module ClassMethods
# Usage in model definition as follows, ex:
# shift_timezone :legacy_registered_at, :legacy_timezone => 'Eastern Time (US & Canada)'
# This will shift the timezone to the specified legacy_timezone or it will use the specified Time.zone in Rails config
def shift_timezone(field_name, options = {})
# Override the getter like 'registered_at'
define_method(field_name) {
if read_attribute(field_name)
Time.zone.at(read_attribute(field_name).to_i - read_attribute(field_name).in_time_zone(options[:legacy_timezone] || Time.zone).utc_offset)
end
}
# Override the setter like 'registered_at='
define_method(field_name.to_s + '=') { |value|
unless value.blank?
value = Time.parse(value) if value.class == String
if value
legacy_time = Time.zone.at(value.to_i + value.in_time_zone(options[:legacy_timezone] || Time.zone).utc_offset)
else
legacy_time = nil
end
write_attribute(field_name, legacy_time)
end
}
end
end
end
# Make shift_timezone available to all ActiveRecord models
class ActiveRecord::Base
include BackToTheTimezone
end
# Cause I can : )
String.class_eval do
def to_mcfly
self + " McFly [KNOCK] [KNOCK] [KNOCK], Anybody home McFly?!"
end
end | true |
fe2b33944e076cb4c42e5e19413a8fab029cf07d | Ruby | starksm64/node.x | /src/main/ruby/core/shared_data.rb | UTF-8 | 3,611 | 2.53125 | 3 | [] | no_license | # Copyright 2002-2011 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
require 'delegate'
include Java
module Nodex
module SharedData
module Immutable
include org.nodex.java.core.Immutable
end
def SharedData.get_hash(key)
map = org.nodex.java.core.shared.SharedData.getMap(key)
SharedHash.new(map)
end
def SharedData.get_set(key)
set = org.nodex.java.core.shared.SharedData.getSet(key)
SharedSet.new(set)
end
def SharedData.get_counter(key)
org.nodex.java.core.shared.SharedData.getCounter(key)
end
def SharedData.remove_hash(key)
org.nodex.java.core.shared.SharedData.removeMap(key)
end
def SharedData.remove_set(key)
org.nodex.java.core.shared.SharedData.removeSet(key)
end
def SharedData.remove_counter(key)
org.nodex.java.core.shared.SharedData.removeCounter(key)
end
# We need to copy certain objects because they're not immutable
def SharedData.check_copy(obj)
if obj.is_a?(Buffer)
obj = obj.copy
elsif obj.is_a?(String)
obj = String.new(obj)
end
obj
end
class SharedHash < DelegateClass(Hash)
def initialize(hash)
@hash = hash
# Pass the object to be delegated to the superclass.
super(@hash)
end
def []=(key, val)
key = SharedData.check_copy(key)
val = SharedData.check_copy(val)
# We call the java class directly - otherwise RubyHash does a scan of the whole map!! :(
@hash.put(key, val)
end
alias store []=
def [](key)
# We call the java class directly
@hash.get(key)
end
def ==(other)
if other.is_a?(SharedHash)
@hash.equal?(other._to_java_map)
else
false
end
end
def _to_java_map
@hash
end
private :initialize
end
class SharedSet
def initialize(j_set)
@j_set = j_set
end
def ==(other)
if other.is_a?(SharedSet)
@j_set.equal?(other._to_java_set)
else
false
end
end
def _to_java_set
@j_set
end
def add(obj)
obj = SharedData.check_copy(obj)
@j_set.add(obj)
self
end
def add?(obj)
obj = SharedData.check_copy(obj)
if !@j_set.contains(obj)
@j_set.add(obj)
self
else
nil
end
end
def clear
@j_set.clear
end
def delete(obj)
@j_set.remove(obj)
end
def delete?(obj)
if @j_set.contains(obj)
@j_set.remove(obj)
self
else
nil
end
end
def each(&block)
iter = @j_set.iterator
while iter.hasNext do
block.call(iter.next)
end
end
def empty?
@j_set.isEmpty
end
def include?(obj)
@j_set.contains(obj)
end
def size
@j_set.size
end
private :initialize
end
end
end | true |
411f517b0a8d8ea71b51d0eac070a5d081e14bf8 | Ruby | gyan88singh/timecard_new | /app_BKP13thMar18/helpers/application_helper.rb | UTF-8 | 618 | 2.53125 | 3 | [] | no_license | module ApplicationHelper
def showdatetime(mydatetime)
if mydatetime
strdatetime=mydatetime.to_time.strftime("%d-%m-%Y %I:%M %P")
else
strdatetime=""
end
return strdatetime
end
def showtime(mydatetime)
if mydatetime
strdatetime=mydatetime.to_time.strftime("%I:%M %P")
else
strdatetime=""
end
return strdatetime
end
def showdate(mydate)
if mydate
strdate=mydate.to_date.strftime("%B-%Y")
else
strdate=""
end
return strdate
end
end
| true |
518460efd5fe59f56895c09111e7fc25308395b8 | Ruby | Satkar/entertainment_platform | /app/models/user.rb | UTF-8 | 1,384 | 2.5625 | 3 | [] | no_license | # This class represents a user in the system
class User < ApplicationRecord
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, presence:true, uniqueness: true
has_many :library_items, dependent: :destroy
after_commit :flush_cache
# cache the result
def self.fetch_and_cache
Rails.cache.fetch("users", expires_in: 12.hours) do
all.to_a
end
end
# lists all active subscriptions of user ordered by expiry date
def library
library_items.active_subscriptions.ordered_by_expiry.includes(:gallery_item, :purchase_option)
end
# Below method checks
# if subscription for the movie or season id not expired then returns 'false'
# else creates a new subscription for the user
def purchase_now(gallery_item, purchase_option)
remaining_time = active_subscription_remaining_time(gallery_item.id, purchase_option.id)
return remaining_time if remaining_time.present?
LibraryItem.add_subscription(self.id, gallery_item.id, purchase_option.id)
true
end
private
def active_subscription_remaining_time(gallery_item_id, purchase_option_id)
list = library_items.where(
gallery_item_id: gallery_item_id,
purchase_option_id: purchase_option_id
).active_subscriptions
return nil if list.empty?
list.last.calculate_remaining_time
end
def flush_cache
Rails.cache.delete('users')
end
end | true |
945a98371827682148e7ec7cc12df2cffc557c3e | Ruby | debzow/ruby_exercices_week_0 | /exo_12.rb | UTF-8 | 120 | 3.203125 | 3 | [] | no_license | puts "Donnes moi un nombre !!!!"
print ">"
loopNumber = gets.chomp.to_i
i=1
loopNumber.times do
puts i
i += 1
end | true |
94f2329e71b1d97b2ea8dc7eaeb93f16c963af65 | Ruby | flyerhzm/rails_best_practices | /lib/rails_best_practices/reviews/use_query_attribute_review.rb | UTF-8 | 5,206 | 3.09375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module RailsBestPractices
module Reviews
# Make sure to use query attribute instead of nil?, blank? and present?.
#
# See the best practice details here https://rails-bestpractices.com/posts/2010/10/03/use-query-attribute/
#
# Implementation:
#
# Review process:
# check all method calls within conditional statements, like @user.login.nil?
# if their receivers are one of the model names
# and their messages of first call are not pluralize and not in any of the association names
# and their messages of second call are one of nil?, blank?, present?, or they are == ""
# then you can use query attribute instead.
class UseQueryAttributeReview < Review
interesting_nodes :if, :unless, :elsif, :ifop, :if_mod, :unless_mod
interesting_files ALL_FILES
url 'https://rails-bestpractices.com/posts/2010/10/03/use-query-attribute/'
QUERY_METHODS = %w[nil? blank? present?].freeze
# check if node to see whose conditional statement nodes contain nodes that can use query attribute instead.
#
# it will check every call nodes in the if nodes. If the call node is
#
# 1. two method calls, like @user.login.nil?
# 2. the receiver is one of the model names
# 3. the message of first call is the model's attribute,
# the message is not in any of associations name and is not pluralize
# 4. the message of second call is one of nil?, blank? or present? or
# the message is == and the argument is ""
#
# then the call node can use query attribute instead.
add_callback :start_if, :start_unless, :start_elsif, :start_ifop, :start_if_mod, :start_unless_mod do |node|
all_conditions =
if node.conditional_statement == node.conditional_statement.all_conditions
[node.conditional_statement]
else
node.conditional_statement.all_conditions
end
all_conditions.each do |condition_node|
next unless query_attribute_node = query_attribute_node(condition_node)
receiver_node = query_attribute_node.receiver
add_error "use query attribute (#{receiver_node.receiver}.#{receiver_node.message}?)",
node.file,
query_attribute_node.line_number
end
end
private
# recursively check conditional statement nodes to see if there is a call node that may be
# possible query attribute.
def query_attribute_node(conditional_statement_node)
case conditional_statement_node.sexp_type
when :and, :or
node =
query_attribute_node(conditional_statement_node[1]) || query_attribute_node(conditional_statement_node[2])
node.file = conditional_statement_code.file
return node
when :not
node = query_attribute_node(conditional_statement_node[1])
node.file = conditional_statement_node.file
when :call
return conditional_statement_node if possible_query_attribute?(conditional_statement_node)
when :binary
return conditional_statement_node if possible_query_attribute?(conditional_statement_node)
end
nil
end
# check if the node may use query attribute instead.
#
# if the node contains two method calls, e.g. @user.login.nil?
#
# for the first call, the receiver should be one of the class names and
# the message should be one of the attribute name.
#
# for the second call, the message should be one of nil?, blank? or present? or
# it is compared with an empty string.
#
# the node that may use query attribute.
def possible_query_attribute?(node)
return false unless node.receiver.sexp_type == :call
variable_node = variable(node)
message_node = node.grep_node(receiver: variable_node.to_s).message
is_model?(variable_node) && model_attribute?(variable_node, message_node.to_s) &&
(QUERY_METHODS.include?(node.message.to_s) || compare_with_empty_string?(node))
end
# check if the receiver is one of the models.
def is_model?(variable_node)
return false if variable_node.const?
class_name = variable_node.to_s.sub(/^@/, '').classify
models.include?(class_name)
end
# check if the receiver and message is one of the model's attribute.
# the receiver should match one of the class model name, and the message should match one of attribute name.
def model_attribute?(variable_node, message)
class_name = variable_node.to_s.sub(/^@/, '').classify
attribute_type = model_attributes.get_attribute_type(class_name, message)
attribute_type && !%w[integer float].include?(attribute_type)
end
# check if the node is with node type :binary, node message :== and node argument is empty string.
def compare_with_empty_string?(node)
node.sexp_type == :binary && ['==', '!='].include?(node.message.to_s) &&
s(:string_literal, s(:string_content)) == node.argument
end
end
end
end
| true |
5485a7e64433c6a7b4e87e39235cb23771c7af8e | Ruby | Noirbot/TicTicToeAgents | /GameDriver.rb | UTF-8 | 3,322 | 3.671875 | 4 | [] | no_license | require "./TTTGame.rb"
require "./RandomTTTPlayer.rb"
require "./SmartTTTPlayer.rb"
# Adding a method to the global String class to check if a string represents an integer.
class String
def is_i?
!!(self =~ /^[-+]?[0-9]+$/)
end
end
# If there are no arguments, give help.
if ARGV.length == 0
puts("Help!\nUsage: ruby GameDriver.rb <agent-x> <agent-o> <num_games> [--silent]\n\tValues for agent-x: 'random', 'smart'\n\tValues for agent-o: 'random', 'smart'\n\tValues for num_games: Any integer\n\t--silent will suppress additional output - boards for every move and winners for each game.")
exit
else # If there are arguments, but they are not the ones we need/expect, give help.
if ARGV.length > 4 or ARGV.length < 3 or (ARGV[0] != 'smart' and ARGV[0] != 'random') or (ARGV[1] != 'smart' and ARGV[1] != 'random') or !(ARGV[2].is_i? and ARGV[2].to_i > 0)
puts("Help!\nUsage: ruby GameDriver.rb <agent-x> <agent-o> <num_games> [--silent]\n\tValues for agent-x: 'random', 'smart'\n\tValues for agent-o: 'random', 'smart'\n\tValues for num_games: Any integer\n\t--silent will suppress additional output - boards for every move and winners for each game.")
exit
else # Store the arguments to the correct variables.
agent_x = ARGV[0]
agent_o = ARGV[1]
num_games = ARGV[2].to_i
if ARGV.length == 4 and ARGV[3] == '--silent'
debug = false
else
puts("Debug Mode Activated. I Hope You're Ready!")
puts("Player Information:\nPlayer X is the #{agent_x} agent\nPlayer O is the #{agent_o} agent\nPlaying #{num_games} Games!")
debug = true
end
end
end
# Win/loss tracking variables.
game_count = 0
x_wins = 0
cat_wins = 0
while game_count < num_games do
# Instantiate the agents and game tracker.
game = TTTGame.new()
player_x = agent_x == 'smart' ? SmartTTTPlayer.new('X', debug) : RandomTTTPlayer.new(debug)
player_o = agent_o == 'smart' ? SmartTTTPlayer.new('O', debug) : RandomTTTPlayer.new(debug)
if debug
puts "Starting Game #{game_count + 1}"
end
while not game.has_winner? and not game.is_full? do # As long as we need someone to move, select the correct player and have them pick a move.
if game.to_play == 'X'
move = player_x.choose_move(game.game_board)
unless game.turn_x?(move.x, move.y)
puts('Somehow, someone went on the wrong turn.')
end
else
move = player_o.choose_move(game.game_board)
unless game.turn_o?(move.x, move.y)
puts('Somehow, someone went on the wrong turn.')
end
end
if debug
puts("#{game.board_string}#####")
end
end
# If the last move won the game for someone,
if game.has_winner?
if debug
puts("The Glorious Winner of game #{game_count + 1} is #{game.winner}")
end
if game.winner == 'X' # We only need to track x-wins and cat games, since O-wins is everything else.
x_wins = x_wins + 1
end
else # If there's not a winner, there's a tie.
if debug
puts('Filled board with no winner.')
end
cat_wins = cat_wins + 1
end
if debug
puts('The Final Board Position is:')
puts("#{game.board_string}\n")
end
game_count = game_count + 1
end
# Print the helpful stats.
puts("Total Game Stats\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nX: #{x_wins} Wins\nO: #{game_count - x_wins - cat_wins} Wins\nCat Games: #{cat_wins}\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
| true |
dd6652ae5ca59071c73dac6b2ac1db86aaec001f | Ruby | austinoso/ruby-oo-complex-objects-school-domain-sfo-web-012720 | /lib/school.rb | UTF-8 | 481 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class School
attr_accessor :roster
def initialize(school_name)
@name = school_name
@roster = Hash.new{|h,k| h[k] = []}
end
def add_student(name, grade)
@roster[grade] << name
end
def grade(grade)
@roster[grade]
end
def sort
sorted_roster = {}
@roster.map do |k,v|
sorted_roster[k] = v.sort
end
sorted_roster
end
end
school = School.new("Bay High School") | true |
0ba54649b24fed1d4a2c8caca1ceeac450dea1ae | Ruby | motonari728/donno | /lib/tasks/sample_data.rake | UTF-8 | 778 | 2.75 | 3 | [] | no_license | require 'securerandom'
namespace :db do
desc "Fill database with sample data"
task populate: :environment do #populate: データを入れる,入植させる
make_rooms
make_users
make_microposts
end
end
def make_rooms
10.times do |n|
room_name = Faker::Name.name
Room.create!( room_name: room_name )
end
end
def make_users
uuid = "XXX"
room_id = 1
User.create!( uuid: uuid, room_id: room_id )
100.times do |n|
uuid = SecureRandom.uuid # => "96b0a57c-d9ae-453f-b56f-3b154eb10cda"
room_id = 1
User.create!( uuid: uuid, room_id: room_id )
end
end
def make_microposts
users = User.all
room_id = 1
users.each do |user|
content = Faker::Lorem.sentence(5)
Micropost.create!( content: content, room_id: room_id, uuid: user.uuid )
end
end
| true |
5035298fef7cb81a9b023221042856cfe958b7b2 | Ruby | gurgeous/scripto | /lib/scripto/run_commands.rb | UTF-8 | 2,553 | 3.03125 | 3 | [
"MIT"
] | permissive | require "English"
require "shellwords"
module Scripto
module RunCommands
# The error thrown by #run, #run_capture and #run_quietly on failure.
class RunError < StandardError
end
# Run an external command. Raise RunError if something goes wrong. The
# command will be echoed if verbose?.
#
# Usage is similar to Kernel#system. If +args+ is nil, +command+ will be
# passed to the shell. If +args+ are included, the +command+ and +args+ will
# be run directly without the shell.
def run(command, args = nil)
CommandLine.new(command, args).run
end
# Run a command and capture the output like backticks. See #run
# for details.
def run_capture(command, args = nil)
CommandLine.new(command, args).capture
end
# Run a command and suppress output by redirecting to /dev/null. See #run
# for details.
def run_quietly(command, args = nil)
cmd = CommandLine.new(command, args)
run("#{cmd} > /dev/null 2> /dev/null")
end
# Returns true if the command succeeds. See #run for details.
def run_succeeds?(command, args = nil)
run_quietly(command, args)
true
rescue RunError
false
end
# Returns true if the command fails. See #run for details.
def run_fails?(command, args = nil)
!run_succeeds?(command, args)
end
# Escape str if necessary. Useful for passing arguments to a shell.
def shellescape(str)
Shellwords.escape(str)
end
# :nodoc:
class CommandLine
attr_accessor :command, :args
def initialize(command, args)
self.command = command
self.args = begin
if args
args.map(&:to_s)
else
[]
end
end
end
def run
system(command, *args)
raise!($CHILD_STATUS) if $CHILD_STATUS != 0
end
def capture
begin
captured = `#{self}`
rescue Errno::ENOENT
raise RunError, "#{self} failed : ENOENT (No such file or directory)"
end
raise!($CHILD_STATUS) if $CHILD_STATUS != 0
captured
end
def raise!(status)
if status.termsig == Signal.list["INT"]
raise "#{self} interrupted"
end
raise RunError, "#{self} failed : #{status.to_i / 256}"
end
def to_s
if !args.empty?
escaped = args.map { Shellwords.escape(_1) }
"#{command} #{escaped.join(" ")}"
else
command
end
end
end
end
end
| true |
da4d5fc057fd07c55254bfab5d2e1c87c0c7607f | Ruby | sgneha/chitter-challenge | /lib/peep.rb | UTF-8 | 254 | 2.71875 | 3 | [] | no_license | class Peep
attr_reader :id, :text, :timestamp, :updatedtime, :user_id
def initialize(id, text, timestamp, updatedtime, user_id)
@id = id
@text = text
@timestamp = timestamp
@updatedtime = updatedtime
@user_id = user_id
end
end
| true |
ed1923d31fae5442054ee142790ad4a07229a44b | Ruby | simonewebdesign/expression-parser | /main.rb | UTF-8 | 291 | 3.625 | 4 | [] | no_license | require './evaluator.rb'
# This program calculates the value of an expression
# consisting of numbers, arithmetic operators, and parentheses.
print 'Enter an expression: '
expression = gets
evaluator = Evaluator.new expression
result = evaluator.get_expression_value
puts "=> #{result}"
| true |
91a0358896d012a033a5d882501260df4d332178 | Ruby | micktaiwan/weewar-bot-platform | /specs/goals_tests.rb | UTF-8 | 498 | 2.875 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../lib/goal'
class MyClass
def initialize
@some_value = 2
end
def set_action(goal)
goal.set_action(method(:test_action))
end
def test_action
@some_value
end
end
describe "Goal" do
before(:all) do
@goal = Weewar::Goal.new(:test)
@plan = Weewar::Plan.new
@plan << @goal
@test = MyClass.new
@test.set_action(@goal)
end
it "init" do
@goal.run.should eq(2)
@plan[0].should eq(@goal)
end
end
| true |
e987253df2db83e7e54cb2cff3ba9b22cf6448bb | Ruby | ricocaldeira/domr | /bin/domr | UTF-8 | 173 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'domr'
# Check for empty query
if !ARGV[0]
arg = ''
else
arg = ARGV[0]
end
# Perform the search
if !Domr.search(arg)
exit 1
else
exit 0
end | true |
1d84d1558f20adfd4611d594142e59eccbc1370a | Ruby | kaleemullah/being_lucky | /being_lucky.rb | UTF-8 | 307 | 3.53125 | 4 | [] | no_license | require_relative 'die'
class BeingLucky
attr_reader :dice
def initialize(dice)
@dice = dice
end
def score
score = 0
(1..6).each do |num|
count = dice.count(num)
# calculate each die score and add it
score += Die.new(num, count).score
end
score
end
end | true |
4c3c80a8ece9bda975e9cd56dd3304328414065f | Ruby | shaunagm/bridge_troll | /app/services/omniauth_providers.rb | UTF-8 | 2,019 | 2.71875 | 3 | [] | no_license | module OmniauthProviders
def self.provider_data
[
{
key: :facebook,
name: 'Facebook',
icon: 'fa-facebook-square'
},
{
key: :twitter,
name: 'Twitter',
icon: 'fa-twitter-square'
},
{
key: :github,
name: 'Github',
icon: 'fa-github-square'
},
{
key: :meetup,
name: 'Meetup',
icon: 'fa-calendar'
}
]
end
def self.provider_count
self.provider_data.count
end
def self.finish_auth_for(authentication)
if authentication.provider == 'meetup'
MeetupImporter.new.associate_user(authentication.user, authentication.uid)
end
end
def self.provider_data_for(provider)
self.provider_data.find { |data| data[:key] == provider.to_sym }
end
def self.user_attributes_from_omniauth(omniauth)
case omniauth['provider']
when 'facebook'
self.facebook_omniauth_attributes(omniauth)
when 'twitter'
self.twitter_omniauth_attributes(omniauth)
when 'github'
self.github_omniauth_attributes(omniauth)
when 'meetup'
self.meetup_omniauth_attributes(omniauth)
else
raise 'Unknown Provider'
end
end
private
def self.split_name(full_name)
return {} if full_name.blank?
components = full_name.split(' ')
{
first_name: components[0],
last_name: components[1..-1].join(' ')
}
end
def self.facebook_omniauth_attributes(omniauth)
{
email: omniauth['info']['email'],
first_name: omniauth['info']['first_name'],
last_name: omniauth['info']['last_name']
}
end
def self.twitter_omniauth_attributes(omniauth)
self.split_name(omniauth['info']['name'])
end
def self.github_omniauth_attributes(omniauth)
self.split_name(omniauth['info']['name']).merge(
email: omniauth['info']['email']
)
end
def self.meetup_omniauth_attributes(omniauth)
self.split_name(omniauth['info']['name'])
end
end | true |
a23f6cc7943b6a14abb56f91f5d84afd9f87f5fa | Ruby | reneecruz/blood-oath-relations-dumbo-web-080519 | /app/models/cult.rb | UTF-8 | 2,016 | 3.6875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Cult
attr_accessor :name, :location, :founding_year, :slogan
@@all = []
def initialize(name, location, founding_year, slogan)
@name = name
@location = location
@founding_year = founding_year
@slogan = slogan
@@all << self
end
def oaths
BloodOath.all.select do |oath|
oath.cult == self
end
end
def followers
oaths.map do |oath|
oath.follower
end
end
# Cult.all
# returns an Array of all the cults
def self.all
@@all
end
# Cult#recruit_follower
# takes in an argument of a Follower instance and adds them to this cult's list of followers
def recruit_follower(follower)
BloodOath.new(follower, self)
end
# Cult#cult_population
# returns a Fixnum that is the number of followers in this cult
def cult_population
end
# Cult.find_by_name
# takes a String argument that is a name and returns a Cult instance whose name matches that argument
def self.find_by_name(name)
self.all.find do |cult|
cult == name
end
end
# Cult.find_by_location
# takes a String argument that is a location and returns an Array of cults that are in that location
def self.find_by_location(location)
self.all.select do |cult|
cult.location == location
end
end
## Cult.find_by_founding_year
# takes a Fixnum argument that is a year and returns all of the cults founded in that year
def self.find_by_founding_year(founding_year)
self.all.select do |cult|
cult.founding_year == founding_year
end
end
end
# Cult
# Cult#name
# returns a String that is the cult's name
# Cult#location
# returns a String that is the city where the cult is located
# Cult#founding_year
# returns a Fixnum that is the year the cult was founded
# Cult#slogan
# returns a String that is this cult's slogan
| true |
8ed9d6c985c5e8d3d5fb54e48bde050a3aecaa31 | Ruby | zeade/minesweeper | /lib/minesweeper/solver.rb | UTF-8 | 4,789 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | require 'benchmark'
module Minesweeper
class Solver
attr_accessor :board, :wins, :losses, :solve_time
# Run from class wrapper
def self.run(tries: 100_000, debug: false)
solver = self.new(debug: debug)
solver.solve(tries: tries)
end
def initialize(size: 10, mines: 10, debug: false)
@wins = 0
@losses = 0
@solve_time = 0
@size = size
@mines = mines
@debug = debug
end
def solve(tries: 100_000)
@wins = 0
@losses = 0
@solve_time = Benchmark.realtime do
tries.times do
if solve_one == 1
@wins += 1
else
@losses += 1
end
end
end
puts "wins: #{wins}, losses: #{losses}, took: #{solve_time.round(4)} sec"
end
def solve_one
@board = Minesweeper::Board.new(rows_count: @size, mines_count: @mines)
board.uncover_first 0, 0
loop do
display_board
# stop
return 0 if board.lost?
return 1 if board.won?
# Walk board till there are no single position logical are cleared or flagged
loop do
if simple_clear_and_flag == 0
break
else
display_board
end
end
# Clear any remaining tiles if we have put down as many flags as there are mines
if board.all_tiles.count { |t| t.flagged? } == board.mines_count
board.all_tiles.select { |t| t.untouched? }.each do |t|
board.uncover t.row, t.column
end
# Pick (guess) a new tile to uncover
elsif board.all_tiles.find { |t| t.untouched? }
# Attempt to locate worst forced choice first to exit game early
pick_fifty_fifty || pick_best_random
end
end
end
def stop
print board.text_display
gets
end
def display_board
print board.text_display if @debug
end
def display_msg(msg)
puts msg if @debug
end
def simple_clear_and_flag
flags_set, tiles_cleared = 0, 0
board.all_tiles do |t|
# Untouched or already looked at, move on
next if t.untouched? || t.flagged?
mines = t.adjacent_mines_count
# Not surrounded by mines, move on
next if mines == 0
flagged = t.adjacent_flagged_count
untouched = t.adjacent_untouched_count
# Nothing to do, move on
next if untouched == 0
# Clear any tiles that are not flagged if we have as many flags as untouched tiles
if flagged == mines && untouched > 0
t.adjacent.each do |a|
next unless a.untouched?
board.uncover a.row, a.column
# Fail out if we somehow uncovered a mine
fail if a.mine?
tiles_cleared += 1
end
# Flag any untouched tiles that add up to total of remaining mines
elsif flagged < mines && untouched == mines - flagged
t.adjacent.each do |a|
next unless a.untouched?
a.flag!
# Fail out if we somehow flagged an empty tile
fail unless a.mine?
flags_set += 1
end
end
end
flags_set + tiles_cleared
end
# Return any isolated pairs that can only be guessed at
def pick_fifty_fifty
pick = nil
board.all_tiles.select { |t| t.adjacent_untouched_count == 1 }.each do |t|
a = t.adjacent.find { |a| a.untouched? }
if a.adjacent_untouched_count == 1
pick = a
break
end
end
if pick
display_msg "picking 50-50: (#{pick.row}, #{pick.column})"
board.uncover pick.row, pick.column
end
pick
end
def pick_best_random
best_ratio = 8 # (impossibly) best = 0.125
best_tile = nil
# Look at all uncovered tiles that have: surrounding mines count, untouched tiles
board.all_tiles.select { |t| t.uncovered? && t.adjacent_mines_count > 0 && t.adjacent_untouched_count > 0 }.each do |t|
r = t.adjacent_mines_count / t.adjacent_untouched_count.to_f
if r < best_ratio
best_ratio = r
best_tile = t
end
end
# We may not have a best selection
pick = if best_tile
pick = best_tile.adjacent.select { |t| t.untouched? }.sample
display_msg "picking: (#{pick.row}, #{pick.column}), based on (#{best_tile.row}, #{best_tile.column}) (ratio=#{best_ratio.round(3)})"
pick
else
pick = board.all_tiles.select { |t| t.untouched? }.sample
display_msg "picking randomly: (#{pick.row}, #{pick.column})"
pick
end
board.uncover pick.row, pick.column
end
end
end
| true |
a74b7e66b8ee740db091e82a1071cdbe494bc68e | Ruby | L-codes/ctf-scripts | /misc/encoder/base92.rb | UTF-8 | 1,757 | 3.4375 | 3 | [] | no_license | #!/usr/bin/env ruby
#
# Author L
# base92 encode/decode
#
class Base92
def self.decode(str)
return '' if str == '~'
bitstr = ''
str.chars.each_slice(2) do |x,y|
if y
n = base92_ord(x)*91 + base92_ord(y)
bitstr += '%013b' % n
else
n = base92_ord(x)
bitstr += '%06b' % n
end
end
bitstr.scan(/[01]{8}/).map{|n| n.to_i(2)}.pack('C*')
end
def self.encode(str)
return '~' if str == ''
bitstr = str.bytes.map{|x| '%08b' % x}.join
bitstr.chars.each_slice(13).map{|bs|
bs = bs.join
case bs.size
when 13
x, y = bs.to_i(2).divmod(91)
base92_chr(x) + base92_chr(y)
when 0..6
base92_chr((bs+'0'*(6-bs.size)).to_i(2))
else
x, y = (bs+'0'*(13-bs.size)).to_i(2).divmod(91)
base92_chr(x) + base92_chr(y)
end
}.join
end
private
def self.base92_chr(val)
raise 'val must be in (0..91)' unless (0..91).include? val
return '!' if val == 0
val <= 61 ? ('#'.ord + val - 1).chr : ('a'.ord + val - 62).chr
end
def self.base92_ord(val)
case val
when '!'
0
when '#'..'_'
val.ord - '#'.ord + 1
when 'a'..'}'
val.ord - 'a'.ord + 62
else
raise 'val is not a base92 character'
end
end
end
if __FILE__ == $PROGRAM_NAME
if ARGV.size == 2
abort "No such option '#{ARGV[0]}'" unless 'ed'.index ARGV[0]
abort "No such file '#{ARGV[1]}'" unless File.exist? ARGV[1]
data = File.binread(ARGV[1]).strip
if ARGV[0] == 'e'
puts Base92.encode data
else
puts Base92.decode data
end
else
puts <<~EOF
usage:
base92.rb <option> <file>
option:
e - encode
d - decode
EOF
end
end
| true |
fe527f69f2103475cd744eb7f4463dd35383b280 | Ruby | geoffreyadebonojo-zz/super_sports_games-new | /super_sports_games-master/runner.rb | UTF-8 | 1,068 | 4.09375 | 4 | [] | no_license | # Create a program that allows a User to interact with the Games through the command line
# Upon starting the program, the User should enter the year for the games
# The User can then create new Events and get a Summary of the Events
require 'pry'
require './lib/games'
def create_new_games
p "What year are the games?"
reply = gets.chomp.to_i
games = Games.new(reply)
puts "LET THE #{games.year} GAMES BEGIN!"
end
def add_events
p "Add events?"
reply = gets.chomp.to_s
if reply == "y"
create_new_event
end
end
def create_new_event
p "What's the new event called?"
event_name = gets.chomp.to_s
age_array = enter_ages
@new_event = Event.new("#{event_name}", age_array)
# puts "#{@new_event.name.upcase} event has been created!"
return @new_event
end
def enter_ages
p "please enter the ages of the participants, separated by commas"
ages = gets.chomp.split(",").to_a
ages.map do |age|
age.to_i
end
end
puts "Create New Games? y/!y"
reply = gets.chomp.to_s
if reply == "y"
create_new_event
else
puts "Goodbye!"
end
| true |
77a0f92a618b8fb83655099999de9e772c84c2be | Ruby | AnanthSrinivasan/CodeChallenges | /Translator/MetalObject.rb | UTF-8 | 299 | 2.6875 | 3 | [
"MIT"
] | permissive | # MetalObject will hold the values of various metal
# present in the configuration.
# silver - silver value
# gold - gold value
# iron - iron value
class MetalObject
# attr_accessor :silver
# attr_accessor :gold
# attr_accessor :iron
attr_accessor :type
attr_accessor :value
end
| true |
aaab92012afc8488c624cf62e888c40be3187c93 | Ruby | petertseng/exercism-problem-specifications | /exercises/food-chain/verify.rb | UTF-8 | 1,285 | 3.234375 | 3 | [
"MIT"
] | permissive | require 'json'
require_relative '../../verify'
ANIMALS = [
[:horse, 'She\'s dead, of course!'],
[:cow, 'I don\'t know how she swallowed a cow!'],
[:goat, 'Just opened her throat and swallowed a goat!'],
[:dog, 'What a hog, to swallow a dog!'],
[:cat, 'Imagine that, to swallow a cat!'],
[:bird, 'How absurd to swallow a bird!'],
[:spider, 'It', 'wriggled and jiggled and tickled inside her'],
[:fly],
].map(&:freeze).freeze
def verse(n)
animal, extra1, extra2 = ANIMALS[-n]
punctuation = extra1&.end_with?(?!) ? '' : '.'
[
"I know an old lady who swallowed a #{animal}.",
extra1 && [extra1, extra2].compact.join(' ') + punctuation,
].compact + (n >= ANIMALS.size ? [] : ANIMALS.last(n).each_cons(2).map { |(a, *), (b, _, c)|
"She swallowed the #{a} to catch the #{b}#{c && " that #{c}"}."
} << "I don't know why she swallowed the fly. Perhaps she'll die.")
end
module Intersperse refine Enumerable do
def intersperse(x)
map { |e| [x, e] }.flatten(1).drop(1)
end
end end
using Intersperse
def verses(a, b)
(a..b).map { |n| verse(n) }.intersperse('').flatten(1)
end
json = JSON.parse(File.read(File.join(__dir__, 'canonical-data.json')))
verify(json['cases'], property: 'recite') { |i, _|
verses(i['startVerse'], i['endVerse'])
}
| true |
f1882ea6502144708eea630d9a8adcf6db14df73 | Ruby | TashfeenRao/tic-tac-toe | /spec/game_spec.rb | UTF-8 | 4,051 | 3.109375 | 3 | [] | no_license | # frozen_string_literal: true
require_relative '../lib/board'
require_relative '../lib/game_status'
require_relative '../lib/player'
RSpec.describe 'GameStatus' do
let(:board) { Board.new }
let(:plyr) { Player.new }
let(:game) { GameStatus.new }
let(:display) { TicTacToe.new }
let(:win) { [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] }
describe '#initialize' do
it 'defines a win_combinations with arrays for each win combination' do
expect(game.win_combinations).to eql(win)
end
end
describe '#won?' do
it 'it will return winning combination if board having winning combinations' do
brd = ['X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
expect(game.won?(brd, win)).to eql([0, 1, 2])
end
it 'it will return winning combination if board having winning combinations' do
brd = [' ', ' ', ' ', 'X', 'X', 'X', ' ', ' ', ' ']
expect(game.won?(brd, win)).to eql([3, 4, 5])
end
it 'it will return winning combination if board having winning combinations' do
brd = [' ', ' ', ' ', ' ', ' ', ' ', 'X', 'X', 'X']
expect(game.won?(brd, win)).to eql([6, 7, 8])
end
it 'it will return winning combination if board having winning combinations' do
brd = ['O', ' ', ' ', 'O', ' ', ' ', 'O', ' ', ' ']
expect(game.won?(brd, win)).to eql([0, 3, 6])
end
it 'it will return winning combination if board having winning combinations' do
brd = [' ', 'O', ' ', ' ', 'O', ' ', ' ', 'O', ' ']
expect(game.won?(brd, win)).to eql([1, 4, 7])
end
it 'returns winning combination for diagonal top left to bottom right' do
brd = ['X', ' ', ' ', ' ', 'X', ' ', ' ', ' ', 'X']
expect(game.won?(brd, win)).to eql([0, 4, 8])
end
it 'returns winning combination for diagonal top right to bottom left' do
brd = ['', ' ', 'X', ' ', 'X', ' ', 'X', ' ', ' ']
expect(game.won?(brd, win)).to eql([2, 4, 6])
end
it 'it will return nil if winning combinations are not provide' do
brd = [' ', 'O', ' ', ' ', 'X', ' ', ' ', 'O', ' ']
expect(game.won?(brd, win)).to eql(nil)
end
end
describe '#draw?' do
it 'it will return true if board is full and not have winning combinatons' do
brd = %w[X O X O X O O X O]
expect(game.draw?(brd, win)).to eql(true)
end
it 'it will return false if board is full and having winning combinations' do
brd = %w[X O X O X O X X X]
expect(game.draw?(brd, win)).not_to eql(true)
end
end
describe '#full?' do
it 'returns true if the board array fills up with players tokens' do
brd = %w[X O X O X X O X O]
expect(game.full?(brd)).to eql(true)
end
it 'returns false if the board array is not full' do
brd = ['X', 'O', 'X', 'O', 'X', ' ', 'O', 'X', 'O']
expect(game.full?(brd)).not_to eql(true)
end
end
describe '#game_over?' do
it 'returns true if the board is full' do
brd = %w[X O X O X X O X O]
expect(game.game_over?(brd, win)).to eql(true)
end
it 'returns true if the game is won' do
brd = ['X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
expect(game.game_over?(brd, win)).to eql(true)
end
it 'return true if the game is a draw' do
brd = %w[X O X O X X O X O]
expect(game.game_over?(brd, win)).to eql(true)
end
end
describe '#position_taken?' do
it 'returns true if the board cell occupies with "X" or "O" token' do
brd = [' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
expect(board.position_taken?(brd, 1)).to eql(true)
end
it 'returns false if the board cell is empty' do
brd = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
expect(board.position_taken?(brd, 3)).not_to eql(true)
end
end
describe '#move' do
it "places player's to the position specified" do
current = board.move(board.board, 2, plyr)
brd = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
expect(brd[2] = current).to eql('X')
end
end
end
| true |
8370a5e815953764c157487042c16faf59613717 | Ruby | tera911/merrychacha | /loaddata.rb | UTF-8 | 4,425 | 2.734375 | 3 | [] | no_license | #!/usr/bin/ruby
# encoding: utf-8
require "csv"
require "Base64"
# パスを指定してcsvをロードする
def loadCSV(filename)
csv = CSV.read(filename, encoding: "SJIS:UTF-8")
return csv
end
# CSVを書き込む
def writeCSV(arr, filename)
CSV.open(filename, 'w') do |writer|
arr.each{|row| writer << row}
end
end
# CSV用の配列から文字を検索する
def search(csv, word)
i = 0
csv.each_with_index do |row, index|
# col.each_with_index do |row, index|
if row[9] != nil && row[9] =~ /#{word}/ then
p row.find_index {|item|item =~ /#{word}/}
p ""
p row[1]
p index
i = i + 1
end
# end
end
p i
end
# 花(マリメッコ系)の商品を削除
def remove_flower(csv)
csv.each_with_index do |row, index|
if row[9] != nil && row[9] =~ /flower/ then
csv.delete_at(index)
end
end
end
# 古い(卸先が使ってる)商品コードに妥当する商品を削除
def remove_oldcode(csv, pattern)
index = -1
index = csv.find_index {|item| item[2] =~ /#{pattern}/}
if index != nil && index >= 0 then
p "hit!"
csv.delete_at(index)
end
end
def remove_noImageData(csv)
csv.each_with_index do |row, index|
if index == 0 then
next
end
if !checkImage(row[2]) then
csv.delete_at(index)
end
end
end
# 商品コードをすべて表示する。
def viewCode(csv)
csv.each_with_index do |row, index|
p row[2] +" :" + index.to_s
end
end
# 自社で使う商品コードに変換する
def setCode(csv, start)
csv.each_with_index do |row, index|
if index == 0 then next end
row[200] = start
start = start + 1
end
if start % 8 != 0 then
count = 8 - (start % 8) - 1;
count.times do
csv.push ["","","","","","","","","","","","","","","","","","","",""]
end
end
end
# 商品説明文から画像パスを取得する。(現在は使用されていない)
def getImageFileName(row)
text = row[9][0..150]
start = text =~ /http\:\/\/lib2\.shopping\.srv\.yimg\.jp\/lib\//
if start == nil then
return nil
end
text = text[start + 51 ..150]
if text == nil then
return nil
end
path = text.scan /\S*\.jpg/
return path
end
# 画像があるかどうかを確認する
def checkImage(filename)
path = Dir::glob("./pictures/" << filename.downcase << "*")
if path.length > 5 || path.length == 0 then
return false
else
return true
end
end
# 画像のなめからimgタグを作成する。
def createImageTag(filename)
path = Dir::glob("./pictures/" << filename.downcase << "*")
if path.length > 5 then
p "yabai"
return ""
elsif path.length == 0 then
p "nil"
return ""
end
p path[0]
f = File.open(path[0])
img = "<img src=\""
img << "data:image/jpeg;base64, " << Base64.encode64(f.read)
img << "\" width=\"100px\" height=\"100px\"></img>"
return img
end
# カテゴリをまとめたファイルを作る(html)
def generateCatalog(csv)
if File.exists?("catalog.html") then
File.delete("catalog.html")
end
File.open("catalog.html", "w") do |file|
file.write File.open("head.m","r").read
csv.each_with_index do |row, index|
if index == 0 then
next
end
if (index - 1 ) % 8 == 0 then
if index >= 8 then
file.write "</table>"
end
end
if (index - 1) % 8 == 0 then
file.write "<table>"
end
file.write "<tr>"
file.write "<td contenteditable=true>松平<br>商会</td>\n" #会社名
file.write "<td contenteditable=true>" + row[200].to_s << "</td>\n" #商品コード
file.write "<td contenteditable=true>" + row[8] << "</td>\n" #商品名
file.write "<td contenteditable=true>" << createImageTag(row[2]) << "</td>\n"
#ファイルの画像パス
file.write "<td contenteditable=true>" + row[5].to_s << "</td>\n" #仕入れ値
file.write "<td contenteditable=true></td>" #売値(今は空)
file.write "<td><span>Y</span><span>ヤ</span><span>D</span><span>A</span></td>"
file.write "</tr>\n"
end
file.write File.open("foot.m", "r").read
end
end
def main()
csv = loadCSV("data.csv")
#マリメッコ系の商品を削除
remove_flower(csv)
remove_flower(csv)
#既存の商品を削除
remove_items = ["portable-led-battery", "iphone-cube", "iPhone5-quilt-book", "iPhone-nail","iphone5-steven","iphone5-arm"]
remove_items.each do |s|
remove_oldcode(csv, s)
end
remove_noImageData(csv)
remove_noImageData(csv)
remove_noImageData(csv)
remove_noImageData(csv)
setCode(csv, 2175)
generateCatalog(csv)
return csv
end
| true |
e0e40e2b74666dd90a3f3f66f1221a4d16427d9d | Ruby | vitormd/RubyAlgorithms | /spec/exercise_12_spec.rb | UTF-8 | 656 | 3.078125 | 3 | [] | no_license | require_relative '../exercises/exercise_12'
describe Array do
context 'self each' do
it 'execute the block then, return equal the argument' do
#Arrange
array = [1,2,3,4,5]
#Act
result = array.each { |x| x + 1 }
#Assert
expect(result).to eq([1,2,3,4,5])
end
it 'execute the block and test it' do
#Arrange
funcao = double('funcao')
allow(funcao).to receive :xablau
array = [1,2,3,4,5]
#Act
result = array.each { |x| funcao.xablau(x) }
#Assert
expect(funcao).to have_received(:xablau).with(1)
end
end
end
#Arrange, como preparar as dependencias do teste | true |
570078950fa15851e82db20a6f7b0bc1eca7223e | Ruby | isabella232/appoxy_rails | /lib/sessions/shareable.rb | UTF-8 | 7,135 | 2.515625 | 3 | [] | no_license | require 'aws'
require 'simple_record'
module Appoxy
module Sessions
module Shareable
# Call this method on your Sharable object to share it with the person.
# returns: a hash with :user (the user that the item was shared with), :ac (activation code that should be sent to the user)
# or false if couldn't be shared.
# You can check for errors by looking at the errors array of the object.
# Eg:
# if my_ob.share_with(x)
# # all good
# Mail the user a link that contains user_id and ac, this gem will take care of the rest.
# else
# # not all good, check errors
# errors = my_ob.errors
# end
def share_with(email, access_rights={}, options={})
access_rights = {} if access_rights.nil?
@email = email.strip
if @email == self.user.email
self.errors.add_to_base("User already owns this item.")
return false
end
user = ::User.find_by_email(@email)
if user.nil?
# lets create the user and send them an invite.
user = ::User.new(:email=>@email, :status=>"invited")
user.set_activation_code # todo: this shouldn't be on user anymore
if user.save
else
self.errors = user.errors
return false
end
end
activation_code = user.activation_code
# check if exists
share_domain = self.share_domain
item_id_name = self.item_id_name
# puts 'share_domain = ' + share_domain.inspect
@sdb = SimpleRecord::Base.connection
# @shared_with = share_class.find(:first, :conditions=>["user_id = ? and item_id = ?", user.id, @item.id])
@project_user = Shareable.get_results(:first, ["select * from #{share_domain} where user_id=? and #{item_id_name} = ?", user.id, self.id])
puts 'sharing user=' + @project_user.inspect
unless @project_user.nil?
self.errors.add_to_base("This item is already shared with #{email}.")
return false
end
now = Time.now
id = share_id(user)
@sdb.put_attributes(share_domain, id, {:new_share=>true,
:id=>id,
:created=>SimpleRecord::Translations.pad_and_offset(now),
:updated=>SimpleRecord::Translations.pad_and_offset(now),
:user_id => user.id,
:activation_code=>activation_code,
:status=>"invited",
item_id_name => self.id}.merge(access_rights),
true,
:create_domain=>true)
# ret = {
# :user=>user,
# :ac=>activation_code
# }
# return ret
return user
end
def item_id_name
return self.class.name.foreign_key
end
def common_attributes
["new_share", "id", "created", "updated", "user_id", item_id_name]
end
# Returns a list of users that this item is shared with.
def shared_with
project_users = Shareable.get_results(:all, ["select * from #{share_domain} where #{item_id_name} = ?", self.id])
user_ids = []
options_hash = {}
project_users.each do |puhash|
puhash.each_pair do |k, v|
puhash[k] = v[0]
end
puts 'puhash=' + puhash.inspect
user_ids << puhash["user_id"]
options_hash[puhash["user_id"]] = puhash
end
ret = ::User.find(:all, :conditions=>["id in ('#{user_ids.join("','")}')"]).collect do |u|
def u.share_options=(options=nil)
instance_variable_set(:@share_options, options)
end
def u.share_options
instance_variable_get(:@share_options)
end
u.share_options=options_hash[u.id]
u
end
ret
end
# this unshares by the
def unshare_by_id(id)
# @project_user = ProjectUser.find(params[:pu_id])
# @project_user.delete
# puts 'unsharing ' + id.to_s
@sdb = SimpleRecord::Base.connection
puts "delete_attributes=" + @sdb.delete_attributes(share_domain, id.to_s).inspect
# puts 'deleted?'
end
# Unshare by user.
def unshare(user)
@sdb = SimpleRecord::Base.connection
@sdb.delete_attributes(share_domain, share_id(user))
# @project_user = Shareable.get_results(:first, ["select * from #{share_domain} where user_id=? and #{item_id_name} = ?", user.id, self.id])
# @project_user.each do |pu|
# @sdb.delete_attributes(share_domain, pu["id"])
# end
end
def update_sharing_options(user, options={})
options={} if options.nil?
# puts 'options=' + ({ :updated=>Time.now }.merge(options)).inspect
@sdb = SimpleRecord::Base.connection
@project_user = Shareable.get_results(:first, ["select * from #{share_domain} where user_id=? and #{item_id_name} = ?", user.id, self.id])
# compare values
to_delete = []
@project_user.each_pair do |k, v|
if !common_attributes.include?(k) && !options.include?(k)
to_delete << k
end
end
if to_delete.size > 0
puts 'to_delete=' + to_delete.inspect
@sdb.delete_attributes(share_domain, share_id(user), to_delete)
end
@sdb.put_attributes(share_domain, share_id(user), {:updated=>Time.now}.merge(options), true)
end
def share_id(user)
"#{self.id}_#{user.id}"
end
def share_domain
# puts 'instance share_domain'
ret = self.class.name + "User"
# puts 'SHARE_NAME=' + ret
ret = ret.tableize
# puts 'ret=' + ret
ret
end
def self.get_results(which, q)
@sdb = SimpleRecord::Base.connection
next_token = nil
ret = []
begin
begin
response = @sdb.select(q, next_token)
rs = response[:items]
rs.each_with_index do |i, index|
puts 'i=' + i.inspect
i.each_key do |k|
puts 'key=' + k.inspect
if which == :first
return i[k].update("id"=>k)
end
ret << i[k]
end
# break if index > 100
end
next_token = response[:next_token]
end until next_token.nil?
rescue Aws::AwsError, Aws::ActiveSdb::ActiveSdbError
if ($!.message().index("NoSuchDomain") != nil)
puts 'NO SUCH DOMAIN!!!'
# this is ok
else
raise $!
end
end
which == :first ? nil : ret
end
end
end
end
| true |
e29d7abb7b261b0b773806ce348d25d979322906 | Ruby | htphan/codecreep | /lib/codecreep/github.rb | UTF-8 | 1,034 | 2.84375 | 3 | [
"MIT"
] | permissive | require 'httparty'
require 'pry'
module Codecreep
class Github
include HTTParty
base_uri 'https://api.github.com'
basic_auth ENV['GH_USER'], ENV['GH_PASS']
def get_user(username)
self.class.get("/users/#{username}")
end
def follower_page(username, page)
self.class.get("/users/#{username}/followers?page=#{page}&per_page=100")
end
def get_followers(username)
# self.class.get("/users/#{username}/followers?per_page=100")
page = 1
followers = []
followers = followers + self.follower_page(username, page)
until followers.length % 100 != 0
if self.follower_page(username, page)[0] != nil
page += 1
followers = followers + self.follower_page(username, page)
end
end
followers
# response.headers['link'].split(', ')[1].match(/page=(\d+)/)[1].to_i (takes the first one)
end
def get_following(username)
self.class.get("/users/#{username}/following?per_page=100")
end
end
end
| true |
ed4526999893f97ef77f17d9fbef9939cbb13099 | Ruby | JordanFaust/dotfiles | /eventable/lib/eventable/worker/pool.rb | UTF-8 | 1,000 | 2.53125 | 3 | [] | no_license | require 'concurrent'
require 'logger'
module Eventable
module Worker
class Pool
attr_accessor :store
def initialize(params = {})
@pool = Concurrent::FixedThreadPool.new(params[:threads] || 5)
@store = Concurrent::Map.new()
@task = nil
@signal = Proc.new {}
@callback = Proc.new {}
end
# Process the work item and signal when complete
def process(&block)
# Concurrent work
@pool.post do
@callbock ||= block
properties = block.call()
@signal.call(properties)
end
end
# Define the block that is executed when a work item is complete
def on_change(&block)
@signal = block
end
# Sets the interval at which data is refreshed.
def refresh(params, &block)
@task = Concurrent::TimerTask.new(execution_interval: params[:interval] || 10) do
block.call
end
@task.execute
end
end
end
end
| true |
8162dddda0d3c2688179af21caeac6ca066ebdda | Ruby | mozamimy/toolbox | /ruby/search_ec2_missing_tag/search_ec2_missing_tag.rb | UTF-8 | 732 | 2.546875 | 3 | [
"CC0-1.0"
] | permissive | #!/usr/bin/env ruby
require 'aws-sdk-ec2'
tag_key = ARGV[0]
ec2 = Aws::EC2::Client.new
results = []
ec2.describe_instances.reservations.each do |reservation|
results << reservation.instances.select do |instance|
instance.tags.all? { |tag| tag.key != tag_key }
end
end
results.flatten!
if results.size < 1
warn 'No instances.'
exit 1
end
results = results.sort_by { |r| r.tags.find { |t| t.key == 'Name' }.value }
puts '"Name","Instance ID","Role","Status"'
results.each do |result|
id = result.instance_id
name = result.tags.find { |t| t.key == 'Name' }.value
role = result.tags.find { |t| t.key == 'Role' }&.value
status = result.state.name
puts "\"#{name}\",\"#{id}\",\"#{role}\",\"#{status}\""
end
| true |
b90cbc9a419f8401a52796c2a6c978f965fab9f5 | Ruby | IvanKhoteev/polyglot | /app/interactions/phrases/create.rb | UTF-8 | 1,451 | 2.546875 | 3 | [] | no_license | module Phrases
class Create < ActiveInteraction::Base
object :word
hash :ru do
string :present_i
string :present_you
string :present_we
string :present_they
string :present_he
string :present_she
string :past_i
string :past_you
string :past_we
string :past_they
string :past_he
string :past_she
string :future_i
string :future_you
string :future_we
string :future_they
string :future_he
string :future_she
end
hash :en do
string :common
string :specific_present_statement
string :specific_past_statement
end
hash :personal_pronouns do
array :i_we, default: nil
array :you, default: nil
array :they, default: nil
array :he_she, default: nil
end
array :interrogatives, default: nil
array :pretexts, default: nil
def execute
create_statements_phrases
create_negatives_phrases
create_questions_phrases
end
private
def create_statements_phrases
Phrases::Statements::Create.run data
end
def create_negatives_phrases
Phrases::Negatives::Create.run data
end
def create_questions_phrases
Phrases::Questions::Create.run data
end
def data
{ word: word, en: en, ru: ru, interrogatives: interrogatives,
personal_pronouns: personal_pronouns, pretexts: pretexts }
end
end
end
| true |
1f43efd56d50e5936487e19549775e0c972204c9 | Ruby | kohkb/atcoder | /abc051_100/abc099/b.rb | UTF-8 | 95 | 2.953125 | 3 | [] | no_license | a, b = gets.chomp.split.map(&:to_i)
h = 0
(b - a - 1).downto(1) do |i|
h += i
end
p h - a
| true |
6b1d7ab2c5ccdc3a0ca92ca848d3d1c53a405895 | Ruby | xingzo/trivia-game | /db.rb | UTF-8 | 732 | 3.015625 | 3 | [] | no_license | # Database Configuration
# ======================
# Documentation: https://deveiate.org/code/pg/PG.html
# Use this module to:
# - Connect to the adventure database
# - CRUD operations (CREATE, SELECT, UPDATE, DELETE)
#
require 'pg'
def connection
PG::Connection.new(dbname: 'trivia')
end
def add_table(questions)
connection.exec("CREATE TABLE #{questions} (id SERIAL PRIMARY KEY, question VARCHAR(255), answer VARCHAR(255))")
p "Table created: #{questions}"
end
def add_questions(question, answer)
connection.exec("INSERT INTO questions (question, answer) VALUES ('#{question}','#{answer}')")
#include the list of values you want to add as arguments or add id manually
p "User created: #{question}, #{answer} "
end
| true |
4d6f41bf0ef3ae3737c73e9d75b0bac617487284 | Ruby | c-amos/ttt-10-current-player-ruby-intro-000 | /lib/current_player.rb | UTF-8 | 411 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # require_relative '../spec/current_player_spec.rb'
def turn_count(board)
counter = 0
for member in board
if member == "X"
counter += 1
end
if member == "O"
counter += 1
end
end
counter
end
def current_player(board)
counter = turn_count(board)
if counter % 2 == 0
current_player = "X"
end
if counter % 2 == 1
current_player = "O"
end
current_player
end
| true |
8f1b90a635688e03e634112a1b15944c1f9f04ca | Ruby | under-os/under-os | /gems/under-os-ui/spec/under_os/page/stylesheet_spec.rb | UTF-8 | 2,454 | 2.546875 | 3 | [
"MIT"
] | permissive | describe UnderOs::Page::Stylesheet do
before do
@stylesheet = UnderOs::Page::Stylesheet.new
end
describe '#initialize' do
it "should make an empty stylesheet" do
@stylesheet.rules.should == {}
end
it "should allow initialize with some rules" do
stylesheet = UnderOs::Page::Stylesheet.new(button: {color: 'orange'})
stylesheet.rules.should == {'button' => {color: 'orange'}}
end
end
describe '#[]' do
it "should allow to set new style rules" do
@stylesheet['button'] = {color: :red}
@stylesheet['button'].should == {color: :red}
end
it "should allow to extend the rules" do
@stylesheet['button'] = {color: 'red'}
@stylesheet['button'] = {right: 50 }
@stylesheet['button'].should == {color: 'red', right: 50}
end
it "should overwrite existing rules when match" do
@stylesheet['button'] = {color: 'red', left: 20}
@stylesheet['button'] = {color: 'blue'}
@stylesheet['button'].should == {color: 'blue', left: 20}
end
end
describe '#<<' do
it "should merge another stylesheet into the current one" do
other_sytles = UnderOs::Page::Stylesheet.new(button: { color: 'blue' })
@stylesheet['button'] = {left: 30}
@stylesheet << other_sytles
@stylesheet['button'].should == {color: 'blue', left: 30}
end
end
describe '#+' do
it "should create a new stylesheet combined out of the two" do
sheet1 = UnderOs::Page::Stylesheet.new(button: { color: 'blue' })
sheet2 = UnderOs::Page::Stylesheet.new(button: { left: 20 })
sheet3 = sheet1 + sheet2
sheet1['button'].should == {color: 'blue'}
sheet2['button'].should == {left: 20}
sheet3['button'].should == {color: 'blue', left: 20}
end
end
describe '#load' do
it "should load rules from the given test stylesheet file" do
@stylesheet.load('test.css')
@stylesheet.rules.should == {
"page"=>{:backgroundColor=>"yellow"},
".test"=>{:backgroundColor=>"green"}
}
end
end
describe '#styles_for' do
before do
@view = UnderOs::UI::View.new(class: 'test')
@stylesheet.load('app.css')
@stylesheet.load('test.css')
end
it "should calculate the styles correctly" do
@stylesheet.styles_for(@view).should == {
color: 'yellow',
backgroundColor: 'green',
borderRadius: 10
}
end
end
end
| true |
d806ce417a5ff4a8bf4029bd097f948bdcf37d48 | Ruby | wlcreate/ruby-oo-fundamentals-object-attributes-lab-nyc04-seng-ft-071220 | /lib/dog.rb | UTF-8 | 206 | 3.15625 | 3 | [] | no_license | class Dog
def name
@name
end
def name=(name_arg)
@name = name_arg
end
def breed
@breed
end
def breed=(breed_arg)
@breed = breed_arg
end
end | true |
f4aa2bc216ecd015868cc18e516311117711a675 | Ruby | zhangbay/guideproject | /blog/spec/string_calculator_spec.rb | UTF-8 | 318 | 2.796875 | 3 | [] | no_license | require "string_calculator"
describe StringCalculator do
context "two numbers" do
it "given 2,4" do
expect(StringCalculator.add("2,4")).to eql(6)
end
end
context "given '17,100'" do
it "returns 17" do
expect(StringCalculator.add("17,100")).to eql(117)
end
end
end | true |
eedd70a18dc85ef78fe277301ba5f875134bd0f3 | Ruby | angeljolon/learn-co-sandbox | /arrays.rb | UTF-8 | 392 | 3.953125 | 4 | [] | no_license | #create an Array
a = ["Ruth", "Lilly", "Bicondova","Romeo", "Dicaprio", "John"]
# puts a[0]
# puts a[3]
# #extracting ALL elements of an array
# puts a
# a.push("Pratt")
# a << "Zac"
# puts a
#removing elements from an array
# a.delete_at(0)
# puts a
#size the array
# puts a.size
#changing an element
# puts a[0]
a[0] = "CARDI B"
# puts a[0]
puts a
puts a[2]
a[2] = "Hiro"
puts a
| true |
65a2d58cbc3c4764c5dd9c2617b5dc24c33cffdb | Ruby | hhofner/Scripts | /secret_santa.rb | UTF-8 | 1,979 | 2.9375 | 3 | [] | no_license | require 'mail'
# Secret Santa
# names of all participants
friends = Array.new
participants = Array.new
secret_santas = Array.new
emails = Hash.new
# secret santa assignments
ss_mappings = Hash.new
name = 'temp'
email = 'temp'
print 'Enter Name and Email: '
while user_input = gets.chomp
splitted_input = Array.new
case user_input
when "end"
puts "Sending Secret Santas!"
break
when ""
puts "Sending Secret Santas!"
break
else
splitted_input = user_input.split('-')
friends.push(splitted_input[0])
participants.push(splitted_input[0])
secret_santas.push(splitted_input[0])
name = splitted_input[0]
email = splitted_input[1]
emails["#{name}"] = "#{email}"
end
end
if (friends.length < 3)
puts "only allows for 4 or more people"
else
# randomize and check if key is not equal to value
size = friends.length
while ss_mappings.length < size
# make copy of friends array
ss = secret_santas.sample
ff = friends.sample
if ss == ff
puts 'Mismatch'
else
ss_mappings["#{ss}"] = ff
secret_santas.delete("#{ss}")
friends.delete("#{ff}")
end
end
end
#puts ss_mappings
options = { :address => '',
:port => 7,
:domain => 'your.host.name',
:user_name => 'MY_USER_NAME',
:password => 'MY_PASSWORD',
:authentication => 'plain',
:enable_starttls_auto => true }
Mail.defaults do
delivery_method :smtp, options
end
# write to file
for friend in participants do
File.open("body.txt", "w") do |f|
f.print("Thank you for taking part in Secret Santa!\n")
f.puts("\n")
f.puts("Remember to keep this secret...")
f.puts("You are secret santa for...\n")
f.puts("\n")
f.puts("\n")
f.puts "#{ss_mappings["#{friend}"]} !"
end
mail = Mail.new do
to emails["#{friend}"]
#to 'B1401489@gl.aiu.ac.jp'
from 'your_email@site.com'
subject '~* SECRET SANTA *~'
body File.read('body.txt')
end
mail.deliver!
end
| true |
bb0fc03014f6a90c6ab78b93fdab5e22a550b547 | Ruby | socketry/async-http | /lib/async/http/proxy.rb | UTF-8 | 3,531 | 2.609375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2019-2023, by Samuel Williams.
require_relative 'client'
require_relative 'endpoint'
require_relative 'body/pipe'
module Async
module HTTP
# Wraps a client, address and headers required to initiate a connectio to a remote host using the CONNECT verb.
# Behaves like a TCP endpoint for the purposes of connecting to a remote host.
class Proxy
class ConnectFailure < StandardError
def initialize(response)
super "Failed to connect: #{response.status}"
@response = response
end
attr :response
end
module Client
def proxy(endpoint, headers = nil)
Proxy.new(self, endpoint.authority(false), headers)
end
# Create a client that will proxy requests through the current client.
def proxied_client(endpoint, headers = nil)
proxy = self.proxy(endpoint, headers)
return self.class.new(proxy.wrap_endpoint(endpoint))
end
def proxied_endpoint(endpoint, headers = nil)
proxy = self.proxy(endpoint, headers)
return proxy.wrap_endpoint(endpoint)
end
end
# Prepare and endpoint which can establish a TCP connection to the remote system.
# @param client [Async::HTTP::Client] the client which will be used as a proxy server.
# @param host [String] the hostname or address to connect to.
# @param port [String] the port number to connect to.
# @param headers [Array] an optional list of headers to use when establishing the connection.
# @see Async::IO::Endpoint#tcp
def self.tcp(client, host, port, headers = nil)
self.new(client, "#{host}:#{port}", headers)
end
# Construct a endpoint that will use the given client as a proxy for HTTP requests.
# @param client [Async::HTTP::Client] the client which will be used as a proxy server.
# @param endpoint [Async::HTTP::Endpoint] the endpoint to connect to.
# @param headers [Array] an optional list of headers to use when establishing the connection.
def self.endpoint(client, endpoint, headers = nil)
proxy = self.new(client, endpoint.authority(false), headers)
return proxy.endpoint(endpoint.url)
end
# @param client [Async::HTTP::Client] the client which will be used as a proxy server.
# @param address [String] the address to connect to.
# @param headers [Array] an optional list of headers to use when establishing the connection.
def initialize(client, address, headers = nil)
@client = client
@address = address
@headers = ::Protocol::HTTP::Headers[headers].freeze
end
attr :client
# Close the underlying client connection.
def close
@client.close
end
# Establish a TCP connection to the specified host.
# @return [Socket] a connected bi-directional socket.
def connect(&block)
input = Body::Writable.new
response = @client.connect(@address.to_s, @headers, input)
if response.success?
pipe = Body::Pipe.new(response.body, input)
return pipe.to_io unless block_given?
begin
yield pipe.to_io
ensure
pipe.close
end
else
# This ensures we don't leave a response dangling:
response.close
raise ConnectFailure, response
end
end
# @return [Async::HTTP::Endpoint] an endpoint that connects via the specified proxy.
def wrap_endpoint(endpoint)
Endpoint.new(endpoint.url, self, **endpoint.options)
end
end
Client.prepend(Proxy::Client)
end
end
| true |
1570739f17a216087d7624cd44a7c0a636ec3a01 | Ruby | prs148/chessmate | /app/models/queen.rb | UTF-8 | 209 | 3 | 3 | [] | no_license | class Queen < Piece
def valid_move?(x, y)
super(x, y) &&
(x_position == x || y_position == y ||
x + y == x_position + y_position ||
x - y == x_position - y_position)
end
end | true |
c48eac5069f4afc225bdff27981214998394b054 | Ruby | mkenane/looping-for-prework | /for.rb | UTF-8 | 86 | 2.875 | 3 | [] | no_license |
def using_for
checklist = 1..10
for item in checklist
puts "Wingardium Leviosa"
end
end
| true |
c9d6f00c808699026272e595ebb7350f56541007 | Ruby | kazutxt/Sample | /rb/dirのtree.rb | SHIFT_JIS | 1,150 | 2.984375 | 3 | [] | no_license | #dirtree
def dirs(path = Dir.pwd ,depth = [])
# JgfBNg̈ړ
Dir.chdir(path)
#p lastdir
# . .. ȊÔׂẴt@Czɂ
lists = Dir.glob("./*")
if(depth.size == 0)
print "/--+\n"
else
print File.basename(path) + "\n"
end
# ̗vfƂi܂./tĂ)
lists.size.times{ |i|
# ./菜
data = lists[i].slice!(2..-1)
# sԂ̐
depth.each{|j|
if j == 0
print(" |")
else
print(" ")
end
}
printf(" |\n")
# ܂łŐ
# t@CAtH_̍s̍쐬
depth.size.times{|k|
if depth[k] == 0
print(" |")
else
print(" ")
end
}
print(" ")
# ܂łō쐬
# +,/
if i == (lists.size - 1)
print("/")
else
print("+")
end
printf("---")
if File.ftype("./#{data}") == "directory"
if i == lists.size-1
dirs(path+"/"+data,depth << 1)
else
dirs(path+"/"+data,depth << 0)
end
Dir.chdir(path)
else
print data + "\n"
end
}
depth.pop
end | true |
83957dd0d703a0baf14d13d0000be0d26d211ce4 | Ruby | kiizerd/chess | /spec/event_bus_spec/event_bus_spec.rb | UTF-8 | 2,314 | 2.84375 | 3 | [] | no_license | require_relative '../../lib/event_bus/event_bus'
describe EventBus do
describe "#get_event" do
context "given token matches existing event" do
let(:new_event) { Event.new :new_event }
before { EventBus.events << new_event }
it "returns event object" do
event = EventBus.get_event :new_event
expect(event).to be_an Event
end
end
context "given non-matching token" do
let(:event) { EventBus.get_event :nonexistant }
it "returns false" do
expect(event).to be false
end
end
end
describe "#subscribe" do
let(:handler) { Handler.new(:handler, ->{ p :hi }) }
before { EventBus.subscribe :new_event, handler }
context "subscribing to a non-existant event" do
it "creates a new event with given name" do
event_name = EventBus.events[-1].name
expect(event_name).to be :new_event
end
it "subscribes(adds given handler) to new event" do
new_handler = Handler.new :new_handler, ->{ p :hi_again }
EventBus.subscribe :newer_event, new_handler
event_handler = EventBus.get_event(:newer_event).handlers.first
expect(event_handler).to be new_handler
end
end
context "subscribing to existing event" do
before { EventBus.events[0] = Event.new :old_event }
it "subscribes to event" do
EventBus.subscribe(:old_event, handler)
expect(EventBus
.get_event(:old_event)
.handlers
.find { |h| h == handler }
).to be handler
end
end
end
describe "#publish" do
context "publishing nonexistant event" do
it "creates a new event with given name" do
EventBus.publish(:new_event, { hi: 'there' })
event = EventBus.get_event :new_event
expect(event).to be_an Event
end
end
context "publishing existing event" do
let(:event) { Event.new :super_special_event }
let(:handler) { Handler.new :super_handler, ->{ p x} }
before { event.handlers << handler }
before { EventBus.events << event }
it "calls all of events handlers" do
expect(handler).to receive(:call).with({ hi: "there" })
EventBus.publish(:super_special_event, { hi: "there" })
end
end
end
end | true |
afb18b00771bd7d8ce570247eca9c7ee9f06ba61 | Ruby | loych03/ruby-advanced-class-methods-lab-dumbo-web-100818 | /lib/song.rb | UTF-8 | 1,159 | 3.25 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Song
attr_accessor :name, :artist_name
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
song= Song.new
song.save
song
end
def self.new_by_name(name_song)
song = self.new
song.name = name_song
song
end
def self.create_by_name(name_song)
song = self.create
song.name = name_song
song
end
def self.find_by_name(name_song)
self.all.find {|a| a.name == name_song}
end
def self.find_or_create_by_name(name_song)
self.find_by_name(name_song) || self.create_by_name(name_song)
end
def self.alphabetical
@@all.sort_by {|a| a.name}
end
def self.new_from_filename(filename)
parts = filename.split(" - ")
artist_name = parts[0]
song_name = parts[1].gsub(".mp3", "")
song = self.new
song.name = song_name
song.artist_name = artist_name
song
end
def self.create_from_filename(filename)
parts = filename.split(" - ")
artist_name = parts[0]
song_name = parts[1].gsub(".mp3", "")
song = self.create
song.name = song_name
song.artist_name = artist_name
song
end
def self.destroy_all
@@all.clear
end
end
| true |
ecdaa5b0b50957b6be85c80b89161bc0a6ec3cc5 | Ruby | COASST/coasst-old | /app/models/name.rb | UTF-8 | 401 | 3.671875 | 4 | [] | no_license | class Name
attr_reader :first_name, :middle_initial, :last_name
def initialize(first_name, middle_initial, last_name)
@first_name = first_name
@middle_initial = middle_initial
@last_name = last_name
end
def to_s
[ @first_name, @middle_initial, @last_name ].compact.join(" ")
end
def tokens
[ @first_name, @last_name].map { |l| l.downcase}
end
end
| true |
9c116f9310cbde131c22d7c0afc6c818c9b3a9c4 | Ruby | ajgosling/App_Academy_Review | /Alpha_Curriculum/rspec_exercises/rspec_exercise_1/lib/part_2.rb | UTF-8 | 811 | 3.609375 | 4 | [] | no_license | def hipsterfy(word)
i = word.length - 1
vowels = "aeiou"
while i >= 0
if vowels.include?(word[i].downcase)
return word[0...i] + word[i + 1..-1]
end
i -= 1
end
return word
end
def vowel_counts(str)
vowel_hash = Hash.new(0)
vowels = "aeiou"
str.each_char do |char|
if vowels.include?(char.downcase)
vowel_hash[char.downcase] += 1
end
end
return vowel_hash
end
def caesar_cipher(message, n)
alpha = ("a".."z").to_a
new_str = ""
message.each_char do |char|
if alpha.include?(char)
old_idx = alpha.index(char)
new_idx = (old_idx + n) % 26
new_str += alpha[new_idx]
else
new_str += char
end
end
return new_str
end | true |
c7d541e00add0a9c670bbe6b2cda5761cf8791e9 | Ruby | donal/mobile-auth | /v3/consumer_middleware.rb | UTF-8 | 877 | 2.53125 | 3 | [] | no_license | require 'rack'
class ConsumerMiddleware
def initialize(app, options = {})
@app = app
end
def call(env)
puts "consumer_password"
# valid = true
# unless env['REQUEST_METHOD'] == 'POST' && env['PATH_INFO'].match(/\/(session|users)/)
# # TODO check consumer
# # get the consumer_key from env['auth_params']
# # (it must be set at this point)
# # lookup user using consumer_key and load into env['user']
# valid = false
# end
# if valid
# status, headers, bodies = @app.call(env)
# else
# status = 403
# headers = {"Content-Type" => "application/json"}
# response = {
# status: "CONSUMER FAILURE",
# message: "Who are you?"
# }
# bodies = [response.to_json]
# end
status, headers, bodies = @app.call(env)
return [status, headers, bodies]
end
end
| true |
d28cb955227bfaa2019cbd7dbc9e37a4451ae523 | Ruby | iarunpaul/Ruby-Object-Relationships | /Classes/cinema.rb | UTF-8 | 254 | 3.359375 | 3 | [] | no_license | class Cinema
attr_accessor :name, :location
def initialize(name, location)
@name = name
@location = location
@movies = []
end
def add_movie(movie)
@movies << movie
movie.cinema = self
end
end
| true |
7dc3213cdb20ef823b743125bf1ddd5599b2898d | Ruby | JohnLoza/black-brocket | /app/models/concerns/searchable.rb | UTF-8 | 1,224 | 2.640625 | 3 | [] | no_license | require 'active_support/concern'
module Searchable
extend ActiveSupport::Concern
class_methods do
# search for key_words in certain fields
# available options, key_words = String, fields = Array and joins = Hash
def search(options={})
# not search anything if there are no key_words or fields to search for
return all unless options[:key_words].present?
raise ArgumentError, "No fields to search were given" unless options[:fields].present?
raise ArgumentError, "fields option must be an Array" unless options[:fields].kind_of? Array
raise ArgumentError, "joins options must be a Hash" if options[:joins].present? and !options[:joins].kind_of? Hash
query = Array.new
options[:key_words] = Utils.format_search_key_words(options[:key_words])
operator = options[:key_words].at(Utils::REGEXP_SPLITTER) ? :REGEXP : :LIKE
options[:fields].each do |field|
query << "#{field} #{operator} :key_words"
end
query = query.join(' OR ')
if options[:joins].present?
joins(options[:joins]).where(query, key_words: options[:key_words])
else
where(query, key_words: options[:key_words])
end
end
end
end
| true |
1535d646c2614db5f4d456457e28323bc6cb092c | Ruby | Dahie/blight-music-video | /lib/image_placement_helpers.rb | UTF-8 | 367 | 2.6875 | 3 | [] | no_license | module ImagePlacementHelpers
def middle_x(image)
x - image.width / 2.0
end
def middle_y(image)
y - image.height / 2.0
end
def left
middle_x(animation.image)
end
def right
left + animation.image.width * x_factor
end
def top
middle_y(animation.image)
end
def bottom
top + animation.image.height * y_factor
end
end
| true |
d97a218098a1418f8b9e53058cda76999f0d1d04 | Ruby | ErikaNana/MyGrades | /app/models/assignment.rb | UTF-8 | 616 | 2.671875 | 3 | [] | no_license | class Assignment < ActiveRecord::Base
attr_accessible :title #list of fields that you want to be accessible
attr_accessible :description
attr_accessible :user_id
attr_accessible :grade
attr_accessible :dueDate
def self.build_from_csv(row, params)
row.compact! #take out nil values, figure out why they were there later
@assignment = Assignment.create!(:title => params[:title], :description => params[:description],
:user_id => row[0], :grade => row[1], :dueDate => params[:dueDate])
#find existing user from UH id or create new
end
end | true |
c9e8bac999fa90f0555604770ada41f7d30f9a16 | Ruby | fanjieqi/LeetCodeRuby | /1301-1400/1359. Count All Valid Pickup and Delivery Options.rb | UTF-8 | 141 | 2.953125 | 3 | [
"MIT"
] | permissive | MOD = 10**9 + 7
# @param {Integer} n
# @return {Integer}
def count_orders(n)
(2..n).inject(1) { |ans, i| ans * (2 * i * i - i) % MOD }
end
| true |
5ebe7d8ab5ccce716cf105100ab8e3221ab1b93e | Ruby | sabtain93/rb_101_small_problems | /medium_2/04.rb | UTF-8 | 2,409 | 4.625 | 5 | [] | no_license | =begin
# Problem:
- Input: a string
- Output: Boolean
- true if all the parentheses in the string argument are properly balanced
i.e. occur in matching () pairs
- return true if there are no parenthesis in the input string
- false if the parentheses in the string are not balanced
# Examples:
balanced?('What (is) this?') == true
- 'What (is) this?'
- Each open parenthesis has a correct close parentheses
balanced?('What is) this?') == false
- 'What is) this?'
- there is a close parenthesis that does not have an open parentheses
balanced?('What (is this?') == false
- 'What (is this?'
- there is an open parenthesis that is never close
balanced?('((What) (is this))?') == true
- '((What) (is this))?'
balanced?('((What)) (is this))?') == false
- '((What)) (is this))?'
^
- there is an extra close parentheses
balanced?('Hey!') == true
- 'Hey!'
- no parenthesis returns a true
balanced?(')Hey!(') == false
- ')Hey!('
- return false if there is the correct number of parenthesis, but incorrect order
balanced?('What ((is))) up(') == false
- 'What ((is))) up('
^ ^
# Algorithm
- Initialize a hash to keep track of parentheses pairs
- Initialize a variable pairs to 0 to keep track of pairs
- Iterate over the characters in the input string
- If the current char is a `(`:
- Increment pairs, and add as a key in the hash with a value of `false`
- If the current char is a `)`:
- Access the value at the key for the current number of `pairs`
- Change the associated value to true
- If the value at the key is `nil`, return false
- Return true if all the values in the hash are true, or if the hash is empty
=end
def balanced?(string)
parentheses_pairs = {}
current_pair = 0
string.each_char do |char|
if char == '('
current_pair += 1
parentheses_pairs[current_pair] = false
elsif char == ')'
return false if parentheses_pairs[current_pair] == nil
parentheses_pairs[current_pair] = true
current_pair -= 1
end
end
parentheses_pairs.values.all? || parentheses_pairs.empty?
end
p balanced?('What (is) this?') == true
p balanced?('What is) this?') == false
p balanced?('What (is this?') == false
p balanced?('((What) (is this))?') == true
p balanced?('((What)) (is this))?') == false
p balanced?('Hey!') == true
p balanced?(')Hey!(') == false
p balanced?('What ((is))) up(') == false
| true |
439bef72a522732ae27421fe68977e07056267c8 | Ruby | 0308199710520/oystercard2 | /lib/oystercard.rb | UTF-8 | 1,204 | 3.375 | 3 | [] | no_license | require_relative "./journey"
class Oystercard
attr_reader :balance, :journey
MAX_BALANCE = 90
MIN_CHARGE = 1
def initialize(balance: 0, journey: Journey.new)
@balance = balance
@journey = journey
end
def top_up(amount)
fail "Can't top up, would take balance over #{MAX_BALANCE}" if max_balance?(amount)
@balance += amount
end
def touch_in(station, zone)
fail "Can't touch in, balance under #{MIN_CHARGE}" if min_balance?
if in_journey?
@journey.charge
@journey.clear_entry
touch_in(station, zone)
else
@journey.entry(station, zone)
end
end
def touch_out(station, zone)
fail "You did not touch in" unless in_journey?
@journey.exit(station, zone)
deduct(@journey.charge)
log_and_clear
end
def max_balance?(amount)
@balance + amount > MAX_BALANCE
end
def min_balance?
@balance < MIN_CHARGE
end
def in_journey?
@journey.entry_station != nil
end
def log_and_clear
@journey.add_journey
@journey.clear_exit
@journey.clear_entry
end
def journey_printer
print(@journey.return_log)
end
private
def deduct(cost)
@balance -= cost
end
end
| true |
eec38c9c0534f0346072f1c8d9dd8802ebb23311 | Ruby | diogoribeiro/sample_app | /spec/models/user_spec.rb | UTF-8 | 5,688 | 2.703125 | 3 | [] | no_license | # == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#
require 'spec_helper'
describe User do
before(:each) do
@attr = {
:name=> "Joao bobo",
:email=> "jaobobo@email.com",
:password=> '123456',
:password_confirmation=> '123456'
}
end
it "should create a new instace given valid attributes" do
User.create!(@attr)
end
it "should require a name" do
no_name_user = User.new(@attr.merge(:name=> ""))
no_name_user.should_not be_valid
end
it "should require a email" do
no_email_user = User.new(@attr.merge(:email=> ""))
no_email_user.should_not be_valid
end
it "sould reject names that is too long" do
long_name= "a" *51
long_name_user= User.new(@attr.merge(:name=> long_name))
long_name_user.should_not be_valid
end
it "should accept valid email" do
adresses= %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jpg]
adresses.each do |adress|
valid_email_user= User.new(@attr.merge(:email=> adress))
valid_email_user.should be_valid
end
end
it "should reject invalid email" do
invalid_adresses= %w[user@foo,com user_at_foo.org example.user@foo.]
invalid_adresses.each do |invalid_adress|
invalid_email_user= User.new(@attr.merge(:email=> invalid_adress))
invalid_email_user.should_not be_valid
end
end
it "should reject duplicate email adress" do
User.create!(@attr)
user_with_duplicate_email= User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
it "should reject email identical up to case" do
upcased_email= @attr[:email].upcase
User.create!(@attr.merge(:email=> upcased_email))
user_with_duplicate_email= User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
describe "password validation" do
it "should require a password" do
user_without_password= User.new(@attr.merge(:password=> '', :password_confirmation=> ''))
user_without_password.should_not be_valid
end
it "should require a matching password confirmation" do
user_with_different_confirmationpassword= User.new(@attr.merge(:password_confirmation=> 'different'))
user_with_different_confirmationpassword.should_not be_valid
end
it "should reject short password" do
short= "a" *5
invalid_attrs= @attr.merge(:password=> short, :password_confirmation=> short)
user_with_short_password= User.new(invalid_attrs)
user_with_short_password.should_not be_valid
end
it "should reject long password" do
long= "a" *41
invalid_attrs= @attr.merge(:password=> long, :password_confirmation=> long)
user_with_long_password= User.new(invalid_attrs)
user_with_long_password.should_not be_valid
end
end
describe "password encryption" do
before(:each) do
@user= User.create!(@attr)
end
it "should have an encrypted password attribute" do
@user.should respond_to(:encrypted_password)
end
it "should set the encrypted password" do
@user.encrypted_password.should_not be_blank
end
describe "has_password? method" do
it "should be true if the passwords match" do
@user.has_password?(@attr[:password]).should be_true
end
it "should be false if the passwords don't match" do
@user.has_password?('invalid').should be_false
end
end
describe "authenticated method" do
it "should return nil on email/password mismatch" do
wrong_password_user= User.authenticate(@attr[:email], 'wrongpass')
wrong_password_user.should be_nil
end
it "should return nil for an email address with no user" do
nonexistent_user= User.authenticate("vish@email.com", @attr[:password])
nonexistent_user.should be_nil
end
it "should return the user on email/password match" do
matching_user= User.authenticate(@attr[:email], @attr[:password])
matching_user.should == @user
end
end
end
describe "admin attribute" do
before(:each) do
@user= User.create!(@attr)
end
it "should respond to admin" do
@user.should respond_to(:admin)
end
it "should not be an admin by default" do
@user.should_not be_admin
end
it "should be convertible to an admin" do
@user.toggle!(:admin)
@user.should be_admin
end
end
describe "microposts associations" do
before(:each) do
@user= User.create!(@attr)
@mp1= Factory(:micropost, :user=> @user, :created_at=> 1.day.ago)
@mp2= Factory(:micropost, :user=> @user, :created_at=> 1.hour.ago)
end
it "should have microposts attribute" do
@user.should respond_to(:microposts)
end
it "should have the right microposts in the right order" do
@user.microposts.should == [@mp2, @mp1]
end
it "should destroy associated microposts" do
@user.destroy
[@mp1, @mp2].each do |micropost|
Micropost.find_by_id(micropost.id).should be_nil
end
end
describe "status feed" do
it "should have a feed" do
@user.should respond_to(:feed)
end
it "should include the user's microposts" do
@user.feed.include?(@mp1).should be_true
@user.feed.include?(@mp2).should be_true
end
it "should not include a different user's micropost" do
mp3 = Factory(:micropost,
:user => Factory(:user, :email => Factory.next(:email)))
@user.feed.include?(mp3).should be_false
end
end
end
end
| true |
dc9d725dbee3dc645f48977943f8e48f46e41ec8 | Ruby | Agatov/happymama | /app/models/groop.rb | UTF-8 | 290 | 2.65625 | 3 | [] | no_license | class Groop < ActiveRecord::Base
belongs_to :workshop
belongs_to :place
validates :workshop_id, presence: true
validates :place_id, presence: true
def seats_available
if total_seats and reserved_seats
total_seats - reserved_seats
else
nil
end
end
end
| true |
08402e7d967b5fa89bd30b13a8ebc2382b03d5b5 | Ruby | dcaba/personal-training | /codewars/pig.rb | UTF-8 | 228 | 3.421875 | 3 | [] | no_license | def pig_it text
words = text.split " "
words.map! do |word|
if word.downcase.gsub(/[^a-z0-9\s]/i, '') == ""
word
else
word[1..word.size] + word[0] + 'ay'
end
end
words.join " "
end
puts pig_it "Test example !"
| true |
0bc9402f7efd7317b7595e9636b75173539dbd96 | Ruby | vinnyalfieri/lectures-and-videos-web-615-public | /search_youtube/youtube.rb | UTF-8 | 332 | 2.609375 | 3 | [] | no_license | require 'open-uri'
require 'nokogiri'
require 'pry'
puts "What would you like to see?"
query = gets.strip
html = open("https://www.youtube.com/results?search_query=#{query}").read
doc = Nokogiri::HTML(html)
href = doc.search("h3.yt-lockup-title a.yt-uix-tile-link").first.attr("href")
system("open https://youtube.com#{href}") | true |
08ebea1856130ed26d9733fcbd42606237d97eb1 | Ruby | Erol/active_model_validations | /spec/active_model_validations/maximum_validator_spec.rb | UTF-8 | 758 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
class MaximumValidatorModel < OpenStruct
include ActiveModel::Validations
validates :value, maximum: { value: 0, message: 'must not be higher than the maximum value' }
end
RSpec.describe MaximumValidator do
it 'allows an equal value' do
model = MaximumValidatorModel.new(value: 0)
expect(model).to be_valid
expect(model.errors).to be_empty
end
it 'allows a lower value' do
model = MaximumValidatorModel.new(value: -1)
expect(model).to be_valid
expect(model.errors).to be_empty
end
it 'fails a higher value' do
model = MaximumValidatorModel.new(value: 1)
expect(model).not_to be_valid
expect(model.errors[:value]).to include 'must not be higher than the maximum value'
end
end
| true |
32ad4e32816fb11bcf56dc80fca0d747a66c8980 | Ruby | timetwister4/nanotwitter | /client_lib/clientlib_test.rb | UTF-8 | 3,481 | 2.6875 | 3 | [
"MIT"
] | permissive | require_relative '../test/test_helper.rb'
require 'byebug'
require_relative '../models/user.rb'
require_relative '../models/tweet.rb'
require_relative '../clientlib.rb'
tweet_id1, tweet_id2 = 0
include Rack::Test::Methods
#if env == "test"
# puts "starting in test mode"
# User.destroy_all
# Tweet.destroy_all
# user1 = User.create(user_name: "TestUser1", email: "test1@test.com")
# user2 = User.create(user_name: "TestUser2", email: "test2@test.com")
# user3 = User.create(user_name: "TestUser3", email: "test3@test.com")
# tweet1 = Tweet.create(author_name: user1.user_name, author_id: user1.id, text: "Original Tweet")
# tweet_id1 = tweet1.id
# tweet2 = Tweet.create(author_name: user2.user_name, author_id: user2.id, reply_id: tweet1.id, text: "Reply Tweet")
# tweet_id2 = tweet2.id
# User 1 follows user 2
# User 2 likes tweet 1
#end
describe "client" do
def app
Sinatra::Application
end
before do
User.destroy_all
Tweet.destroy_all
user1 = User.create(user_name: "TestUser1", email: "test1@test.com", name: "John", password: "pass")
user2 = User.create(user_name: "TestUser2", email: "test2@test.com", name: "Jane", password: "pass")
user3 = User.create(user_name: "TestUser3", email: "test3@test.com", name: "Jim", password: "pass")
tweet1 = Tweet.create(author_name: user1.user_name, author_id: user1.id, text: "Original Tweet")
tweet_id1 = tweet1.id
tweet2 = Tweet.create(author_name: user2.user_name, author_id: user2.id, reply_id: tweet1.id, text: "Reply Tweet")
tweet_id2 = tweet2.id
end
it "should get a user" do
user = get_username("TestUser1")
assert user["user_name"] == "TestUser1"
assert user["email"] == "test1@test.com"
end
it "should return nil for a user not found" do
assert User.find_by_name("TestUser0") == nil
end
it "should get a tweet" do
tweet = get_tweet(tweet_id1)
assert tweet["author_name"] == "TestUser1"
assert tweet["text"] == "Original Tweet"
end
#it returns an empty array, I think that's good enough
#it "should return nil for a tweet not found" do
#get_tweet(0).should be_nil
#assert_raises(Exception) {get_tweet(0)}
#end
#again, see above
#it "should return nil for no tweets" do
#get_user_tweets("TestUser3").should be_nil
# assert get_user_tweets("TestUser3") == nil
#end
#temporarily removed test because it depends on Redis to get replies
#I'm not sure how this should respond...
#it "should get replies" do
# tweet = get_replies(tweet_id1)
# tweet["author_id"].should == "TestUser2"
# tweet["text"].should == "Reply Tweet"
#end
#it "should return nil for no replies" do
#get_replies(tweet_id2).should be_nil
# assert get_replies(tweet_id2) == nil
#end
it "should get a user's tweets" do
tweet = get_user_tweets("TestUser1")
assert tweet[0]["author_name"] == "TestUser1"
tweet[0]["text"] == "Original Tweet"
end
#it "should get a user's home feed" do
#end
#it "should return nil for [failed home feed test?]" do
#end
#it "should get a user's followings" do
#end
#it "should return nil for no follows" do
#end
#it "should get a tweet's likes" do
#end
#it "should return nil for [failed tweet likes test?]" do
#end
end
#get_user_tweets(user_name)
#get_user_home_feed(user_name)
#get_user_followings(user_name)
#get_tweet_likes(user_name)
| true |
246d4104828909860ba6e72bfc644e7f2fb77c57 | Ruby | mberrueta/statistic_calcs | /lib/statistic_calcs/distributions/base.rb | UTF-8 | 1,711 | 2.828125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'statistic_calcs/helpers/alias_attributes'
require 'gsl'
require 'pry'
module StatisticCalcs
module Distributions
class Base
include StatisticCalcs::Helpers::AliasAttributes
attr_accessor :mean, :variance, :standard_deviation, :median,
:skewness, :kurtosis, :coefficient_variation,
:cumulative_less_than_x_probability, :cumulative_greater_than_x_probability
attr_alias :f_x, :cumulative_less_than_x_probability
attr_alias :g_x, :cumulative_greater_than_x_probability
attr_alias :mu, :mean
attr_alias :sigma, :variance
attr_alias :sd, :standard_deviation
attr_alias :cv, :coefficient_variation
def calc!
self.variance ||= standard_deviation**2 if standard_deviation
self.standard_deviation ||= Math.sqrt(variance) if variance&.positive?
self.coefficient_variation = variance || 0 / mean if mean&.positive?
round_all!
self
end
private
# The probability density function end with the suffix _pdf
def gsl_ran
GSL::Ran
end
# The cumulative functions P(x) and Q(x) ends with the suffix _P and _Q respectively.
# The inverse cumulative functions P^{-1}(x) and Q^{-1}(x) ends with the suffix _Pinv and _Qinv respectively.
def gsl_cdf
GSL::Cdf
end
def type
discrete? ? :discrete : :continuous
end
def round_all!
instance_variables.each do |key|
value = instance_variable_get(key)
instance_variable_set(key, value.round(StatisticCalcs::DECIMALS)) if value.is_a?(Float)
end
end
end
end
end
| true |
0324ed529200b73ba3705b2f49896f1e5de733f8 | Ruby | RutarAndriy/Ruby_Learning | /Lesson_15/Libraries.rb | UTF-8 | 657 | 3.203125 | 3 | [
"MIT"
] | permissive | # Підкючення бібліотеки <io-console>
require "io/console"
puts "Використання бібліотеки \"io-console\""
puts "\n"
puts "Незахищене поле ввделення тексту"
text_1 = STDIN.gets.chomp
puts "\n"
puts "Захищене поле ввделення тексту"
# Використання бібліотеки для приховування введеного тексту
text_2 = STDIN.noecho(&:gets).chomp
puts "\n"
# Виведення результату
puts "Текст із першого поля: \"#{text_1}\""
puts "Текст із другого поля: \"#{text_2}\"" | true |
32a5df0906b3d9e313d938a7569302eed1755537 | Ruby | vikram7/connect_four_v2 | /play_connect_four.rb | UTF-8 | 424 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env ruby
require './game.rb'
require './board.rb'
require './player.rb'
# gameplay:
game = Game.new
board = Board.new(game)
player1 = game.set_player_type(1, "o")
player2 = game.set_player_type(2, "x")
game.setup_turn_queue(player1, player2, board)
while board.check_for_winner == false
board.display_board
game.active_player.take_turn(board)
board.advance_turn_counter
game.reverse_turn_queue
end
| true |
f6c776b585ac5c97f0ddddb7baae6aaf6e9b6dad | Ruby | CodingDojoDallas/ruby_dec_16 | /Woodall_Robert/assignments/ruby_fundamentals/basic13.rb | UTF-8 | 1,385 | 4.3125 | 4 | [] | no_license | # print 1-255
# (1..255).each { |i| puts i }
# print odds 1-255
# (1..255).each { |i| puts i if i % 2 != 0}
# print sum
#sum = 0
#(1..255).each { |i| puts "New number: #{i}, Sum: #{sum += i}" }
# following won't work for some reason
# (1..255).inject(0) { |sum, i| puts "New number: #{i}, Sum: #{sum + i}" }
# iterate through array
#[1,3,5,7,9,11,13].each { |i| puts "#{i}" }
# find max
#myArr = [-3,-5,-7].sort
#puts myArr[-1]
#
#myArr = [10,8,6,4,2,0].sort
#puts myArr[-1]
# get average
#myArr = [2,10,3]
#puts "Avg of #{myArr} is #{myArr.inject(0) { |sum, i| sum + i } / myArr.count}"
# create odd numbered array
#puts "y values -> #{(1..255).to_a.delete_if { |i| i % 2 == 0 }}"
# greater than y
#y = 3
#myArr = [1,3,5,7].delete_if { |i| i <= y }
#puts "Number of values in #{[1,3,5,7]} greater than #{y} -> #{myArr.count}"
# square the values
#puts "Squared values in #{[1,5,10,-2]} -> #{[1,5,10,-2].map {|i| i * i}}"
# replace negatives
#puts "Replaced negatives in #{[1,5,10,-2]} -> #{[1,5,10,-2].map { |i| i < 0 ? 0 : i }}"
# max, min, and average
#myArr = [1,5,10,-2].sort
#puts "Min #{myArr[0]}, Max #{myArr[-1]}, Avg #{myArr.inject(0) { |sum, i| sum + i }}"
# shift values
#myArr = [1,5,10,7,-2]
#myArr.shift
#puts "Shifted array -> #{myArr.push(0)}"
# replace negatives
puts "Replaced negatives in #{[1,5,10,-2]} -> #{[1,5,10,-2].map { |i| i < 0 ? "Dojo" : i }}" | true |
99ab429b78ad1119b8dd826aa3852cbe20866ef3 | Ruby | Hostile359/MarginalValera | /lib/saver.rb | UTF-8 | 693 | 3.328125 | 3 | [] | no_license | require 'json'
class Saver
def self.read_stats(filename)
file = File.read(filename)
JSON.parse(file)
end
def self.save_stats(stats, filename)
file = File.open(filename, 'w')
file.write(JSON.dump(stats))
file.close
end
def self.saver(stats, choice)
filename = ''
loop do
puts('Введите имя пользователя')
filename = "./resources/#{$stdin.gets.strip}.json"
break unless !File.file?(filename) && (choice == 9)
puts('Такого пользователя не существует')
end
if choice == 9
read_stats(filename)
else
save_stats(stats, filename)
stats
end
end
end
| true |
25b5def53193fb7fc9395409416c70e495634da5 | Ruby | rennex/hellbender | /irc.rb | UTF-8 | 4,260 | 2.734375 | 3 | [] | no_license |
require "socket"
require "yaml"
require "logger"
require_relative "loggerformatter"
require_relative "util"
require_relative "message"
module Hellbender
class IRC
include UtilMethods
attr_reader :config, :log, :connected
def initialize(config = {})
@config = config
@connected = false
@sock = nil
@sock_mutex = Mutex.new # for writing to the socket
@log = Logger.new(STDOUT)
@log.formatter = LoggerFormatter.new
end
def connect
path = config["path"]
if path
log.info "Connecting to unix socket #{path}"
@sock = Socket.unix(path)
else
log.info "Connecting to server (TCP) #{config["host"]}:#{config["port"]}"
@sock = Socket.tcp(config["host"], config["port"], config["bindhost"],
connect_timeout: (config["timeout"] || 10))
end
if config["tls"]
log.info "Connected, establishing TLS encryption"
require "openssl"
ctx = OpenSSL::SSL::SSLContext.new
unless config["tls_verify_peer"] == false
ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
end
sslsock = OpenSSL::SSL::SSLSocket.new(@sock, ctx)
sslsock.sync_close = true
sslsock.connect
@sock = sslsock
end
log.info "Connection established"
pass = config["pass"]
if pass
log.debug ">>\e[0;1m\"PASS <redacted>\""
sendraw "PASS #{pass}", no_log: true
end
sendraw "NICK #{config['nick']}"
sendraw "USER #{config['username']} #{config['bindhost'] || 'localhost'} " +
"#{config['host'] || '*'} :#{config['realname']}"
rescue Errno::ECONNREFUSED, Errno::EALREADY
# Socket.tcp with a connect timeout seems to raise EALREADY
# if the server refused the connection
log.error "Connection refused"
return false
rescue Errno::ETIMEDOUT
log.error "Connection timed out"
return false
end
def run(&block)
loop do
if connect()
until @sock.eof?
line = @sock.gets || break
guess_encoding(line)
m = IRC.parse_msg(line, self)
if m
log_msg(m, line)
process_msg(m, &block)
else
log.error "Malformed message: #{line.inspect}" unless line.strip.empty?
end
end
log.warn "Lost connection to server"
@connected = false
end
break unless config["reconnect"]
sleep 2
end
end
def log_msg(m, line)
case m.command
when "375", "372", "376", "PING"
# don't log the MOTD or PINGs
when /^[45]\d\d$/
# log error replies (400 to 599) at error level
log.error "<<#{line.chomp}"
else
log.debug "<<#{line.chomp}"
end
end
# handle an incoming server message
def process_msg(m)
case m.command
when "001"
log.info "Login to server was successful"
@connected = true
when "PING"
sendraw "PONG #{m.params.first}", no_log: true
end
yield m
end
# parse messages received from the server
def IRC.parse_msg(line, irc)
line.match(/\A(:([^ ]+) )?([^ ]+)/) do |md|
prefix = md[2].freeze
command = md[3].upcase.freeze
rest = md.post_match.chomp
# the last parameter can have spaces by starting with a colon
rest_md = rest.match(/ :/)
params = if rest_md
rest_md.pre_match.split << rest_md.post_match
else
rest.split
end
params.each(&:freeze)
params.freeze
return Message.new(prefix, command, params, irc)
end
end
# send a raw command to the server (only the first line of text,
# up to 510 characters)
def sendraw(msg, no_log: false)
if msg =~ /\A([^\r\n]+)/
# the real limit is 512 bytes including the trailing CRLF.
# Let's not deal with message splitting here.
line = $1[0,510]
log.debug ">>\e[0;1m#{line.inspect}" unless no_log
# thread-safe sending!
@sock_mutex.synchronize do
@sock.write "#{line}\r\n"
end
end
end
end
end
| true |
0e58c6f8c434506a14046597c6bb3a6001d572f5 | Ruby | cha63506/bus-scheme | /lib/eval.rb | UTF-8 | 908 | 2.84375 | 3 | [] | no_license | module BusScheme
class << self
# Parse a string, then eval the result
def eval_string(string)
eval(parse("(begin #{string})"))
end
# Eval a form passed in as an array
def eval(form)
# puts "evaling #{form.inspect}"
if (form.is_a?(Cons) or form.is_a?(Array)) and form.first
apply(form.first, form.rest)
elsif form.is_a? Sym or form.is_a? Symbol
form = form.sym if form.is_a? Symbol
raise EvalError.new("Undefined symbol: #{form.inspect}") unless Lambda.in_scope?(form)
Lambda[form]
else # well it must be a literal then
form
end
end
# Call a function with given args
def apply(function, args)
# puts "applying #{function.inspect} with #{args.inspect}"
args = args.to_a
args.map!{ |arg| eval(arg) } unless function.special_form?
eval(function).call(*args)
end
end
end
| true |
228b91be40dc0d5f48130e399e2fa966f6a96cb1 | Ruby | airservice/grape-apiary | /lib/grape-apiary/route.rb | UTF-8 | 1,303 | 2.546875 | 3 | [
"MIT"
] | permissive | module GrapeApiary
class Route < SimpleDelegator
# would like to rely on SimpleDelegator but Grape::Route uses
# method_missing for these methods :'(
delegate :route_namespace, :route_path, :route_method, to: '__getobj__'
def route_params
@route_params ||= begin
__getobj__.route_params.stringify_keys.sort.map do |param|
Parameter.new(self, *param)
end
end
end
def route_name
route_namespace.split('/').last ||
route_path.match('\/(\w*?)[\.\/\(]').captures.first
end
def route_description
"#{__getobj__.route_description} [#{route_method.upcase}]"
end
def route_path_without_format
route_path.gsub(/\((.*?)\)/, '')
end
def route_model
route_namespace.split('/').last.singularize
end
def route_type
list? ? 'collection' : 'single'
end
def request_description
"+ Request #{'(application/json)' if request_body?}"
end
def response_description
code = route_method == 'POST' ? 201 : 200
"+ Response #{code} (application/json)"
end
def list?
%w(GET POST).include?(route_method) && !route_path.include?(':id')
end
private
def request_body?
!%w(GET DELETE).include?(route_method)
end
end
end
| true |
ce97ece08f067837c3769443d77f3d39e8a78a3b | Ruby | fieldstyler/war_or_peace | /test/player_test.rb | UTF-8 | 876 | 3.125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/card'
require './lib/deck'
require './lib/player'
class PlayerTest < Minitest::Test
def setup
@card1 = Card.new(:diamond, 'Queen', 12)
@card2 = Card.new(:spade, 'Ace', 14)
@card3 = Card.new(:heart, '3', 3)
@cards = [@card1, @card2, @card3]
@cards2 = []
@deck = Deck.new(@cards)
@deck2 = Deck.new(@cards2)
@player1 = Player.new('Clarisa', @deck)
end
def test_it_exists
assert_instance_of Player, @player1
end
def test_player_has_a_name
assert_equal 'Clarisa', @player1.name
end
def test_player_has_a_deck
assert_equal @deck, @player1.deck
end
def test_that_player_has_lost
player2 = Player.new('Harry', @deck2)
# require "pry"; binding.pry
assert_equal false, @player1.has_lost?
assert_equal true, player2.has_lost?
end
end
| true |
2a3838b0a9a71aba89ebbf36cab0763e1c76778d | Ruby | yogodoshi/slackbot-therock | /app/services/slack_api.rb | UTF-8 | 427 | 2.515625 | 3 | [] | no_license | class SlackAPI
def initialize
@channel_id ||= ENV['SLACK_CHANNEL_ID']
@client ||= Slack::Web::Client.new
end
def usernames_list
usernames_list = []
channel_users_ids.each do |user_id|
usernames_list << "@#{@client.users_info(user: user_id)['user']['name']}"
end
usernames_list
end
def channel_users_ids
@client.channels_info(channel: @channel_id)['channel']['members']
end
end
| true |
182a16781e787329a66839de09f97b5945cb5070 | Ruby | jonny-gates/react-udemy-exercises | /workshops/conditional-flow/voting_age.rb | UTF-8 | 140 | 3.609375 | 4 | [] | no_license | puts "What's your age?"
age = gets.chomp.to_i
if age >= 18
# code to be executed
puts "You can vote!"
else
puts "You can't vote"
end
| true |
3aa56fab1685d7b03e1f6fdbe8a94f95aeed24db | Ruby | csipsz/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-atl01-seng-ft-051120 | /nyc_pigeon_organizer.rb | UTF-8 | 458 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
pigeon_list = {}
data.each do |color_gender_lives, info|
info.each do |info, list|
list.each do |bird|
if pigeon_list[bird] == nil
pigeon_list[bird] = {}
end
if pigeon_list[bird][color_gender_lives] == nil
pigeon_list[bird][color_gender_lives] = []
end
pigeon_list[bird][color_gender_lives].push(info.to_s)
end
end
end
pigeon_list
end | true |
a269b7a2e904186e8b142ac87c210ed06fde3770 | Ruby | bergenrb/RubyNuby | /archaic/videre-med-ruby-kurs/code/traad_mutex1.rb | ISO-8859-15 | 682 | 3.375 | 3 | [] | no_license | ## <CODE>
require 'thread'
$delt_teller = 0
$mutex = Mutex.new
# Lag ti trder som ker den delte telleren
# gradvis tjuefem ganger.
traader = (1..10).collect do
Thread.new do
25.times do |i|
$mutex.synchronize do ### Synkronisert
gammel_verdi = $delt_teller # kodebit.
ny_verdi = gammel_verdi + 1 #
sleep 0 # Framtvinge trdproblematikk #
$delt_teller = ny_verdi #
end ###
end
end
end
# Vent p alle trdene fr vi skriver ut den endelige verdien.
traader.each{|t| t.join}
puts $delt_teller # Skal skrive ut "250"
##</CODE>
| true |
384e691239c0d2387d82c6336c7c6dd3813fe518 | Ruby | amitrathore/hbase-migrations | /lib/hbase_migrations/hbase_commands.rb | UTF-8 | 8,207 | 2.71875 | 3 | [] | no_license | =begin
HBASE SURGERY TOOLS:
close_region Close a single region. Optionally specify regionserver.
Examples:
hbase> close_region 'REGIONNAME'
hbase> close_region 'REGIONNAME', 'REGIONSERVER_IP:PORT'
compact Compact all regions in passed table or pass a region row
to compact an individual region
disable_region Disable a single region
enable_region Enable a single region. For example:
hbase> enable_region 'REGIONNAME'
flush Flush all regions in passed table or pass a region row to
flush an individual region. For example:
hbase> flush 'TABLENAME'
hbase> flush 'REGIONNAME'
major_compact Run major compaction on passed table or pass a region row
to major compact an individual region
split Split table or pass a region row to split individual region
Above commands are for 'experts'-only as misuse can damage an install
=end
=begin
HBASE SHELL COMMANDS:
alter Alter column family schema; pass table name and a dictionary
specifying new column family schema. Dictionaries are described
below in the GENERAL NOTES section. Dictionary must include name
of column family to alter. For example,
To change or add the 'f1' column family in table 't1' from defaults
to instead keep a maximum of 5 cell VERSIONS, do:
hbase> alter 't1', {NAME => 'f1', VERSIONS => 5}
To delete the 'f1' column family in table 't1', do:
hbase> alter 't1', {NAME => 'f1', METHOD => 'delete'}
count Count the number of rows in a table. This operation may take a LONG
time (Run '$HADOOP_HOME/bin/hadoop jar hbase.jar rowcount' to run a
counting mapreduce job). Current count is shown every 1000 rows by
default. Count interval may be optionally specified. Examples:
hbase> count 't1'
hbase> count 't1', 100000
create Create table; pass table name, a dictionary of specifications per
column family, and optionally a dictionary of table configuration.
Dictionaries are described below in the GENERAL NOTES section.
Examples:
hbase> create 't1', {NAME => 'f1', VERSIONS => 5}
hbase> create 't1', {NAME => 'f1'}, {NAME => 'f2'}, {NAME => 'f3'}
hbase> # The above in shorthand would be the following:
hbase> create 't1', 'f1', 'f2', 'f3'
hbase> create 't1', {NAME => 'f1', VERSIONS => 1, TTL => 2592000, \\
BLOCKCACHE => true}
describe Describe the named table: e.g. "hbase> describe 't1'"
delete Put a delete cell value at specified table/row/column and optionally
timestamp coordinates. Deletes must match the deleted cell's
coordinates exactly. When scanning, a delete cell suppresses older
versions. Takes arguments like the 'put' command described below
deleteall Delete all cells in a given row; pass a table name, row, and optionally
a column and timestamp
disable Disable the named table: e.g. "hbase> disable 't1'"
drop Drop the named table. Table must first be disabled
enable Enable the named table
exists Does the named table exist? e.g. "hbase> exists 't1'"
exit Type "hbase> exit" to leave the HBase Shell
get Get row or cell contents; pass table name, row, and optionally
a dictionary of column(s), timestamp and versions. Examples:
hbase> get 't1', 'r1'
hbase> get 't1', 'r1', {COLUMN => 'c1'}
hbase> get 't1', 'r1', {COLUMN => ['c1', 'c2', 'c3']}
hbase> get 't1', 'r1', {COLUMN => 'c1', TIMESTAMP => ts1}
hbase> get 't1', 'r1', {COLUMN => 'c1', TIMESTAMP => ts1, \\
VERSIONS => 4}
list List all tables in hbase
put Put a cell 'value' at specified table/row/column and optionally
timestamp coordinates. To put a cell value into table 't1' at
row 'r1' under column 'c1' marked with the time 'ts1', do:
hbase> put 't1', 'r1', 'c1', 'value', ts1
tools Listing of hbase surgery tools
scan Scan a table; pass table name and optionally a dictionary of scanner
specifications. Scanner specifications may include one or more of
the following: LIMIT, STARTROW, STOPROW, TIMESTAMP, or COLUMNS. If
no columns are specified, all columns will be scanned. To scan all
members of a column family, leave the qualifier empty as in
'col_family:'. Examples:
hbase> scan '.META.'
hbase> scan '.META.', {COLUMNS => 'info:regioninfo'}
hbase> scan 't1', {COLUMNS => ['c1', 'c2'], LIMIT => 10, \\
STARTROW => 'xyz'}
truncate Disables, drops and recreates the specified table.
version Output this HBase version
GENERAL NOTES:
Quote all names in the hbase shell such as table and column names. Don't
forget commas delimit command parameters. Type <RETURN> after entering a
command to run it. Dictionaries of configuration used in the creation and
alteration of tables are ruby Hashes. They look like this:
{'key1' => 'value1', 'key2' => 'value2', ...}
They are opened and closed with curley-braces. Key/values are delimited by
the '=>' character combination. Usually keys are predefined constants such as
NAME, VERSIONS, COMPRESSION, etc. Constants do not need to be quoted. Type
'Object.constants' to see a (messy) list of all constants in the environment.
This HBase shell is the JRuby IRB with the above HBase-specific commands added.
For more on the HBase Shell, see http://wiki.apache.org/hadoop/Hbase/Shell
=end
module HbaseCommands
# DDL
def admin()
@admin = HbaseAdmin.new(server) unless @admin
@admin
end
def table(table)
HbaseTable.new(@configuration, table_name(table))
end
def create(table, *args)
puts "Creating: #{table}"
admin().create(table_name(table.to_s), args)
end
def drop(table)
admin().drop(table_name(table))
end
def alter(table, args)
admin().alter(table_name(table), args)
end
# Administration
def list
admin().list()
end
def describe(table)
admin().describe(table_name(table))
end
def enable(table)
admin().enable(table_name(table))
end
def disable(table)
admin().disable(table_name(table))
end
def enable_region(regionName)
admin().enable_region(regionName)
end
def disable_region(regionName)
admin().disable_region(regionName)
end
def exists(table)
admin().exists(table_name(table))
end
def truncate(table)
admin().truncate(table_name(table))
end
def close_region(regionName, server = nil)
admin().close_region(regionName, server)
end
# CRUD
def get(table, row, args = {})
table(table_name(table)).get(row, args)
end
def put(table, row, column, value, timestamp = nil)
table(table_name(table)).put(row, column, value, timestamp)
end
def scan(table, args = {})
table(table_name(table)).scan(args)
end
def delete(table, row, column,
timestamp = org.apache.hadoop.hbase.HConstants::LATEST_TIMESTAMP)
table(table_name(table)).delete(row, column, timestamp)
end
def deleteall(table, row, column = nil,
timestamp = org.apache.hadoop.hbase.HConstants::LATEST_TIMESTAMP)
table(table_name(table)).deleteall(row, column, timestamp)
end
def count(table, interval = 1000)
table(table_name(table)).count(interval)
end
def flush(tableNameOrRegionName)
admin().flush(table_name(tableNameOrRegionName))
end
def compact(tableNameOrRegionName)
admin().compact(table_name(tableNameOrRegionName))
end
def major_compact(tableNameOrRegionName)
admin().major_compact(table_name(tableNameOrRegionName))
end
def split(tableNameOrRegionName)
admin().split(table_name(tableNameOrRegionName))
end
def table_name(table)
"#{user}_#{env}_#{table}"
end
end
| true |
45acca659cda3a419ef094037e48f88e1897599c | Ruby | avioli/opal | /corelib/error.rb | UTF-8 | 688 | 2.65625 | 3 | [
"MIT"
] | permissive | class Exception
def initialize(message = '')
`Error.captureStackTrace(self, self.m$raise);`
@message = message
end
def ==(*)
raise NotImplementedError, 'Exception#== not yet implemented'
end
def backtrace
@backtrace ||= `VM.backtrace(self)`
end
def awesome_backtrace
@backtrace ||= `VM.awesome_backtrace(self)`
end
def exception(*)
raise NotImplementedError, 'Exception#exception not yet implemented'
end
def inspect
"#<#{self.class}: '#{message}'>"
end
def message
@message
end
def set_backtrace(*)
raise NotImplementedError, 'Exception#set_backtrace not yet implemented'
end
alias_method :to_s, :message
end
| true |
d8d6ca08ccae82cf6759ead9de56e72eb7e890d8 | Ruby | Videmor/FundamentosRuby | /clase3/log/_ejem1.rb | UTF-8 | 149 | 3.4375 | 3 | [] | no_license | def bienvenido(nombre)
"Bienvenido #{nombre}"
end
puts 'Cual es tu nombre?'
captura = gets.chomp
resultado = bienvenido(captura)
puts resultado
| true |
9d584dee37f684303bfb748ec47d11be4e3bc78c | Ruby | CaptainSpectacular/pos_web_app | /app/presenters/card_presenter.rb | UTF-8 | 195 | 2.578125 | 3 | [] | no_license | class CardPresenter
def initialize(card)
@card = card
end
def name
@card.name
end
def image
@image ||= @card.image
end
def price
@price ||= @card.price
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.