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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
eedee8cf8f4fa166ac3d9a3166df723fdd0dd37e | Ruby | raptowitz/Mastermind | /board.rb | UTF-8 | 578 | 3.4375 | 3 | [] | no_license | # frozen_String_literal: true
# display board
class Board
include Colors
def initialize
@board = Array.new(12) { Array.new(4, blank) }
end
def print_board
@board.each do |row|
puts row.join
end
end
def color_move
@guess.map { |guess| color(guess) }
end
def place_move(guess, re... | true |
a936720a0f9ee6ccba3148509e70edae0f2d83b5 | Ruby | tganzarolli/offlook | /lib/google_calendar_wrapper.rb | UTF-8 | 3,277 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'google_calendar'
require 'timezone_parser'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
#monkey patch
module Google
class Event
def local_timezone_json
tz = Time.now.zone
tz_name = TimezoneParser::getTimezones(tz).last
",\"timeZone\" : \"#{tz_name}\""
end
end
end
class... | true |
720eda48a610f2bd96d2c36203c69c956438bc73 | Ruby | torubylist/ruby_learning | /alg/reverse.rb | UTF-8 | 253 | 3.5 | 4 | [] | no_license | def reverse_str(str)
n = str.size
head = 0
tail = n -1
while ( head < tail ) do
t = str[head]
str[head] = str[tail]
str[tail] = t
head += 1
tail -= 1
end
str
end
puts reverse_str('abcd')
puts reverse_str('adef')
| true |
43f98630ed35fbd25cc4cabfabd5055baa9a3c1d | Ruby | CRBairdUSA/musicbrainz-ruby | /spec/musicbrainz/client_spec.rb | UTF-8 | 2,523 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe MusicBrainz::Client do
let(:client){ MusicBrainz::Client.new }
subject { client }
it 'provides access to the core resources' do
resources = [:artist, :label, :recording, :release, :release_group, :work]
should respond_to(*resources).with(1).argument
end
it 'provides a... | true |
1ac47c6a676819a5b331bd8cfbb3aa6888467cd9 | Ruby | deepgpatel/square_array-prework | /square_array.rb | UTF-8 | 108 | 3.484375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
array_squared = []
array.each {|x| array_squared << x ** 2}
array_squared
end
| true |
8318fa6ad7c004202ea86a146b9125764ef450ca | Ruby | kpeck71/activerecord-validations-lab-v-000 | /app/models/post.rb | UTF-8 | 486 | 2.84375 | 3 | [] | no_license | class Post < ActiveRecord::Base
validates :title, presence: true
validates :content, length: { minimum: 250 }
validates :summary, length: { maximum: 250 }
validates :category, inclusion: { in: %w(Fiction NonFiction) }
validates :title_valid, acceptance: true
def title_valid
clickbait = ["Won't Believe"... | true |
d5b0eccf3713819cc50523182a38c73b85761ab8 | Ruby | doodzik/enumerator_concurrent | /test/test_enumerator_concurrent_queued.rb | UTF-8 | 701 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'minitest/autorun'
require 'enumerator_concurrent/queued'
# Test for EnumeratorQueued
class EnumeratorConcurrentQueuedTest < Minitest::Test
def test_map_workers
cq = EnumeratorConcurrent::Queued.new [1, 2, 3, 4], 2
assert_equal([2, 4, 6, 8], cq.map { |x| x * 2 })
end
def test_each_workers
cq... | true |
e1c562aa6f91f8ee567e752d9955290cf19143e7 | Ruby | CodeZeus-dev/oyster-card | /spec/journey_spec.rb | UTF-8 | 1,582 | 3.15625 | 3 | [] | no_license | require 'journey'
describe Journey do
let(:station) { Station.new("Aldgate East", 1)}
it "creates an instance of Journey" do
expect(subject).to be_instance_of(described_class)
end
describe "#initialize" do
it "creates an empty_station instance variable upon initialisation" do
expect(subject.ent... | true |
8d39d2338d487b51c52eb1150d58da7756b2729f | Ruby | trustarun/robotic | /simulate_robot.rb | UTF-8 | 1,478 | 3.625 | 4 | [] | no_license | require_relative 'robot.rb'
VALID_INPUT = ["place", "move", "left", "right", "report", "stop"]
VALID_DIRECTION = ["north", "south", "east", "west"]
def simulate_robot(robot)
input = gets().chomp
arg = input.split(/[\s,]+/)
begin
if VALID_INPUT.include?(arg[0].downcase)
while arg[0].to_s != "stop"
... | true |
ce85acf11cbdd1f2b9e61e42c762d267d90d086a | Ruby | thib123/TPJ | /Notes/Ruby/sample_code/ex1422.rb | UTF-8 | 225 | 2.765625 | 3 | [
"MIT"
] | permissive | # Sample code from Programing Ruby, page 642
require 'csv'
CSV::Writer.generate(STDOUT, '|') do |csv|
csv << [ 1, "line 1", 27 ]
csv << [ 2, nil, 123 ]
csv << [ 3, "|bar|", 32.5]
end
| true |
c4c82adb4c1c8f2af3715c3be6080d657c78ed79 | Ruby | mze3e/udemy | /scraper.rb | UTF-8 | 2,703 | 2.625 | 3 | [] | no_license | require 'scraperwiki'
@SOURCE = 'Udemy'
@URL = "http://www.udemy.com"
@ID = 0
#p html
require 'nokogiri'
require 'open-uri'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
MAPPING = [
[1, /Arts and Photography/i],
[3, /Business/i],
[1, /Crafts and Hobbies/i],
[1, /Design/i],
[9, /E... | true |
17b8b264365c0acf9565f852c4689a24f99adb0f | Ruby | joshbeglan/programming-univbasics-nds-nds-to-insight-with-methods-dc-web-030920 | /lib/nds_extract.rb | UTF-8 | 850 | 3.328125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | $LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
# Find a way to accumulate the :worldwide_grosses and return that Integer
# using director_data as input
def gross_for_director(director_data)
total = 0
i = 0
while i < director_data.length
movies = director_data[:movies]
j = 0
... | true |
0fac2dca64da9948b8acf777f9dbaa2569d89d94 | Ruby | kamilsymanski/falcon | /lib/filters/kelvin.rb | UTF-8 | 749 | 2.875 | 3 | [] | no_license | require_relative 'base'
module Filters
# Named after Lord Kelvin, this effect applies a strong peach/orange overlay, and adds a washed out photo frame.
#
class Kelvin < Base
# In English: create a working file, load the image into memory, normalize, enhance brightness by a fifth,
# desaturate by half, ... | true |
e2823d6e822de156dda55d27520aaf5bc59879e1 | Ruby | zuntopia/ruby_study | /callback.rb | UTF-8 | 182 | 2.96875 | 3 | [] | no_license | p 1.class
p 1.object_id
p 1.methods
a, b = "str", "str"
p a.object_id
p b.object_id
p a == b
p a.equal? b
foo = "UpPer CasE"
p foo
p foo.downcase
p foo
p foo.downcase!
p foo | true |
ab09b95719e7442ed948ccda6e19f03e16db2ade | Ruby | victorlin-houzz/prime_multi_table | /spec/prime_multi_table_spec.rb | UTF-8 | 880 | 3.328125 | 3 | [] | no_license | require "prime_multi_table"
require 'prime'
describe "prime multiplication table functions" do
describe "#is_prime?" do
it "checks if a number is a prime" do
# expect(is_prime?(-1)).to be_falsey
# expect(is_prime?(0)).to be_falsey
# expect(is_prime?(1)).to be_falsey
# expect(is_prime?(2)... | true |
e49c440df05bc0e93d2e31c36be690ba2fc2df88 | Ruby | hiroponz/neo4r | /lib/neo4r/relation.rb | UTF-8 | 3,000 | 2.828125 | 3 | [
"MIT"
] | permissive | require "neo4r/will_paginate"
require "neo4r/rest_wrapper"
module Neo4r
# Neo4r relation class
class Relation
include Enumerable
include ::Neo4r::WillPaginate
alias_method :all, :to_a
alias_method :size, :count
def initialize(klass)
@klass = klass
@labels = klass.name.split("::")
... | true |
6cc5465459226135d221469461a27955bc4d5c27 | Ruby | spgiovanni/AppAcademy | /giovanni_spikes_recursion_excercises.rb | UTF-8 | 2,374 | 4.15625 | 4 | [] | no_license | require "byebug"
def range(start_num, end_num)
return [] if end_num < start_num || start_num == end_num
arr = [start_num]
return arr if start_num == end_num - 1
arr + range(start_num + 1, end_num)
end
def range_iterative(start_num, end_num)
arr = []
(start_num...end_num).each do |i|
... | true |
872d4a270414fc1fa6bb969b8ce3c6e545b0593a | Ruby | Daleon/Complete-Me | /test/complete_me_test.rb | UTF-8 | 2,569 | 3 | 3 | [] | no_license | gem 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/complete_me'
class CompleteMeTest < Minitest::Test
def test_can_create_a_complete_me_object
completion = CompleteMe.new
assert_equal CompleteMe, completion.class
end
def test_can_create_a_trie_object_from_complete_me
c... | true |
fa165be759acf75812b425eccfc634ed9d8da026 | Ruby | mgidea/kickball | /kickball.rb | UTF-8 | 2,590 | 4.15625 | 4 | [] | no_license | #phase 1 pseudo code
#ask for team 1's name and scores
#store this information
#ask for team 2's name and scores
#store this information
#compare scores
#report back who the victor is
victors = []
game_scores = []
def identifiy_winner(first_team, first_team_score, second_team, second_team_score, winner, scores)
if f... | true |
8fe6088b6026788785af7f75200f4f7bab3ffe21 | Ruby | DausdasKreuz/ironhack-week2-testing | /day_4-testing_web_applications/blogging_blog/lib/blog.rb | UTF-8 | 293 | 3.140625 | 3 | [] | no_license | class Blog
attr_reader :posts
def initialize
@posts = []
end
def add_post( post )
@posts.push(post)
end
def delete_post( post )
@posts.delete(post)
end
def show_posts
@posts
end
def latest_posts
@posts.sort_by { |post| post.date }.reverse
end
end
| true |
ac806c6b9e9a7e127aaf685936a1fe861f31bc24 | Ruby | muzudho/gtp-to-nngs | /parsing1/human-vs-engine/communication/player-a/PlayerA - decode_coords.rb | UTF-8 | 333 | 3.0625 | 3 | [
"MIT"
] | permissive |
# 指し手の文字列
def decode_coords(move_text)
if (move_text.upcae == 'PASS')
return [-1, -1]
end
# 大文字にする。
# I列 が欠番なので調整。
i = (move_text.upcase[0] - ?A) + 1
if (i >= ?I - ?A)
i -= 1
end
j = move_text[/[0-9]+/].to_i
return [i, j]
end
| true |
ba215bc2cb85fce5c549360fe7771e3f693ae2eb | Ruby | SFR1981/pub_lab_extra | /specs/food_spec.rb | UTF-8 | 384 | 3.109375 | 3 | [] | no_license | require("minitest/autorun")
require_relative("../food.rb")
class FoodTest < MiniTest::Test
def setup
@food = Food.new("chips", 1.50, 2.0)
end
def test_food_has_name
assert_equal("chips", @food.name())
end
def test_food_has_price
assert_equal(1.50, @food.price())
end
def test_food_has_rejuvenation_l... | true |
450bb4d6c43fe60704b2b30f11c086c76cf7c605 | Ruby | gropax/music_theory | /obsolete/mode.rb | UTF-8 | 1,600 | 2.890625 | 3 | [] | no_license | require_relative 'scale_advance_factory'
module Music
module Cyclic
class Mode
extend HasIntervals
include HasIntervals
def self.scale
@scale
end
def self.scale=(scale)
@scale = scale
end
def self.degree
@degree
end
... | true |
889a789b7b0b6f94ab28e3c10bcbb7d1588d3577 | Ruby | waihon/prag_studio_fund | /lib/crowdfund/fundable.rb | UTF-8 | 378 | 3.109375 | 3 | [
"MIT"
] | permissive | module CrowdFund
module Fundable
def add_fund(amount=25)
self.funding += amount
puts "\n#{name} got more funds!"
end
def remove_fund(amount=15)
self.funding -= amount
puts "\n#{name} lost some funds!"
end
def funding_needed
target_funding - funding
end
def ... | true |
1d8c33d9ce397823e5219f1df78c6103f654b118 | Ruby | daganM/Hom-Eat | /app/controllers/pages_controller.rb | UTF-8 | 990 | 2.671875 | 3 | [] | no_license | class PagesController < ApplicationController
def index
@meals = Meal.all.order('created_at DESC').limit(3)
end
def search
@lat1 = params[:lat].to_f
@lng1 = params[:lng].to_f
places = Place.all
@status = true
place_ids = []
places.each do |p|
if CoorDistance(p.latitude, p.long... | true |
31639bb43f543eb9d9a81464f2167957038336a1 | Ruby | jcbantuelle/euler | /007.rb | UTF-8 | 261 | 3.25 | 3 | [] | no_license | max_value = 1000000
sieve = []
(2..max_value).each { |i|
sieve << i
}
sieve.each { |index|
next if index.nil?
value = index
(value..max_value).step(value) { |filter|
sieve[filter-2] = nil if filter != value
}
}
sieve.compact!
puts sieve[10000] | true |
57397231f120783368e1151bbdda127ec9988a2e | Ruby | khalilhayek/ruby-101 | /tictactoe-03.rb | UTF-8 | 2,663 | 4.34375 | 4 | [] | no_license | # OK, now let's define those missing methods.
board = [
['_', '_', '_'],
['_', '_', '_'],
['_', '_', '_']
]
# Here's the method to display the board.
def show_board board
for row in board
print row.join(' '), "\n"
end
end
# Check if the player's move is legal.
# The player has selected a cell, defined by it... | true |
086c3a2cc766ef7021ac1f45f2cafb647db6aaa8 | Ruby | GeorgeSG/jirify | /lib/jirify/models/project_list.rb | UTF-8 | 461 | 2.578125 | 3 | [
"MIT"
] | permissive | module Jirify
module Models
class ProjectList < BaseList
def initialize(list)
@list = list.map { |project| Project.new project }
end
def find_by_name(name)
find { |project| project.name == name }
end
def keys
map(&:key)
end
def names
map... | true |
227a02411cdbb5db0616dbdb6b3e97c05d51c4c6 | Ruby | rsoemardja/Codecademy | /Ruby/Learn Ruby/Arrays and Hashes/Create a Histogram/You Know the Drill.rb | UTF-8 | 104 | 3.484375 | 3 | [] | no_license | # We need to get the input from the user
puts "Enter a phrase you'd like to analyze: "
text = gets.chomp | true |
b34124d96935d3a690e64a79c1895cf4812158b8 | Ruby | MITLibraries/bento | /app/models/normalize_primo.rb | UTF-8 | 1,322 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | # Tranforms results from {SearchPrimo} into normalized {Result}s
#
class NormalizePrimo
class InvalidResults < StandardError; end
# Translate Primo results into local result model
def to_result(results, type, q)
@type = type
norm = {}
norm['total'] = results['info']['total']
norm['results'] = []
... | true |
3de53b8e90a1a82eb64d94dfeddfd405d06e3c7c | Ruby | pulibrary/pulfalight | /app/values/pulfalight/delivery_note.rb | UTF-8 | 471 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
module Pulfalight
class DeliveryNote
attr_reader :location_code
def initialize(location_code)
@location_code = location_code
end
def brief_note
return unless delivery_warning_locations.include?(location_code)
"This item is stored offsite. Please allow ... | true |
9449ee3d77c6207465b9c985c37829a2ce3c8b1e | Ruby | evertofd/desafio-objeto | /4.rb | UTF-8 | 261 | 3.546875 | 4 | [] | no_license | class Dog
def initialize(propiedades)
@nombre = propiedades[:nombre]
end
def ladrar
puts "#{@nombre} está ladrando!"
end
end
propiedades = {nombre: 'Beethoven', raza: 'San Bernardo', color: 'Café'}
perro = Dog.new(propiedades)
perro.ladrar
| true |
542cf6cb9b9a7498813b4392552d6c50a037911f | Ruby | pauloptimised/my-project-manager | /app/models/discount.rb | UTF-8 | 550 | 2.671875 | 3 | [] | no_license | class Discount < ActiveRecord::Base
belongs_to :project
attr_accessor :percentage
validates :amount, presence: true
validates :project, presence: true
delegate :brand_price, to: :project
before_validation :set_amount, if: :percentage?
private
def percentage?
percentage.present?
end
def set_... | true |
891b006eca9da7768ff3752c7fed56e2e90334fc | Ruby | KielRodriguez/codigofacilito_examples | /splat.rb | UTF-8 | 345 | 3.484375 | 3 | [] | no_license | def hola_gente(mensaje, *personas)
personas.each { |persona| puts "#{mensaje} #{persona}" }
end
nombres = %w[Ikker Kiel Carlos]
hola_gente "Hey hola", *nombres
#Al anteponer * sobre el nombre del un argumento esto nos indica que puede ingresarse n argumentos los cuales se
#alamacenan dentro de la variable de nombre... | true |
80fa051be302e0b0cb2fb82b4649470b465afc3a | Ruby | junko911/ruby-oo-complex-objects-school-domain-nyc-web-033020 | /lib/school.rb | UTF-8 | 683 | 3.734375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
require 'pry'
class School
def initialize(school)
@school = school
@roster = {}
end
def add_student(name, grade)
if @roster[grade]
@roster[grade] << name
else
@roster[grade] = []
@roster[grade] << name
end
end... | true |
c4b2ecdd3051a950293332f27ff569e50bf9794d | Ruby | GoalSmashers/gs-ruby-utils | /lib/gs_ruby_utils/live/notifier.rb | UTF-8 | 1,146 | 2.609375 | 3 | [] | no_license | require_relative 'message'
module GS
module Live
class Notifier
def initialize(*args)
@messages = {}
end
def add(receiver, options)
messages[receiver.id] ||= []
messages[receiver.id] << Message.new(receiver, options)
end
def get(receiver)
messages.f... | true |
3869d689e6bdc68ce9e4fe9c1bc9eb2f86571e6f | Ruby | apanzerj/zit | /spec/settings_spec.rb | UTF-8 | 1,673 | 2.53125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby -wKU
require "spec_helper"
require_relative '../lib/zit/settings.rb'
def setup
ENV.stub(:[]).with("HOME").and_return("foo")
settings_file = double("File")
File.stub(:open).with("foo/.zit").and_return(settings_file)
settings_hash = Zit::Settings::DEFAULTS
Psych.stub(:load).with(s... | true |
df11a0fb69e1ebffaf592988fa39b84ba186cf87 | Ruby | jasmine1226/flight_deals | /lib/flight_deals/cli.rb | UTF-8 | 2,826 | 3.40625 | 3 | [
"MIT"
] | permissive | class FlightDeals::CLI
attr_reader :current_page, :scraped_page
def call
@current_page = 1
@scraped_page = 1
generate_deals(@scraped_page)
list_deals(@current_page)
menu
end
def generate_deals(page)
deals_array = FlightDeals::DealScraper.scrape_deals(page)
FlightDeals::Deal.create_... | true |
01c12b184e511c193ff6e37339e0580e0a50ed77 | Ruby | hopsoft/queryable_hash | /lib/queryable_hash/wrapper.rb | UTF-8 | 1,100 | 2.703125 | 3 | [
"MIT"
] | permissive | require "delegate"
module QueryableHash
class Wrapper < SimpleDelegator
attr_reader :nil_value, :raise_when_nil
def initialize(hash, nil_value: nil, raise_when_nil: false)
@original_hash = hash
@nil_value = nil_value
@raise_when_nil = raise_when_nil
super hash
end
def get_al... | true |
4ae5c002dc4dcbf25957c7fa11612db496e25195 | Ruby | godspeedyoo/algorithms-practice | /tester.rb | UTF-8 | 1,194 | 3.421875 | 3 | [] | no_license | # Solutions Ruby
# Problem 1
def solve_tree_a(tree_a)
queue = [tree_a.root]
solution = []
while !queue.empty?
current_node = queue.shift
# should go from left to right visiting each node's children
# assume we can call .left, .mid, .right on each node to specify
solution << current_node
queue ... | true |
c06a88eee7e167927d2a2b07e137022fca7e1b7c | Ruby | EiichiroSako/ruby_lesson | /fizz_buzz.rb | UTF-8 | 274 | 3.875 | 4 | [] | no_license | def fizz_buzz(number)
if number % 15==0
"finzzbuzz"
elsif number % 3==0
"fizz"
elsif number % 5==0
"buzz"
else number.to_s
end
end
puts "1 以上の数字を入力してください"
input = gets.to_i
puts "結果は"
puts fizz_buzz(input)
| true |
f9162014d934e6ac66117336d22e95a265094437 | Ruby | nikhilbhardwaj/Project-Euler | /problem_4/problem4.rb | UTF-8 | 369 | 3.796875 | 4 | [] | no_license | #Find the largest palindrome made from the product of two 3-digit numbers.
def palindrome? num
return true if num.to_s == num.to_s.reverse
end
largest_palindrome = 0
(100..999).each do |num1|
(100..999).each do |num2|
prod = num1 * num2
largest_palindrome = prod if palindrome? prod and prod > largest_pal... | true |
058baeef0b9f734f9e9aaa6c7196596dd7d52a17 | Ruby | rizwanniazigroupdocs/groupdocs-conversion-cloud-ruby-samples | /Examples/src/Working_With_Conversions/Conversion_Ruby_Convert_To_Any_Format.rb | UTF-8 | 746 | 2.625 | 3 | [
"MIT"
] | permissive | # Load the gem
require 'groupdocs_conversion_cloud'
require 'common_utilities/Utils.rb'
class Working_With_Conversions
def self.Conversion_Ruby_Convert_To_Any_Format(*args)
# Getting instance of the API
api = Common_Utilities.Get_ConvertApi_Instance()
$settings = GroupDocsConversionCloud::ConvertSettin... | true |
741e01c79718b2c2b5fba3bd1bedef6ab34b6bf6 | Ruby | ddowl/advent-of-code | /2018/day-01/day_01.rb | UTF-8 | 370 | 3.359375 | 3 | [] | no_license | require 'set'
sum = File.readlines('input.txt').map(&:to_i).sum
puts sum
sums = Set.new()
running_sum = 0
# Is there a more efficient way to generate a repeating list on demand?
seq = File.readlines('input.txt').map(&:to_i) * 100000
seq.each do |num|
running_sum += num
if sums.include?(running_sum)
puts runni... | true |
93b954429f72476dd6649a74ce3eec0f94db2579 | Ruby | RodriguezLucha/aA-homeworks | /W1D5/map.rb | UTF-8 | 746 | 3.515625 | 4 | [] | no_license | class Map
def initialize
@arr = []
end
def set(key, value)
found = get(key)
if found.nil?
@arr.push([key, value])
else
pair = @arr.select do |element|
element[1] = value if element.first == key
end
end
end
def get(key)
pair = @arr.select { |element| element... | true |
a7b8422d0e88e7e62d979b7f98dd35162dc06772 | Ruby | JARVIS-VOVA/dive-in-programming | /01 Путь Ruby - Фултон Хэл, Арко Андре/08 Массивы, хэши и другие перечисляемые структуры/8.1 Массивы/8.1.23. Вычисление частоты различных значений в массиве.rb | UTF-8 | 565 | 3.765625 | 4 | [] | no_license | # Для массивов нет метода count, как для строк (чтобы подсчитать число вхождений каждого элемента).
# Поэтому создадим свой собственный:
class Array
def count
k = Hash.new(0)
self.each{ |x| k[x]+=1 }
k
end
end
meal = %w[spam spam eggs ham eggs spam]
p items = meal.count
# items равно {"ham" => 1, "spa... | true |
bcc5cd3f86f7f9972138d61c30691620f5defdca | Ruby | RomAnoX/appfuel | /lib/appfuel/request.rb | UTF-8 | 1,484 | 2.9375 | 3 | [] | no_license | module Appfuel
class Request
attr_reader :action_route, :feature, :action, :inputs, :namespace
def initialize(action_route, inputs = {})
unless inputs.respond_to?(:to_h)
fail "inputs must respond to :to_h"
end
@inputs = inputs.to_h
@action_route, @feature, @action = parse_rout... | true |
adfb6151aab61c0ab3da404736b0b1714e04c97b | Ruby | twrameshb/frameworks | /Selenium-Ruby-Project2/script/refactoring/cobrand_move.rb | UTF-8 | 1,101 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/ruby
file = ARGV[0]
# should be path like app/views/header/_offsite_navigation_mykmart.rhtml
# first tokenize path
def path_tokens path
path_tokens = path.split '/'
file_name = path_tokens.pop
old_path = path_tokens.join '/'
file_name_no_extension = file_name.split('.')[0]
cobrand_... | true |
177f78da3a05db5503e0e7c28b3db3a9a7588bb1 | Ruby | melissames/module-one-final-project-guidelines-web-012918 | /lib/player.rb | UTF-8 | 525 | 3.234375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Player
attr_accessor :name, :lives, :username, :item
def initialize(username=nil)
@username = username
@lives = 3
@item = 0
end
def get_next_item
last_item = player_items.last != nil ? player_items.last.id_number : 0
next_id = last_item + 1
next_item = Item.all.find {|item| item... | true |
0c22b6ddf3814aeef55fb7c18631e1ea4787915a | Ruby | meganeding1/algo-practice | /Q1-cake.rb | UTF-8 | 607 | 4 | 4 | [] | no_license | # Stock trading: look at an array of yesterday's stock prices to maximize profit when you buy/sell
# must buy before you sell
# return the profit (integer)
def max_profit(stock_prices)
min_val_1 = stock_prices.min
min_val_1_index = stock_prices.index(min_val_1)
modified_stock_prices_1 = stock_prices[(min_val_1_... | true |
9f96dd7026987b2c00c57eee5ab5304b827dae5b | Ruby | Bykanir/ruby_lessons | /Lesson_14/passenger_carriage.rb | UTF-8 | 115 | 2.578125 | 3 | [] | no_license | class PassengerCarriage < Carriage
def initialize(number, seats)
super(number)
@seats = seats
end
end
| true |
164702109bb46fe91de9087165d34b890edea071 | Ruby | fuseumass/dashboard | /app/models/judgement.rb | UTF-8 | 1,851 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | class Judgement < ApplicationRecord
belongs_to :project
belongs_to :user
validates :project_id, presence: true
validates :user_id, presence: true
# Generating CSV for all judgements
def self.to_csv
CSV.generate do |csv|
finalKeyArr = Array.new
keyArr = Judgement.first.attributes.keys
customScore... | true |
db955c24cee3aa683b2bc2e621e4147a5a401e9f | Ruby | jscho13/leetcode | /diameter-of-binary-tree.rb | UTF-8 | 754 | 3.609375 | 4 | [] | no_license | # Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer}
def diameter_of_binary_tree(n)
return 0 if n == nil
left = dfs_search(n.left,... | true |
29dfbd85e66f4c99f431f964f2160b15cd435d60 | Ruby | mjdele/cartoon-collections-v-000 | /cartoon_collections.rb | UTF-8 | 516 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | long_words = ["blabber", "frunkuss", "tattletale", "bop"]
def roll_call_dwarves(dwarves)
dwarves.each_with_index do |name, index|
puts "#{index+1} #{name}"
end
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.collect do |shouts|
"#{shouts.capitalize}!"
end
end
def long_planeteer_calls(l... | true |
929e428e01ef0c257029b7b2321804cf857c1ca5 | Ruby | honorarac/vagrant | /plugins/kernel_v2/config/push.rb | UTF-8 | 4,044 | 2.546875 | 3 | [
"MIT"
] | permissive | require "vagrant"
module VagrantPlugins
module Kernel_V2
class PushConfig < Vagrant.plugin("2", :config)
VALID_OPTIONS = [:strategy].freeze
attr_accessor :name
def initialize
@logger = Log4r::Logger.new("vagrant::config::push")
# Internal state
@__defined_pushes = {}... | true |
c8492800c6fd740cb046f116877cd7d61f7c3ebc | Ruby | brahamshakti/minesweeper | /src/minesweeper.rb | UTF-8 | 823 | 3.34375 | 3 | [] | no_license | require_relative './row'
class Minesweeper
attr_reader :rows, :boxes_opened
def initialize
@rows = []
end
def add_rows(box_states)
# x,y,z location state
x,y,z = box_states.split('')
@rows << Row.new(x,y,z)
end
def display
layout_string = ''
@rows.each do |row|
layout_string << "#{box_statuses(... | true |
2a7670dd453903eb85ae2eab48d9be7f989860dc | Ruby | Precnet/TestGuru | /db/seeds.rb | UTF-8 | 2,527 | 2.546875 | 3 | [] | no_license | # frozen_string_literal: true
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: ... | true |
8b7b1eb84619e8e1b230d14b4d74a4294cc17940 | Ruby | bittujoju/shop | /app/models/item.rb | UTF-8 | 469 | 2.640625 | 3 | [] | no_license | class Item < ApplicationRecord
belongs_to :product
belongs_to :county
belongs_to :sale
validates_presence_of :quantity, :message => "quantity Required"
before_save :set_selling_price, :set_tax
def name
self.product.name
end
def cost_price
self.product.cost_price * quantity
end
def set... | true |
6af2b1a7961b60b302ed871b6238afcb0abae1e8 | Ruby | jamesdphillips/zimmermann-base32 | /lib/zbase32.rb | UTF-8 | 1,875 | 3.0625 | 3 | [
"MIT"
] | permissive | module ZBase32
CHARSET = %w( y b n d r f g 8 e j k m c p q x o t 1 u w i s z a 3 4 5 h 7 6 9 ).freeze
MASKS = [0x1f, 0x3e, 0x7c, 0xf8, 0xf0, 0xe0, 0xc0, 0x80].freeze
MASKS2 = [0x1, 0x3, 0x7, 0xf].freeze
ZB2N = CHARSET.each_with_index.inject({}) { |acc, (a, b)| acc[a] = b; acc }.freeze
extend self
def e... | true |
4bf938393d515b9c6bba648d7dec4841cc013a07 | Ruby | automation555/imap_auth | /test/imap_authenticatable_test.rb | UTF-8 | 4,947 | 2.609375 | 3 | [
"MIT"
] | permissive | require File.join(File.dirname(__FILE__), 'test_helper')
class Normal < ActiveRecord::Base
imap_authenticatable :host => 'mail.example.com', :default_domain => 'example.com'
end
class Admin < ActiveRecord::Base
imap_authenticatable :host => 'collectiveidea.com', :allow_new_users => false
# override authentic... | true |
d0102feb26f81d13b82025ae35bd456f16456696 | Ruby | mainRomainRo/games-in-ruby | /Hangman/system.rb | UTF-8 | 1,384 | 3.546875 | 4 | [] | no_license | class System
attr_accessor :word_to_display, :used_letters
def initialize
@word_to_display = []
@used_letters = []
end
def generate_word
dico_words = File.open('dico.txt', 'r').readlines
new_word = dico_words.select { |el| el.length >= 5 && el.length <= 12 }.sample.chomp.upcase
@word_to_d... | true |
519c14aeeddcde71455fd4eccd900ec1b7647b7d | Ruby | mvassaramo/checkout-system | /spec/checkout_spec.rb | UTF-8 | 1,994 | 2.953125 | 3 | [] | no_license | require_relative '../lib/checkout'
RSpec.describe Checkout do
subject(:checkout) { Checkout.new(promotional_rules) }
let(:promotional_rules) do
[
{ type: 'item', discount_percentage: 0.75/9.25, item_code: 001, min_quantity: 2, threshold: nil },
{ type: 'basket', discount_percentage: 0.1 , item_co... | true |
76650ffa3f734082a2bde85e5086238779329b57 | Ruby | mydomino/domino | /lib/tasks/test_utils.rake | UTF-8 | 3,467 | 2.625 | 3 | [] | no_license | require "#{Rails.root}/lib/helper_functions"
require 'faker'
include HelperFunctions
# This file contains all test functions used for testings purposes
namespace :md_test do
desc "Generate X number of fake data rows for CSV file upload. Example usage: rake csv:build_csv_file_with_fake_data 200"
task build_c... | true |
8e65b86cdedd4c630be165318d41ad8d0c730c16 | Ruby | Honobono/Launch_School_Backend_Course | /intro_to_ruby_exercises/exercises_5.rb | UTF-8 | 637 | 4.53125 | 5 | [] | no_license | ## Intro to Programming: Arrays Exercises
#1
arr = [1,3,5,7,9,11]
number = 3
if arr.include?(number)
puts "#{number} is in the array."
end
=> true
#2
1. returns 1, arr is modified to [["b"], ["b", 2], ["b", 3], ["a", 1], ["a", 2], ["a", 3]]
2. returns [1,2,3], arr is modified to [["b"], ["a", [1, 2, 3]]]
#3
arr.... | true |
96006f01b74c136098b39886af4f0c8e66f560a8 | Ruby | pedz/Raptor | /app/models/cached/center.rb | UTF-8 | 3,143 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
#
# Copyright 2007-2011 Ease Software, Inc. and Perry Smith
# All Rights Reserved
#
module Cached
# === Retain Center Model
#
# This model is the database cached version of a Retain center. The
# database table is <em>cached_centers</em>. The fields cached from
# Retain are a bit ar... | true |
84cc26f26c71e3685fee424e233aa97ee59820a0 | Ruby | wwhitehead/raxe | /examples/BlockComments.rx | UTF-8 | 857 | 3.4375 | 3 | [
"MIT"
] | permissive | # vim: set ft=rb:
###
This is how block (multiline) comments look in Raxe.
You can plase as much text here as you want, you just must
terminate block comment with same number of hypnens as you
initialized it.
###
class @
#####
If you want to use nested block comments, you must initialize
block comment with diffe... | true |
ebe96bfcb1ac2c2c96317962bf949999ce5d855e | Ruby | bbuck/eleetscript | /lib/engine/engine.rb | UTF-8 | 3,232 | 2.765625 | 3 | [
"MIT"
] | permissive | require "lang/runtime/memory"
require "lang/interpreter"
require "engine/values"
module EleetScript
class CannotInstantiateBaseEngine < Exception
def initialize
super("You cannot instantiate BaseEngine, use SharedEngine or StandaloneEngine")
end
end
class CannotCallInstanceOrClassMethodsExcpetion ... | true |
a68ba10ad80e6bd79a8c52d5570156f9170ad617 | Ruby | bethink/RubyProgrames | /n_parentheses.rb | UTF-8 | 1,127 | 4.15625 | 4 | [] | no_license | # =================== SAMPLE INPUTS & ITS RESULTS
#
# 1 => ()
#
# 2 => ()() | (())
#
# 3 =>
#
# ()()()
#
# ()(()) (())()
#
# ((()))
#
# 4 =>
#
# ()()()()
#
# ()()(()) ()(())() (())()() (())(())
#
# ((()))() ()((()))
#
# (((())))
print "\nEnter a number(n): "
n = gets().to_i
# ===... | true |
b1d712074b7786ebecc4d89821b7fe249a8bc4a4 | Ruby | bibliotechy/local_playlist | /lib/local_playlist/venues.rb | UTF-8 | 3,081 | 3.140625 | 3 | [] | no_license | require 'songkickr'
module LocalPlaylist
class Venues < Base
# Searches Songkick with location and returns a list of venues and shows near that location
# @param params [Hash] a hash of parameters
# @options opts [String] :coordinates Latitude, Longitude
# @options opts [String] :named_location The... | true |
11f92fa9e8ef176c7540c153ef594b773776ebbc | Ruby | sosheskaz/Project-Euler | /Ruby/Euler015.rb | UTF-8 | 317 | 3.515625 | 4 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/env ruby
def main
target = 20
puts combinatoric(target * 2, target)
end
def combinatoric(n, r)
numer = factorial(n)
denom = factorial(r) * factorial(n - r)
return numer / denom
end
def factorial(n)
p = 1
while n > 1
p *= n
n -= 1
end
return p
end
if __FILE__ == $0
main
end
| true |
45b36f8c575f05314f54fe70e4576aa4ecc1e0a4 | Ruby | day-katy/oyster-card2 | /lib/oystercard.rb | UTF-8 | 730 | 3.546875 | 4 | [] | no_license | class Oystercard
attr_reader :balance, :in_journey
MAXIMUM_BALANCE = 90
MINIMUM_BALANCE = 1
def initialize
@balance = 0
@in_journey = false
end
def topup(amount)
raise "Maximum balance of #{MAXIMUM_BALANCE} exceeded" if limit_reached?(amount)
@balance += amount
end
def in_journey?
... | true |
3daf6651751c2d3f7b3bfc9b12978ce46a693fd0 | Ruby | maksimTHP/exoruby14012020 | /exo_07_c.rb | UTF-8 | 318 | 3.625 | 4 | [] | no_license | user_name = gets.chomp
puts user_name
#le programme fait pareille que les autres sauf qu'il n'y a pas d'indication et que si ce n'est pas affiché, en tant qu'user on ne sait pas quoi faire. Lorsque on run le programme, visuellement, rien ne se passe, alors que le programme demande juste que l'user mette un string.
| true |
5c9c7b9091c7e8317ab8d4eb5002326e9d698826 | Ruby | andruby/thesis | /cplex_to_yaml.rb | UTF-8 | 917 | 2.625 | 3 | [] | no_license | # Convertor om die de outputfile van cplex omzet naar een yaml bestand
# dat gebruikt kan worden door de assignment_viewer
require 'config'
dates = '7_27'
conf = 'conf7'
flights_yaml = "data/assignments/#{dates}_original.yml"
flights_write_yaml = "data/assignments/#{dates}_#{conf}_cplex.yml"
flights = load_from_yaml... | true |
e56fbba80062c2913c379e8e4ea081e0a7fc7579 | Ruby | chris-ramon/worldportsource-parser | /Port.rb | UTF-8 | 768 | 2.828125 | 3 | [] | no_license | class Port
attr_accessor :port_location, :port_name, :port_authority, \
:address, :phone, :fax, :eight_number, :email, :web_site, \
:latitude, :longitude, :un_locode, :port_type, :port_size
def initialize(port_location=nil, port_name=nil, port_authority=nil,
address=nil, phone=nil, fax=nil, eight_number=nil, ema... | true |
57b234b15d9da65ddeb6cbc3584b8d82c7e2b03c | Ruby | fatihorhan/dump | /tvarsivi.rb | UTF-8 | 801 | 2.6875 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'fileutils'
class Integer
def tries(options={}, &block)
attempts = self
exception_classes = [*options[:on] || StandardError]
begin
return yield
rescue *exception_classes => e
sleep 2
puts "#{e.message}. #{attempts} attempts left"
... | true |
5cf5fe7e78e634c97440e58f68a7d97491966667 | Ruby | w-simon/tact | /bin/get_conf_value | UTF-8 | 1,888 | 2.625 | 3 | [] | no_license | #!/usr/bin/ruby
require 'optparse'
require 'rexml/document'
include REXML
test_dir=Dir.getwd
# TODO: assert that we're running within test directory
if (test_dir[/^\/.+\/tests\/([^\/]+)$/] == nil)
if !ENV.has_key?('TACT_DIR') || !ENV.has_key?('TEST_DIR') || !ENV.has_key?('APP_DIR')
puts 'error: TACT_DIR, TEST_DIR ... | true |
ed8be31fcf214cdf28c516052c6aded7bbafa938 | Ruby | faithngetich/news-cli | /cli/news_cli.rb | UTF-8 | 1,025 | 3.21875 | 3 | [] | no_license | require 'colorize'
require_relative '../news_api'
require_relative 'news_options'
class NewsCli
include NewsOption
def call
introduction
command_helper
news_categories
end
def introduction
puts 'NEWS CLI '
puts '==========='
puts 'Here are the list of commands you can use, enter a numb... | true |
0ece48f014938560f3b0de18bf29d5305620161f | Ruby | jw-park/hw-ruby-intro | /lib/ruby_intro.rb | UTF-8 | 1,122 | 3.953125 | 4 | [] | no_license | # When done, submit this entire file to the autograder.
# Part 1
def sum arr
arr.inject(0){|sum, x| sum + x}
end
def max_2_sum arr
sum(arr.max(2))
end
def sum_to_n? arr, n
if arr.length == 0
return false
end
i = 0
j = arr.length - 1
sorted = arr.sort
while i < j
if sorted[i] + sorted[j] ==... | true |
0a2fa50a26e440cae76e096220e0abcee194fd33 | Ruby | markbiddlecom/sketchup-crafty | /src/crafty/tool_state_machine/mode.rb | UTF-8 | 2,915 | 2.640625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Crafty
module ToolStateMachine
class Mode
EMPTY_CHORDSET = Chords::Chordset.new
# @type [Array(Boolean, String, String)]
NULL_VCB_STATE = [false, '', ''].freeze
CLICK_SLOP_DISTANCE = 5
# @return [Chords::Chordset] the command chords applicable t... | true |
e83624601e49b671b397058b45b61747d782c9dc | Ruby | robintran/carstore2 | /lib/tasks/database.rake | UTF-8 | 3,384 | 2.796875 | 3 | [] | no_license | desc "Fetch database"
task :fetch_database => :environment do
require 'nokogiri'
require 'open-uri'
require 'cgi'
finish = false
current_category = nil
url = "http://www.gumtree.com/all/london"
while !finish
url = current_category.link unless !current_category
category_tags = fetch_category_tags(url)
c... | true |
57f979c5af5527e228c493b72e80138368864122 | Ruby | pejotes/fuel-plugin-lma-collector | /deployment_scripts/puppet/modules/lma_collector/lib/puppet/parser/functions/get_cluster_names.rb | UTF-8 | 1,575 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2015 Mirantis, Inc.
#
# 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 ... | true |
b302b8a81afad2e253dee80ed847a19f6dc21a9d | Ruby | takumi-kani/furima-36551 | /spec/models/user_spec.rb | UTF-8 | 6,036 | 2.640625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
describe "ユーザー新規登録" do
context "新規登録できるとき" do
it "全ての項目の入力が存在すれば登録できること" do
expect(@user).to be_valid
end
it "passwordが6文字以上の半角英数字混... | true |
1f46625a0ebdacc24d8c732ee0e1ceec276833b1 | Ruby | millisami/wedding | /app/models/cart.rb | UTF-8 | 4,981 | 2.515625 | 3 | [] | no_license | class Cart
attr_reader :items
attr_reader :total_price
attr_reader :converted_total_price, :shipping_cost, :total_weight, :total_quantity
attr_accessor :exchange_currency
def initialize
@exchange_currency = 'EUR'
empty_all_items
end
def get_quantity(product_id)
existing_item = @item... | true |
273868520f9dd2f4d1808c1b4c4238cb16113cde | Ruby | Toxinfernal/mini_jeu_poo | /app.rb | UTF-8 | 642 | 3.171875 | 3 | [] | no_license | require 'bundler'
Bundler.require
require_relative 'lib/game'
require_relative 'lib/player'
player1 = Player.new("Marie")
player2 = Player.new("Joseph")
while player1.life_points > 0 || player2.life_points > 0
puts "Voici l'état de nos deux CHALLENGER !!!"
player1.show_state
player2.show_state
... | true |
0cde56a5761b277e96aaceb302b4d977f48e65fa | Ruby | IbraWorks/connect_four | /spec/board_spec.rb | UTF-8 | 2,695 | 3.40625 | 3 | [] | no_license | require "board.rb"
describe Board do
let(:c4){Board.new}
it "is a class" do
expect(c4).to be_instance_of Board
end
it "has instance variables" do
expect(c4).to respond_to(:game_board, :turns)
end
it "is initialized with a game_board array of size 7x6" do
board = Array.new(7) { Array.new(6, ... | true |
8f2853c0508a2edf6e77dbdf51394c3796926b89 | Ruby | roxer/angular_raills_example | /lib/result.rb | UTF-8 | 441 | 3 | 3 | [
"MIT"
] | permissive | class Result
@result = false
@notice = ''
@error_string = ''
def initialize(result)
@result = result
end
def success?
@result
end
def fail?
!@result
end
def error_string
@error_string
end
def error_string=(error_string)
@error_string = error_string
end
def notice
... | true |
b4e2aa1a3462b3142f8c5ad53b5e26365143132e | Ruby | mx98829/123 | /Lesson_4/test95.rb | UTF-8 | 414 | 4.3125 | 4 | [] | no_license | # Upgrade Ruby's Hash class to work like a JavaScript Object. For example:
# hash = {:five => 5, :ten => 10}
# hash.five #=> 5
# hash.fifteen = 15
# hash[:fifteen] #=> 15
# This should work for any Ruby hash, both setting and getting values. For simplicity's sake, don't worry about supporting string keys, only symb... | true |
c4604cfed4a13147f9f2f3d9d4d676c05f4ca90c | Ruby | tgaff/horasdeoficina | /app/models/weekly_time_block.rb | UTF-8 | 3,330 | 3.015625 | 3 | [
"MIT"
] | permissive | # == Schema Information
#
# Table name: weekly_time_blocks
#
# id :integer not null, primary key
# from :datetime
# to :datetime
# can :boolean
# preferred :integer
# course_participant_id :integer
# created_at ... | true |
0aa192797256b5917f09c3bae973ec6dd172fa37 | Ruby | scorp200/Open-Sweeper-Ruby | /app/lib/doge_camera.rb | UTF-8 | 1,482 | 2.671875 | 3 | [
"MIT"
] | permissive | # Requires:
# doge_array.rb
# doge_tick.rb
# Usage:
# initialize the camera with position and zoom
# For mouse position use mouse.local_position
# When using scale variables multiply them by camera.zoom
# To scale mouse.dragging_dist divide it by camera.zoom
# Credit:
# By Anton K. (ai Doge) https://aidoge.net
class ... | true |
b65b8f69a2749fb406f05bbfe9cb067e8dff0ab5 | Ruby | alexanderko/compose-test | /app.rb | UTF-8 | 151 | 2.515625 | 3 | [] | no_license | require "sinatra"
require "redis"
redis = Redis.new(host: "redis")
get "/hi" do
redis.incr("hits")
"Hello World! Hits: " + redis.get("hits")
end
| true |
4ba61aad2fcca5a2c6754206be3104465c89aafd | Ruby | emsk/nhk_line_notifier | /lib/nhk_line_notifier/client.rb | UTF-8 | 1,274 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'net/http'
require 'nhk_program'
require 'time'
module NhkLineNotifier
class Client < NHKProgram::Client
NHK_ENDPOINT = 'http://api.nhk.or.jp/v2/pg'.freeze
LINE_NOTIFY_ENDPOINT = 'https://notify-api.line.me/api/notify'.freeze
attr_accessor :area, :service, :date, :nhk_key, :line_key, :word
... | true |
8911cb259329a37fde11e8f0fc3396185dfc2778 | Ruby | noir-neo/slappy-bird | /main.rb | UTF-8 | 722 | 2.625 | 3 | [
"MIT"
] | permissive | require 'slack'
require './game.rb'
require 'pry'
token = ENV['SLACK_TOKEN'] || (print "Token: "; gets.strip)
Slack.configure {|config| config.token = token }
client = Slack.realtime
games = []
client.on :hello do
puts 'Connected.'
end
client.on :message do |data|
if data['text'] == 'slappybird' && data['subty... | true |
2dee66a9b979b118a8cbf036d5705e2c8db0f7b6 | Ruby | ttuan/hackerrank_solutions | /algorithms/implementation/beautiful-triplets.rb | UTF-8 | 330 | 3.421875 | 3 | [] | no_license | #!/bin/ruby
def beautifulTriplets(d, arr)
result = 0
hash = {}
arr.each do |a|
hash[a] = a
if hash[a -d] and hash[a-2*d]
result += 1
end
end
result
end
n, d = gets.strip.split(' ')
n = n.to_i
d = d.to_i
arr = gets.strip
arr = arr.split(' ').map(&:to_i)
result = beautifulTriplets(d, arr)
pu... | true |
bbb3760f4915d6c123a9c484469181c4b89ec0b6 | Ruby | pliam/luhn_gem | /test/test_luhn.rb | UTF-8 | 1,440 | 3.03125 | 3 | [
"MIT"
] | permissive | require 'test/unit'
require File.join(File.dirname(__FILE__), '..', 'lib', 'luhn')
class TestLuhn < Test::Unit::TestCase # :nodoc:
# test known values
def test_known
# NOTE: Not real cards!
# these were published along with the algorithm pseudo-code
known_cards = <<-END
5399968743187425
525... | true |
aeb5375486f6fd070cf486c8e1aaee34a2686dd1 | Ruby | gerrit-rws/yatata | /lib/yatata/consumer.rb | UTF-8 | 295 | 2.5625 | 3 | [] | no_license | module Yatata
class Consumer
attr_accessor :client
def initialize(jid, password)
@client = Client.setup jid, password
end
def run
@client.connect
self
end
def consume(hash)
p "consume #{hash}, #{@client.ready?}"
@client.deliver hash['stanza']
end
end
end
| true |
17586207fd6a60c436c6eb771d29756d3ba30bb7 | Ruby | mtarias/agendapro_roulette | /app/services/dark_sky_api.rb | UTF-8 | 837 | 2.734375 | 3 | [] | no_license | module DarkSkyApi
API_TOKEN = Rails.application.secrets.dark_sky_token
LATITUDE = GlobalVariables::DarkSkyData::Latitude
LONGITUDE = GlobalVariables::DarkSkyData::Longitude
API_URL = "https://api.darksky.net/forecast/#{API_TOKEN}/#{LATITUDE},#{LONGITUDE}?exclude=currently,minutely,hourly,alerts"
... | true |
23b0bf87881dcd39e924afc6e7cb89ec218ffd5b | Ruby | bhollan/ttt-with-ai-project-v-000 | /lib/game.rb | UTF-8 | 3,168 | 3.65625 | 4 | [] | no_license | class Game
attr_accessor :board, :player_1, :player_2, :winner
WIN_COMBINATIONS = [[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
... | true |
dc69f971587ab6207fd8a9c96165e77236d6a8c4 | Ruby | ifeodugbesan/rails-longest-word-game | /app/controllers/games_controller.rb | UTF-8 | 518 | 2.8125 | 3 | [] | no_license | require 'json'
require 'open-uri'
class GamesController < ApplicationController
def new
grid = ('A'..'Z').to_a
@letters = Array.new(9) { grid.sample }
end
def score
@words = params[:grid].split(' ')
@guess = params[:word].upcase.split('')
@result = @guess.all? do |letter|
@guess.count(... | true |
e3da1d720b1283a030dff4a954870adbb6e3ea07 | Ruby | tomily1/ip_formatter | /lib/ip_formatter.rb | UTF-8 | 1,081 | 3.109375 | 3 | [] | no_license | require_relative './concerns/utitlity_methods.rb'
class IpFormatter
include UtilityMethods
attr_reader :data, :file_path, :result
def initialize(file)
@file_path = file
@result = {}
end
def prepare_file
if File.exist?(@file_path)
data = File.open(@file_path, 'rb', &:read)
result[:err... | true |
f479056f883dfbaabbbbacbafd2510aadfe02e49 | Ruby | benstafford/Gilded-Rose-Ruby | /lib/gilded_rose.rb | UTF-8 | 1,482 | 3.1875 | 3 | [] | no_license | module GildedRose
class Item
attr_reader :days_remaining, :quality
def initialize(days_remaining, quality)
@days_remaining = days_remaining
@quality = quality
end
def tick; end
end
class Normal < Item
def tick
@days_remaining -= 1
return if @quality.zero?
@qua... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.