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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2bdfb3b662e76c103623633cfa4329cb52819334 | Ruby | cklim83/launch_school | /02_rb101_rb109_small_problems/03_easy_3/01_searching_101.rb | UTF-8 | 1,729 | 4.46875 | 4 | [] | no_license | =begin
Searching 101
Write a program that solicits 6 numbers from the user, then prints a message
that describes whether or not the 6th number appears amongst the first 5
numbers.
Examples:
==> Enter the 1st number:
25
==> Enter the 2nd number:
15
==> Enter the 3rd number:
20
==> Enter the 4th number:
17
==> Enter the 5th number:
23
==> Enter the last number:
17
The number 17 appears in [25, 15, 20, 17, 23].
==> Enter the 1st number:
25
==> Enter the 2nd number:
15
==> Enter the 3rd number:
20
==> Enter the 4th number:
17
==> Enter the 5th number:
23
==> Enter the last number:
18
The number 18 does not appear in [25, 15, 20, 17, 23].
=end
def prompt(count)
puts "==> Enter the #{count} number:"
end
def store_number(numbers)
numbers << gets.chomp.to_i
end
numbers = []
prompt("1st")
store_number(numbers)
prompt("2nd")
store_number(numbers)
prompt("3rd")
store_number(numbers)
prompt("4th")
store_number(numbers)
prompt("5th")
store_number(numbers)
prompt("last")
last_number = gets.chomp.to_i
if numbers.include?(last_number)
puts "The number #{last_number} appears in #{numbers}."
else
puts "The number #{last_number} does not appear in #{numbers}."
end
=begin
Solution
numbers = []
puts "Enter the 1st number:"
numbers << gets.chomp.to_i
puts "Enter the 2nd number:"
numbers << gets.chomp.to_i
puts "Enter the 3rd number:"
numbers << gets.chomp.to_i
puts "Enter the 4th number:"
numbers << gets.chomp.to_i
puts "Enter the 5th number:"
numbers << gets.chomp.to_i
puts "Enter the last number:"
last_number = gets.chomp.to_i
if numbers.include? last_number
puts "The number #{last_number} appears in #{numbers}."
else
puts "The number #{last_number} does not appear in #{numbers}."
end
=end | true |
11465913fb2202eea55f0d3a1ec475ad8d996850 | Ruby | k1LoW/bun | /lib/bun/extractor.rb | UTF-8 | 1,501 | 2.625 | 3 | [
"MIT"
] | permissive | # coding: utf-8
require 'natto'
require 'ltsv'
module Bun
class Exctractor
def self.extract_line(line)
line.strip!
line.gsub!(/([>"'])/, '\1 ') # @dirty
fmt = {
node_format: 'word:%M\ttype:%s\tfeature:%H\n',
unk_format: 'word:%M\ttype:%s\tfeature:%H\n',
eos_format: 'EOS\n',
userdic: File.dirname(__FILE__) + '/userdic/symbol.dic'
}
@nm = Natto::MeCab.new(fmt) unless @nm
paragraphs = []
extracted = []
bun_start = false
last_feature = nil
@nm.parse(line) do |n|
break if n.is_eos?
parsed = LTSV.parse(n.feature)
word = parsed[0][:word]
feature = parsed[0][:feature].split(',').first
bun_start = true if word.is_part_of_bun?
if bun_start && !word.is_part_of_bun?
if !extracted.join.ascii_only? && extracted.join != ''
paragraphs.concat(self.separate_paragraphs(extracted.join.strip))
end
bun_start = false
extracted = []
last_feature = feature
next
end
extracted << word if word.is_part_of_bun?
last_feature = feature
end
unless extracted.join == '' || extracted.join.ascii_only?
paragraphs.concat(self.separate_paragraphs(extracted.join.strip))
end
paragraphs
end
def self.separate_paragraphs(paragraphs)
paragraphs.gsub(/([。\.]+)/, '\1\n').split('\n').map do |p|
p.strip
end
end
end
end
| true |
83f0e1cf5df68d860a6f5b1f362804a7086ce77f | Ruby | iiom/codewars | /Alternating_Split.rb | UTF-8 | 8,270 | 3.90625 | 4 | [] | no_license | # For building the encrypted string:
# Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
# Do this n times!
# Examples:
# "This is a 14-2 v1 v2!", 1 -> "hsi etTi sats!"
# "This is a 14-2 v1 v2!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!"
# моё
def encrypt(text, n)
return text if n <= 0
# возвращаем массивы символов по по чётным и не четным индексам и потом их складываем
arr1 = text.chars.select.with_index {|_, idx| idx.odd?}
arr2 = text.chars.select.with_index {|_, idx| idx.even?}
encrypt((arr1 + arr2).join, n - 1)
end
def decrypt(encrypted_text, n)
return encrypted_text if n <= 0
# делим защифрованную строку на двое и в разные массивы и потом их сшиваем
midpoint = encrypted_text.length / 2
arr1 = encrypted_text[0...midpoint].chars
arr2 = encrypted_text[midpoint..-1].chars
decrypt(arr2.zip(arr1).join, n - 1)
end
############################################################################
# решения с каты:
# лучшее
def encrypt text, n
n.times.reduce(text){|y,_|y.scan(/(.)(.)?/).transpose.reverse.join} rescue text
end
def decrypt text, n
n.times.reduce(text){|y,_|y.scan(/(?=.{#{y.size/2}}(.))(.)/).join[0...y.size]} rescue text
end
####################################################################################
def encrypt(text, n)
return text if n <= 0
encrypt(text.scan(/(.)(.)?/).transpose.reverse.join, n-1)
end
def decrypt(text, n)
return text if n <= 0
c, s = text.chars, text.size/2
decrypt(c.drop(s).zip(c.take s).join, n-1)
end
################################################################################
# решения с каты:
def encrypt(text, n)
return text if n <= 0 or text.nil?
n.times do
list = text.scan /(.)(.?)/
o1 = []
o2 = []
list.map do |x, y|
o1 << x
o2 << y
end
text = o2.join + o1.join
end
return text
end
def decrypt(encrypted_text, n)
return encrypted_text if n <= 0 or encrypted_text.nil?
m = encrypted_text.size# / 2
n.times do
text = []
m.times do |i|
text << encrypted_text[m + i]
text << encrypted_text[i]
end
text << encrypted_text[-1] if encrypted_text.size % 2 == 1
encrypted_text = text.join
end
return encrypted_text
end
######################################################################################
#
# chars - Возвращает массив, содержащий символы строки, из которой вызывается метод
# "hello".chars #-> ["h", "e", "l", "l", "o"]
#
# select Возвращает массив, содержащий все элементы enum, для которых результат обработки
# block не является false (см.также Enumerable#reject).
# enum.find_all {| obj | block } => array
# enum.select {| obj | block } => array
# (1..10).find_all {|i| i % 3 == 0 } #=> [3, 6, 9]
# (1..10).select {|i| i % 3 == 0 } #=> [3, 6, 9]
#
# with_index принимает необязательный параметр для смещения начального индекса.
# each_with_index делает то же самое, но не имеет необязательного начального индекса.
#
# # join Возвращает строку, созданную путем преобразования каждого элемента
# # массива в строку, разделенных строкой ["a", "b", "c" ].join("-") #=> "a-b-c"
#
# zip Преобразует аргументы в массивы (при помощи методаto_a). Объединяет каждый элемент
# массива array с соответствующим массивом, переданным в качестве аргумента. В результате
# этого создается двумерный массив с array.size строками и сn столбцами, гдеn — максимальная
# из длин аргументов-массивов. Если длина какого либо из аргументов-массивов меньшеn,
# то он расширяется до длиныn (дополняетсяnil). Если задан блок, то получаемые массивы
# передаются в блок в качестве параметра, иначе — возвращается двумерный массив.
# Обычно используется совместно с методом assoc, то естьzip подготавливает для него массив,
# по которому будет осуществляться ассоциация
#array.zip(arg, ...) #=> an_array
# array.zip(arg, ...) {| arr | block } #=> nil
# a = [4, 5, 6]
# b = [7, 8, 9]
# [1,2,3].zip(a, b) #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# [1,2].zip(a,b) #=> [[1, 4, 7], [2, 5, 8]]
# a.zip([1,2],[8]) #=> [[4,1,8], [5,2,nil], [6,nil,nil]]
#
# reduce или inject это метод который обрабатывает элементы enum применяя к ним блок,
# принимающий два параметра - аккумулятор (memo) и обрабатываемый элемент. Комбинирует все
# элементы в enum, применяя бинарную операцию, переданную в виде блока или символа в метод.
# Если явно не указано начальное значение для memo, то первый элемент коллекции используется
# в качестве начального значения memo.
#
# scan находит все указанные подстроки и возвращает их в виде массива строк.
# В данном примере, метод .size считает количество элементов массива, возвращаемого .scan
# string = "жыло-было шыбко шыпящее жывотное"
# string.scan("шы") #=> ["шы", "шы"]
# string.scan("шы").size #=> 2
#
# # reverse - Возвращает новый массив, в котором элементы массива array стоят в обратном порядке.
#
# transpose — транспонирование массива. Еси представить двуметный массив в виде таблицы,
# где вложенные массивы являются столбцами, то метод #transpose предоставляет возможность
# изменьсть структуру массива, на такую, где столбцы преобразуются в стоки. Словами объяснить
# это сложновато, вам следует взглянуть на пример, чтобы понять лучше:
# # a = [[10,11,12],[20,21,22]]
# a.transpose #=> [[10, 20], [11, 21], [12, 22]]
# Вместо двух столбцов по три строки образовалось три строки по два столбца.
#
# drop — метод используется для возвращения нового массива с удаленным N — числом элементов с
# начала массива, пример:
# a = [1,2,3,4,5,"bingo"]
# a.drop(3) #=> [4, 5, "bingo"]
# a.drop(a.size-1) #=> ["bingo"]
# a #=> [1, 2, 3, 4, 5, "bingo"]
#
# compact — данный метод позволяет удалить все элементы массив значение которых nil, пример:
# a = []
# a[0] = 1 #=> 1
# a[5] = 2 #=> 2
# a #=> [1, nil, nil, nil, nil, 2]
# a.compact #=> [1, 2]
# a #=> [1, nil, nil, nil, nil, 2]
# a.compact! #=> [1, 2]
# a #=> [1, 2]
#
# take — сей метод получает в качестве аргумента число N и возвращет N — первых элементов
# массива, пример:
# [1,5,6,7,10].take(3) #=> [1, 5, 6] | true |
0e66427fb19d1b582bdf5dae9793fe350c152be9 | Ruby | egrueter-dev/Other-challenges | /ab_check.rb | UTF-8 | 534 | 3.984375 | 4 | [] | no_license | #A/B_Check.rb
# Return the string true if the characters a and b are
# separated by exactly 3 places anywhere in the string at
# least once (ie. "lane borrowed" would result in true
# because there is exactly three characters between a and b).
# Otherwise return the string false.
def ABCheck(str)
i = 0
while i < str.length
if str[i] == 'a' && str[i+4] == 'b'
return "true"
elsif str[i] == 'b' && str[i+4] == 'a'
return "true"
end
i += 1
end
return "false"
end
# occurences("a#asg#sdfg#d##")
| true |
16b9a5c5b528d21c81545c5c9c5849d2965da558 | Ruby | emilyjspencer/student-directory | /directory.rb | UTF-8 | 3,190 | 4.34375 | 4 | [] | no_license | @students = [] # an empty array accessible to all methods
def print_menu
puts "1. Input the students"
puts "2. Show the students"
puts "3. Save the list to students.csv"
puts "4. Load the list of students from students.csv"
puts "9. Exit" # 9 because we'll be adding more items
end
def interactive_menu
loop do # set up a loop
print_menu
process(STDIN.gets.chomp)
end
end
def process(selection)
case selection
when "1"
input_students
when "2"
show_students
when "3"
save_students
when "4"
load_students
when "9"
exit
else
puts "I don't know what you mean, try again"
end
end
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
# create an empty array
name = STDIN.gets.chomp # name stored in variable
while !name.empty? do # set up while loop
# while the name is not empty, repeat this code
# add the student hash to the array
@students << {name: name, cohort: :november}
puts "Now we have #{@students.count} students"
# get another name from the user
name = STDIN.gets.chomp
end
@students # Print the students array - with their names and cohorts
end
def show_students
print_header
print_student_list
print_footer
end
def print_header
puts "The students of Villains Academy"
puts "-------------"
end
def print_student_list # Passing our students variable as students argument because
@students.each do |student| # methods don't have access to the local variables
puts "#{student[:name]} (#{student[:cohort]} cohort)" # defined outside them - but we are no longer only passing names
end
end
# renamed argument names to students because we are no longer passing
def print_footer # only names - but the methods still don't
puts "Overall, we have #{@students.count} great students" # have access to the
# we could also use students.length # students variable defined at the top
end
def save_students
# open the file for writing
file = File.open("students.csv", "w")
# iterate over the array of students
@students.each do |student|
student_data = [student[:name], student[:cohort]]
csv_line = student_data.join(",")
file.puts csv_line
end
file.close
end
def load_students(filename = "students.csv") # this method allows the user to
file = File.open(filename, "r") # load data from a file upon startup
file.readlines.each do |line| # It accepts the filename as an argument
name, cohort = line.chomp.split(',') # Without this method - one is unable to type
@students << {name: name, cohort: cohort.to_sym} # ruby directory.rb students csv
end
file.close
end
def try_load_students
filename = ARGV.first # first argument from the command line
return if filename.nil? # get out of the method if it isn't given
if File.exists?(filename) # if it exists
load_students(filename)
puts "Loaded #{@students.count} from #{filename}"
else # if it doesn't exist
puts "Sorry, #{filename} doesn't exist."
exit # quit the program
end
end
try_load_students
interactive_menu
| true |
19ac706d5ef58e5521097ad433c1cfe71680dab6 | Ruby | phebal/matasano-crypto-ruby | /s2c12.rb | UTF-8 | 1,706 | 3.21875 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'pry'
require 'openssl'
require 'base64'
require './cryptlib.rb'
key = random_bytes(16)
target = Base64.decode64('Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK')
def encryption_oracle(msg, key, padding)
padded_msg = padding + msg
encrypt_ecb(padded_msg, key)
end
def find_oracle_blocks_by_hamming(msg, key)
(4..32).map do |size|
padding = 'A' * (size * 3)
canditate = encryption_oracle(msg, key, padding)
score = hamming_distance_for_chunks(canditate, size)
[score, size]
end.sort_by {|o| o[0] }
end
def find_oracle_blocks_by_repeats(msg, key)
(4..32).map do |size|
padding = 'A' * size * 2
canditate = encryption_oracle(msg, key, padding)
score = find_repeating_blocks(canditate, size)
[score, size]
end.sort_by {|o| o[0] }
end
def guess_block_size(msg, key)
block_guesses = find_oracle_blocks_by_hamming(msg, key)
block_guesses[0..1].sort_by {|o| o[1] }.first[1]
end
def check_if_ecb(target, key, size)
padding = 'A' * size * 2
padded_crypt = encryption_oracle(target, key, padding)
raise "Not ECB" if find_repeating_blocks(padded_crypt, size) == 0
end
def oracle_dictionary(key)
@dictionary ||= 128.times.inject({}) do |h, num|
msg = 'A' * (key.length - 1) + num.chr
crypt = encrypt_ecb(msg, key)[0..key.length - 1]
h[crypt] = num.chr
h
end
end
def break_cypher(msg, key, size)
chunk = msg.length.times.map do |i|
padded_msg = 'A' * (size - 1) + msg[i]
crypt = encrypt_ecb(padded_msg, key)[0..size - 1]
oracle_dictionary(key)[crypt]
end.join
end
block_size = guess_block_size(target, key)
puts "Selected block size of: #{block_size}"
check_if_ecb(target, key, block_size)
puts break_cypher(target, key, block_size)
| true |
e1a46166470adc2f152377579e5fe124173f4d71 | Ruby | DamonClark/mystuff | /calculatorex4.rb | UTF-8 | 285 | 3.328125 | 3 | [] | no_license | #How many cases are in Sugar?
VSA = 16
Support = 9
Open = VSA + Support
puts Open
#How many cases are in my Sugar?
MySupport = 2
MyAwaitingResponce = 8
MyCases = MySupport + MyAwaitingResponce
puts
# A string is how you make something that your program might give to a human.
| true |
e8075b34c88587ef2ab9f1586f5238a5b05d01b6 | Ruby | yyytuit/ruby_gold | /弱い問題/26.rb | UTF-8 | 727 | 2.84375 | 3 | [] | no_license | オブジェクトのマーシャリングについて、適切な記述を全て選びなさい。(複数選択)
1.IOクラスのオブジェクトはマーシャリングできない。
2.特異メソッドを持つオブジェクトはマーシャリングできない。
3.ユーザが作成したオブジェクトはマーシャリングできない。
4.無名のクラスやモジュールはマーシャリングできない。
答え1,2,4
システムの状態を保持するオブジェクト(IO、File、Dir、Socket)
や特異メソッドを定義したオブジェクトは、マーシャリングできません。また、無名のクラスやモジュールもマーシャリングできません。
| true |
81a514572d30ac78c5614191edeb67a137740ec6 | Ruby | kwgt/envlog | /lib/envlog/schema.rb | UTF-8 | 805 | 2.515625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env ruby
# coding: utf-8
#
# Environemnt data logger
#
# Copyright (C) 2020 Hiroshi Kuwagata <kgt9221@gmail.com>
#
require "yaml"
require "json_schemer"
module EnvLog
module Schema
using DeepFreezer
class << self
def read(path)
data = YAML.load_file(path)
data.keys.each {|key| data[key.to_sym] = data.delete(key)}
data.deep_freeze
@schema = data
end
def [](key)
raise("schema data not read yet") if not @schema
return @schema[key]
end
def validate(key, data)
raise("schema data not read yet") if not @schema
sch = JSONSchemer.schema(@schema[key])
return sch.validate(data).to_a
end
def valid?(key, data)
return validate(key, data).empty?
end
end
end
end
| true |
b55d105584c6343f111522e6e089d74302a07b59 | Ruby | lionellionel/tealeaf_prep_course | /intermediate_quiz.ex9.rb | UTF-8 | 682 | 3.34375 | 3 | [] | no_license | munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
age_groups = { kid: (0..17), adult: (18..64), senior: (65..150) }
cheese = munsters.each_pair do |k,v|
case v["age"]
when age_groups[:kid]
munsters[k][:age_group] = "kid"
when age_groups[:adult]
munsters[k][:age_group] = "adult"
when age_groups[:senior]
munsters[k][:age_group] = "senior"
else
munsters[k][:age_group] = "dead"
end
end
puts munsters
puts cheese
| true |
335465c723a16141cb387983b4a11939f7de21f3 | Ruby | shelleyyz/WDi28-Homework | /zabrina_lagamayo/week_04/day_04/main.rb | UTF-8 | 1,738 | 2.6875 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
require 'pry'
require 'youtube_embed'
# remember Create Read Update Delete
get '/' do
erb :home
end
get '/instruments' do
@instruments = query_db 'SELECT * FROM instruments'
erb :instruments_index
end
get '/instruments/new' do
erb :instruments_new
end
post '/instruments' do
query_db "INSERT INTO instruments (name, family, video) VALUES ('#{params[:name]}','#{params[:family]}', '#{params[:video]}')"
binding.pry
redirect to('/instruments')
end
get '/instruments/:id' do
@instrument = query_db "SELECT * FROM instruments WHERE id = #{params[:id]} "
@url = query_db "SELECT video FROM instruments WHERE id = #{params[:id]} "
@video = YoutubeEmbed::Video.new("#{@url}")
@instrument = @instrument.first
erb :instruments_show
end
get '/instruments/:id/edit' do
@instrument = query_db "SELECT * FROM instruments WHERE id=#{params[:id]}"
@url = query_db "SELECT video FROM instruments WHERE id = #{params[:id]} "
@video = YoutubeEmbed::Video.new("#{@url}")
@instrument = @instrument.first
# binding.pry
erb :instruments_edit
end
#Update
post '/instruments/:id' do
update = "UPDATE instruments SET name= '#{params[:name]}', family = '#{params[:family]}', video = '#{params[:video]}' WHERE id=#{params[:id]}"
# binding.pry
query_db update
redirect to("/instruments/#{params[:id]}")
end
#delete
get '/instruments/:id/delete' do
query_db "DELETE FROM instruments WHERE id=#{ params[:id]}"
redirect to('/instruments')
end
def query_db(sql_statement)
db = SQLite3::Database.new 'database.sqlite3'
db.results_as_hash = true
results = db.execute sql_statement
puts sql_statement
db.close
results
end
| true |
2390ddcb558f751e5711e29be85dde80c050c858 | Ruby | RomanADavis/challenges | /euler/ruby/solved/problem_set(1-25)/problem21/solutions/solution.rb | UTF-8 | 381 | 3.609375 | 4 | [] | no_license | def sum_of_proper_divisors(n)
divisors = [1]
(2..((n**0.5).to_i)).each do |candidate|
divisors += [candidate, n / candidate] if n % candidate == 0
end
divisors.uniq.inject(:+)
end
def amicable?(n)
n == sum_of_proper_divisors(sum_of_proper_divisors(n)) && n != sum_of_proper_divisors(n)
end
puts (1...10_000).inject(0) {|total, n| amicable?(n) ? total + n : total}
| true |
6d44cfd8b99f35c25f86b6f0791492a4bc1e1ddf | Ruby | stefanos1316/Rosetta_Code_Data_Set | /tasks/concurrent-computing/ruby/concurrent-computing.rb | UTF-8 | 194 | 2.84375 | 3 | [
"CC0-1.0"
] | permissive |
(0..1000000).each do |i|
%w{Enjoy Rosetta Code}.map do |x|
Thread.new do
sleep 0.001
puts "#{i} #{x}"
end
end.each do |t|
t.join
end
end
| true |
760ea2e531db08522c51c86b92ca4cf1ad58e51e | Ruby | fcofdez/biimail | /app/models/repository.rb | UTF-8 | 243 | 2.640625 | 3 | [] | no_license | class Repository
def initialize
@repositories ||= {}
end
def register(type, repository)
repositories[type] = repository
end
def repositories
@repositories ||= {}
end
def for(type)
repositories[type]
end
end
| true |
3d04eff435f2bff48081e33c344e09b68f33d4ab | Ruby | antman999/ruby-oo-object-relationships-kickstarter-lab-nyc01-seng-ft-042020 | /lib/backer.rb | UTF-8 | 509 | 3 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Backer
attr_accessor :name
def initialize(name)
@name = name
end
def back_project(project)
ProjectBacker.new(project, self)
# create a project backer
# connect the project with the backer
end
def backed_projects
projects_backed = ProjectBacker.all.select do |project|
project.backer == self
end
projects_backed.map do |project_backed|
project_backed.project
end
end
end | true |
176e53c270d6ba01e253a8674735db69aa33f9bd | Ruby | jmartenstein/streetfood | /server/streetfood.rb | UTF-8 | 3,136 | 2.515625 | 3 | [] | no_license | #!/usr/bin/ruby
require 'sinatra'
require 'haml'
require 'compass'
require 'active_support/core_ext/integer/inflections'
require './model/stop.rb'
require './model/truck.rb'
require './model/location.rb'
configure do
Compass.configuration do |config|
config.project_path = File.dirname(__FILE__)
config.sass_dir = '/../static/sass'
end
set :sass, Compass.sass_engine_options
set :views, File.dirname(__FILE__) + '/../static'
set :public, File.dirname(__FILE__) + '/../static'
end
#if (settings.environment = "development") {
# root_url = "http://localhost:4567"
#}
#else {
# root_url = "http://www.lunchonfourwheels.com"
#}
#root_url = "http://" + request.host + ":" + request.port
helpers do
def base_url
@base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}"
end
def page_text
@page_text = {
'title' => 'Lunch on Four Wheels',
'sub-title' => 'a seattle street food directory',
'footer-text' => '(c) Justin Martenstein, 2011',
'footer-links' => {
'about' => 'about',
}
}
end
def global_helper
base_url; page_text
end
end
before do
global_helper
end
### Miscellaneous Routes ###
get '/' do
redirect '/today'
end
get '/stylesheets/:name.css' do
content_type 'text/css', :charset => 'utf-8'
scss( :"sass/#{params[:name]}", Compass.sass_engine_options )
end
get '/about' do
haml :about
end
# test page for Blueprint CSS grids
get '/test' do
haml :test, :layout => false
end
### By Neighborhood / Location / Stop ###
get '/neighborhoods' do
haml :neighborhoods
end
get '/neighborhood/:neighborhood' do | hood |
@neighborhood = hood
haml :neighborhood
end
get '/location/:name/edit' do | name |
@location = Location.find_by_name(name)
@selected_hood = @location.neighborhood
@neighborhoods = Neighborhood.all
haml :edit_location
end
post '/location/:name/edit' do | name |
@location = Location.find_by_name(name)
@neighborhood = Neighborhood.find_by_name(params[ :location_hood ])
@location.name = params[ :location_name ]
@location.notes = params[ :location_notes ]
@location.neighborhood = @neighborhood
@location.save
redirect "/neighborhood/#{@neighborhood.name}"
end
### By Truck ###
get '/trucks' do
haml :trucks
end
get '/truck/:truck_name' do | name |
@truck = Truck.find_by_name(name)
@object = @truck
haml :truck
end
### By Schedule / Date ###
get '/today' do
@day = Date.today
unsorted_stops = Stop.by_date(@day)
@stops = unsorted_stops.sort_by{ |a| [ a.location.neighborhood.distance, a.location.neighborhood.name, a.location.name ] }
haml :today
end
get '/today\s:num' do | num |
@day = Date.today + num.to_i
unsorted_stops = Stop.by_date(@day)
@stops = unsorted_stops.sort_by{ |a| [ a.location.neighborhood.distance, a.location.neighborhood.name ] }
haml :today
end
get '/this_week' do
@num = 0
haml :this_week
end
get '/this_week\s:num' do | num |
@num = num
haml :this_week
end
get '/tomorrow' do
redirect '/today+1'
end
| true |
066fb3b6fea7b359b38c0f8dcce6b59bda049c8a | Ruby | iMears/ruby_practice | /nick1.rb | UTF-8 | 259 | 3.8125 | 4 | [] | no_license | class Personal_chef
def make_milkshake(flavor)
puts("making the milkshake #{flavor}.")
end
def make_eggs(quantity)
puts("making #{quantity} eggs for you sir..")
end
end
frank = Personal_chef.new
frank.make_milkshake("chocolate")
frank.make_eggs(9) | true |
8208a3202b8ac54c04fcfce98a08d78ef53b398c | Ruby | 343334/pokemon-webhook | /lib/pokedex.rb | UTF-8 | 780 | 3.5 | 4 | [] | no_license | require 'json'
class Pokedex
DATAFILE = 'lib/pokemon.json'
def initialize (id=0)
file = File.read(DATAFILE)
@@dex = JSON.parse(file)
@current = id
end
def show
puts @@dex
end
def find (id=0)
if id.is_a? String
p = @@dex.select {|k,v| v['name'].downcase==id.downcase}
@current = p.keys[0].to_i
else
@current = id.to_i
end
self
end
def name
begin
return @@dex[@current.to_s]['name']
rescue => e
puts e.inspect
puts e.backtrace
return false
end
end
def id
begin
return @current.to_i
rescue => e
puts e.inspect
puts e.backtrace
return false
end
end
end
#dex = Pokedex.new
#puts dex.find(149).name
#puts dex.find('Dragonite').id
| true |
6f069a7e5615a7387658cf4333bc95aa7b12a425 | Ruby | hariskov/ruby-fi | /databaseConfig.rb | UTF-8 | 218 | 2.578125 | 3 | [] | no_license | require 'sequel';
class DatabaseConfig
attr_reader :table;
def initialize()
db = Sequel.sqlite;
db.create_table :fibonacci do
primary_key :id
String :contents
end
@table = db[:fibonacci];
end
end
| true |
6eaf6379b4415e947491b1d42da6a9ec4fc3a5f6 | Ruby | lev18d/FamilyMosaic | /FamilyMosaic/app/helpers/application_helper.rb | UTF-8 | 12,540 | 2.640625 | 3 | [] | no_license | module ApplicationHelper
# Common helpers sit under lib/helpers
include TextFormattingHelper
def bootstrap_flash_class(flash_type)
{ success: 'alert-success',
error: 'alert-danger',
alert: 'alert-warning',
notice: 'alert-info'
}[flash_type.to_sym] || flash_type.to_s
end
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
# Create a image_tag or video_tag for the file and link_to
# the path of the path_file
def image_or_video (file)
if ["image/jpeg", "image/gif", "image/png", "image/jpg"].include?(file.file_content_type)
image_tag(file.file.url)
elsif ["video/mp4", "video/avi", "video/mpeg", "video/x-ms-wmv", "video/x-flv"].include?(file.file_content_type)
video_tag(file.file.url, controls: true)
end
end
#*******************Picture sizing****************************************************
# Calculate height for div (picholder) in a post which include pictures (two for now)
# take consideration of the side length and gap between the pictures
# Return an array containing two hash that has {:name, :div_w, :div_h, :left, :file}
def size_for_two(pics, side_length, pic_gap)
w0 = pics[0].dimensions[0]
w1 = pics[1].dimensions[0]
h0 = pics[0].dimensions[1]
h1 = pics[1].dimensions[1]
# if W, place one on top of another
if three_by_one(w0, h0) || three_by_one(w1, h1)
div_h0 = div_h1 = (side_length / 3.0).round
div_w0 = div_w1 = side_length
div_left0 = div_left1 = div_top0 = 0
div_top1 = div_h0 + pic_gap
outer_h = div_h0 + div_h1 + pic_gap
# else, place one beside another
else
div_h0 = div_h1 = side_length / 2
div_w0 = div_w1 = side_length / 2 - pic_gap / 2
div_left0 = div_top0 = div_top1 = 0
div_left1 = div_w0 + pic_gap
outer_h = div_h0
end
temp_h0 = one_image_fit(w0, h0, div_w0, div_h0)
temp_h1 = one_image_fit(w1, h1, div_w1, div_h1)
img_w0, img_h0, img_left0, img_top0 =\
temp_h0[:img_w], temp_h0[:img_h], temp_h0[:img_left], temp_h0[:img_top]
img_w1, img_h1, img_left1, img_top1 =\
temp_h1[:img_w], temp_h1[:img_h], temp_h1[:img_left], temp_h1[:img_top]
return [{name: pics[0].file_file_name, outer_h: outer_h,\
div_w: div_w0, div_h: div_h0, div_left: div_left0, div_top: div_top0,\
img_w: img_w0, img_h: img_h0, img_left: img_left0, img_top: img_top0, file: pics[0]},
{name: pics[1].file_file_name, outer_h: outer_h,\
div_w: div_w0, div_h: div_h0, div_left: div_left1, div_top: div_top1,\
img_w: img_w1, img_h: img_h1, img_left: img_left1, img_top: img_top1, file: pics[1]}]
end
# Calculate height for div (picholder) in a post which include pictures (three for now)
# make sure width is 470px
# Use "primary pic" like fb has. "primary pic" is the first pic selected.
# Follow the priciple facebook has - display the most of the pictures
def size_for_three(pics, side_length, pic_gap)
w0 = pics[0].dimensions[0]
w1 = pics[1].dimensions[0]
w2 = pics[2].dimensions[0]
h0 = pics[0].dimensions[1]
h1 = pics[1].dimensions[1]
h2 = pics[2].dimensions[1]
wh_pairs = [[w0, h0], [w1, h1], [w2, h2]]
# if HH or WW, primary pic will be displayed to the leftmost or topmost,
# however, the its space will not be larger.
# if WW
if two_by_one_a(wh_pairs)
# since number is assigned with value rather than reference, I can do this.
# otherwise, I might need div_w0, div_w1, div_w2 = 470, 470, 470
div_w0 = div_w1 = div_w2 = side_length
div_h0 = div_h1 = div_h2 = (side_length / 3.0).floor - 1
div_top0, div_top1, div_top2 = 0, div_h0 + pic_gap, div_h0 * 2 + pic_gap * 2
div_left0 = div_left1 = div_left2 = 0
# calculate the height, width image for each image depends on their ratio
temp_h0 = set_img_pos_for_three_WW(wh_pairs[0], side_length)
temp_h1 = set_img_pos_for_three_WW(wh_pairs[1], side_length)
temp_h2 = set_img_pos_for_three_WW(wh_pairs[2], side_length)
# if HH
elsif two_by_one_a([[h0, w0], [h1, w1], [h2, w2]])
div_w0 = div_w1 = div_w2 = (side_length / 3.0).floor - 1
div_h0 = div_h1 = div_h2 = side_length
div_top0 = div_top1 = div_top2 = 0
div_left0, div_left1, div_left2 = 0, div_w0 + pic_gap, div_w0 * 2 + pic_gap * 2
temp_h0 = set_img_pos_for_three_HH(wh_pairs[0], side_length)
temp_h1 = set_img_pos_for_three_HH(wh_pairs[1], side_length)
temp_h2 = set_img_pos_for_three_HH(wh_pairs[2], side_length)
# if hh or ww are not strong, the layout of the pics depends on the primary pic,
# whereas the primary pic will get the largest space.
else
# the primary pic is a wide pic
if (w0 >= h0)
# w
if three_by_one(w0, h0)
div_w0, div_h0 = side_length, side_length / 2
# W
else
div_w0, div_h0 = side_length, side_length / 3 * 2
end
div_left0 = div_top0 = 0
div_w1 = side_length - side_length / 2 - pic_gap / 2
div_h1 = side_length - div_h0 - pic_gap
div_w2, div_h2 = div_w1, div_h1
div_left1, div_top1 = 0, div_h0 + pic_gap
div_left2, div_top2 = div_w1 + pic_gap, div_h0 + pic_gap
# the primary pic is a high pic
else
# h
if three_by_one(h0, w0)
div_w0, div_h0 = side_length / 2, side_length
# H
else
div_w0, div_h0 = side_length / 3 * 2, side_length
end
div_left0 = div_top0 = 0
div_w1 = side_length - div_w0 - pic_gap
div_h1 = side_length - side_length / 2 - pic_gap / 2
div_w2, div_h2 = div_w1, div_h1
div_left1, div_top1 = div_w0 + pic_gap, 0
div_left2, div_top2 = div_w0 + pic_gap, div_h1 + pic_gap
end
temp_h0 = one_image_fit(w0, h0, div_w0, div_h0)
temp_h1 = one_image_fit(w1, h1, div_w1, div_h1)
temp_h2 = one_image_fit(w2, h2, div_w2, div_h2)
end
img_w0, img_h0, img_left0, img_top0 =\
temp_h0[:img_w], temp_h0[:img_h], temp_h0[:img_left], temp_h0[:img_top]
img_w1, img_h1, img_left1, img_top1 =\
temp_h1[:img_w], temp_h1[:img_h], temp_h1[:img_left], temp_h1[:img_top]
img_w2, img_h2, img_left2, img_top2 =\
temp_h2[:img_w], temp_h2[:img_h], temp_h2[:img_left], temp_h2[:img_top]
return [{name: pics[0].file_file_name, div_w: div_w0, div_h: div_h0, div_left: div_left0,\
div_top: div_top0, img_left: img_left0, img_top: img_top0,\
img_w: img_w0, img_h: img_h0, file: pics[0]},
{name: pics[1].file_file_name, div_w: div_w1, div_h: div_h1, div_left: div_left1,\
div_top: div_top1, img_left: img_left1, img_top: img_top1,\
img_w: img_w1, img_h: img_h1, file: pics[1]},
{name: pics[2].file_file_name, div_w: div_w2, div_h: div_h2, div_left: div_left2,\
div_top: div_top2, img_left: img_left2, img_top: img_top2,\
img_w: img_w2, img_h: img_h2, file: pics[2]}]
end
# Special function for now to help add the plus sign
def size_for_four_sqr_special(pics, side_length, pic_gap)
w0 = pics[0].dimensions[0]
w1 = pics[1].dimensions[0]
w2 = pics[2].dimensions[0]
h0 = pics[0].dimensions[1]
h1 = pics[1].dimensions[1]
h2 = pics[2].dimensions[1]
wh_pairs = [[w0, h0], [w1, h1], [w2, h2]]
div_w0 = div_w1 = div_w2 = div_h0 = div_h1 = div_h2 = side_length / 2 - pic_gap / 2
div_left0 = div_left2 = 0
div_top0 = div_top1 = 0
div_left1 = div_top2 = side_length / 2 + pic_gap / 2
temp_h0 = one_image_fit(w0, h0, div_w0, div_h0)
temp_h1 = one_image_fit(w1, h1, div_w1, div_h1)
temp_h2 = one_image_fit(w2, h2, div_w2, div_h2)
img_w0, img_h0, img_left0, img_top0 =\
temp_h0[:img_w], temp_h0[:img_h], temp_h0[:img_left], temp_h0[:img_top]
img_w1, img_h1, img_left1, img_top1 =\
temp_h1[:img_w], temp_h1[:img_h], temp_h1[:img_left], temp_h1[:img_top]
img_w2, img_h2, img_left2, img_top2 =\
temp_h2[:img_w], temp_h2[:img_h], temp_h2[:img_left], temp_h2[:img_top]
return [{name: pics[0].file_file_name, div_w: div_w0, div_h: div_h0, div_left: div_left0,\
div_top: div_top0, img_left: img_left0, img_top: img_top0,\
img_w: img_w0, img_h: img_h0, file: pics[0]},
{name: pics[1].file_file_name, div_w: div_w1, div_h: div_h1, div_left: div_left1,\
div_top: div_top1, img_left: img_left1, img_top: img_top1,\
img_w: img_w1, img_h: img_h1, file: pics[1]},
{name: pics[2].file_file_name, div_w: div_w2, div_h: div_h2, div_left: div_left2,\
div_top: div_top2, img_left: img_left2, img_top: img_top2,\
img_w: img_w2, img_h: img_h2, file: pics[2]}]
end
# fit one image into the a given box,
# the box has starting pos x=0 and y=0
def one_image_fit(w, h, box_w, box_h)
# # a wide box
# if (box_w >= box_h)
# higher
if (h.to_f / w) >= (box_h.to_f / box_w)
m = box_w.to_f / w
img_h = (m * h).round
img_w = box_w
img_top = img_left = 0
# fatter
else
m = box_h.to_f / h
img_h = box_h
img_w = (m * w).round
img_top = 0
img_left = - (img_w - box_w) / 2
end
# # a high box
# else
# end
return {img_w: img_w, img_h: img_h, img_left: img_left, img_top: img_top}
end
# Return the width, height, left position and top position for the image with the
# actual width and height given by the pair. The function currently only works for
# three photo positioning in the case of WW
def set_img_pos_for_three_WW(pair, side_length)
if three_by_one(pair[0], pair[1])
# if ratio at least 3, height is set to
height = (side_length / 3.0).floor - 1
m = height.to_f / pair[1]
reserve_w = false
else
# if ratio smaller than 3, width is set to
width = side_length.to_f
m = width / pair[0]
reserve_w = true
end
img_h, img_w = (pair[1] * m).round, (pair[0] * m).round
if reserve_w
img_left = 0
# fb set top to 0 in this case
img_top = 0
# img_top = - ((img_h - 155) / 2).floor
else
img_top = 0
img_left = - ((img_w - side_length) / 2.0).floor
end
return {img_w: img_w, img_h: img_h, img_left: img_left, img_top: img_top}
end
## Maybe combine set_img_pos_for_three_HH and set_img_pos_for_three_WW.
# Return the width, height, left position and top position for the image with the
# actual width and height given by the pair. The function currently only works for
# three photo positioning in the case of HH
def set_img_pos_for_three_HH(pair, side_length)
if three_by_one(pair[1], pair[0])
# if ratio at least 3, width is set to
# thin one
width = (side_length / 3.0).floor - 1
m = width.to_f / pair[0]
reserve_h = false
else
# if ratio smaller than 3, heigth is set to
# fatter one
height = side_length.to_f
m = height / pair[1]
reserve_h = true
end
img_h, img_w = (pair[1] * m).round, (pair[0] * m).round
if reserve_h
width = (side_length / 3.0).floor - 1
img_left = - ((img_w - width) / 2.0).floor
img_top = 0
else
img_top = 0
img_left = 0
end
return {img_w: img_w, img_h: img_h, img_left: img_left, img_top: img_top}
end
# return a boolean
# return true if at least two of the pairs in array a have their first number at least
# twice as big as their second number.
# a = [pair1, pair2, pair3] where each pair is either [h,w] or [w,h].
def two_by_one_a(a)
counter = 0
a.each do |pair|
if (pair[0] >= pair[1] * 2)
counter += 1
end
if (counter >= 2)
return true
end
end
return false
end
# check if the x, y ratio is at least 3
def three_by_one(x, y)
if (x / y) >= 3
return true
else
return false
end
end
# separate videos and pictures
def pic_and_vid_separator(pvs)
pics = []
vids = []
pvs.each do |file|
if ["image/jpeg", "image/gif", "image/png", "image/jpg"].include?(file.file_content_type)
pics.push(file)
elsif ["video/mp4", "video/avi", "video/mpeg", "video/x-ms-wmv", "video/x-flv"].include?(file.file_content_type)
vids.push(file)
end
end
return {pics: pics, vids: vids}
end
end
| true |
b0b542d709745dd07f0734845961f7b35381da55 | Ruby | groovad/dawn-ce | /script/backup_db.rb | UTF-8 | 2,849 | 2.578125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | # -*- coding: utf-8 -*-
# DBからバックアップファイルを作るスクリプト
# rakeから使う。
$:.unshift(File.join(File.expand_path('.'), 'src'))
require 'find'
require 'pathname'
require 'optparse'
require 'sequel'
require 'sequel/extensions/inflector'
require 'unlight'
OUTPUT = false
SEPARATOR = ','
ORIG = true
# 漢字取り出しに使う物だけバックアップ
FILE_LIST = /Achievement\z|ActionCard\z|AvatarItem\z|AvatarPart\z|Channel\z|CharaCardStory\z|CharaCard\z|CharaRecord\z|Charactor\z|Dialogue\z|EquipCard\z|EventCard\z|Feat\z|PassiveSkill\z|QuestLand\z|QuestMap\z|Quest\z|RealMoneyItem\z|TreasureData\z|WeaponCard/
opt = OptionParser.new
# オプションがjの時日本語用のDBに接続L
#
opt.on('-j', '--japanese', '日本語版で作る') do |v|
if v
end
end
opt.on('-s', '--sandbox', 'sandboxをのバックアップファイルを作る') do |v|
if v
ORIG = false
#mysql設定
# SB_MYSQL_CONFIG = {
# :host =>"10.162.66.17",
# :port =>3306,
# :user => "unlight",
# :password =>"ul0073",
# :database =>"unlight_db",
# :encoding => 'utf8',
# :max_connections => 5,
# }
# BDB = Sequel.mysql(nil,SB_MYSQL_CONFIG)
puts 'SBDBにした上書き.'
end
end
opt.parse!(ARGV)
def csv_output(dataset, include_column_titles = true)
n = dataset.naked
cols = n.columns
cols.reject! { |c| (c =~ /_en\z|_scn\z|_tcn\z_fr\z/) }
tsv = ''
tsv << "#{cols.join(SEPARATOR)}\r\n" if include_column_titles
n.each do |r|
a = ''
cols.collect { |c| r[c] }.each { |f| a << "\"#{f}\"#{(SEPARATOR)}" }
a << "\r\n"
tsv << a
end
tsv
end
system('rm ./data/backup/*.csv')
Find.find('./src/model') do |f|
# モデル以下のファイルを全部require
next if File.directory?(f)
Find.prune if f.split('/').size > 4
req = f.gsub('./src/', '')
m = f.gsub('./src/', '')
# モデル名を取得する
m = m.gsub('model/', '').gsub('.rb', '')
m = m.camelize
# クラス名から一つずつcsvを取り出す
next unless FILE_LIST.match?(m)
next if /^[^A-Z]/.match?(m)
require "#{req}"
puts "BackUp #{m}"
filename = "./data/backup/#{m}_#{Time.now.strftime("%y%m%d")}"
oldname = "./data/backup/old/#{m}_#{Time.now.strftime("%y%m%d")}"
doc = <<-END
Unlight::#{m}.db = BDB unless ORIG
file = Pathname.new("#{filename}.csv")
i = 0
while file.exist?
ofile = Pathname.new("#{oldname}.csv")
while ofile.exist?
ofile = Pathname.new("#{oldname}_"+i.to_s+".csv")
i+=1
end
File.rename(file, ofile)
end
if Unlight::#{m}.superclass == Sequel::Model
puts "Create BackUpFile"+file.to_s
file.open('w') {|f| f.puts csv_output(Unlight::#{m})}
end
END
# puts doc if OUTPUT
eval doc
end
| true |
2fa2f5200a66949e4cdd6d0a67ea86c75d4d7650 | Ruby | bastianorte/actividad11 | /2 ciclos/ejercicio8.rb | UTF-8 | 245 | 3.734375 | 4 | [] | no_license | # Generar -utilizando un ciclo iterativo- un string con la siguiente estructura:
# a = '1impar 2par 3impar 4par 5impar 6par 7impar 8par 9impar 10par'
a = 0
10.times do |i|
a += 1
print "#{a}par " if a.even?
print "#{a}impar " if a.odd?
end
| true |
b9eb0a2091c1c952bb627dc51ba5b1737b34ef6e | Ruby | BDiumula/Itsa-me-Mario | /exo_03.rb | UTF-8 | 202 | 3.140625 | 3 | [] | no_license | puts "Bonjour, monde!"
#puts "Et avec une voix sexy, ça donne : Bonjour, monde!" --> Mettre en # devant la ligne transforme celle-ci en commentaire. Il n'y a donc que la première ligne qui s'affiche.
| true |
07f4ca755f35da0789911df5bd35d5efc1f62379 | Ruby | google-code/applicationwiki | /base/base_scrap.rb | UTF-8 | 4,953 | 2.625 | 3 | [] | no_license |
# this is some stuff for youthgive specifically that is in base_utils but seems to crash
# it is a mess anyway
#########################################################################
# utilities
# xxx move this
#########################################################################
# dump all an object's attributes for inspection purposes
# creates a div with the specified name to which it appends _# where # is the id of the object
def show_details(object, divname)
#return "foo"
#return nil if !object
if object && @session[:username] && (@session[:username] == "testbrad" || @session[:username] == "testuser" || @session[:username] == "anselm" )
write '<script>var current_status = evenodd; evenodd=true;</script>'
write '<a href="#" class="button" onclick=\'showDiv("' + divname + '_' + object.id.to_s + '"); return false;\'>show details</a>'
write '<div id="' + divname + '_' + object.id.to_s + '" class="db-details">'
write '<a href="#" class="button" onclick=\'hideDiv("' + divname + '_' + object.id.to_s + '"); return false;\'>hide details</a><br>'
write '<table>'
write '<tr class="oddrow"><td><span class="db-details-fieldname">ID</span></td><td> <span class="db-details-fieldvalue">' + object.id.to_s + '</span></td></tr>'
write '<tr class="evenrow"><td><span class="db-details-fieldname">Type</span></td><td> <span class="db-details-fieldvalue">' + object.class.to_s + '</span></td></tr>'
object.class.new.attribute_names.each do |x|
write '<script>evenodd = !evenodd; if (evenodd) document.write(\'<tr class="evenrow">\'); else document.write(\'<tr class="oddrow">\'); </script>'
write '<td><span class="db-details-fieldname">' + x +'</span></td><td> <span class="db-details-fieldvalue">'
write object.send(x)
write '</span> </td></tr>'
end
write '</table></div>'
write '<script>hideDiv("' + divname + '_' + object.id.to_s + '"); evenodd = current_status ;</script>'
end
end
# display a table of alternating style rows
# takes a collection of objects, a list of column-headers space-separated, and a list of corresponding fields space-separated
def zebra_table(objects, headers, fields )
#return ""
return if !objects
hdrs = headers.split("|")
flds = fields.split("|")
write '<script>var current_status = evenodd; evenodd=true;</script>'
write '<thead>'
hdrs.each do |hdr|
if hdr != "Details" || (@session[:username] && (@session[:username] == "testbrad" || @session[:username] == "testuser" || @session[:username] == "anselm" ))
write '<th>' + hdr + '</th>'
end
end
write '</thead><tbody>'
objects.each do |obj|
objtyp = obj.class.to_s
write '<script>evenodd = !evenodd; if (evenodd) document.write(\'<tr class="evenrow">\'); else document.write(\'<tr class="oddrow">\'); </script>'
flds.each do |fld|
if fld == "details"
write '<td valign="center" width="100px">' if @session[:username] && (@session[:username] == "testbrad" || @session[:username] == "testuser" || @session[:username] == "anselm" )
else
write '<td valign="top">'
end
value = obj.send fld if fld != "details"
typ = "String"
typ = value.class.to_s if value
if fld == "depiction" && value && value.length >1
if objtyp == "Bookmark"
write '<a href="/' + obj.title + '"><img src="/' + obj.title + '/.' + obj.title + '.jpg" width="80"></img></a>'
else
write '<img src="' + value +'" border=0 width="40px"/>'
end
elsif typ == "User"
name = value.login
write '<a href="/' + name + '">' + name + '</a>'
elsif fld == "details"
show_details(obj, "details")
elsif fld == "total_donations"
write("$" ) if value
write( value) if value
elsif fld == "name" || fld == "title" || fld == "login"
if objtyp =="Group"
write '<a href="/' + obj.uid + '">' + value + '</a>'
elsif objtyp =="User"
write '<a href="/' + value + '">' + value + '</a>'
elsif objtyp =="Bookmark"
write '<a href="/' + value + '">' + value + '</a>'
elsif objtyp == "Nonpros"
write '<a href="/catalogue/' + obj.id.to_s + '">' + value + '</a>'
else
write value
end
elsif objtyp == "Account" && fld == "ein"
donor = value
if donor
donor = User.find_by_id(donor)
donor = donor.login if donor
else
donor = "anonymous"
end
write donor
else write value if value && !(fld == "selected" && value == "Not Selected") #fld + ": " +
end
# write ' ' + value.type.to_s if value
write '</td>'
end
write '</tr>'
end
write '</tbody>'
write '<script>evenodd = current_status ;</script>'
end
@default_depiction= '/images/cat-glyph.gif'
def user_pic_or_default(user_pic)
def_pic = '/images/cat-glyph.gif' # @default_depiction
def_pic = user_pic if user_pic and user_pic.length >1
return def_pic
end
| true |
ee4a7a7e2f03d7234f94c123c5b9e7c503abb7ed | Ruby | ga-chicago/sinatra-mvc-crud | /controllers/ApplicationController.rb | UTF-8 | 2,181 | 2.578125 | 3 | [] | no_license | # this will take the place of app.rb from now on
# it's the primary class in our app
# note that it inherits from Sinatra Base application
class ApplicationController < Sinatra::Base
require 'bundler'
Bundler.require()
# enable sessions
enable :sessions # yep that's it
# set up db connection
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:database => 'salty_items'
)
# enable cors
register Sinatra::CrossOrigin
configure do
enable :cross_origin
end
set :allow_origin, :any
set :allow_credentials, true
set :allow_methods, [:get, :post, :put, :patch, :delete, :options]
# use some middleware to allow us to process delete/put/patch etc requests
use Rack::MethodOverride # like express, we "use" middleware in Rack-based libraries/frameworks
set :method_override, true
# teach it where views live
set :views, File.expand_path('../../views', __FILE__)
# teach it where static assets live
set :public_dir, File.expand_path('../../public', __FILE__)
# telling the browser what's ok and what's not
options '*' do
puts "options request received"
response.headers['Allow'] = 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
response.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000'
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Authorization, Content-Type, Cache-Control, Accept"
200 #this is the status code & also sends a response
end
get '/' do
# @hey = "hey shilpa with the shoes"
# # binding.pry will pause exectuion and
# # open a REPL where you can mess around in that scope in the code
# # you can inspect variables
# # test out DB queries
# # you can enter ruby statements directly
# # whatever
# # just be sure to type exit when you're done
# # because the client is still waiting for that response
binding.pry
# @hey
redirect '/items'
end
get '/template' do
erb :hello
end
get '*' do
response = ""
404.times { response += "404 "}
response
end
end | true |
d9c97d27f425c57b5697945ee843a4a4a1c69f60 | Ruby | brewster1134/yuyi | /lib/yuyi/cli.rb | UTF-8 | 1,310 | 2.609375 | 3 | [] | no_license | require 'thor'
class Yuyi::Cli < Thor
desc 'list', 'Show all rolls available based on the sources defined in your menu.'
option :menu, :aliases => '-m', :desc => 'Path to your menu file'
def list
Yuyi::Menu.new options[:menu]
# Collect all rolls from all sources
#
rolls = []
Yuyi::Menu.sources.each do |source|
rolls |= source.rolls.keys
end
# alphabatize rolls
rolls = rolls.map(&:to_s).sort
Yuyi.say 'Available Rolls', :type => :success
Yuyi.say '---------------', :type => :success
rolls.each do |roll|
Yuyi.say roll
end
Yuyi.say
end
desc 'version', 'Show the currently running version of yuyi'
def version
say "#{Yuyi::NAME} #{Yuyi::VERSION}"
end
desc 'start', 'Run Yuyi'
option :verbose, :default => false, :aliases => '-v', :type => :boolean, :desc => 'Run in verbose mode'
option :upgrade, :default => false, :aliases => '-u', :type => :boolean, :desc => 'Check for upgrades for rolls on the menu that are already installed'
option :menu, :aliases => '-m', :desc => 'Path to your menu file'
def start
# enable verbose mode if flag is passed
Yuyi.verbose = options[:verbose]
Yuyi.upgrade = options[:upgrade]
Yuyi.menu_path = options[:menu]
Yuyi.start
end
default_task :start
end
| true |
8fe3612a6abb11e7f2973772475af101e03cad4b | Ruby | Andyreyesgo/patrones | /x.rb | UTF-8 | 278 | 3.390625 | 3 | [] | no_license | def xletter2(n)
n.times do |i|
n.times do |j|
if j == n-(i+1)
print "*"
elsif j==i
print "+"
else
print " "
end
end
print "\n"
end
end
xletter2(5) | true |
60d1323ddf1288b307c160c0901d2e4c6efc8eeb | Ruby | raecoo/thinking-sphinx-chinese | /lib/thinking_sphinx/index.rb | UTF-8 | 2,614 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'thinking_sphinx/index/builder'
require 'thinking_sphinx/index/faux_column'
module ThinkingSphinx
# The Index class is a ruby representation of a Sphinx source (not a Sphinx
# index - yes, I know it's a little confusing. You'll manage). This is
# another 'internal' Thinking Sphinx class - if you're using it directly,
# you either know what you're doing, or messing with things beyond your ken.
# Enjoy.
#
class Index
attr_accessor :model, :sources, :delta_object
# Create a new index instance by passing in the model it is tied to, and
# a block to build it with (optional but recommended). For documentation
# on the syntax for inside the block, the Builder class is what you want.
#
# Quick Example:
#
# Index.new(User) do
# indexes login, email
#
# has created_at
#
# set_property :delta => true
# end
#
def initialize(model, &block)
@model = model
@sources = []
@options = {}
@delta_object = nil
end
def fields
@sources.collect { |source| source.fields }.flatten
end
def attributes
@sources.collect { |source| source.attributes }.flatten
end
def name
self.class.name_for @model
end
def self.name_for(model)
model.name.underscore.tr(':/\\', '_')
end
def prefix_fields
fields.select { |field| field.prefixes }
end
def infix_fields
fields.select { |field| field.infixes }
end
def local_options
@options
end
def options
all_index_options = ThinkingSphinx::Configuration.instance.index_options.clone
@options.keys.select { |key|
ThinkingSphinx::Configuration::IndexOptions.include?(key.to_s) ||
ThinkingSphinx::Configuration::CustomOptions.include?(key.to_s)
}.each { |key| all_index_options[key.to_sym] = @options[key] }
all_index_options
end
def delta?
!@delta_object.nil?
end
private
def adapter
@adapter ||= @model.sphinx_database_adapter
end
def utf8?
options[:charset_type] == "utf-8"
end
# Does all the magic with the block provided to the base #initialize.
# Creates a new class subclassed from Builder, and evaluates the block
# on it, then pulls all relevant settings - fields, attributes, conditions,
# properties - into the new index.
#
def initialize_from_builder(&block)
#
end
def sql_query_pre_for_delta
[""]
end
end
end
| true |
0fcd3101670e2dafea2d177408cffb2eda9b7d13 | Ruby | ffaker/ffaker | /lib/ffaker/lorem_ua.rb | UTF-8 | 1,168 | 2.890625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
module FFaker
module LoremUA
extend ModuleUtils
extend self
def word
fetch_sample(WORDS)
end
def words(num = 3)
fetch_sample(WORDS, count: num)
end
def sentence(word_count = 7)
elements = words(word_count + rand(0..9))
elements.insert(rand(3..(elements.count - 3)), ',') if elements.count > 10
result = elements.join(' ').gsub(' , ', ', ')
capitalize_ukrainian(+"#{result}#{sentence_type_mark}")
end
alias phrase sentence
def sentences(sentence_count = 3)
(1..sentence_count).map { sentence }
end
alias phrases sentences
def paragraph(sentence_count = 5)
sentences(sentence_count + rand(0..2)).join(' ')
end
def paragraphs(paragraph_count = 3)
(1..paragraph_count).map { paragraph }
end
private
def sentence_type_mark
case rand(0..9)
when 0..7 then '.'
when 8 then '!'
when 9 then '?'
end
end
def capitalize_ukrainian(string)
string[0] = CAPITAL_CHARS[CHARS.index(string[0])] unless CAPITAL_CHARS.include?(string[0])
string
end
end
end
| true |
4da376f0760676fc691ea91a5918f00108c4d322 | Ruby | kconnellmail/ruby_for_metadataists | /ruby/marc_fixes.rb | UTF-8 | 4,852 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | require 'marc'
### Error detection
## Find indicators that are non-numeric
def invalid_indicators?(record)
record.fields.each do |field|
next unless field.class == MARC::DataField
return true unless field.indicator1 =~ /^[0-9 ]$/ && field.indicator2 =~ /^[0-9 ]$/
end
false
end
## Find discrepancies between variable fields and their 880 pairings
def pair_880_errors?(record)
pair_880s = []
linked_fields = []
return false unless record['880']
record.fields.each do |field|
return true if field.tag == '880' && field['6'].nil?
next unless field.tag =~ /^[0-8]..$/ && field.class == MARC::DataField && field['6']
if field.tag == '880'
pair_880s << field['6'].gsub(/^([0-9]{3}-[0-9]{2}).*$/, '\1')
else
linked_fields << "#{field.tag}-#{field['6'].gsub(/^880-([0-9]{2}).*$/, '\1').chomp}"
end
end
pair_880s.delete_if { |x| x =~ /^.*-00/ }
return true if pair_880s.uniq != pair_880s || pair_880s.uniq.sort != linked_fields.uniq.sort
false
end
## List of non-repeatable fields taken from the MARC standard
def non_repeatable_fields
%w[
001
003
005
008
010
018
036
038
040
042
043
044
045
066
100
110
111
130
240
243
245
254
256
263
306
310
357
384
507
514
841
842
844
882
]
end
## Identify records where non-repeatable fields are repeated
def repeatable_field_errors?(record)
field_count = record.fields.group_by(&:tag).map { |key, value| { tag: key, count: value.size } }
nr_fields = field_count.select { |item| non_repeatable_fields.include?(item[:tag]) && item[:count] > 1 }
!nr_fields.empty?
end
## Identify records with empty subfields
def empty_subfields?(record)
record.fields.each do |field|
next unless field.class == MARC::DataField
field.subfields.each do |subfield|
return true if subfield.value =~ /^[[:blank:]]*$/
end
end
false
end
### Record fixes
## Remove empty subfields from DataFields
def empty_subfield_fix(record)
fields_to_delete = []
curr_field = -1
record.fields.each do |field|
curr_field += 1
next unless field.class == MARC::DataField
curr_subfield = 0
subfields_to_delete = []
field.subfields.each do |subfield|
subfields_to_delete.unshift(curr_subfield) if subfield.value.empty? || subfield.value.nil?
curr_subfield += 1
end
subfields_to_delete.each do |i|
record.fields[curr_field].subfields.delete_at(i)
end
fields_to_delete.unshift(curr_field) if record.fields[curr_field].subfields.empty?
end
unless fields_to_delete.empty?
fields_to_delete.each do |i|
record.fields.delete_at(i)
end
end
record
end
## Can delete fields based on tags alone, or with
## optional indicator values provided in arrays
def field_delete(record, tags, indicators = {})
if indicators.empty?
record.fields.delete_if { |field| tags.include? field.tag }
else
ind_1 = indicators[:ind_1]
ind_2 = indicators[:ind_2]
if ind_1 && ind_2
record.fields.delete_if { |field| (tags.include? field.tag) && (ind_1.include? field.indicator1) && (ind_2.include? field.indicator2) }
elsif ind_1
record.fields.delete_if { |field| (tags.include? field.tag) && (ind_1.include? field.indicator1) }
else
record.fields.delete_if { |field| (tags.include? field.tag) && (ind_2.include? field.indicator2) }
end
end
record
end
### Count fields in a record; set :subfields to True to drill down to subfields
def field_count(record, opts = {})
results = {}
if opts[:subfields]
record.fields.each do |field|
tag = field.tag.scrub('')
case tag
when /^00/
results[tag] = 0 unless results[tag]
results[tag] += 1
else
field.subfields.each do |subfield|
key = tag + subfield.code.to_s.scrub('')
results[key] = 0 unless results[key]
results[key] += 1
end
end
end
else
record.fields.each do |field|
tag = field.tag.scrub('')
results[tag] = 0 unless results[tag]
results[tag] += 1
end
end
results
end
f880_errors = []
empty_subfields = []
repeated_fields = []
indicator_errors = []
reader = MARC::Reader.new('./sample.mrc')
reader.each do |record|
f880_errors << record if pair_880_errors?(record)
empty_subfields << record if empty_subfields?(record)
repeated_fields << record if repeatable_field_errors?(record)
indicator_errors << record if invalid_indicators?(record)
end
### Sample fix
test_rec = empty_subfields.first
## before record
puts test_rec
## introduce an empty subfield
test_rec.fields('050').first.subfields[1].value = ''
puts test_rec
## fixes
field_delete(test_rec, %w[902 904])
empty_subfield_fix(test_rec)
## after record
puts test_rec
| true |
a696efb30802ed6e88ce5bcd9e830d8883229a65 | Ruby | albertbahia/wdi_june_2014 | /w02/d05/jon_porras/weekend_assignment/lib/apartment.rb | UTF-8 | 949 | 3.359375 | 3 | [] | no_license | require_relative 'tenant.rb'
class Apartment
attr_reader(:name, :floor, :price, :sqftage, :bedrooms, :bathrooms, :tenants)
def initialize(name, floor, price, sqftage, bedrooms, bathrooms)
@name = name
@floor = floor
@price = price
@sqftage = sqftage
@bedrooms = bedrooms
@bathrooms = bathrooms
@tenants = []
end
def add_tenant(tenant)
if @tenants.length >= @bedrooms
return "Too many tenants!"
else
tenants.push(tenant)
end
end
def info
return "Name: #{name} // Floor: #{floor} Price: #{price} // Square Footage: #{sqftage} // Bedrooms: #{bedrooms} // Bathrooms: #{bathrooms} // Tenants: #{tenants}"
end
def list_tenants
info_string = ""
tenants.each { |tenant|
info_string += ">>Tenant Name: #{tenant.name}"
info_string += " // Tentant Age: #{tenant.age}"
info_string += " // Tenant Gender: #{tenant.gender} // "
}
return info_string
end
end
| true |
e344f29d3dc36fe74bf78e04851ea1bbf2b3907e | Ruby | vbabison/jungle-rails | /spec/user_spec.rb | UTF-8 | 3,264 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
context "Validations" do
it "has all valid properties " do
@user = User.create(firstname:"Alex", lastname: "Lock", email: "alex@lock.com",
password:"123456", password_confirmation: "123456")
@user.validate!
@user.errors.full_messages
end
it "must have a firstname" do
@user = User.create(firstname: nil, lastname: "Lock", email: "alex@lock.com",
password:"123456", password_confirmation: "123456")
expect(@user).to_not be_valid
expect(@user.errors.full_messages).to include("Firstname can't be blank")
end
it "must have lastname" do
@user = User.create(firstname:"Alex", lastname: nil, email: "alex@lock.com",
password:"123456", password_confirmation: "123456")
expect(@user).to_not be_valid
expect(@user.errors.full_messages).to include("Lastname can't be blank")
end
it "must have a email" do
@user = User.create(firstname:"Alex", lastname: "Lock", email: nil,
password:"123456", password_confirmation: "123456")
expect(@user).to_not be_valid
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it "must have unique email" do
@user1 = User.create(firstname:"Alex", lastname: "Lock", email: "alex@lock.com",
password:"123456", password_confirmation: "123456")
@user2 = User.create(firstname:"Bob", lastname: "Lock", email: "alex@lock.com",
password:"123456", password_confirmation: "123456")
expect(@user2.errors.messages[:email]).to eq ["has already been taken"]
end
it "must have a password" do
@user = User.create(firstname:"Alex", lastname: "Lock", email: "alex@lock.com",
password: nil, password_confirmation: "123456")
expect(@user).to_not be_valid
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it "must have a minimun password length of 6" do
@user = User.create(firstname:"Alex", lastname: "Lock", email: "alex@lock.com",
password: "1234", password_confirmation: "1234")
expect(@user).to_not be_valid
expect(@user.errors[:password]).to include("is too short (minimum is 6 characters)")
end
it "must have a password confirmation" do
@user = User.create(firstname:"Alex", lastname: "Lock", email:"alex@lock.com" ,
password:"123456", password_confirmation: nil)
expect(@user).to_not be_valid
expect(@user.errors.full_messages).to include("Password confirmation can't be blank")
end
end
describe '.authenticate_with_credentials' do
it "must have email to sign in" do
@user_register = User.create(firstname:"Alex", lastname: "Lock", email:"alex@lock.com" ,
password:"123456", password_confirmation: "123456")
@user_signin = User.authenticate_with_credentials("alex@lock.com","123456")
expect(@user_register).to eq(@user_signin)
end
end
end | true |
70683379558c0a4c0ade4fe029ae22e2b1d4a484 | Ruby | mrflip/lorkbong | /vendor/wukong/lib/wukong/extensions/pathname.rb | UTF-8 | 597 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | require 'pathname'
class Pathname
# Append path segments and expand to absolute path
#
# file = Pathname(Dir.pwd) / "subdir1" / :subdir2 / "filename.ext"
#
# @param [Pathname, String, #to_s] path path segment to concatenate with receiver
#
# @return [Pathname]
# receiver with _path_ appended and expanded to an absolute path
#
# @api public
def /(path)
(self + path).expand_path
end
def self.[](*vals)
new( File.join(vals) )
end
end
class Subdir < Pathname
def self.[](*vals)
dir = File.dirname(vals.shift)
new(File.join(dir, *vals))
end
end
| true |
e84948b1148ee7002c7235c0a350549bae044a42 | Ruby | thesteady/test-r | /app/models/analyzer.rb | UTF-8 | 421 | 2.71875 | 3 | [] | no_license | class Analyzer
# def new
# @survey_data = survey_data
# end
def run
puts "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"
puts "Running Analyzer!!!!"
puts "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"
output = %x(`ruby lib/r_scripts/hello.rb`)
return output
# run a simple R script
# get the value back,
# print it in the console
# return it to the controller (/save it somewhere)
end
end
| true |
a4a4ba1a12dd1fcb19b25b36d2d039f68b0d2369 | Ruby | goronfreeman/alfred-mixed-case | /generator.rb | UTF-8 | 466 | 3.40625 | 3 | [] | no_license | require "json"
def letter?(look_ahead)
look_ahead.match?(/[[:alpha:]]/)
end
def mixed_case(string, upcase: true)
string.each_char.map do |char|
next char unless letter?(char)
(upcase = !upcase) ? char.upcase : char.downcase
end.join
end
input = ARGV[0].split(" ")
output = input.map { |string| mixed_case(string) }.join(" ")
json =
{ items: [
{
uid: "mixedcase",
title: output,
arg: output
}
] }.to_json
print json
| true |
13b4c7ba403e178fc4f0ad351f5659797706c548 | Ruby | skateonrails/flower_shop_ruby | /app/models/order_input_line.rb | UTF-8 | 558 | 2.84375 | 3 | [] | no_license | # frozen_string_literal: true
# OrderInputLine represents one line from order input
# it will be used to validate each line of order input
class OrderInputLine
attr_reader :quantity, :product_code
def initialize(args)
@check_value = nil
@value = args[:value]
parse_value
end
private
def parse_value
raise InvalidInputLineException unless parsed_value
@quantity = parsed_value[1].to_i
@product_code = parsed_value[2]
end
def parsed_value
@check_value ||= @value.match(/^(\d+)\s(\w+)$/)
@check_value
end
end
| true |
daa67ed6e2e3a9bece26b97834e6c1292149c77f | Ruby | janlelis/az | /lib/az/string_ext.rb | UTF-8 | 175 | 2.515625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative "../az"
class String
# Optional core extension for your convenience
def az(font)
Az.az(self, font = :ascii)
end
end
| true |
7026b2d272ee28fd44e117f3dcb11d60afe80930 | Ruby | Lokideos/ruby-think-project | /lesson-8/hw-les-8/route.rb | UTF-8 | 1,310 | 3.296875 | 3 | [] | no_license | class Route
attr_reader :stations, :station_names, :name
def initialize(first_station, last_station)
@stations = [first_station, last_station]
validate!
@name = "route#{object_id}"
end
def add_station(station)
@stations.insert(-2, station)
end
def delete_station(station)
return false if [@stations.first, @stations.last].include?(station)
@stations.delete(station)
end
def stations_names
station_names = []
@stations.each { |station| station_names << station.name }
station_names
end
def valid?(_first_station = 'default', _last_station = 'default')
validate!
true
rescue RuntimeError
false
end
private
ERRORS =
{ unexistance_first: 'Unexisting first station',
unexistance_second: 'Unexisting second station',
equality: 'First station are equal to last station' }.freeze
# I believe that I should keep ABC of validate! method in its current state
# because of method's nature
def validate!
unless Station.all.find { |station| station == stations.first }
raise ERRORS[:unexistance_first]
end
unless Station.all.find { |station| station == stations.last }
raise ERRORS[:unexistance_second]
end
raise ERRORS[:equality] if stations.first.name == stations.last.name
end
end
| true |
9c4138f0981ca55d4057b8bf9ba56e0e31722de7 | Ruby | BadMinus/devise | /lib/devise/encryptors/bcrypt.rb | UTF-8 | 558 | 2.625 | 3 | [
"MIT"
] | permissive | require "bcrypt"
module Devise
module Encryptors
# = BCrypt
# Uses the BCrypt hash algorithm to encrypt passwords.
class Bcrypt < Base
# Gererates a default password digest based on stretches, salt, pepper and the
# incoming password. We don't strech it ourselves since BCrypt does so internally.
def self.digest(password, stretches, salt, pepper)
::BCrypt::Engine.hash_secret([password, pepper].join, salt, stretches)
end
def self.salt
::BCrypt::Engine.generate_salt
end
end
end
end
| true |
caa79aa379bcd22d9254ec2cc0e449010ef67bc6 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/nucleotide-count/ec06ff872e6542f8b5009667c2634ff6.rb | UTF-8 | 617 | 3.671875 | 4 | [] | no_license | class DNA
attr_reader :strand, :nucleotide_counts
def initialize(strand)
@strand = strand
@nucleotide_counts ||= {
'A' => strand.count('A'),
'T' => strand.count('T'),
'C' => strand.count('C'),
'G' => strand.count('G')
}
end
def count(nucleotide)
raise ArgumentError, "Invalid nucleotide" unless valid?(nucleotide)
nucleotide_counts[nucleotide] || 0
end
def valid?(nucleotide)
["A", "T", "C", "G", "U"].include?(nucleotide)
end
end
| true |
54c49086973ba645a51bcbc9947b53381019cb8b | Ruby | wtfspm/advent_of_code | /2020/08/computer.rb | UTF-8 | 1,589 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env ruby
def parse(input)
instruction = /(\w+) ([+-]\d+)/
input.split(/\r?\n/).map { |line|
instruction.match(line).captures.tap { |cap|
cap[1] = cap[1].to_i
}
}
end
def run(instructions)
registers = {
pc: 0,
acc: 0,
}
seen = Array.new(instructions.size, false)
until seen[registers[:pc]] || registers[:pc] >= instructions.size
seen[registers[:pc]] = true
execute(instructions, registers)
end
registers
end
def execute(instructions, registers)
instruction, param = instructions[registers[:pc]]
case instruction
when 'acc'
registers[:acc] += param
registers[:pc] += 1
when 'jmp'
registers[:pc] += param
when 'nop'
registers[:pc] += 1
when 'jmp'
else raise ArgumentError, "Unexpected instruction: '#{instruction}'"
end
registers
end
def run_with_swapped_instrucion(instructions, index)
swapped_instructions = instructions.map.with_index { |instruction, i|
if index == i
[
case instruction.first
when 'jmp' then 'nop'
when 'nop' then 'jmp'
else instruction.first
end,
instruction.last
]
else
instruction
end
}
registers = run(swapped_instructions)
end
if $0 === __FILE__
instructions = parse(ARGF.read)
registers = run(instructions)
puts registers[:acc]
instructions.size.times do |index|
next if instructions[index].first == 'acc'
registers = run_with_swapped_instrucion(instructions, index)
if registers[:pc] >= instructions.size
puts registers[:acc]
break
end
end
end
| true |
1ed3d398b10d90d147c9bc9a25cc98b0e37e8671 | Ruby | jmc282/D2 | /location.rb | UTF-8 | 1,746 | 3.640625 | 4 | [] | no_license | # Class defining location object
class Location
attr_accessor :max_silver
attr_accessor :name
attr_accessor :max_gold
attr_accessor :amt_neighbors
attr_accessor :neighbors
# Initialization of location
def initialize(name, max_silver, max_gold, amt_neighbors)
@name = name
@max_silver = max_silver
@max_gold = max_gold
@amt_neighbors = amt_neighbors
@neighbors = nil
end
def set_neighbors(first_neighbor, second_neighbor, third_neighbor, fourth_neighbor)
@neighbors = [first_neighbor, second_neighbor, third_neighbor, fourth_neighbor]
end
# Displays the amount of silver or gold found in a single iteration.
def display_findings(silver_found, gold_found)
if silver_found.zero? && gold_found.zero?
display_no_metals_found
else
print "\tFound "
display_metal_found(gold_found, 'gold') if gold_found > 0
print 'and ' if !silver_found.zero? && !gold_found.zero?
display_metal_found(silver_found, 'silver') if silver_found > 0
print "in #{@name}.\n"
end
end
# Called by display_findings to display how much of a metal was found at a location for one iteration.
def display_metal_found(amount, metal)
return nil if amount <= 0
print "#{get_units(amount)} of #{metal} "
end
# Called by display_findings if no silver or gold has been found at a location
# to display that no metals have been found
def display_no_metals_found
puts "\tFound no precious metals in #{@name}."
end
# Returns the amount of gold or silver with appropiate units in ounces.
def get_units(amount)
raise 'Cannot get less than 0 units.' if amount < 0
if amount == 1
'1 ounce'
else
"#{amount} ounces"
end
end
end
| true |
0c284f2d6904e3d9fa39209696428e7b57ef0c3f | Ruby | mrinsin/Ruby_recap | /ruby_basics.rb | UTF-8 | 2,459 | 4.21875 | 4 | [] | no_license | #Write a program which takes a number and prints "Valid" if the number is between 1 and 10 (inclusive) and "Invalid" otherwise.
def is_valid(num)
(1..10).include?(num.to_i) ? "Valid" : "Invalid"
end
#PASSWORD CHECKER CHALLENGE
# Challenge: Write a function called same that takes a user ID and a password, and returns true if they are, and false otherwise.
# Tests:
#
# same("joe", "joe") -> true
# same("joe", "joe1") -> false
def same?(user_id, password)
user_id.to_s == password.to_s ? true : false
end
#Challenge: Write a function called long_enough that checks whether a String is at least six characters long, and returns true if it is, and false otherwise.
# Tests:
#
# long_enough("12345") -> false
# long_enough("123456") -> true
def long_enough(str)
str.length >= 6 ? true : false
end
# Challenge Write a function called does_not_contain_special which checks to see if !, #, $ is not contained in a given String.
# Tests:
#
# does_not_contain_special("Hello Friend") -> true
# does_not_contain_special("A#C") -> false
# does_not_contain_special("A!C") -> false
# does_not_contain_special("A$C") -> false
def does_not_contain_special(string)
if string.include?("!") || string.include?("#") || string.include?("$")
false
else
true
end
end
#Challenge Write a method called contains_special which checks to see if !, #, $ is contained in a given String.
# Tests:
#
# contains_special("Hello Friend") -> false
# contains_special("A#C") -> true
# contains_special("A!C") -> true
# contains_special("A$C") -> true
def contains_special(string)
if string.include?("!") || string.include?("#") || string.include?("$")
true
else
false
end
end
# Challenge Write a method that inputs user ID and password from the user, and then tells the user if the they are acceptable.
# Write a main method called validate_password that:
#
# First lets a user input both user ID and password,
# Then use the methods above to evaluate if the user ID and password combination is acceptable or not
# Tells user what the result is
def user_registration
puts "Enter a user ID."
user_id = gets.chomp
puts "Enter a password"
password = gets.chomp
if !same?(user_id, password) && long_enough(user_id) && long_enough(password) && contains_special(password) && does_not_contain_special(user_id) && password != "password"
"Your user information is valid!"
else
"Invalid credentials! try again"
end
end
| true |
cad3567719c0df155790cd50e4ea34c013c5998a | Ruby | JoJordan/one_stop_shop | /lib/services.rb | UTF-8 | 442 | 2.515625 | 3 | [] | no_license | require 'yaml'
class Services
class << self
def init
@services ||= YAML::load(File.open('./services.yaml'))
end
def services
init
@services
end
def service_url(service_name, post_code)
init
@services[service_name]['where'].gsub(':post_code', post_code)
end
def local_services
init
@services.select {|_, service_obj| service_obj['internal']}
end
end
end
| true |
f0cdd7cb7d0bab4076281dea78191eba5acb5d80 | Ruby | cielavenir/procon | /codeforces/tyama_codeforces722B.rb | UTF-8 | 103 | 2.765625 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
gets
a=gets.chars.chunk{|c|c}.select{|k,v|k=='B'}.map{|k,v|v.size}
p a.size
puts a*' '
| true |
57b7643329932445df93f86a3a0db7e4532c6f28 | Ruby | luchrist777/ruby-music-library-cli-onl01-seng-pt-050420 | /lib/concerns/findable.rb | UTF-8 | 356 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | module Concerns::Findable # defines a module named Concerns::Findable (FAILED - 1)
def find_by_name(name)
self.all.detect{|song| song.name == name}
end
def find_or_create_by_name(name) # is added as a class method to classes that extend the module (FAILED - 1)
self.find_by_name(name) || self.create(name)
end
end | true |
e60ef092376c3268d987810b4d7dd765bea6e8a0 | Ruby | mariofsalles/minicurso-ruby | /Modulo3/blocos.rb | UTF-8 | 609 | 3.640625 | 4 | [] | no_license | def bloco
puts "Esse é o inicio do bloco"
yield #Aqui virá o código passado no bloco ao chamar o método
puts "Esse é o fim do bloco"
end
bloco { puts "Fui chamado no bloco da chamada do método" }
puts "---------------------------------------------------"
bloco do
puts "Dessa forma, pode-se chamar várias instruções para o bloco"
puts ":)"
end
#OBS: se o método for chamado sem que se passe um bloco, o ruby levanta uma Exception no block given (LocalJumpError)
def tem_bloco?
if block_given?
yield
else
puts "nenhum bloco"
end
end
tem_bloco? {puts "Olá"}
tem_bloco? | true |
69b66c7c0dc227a2563ab6c19e606e02ffc0e356 | Ruby | mawaldne/exercism_solutions | /ruby/space-age/space_age.rb | UTF-8 | 568 | 3.359375 | 3 | [] | no_license | class SpaceAge
ORBITAL_PERIOD_EARTH_YEARS = {
earth: 1,
mercury: 0.2408467,
venus: 0.61519726,
mars: 1.8808158,
jupiter: 11.862615,
saturn: 29.447498,
uranus: 84.016846,
neptune: 164.79132
}
EARTH_YEARS_SECONDS = 31557600
def initialize(seconds)
@seconds = seconds
end
ORBITAL_PERIOD_EARTH_YEARS.keys.each do |planet|
define_method :"on_#{planet.to_s}" do
age_on(planet)
end
end
private
def age_on(planet)
@seconds.to_f / (EARTH_YEARS_SECONDS * ORBITAL_PERIOD_EARTH_YEARS[planet])
end
end
| true |
d7e4bcc5ceb1bb0ae521de5744129d21b32c9ae6 | Ruby | lucidstack/nascunna | /lib/nascunna.rb | UTF-8 | 1,795 | 2.5625 | 3 | [
"MIT"
] | permissive | require "configuration"
require "cacheable"
module Nascunna
def self.redis
@redis
end
def self.redis=(redis_instance)
@redis = redis_instance
end
def self.add_model(model)
@model = model
yield(self)
Nascunna::Configuration.cacheables.each do |model|
model.class_eval <<-EOS
include Nascunna::Cacheable
EOS
end
end
def self.add_dependency(method_sym, dependencies, base=@model)
Nascunna::Configuration.new(@model, method_sym) do |graph|
graph.add_dependency(dependencies)
recursively_compute_deps(graph, method_sym, dependencies, base)
end
end
def self.connect(method_sym, sources)
connected_dependencies = Array(sources).collect do |source|
Nascunna::Configuration.dependencies[@model.name][source].to_a
end.flatten(1).uniq
connected_dependencies = connected_dependencies[0] if connected_dependencies.size == 1
self.add_dependency(method_sym, connected_dependencies)
end
private
def self.recursively_compute_deps(graph, method_sym, dependencies, base)
case dependencies
when Symbol, String
graph.add_invalidation(base, dependencies.to_sym)
when Hash
dependencies.each do |key, value|
graph.add_invalidation(base, key.to_sym)
new_base = base.reflect_on_association(key)
raise "Polymorphic associations (#{key}) not supported yet!" if new_base.options[:polymorphic]
new_base = new_base.class_name.constantize
self.recursively_compute_deps(graph, method_sym, value, new_base)
end
when Array
dependencies.each do |dependency|
self.recursively_compute_deps(graph, method_sym, dependency, base)
end
else
raise ArgumentError, "dependencies type not supported"
end
end
end
| true |
413d33a668bf7aa80d1f0ed78ec4803389bb38dc | Ruby | KenEucker/jackpine-biketag-api-rails | /app/models/notifications/successful_guess_notification.rb | UTF-8 | 294 | 2.578125 | 3 | [] | no_license | class Notifications::SuccessfulGuessNotification < Notifications::DeviceNotification
attr_reader :guesser_name
def initialize(guess)
@guesser_name = guess.user_name
end
def push_notification
Houston::Notification.new( alert: "#{guesser_name} captured your spot!" )
end
end
| true |
580e2c03ba969d00af6dd59e30e4f0aeac6a52ba | Ruby | adam-mrachek/launchschool120-old | /lesson_4/easy_3/question_7.rb | UTF-8 | 576 | 4.09375 | 4 | [] | no_license | # What is used in this class but doesn't add any value?
class Light
attr_accessor :brightness, :color
def initialize(brightness, color)
@brightness = brightness
@color = color
end
def self.information
return "I want to turn on the light with a brightness level of super high and a color of green"
end
end
# Answer:
# The `return` in the information method is unecessary since Ruby automatically returns the last line of any method.
# Also, the attr_accessor for color and brightness are unused in the class. They could be used in information method. | true |
1014309795ea294f2d461643ad80fe327252314d | Ruby | ksefcovic/CYBR4580 | /find_my_device_app/application/lib/data_token.rb | UTF-8 | 468 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | class DataToken < TokenBuilder
include InitLater
def initialize(extract_data = ->(x) { x }, token_builder)
@token_builder = token_builder
@extract_data = extract_data
end
def build(data)
puts "builds_data"
cons(extract_data.(data), token_builder.build(data))
end
def verify(token)
token_builder.verify(cdr(token)) && car(token)
end
private
attr_reader :token_builder, :extract_data
end | true |
d076cea54b14d8d64e653c2dd2c260205a2a0bf9 | Ruby | myles-i-appdev/each-chapter | /each_spell_word.rb | UTF-8 | 230 | 3.984375 | 4 | [] | no_license | # Write a program that:
#
# Asks your user to enter any word and have it spelled out letter by letter.
p "Enter a word for me to spell:"
word = gets.chomp
num_letters = word.length
num_letters.times do |idx|
p word[idx]
end | true |
1f733075b3e7227d3c6f6782540f1ab34d55c570 | Ruby | shakamo/booklyn | /app/models/import_images.rb | UTF-8 | 728 | 2.65625 | 3 | [] | no_license |
require 'net/https'
require 'json'
# コンテンツの一覧を取得するクラス
# アニメやドラマのタイトル、放送日などを取得する。
# アニメやドラマのタイトル、放送日などを取得する。
class ImportImages
# Contentを取得して、データベースに格納する。
# @param site_name [String] Contentを取得するサイトを指定する。Anikore, Rakuten
# @param year [String] Contentを取得する範囲を指定する。Anikore のみ。2015
# @param season [String] Contentを取得するシーズンを指定する。winter, spring, summer, autumn
def perform_all(_site_name, year, season)
Video::Anikore.new.import_all(year, season)
end
end
| true |
ab1fd1e01786689c73d0b7f3d1ddf3aab17f102e | Ruby | jeanlazarou/swiby | /core/test/test_changing_styles.rb | UTF-8 | 2,052 | 2.5625 | 3 | [
"CC-BY-2.5",
"BSD-3-Clause"
] | permissive | #--
# Copyright (C) Swiby Committers. All rights reserved.
#
# The software in this package is published under the terms of the BSD
# style license a copy of which has been included with this distribution in
# the LICENSE.txt file.
#
#++
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'test/unit'
require 'swiby/styles'
include Swiby
class TestStyles < Test::Unit::TestCase
def setup
@styles = create_styles {
root(
:font_family => Styles::VERDANA,
:font_style => :normal,
:font_size => 10
)
label(
:font_style => :italic,
:font_size => 12
)
input(
:font_family => Styles::VERDANA,
:font_style => :normal,
:font_size => 14
)
button(
:font_weight => :bold
)
a_class {
label(
:font_size => 3
)
}
}
end
def test_setting_the_same_value_to_some_specific_style
@styles.change!(:font_size, 21)
assert_equal 21, @styles.root.font_size
assert_equal 21, @styles.label.font_size
assert_equal 21, @styles.input.font_size
assert_equal 21, @styles.a_class.label.font_size
end
def test_setting_different_values_for_some_specific_style
@styles.change!(:font_size) do |path, size|
size + 7
end
assert_equal 17, @styles.root.font_size
assert_equal 19, @styles.label.font_size
assert_equal 21, @styles.input.font_size
assert_equal 10, @styles.a_class.label.font_size
end
def test_setting_only_some_values
@styles.change!(:font_size) do |path, size|
if path == 'root'
size + 3
elsif path == 'a_class.label'
size + 5
end
end
assert_equal 13, @styles.root.font_size
assert_equal 12, @styles.label.font_size
assert_equal 14, @styles.input.font_size
assert_equal 8, @styles.a_class.label.font_size
end
end
| true |
e5adbf41d5086893fbc598f8e00358422d86aee1 | Ruby | peterylai/exercism | /ruby/hamming/hamming.rb | UTF-8 | 265 | 2.859375 | 3 | [] | no_license | class Hamming
def self.compute(first_strand, second_strand)
raise ArgumentError.new if first_strand.length != second_strand.length
(0...first_strand.length).count { |i| first_strand[i] != second_strand[i] }
end
end
module BookKeeping
VERSION = 3
end | true |
ae9752e6d835ba55b0d17d90eab4a16a0c9df40d | Ruby | 40grivenprog/homeworks | /HW_04/Boris_Tsarikov/boris_tsarikov_hw_04_t_02.rb | UTF-8 | 786 | 2.859375 | 3 | [] | no_license | require 'yaml'
def magic_number(pool = 1, timeout = 1000)
timeout = 1000 if timeout.nil?
pool = 1 if pool.nil?
pool * timeout
end
def selection_of_info(hash = {})
result = {}
selection(result: result, hash: hash, id: :db, selec_name: 'database')
selection(result: result, hash: hash, id: :user, selec_name: 'username')
selection(result: result, hash: hash, id: :password, selec_name: 'password')
result[:magic_number] = magic_number(hash['pool'], hash['timeout'])
result
end
def selection(result:, hash:, id:, selec_name:)
result[id] = hash[selec_name] if hash.key?(selec_name)
end
def task_4_2(yaml_info)
return yaml_info if yaml_info.empty?
hash = YAML.safe_load(yaml_info)
hash.map { |key, value| [key.to_sym => selection_of_info(value)] }.flatten
end
| true |
fbbc7624c65be3199109a7fff4f47007b849fc49 | Ruby | Monique1129/practice-folder | /user_practice.rb | UTF-8 | 1,051 | 3.359375 | 3 | [] | no_license | class User
def initialize
@first_name = nil
@middle_name = nil
@last_name = nil
@email = nil
@phone_number = nil
@address = nil
end
def set_first_name(identity)
@first_name = identity
end
def get_first_name
puts @first_name
return @first_name
end
def set_middle_name(mother)
@middle_name = mother
end
def get_middle_name
puts @middle_name
return @middle_name
end
def set_last_name(father)
@last_name = father
end
def get_last_name
puts @last_name
return @last_name
end
def set_email(website)
@email = website
end
def get_email
puts @email
return @email
end
def set_phone_number(contact)
@phone_number = contact
end
def get_phone_number
puts @phone_number
return @phone_number
end
def set_address(laspinas)
@address = laspinas
end
def get_address
puts @address
return @address
end
def display_name
puts "#{@first_name}, #{@middle_name}, #{@last_name}, #{@email}, #{@phone_number}, #{@address}"
end
end
| true |
1519dcd6d9542bcffe5b12fa66640332014e04bf | Ruby | KayQuillen/SandBox | /3_11.rb | UTF-8 | 579 | 3.890625 | 4 | [] | no_license | #challenge 1
#begin
first_name = "Sam"
last_name = " Wright"
savings = 3000000
checking = 2000
print "#{first_name}#{last_name} has #{savings} dollars in savings and #{checking} dollars in checking."
#end
#challenge 2
#begin
puts "please enter First name"
first_name = gets.chomp.to_s
puts "please enter Last name"
last_name = gets.chomp.to_s
puts "Please enter savings amount"
savings = gets.chomp.to_i
puts "Please enter checking amount"
checking = gets.chomp.to_i
puts "#{first_name} #{last_name} has #{savings} dollars in savings and #{checking} dollars in checking."
#end | true |
85e48d9e2ecae7b7e821592f3b9831206f7b695a | Ruby | RolandeS/customer_relationship_application | /crm.rb | UTF-8 | 3,251 | 3.984375 | 4 | [] | no_license | require_relative './rolodex.rb'
require_relative './contact.rb'
class CRM
attr_accessor :name
def initialize(name)
@name = name #instance variable
@rolodex = Rolodex.new
end
def print_main_menu
puts "[1] Add a contact"
puts "[2] Modify a contact"
puts "[3] Display one contact"
puts "[4] Display all contacts"
puts "[5] Display an attribute"
puts "[6] Delete a contact"
puts "[7] Exit"
end
def main_menu
puts "Welcome to #{@name}"
while true
print_main_menu
input = gets.chomp.to_i
chose_option(input)
return if input == 7
end
end
def chose_option(option)
case option
when 1 then add_contact
when 2 then modify_contact
when 3 then display_contact
when 4 then display_contacts
when 5 then display_attribute
when 6 then delete_contact
when 7
puts "Goodbye!"
return
else puts "Incorrect option, try again."
end
end
def add_contact
puts "Provide Contact Details"
print "First Name:"
first_name = gets.chomp
print "Last Name:"
last_name = gets.chomp
print "Email:"
email = gets.chomp
print "Note:"
note = gets.chomp
new_contact = Contact.new(first_name, last_name, email, note)
@rolodex.add_contact(new_contact)
end
def modify_contact
puts "Enter the ID of the contact you would like to modify."
id = gets.chomp.to_i
contact = @rolodex.display_particular_contact(id)
puts "#{contact.id}, #{contact.first_name}, #{contact.last_name}, #{contact.email}, #{contact.note}"
puts "Are you sure you want to modify the above contact?\nYES/NO:"
if gets.chomp.to_s.upcase == "YES"
puts "[1] Change the first name"
puts "[2] Change the last name"
puts "[3] Change the email"
puts "[4] Change the notes"
num = gets.chomp.to_i
puts "Enter a new value for your attribute."
new_value = gets.chomp.to_s
contact = @rolodex.modify_contact(id, num, new_value)
puts "The contact is now #{contact.id}, #{contact.first_name}, #{contact.last_name}, #{contact.email}, #{contact.note}"
else puts "Move on"
end
end
def display_contacts
contacts = @rolodex.display_all_contacts
contacts.each { |contact| puts "#{contact.id}, #{contact.first_name}, #{contact.last_name}, #{contact.email}, #{contact.note}"}
end
def display_contact
puts "Enter the ID of the contact you would like to display."
id = gets.chomp.to_i
contact = @rolodex.display_particular_contact(id)
puts "The contact you chose to display is"
puts "#{contact.id}, #{contact.first_name}, #{contact.last_name}, #{contact.email}, #{contact.note}"
end
def display_attribute
puts "Enter the ID of the contact you would like to display an attribute for."
id = gets.chomp.to_i
puts "[1] Display the first name"
puts "[2] Display the last name"
puts "[3] Display the email"
puts "[4] Display the notes"
num = gets.chomp.to_i
attr = @rolodex.display_info_by_attribute(id, num)
puts "The attribute you asked for is #{attr}"
end
def delete_contact
puts "Enter the ID of the contact you would like to delete."
id = gets.chomp.to_i
@rolodex.delete_contact(id)
puts "The contact with the ID #{id} has been deleted."
end
end
bitmaker = CRM.new("Bitmaker Labs CRM")
bitmaker.main_menu
puts bitmaker.name | true |
fafff96d9cbc9e2c647ffa241cf30ef1e7a36745 | Ruby | manzugeek/prog_foundation | /lesson_2/test_data.rb | UTF-8 | 870 | 3.90625 | 4 | [] | no_license |
# produce = {
# 'apple' => 'Fruit',
# 'carrot' => 'Vegetable',
# 'pear' => 'Fruit',
# 'broccoli' => 'Vegetable'
# }
#
# def select_fruit(produce_list)
# produce_list.select { |k, v| v == "Fruit" }
# end
#
# select_fruit(produce)
# do..end
# produce_list.select do |k, v|
# v == "Fruit"
# end
arr = [1, 2, 3, 4, 5]
counter = 0
loop do
arr[counter] += 1
counter += 1
break if counter == arr.size
end
p arr
#Essentially same but below solved elegantly
new_arr = arr.map { |counter| counter += 1 }
p new_arr
color = [ 'green', 'blues', 'purple', 'orange']
# Iteration using Enumarable methods - elegantly solved
color.each { |element| puts "I'm the color #{element}!"}
# Manually
color = [ 'green', 'blues', 'purple', 'orange']
counter = 0
loop do
break if counter == color.size
puts "I'm the color #{color[counter]}!"
counter += 1
end
| true |
d707f5244ec0ee072392c1242adb4e32b0c39012 | Ruby | erikabalbino/codecore-homework | /homework-5/blog_on_rails/db/seeds.rb | UTF-8 | 417 | 2.609375 | 3 | [] | no_license |
Post.destroy_all
50.times.each do
p = Post.create(
title: Faker::Job.title,
body: Faker::Lorem.paragraph
)
if p.valid?
rand(0..10).times.each do
Comment.create(
body: Faker::Job.field,
post: p
)
end
end
end
posts=Post.all
comments = Comment.all
puts Cowsay.say "Created #{posts.count} posts", :frogs
puts Cowsay.say "Created #{comments.count} comments", :sheep
| true |
f815e0b069e40b8a406db0defd92f7a144594e66 | Ruby | ARElton/deli-counter-ruby-apply-000 | /deli_counter.rb | UTF-8 | 627 | 4.03125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def line(katz_deli)
if katz_deli == []
puts "The line is currently empty."
elsif
final_message = "The line is currently:"
katz_deli.each_with_index do |people, i|
final_message << " #{i += 1}. #{people}"
end
puts final_message.chomp
end
end
def take_a_number(katz_deli, customer)
katz_deli.push(customer)
puts "Welcome, #{customer}. You are number #{katz_deli.length} in line."
end
def now_serving(katz_deli)
if
katz_deli == []
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{katz_deli[0]}."
katz_deli.shift
end
end
| true |
9c0a8af242d5f7b3d47b8018fc509f52643e33d6 | Ruby | philjdelong/code_challenges | /recursion.rb | UTF-8 | 1,279 | 3.90625 | 4 | [] | no_license | # require 'pry'
def combo
menu = {
'veggie sandwich' => 6.85,
'extra veggies' => 2.20,
'chicken sandwich' => 7.85,
'extra chicken' => 3.20,
'cheese' => 1.25,
'chips' => 1.40,
'nachos' => 3.45,
'soda' => 2.05,
}
sorted_menu = menu.sort.reverse
receipts = [4.85, 11.05, 13.75, 17.75, 18.25, 19.40, 28.25, 40.30, 75.00]
receipts.map do |original_receipt|
return possibility if original_receipt == 0.00
possibility = sorted_menu.map do |menu_item|
if menu_item[1] < original_receipt
original_receipt = (original_receipt - menu_item[1]).round(2)
menu_item[0]
end
end.compact
end
end
p combo
# Constraints:
# - you must use 100% of the receipt value, we don't want any money left over
# - you can order any quantity of any menu item
# - none of the receipt values are "tricks", they all have answers
# The Challenge:
# Find the first combination of food that adds up to the receipt total, print out only one combination for that receipt, and move on to the next receipt.
# The output format is up to you, but here are some examples:
# 4.85:
# 3 items, extra veggies, chips, cheese
# 13.75:
# 3 items, {'veggie sandwich': 1, 'nachos': 2}
| true |
8f1ac29af30d68fffa74d170a1ba9e9dec8f18f4 | Ruby | mattTea/chitter-challenge | /spec/features/posting_peeps_spec.rb | UTF-8 | 476 | 2.5625 | 3 | [] | no_license | # As a Maker
# So that I can let people know what I am doing
# I want to post a message (peep) to chitter
feature "Posting peeps" do
scenario "a user can add message to form" do
visit "/peeps/new"
expect(page).to have_selector "form"
end
scenario "a user can post a peep to Chitter" do
visit "/peeps/new"
fill_in "message", :with => "Writing a Chitter app!"
click_button "Post"
expect(page).to have_content "Writing a Chitter app!"
end
end
| true |
69df198601c9217a584fe7c964af09b0679a8c00 | Ruby | Nekitoni4/thinknetica_begin | /lesson_1/quadratic_equation.rb | UTF-8 | 432 | 3.34375 | 3 | [] | no_license | puts "Input a coefficient plz, sir:"
a = gets.to_i
puts "Input b coefficient plz, sir:"
b = gets.to_i
puts "Input c coefficient plz, sir:"
c = gets.to_i
d = b**2 - 4 * a * c
if d < 0
puts "No roots. bro;("
elsif d == 0
x = -b/(2.0 * a)
puts "Discriminant is #{d}, x is #{x}"
else
discRoot = Math.sqrt(d)
x1 = (-b + discRoot)/2 * a
x2 = (-b - discRoot)/2 * a
puts "Discriminant is #{d}, x1 is #{x1}, x2 is #{x2}"
end
| true |
4faa20de601f820c8bfe2759812236e0b1f45e03 | Ruby | thefrankharvey/key-for-min-value-prework | /key_for_min.rb | UTF-8 | 531 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # ```ruby
# ikea = {:chair => 25, :table => 85, :mattress => 450}
# key_for_min_value(ikea)
# # => :chair
#
# name_hash = {"apple" => -45, "banana" => -44.5, "carrot" => -44.9}
# # key_for_min_value(veggies)
# # # => "apple"
# # ```
def key_for_min_value(name_hash)
values = []
hash_array = name_hash.to_a
name_hash.each do |k, v|
values.push(v)
end
min_value = values.sort
i = 0
while i < hash_array.length do
if hash_array[i][1] == min_value[0]
min_key = hash_array[i][0]
end
i += 1
end
min_key
end
| true |
b6da3ac52d73a8cd421d919d218267f8b371543a | Ruby | jukinner/Coding-Practice-Codewars-Codility-Hackerrank-etc.- | /playing_with_numbers-7ku-strong_number.rb | UTF-8 | 1,931 | 4.125 | 4 | [] | no_license | # Definition
# Strong number is the number that the sum of the factorial of its digits is equal to number itself.
# For example : 145 , since
# 1! + 4! + 5! = 1 + 24 + 120 = 145
# So, 145 is a Strong number.
# Task
# Given a number, Find if it is Strong or not .
# Warm-up (Highly recommended)
# Playing With Numbers Series
# Notes
# Number passed is always Positive .
# Return the result as String
# Input >> Output Examples
# 1- strong_num (1) ==> return "STRONG!!!!"
# Explanation:
# Since , the sum of its digits' factorial of (1) is equal to number itself (1) , Then its a Strong .
# 2- strong_num (123) ==> return "Not Strong !!"
# Explanation:
# Since , the sum of its digits' factorial of 1! + 2! + 3! = 9 is not equal to number itself (123) , Then it's Not Strong .
# 3- strong_num (2) ==> return "STRONG!!!!"
# Explanation:
# Since , the sum of its digits' factorial of 2! = 2 is equal to number itself (2) , Then its a Strong .
# 4- strong_num (150) ==> return "Not Strong !!"
# Explanation:
# Since , the sum of its digits' factorial of 1! + 5! + 0! = 122 is not equal to number itself (150) , Then it's Not Strong .
# Playing with Numbers Series
# Playing With Lists/Arrays Series
# For More Enjoyable Katas
# ALL translations are welcomed
# Enjoy Learning !!
# Zizou
def strong_num(n)
sum = 0
n.digits.compact.each {|x| sum += factorial(x) if x != 0 }
if sum == n
p "STRONG!!!!"
else
p "Not Strong !!"
end
end
def factorial(n)
n.downto(1).inject(:*)
end
strong_num(1)
strong_num(2)
strong_num(7)
strong_num(93)
strong_num(40585)
strong_num(145)
strong_num(185)
# Test.assert_equals(strong_num(1) , "STRONG!!!!")
# Test.assert_equals(strong_num(2) , "STRONG!!!!")
# Test.assert_equals(strong_num(7) , "Not Strong !!")
# Test.assert_equals(strong_num(93) , "Not Strong !!")
# Test.assert_equals(strong_num(145), "STRONG!!!!")
# Test.assert_equals(strong_num(185), "Not Strong !!") | true |
2a68286043be8da46e7eddb8c2429d0aeb6d3251 | Ruby | UKGovernmentBEIS/beis-report-official-development-assistance | /app/models/benefitting_region.rb | UTF-8 | 1,297 | 2.828125 | 3 | [
"MIT"
] | permissive | class BenefittingRegion
include ActiveModel::Model
attr_accessor :name, :code, :level
DEVELOPING_COUNTRIES_CODE = "998"
class << self
def all
@all ||= Codelist.new(type: "benefitting_regions", source: "beis").map { |region| new_from_hash(region) }
end
def all_for_level_code(level_code = 3)
level = BenefittingRegion::Level.find_by_code(level_code)
all.select { |region| region.level == level }
end
def find_by_code(code)
all.find { |region| region.code == code }
end
private
def new_from_hash(region)
new(
name: region["name"],
code: region["code"],
level: Level.find_by_code(region["level"])
)
end
end
def hash
code.hash
end
def eql?(other)
code == other.code
end
def ==(other)
code == other.code
end
class Level
include ActiveModel::Model
attr_accessor :name, :code
class << self
def all
@all ||= Codelist.new(type: "benefitting_region_levels", source: "beis").map { |level| new_from_hash(level) }
end
def find_by_code(code)
all.find { |level| level.code == code }
end
private
def new_from_hash(level)
new(name: level["name"], code: level["code"])
end
end
end
end
| true |
844cffb2343e15a7fa37cb32d28d9d68dddf0617 | Ruby | henrygambles/Boris_Bikes | /spec/docking_station_spec.rb | UTF-8 | 2,552 | 3.09375 | 3 | [] | no_license | require "./lib/docking_station.rb"
describe DockingStation do
it { is_expected.to respond_to :release_bike }
it "returns a bike object when release_bike method is called and a bike is docked" do
docking_station = DockingStation.new
docking_station.dock(Bike.new)
expect(docking_station.release_bike.is_a?(Bike)).to eq true
end
it "returns a bike object that is working when release_bike method called and a bike is docked" do
docking_station = DockingStation.new
docking_station.dock(Bike.new)
expect(docking_station.release_bike.working?).to eq true
end
it { is_expected.to respond_to(:dock).with(1).argument }
it { is_expected.to respond_to(:bike_collection) }
it "returns a bike when the dock method is called with a bike object argument" do
bike = Bike.new
expect(subject.dock(bike)).to eq [bike]
end
it 'returns docked bikes when bike method is called' do
bike = Bike.new
subject.dock(bike)
expect(subject.bike_collection).to eq [bike]
end
it "release_bike method to raise error if called on new docking station object" do
expect{DockingStation.new.release_bike}.to raise_error
end
it "dock method to return error when docking station already has DockingStation::DEFAULT_CAPACITY bike" do
docking_station = DockingStation.new
DockingStation::DEFAULT_CAPACITY.times {docking_station.dock(Bike.new)}
expect{docking_station.dock(Bike.new)}.to raise_error(StandardError).with_message("Docking Station already at full capacity.")
end
it "Sets @bike_collection to an empty array when a docking station object is initialized" do
expect(DockingStation.new.bike_collection).to eq []
end
# it "full? returns true when a docking station has DockingStation::DEFAULT_CAPACITY bikes" do
# docking_station = DockingStation.new
# DockingStation::DEFAULT_CAPACITY.times {docking_station.dock(Bike.new)}
# expect(docking_station.full?).to eq true
# end
#
# it "full? returns false when docking station has less than DockingStation::DEFAULT_CAPACITY bikes" do
# docking_station = DockingStation.new
# 19.times {docking_station.dock(Bike.new)}
# expect(docking_station.full?).to eq false
# end
#
# it "empty? returns true when docking station has no bikes" do
# expect(DockingStation.new.empty?).to eq true
# end
#
# it "empty? returns false when docking station has bikes" do
# docking_station = DockingStation.new
# docking_station.dock(Bike.new)
# expect(docking_station.empty?).to eq false
# end
end
| true |
f020dee596a70edc61390780510efda7dc08f056 | Ruby | PatrickMcConnell88/advent-of-code-2018 | /dec-02/part1.rb | UTF-8 | 638 | 3.625 | 4 | [] | no_license | #!/usr/bin/ruby
input_array = File.readlines('input.txt')
num_doubles = 0
num_triples = 0
input_array.each do |id|
contains_double = false
contains_triple = false
char_array = id.chars
hash_map = {}
char_array.each do |char|
if hash_map[char] == nil
hash_map[char] = 1
else
hash_map[char] = hash_map[char] + 1
end
end
hash_map.values.each do |value|
if value == 2
contains_double = true
elsif value == 3
contains_triple = true
end
end
if contains_double
num_doubles += 1
end
if contains_triple
num_triples += 1
end
end
puts num_doubles * num_triples
| true |
59419961a07f385f8c74ff676552c75892477021 | Ruby | punsammy/ruby_fundamentals2 | /exercise7.rb | UTF-8 | 173 | 3.09375 | 3 | [] | no_license | puts "type something"
text = gets
text = text.chomp
symbol = "###==="
def wrap_text(text, symbol)
"#{symbol.reverse}#{text}#{symbol}"
end
puts wrap_text(text, symbol)
| true |
f368623d93f96b6bfaff008c289005e42f5cab09 | Ruby | jeremyevans/sacruby | /2015-08-rpssl/tests/tc_cfh_random_player.rb | UTF-8 | 339 | 2.703125 | 3 | [] | no_license | require_relative '../players/cfh_random_player.rb'
require 'test/unit'
class MyPlayerTest < Test::Unit::TestCase
def test_choose_rock
p = CfhRandomPlayer.new('cfh')
choice = p.choose
assert(
[:spock, :rock, :paper, :scissors, :lizard].any? do |move|
move == choice
end
)
end
end
| true |
cef7ca11f9339202927d5e62d5c52f0971c69d82 | Ruby | EJLarcs/rake-todo-web-0715-public | /Rakefile | UTF-8 | 1,308 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # This is an example of a Rake Task called "hello_rake"
task :hello_rake do
puts "Hello, from rake"
end
task :default do
puts "Hello, from default task!"
end
#creates a defaul rake
task :environment do
require_relative './config/environment'
end
#creates the environment
task :upcoming_todos => [:environment] do
User.with_upcoming_todos.each do |user|
puts "Emailing #{user}"
end
end
# shifts the todos into the environment
task :overdue_todos => [:environment] do
User.with_overdue_todos.each do |user|
puts "Emailing #{user}"
end
end
namespace :todos do
task :mark_overdue => [:environment] do
Todo.mark_overdue
end
end
#namespacing^^^ allows you to group tasks together
#when a task is within a namespace(group) its name becomes `todos:mark_overdue` - ie. associated
namespace :todos do
task :mark_upcoming => [:environment] do
Todo.mark_upcoming
end
end
desc "Loads an interactive console."
task :console => [:environment] do
load './bin/console'
exit
end
namespace :user do
desc "Send a summary to a User"
task :send_summary, [:email] => [:environment] do |t, args|
# [email] is the argument array
# [environment] is the prerequisite task array
puts "Sending summary to user with #{args[:email]}"
end
end
#Define new tasks below
| true |
100f8dbe8688219fe3dd4b8cedee690845c4e6bb | Ruby | musiccity365/pfwtfp-practice-with-array-integers-lab-dc-web-mod1-repeat | /lib/array_practice.rb | UTF-8 | 1,314 | 4.09375 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | array_of_integers = *0...50
def all_odds(array)
# return all odd numbers from the input array
array.select { |i| i.odd? }
end
def all_evens(array)
# return all even numbers from the input array
array.select { |i| i.even? }
end
def all_squares(array)
# return the square of all numbers from the input array
array.map { |i| i**2 }
end
def first_square_greater_than_350(array)
# return the first number from the input array whose square is greater than 350
array.find { |i| i**2 > 350 }
end
def all_squares_greater_than_350(array)
# return all the numbers from the input array whose square is greater than 350
array.find_all { |i| i**2 > 350 }
end
def all_cubes(array)
# return the cube of all numbers from the input array
array.map { |i| i**3 }
end
def first_cube_greater_than_500(array)
# return the first number from the input array whose cube is greater than 500
array.find { |i| i**3 > 500 }
end
def all_cubes_greater_than_500(array)
# return all the numbers from the input array whose cube is greater than 500
array.find_all { |i| i**3 > 500 }
end
def sum(array)
# return the sum of all integers from the input array
array.inject(:+)
end
def average_value(array)
# return the average of all integers from the input array
array.inject(&:+) / array.size.to_f
end
| true |
745f92a922c96aa46d31d8a90f11f00a67491051 | Ruby | togiberlin/algorithmic_challenges | /coderbyte/a_easy/ruby/17_array_addition/array_addition.rb | UTF-8 | 201 | 3.015625 | 3 | [
"MIT"
] | permissive | def array_addition_i(arr)
largest_number = arr.max
arr.delete(largest_number)
arr.repeated_combination(arr.length)
.to_a
.map { |ary| ary.uniq.inject(:+) }.include? largest_number
end
| true |
8f2dbac0535fa87012507862486ad894e7a62328 | Ruby | xxuejie/cuckoo | /spec/routes/api_spec.rb | UTF-8 | 4,839 | 2.609375 | 3 | [] | no_license | require 'spec_helper'
describe 'api' do
def post_json(loc, hash)
post loc, hash.to_json
end
def fetch_json
last_response.should be_ok
JSON.parse(last_response.body, symbolize_names: true)
end
def signin
post_json '/api/signin.json', {login_name: @login_name, password: @pass}
end
def expect_not_signin
last_response.status.should be(403)
end
def expect_json_ok
expect(fetch_json[:status]).to eq("ok")
end
def expect_json_error
expect(fetch_json[:status]).to eq("error")
end
before(:each) do
Ohm.flush
@login_name = "aname"
@pass = "pass"
@avatar = "avatarvalue"
@description = "description value"
@id = User.create_with_check({login_name: @login_name,
password: @pass,
avatar: @avatar,
description: @description}).id
@wrong_pass = "123"
@not_exist_login_name = "wrongname"
end
it "should be able to sign in" do
signin
expect_json_ok
end
it "should not be able to sign in with wrong password" do
post_json '/api/signin.json', {login_name: @login_name, password: @wrong_pass}
expect_json_error
end
it "should be able to sign out" do
# we use the /api/me.json API which requires sign in to show that we did sign out
get '/api/me.json'
expect_not_signin
signin
get '/api/me.json'
expect_json_ok
get '/api/signout.json'
get '/api/me.json'
expect_not_signin
end
it "should be able to sign up for new user" do
post_json '/api/signup.json', {
login_name: @not_exist_login_name,
password: @wrong_pass}
expect_json_ok
expect(User.find({login_name: @not_exist_login_name}).size).to be(1)
end
it "should not be able to use the API without signing in" do
get '/api/me.json'
expect_not_signin
end
it "should return information of the user itself" do
signin
get '/api/me.json'
resp = fetch_json
expect(resp[:status]).to eq("ok")
data = resp[:data]
expect(data[:id]).to eq(@id)
expect(data[:login_name]).to eq(@login_name)
expect(data[:avatar]).to eq(@avatar)
expect(data[:description]).to eq(@description)
end
it "should be able to update information" do
new_description = "this is a new description"
signin
post_json '/api/me.json', {description: new_description}
expect_json_ok
u = User[@id]
expect(u.description).to eq(new_description)
end
it "should be able to publish and read new tweets" do
content = "This is a new tweet!"
original_count = User[@id].tweets.size
signin
post_json '/api/tweets.json', {content: content}
expect_json_ok
expect(User[@id].tweets.size).to be(original_count + 1)
get '/api/tweets.json'
resp = fetch_json
expect(resp[:status]).to eq("ok")
found = false
resp[:data].each do |t|
found = true if content == t[:content]
end
expect(found).to be_true
end
it "should be able to get a list of users" do
count = User.all.size
signin
get '/api/users.json'
resp = fetch_json
expect(resp[:status]).to eq("ok")
expect(resp[:data].length).to be(count)
end
it "should be able to fetch a user's information" do
signin
get "/api/user/#{@login_name}.json"
expect_json_ok
end
it "should get error when the user to fetch does not exist" do
signin
get "/api/user/#{@not_exist_login_name}.json"
expect_json_error
end
describe "follow tests" do
before(:each) do
@new_user = User.create_with_check({login_name: @not_exist_login_name,
password: @wrong_pass})
@new_user_id = @new_user.id
@myself = User[@id]
@myself.followers.delete(@new_user)
@new_user.following.delete(@myself)
end
it "should be able to follow a user" do
signin
post_json '/api/follow.json', {id: @new_user_id, follow: true}
expect_json_ok
@myself = User[@id]
@new_user = User[@new_user_id]
expect(@myself.followers.member?(@new_user)).to be_true
expect(@new_user.following.member?(@myself)).to be_true
end
it "should be able to unfollow a user" do
@myself.followers.add(@new_user)
@new_user.following.add(@myself)
signin
post_json '/api/follow.json', {id: @new_user_id, follow: false}
expect_json_ok
@myself = User[@id]
@new_user = User[@new_user_id]
expect(@myself.followers.member?(@new_user)).to be_false
expect(@new_user.following.member?(@myself)).to be_false
end
it "should not be able to follow himself/herself" do
signin
post_json '/api/follow.json', {id: @id, follow: true}
expect_json_error
end
end
end
| true |
3f841b61b626027cc7d4f10b13f8db22a4fc1c1e | Ruby | ABaldwinHunter/advent_of_code_2020 | /day_02/solution.rb | UTF-8 | 746 | 3.5625 | 4 | [] | no_license | rows = File.read("./input.txt").split("\n")
items = rows.map { |row| row.split(" ") }.map do |item|
item[0] = item[0].split("-").map(&:to_i) # range
item[1] = item[1].split(":").first
item[2] = item[2]
item
end
## Part 1
# def valid?(range, letter, password)
# occurrences = password.count(letter)
# if (occurrences >= range.first and occurrences <= range.last)
# true
# else
# false
# end
# end
## Part 2
#
def valid?(indices, letter, password)
a = (password[(indices.first - 1)] == letter)
b = (password[(indices.last - 1)] == letter)
(a || b) && !(a && b)
end
valid_count = 0
items.each do |item|
if valid?(item[0], item[1], item[2])
valid_count += 1
end
end
puts "Valid count is #{valid_count}"
| true |
3c2778125adba23457f7a606c865b94dec08c044 | Ruby | raptor-xx/bakalar | /config/initializers/active_record.rb | UTF-8 | 666 | 2.625 | 3 | [] | no_license | module ActiveRecord
module ConnectionAdapters
class Column
def self.string_to_date_with_european_format(string)
begin
Date.strptime(string, '%d.%m.%Y')
rescue
string_to_date_without_european_format(string)
end
end
def self.string_to_time_with_european_format(string)
begin
DateTime.strptime(string, '%d.%m.%Y %H:%M')
rescue
string_to_time_without_european_format(string)
end
end
class << self
alias_method_chain :string_to_date, :european_format
alias_method_chain :string_to_time, :european_format
end
end
end
end | true |
d9bc097950d7af87347030d26f84ac324d600732 | Ruby | ameliend/rails-longest-word-game | /app/controllers/games_controller.rb | UTF-8 | 1,135 | 3.34375 | 3 | [] | no_license | require 'json'
require 'open-uri'
class GamesController < ApplicationController
def new
@letters = []
@voyelles_select = []
@voyelles = ['a','e','i','o','u']
7.times { @letters << ('a'..'z').to_a.sample }
3.times { @voyelles_select << @voyelles.to_a.sample }
@voyelles_select.each do |voyelle|
@letters << voyelle
end
end
def score
@result = ''
@letters = params[:letters]
if is_included?(params[:answer], @letters)
if english_word?(params[:answer])
@result = "Congratulation! #{params[:answer]} is a valid English word!"
else
@result = "Sorry, but #{params[:answer]} doeas not seem to be a valid English word..."
end
else
@result = "Sorry, but #{params[:answer]} can't be built out of \'#{@letters.upcase}\'"
end
@result
end
def english_word?(word)
url = "https://wagon-dictionary.herokuapp.com/#{word}"
select_word = open(url).read
word = JSON.parse(select_word)
word['found']
end
def is_included?(word, letters)
word.chars.all? { |letter| word.count(letter) <= letters.count(letter) }
end
end
| true |
1696645bbd322c5143771919bc523a257337bcfd | Ruby | dpneumo/simplestate | /test/dummy/dummy_state.rb | UTF-8 | 450 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'dummy/dummy_state_holder'
# Designed to match the public interface of decendents of State
class DummyState
attr_reader :holder
def initialize( holder: ,
opts: nil )
@holder = holder
@opts = opts
end
def name
'DummyState'
end
alias :to_s :name
def symbol
:DummyState
end
private
def transition_to(state)
holder.transition_to(state)
end
def enter
end
def exit
end
end
| true |
c5ca11daac9bea5e8ee87fb4d09207e93b8e5eb2 | Ruby | esmaeilmirzaee/rubycode | /udemy/number_of_vowels.rb | UTF-8 | 135 | 3.4375 | 3 | [] | no_license | class String
def number_of_vowels
gsub(/[^aeiou]/, '').size
end
end
p "hello".number_of_vowels
p 'something'.number_of_vowels
| true |
df282a5894e2fa1873d4e764f5cd2d9844e9c676 | Ruby | plamengj/Algorithms-in-ruby | /gnome_sort/gnome_sort.rb | UTF-8 | 702 | 3.875 | 4 | [] | no_license | # include RSpec
# require 'pry'
def gnome_sort(array)
i = 1 # If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
while i < array.size # Repeat till ‘i’ reaches the end of the array
# If the current array element is smaller than the previous array element then swap these two elements and go one step backwards
if array[i-1] > array[i]
array[i-1], array[i] = array[i], array[i-1]
i -= 1 if i > 1
else # If the current array element is larger or equal to the previous array element then go one step right
i += 1
end
end # If the end of the array is reached then stop and the array is sorted.
return array
end | true |
170df159c5030f8f2a7f6409be2ee2234aafc4bf | Ruby | bradbann/kermitweb | /github_issues.rb | UTF-8 | 1,197 | 2.65625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/ruby
require 'rubygems'
require 'curb'
require 'json'
F=File.open('source/code/issues.md','w')
repo = "https://api.github.com/users/kermitfr/repos"
def mdwrite(s)
F.write("#{s}\n")
end
header = <<EOT
---
layout: page
title: "issues"
comments: true
sharing: true
footer: true
sidebar: false
---
Issues extracted from GitHub.
Last updated : #{Time.now.strftime("%Y-%m-%d")}
EOT
mdwrite(header)
c = Curl::Easy.http_get(repo) do |curl|
curl.headers["User-Agent"] = "Curl/Ruby"
end
repos = JSON.parse(c.body_str)
repos.each do |repo|
mdwrite("## #{repo['name']}")
url = "https://api.github.com/repos/#{repo['full_name']}/issues"
get_issues = Curl::Easy.http_get(url) do |curl|
curl.headers["User-Agent"] = "Curl/Ruby"
end
arr_issues = []
issues = JSON.parse(get_issues.body_str)
if issues.length < 1
mdwrite("No issue.")
else
mdwrite("| Issue name | Label ")
mdwrite("|:-----------|:------------")
end
issues.each do |issue|
label = "none"
if issue.has_key?("labels") and issue["labels"][0]
label = issue["labels"][0]["name"]
end
mdwrite("| #{issue["title"]} | #{label}")
end
mdwrite("\n")
end
| true |
773a98f9f34c535032fbfb2c5eddbe167678083d | Ruby | pikender/my_ruby_projects | /gol/lib/composite_command.rb | UTF-8 | 422 | 2.71875 | 3 | [] | no_license | class CompositeCommand < Command
attr_reader :commands
def initialize
@commands = []
end
def add_command(cmd)
@commands << cmd
end
def delete_command(cmd)
@commands.delete(cmd)
end
def execute
@commands.each {|cmd| cmd.execute}
end
def description
description = ''
@commands.each {|cmd| description += "#{cmd.cell.to_debug} #{cmd.description}\n"}
description
end
end
| true |
80ba25c1214cb109c50b43f0fdb9d67a2f5d70ed | Ruby | tianhe/tradewinds | /lib/marketplace/craigslist.rb | UTF-8 | 5,929 | 2.671875 | 3 | [] | no_license | class Marketplace::Craigslist
def initialize url
@url = url
end
def fetch_listings
proxies = HideMyAss::ProxyList.new.fetch
request = HideMyAss::Request.new(proxies)
response = request.run(@url)
@rss = SimpleRSS.parse response.response_body
end
def populate_listings
@rss.items.each do |listing|
listing_price = Marketplace::Craigslist.listing_price(listing)
next if listing_price.to_i > 1000
model = Marketplace::Craigslist.model(listing.title)
next unless model
transaction_price = Marketplace::Craigslist.transaction_price(listing)
list_time = Marketplace::Craigslist.list_time(listing)
link = Marketplace::Craigslist.link(listing)
description = Marketplace::Craigslist.description(listing)
title = Marketplace::Craigslist.title(listing)
condition = Marketplace::Craigslist.condition(listing.title) || Marketplace::Craigslist.condition(listing.description)
brand = Marketplace::Craigslist.brand(listing)
capacity = Marketplace::Craigslist.capacity(listing)
color = Marketplace::Craigslist.color(listing)
carrier = Marketplace::Craigslist.carrier(listing.title) || Marketplace::Craigslist.carrier(listing.description)
unlocked = Marketplace::Craigslist.unlocked(listing)
specs = Marketplace::Craigslist.specs(listing)
cash = Marketplace::Craigslist.cash(listing.description)
city = Marketplace::Craigslist.city(listing.link)
neighborhood = Marketplace::Craigslist.neighborhood(listing.link)
scratches = Marketplace::Craigslist.scratches(listing.description)
cracked_screen = Marketplace::Craigslist.cracked_screen(listing.description)
Listing.create(
listing_price: listing_price,
transaction_price: transaction_price,
list_time: list_time,
url: link,
condition: condition,
description: description,
title: title,
brand: brand,
model: model,
capacity: capacity,
color: color,
carrier: carrier,
specs: specs,
unlocked: unlocked,
scratches: scratches,
cracked_screen: cracked_screen,
cash: cash,
city: city,
neighborhood: neighborhood,
source: 'craigslist'
)
end
end
class << self
def city link
link.split(".")[0].gsub('http://','')
end
def neighborhood link
parts = link.split("/")
if parts.length > 5
return parts[4]
end
end
def listing_price listing
listing.title.scan(/$(.*)/).first.try(:first)
end
def transaction_price listing
end
def list_time listing
listing.dc_date
end
def link listing
listing.link
end
def description listing
listing.description
end
def title listing
listing.title
end
def cash phrase
!!phrase.match(/cash/i)
end
def cracked_screen phrase
return false if phrase.match(/no crack/i)
return true if phrase.match(/crack/i)
end
def scratches phrase
return false if phrase.match(/no scratches/i)
return true if phrase.match(/scratches/i)
end
def condition phrase
phrase = phrase.gsub(/\*/, '')
if phrase.match(/brand new/i)
'brand new'
elsif phrase.match(/ mint /i) || phrase.match(/^mint /i)
'mint'
elsif phrase.match(/like new/i)
'like new'
elsif phrase.match(/ perfect /i) || phrase.match(/^perfect /i)
'perfect'
elsif phrase.match(/ good /i) || phrase.match(/^good /i)
'good'
elsif phrase.match(/ great /i) || phrase.match(/^great /i)
'great'
elsif phrase.match(/ new /i) || phrase.match(/^new /i)
'new'
elsif phrase.match(/ excellent /i)
'excellent'
else
nil
end
end
def brand listing
'Apple'
end
def color listing
if listing.title.present?
%w(white black gold blue yellow pink green gray silver).each do |c|
return c if listing.title.match(/#{c}/i)
end
end
if listing.description.present?
%w(white black gold blue yellow pink green gray grey silver).each do |c|
c = 'gray' if c == 'grey'
return c if listing.description.match(/#{c}/i)
end
end
return nil
end
def carrier phrase
carriers = %w(att sprint verizon tmobile)
if phrase.present?
phrase = phrase.gsub(/\&|\&|\-/, '')
carriers.each do |c|
return c if phrase.match(/#{c}/i)
end
end
return nil
end
def unlocked listing
if listing.title.try(:match, /unlock/i) || listing.description.try(:match, /unlock/i)
true
end
end
def model title
models = {"iphone4s" => "iphone4s",
"iphone5s" => "iphone5s",
"iphone5c" => "iphone5c",
'iphone6\+' => "iphone6plus",
"iphone6plus" => "iphone6plus",
"iphone6" => "iphone6",
"iphone5" => "iphone5"
}
title = title.gsub(/ |\(|\)/,'').downcase
models.each do |m|
return m[1] if title.match(m[0])
end
nil
end
def capacity listing
capacities = {
'128gb' => '128gb',
'16gb' => '16gb',
'32gb' => '32gb',
'64gb' => '64gb',
'8gb' => '8gb'
}
if listing.title
title = listing.title.gsub(/ |\(|\)/,'').downcase
capacities.each do |c|
return c[1] if title.match(c[0])
end
end
if listing.description
description = listing.description.gsub(/ |\(|\)/,'').downcase
capacities.each do |c|
return c[1] if description.match(c[0])
end
end
nil
end
def specs listing
end
end
end | true |
b7f2507a9eef5cbffa22a2e650379e96899ddb44 | Ruby | ladeeluc/deli-counter-ruby-apply-000 | /deli_counter.rb | UTF-8 | 1,061 | 3.859375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def line(position)
index = 0
if position.empty?# should say the line is empty
puts "The line is currently empty."
else #should display the current line
#works with different people in line
string = "The line is currently:"
position.each_with_index do |item, index|
string << " #{index+1}. #{item}"
end
puts string
end
end
# should add a person to the line
# there are already people in line
# should add a person to the end of the line
# adding multiple people in a row
def take_a_number(katz_deli,name)# there is nobody in line
katz_deli.push(name)
puts "Welcome, #{name}. You are number #{katz_deli.count} in line."
end
#should say that the line is empty
# should serve the first person in line and remove them from the queue
def now_serving(katz_deli)
if katz_deli.empty?
puts "There is nobody waiting to be served!"
else puts "Currently serving #{katz_deli[0]}."
katz_deli.shift
end
end
#binding.pry
# katz_deli = []
# foo = "Ada" | true |
7a524b095b28ec32ebfdb8665d3ffc3ab3d49a4a | Ruby | Siphonay/epitech_projects | /projects/projet_103architect/103architect/103architect | UTF-8 | 6,004 | 3.46875 | 3 | [] | no_license | #!/usr/bin/env ruby
# coding: utf-8
# PROJECT 103architech
# TEAM "2 GUYS 1 PROJECT"
# ALEXIS "SAM" VIGUIÉ <alexis.viguie@epitech.eu
# ALEXANDRE "KARIBOU" LARONCE <alexandre.laronce@epitech.eu>
# No license applied. We are not liable in any way from anything caused by any possible use of the following code.
# Started 07-12-2015 17h42
# Last updated 09-12-2015 14h47
### THIS IS A WORK IN PROGRESS ###
# Including external methods
require_relative 'print_and_flush' # This method is for printing without a newline
require_relative 'abort_84' # This method is for exiting the program with the return value "84" in case of error, as stated by the subject
# This next part verifies the validity of the arguments passed and stores them to be used in the script
abort_84 "usage: #{$PROGRAM_NAME} x y transfo1 arg11 [arg12] [transfo2 arg12 [arg22]]" if ARGV.length < 3 # Checking the validity of the number of arguments passed
abort_84 "error: invalid coordinates" unless ((ARGV[0].to_i != 0 || # Checking if the coordinates arguments are valid
ARGV[0][0] == '0') &&
(ARGV[1].to_i != 0 ||
ARGV[1][0] == '0'))
def build_oplist(argpos, oplist) # This recursive method checks the validity of the flags and their arguments and builds a list of operations
valid_args = ["-t", "-h", "-r", "-s"]
abort_84 "error: invalid flag" unless valid_args.include? ARGV[argpos] # Checking if the flag is valid
curr_op = Array.new # Creating an array to be pushed into the operations array
curr_op.push(ARGV[argpos]) # Adding the operation type to the current operation array
if (ARGV[argpos] == "-t" || ARGV[argpos] == "-h")
abort_84 "error: invalid flag argumets" unless ((ARGV[argpos + 1] &&
((ARGV[argpos + 1].to_i != 0) || # Those conditions are used to check the existence and validity of the flag parameters
(ARGV[argpos + 1][0] == '0'))) &&
(ARGV[argpos + 2] &&
((ARGV[argpos + 2].to_i != 0) ||
(ARGV[argpos + 2][0] == '0'))))
curr_op.push(ARGV[argpos + 1].to_i) # These are for pushing the operations arguments into the array
curr_op.push(ARGV[argpos + 2].to_i)
nextflag = 3 # Determining the theoretical position of the next flag
else
abort_84 "error: invalid flag arguments" unless (ARGV[argpos + 1] &&
((ARGV[argpos + 1].to_i != 0) ||
(ARGV[argpos + 1][0] == '0')))
curr_op.push(ARGV[argpos + 1].to_i)
nextflag = 2
end
oplist.push(curr_op) # Adding current operation to the operations list
oplist = build_oplist (argpos + nextflag), oplist if ARGV[argpos + nextflag] # Recurse until there are no more flags to check, also adding the new operations to the list
return oplist
end
oplist = (build_oplist 2, Array.new) # Building the operations list starting at the third argument containing the first flag
# The following parts computes the operations stored in the operations list one by one on a matrix corresponding to the coordinates entered in parameter
mtx_end = [[0, 1, ARGV[0].to_i], # Defining the matrix from the base points passed in argument
[1, 0, ARGV[1].to_i],
[0, 0, 1]]
x_end = ARGV[0].to_i
y_end = ARGV[1].to_i
oplist.each do |operation| # Do an operation for each element in the operations list
case operation[0] # This case control structure is used to determine the operation to do and to display it, then execute it
when "-t"
puts "Translation by the vector (#{operation[1]}, #{operation[2]})" # Prints the name of the opertions that are done
trs_mtx = [operation[1], operation[2], 1]
trs_mtx_tmp = Array.new(3) { 0 }
(0..mtx_end.size - 1).each do |i|
(0..trs_mtx.size - 1).each do |j|
trs_mtx_tmp[i] += mtx_end[i][j] * trs_mtx[j]
end
end
mtx_end = [[1, 0, trs_mtx_tmp[0]],
[0, 1, trs_mtx_tmp[1]],
[0, 0, trs_mtx_tmp[2]]]
x_end = x_end + operation[1].to_f
y_end = y_end + operation[2].to_f
when "-h"
puts "Homothety by the ratios #{operation[1]} and #{operation[2]}"
when "-r"
puts "Rotation at a #{operation[1]} degree angle"
### ROTATION ALGORITHM TO BE WRITTEN
when "-s"
puts "Symmetry about an axis inclined with an angle of #{operation[1]} degrees"
### SYMMETRY ALGORITHM TO BE WRITTEN
end
end
# The next part is used to display the final results (matrix and position)
mtx_end.each do |row_i|
(0..row_i.length - 1).each do |i|
print_and_flush "%.2f" % row_i[i]
print_and_flush "\t" if row_i[i + 1]
end
print_and_flush "\n"
end
puts "(#{ARGV[0]},#{ARGV[1]}) => (%.2f,%.2f)" % [x_end, y_end]
exit 0
| true |
78eea8d021e8235299645bcd531af628391aee38 | Ruby | iSarCasm/codebreaker-app | /lib/models/game.rb | UTF-8 | 887 | 2.703125 | 3 | [
"MIT"
] | permissive | class Game < SessionStorage
extend SingleUnitStorage
attr_reader :codebreaker_game
def self.storage_path
:game
end
def initialize(difficulty:)
@codebreaker_game = Codebreaker::Game.new
@codebreaker_game.start(difficulty.to_sym)
end
def guess(code)
code = code.split('').map { |x| x.to_i(16) }
codebreaker_game.guess(code)
rescue IndexError => e
Error.create "You have to input #{symbols_count} chars."
rescue ArgumentError => e
Error.create "You have to input chars in range 1-#{symbols_range.to_s(16)}"
end
def hint
codebreaker_game.hint
rescue Exception => e
Error.create e.message
end
def current_page
state == :playing ? '/play' : '/result'
end
def method_missing(method, *args)
if codebreaker_game.respond_to?(method)
codebreaker_game.send(method, *args)
else
super
end
end
end
| true |
b7432c0c2c79288efea0fe9d4b7f6be8f6ab1e8a | Ruby | natashamcintyre/oystercard2 | /spec/journey_spec.rb | UTF-8 | 1,228 | 2.625 | 3 | [] | no_license | require "journey"
RSpec.describe Journey do
let(:exit_station) { double :exit_station, zone: 1 }
let(:entry_station) { double :entry_station, zone: 1 }
# let(:completed) { double :completed, zone: 1 }
it "knows if a journey is not complete" do
expect(subject).not_to be_completed
end
it "has a penalty fare by default" do
expect(subject.fare).to eq Journey::PENALTY_FARE
end
it "returns itself when exiting a journey" do
expect(subject.finished(exit_station)).to eq(subject)
end
context "given an entry_station station" do
subject { described_class.new(entry_station: entry_station) }
# it "has an entry_station station" do
# expect(subject.entry_station).to eq entry_station
# end
it "returns a penalty fare if no exit_station station given" do
expect(subject.fare).to eq Journey::PENALTY_FARE
end
context "given an exit_station station" do
let(:other_station) { double :other_station }
before do
subject.finished(exit_station)
end
it "calculates a fare" do
expect(subject.fare).to eq 1
end
it "knows if a journey is complete" do
expect(subject).to be_completed
end
end
end
end
| true |
be2478708a38a1e1c6f65fd5a0ea2e72c27dc1b4 | Ruby | TonyCWeng/w2d4 | /two_sum.rb | UTF-8 | 1,141 | 3.703125 | 4 | [] | no_license | def bad_two_sum?(arr, target)
(0...arr.length-1).each do |i|
(i+1...arr.length).each do |j|
return true if arr[i] + arr[j] == target
end
end
false
end
def okay_two_sum?(arr, target)
sorted = arr.sort
(0...sorted.length).each do |i|
remainder = target - sorted[i]
return true if b_search(sorted[i+1..-1], remainder)
end
false
end
def b_search(arr, remainder)
return nil if arr.empty?
mid = arr.length / 2
return mid if arr[mid] == remainder
left = arr.take(mid)
right = arr.drop(mid + 1)
if remainder < arr[mid]
b_search(left, remainder)
else
val = b_search(right, remainder)
val.nil? ? nil : val + remainder + 1
end
end
def two_sum?(arr, target)
number_counts = Hash.new(0)
arr.each do |el|
number_counts[el] += 1
end
number_counts.keys.each do |key|
remainder = target - key
if number_counts[key] > 1
return true if number_counts.has_key?(remainder)
elsif key == remainder && number_counts[key] <= 1
return false
else
return true if number_counts.has_key?(remainder)
end
end
false
end
p two_sum?([1,-1,7, 7], 14)
| true |
5ce04d9c92bd74a889669ecd0ed8c86e6375f8b4 | Ruby | unheavenlycreature/sinatra-mastermind | /lib/mastermind.rb | UTF-8 | 1,288 | 3.1875 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'codemaker'
# A game manager for the board game "Mastermind"
class Mastermind
def initialize
@codemaker = RobotCodeMaker.new
@remaining_turns = 12
end
def new_game
@remaining_turns = 12
@codemaker.create_secret_code
end
def correct_guess?(guess)
@remaining_turns -= 1
guess == @codemaker.secret_code
end
def lost_game?
@remaining_turns.zero?
end
def hint_pegs(guesses)
secret_code = @codemaker.secret_code.clone
guess = guesses.clone
hints, remaining = add_perfect_matches(secret_code, guess)
hints = add_color_matches(secret_code, remaining, hints)
hints.shuffle
end
private
def add_perfect_matches(secret_code, guess)
hints = []
remaining = Hash.new(0)
until guess.empty?
secret_code_peg = secret_code.shift
guess_peg = guess.shift
if secret_code_peg == guess_peg
hints << :black
else
secret_code << secret_code_peg
remaining[guess_peg] += 1
end
end
[hints, remaining]
end
def add_color_matches(secret_code, remaining, hints)
secret_code.each do |peg|
if remaining[peg].positive?
hints << :white
remaining[peg] -= 1
end
end
hints
end
end
| true |
a6400d5594aae10048ee42d59498a791d6c308c0 | Ruby | moralesalberto/my_game | /my_game.rb | UTF-8 | 724 | 3.046875 | 3 | [] | no_license | require 'rubygems'
require 'gosu'
require 'player'
require 'ball'
class MyGame < Gosu::Window
def initialize
super(1000,1000,false)
@player1 = Player.new(self)
@balls = 3.times.map {|count| Ball.new(self,5+count)}
end
def update
if button_down? Gosu::Button::KbLeft
@player1.move_left
end
if button_down? Gosu::Button::KbRight
@player1.move_right
end
if button_down? Gosu::Button::KbDown
@player1.move_down
end
if button_down? Gosu::Button::KbUp
@player1.move_up
end
@balls.each {|ball| ball.update}
end
def draw
@player1.draw
@balls.each {|ball| ball.draw}
end
end
window = MyGame.new
window.show | true |
9ac838db54d6c6a275cb95ad8bc7ec7108d7dc20 | Ruby | polyfox/moon-packages | /spec/moon/packages/std/core_ext/integer_spec.rb | UTF-8 | 519 | 2.75 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
require 'std/core_ext/integer'
describe Integer do
context '#pred' do
it 'should return the preceeding integer' do
expect(1.pred).to eq(0)
end
end
context '#round' do
it 'should round the integer' do
expect(1.round(2)).to eq(1.0)
end
end
context '#masked?' do
it 'should check if bits are set' do
expect(0.masked?(0)).to eq(true)
expect(0b111001.masked?(0b1)).to eq(true)
expect(0b111001.masked?(0b10)).to eq(false)
end
end
end
| true |
d55ccb5e8d443e519af7bf66d7cf32f52b348477 | Ruby | Franerial/Thinknetica_Ruby_Base-Railway | /lesson_7/wagon.rb | UTF-8 | 353 | 3.03125 | 3 | [] | no_license | require_relative "manufacter"
require_relative "validation"
class Wagon
include Manufacter
include Validation
attr_reader :type
def initialize(type)
@type = type
validate!
end
private
def validate!
raise ArgumentError, "Введён неверный тип вагона" unless [:passenger, :cargo].include? type
end
end
| true |
49033153e1db5e3f50b6d75da4505c24c650bbed | Ruby | koheiyamada/jenkins_test | /script/bank_accounts/reset_bank_id.rb | UTF-8 | 669 | 2.59375 | 3 | [] | no_license | yucho = Bank.find_by_code 'yucho'
mitsu = Bank.find_by_code 'mitsubishi_tokyo_ufj'
ActiveRecord::Base.transaction do
BankAccount.all.each do |bank_account|
if bank_account.bank.blank?
account = bank_account.account
if account.is_a? YuchoAccount
puts "Bank account of user #{bank_account.owner.id} is Yucho"
bank_account.bank = yucho
elsif account.is_a? MitsubishiTokyoUfjAccount
puts "Bank account of user #{bank_account.owner.id} is MitsubishiTokyoUfj"
bank_account.bank = mitsu
else
puts "Bank account of user #{bank_account.owner.id} is ???"
end
bank_account.save!
end
end
end
| true |
9456f55234e92c982b45e89b7229727d45043e82 | Ruby | jason/url-shortener | /app/models/url.rb | UTF-8 | 952 | 2.546875 | 3 | [] | no_license | require 'launchy'
class URL < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :clicks
# attr_accessible :title, :body
# def get_url(url)
# @long_url = url
# save
# end
# def get_short_url
# @short_url = @id
# save
# end
def self.create_url(long_url, user_id = nil)
url = URL.new
url.long_url = long_url
url.user_id = user_id
url.get_short_url
url
end
def get_short_url
save
self.short_url = id
save
end
def open_url(user_id)
Launchy.open(long_url)
click = Click.new
click.url_id = id
click.user_id = user_id
click.save
end
def self.click_counter(url_id)
URL.find(url_id).clicks.count
end
def self.unique_click_counter(url_id_)
Click.where(url_id: url_id_).uniq.pluck(:user_id).count
end
def self.clicks_from_ten_min(url_id_)
Click.where(:created_at => (10.minutes.ago..Time.now), :url_id => url_id_)
end
end
| true |
2e6dff1fe805b3a0b2d63ba66cb92a2f8c5f619b | Ruby | hale4029/backend_module_0_capstone | /day_2/exercises/iteration_practice.rb | UTF-8 | 866 | 4.46875 | 4 | [] | no_license | #Iteration and each Practice
#doubles
x = (1..10).to_a
x.each { |x| puts x * 2 }
print "-----------\n"
#triples
x.each { |x| puts x * 3 }
print "-----------\n"
#print even numbers
x.each { |x| puts x if x.even? }
print "-----------\n"
#create new array whcih contains each number multiplied by 2
x_new = x.collect { |x| x * 2 }
print x_new
print "\n"
print x
print "\n"
#array name exercise
names = ["Alice Smith", "Bob Evans", "Roy Rogers"]
names.each { |x| puts x }
print "\n"
names.select { |x| puts x.split.first }
print "\n"
names.select { |x| puts x.split.last }
print "\n"
#initials
names.each do |x|
puts "#{x.split.first.match(/\p{Upper}/)}." + "#{x.split.last.match(/\p{Upper}/)}."
end
print "\n"
names.each { |x| puts "#{x.split.last}," + "Length: #{x.split.last.length}" }
print "\n"
#characters in total
integer = names.join.length
puts integer
| true |
e853da75901ee887517a0ae44d428c693aebcd18 | Ruby | jgonzalezd/codility | /02/cyclic_rotation.rb | UTF-8 | 1,755 | 3.1875 | 3 | [] | no_license | require 'benchmark'
require 'byebug'
require 'test/unit'
include Test::Unit::Assertions
# [0,1]
# [1,0] n= 1
# [0,1] n= 2
# [0,1,2]
# [2,1,0] n=1
# [0,1,2] 1 2 3
# [0,1,2] n= 3 [2,0,1] | [1,2,0] | [0,1,2]
# [0,0,0,0,0,0,1,1,1,1]
# [1,1,1,0,0,0,0,0,0,1]
# [0,0,0,0,0,1,1,1,1,0]
def solution(array_a, k)
return array_a if array_a.size < 2 || k % array_a.size == 0
k = k % array_a.size if k > array_a.size
first_half = array_a.size-k
array_b = array_a[(first_half..array_a.size-1)]+array_a[(0..first_half-1)]
end
def solution2(a, k)
length = a.length
result = Array.new length
length.times {|i| result[(i + k)] = a[1] }
result
end
array1 = Array.new(10){ rand(-1000..-1000) }
array2 = Array.new(100){ rand(-1000..-1000) }
array3 = Array.new(1000){ rand(-1000..-1000) }
array4 = Array.new(10000){ rand(-1000..-1000) }
array5 = Array.new(100000){ rand(-1000..-1000) }
array6 = Array.new(1000000){ rand(-1000..-1000) }
Benchmark.bm do |bm|
bm.report { solution(array1,99) }
bm.report { solution2(array1,99) }
p '----------------------------'
bm.report { solution(array2,99) }
bm.report { solution2(array2,99) }
p '----------------------------'
bm.report { solution(array3,99) }
bm.report { solution2(array3,99) }
p '----------------------------'
bm.report { solution(array4,99) }
bm.report { solution2(array4,99) }
p '----------------------------'
bm.report { solution(array5,99) }
bm.report { solution2(array5,99) }
p '----------------------------'
bm.report { solution(array6,999999) }
bm.report { solution2(array6,999999) }
p '----------------------------'
end
#
# a_small = Array.new(rand(0..2)){ rand(-1000..-1000) }
# assert_equal a_small.rotate(-4), solution(a_small,-4)
| true |
5d2def01d16cdb653946d9a65edd6560f37efbfa | Ruby | pickleburns/TB-tdd | /hashtag/spec/lib/fake_twitter_spec.rb | UTF-8 | 1,040 | 2.65625 | 3 | [] | no_license | require 'spec_helper'
require 'fake_twitter'
describe FakeTwitter do
context '#search' do
it 'returns an array of objects who respond to text' do
fake_twitter = FakeTwitter.new('#awesome', [{'text' => 'cool yo'}, {'text' => 'sweet bud'}])
results = fake_twitter.search('#awesome')
results.map(&:text).should == ['cool yo', 'sweet bud']
end
it 'handles keys that are symbols' do
fake_twitter = FakeTwitter.new('#awesome', [{text: 'cool yo'}, {text: 'sweet bud'}])
results = fake_twitter.search('#awesome')
results.map(&:text).should == ['cool yo', 'sweet bud']
end
it "returns and empty array if the term isn't found" do
fake_twitter = FakeTwitter.new('#awesome', [{'text' => 'cool yo'}, {'text' => 'sweet bud'}])
results = fake_twitter.search('')
results.should == []
end
it 'returns an array of Twitter::Statuses' do
fake_twitter = FakeTwitter.new('#awesome', [{'text' => 'status'}])
results = fake_twitter.search('#awesome')
results.first.should be_a(Twitter::Status)
end
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.