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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
70934202a1df810a15077bd1f706943dbc495110 | Ruby | artsy/gris | /lib/gris/middleware/error_handlers.rb | UTF-8 | 1,146 | 2.53125 | 3 | [
"MIT"
] | permissive | module Gris
class Middleware
class ErrorHandlers
def initialize(app)
@app = app
end
def call(env)
response = @app.call env
case response[0]
when 400..500
format_error_response response
else
response
end
rescue RuntimeError => e
error = { status: 500, message: e.message }
error_response error.to_json, 500
rescue ::ActiveRecord::RecordNotFound => e
error = { status: 404, message: e.message }
error_response error.to_json, 404
rescue ::ActiveRecord::RecordInvalid => e
error = { status: 409, message: e.message }
error_response error.to_json, 409
end
private
def format_error_response(response)
if response[2].respond_to? :body
response
else
error = { status: response[0], message: response[2] }
error_response(error.to_json, response[0], response[1])
end
end
def error_response(message, status, headers = {})
Rack::Response.new([message], status, headers).finish
end
end
end
end
| true |
cd101247aab5e32a3e7f9ea55d5c4dbae7d4c568 | Ruby | nip3o/7languages | /ruby/2.rb | UTF-8 | 1,133 | 3.515625 | 4 | [] | no_license |
class Tree
attr_accessor :node_name, :children
def initialize(structure)
name, child_structure = structure.first
@node_name = name
@children = child_structure.nil? ? [] : child_structure.map { |e| Tree.new [e] }
end
def visit_all(&block)
visit &block
@children.each { |c| c.visit_all &block }
end
def visit(&block)
block.call self
end
end
def print_each
numbers = (1..16).to_a
end
def print_each_slice
numbers = (1..16).to_a
numbers.each_slice(4) { |e| print e }
end
def print_tree
root = Tree.new({'grandpa' => {'dad' => {'c1' => {}, 'c2' => {}}, 'uncle' => {'c3' => {}}}})
root.visit_all { |c| puts c.node_name }
end
def simple_grep_1(filename, needle)
File.open filename do |f|
f.each_line.with_index do |line, i|
puts "#{i + 1}: #{line}" if /#{needle}/.match line
end
end
end
def simple_grep_2(filename, needle)
IO.readlines(filename).each_with_index do |line, i|
puts "#{i + 1}: #{line}" if /#{needle}/.match line
end
end
# print_each
# print_each_slice
# print_tree
# simple_grep_1('lorem.txt', 'elit')
# simple_grep_2('lorem.txt', 'elit')
| true |
fef96edfc007a482fb7c44044d4d572637162c64 | Ruby | andrewsapa/ruby_small_problems | /easy_4/convert_signed_numbertostring.rb | UTF-8 | 1,769 | 4.3125 | 4 | [] | no_license | ### Convert a Signed Number to a String! ###
# In the previous exercise, you developed a method that converts non-negative
# numbers to strings. In this exercise, you're going to extend that method by
# adding the ability to represent negative numbers as well.
# Write a method that takes an integer, and converts it to a string representation.
# You may not use any of the standard conversion methods available in Ruby, such as
# Integer#to_s, String(), Kernel#format, etc. You may, however, use integer_to_string
# from the previous exercise.
def signed_integer_to_string(num)
num_array = []
float_num = num + 0.0
loop do
num_array << (((float_num / 10) - ((float_num / 10).truncate)) * 10).round
float_num = (float_num / 10).truncate + 0.0
break if float_num == 0
end
string_num = num_array.reverse.join
plus_minus_checker(string_num)
end
def plus_minus_checker(string)
if string.start_with?('-')
string_array = string.split('')
array = []
string_array.select do |e|
if e != '-'
array << e
end
end
array.prepend('-').join
elsif string == '0'
'0'
else
string_array = string.split('')
string_array.prepend('+').join
end
end
p signed_integer_to_string(4321) == '+4321' # => true
p signed_integer_to_string(-123) == '-123' # => true
p signed_integer_to_string(0) == '0' # => true
p signed_integer_to_string(-9999999999999998) == '-9999999999999998' # => true
# seems to work from -9,999,999,999,999,998 up to 9,999,999,999,999,998
# launch school's answer
def signed_integer_to_string(number)
case number <=> 0
when -1 then "-#{integer_to_string(-number)}"
when +1 then "+#{integer_to_string(number)}"
else integer_to_string(number)
end
end | true |
c84d515b1af62b793b469c6c8c5f45b54d5bab65 | Ruby | jamesshieh/algorithms | /hornsat/string_validate.rb | UTF-8 | 121 | 2.703125 | 3 | [] | no_license | # String extention to validate by regexp statement
class String
def validate(regex)
!self[regex].nil?
end
end
| true |
17ca393a8ec3f6b823479e2b988c99fb2f8ff940 | Ruby | Reltre/intro-ruby-workbook_tealeaf | /advanced_questions/quiz_1.rb | UTF-8 | 2,152 | 3.78125 | 4 | [] | no_license | =begin
#1
When n is refernced you should get an error saying that you are referencing an
object that has not been created yet. The if statement will never execute
since it is always false, and this n will never be assigned an initial value.
(^incorrect)
I'm incorrect here, ruby will set the local variable to nil. No undef-
ined method or variable error is thrown. Note: This only works,
because of the assignment in the if statement. If n is never assigned a
value at all, a NameError will be thrown.
#2
Given:
my_hash = {a: 'hi'}
n = my_hash[:a]
n << ' there'
puts n # => "hi there"
puts my_hash
What is outputted by the last line?
hi there is the output. Because, n is given a
reference to the value associated with the key a
when you change the n variable it will also change the value
in the hash as well.
#3
A)
Outputs : One is one; Two is two; Three is three.
B)
Outputs: One is one; Two is two; Three is three.
C)
Outputs: One is two;Two is three;Three is one
#4
A)
Outputs: [1,2,3,4] : The lambdh returns new objects once you multiply
10* input. The original array values remain unchanged.
B)
Outputs: da_string => "40"
In both the two cases below, because we are changing an existing
String that has scope outside the lambdha, the changes will persist.
C)
Outputs: da_string -> "10203040"
D)
Outputs: da_string -> "10203040"
E)
Outputs: "original"
#5
def give_UUID
hexs = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']
eight = (hexs.sample(8) << '-').join
fours = ""
3.times {fours << hexs.sample(4).join + '-' }
twelve = hexs.sample(8).join
hex = eight + fours + twelve
return hex
end
#6
class String
def map_words!
result = self
result =
result.chop.split.map! {|v| v.reverse! }
self.replace(result.join(' ').<<('.'))
return self
end
end
str = "Herman Munster is a BIG BIG man."
p str.map_words!
#7
def dot_separated_ip_address?(input_string)
dot_separated_words = input_string.split(".")
return false if dot_separated_words.size != 4
while dot_separated_words.size > 0 do
word = dot_separated_words.pop
return false if !is_a_number?(word)
end
return true
end
=end | true |
eef39b8276cefcbbc57e441f746ffbd6b8e31cde | Ruby | CarouselSMS/VampireAds | /app/models/user.rb | UTF-8 | 1,210 | 2.515625 | 3 | [
"MIT"
] | permissive | class User < ActiveRecord::Base
has_many :messages
# Period after which, users without any activity considered to be expired
EXPIRY_PERIOD = 12.hours
# Unexpired sessions
named_scope :unexpired, :conditions => [ "updated_at > ?", EXPIRY_PERIOD.ago ]
before_create :assign_seq_num
def pp_phone_num
num = self.phone_num
return "(#{num[0..2]}) #{num[3..5]} - #{num[6..9]}"
end
def phone_num_w1
case name
when "no associated user"
require 'cgi'
CGI::escape "from console"
else
"1#{phone_num}"
end
end
# Sees if the session has expired and updates the
# seq num.
def update_expired_seq_num
return false unless expired?
update_attribute(:seq_num, next_seq_num)
update_attribute(:updated_at, Time.now)
true
end
private
# If session is expired, returns TRUE
def expired?
return false if new_record?
updated_at.nil? || updated_at < EXPIRY_PERIOD.ago
end
# Return the next sequence number among unexpired users.
def next_seq_num
(User.unexpired.map { |u| u.seq_num || 0 }.max || 0)+ 1
end
# Assigns new sequence number before saving the record
def assign_seq_num
self.seq_num = next_seq_num
end
end
| true |
e99aec3795291a6218478c9dd73c967ee63e7c36 | Ruby | hendrikb/ruby-rectangle-intersection | /rectangle.rb | UTF-8 | 884 | 3.5 | 4 | [] | no_license | require_relative './point.rb'
class Rectangle
attr_reader :top_left, :top_right, :bottom_left, :bottom_right, :name
def initialize name, bottom_left, top_right
@name = name
@bottom_left = bottom_left
@top_right = top_right
@bottom_right = Point.new top_right.x, bottom_left.y
@top_left = Point.new bottom_left.x, top_right.y
end
def range
# The right x is excluded
@top_left.x...@bottom_right.x
end
def height
@bottom_left.y...@top_right.y
end
def intersect? another_rectangle
[ another_rectangle.bottom_right, another_rectangle.bottom_left,
another_rectangle.top_right, another_rectangle.top_left].each do |point|
return true if range.include?(point.x) and height.include?(point.y)
end
return false
end
def to_s
"#{@name.upcase}: bottom_left #{@bottom_left}, top_right #{@top_right}"
end
end
| true |
64f68c6336a4b85c861522efb126a7271d486409 | Ruby | GSA/voc_admin | /app/models/reporting_models/choice_question_reporter.rb | UTF-8 | 8,732 | 2.515625 | 3 | [] | no_license | class ChoiceQuestionReporter < QuestionReporter
include ActionView::Helpers::NumberHelper
include Rails.application.routes.url_helpers
field :q_id, type: Integer # ChoiceQuestion id
field :question_text, type: String
# Total number of Answers chosen across ChoiceQuestion responses;
# used for simple average count of number of responses (for multiselect)
field :chosen, type: Integer, default: 0
embedded_in :survey_version_reporter
embeds_many :choice_question_days
embeds_many :choice_answer_reporters
embeds_many :choice_permutation_reporters
index "q_id" => 1
index "choice_question_days.date" => 1
def type
@type ||= allows_multiple_selection ? :"choice-multiple" : :"choice-single"
end
# average number of chosen Answer options across all answered questions
def average_answers_chosen_for_date_range(start_date, end_date, precision = 1)
chosen_for_dates = chosen_for_date_range(start_date, end_date)
answered_for_dates = answered_for_date_range(start_date, end_date)
(chosen_for_dates / answered_for_dates.to_f).round(precision)
end
def top_permutations_for_date_range(start_date, end_date, number = 10)
permutations = choice_permutation_reporters.map {|cqr| cqr.permutation_for_date_range(start_date, end_date)}
permutations.sort_by {|p| -p.count}.first(number)
end
def answered_for_date_range(start_date, end_date, force = false)
return answered if !force && start_date.nil? && end_date.nil?
val = days_for_date_range(start_date, end_date).sum(:answered)
val.nil? ? 0 : val
end
def chosen_for_date_range(start_date, end_date, force = false)
return chosen if !force && start_date.nil? && end_date.nil?
val = days_for_date_range(start_date, end_date).sum(:chosen)
val.nil? ? 0 : val
end
def days_for_date_range(start_date, end_date)
days = choice_question_days
days = days.where(:date.gte => start_date.to_date) unless start_date.nil?
days = days.where(:date.lte => end_date.to_date) unless end_date.nil?
days
end
def ordered_choice_answer_reporters_for_date_range(start_date, end_date)
cars = choice_answer_reporters.map {|car| [car.text, car.count_for_date_range(start_date, end_date), car.ca_id]}
cars.sort_by { |car| -car[1] }
end
def choice_answers_str(start_date, end_date, answer_limit = nil)
answer_reporters = ordered_choice_answer_reporters_for_date_range(start_date, end_date)
total_answered = answered_for_date_range(start_date, end_date)
limit_answers = answer_limit && answer_limit < answer_reporters.size
if limit_answers
additional_reporters = answer_reporters[answer_limit..-1]
answer_reporters = answer_reporters[0...answer_limit]
end
answer_array = answer_reporters.map do |car|
"#{car[0]}: #{number_with_delimiter(car[1])} (#{answer_percent(car[1], total_answered)})"
end
if limit_answers
additional_answer_count = additional_reporters.inject(0) {|sum, car| sum + car[1]} # Add count for each reporter
other_str = "Other Answers: #{number_with_delimiter(additional_answer_count)}"
other_str << " (#{answer_percent(additional_answer_count, total_answered)})" unless allows_multiple_selection
answer_array << other_str
end
answer_array.join(", ")
end
# Generate the data required to plot a chart for a choice question. Creates an array
# of Hash objects, which are required for Flot charting.
#
# @return [String] JSON data
def generate_element_data(display_type, start_date = nil, end_date = nil)
case display_type
when "pie"
total_answered = answered_for_date_range(start_date, end_date)
ordered_choice_answer_reporters_for_date_range(start_date, end_date).map do |car|
[car[0], car[1], answer_percent(car[1], total_answered, 1)]
end
when "bar"
ordered_choice_answer_reporters_for_date_range(start_date, end_date).map.each_with_index do |car, index|
url = survey_responses_path(survey_id: survey_version_reporter.s_id, survey_version_id: survey_version_reporter.sv_id, qc_id: qc_id, search_rr: car[2])
{ data: [[index, car[1]]], label: car[0], count: number_with_delimiter(car[1]), url: url }
end
when "line"
choice_answer_reporters.map do |car|
data_map = days_with_individual_counts(start_date, end_date).map do |date, count_hash|
[date.strftime("%Q"), count_hash[car.ca_id]]
end
url = survey_responses_path(survey_id: survey_version_reporter.s_id, survey_version_id: survey_version_reporter.sv_id, qc_id: qc_id, search_rr: car.ca_id)
{ data: data_map, label: car.text, url: url }
end
else
nil
end.to_json
end
def allows_multiple_selection
question.allows_multiple_selection
end
def update_reporter!
choice_answer_hash = {}
delete_recent_days!
# initialize all answers with zero counts
question.choice_answers.each do |ca|
car = choice_answer_reporters.find_or_create_by(ca_id: ca.id)
car.text = ca.answer
choice_answer_hash[ca.id.to_s] = car
end
update_time = Time.now
responses_to_add(question.question_content).find_each do |raw_response|
add_raw_response(raw_response, choice_answer_hash)
end
self.question_text = question.question_content.statement
self.counts_updated_at = update_time
save
end
def delete_recent_days!
delete_date = begin_delete_date
return unless delete_date.present?
days_for_date_range(delete_date, nil).destroy
self.answered = answered_for_date_range(nil, nil, true)
self.chosen = chosen_for_date_range(nil, nil, true)
choice_answer_reporters.each do |car|
car.days_for_date_range(delete_date, nil).destroy
car.count = car.count_for_date_range(nil, nil, true)
end
choice_permutation_reporters.each do |cpr|
cpr.days_for_date_range(delete_date, nil).destroy
cpr.count = cpr.count_for_date_range(nil, nil, true)
end
save
end
def add_raw_response(raw_response, choice_answer_hash)
answer_values = raw_response.answer.split(",")
date = raw_response.created_at.in_time_zone("Eastern Time (US & Canada)").to_date
return unless add_permutations(raw_response, answer_values, choice_answer_hash, date)
add_day(date, answer_values.count)
answer_values.each do |answer_value|
answer = choice_answer_hash[answer_value]
answer.add_day(date)
end
end
def question
@question ||= ChoiceQuestion.find(q_id)
end
def to_csv(start_date = nil, end_date = nil)
CSV.generate do |csv|
csv << ["Question", "Answer", "Count", "Percent"]
answer_reporters = ordered_choice_answer_reporters_for_date_range(start_date, end_date)
total_answered = answered_for_date_range(start_date, end_date)
answer_array = answer_reporters.map do |car|
[car[0], number_with_delimiter(car[1]), answer_percent(car[1], total_answered)]
end
first_line = [question_text]
first_line += answer_array.shift if answer_array.size > 0
csv << first_line
answer_array.each {|answer_arr| csv << [''] + answer_arr}
end
end
def days_with_individual_counts(start_date, end_date)
@days_with_individual_counts ||= {}
memo_key = "#{start_date}_#{end_date}"
return @days_with_individual_counts[memo_key] if @days_with_individual_counts.has_key?(memo_key)
counts_hash = Hash.new {|hash, key| hash[key] = Hash.new {|h,k| h[k] = 0}}
days_for_date_range(start_date, end_date).asc(:date).each do |day|
counts_hash[day.date]
end
choice_answer_reporters.each do |car|
car.choice_answer_days.each do |day|
counts_hash[day.date][car.ca_id] = day.count
end
end
@days_with_individual_counts[memo_key] = counts_hash
end
private
def add_permutations(raw_response, answer_values, choice_answer_hash, date)
permutations = choice_permutation_reporters.where(ca_ids: raw_response.answer).first
unless permutations
values = answer_values.map do |av|
return false if choice_answer_hash[av].nil?
choice_answer_hash[av].text
end.join(DisplayFieldValue::VALUE_DELIMITER)
permutations = choice_permutation_reporters.create(ca_ids: raw_response.answer, values: values)
end
permutations.add_day(date)
true
end
def add_day(date, chosen_count)
day = choice_question_days.find_or_create_by(date: date)
day.inc(answered: 1)
day.inc(chosen: chosen_count)
inc(answered: 1)
inc(chosen: chosen_count)
end
def answer_percent(count, total, precision = 2)
ap = total == 0 ? 0 : count * 100.0 / total
number_to_percentage(ap, precision: precision)
end
end
| true |
bf6c3474db570a46de8facf6406b5cab19472b32 | Ruby | Meggles25/badges-and-schedules-onl01-seng-pt-032320 | /conference_badges.rb | UTF-8 | 753 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def badge_maker(name)
"Hello, my name is #{name}."
end
badge_maker("Arel")
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def batch_badge_creator(attendees)
badge = []
attendees.each do |attendee|
badge << "Hello, my name is #{attendee}."
end
badge
end
batch_badge_creator(attendees)
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def assign_rooms(attendees)
attendees.map.with_index(1){|speaker,index| "Hello, #{speaker}! You'll be assigned to room #{index}!"}
end
assign_rooms(attendees)
def printer(attendees)
badges = batch_badge_creator(attendees)
rooms = assign_rooms(attendees)
badges.each do |line|
puts line
end
rooms.each do |line|
puts line
end
end
| true |
07957174ebc4328a227bdff74fdf784670c7ff03 | Ruby | steveoro/goggles_admin | /app/strategies/importer_entity_populator.rb | UTF-8 | 9,740 | 2.84375 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
require 'common/format'
=begin
= ImporterEntityPopulator
- Goggles framework vers.: 6.127
- author: Leega
Strategy that populates importer temporary data structures from json parsed data.
Assumes meeting already exist. Also meeting_sessions should exists with meeting_events defined
Note that importar has to create new meeting_event it will be associated with first meetin_session
Steps to perform for data parsing
0. Collect distinct meeting_programs (and meeting_events)
0.a Collect events list
0.b Collect program list
(Those steps could be performed while collecting team names in step 1)
1. Collect distinct team names
2. Collect distinct swimmer names (with year and sex) into corresponding team
3. Collect results associating them to respective swimmers
The resulting import structure should be like:
events_list [event [programs]]
teams [team_data, team_id, team_affiliation_id [swimmers [swimmer_data, swimmer_id, badge_id, {meting_program, result_data}]]]
Meeting header json example:
"name": "15° Trofeo Citta` di Riccione",
"meetingURL": "https://www.federnuoto.it/home/master/circuito-supermaster/archivio-2012-2019/stagione-2018-2019.html#/risultati/134219:15%C2%B0-trofeo-citta`%C2%A0di-riccione.html",
"manifestURL": "/component/solrconnect/download.html?file=L3Zhci93d3cvZmluX2ZpbGVzL2V2ZW50aS8wMDAwMTM0MjE5LnBkZg==",
"dateDay1": "08",
"dateMonth1": "Dicembre",
"dateYear1": "2018",
"dateDay2": "09",
"dateMonth2": "Dicembre",
"dateYear2": "2018",
"organization": "A.S.D. POLISPORTIVA COMUNALE RICCIONE",
"venue1": "RICCIONE STADIO DEL NUOTO",
"address1": "VIA MONTEROSA, SNC - Riccione (RN)",
"venue2": "",
"address2": "",
"poolLength": "50",
"timeLimit": "SI",
"registration": "12/11 - 03/12 23:45",
"sections": []
Individual result group json example (inside the sections element):
{
"title": "50 Stile Libero - M25",
"fin_id_evento": "134219",
"fin_codice_gara": "00",
"fin_sigla_categoria": "M25",
"fin_sesso": "M",
"rows": [
{
"pos": "1",
"name": "PETRINI ANDREA",
"year": "1992",
"sex": "M",
"team": "Virtus Buonconvento ssd",
"timing": "24.32",
"score": "949,42"
},...
With that regexp we can extract swimmer data for test from json (swimmer name, year, sex and team name)
/(?<="name": )(".*",)(?=\s*"year": ("[0-9]{4}",)\s*"sex": ("[MF]",)\s*"team": (".*",))/
=end
class ImporterEntityPopulator
# These must be initialized on creation:
attr_reader :full_pathname, :meeting
# These can be edited later on:
attr_accessor :data_hash, :importer_hash, :individual_events_def
# Creates a new instance
#
# params: file name with full path
#
def initialize( full_pathname, meeting )
@full_pathname = full_pathname
@meeting = meeting
@data_hash = Hash.new()
@importer_hash = JsonImporterDAO.new( meeting )
@individual_events_def = nil
end
# Read the file and extract json string
# Returns the string red
#
def read_json_file()
data = ""
File.open( @full_pathname, 'r' ) do |f|
f.each_line do |curr_line|
data << curr_line
end
end
data
end
# Parse json file and return an hash with symbolized keys
#
def parse()
@data_hash = JSON.parse( read_json_file ) #, { :symbolize_names => true, :quirks_mode => true }
end
# Read elements and retrieve distinct primary enetity values
#
def get_distinct_elements()
#@individual_events_def = get_individual_event_list
# TODO - Find pool type. Verify this is a good data
# What if meeting has multiple pools of different types (such Regionali Emilia)
pool = @data_hash['poolLength']
# Each program element has distinct results in rows element
@data_hash['sections'].each do |program|
# Store event and programs element
# This is the json structure:
# "title": "50 Stile Libero - M25",
# "fin_id_evento": "134219",
# "fin_codice_gara": "00",
# "fin_sigla_categoria": "M25",
# "fin_sesso": "M"
# Separates event title and retrieve program code (event, category, sex)
# Assumes in program_title is always present category
program_title = program['title'].upcase
event_title = find_event_title( program_title )
event_code = find_event_code( event_title )
program_key = create_program_key(event_code, program['fin_sigla_categoria'], program['fin_sesso'])
# If the event isn't already defined creates
@importer_hash.events[event_code] = JsonImporterDAO::EventImporterDAO.new( event_title ) if !@importer_hash.events.has_key?(event_code)
event = @importer_hash.events[event_code]
# Define pool type
pool = find_pool_type( event_title ) if pool = nil
# Assumes program elements are already unique.
# If program already present traces an errors
@importer_hash.add_duplicate_program_error(program_key) if event.programs.has_key?(program_key)
event.programs[program_key] = JsonImporterDAO::EventProgramImporterDAO.new( program_title, pool, program['fin_sesso'], program['fin_sigla_categoria'] )
# Cycle program results
program['rows'].each do |result|
# Json structure for result rows
# "pos": "1",
# "name": "PETRINI ANDREA",
# "year": "1992",
# "sex": "M",
# "team": "Virtus Buonconvento ssd",
# "timing": "24.32",
# "score": "949,42"
# For teams we will consider only name
team_name = result['team'].upcase
# If the team isn't already defined creates
@importer_hash.teams[team_name] = JsonImporterDAO::TeamImporterDAO.new( team_name ) if !@importer_hash.teams.has_key?( team_name )
team = @importer_hash.teams[team_name]
# For swimmer we will consider name, year, sex
swimmer_name = result['name'].upcase
swimmer_year = result['year']
swimmer_sex = result['sex'].upcase
swimmer_key = create_swimmer_key( swimmer_name, swimmer_year, swimmer_sex )
if !team.swimmers.has_key?( swimmer_key )
# If swimmer key already exixts maybe there is an error
if @importer_hash.swimmer_keys.has_key?( swimmer_key )
@importer_hash.add_duplicate_swimmer_error( swimmer_key )
else
#Store swimmer key for checking purposes
@importer_hash.swimmer_keys[swimmer_key] = []
end
# If the swimmer isn't already defined creates
team.swimmers[swimmer_key] = JsonImporterDAO::SwimmerImporterDAO.new( swimmer_name, swimmer_year, swimmer_sex )
end
swimmer = team.swimmers[swimmer_key]
@importer_hash.swimmer_keys[swimmer_key] << "#{team_name} - #{event_code}"
# Adds result to swimmer
# If result exists for event code traces an error
@importer_hash.add_duplicate_result_error("#{swimmer_key} #{event_code} #{program_title} #{result.to_s}") if swimmer.results.has_key?(event_code)
swimmer.results[event_code] = JsonImporterDAO::SwimmerResultImporterDAO.new( result['pos'], result['timing'], result['score'] )
end
end
end
# Removes non valid characters from names
#
def remove_invalid_char( name )
name.gsub(/[\s\-_\.]/, '')
end
# Creates an 'unique' swimmer key to identify swimmers
#
def create_program_key( event, category, sex, separator = ';' )
event + separator + category + separator + sex
end
# Creates an 'unique' swimmer key to identify swimmers
#
def create_swimmer_key( swimmer_name, swimmer_year, swimmer_sex, separator = ';' )
remove_invalid_char(swimmer_name) + separator + swimmer_year + separator + swimmer_sex
end
# Creates an hash with event_code => [short_name, compact_name, description] for each Individual event
#
def get_individual_event_list
possible_events = Hash.new()
EventType.are_not_relays.joins(:stroke_type).includes(:stroke_type).each do |event_type|
possible_events[event_type.code] = [event_type.i18n_short, event_type.i18n_compact, event_type.i18n_description]
end
possible_events
end
# Separates event title from program title
# Event title should contain only the event code, short or long description
#
def find_event_title( program_title )
regexp = Regexp::new(/(50|100|200|400|800|1500)\s*(STILE LIBERO|STILE|DORSO|MISTI|RANA|FARFALLA|DELFINO|MI|MX|SL|DO|FA|RA|ST|DE)/i)
regexp.match( program_title )[0]
end
# Find event code starting from an event title
#
def find_event_code( event_title )
distace_match = /(50|100|200|400|800|1500)/.match( event_title )
if distace_match
distance = distace_match[0]
stroke_match = /(STILE LIBERO|STILE|DORSO|MISTI|RANA|FARFALLA|DELFINO|MI|MX|SL|DO|FA|RA|ST|DE)/i.match( event_title )
if stroke_match
stroke = stroke_match[0]
if /(DORSO|DO|DS)/i.match?( stroke )
stroke_code = 'DO'
elsif /(RANA|RA)/i.match?( stroke )
stroke_code = 'RA'
elsif /(FARFALLA|DELFINO|FA|DE)/i.match?( stroke )
stroke_code = 'FA'
elsif /(MISTI|MI|MX)/i.match?( stroke )
stroke_code = 'MI'
else
stroke_code = 'SL'
end
distance + stroke_code
else
nil
end
else
nil
end
end
# Find pool type for given event in meeting schedule
# Assumes meeting schedule is complete or at least has one session configured
#
def find_pool_type( event_title )
# TODO
'25'
end
#-- --------------------------------------------------------------------------
#++
end
| true |
4825b5c6d387c74929fc3f9a7c11dd677b247de5 | Ruby | ruby-rdf/sparql | /lib/sparql/algebra/operator/left_join.rb | UTF-8 | 7,808 | 2.8125 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | module SPARQL; module Algebra
class Operator
##
# The SPARQL GraphPattern `leftjoin` operator.
#
# [57] OptionalGraphPattern ::= 'OPTIONAL' GroupGraphPattern
#
# @example SPARQL Grammar
# PREFIX : <http://example/>
# SELECT * {
# ?x :p ?v .
# OPTIONAL {
# ?y :q ?w .
# FILTER(?v=2)
# }
# }
#
# @example SSE
# (prefix ((: <http://example/>))
# (leftjoin
# (bgp (triple ?x :p ?v))
# (bgp (triple ?y :q ?w))
# (= ?v 2)))
#
# @see https://www.w3.org/TR/sparql11-query/#sparqlAlgebra
class LeftJoin < Operator
include Query
NAME = [:leftjoin]
##
# Executes each operand with `queryable` and performs the `leftjoin` operation
# by adding every solution from the left, merging compatible solutions from the right
# that match an optional filter.
#
# @param [RDF::Queryable] queryable
# the graph or repository to query
# @param [Hash{Symbol => Object}] options
# any additional keyword options
# @yield [solution]
# each matching solution
# @yieldparam [RDF::Query::Solution] solution
# @yieldreturn [void] ignored
# @return [RDF::Query::Solutions]
# the resulting solution sequence
# @see https://www.w3.org/TR/sparql11-query/#sparqlAlgebra
# @see https://ruby-rdf.github.io/rdf/RDF/Query/Solution#merge-instance_method
# @see https://ruby-rdf.github.io/rdf/RDF/Query/Solution#compatible%3F-instance_method
def execute(queryable, **options, &block)
filter = operand(2)
raise ArgumentError,
"leftjoin operator accepts at most two arguments with an optional filter" if
operands.length < 2 || operands.length > 3
debug(options) {"LeftJoin"}
left = queryable.query(operand(0), **options.merge(depth: options[:depth].to_i + 1))
debug(options) {"=>(leftjoin left) #{left.inspect}"}
right = queryable.query(operand(1), **options.merge(depth: options[:depth].to_i + 1))
debug(options) {"=>(leftjoin right) #{right.inspect}"}
# LeftJoin(Ω1, Ω2, expr) =
@solutions = RDF::Query::Solutions()
left.each do |s1|
load_left = true
right.each do |s2|
s = s2.merge(s1)
# Re-bind to bindings, if defined, as they might not be found in solution
options[:bindings].each_binding do |name, value|
s[name] = value if filter.variables.include?(name)
end if options[:bindings] && filter.respond_to?(:variables)
# See https://github.com/w3c/rdf-tests/pull/83#issuecomment-1324220844 for @afs's discussion of the simplified/not-simplified issue.
#
# The difference is when simplification is applied. It matters for OPTIONAL because OPTIONAL { ... FILTER(...) } puts the filter into the LeftJoin expressions. In LeftJoin, the FILTER can see the left-hand-side variables. (SQL: LEFT JOIN ... ON ...)
#
# For OPTIONAL { { ... FILTER(...) } }, the inner part is Join({}, {.... FILTER }).
#
# if simplify happens while coming back up the tree generating algebra operations, it removes the join i.e. the inner of {{ }}, and passes "... FILTER()" to the OPTIONAL. The effect of the extra nesting in {{ }} is lost and it exposes the filter to the OPTIONAL rule.
#
# if simplification happens as a step after the whole algebra is converted, this does not happen. Compiling the OPTIONAL see a join and the filter is not at the top level of the OPTIONAl block and so not handled in the LeftJoin.
#
# Use case:
#
# # Include name if person over 18
# SELECT *
# { ?person :age ?age
# OPTIONAL { ?person :name ?name. FILTER(?age > 18) }
# }
# Hindsight: a better syntax would be call out if the filter needed access to the LHS.
#
# OPTIONAL FILTER(....) { }
#
# But we are where we are.
#
# (a "no conditions on LeftJoin" approach would mean users having to duplicate parts of their query - possibly quite large parts.)
expr = filter ? boolean(filter.evaluate(s)).true? : true rescue false
debug(options) {"===>(evaluate) #{s.inspect}"} if filter
if expr && s1.compatible?(s2)
# { merge(μ1, μ2) | μ1 in Ω1 and μ2 in Ω2, and μ1 and μ2 are compatible and expr(merge(μ1, μ2)) is true }
debug(options) {"=>(merge s1 s2) #{s.inspect}"}
@solutions << s
load_left = false # Left solution added one or more times due to merge
end
end
if load_left
debug(options) {"=>(add) #{s1.inspect}"}
@solutions << s1
end
end
debug(options) {"=> #{@solutions.inspect}"}
@solutions.each(&block) if block_given?
@solutions
end
# The same blank node label cannot be used in two different basic graph patterns in the same query
def validate!
left_nodes, right_nodes = operand(0).ndvars, operand(1).ndvars
unless (left_nodes.compact & right_nodes.compact).empty?
raise ArgumentError,
"sub-operands share non-distinguished variables: #{(left_nodes.compact & right_nodes.compact).to_sse}"
end
super
end
##
# Optimizes this query.
#
# If optimize operands, and if the first two operands are both Queries, replace
# with the unique sum of the query elements
#
# @return [Object] a copy of `self`
# @see SPARQL::Algebra::Expression#optimize
# FIXME
def optimize!(**options)
return self
ops = operands.map {|o| o.optimize(**options) }.select {|o| o.respond_to?(:empty?) && !o.empty?}
expr = ops.pop unless ops.last.executable?
expr = nil if expr.respond_to?(:true?) && expr.true?
# ops now is one or two executable operators
# expr is a filter expression, which may have been optimized to 'true'
case ops.length
when 0
RDF::Query.new # Empty query, expr doesn't matter
when 1
expr ? Filter.new(expr, ops.first) : ops.first
else
expr ? LeftJoin.new(ops[0], ops[1], expr) : LeftJoin.new(ops[0], ops[1])
end
end
##
#
# Returns a partial SPARQL grammar for this operator.
#
# @param [Boolean] top_level (true)
# Treat this as a top-level, generating SELECT ... WHERE {}
# @param [Hash{String => Operator}] extensions
# Variable bindings
# @param [Array<Operator>] filter_ops ([])
# Filter Operations
# @return [String]
def to_sparql(top_level: true, filter_ops: [], extensions: {}, **options)
str = "{\n" + operands[0].to_sparql(top_level: false, extensions: {}, **options)
str <<
"\nOPTIONAL {\n" +
operands[1].to_sparql(top_level: false, extensions: {}, **options)
case operands[2]
when SPARQL::Algebra::Operator::Exprlist
operands[2].operands.each do |op|
str << "\nFILTER (" + op.to_sparql(**options) + ")"
end
when nil
else
str << "\nFILTER (" + operands[2].to_sparql(**options) + ")"
end
str << "\n}}"
top_level ? Operator.to_sparql(str, filter_ops: filter_ops, extensions: extensions, **options) : str
end
end # LeftJoin
end # Operator
end; end # SPARQL::Algebra
| true |
1ff5ba2ae9eb2f2028cdbf691a26c8d8813c6277 | Ruby | clairebvs/Battleship | /lib/start.rb | UTF-8 | 952 | 2.796875 | 3 | [] | no_license | class Start
def welcome
"Welcome to BATTLESHIP. Would you like to (p)lay, read the (i)nstructions or (q)uit?"
end
def instructions
'The goal of the game is to sink the ship of your opponent.
Each player calls out one coordinate each turn in attempt to hit one of their opponent’s ships.'
end
def place_ship_destroyer
'You have to place a destroyer on your grid. It is a two unit long. The different positions possible are A1 from A4 and D1 to D4'
end
def place_ship_cruiser
'You have to place a cruiser on your grid. It is a three unit long. The different positions possible are A1 from A4 and D1 to D4'
end
def incorrect_ship_placement
'Ships cannot wrap around the board.
Ships cannot overlap.
Ships can be laid either horizontally or vertically.
Coordinates must correspond to the first and last units of the ship.
(IE: You can’t place a two unit ship at “A1 A3”).'
end
end
| true |
9181ee3a344f5f423bf32ca1092304c7a527c9c2 | Ruby | grandnumber/surveyproject | /app/helpers/user_helper.rb | UTF-8 | 377 | 2.59375 | 3 | [] | no_license | helpers do
def debug_hash(label, object)
if object.respond_to? :to_hash
object = JSON.pretty_generate object.to_hash
elsif object.respond_to? :to_a
object = JSON.pretty_generate object.to_a
end
<<-HTML
<div class="debug">
<div class="debug--label">#{ escape_html label }</div>
<pre>#{ escape_html object.to_s }</pre>
</div>
HTML
end
end
| true |
b237612d8edead9d0b4b43ee1fca724bf65bb3ad | Ruby | danachen/Ruby | /LS101/easy1/p1.rb | UTF-8 | 197 | 3.59375 | 4 | [] | no_license | # Prob one
def repeat(str, int)
# output = str * int
int.times do
puts str
end
end
repeat('Hello', 3)
# note that using * will output everything on a row
# int.times do puts string
| true |
e031bd47247e8ff8dac8041dc259f0015dec0f00 | Ruby | wribln/pmodbase | /app/models/abbreviation.rb | UTF-8 | 1,209 | 2.6875 | 3 | [] | no_license | require './lib/assets/app_helper.rb'
class Abbreviation < ActiveRecord::Base
include ApplicationModel
include Filterable
before_save :set_sort_code
validates :code,
length: { maximum: MAX_LENGTH_OF_CODE },
presence: true
validates :description,
length: { maximum: MAX_LENGTH_OF_DESCRIPTION },
presence: true
validates :sort_code,
length: { maximum: MAX_LENGTH_OF_CODE }
default_scope { order( sort_code: :asc )}
scope :as_abbr, -> ( a ){ where( 'code LIKE ?', "#{ a }%" )}
scope :as_desc, -> ( d ){ where( 'description LIKE ?', "%#{ d }%" )}
class << self;
alias :ff_code :as_abbr
alias :ff_desc :as_desc
end
set_trimmed :code, :sort_code, :description
# use this to automatically create the sort code from the abbreviation:
# remove punctuation characters and map all uppercase characters to lowercase;
# if the remaining string is empty, the sort code will be the code with each
# character replaced by a questionmark
def set_sort_code
if self.sort_code.blank?
self.sort_code = code.delete( '^a-zA-Z0-9' ).downcase
if self.sort_code.blank?
self.sort_code = code.gsub( /./, '?' )
end
end
end
end
| true |
3504900a2a2d117e1b0e3809f586fb13a0278d6d | Ruby | littlekbt/slack-lambda | /bot/lib/slack-lambda-bot/user_file.rb | UTF-8 | 1,995 | 2.640625 | 3 | [] | no_license | class SlackLambdaBot
class UserFile
REGISTER_REGEXP = /name:\s?(.+)\n(language:\s?.*\nversion:\s?.*\n```\n?[\s\S]*\n?```)/
SHOW_REGEXP = />\s*show\s*([a-z|A-Z|0-9|_|-]*)/
LIST_REGEXP = />\s*list/
REMOVE_REGEXP = />\s*remove\s*([a-z|A-Z|0-9|_|-]*)/
RUN_REGEXP = />\s*run\s*([a-z|A-Z|0-9|_|-]*)/
FILE_PATH = ::Pathname.new((ENV['STORAGE_PATH'] || '../storage/user_files') + '/')
class << self
def register(text)
m = text.match(REGISTER_REGEXP)
if m
name = m[1]
parameter = m[2]
namem = name.match(/[a-z|A-Z|0-9|_|-]*/)
return 'you can use only [a-z|A-Z|0-9|_|-] for function name.' unless namem[0].to_s.length == name.to_s.length
return "#{name} is already exist" if File.exist?(to_s_path(name))
File.open(to_s_path(name), "w") do |f|
f.puts(parameter)
end
return "success register #{name}"
end
end
def show(text)
m = text.match(SHOW_REGEXP)
if m
name = m[1]
return "#{name} not found" unless File.exist?(to_s_path(name))
File.read(to_s_path(name))
end
end
def list(text)
m = text.match(LIST_REGEXP)
Dir.glob("#{FILE_PATH}*").map{ |f| File.basename(f) }.join("\n") if m
end
def remove(text)
m = text.match(REMOVE_REGEXP)
if m
name = m[1]
return "#{name} not found" unless File.exist?(to_s_path(name))
File.delete(to_s_path(name))
"delete #{name} function"
end
end
def run(text)
m = text.match(RUN_REGEXP)
if m
name = m[1]
return "#{name} not found" unless File.exist?(to_s_path(name))
t = File.read(to_s_path(name))
PostProxy.post(t)
end
end
private
def to_s_path(name)
Pathname.new(FILE_PATH).join(name).to_s
end
end
end
end
| true |
e0f83e6135273d41c6861be228079c2df45b819d | Ruby | praveenag/damsel_in_distress | /app/json_builder.rb | UTF-8 | 276 | 2.546875 | 3 | [] | no_license | require './workspace'
class JsonBuilder
def chart_json(data)
return_val = {}
values = data.collect { |role, value| {'label' => role, 'values' => value} }
return_val['label'] = ["Male", "Female"]
return_val['values'] = values
return_val.to_json
end
end | true |
1809d01093ca2a6325efc028358c07a090de7845 | Ruby | kyoungeagle/phase-0-tracks | /ruby/santa.rb | UTF-8 | 1,828 | 3.5625 | 4 | [] | no_license | class Santa
attr_reader :age
attr_accessor :gender
def initialize(gender, ethnicity)
@gender = gender
@ethnicity = ethnicity
@reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
@age = 0
end
def speak
puts "Ho, ho, ho! Haaaapy Holidays!"
end
def eat_milk_and_cookies(cookie)
puts "Yum! That was a good #{cookie}!"
end
def identity
puts "I identify as #{@ethnicity} and #{@gender}"
end
def celebrate_birthday
@age += 1
end
#setter method
def gender=(new_gender)
@gender = new_gender
puts @gender
end
def get_mad_at(reindeer)
@reindeer_ranking.delete(reindeer)
@reindeer_ranking.insert(-1, reindeer)
end
#IGNORE THIS COMMENTED OUT SECTION
#getter methods
#def ethnicity
# @ethnicity
#end
#def age
# @age
#end
#RELEASE 4
def kris_kringle_simulator(gender_of_santa, ethnicity_of_santa)
gender_of_santa = gender_of_santa.sample
ethnicity_of_santa = ethnicity_of_santa.sample
random_age = Random.new
@age = random_age.rand(140)
puts "Santa idenitfies as #{gender_of_santa}, #{ethnicity_of_santa}, and is #{@age} years old"
end
end
genders = ["cisgender", "pangender", "transgender", "male", "female", "two-spirit"]
ethnicities = ["black", "latino", "white", "Native American", "prefer not to say", "Mystical Creature (red panda)", "Samoan"]
santas = []
santa = Santa.new("","")
santa.speak
santa.eat_milk_and_cookies("sugar cookie")
puts "Initiate Kris Kringle Simulator"
genders.length.times do |iteration|
santas << Santa.new(genders[iteration], ethnicities[iteration])
end
santas.each do |santa|
santa.identity
end
santa.celebrate_birthday
p santa.age
santa.get_mad_at("Rudolph")
santa.gender=("cisgender")
200.times do
p santa.kris_kringle_simulator(genders, ethnicities)
end
| true |
026508e3c415ba64556d10e62958b713fae880d5 | Ruby | arwensookim/aa_classwork | /W5/w5d1/skeleton/lib/p02_hashing.rb | UTF-8 | 640 | 3.53125 | 4 | [] | no_license | class Integer
# Integer#hash already implemented for you
end
class Array
def hash
# [1, 2, 3].hash == [3, 2, 1].hash # => false
hash = 0
self.each_with_index do |el, i|
hash = hash ^ (el.hash & i.hash)
end
hash
end
end
class String
def hash
hash = 0
self.each_char.with_index do |c, i|
hash = hash ^ (c.ord.hash & i.hash)
end
hash
end
end
class Hash
# This returns 0 because rspec will break if it returns nil
# Make sure to implement an actual Hash#hash method
def Hash
hash = 0
self.each do |k, v|
hash = hash ^ (k.hash & v.hash)
end
hash
end
end
| true |
51042657e84259201ab78006e8955626cff4aab4 | Ruby | dalspok/exercises | /small_problems_i3/easy_7/5.rb | UTF-8 | 308 | 3.34375 | 3 | [] | no_license |
def staggered_case(str)
str.chars.map.with_index {|char, idx| idx.even? ? char.upcase : char.downcase}.join("")
end
p staggered_case('I Love Launch School!') == 'I LoVe lAuNcH ScHoOl!'
p staggered_case('ALL_CAPS') == 'AlL_CaPs'
p staggered_case('ignore 77 the 444 numbers') == 'IgNoRe 77 ThE 444 NuMbErS' | true |
8dd1fa3491f8faf242bb083a73c83b8ad4fa7166 | Ruby | emilyroulund/reverse-each-word-chicago-web-051319 | /reverse_each_word.rb | UTF-8 | 94 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def reverse_each_word (string)
string.split.collect {|word|word.reverse}.join(" ")
end | true |
68bb29d19ef5e18206dae007b93115730582adca | Ruby | jigneshkapuriya/ruby_learning | /if_elsif.rb | UTF-8 | 176 | 3.171875 | 3 | [] | no_license | color = "Yellow"
if color == "Red"
puts "red is rad"
elsif color == "Green"
puts "Green is Great"
elsif color == "Yellow"
puts "yah is Yellow"
else
puts 'hybtfvft'
end
| true |
07de1e338a52be6d05212e2c2c02294bb6479ecb | Ruby | Spekachu/learn_ruby | /08_book_titles/book.rb | UTF-8 | 439 | 3.40625 | 3 | [] | no_license | class Book
def initialize(title=nil)
@title = title
end
def title=(new_title)
little = ['and', 'but', 'or', 'the', 'over', 'a', 'an','in', 'of']
new_title = new_title.split.each do |word|
word.capitalize! unless little.include?(word)
end
new_title[0].capitalize!
@title = new_title.join(' ')
end
def title
@title
end
end | true |
8fce9c8d9f4f28ce4babd3b28501e338115e0846 | Ruby | AnnAllan/assignment_recursion_sprint | /rec.rb | UTF-8 | 1,439 | 4.1875 | 4 | [] | no_license | def factorial_r(n)
if n <= 1
return 1
else
return n * factorial_r(n - 1)
end
end
puts "fact r 5 is #{factorial_r(5)}"
puts "fact r 0 is #{factorial_r(0)}"
def factorial_i(n)
fact = 1
2.upto(n) do |y|
fact *= y
end
return fact
end
puts "fact i 5 is #{factorial_i(5)}"
def sumdigit_r(n)
if n < 10
return n
else
num = n % 10
return sumdigit_r((n - num) / 10) + num
end
end
puts "sumdigit r 103 is #{sumdigit_r(103)}"
def sumdigit_i(n)
sum = 0
digit_arr = n.to_s.split("")
digit_arr.each do |num|
number = num.to_i
sum += number
end
return sum
end
puts "sumdigit i 103 is #{sumdigit_i(103)}"
def palindrome_r(word)
if word.is_a? String
letter_arr = word.split("")
else
letter_arr = word
end
if (letter_arr.length < 2)
return true
else
if letter_arr[0] == letter_arr[ -1]
return palindrome_r(letter_arr[1..-2])
else
return false
end
end
end
puts "pal r 'radar' is #{palindrome_r("radar")}"
puts "pal r 'ann' is #{palindrome_r("ann")}"
def palindrome_i(word)
letter_arr = word.split("")
half = letter_arr.length / 2
first = 0
last = -1
palindrome = true
half.times do
if letter_arr[first] != letter_arr[last]
palindrome = false
else
first += 1
last -= 1
end
end
return palindrome
end
puts "pal i 'radar' is #{palindrome_i("radar")}"
puts "pal i 'ann' is #{palindrome_i("ann")}"
| true |
e4eabc615f55775e1e649972826870a18abd1cf2 | Ruby | Stupot83/battle | /app.rb | UTF-8 | 647 | 2.578125 | 3 | [] | no_license | # frozen_string_literal: true
require 'sinatra/base'
require './lib/player.rb'
require './lib/game.rb'
require './lib/attack.rb'
class Battle < Sinatra::Application
enable :sessions
set :session_secret, 'session_secret'
get '/' do
erb :index
end
post '/names' do
player_1 = Player.new(name: params[:p1_name])
player_2 = Player.new(name: params[:p2_name])
$game = Game.new(player_1: player_1, player_2: player_2)
$attack = Attack.new(game: $game)
redirect '/play'
end
get '/play' do
@game = $game
erb :play
end
get '/attack' do
@game = $game
$attack.run_attack
erb :play
end
end | true |
bd3cc2e02a020c64e360243813522330485dd93a | Ruby | Nova840/phase-0 | /week-6/nested_data_solution.rb | UTF-8 | 2,080 | 3.734375 | 4 | [
"MIT"
] | permissive | # RELEASE 2: NESTED STRUCTURE GOLF
# Hole 1
# Target element: "FORE"
array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]]
# attempts:
# ============================================================
#p array[2][2][3][1]
#p array[2]
#p array[1]
p array[1][1][2][0]
# ============================================================
# Hole 2
# Target element: "congrats!"
hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}}
# attempts:
# ============================================================
#p hash[outer:][inner:]["almost"][3]
#p hash[:outer]
p hash[:outer][:inner]["almost"][3]
# ============================================================
# Hole 3
# Target element: "finished"
nested_data = {array: ["array", {hash: "finished"}]}
# attempts:
# ============================================================
p nested_data[:array][1][:hash]
# ============================================================
# RELEASE 3: ITERATE OVER NESTED STRUCTURES
number_array = [5, [10, 15], [20,25,30], 35]
def add5!(array)
index = 0
array.each{ |i|
if(i.is_a? Array)
add5!(i)
else
array[index] = i + 5
end
index += 1
}
end
add5! number_array
p number_array
# Bonus:
startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]]
def addLy!(array)
index = 0
array.each{ |i|
if(i.is_a? Array)
addLy!(i)
else
array[index] = i + "ly"
end
index += 1
}
end
addLy! startup_names
p startup_names
=begin
Reflection:
What are some general rules you can apply to nested arrays?
Nested arrays are arrays with one or more arrays inside of the array.
What are some ways you can iterate over nested arrays?
You can use nested loops if you know how many dimensions the array has of recursion if you don't.
Did you find any good new methods to implement or did you re-use one you were already familiar with? What was it and why did you decide that was a good option?
We didn't use any new methods. I couldn't find any that would better do what I wanted than the ones I already knew.
=end | true |
a8888fd1d57fbb07402bd13901c37ef4d5936f62 | Ruby | saulocn/curso-ruby | /campo_minado/ponto.rb | UTF-8 | 1,137 | 3.3125 | 3 | [] | no_license | class Ponto
attr_accessor :x, :y, :conteudo, :descoberto, :flag
attr_reader :bomba, :bandeira, :clear, :unknown
def initialize(x, y)
@x = x
@y = y
@descoberto = false
@flag = false
@bomba = "*"
@clear = " "
@unknown = "."
@bandeira = "F"
@conteudo = @unknown
end
def coloca conteudo
@conteudo = conteudo
end
def tem_bomba?
return true if conteudo==@bomba
false
end
def set_clear
coloca @clear
end
def set_flag
if @flag
return @flag = false
end
@flag = true
end
def show xray
# board_format = {
# unknown_cell: '.',
# clear_cell: ' ',
# bomb: '#',
# flag: 'F'
# }
#puts descoberto
return conteudo if descoberto || xray
return @bandeira if @flag
@unknown
end
def foi_descoberto?
return descoberto
end
def tem_flag?
@flag
end
def descobrir
@descoberto = true
end
end | true |
da4feaad352b2ff1dcd5f3d92527fc42efb2b2c5 | Ruby | UjwalBattar/algorithms-dataStructures | /topTal/codility/ruby/cyclic_rotation.rb | UTF-8 | 1,478 | 4.53125 | 5 | [] | no_license | # An array A consisting of N integers is given. Rotation of the array
# means that each element is shifted right by one index, and the last
# element of the array is moved to the first place. For example, the
# rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements
# are shifted right by one index and 6 is moved to the first place).
#
# The goal is to rotate array A K times; that is, each element of A
# will be shifted to the right K times.
#
# Write a function:
#
# def solution(a, k)
#
# that, given an array A consisting of N integers and an integer K,
# returns the array A rotated K times.
#
# For example, given
#
# A = [3, 8, 9, 7, 6]
# K = 3
# the function should return [9, 7, 6, 3, 8]. Three rotations were made:
#
# [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
# [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
# [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
# For another example, given
#
# A = [0, 0, 0]
# K = 1
# the function should return [0, 0, 0]
#
# Given
#
# A = [1, 2, 3, 4]
# K = 4
# the function should return [1, 2, 3, 4]
#
# Assume that:
#
# N and K are integers within the range [0..100];
# each element of array A is an integer within the range
# [−1,000..1,000].
# In your solution, focus on correctness. The performance of your
# solution will not be the focus of the assessment.
def cyclic_rotation(a, k)
a.reverse.take(k % a.length).reverse + a.reverse.drop(k % a.length).reverse
end
cyclic_rotation([3, 8, 9, 7, 6], 3)
| true |
c6fedc4edd2347e2e7a6f51cc98aeda39e32ed67 | Ruby | cebarks/black_thursday | /lib/merchant_repository.rb | UTF-8 | 548 | 2.625 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'repository'
require_relative 'merchant'
class MerchantRepository < Repository
attr_accessor :sorted, :instances
def initialize
@type = Merchant
@attr_whitelist = [:name]
@sorted = false
super
end
def find_all_by_name(fragment)
@instances.select do |instance|
instance.name.downcase.include?(fragment.downcase)
end
end
def find_by_name(fragment)
@instances.find do |instance|
instance.name.downcase.include?(fragment.downcase)
end
end
end
| true |
c0950e819c17192ae33ae64d0d7d9c68b1e2ce7c | Ruby | Yobisense/rtesseract | /lib/rtesseract/uzn.rb | UTF-8 | 1,360 | 2.59375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # encoding: UTF-8
# RTesseract
class RTesseract
# Alternative approach to Mixed when you want to read from specific areas.
# Requires `-psm 4` which means the text must be "a single column of text of variable sizes".
class Uzn < RTesseract
attr_reader :areas
DEFAULT_ALPHABET = 'Text/Latin'
def initialize(src = '', options = {})
@areas = options.delete(:areas) || []
@alphabet = options.delete(:alphabet) || DEFAULT_ALPHABET
super(src, options.merge(psm: 4))
yield self if block_given?
end
# Add areas
def area(points)
areas << points
end
def convert_command
@image = image
write_uzn_file
`#{configuration.command} "#{@image}" "#{file_dest}" #{lang} #{psm} #{tessdata_dir} #{user_words} #{user_patterns} #{config_file} #{clear_console_output} #{options_cmd.join(' ')}`
end
def after_convert_hook
RTesseract::Utils.remove_files([@uzn_file])
end
private
def write_uzn_file
folder = File.dirname(@image)
basename = File.basename(@image, '.tif')
@uzn_file = File.new("#{folder}/#{basename}.uzn", File::CREAT|File::TRUNC|File::RDWR)
areas.each do |points|
s = "#{points[:x]} #{points[:y]} #{points[:w]} #{points[:h]} #{@alphabet}\n"
@uzn_file.write(s)
@uzn_file.flush
end
end
end
end
| true |
6f6d5f1071d69d5c5294f6d2cba7066dc335f776 | Ruby | AhmedC414/W2D2 | /startup_project/lib/startup.rb | UTF-8 | 1,714 | 3.6875 | 4 | [] | no_license | require "employee"
class Startup
attr_reader :name, :funding, :salaries, :employees
def initialize(name, funding, salaries)
@name = name
@funding = funding
@salaries = salaries
@employees = []
# hash.each do |title, salary|
# @salaries[title] = Employee.new(name, title).pay(salary)
# end
end
def valid_title?(str)
if @salaries.has_key?(str)
return true
else
return false
end
end
def >(start_up)
if self.funding > start_up.funding
return true
else
return false
end
end
def hire(name, title)
if self.valid_title?(title)
@employees << Employee.new(name, title)
else
raise "something went wrong"
end
end
def size
@employees.length
end
def pay_employee(employee)
owed = @salaries[employee.title]
if @funding >= owed
employee.pay(owed)
@funding -= owed
else
raise "not enough funds"
end
end
def payday
employees.each { |employee| pay_employee(employee)}
end
def average_salary
sum = @employees.map { |employee| @salaries[employee.title] }.sum
sum / self.size.to_f
end
def close
@employees = []
@funding = 0
end
def acquire(start_up)
@funding += start_up.funding
start_up.salaries.each do |k, v|
if !@salaries.has_key?(k)
@salaries[k] = v
end
end
@employees = @employees + start_up.employees
start_up.close
end
end
| true |
bc52ca201591f5500ee8516e453f65328fa60c1b | Ruby | temi-adediran/music-library | /lib/models/base_model.rb | UTF-8 | 430 | 2.78125 | 3 | [] | no_license | require_relative '../concerns/findable.rb'
class BaseModel
extend Concerns::Findable
include Concerns::InstanceMethods
attr_accessor :name, :songs
def initialize(name)
@name = name
@songs = []
end
def save
self.class.all << self unless self.class.all.include?(self)
end
def self.destroy_all
all.clear
end
def self.create(name)
model = new(name)
model if model.save
end
end
| true |
14fdbf55b3d0c990ce68550d655e29135a6aa647 | Ruby | imkaruna/ruby-music-library-cli-v-000 | /lib/music_library_controller.rb | UTF-8 | 1,107 | 3.078125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class MusicLibraryController
attr_accessor :path
def initialize(path = './db/mp3s')
MusicImporter.new(path).import
end
def call
puts "Please use these commands: 'list songs', 'list genres', 'list artists', 'play song', 'list artist', 'list genre', 'exit"
exit_musiclibrary = false
while !exit_musiclibrary
input = gets.strip
case input
when 'list songs'
Song.list
when 'list genres'
Genre.list
when 'list artists'
Artist.list
when 'play song'
puts "Pick a song number"
song_num = gets.strip
Song.play_song(song_num.to_i)
when 'list artist'
puts "Pick an artist"
artist_choice = gets.strip
Artist.choice_artist(artist_choice)
when 'list genre'
puts "Pick a genre"
genre_choice = gets.strip
Genre.choice_genre(genre_choice)
when 'exit'
puts "Exiting..."
exit_musiclibrary = true
else
puts "Exiting..."
exit_musiclibrary = true
end
end
end
end | true |
512904303b07e29b7ecb256a97d896ce10bf8306 | Ruby | j00p34/inspec | /test/unit/mock/profiles/filter_table/controls/validate_criteria_as_params.rb | UTF-8 | 1,347 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | title '`where` should reject unknown criteria'
raw_data = [
{ id: 1, name: 'Annie', shoe_size: 12},
{ id: 2, name: 'Bobby', shoe_size: 10, favorite_color: 'purple'},
]
control '2943_pass_undeclared_field_in_hash' do
title 'It should tolerate criteria that are keys of the raw data but are not declared as fields'
# simple_plural only has one declared field, 'id'
describe simple_plural(raw_data).where(name: 'Annie') do
it { should exist }
end
end
control '2943_pass_irregular_row_key' do
title 'It should tolerate criteria that are keys of one row but not the first'
describe simple_plural(raw_data).where(favorite_color: 'purple') do
it { should exist }
end
end
control '2943_pass_raise_error_when_key_not_in_data' do
describe 'It should not tolerate criteria that are not keys of the raw data' do
it { lambda { simple_plural(raw_data).where(hat_size: 'Why are these in eighths?') }.should raise_error ArgumentError }
end
end
control '2943_pass_no_error_when_no_data' do
describe simple_plural([]).where(arbitrary_key: 'any_value') do
it { should_not exist }
end
end
# This should fail but not abort the run
# It is treated as a control source code failure
control '2943_fail_derail_check' do
describe simple_plural(raw_data).where(monocle_size: 'poppable') do
it { should exist }
end
end | true |
9936dbc55649a55df2b5abcf7cf4a9774dce7b1b | Ruby | gsamokovarov/puppet | /lib/puppet/agent/locker.rb | UTF-8 | 1,018 | 2.75 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | require 'puppet/util/pidlock'
# This module is responsible for encapsulating the logic for
# "locking" the puppet agent during a run; in other words,
# keeping track of enough state to answer the question
# "is there a puppet agent currently running?"
#
# The implementation involves writing a lockfile whose contents
# are simply the PID of the running agent process. This is
# considered part of the public Puppet API because it used
# by external tools such as mcollective.
#
# For more information, please see docs on the website.
# http://links.puppetlabs.com/agent_lockfiles
module Puppet::Agent::Locker
# Yield if we get a lock, else do nothing. Return
# true/false depending on whether we get the lock.
def lock
if lockfile.lock
begin
yield
ensure
lockfile.unlock
end
end
end
def running?
lockfile.locked?
end
def lockfile
@lockfile ||= Puppet::Util::Pidlock.new(Puppet[:agent_pidfile])
@lockfile
end
private :lockfile
end
| true |
a04c03bb94c10160059b9f0dfc141ad119194fcc | Ruby | ronanduddy/exercises | /ruby/pragprog/e4/extent.rb | UTF-8 | 313 | 2.96875 | 3 | [] | no_license | require_relative 'coordinate'
class Extent
def initialize(coordinates)
@coordinates = coordinates
end
def max
@max ||= Coordinate.new(@coordinates.map(&:x).max, @coordinates.map(&:y).max)
end
def min
@min ||= Coordinate.new(@coordinates.map(&:x).min, @coordinates.map(&:y).min)
end
end
| true |
9c662fe64edeea5d7eec84a64898e7b9a90410f8 | Ruby | kaleflatbread/oo-cash-register-nyc-web-051418 | /lib/cash_register.rb | UTF-8 | 871 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class CashRegister
attr_accessor :items, :discount, :total, :last_transaction
# initialize a total and items: |array| with an optional discount argument
def initialize(discount=0)
@total = 0
@discount = discount
@items = []
end
# adds an item (with an optional quantity argument) to the total
def add_item(item, price, quantity=1)
self.total += price * quantity
quantity.times do
items << item
end
self.last_transaction = price * quantity
end
# applies optional discount
def apply_discount
if discount != 0
self.total = (total * ((100.0 - discount.to_f)/100)).to_i
"After the discount, the total comes to $#{self.total}."
else
"There is no discount to apply."
end
end
# voids the last transaction
def void_last_transaction
self.total = self.total - self.last_transaction
end
end
| true |
a53b1585451d48fcd69fe1d0d4f9799d870e7d6a | Ruby | appfolio/ladle | /lib/ladle/pull_request_info.rb | UTF-8 | 305 | 2.65625 | 3 | [] | no_license | module Ladle
class PullRequestInfo
attr_reader :head_sha, :base_sha
def initialize(head_sha, base_sha)
@head_sha = head_sha
@base_sha = base_sha
end
def ==(other)
@head_sha == other.head_sha &&
@base_sha == other.base_sha
end
alias eql? ==
end
end
| true |
d59453996172e4e3dacf947376a058691393ed39 | Ruby | jamesgraham320/badges-and-schedules-prework | /conference_badges.rb | UTF-8 | 548 | 4.0625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def badge_maker(name)
badge = "Hello, my name is #{name}."
end
def batch_badge_creator(names)
badges = []
names.each do |name|
badges << badge_maker(name)
end
badges
end
def assign_rooms(names)
rooms = []
names.each_with_index {| name, index |
room = index + 1
rooms << "Hello, #{name}! You'll be assigned to room #{room}!"}
rooms
end
def printer(attendees)
badges = batch_badge_creator(attendees)
rooms = assign_rooms(attendees)
badges.each {|badge| puts(badge)}
rooms.each {|room| puts(room)}
end
| true |
6b68b76ffad7c4f3970190121567ec5278243671 | Ruby | youta777/AtCoder | /ABC/ABC172/a.rb | UTF-8 | 352 | 2.703125 | 3 | [] | no_license | =begin
date:2020.7.17 fri
result:AC
問題URL:https://atcoder.jp/contests/abc172/tasks/abc172_a
結果URL:https://atcoder.jp/contests/abc172/submissions/15276049
=end
# 自分の解答 ------------------------
a = gets.to_i
puts a + a*a + a*a*a
# 他の回答 -------------------------
a = gets.chomp.to_i
puts a + a**2 + a**3 | true |
46560b648210832f737582cd0ed409871b255a68 | Ruby | jomapormentilla/hogwarts-social-network-sinatra | /app/models/concerns/slugifiable.rb | UTF-8 | 361 | 2.875 | 3 | [
"MIT"
] | permissive | module Slugifiable
module ClassMethods
def find_by_slug( slug )
self.all.detect{ |obj| obj.slug == slug }
end
end
module InstanceMethods
def slug
string = self.class == Wizard ? self.username : self.name
string.downcase.gsub(/\W/," ").gsub(/\s+/," ").gsub(" ","-")
end
end
end | true |
35ec88040058aa1d4f8d437ec4264380e9e3593b | Ruby | Yetidancer/backend_module_0_capstone | /day_1/ex11.rb | UTF-8 | 226 | 3.921875 | 4 | [] | no_license | print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.strip
print "How much do you weigh? "
weight = gets.chomp
weight[3..6]="."
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
| true |
893589366d856da4f0a68157deb3d88b66dc651e | Ruby | danielng09/App-Academy | /w1d2 Classes/io.rb | UTF-8 | 2,014 | 4.125 | 4 | [] | no_license | class NumberGuessingGame
attr_reader :answer
def initialize
@answer = rand(100) + 1
end
def prompt
puts "Guess a number"
Integer(gets)
end
def check(number)
if answer > number
puts "Too Low"
elsif answer < number
puts "Too High"
end
end
def run_game
guess_num = 0
user_input = 0
until won?(user_input)
user_input = prompt
check(user_input)
guess_num += 1
end
puts "You won in #{guess_num} guesses"
end
def won?(number)
answer == number
end
end
class ShuffleLines
def run
prompt
@file_contents.shuffle!
write_to_file
"shuffle file complete"
end
def prompt
puts "Type in file name"
@file_name = gets.chomp
@file_contents = File.readlines(@file_name)
end
def write_to_file
input_name = @file_name.gsub(/\..*$/,"")
File.open("#{input_name}-shuffled.txt", "w") do |f|
f.puts @file_contents
end
end
end
class RPNCalculator
def prompt
puts "Type in the file to read or write out the stack"
@arguments = gets.chomp
if file?
@arguments = File.read(@arguments).split(/\s+/)
else
@arguments = @arguments.split(" ")
end
calculate
end
def file?
@arguments =~ /\./
end
def calculate
@output = []
@arguments.each do |ele|
if ele =~ /\d/
@output << ele.to_i
elsif ele =~ /\+/
add
elsif ele =~ /-/
subtract
elsif ele =~ /\//
divide
elsif ele =~ /\*/
multiply
end
end
@output.count == 1 ? @output.first : "Error"
end
def add
first = @output.pop
second = @output.pop
@output << first + second
end
def subtract
first = @output.pop
second = @output.pop
@output << second - first
end
def multiply
first = @output.pop
second = @output.pop
@output << first * second
end
def divide
first = @output.pop
second = @output.pop
@output << second / first
end
end
| true |
b43a86abed739c7a17840e6670994858fc997c91 | Ruby | alxtz/developer-exercise | /exercise.rb | UTF-8 | 772 | 3.984375 | 4 | [] | no_license | class Exercise
def self.marklar(str)
return str.gsub(/\w{5,}/){ |input| /[[:upper:]]/.match(input[0]) ? 'Marklar' : 'marklar' }
end
def self.even_fibonacci(nth)
fib_array = create_fibonacci(nth)
sum = 0
fib_array.each { |x|
if (x%2==0)
sum += x
end
}
# puts('sum',sum)
return sum
end
def self.create_fibonacci(nth)
index = 0
ary = []
a, b = 0, 1
while index < nth
index = index + 1
ary.push(a)
a, b = b, a+b
end
return ary
end
end
# Testing the result
# puts(Exercise.marklar('The quick brown fox'))
# puts(Exercise.marklar('Down goes Frazier'))
# puts(Exercise.marklar('How is the weather today? I have not been outside.'))
# Exercise.even_fibonacci(35)
| true |
19a296ad510bbd957b477f0b9334a017851f6867 | Ruby | matthewrudy/moving-people-safely | /app/services/authorize_user_to_access_prisoner.rb | UTF-8 | 646 | 2.625 | 3 | [] | no_license | class AuthorizeUserToAccessPrisoner
def self.call(user, prison_number)
new(user, prison_number).call
end
def initialize(user, prison_number)
@user = user
@prison_number = prison_number
end
def call
return true if user.admin? || user.court? || user.police?
return true unless prisoner_location
user.authorized_establishments.include?(prisoner_location)
end
private
attr_reader :user, :prison_number
def prisoner_location
response = Detainees::LocationFetcher.new(prison_number).call
return false unless response.to_h[:code]
Establishment.find_by(nomis_id: response.to_h[:code])
end
end
| true |
c17331f2b6d22fefe9395958e9ff53db29c29fed | Ruby | yutingcxiang/blackjack | /spec/deck_spec.rb | UTF-8 | 3,304 | 3.3125 | 3 | [] | no_license | require 'spec_helper'
require_relative '../lib/deck.rb'
require_relative "../lib/card.rb"
RSpec.describe Deck do
let(:new_deck) { Deck.new }
let(:new_deck_suits) { new_deck.cards.map(&:suit) }
let(:new_deck_values) { new_deck.cards.map(&:value) }
context 'when Deck is initialized' do
it 'will have 52 cards' do
expect(new_deck.num_cards).to eql(52)
end
it 'will contain 4 suits' do
expect(new_deck_suits.uniq.count).to eq(4)
expect(new_deck_suits).to include('Diamonds')
expect(new_deck_suits).to include('Hearts')
expect(new_deck_suits).to include('Spades')
expect(new_deck_suits).to include('Clubs')
end
it 'will contain 13 different values' do
expect(new_deck_values.uniq.count).to eq(13)
expect(new_deck_values).to include('A')
expect(new_deck_values).to include('2')
expect(new_deck_values).to include('3')
expect(new_deck_values).to include('4')
expect(new_deck_values).to include('5')
expect(new_deck_values).to include('6')
expect(new_deck_values).to include('7')
expect(new_deck_values).to include('8')
expect(new_deck_values).to include('9')
expect(new_deck_values).to include('10')
expect(new_deck_values).to include('J')
expect(new_deck_values).to include('Q')
expect(new_deck_values).to include('K')
end
it 'will create an ordered deck' do
expect(new_deck.cards[0].read).to eql("| A of Diamonds |")
expect(new_deck.cards[-1].read).to eql("| K of Spades |")
end
end
let(:dealt_card) { new_deck.deal }
describe '#deal_card' do
it 'will select the first card from the Deck' do
expect(dealt_card.read).to eql("| A of Diamonds |")
end
it 'removes first card from deck' do
expect(new_deck.cards.include?(dealt_card)).to be(false)
expect(new_deck.num_cards).to be(51)
end
it 'does not return card if Deck is empty' do
empty_deck = Deck.new
while empty_deck.cards.count > 0 do
empty_deck.deal
end
expect(empty_deck.deal).to eql("Deck empty - no more cards to draw.")
expect(empty_deck.num_cards).to be(0)
end
end
describe '#shuffle_deck' do
let(:original_deck) { new_deck.cards.dup }
let(:shuffled_deck) { new_deck.shuffle }
it 'will randomize the cards in the Deck' do
# it has the same cards && the cards are in a different order
# same_cards && different_order
same_order = original_deck == shuffled_deck
original_sorted_cards = original_deck.sort
shuffled_sorted_cards = shuffled_deck.sort
same_cards = original_sorted_cards == shuffled_sorted_cards
expect(same_cards && !same_order).to be(true)
end
let(:reshuffled_deck) { new_deck.shuffle }
it 'will have different cards each time' do
shuffled_deck_cards = shuffled_deck.dup
reshuffled_deck_cards = new_deck.shuffle
expect(shuffled_deck_cards).not_to eq(reshuffled_deck_cards)
expect(shuffled_deck_cards).not_to eq(original_deck)
end
end
describe 'reset' do
let(:original_deck) { new_deck.cards.dup }
it 'will reset the order of the cards to the initial order' do
new_deck.shuffle
expect(new_deck.reset).to eq(original_deck)
end
end
end
| true |
e41051ddb92318300d3072ab0237b95aab3909d6 | Ruby | shubhbjp/josh_app | /app/models/seat.rb | UTF-8 | 1,364 | 2.65625 | 3 | [] | no_license | class Seat < ApplicationRecord
belongs_to :room
has_one :employee
has_many :emp_date_wise_seat, :foreign_key => "seat_id"
scope :get_all_seats_in_room, ->(room_id) { self.where(room_id: room_id).pluck(:id) rescue []}
scope :get_room_wise_seat_count, -> () {self.group(:room_id).count}
def self.room_with_more_than_n_emp(n=0)
count_of_rooms = self.get_room_wise_seat_count
return [] if count_of_rooms.blank?
count_of_employee_in_each_room = []
count_of_rooms.keys.each do |c|
available_seats = self.get_all_seats_in_room(c) if count_of_rooms[c] >= n
next if available_seats.blank?
emp_count = Employee.where("curr_seat_id = ? ", available_seats).count
count_of_employee_in_each_room << {room_id: c, emp_count: emp_count} if emp_count >=n
end
return count_of_employee_in_each_room
end
def self.get_emp_seat_on_given_date(emp_id=0, date='')
response = {room_id: '', seat_id: ''}
date = date.to_date.strftime("%Y-%m-%d") rescue Date.today.strftime("%Y-%m-%d")
data = self.joins(:emp_date_wise_seat).where("emp_date_wise_seats.employee_id = ?", emp_id).where("DATE(emp_date_wise_seats.created_at) <= ?", date).order("emp_date_wise_seats.id desc").try(:first) rescue ''
response[:room_id] = data.room_id rescue ''
response[:seat_id] = data.id rescue ''
return response
end
end
| true |
1cd4bcb7de9a4af6be1ab0530467998b7cf9b0f8 | Ruby | gweng1t/exo_ruby | /voyages.rb | UTF-8 | 621 | 3.140625 | 3 | [] | no_license | villes = ["Paris", "New York", "Berlin", "Montreal"];
voyages = [
{ville: "Paris", duree: 10},
{ville: "New York", duree: 5},
{ville: "Berlin", duree: 2},
{ville: "Montreal", duree: 15}
]
puts "DEFI N°1 - Si j'étais en vacances, j'irais à ..."
villes.each do |ville|
puts ville
end
puts "\n"
puts "DEFI N°2 - Détail de mes vacances de rêve"
voyages.each do |vol|
puts "Voyage à " +vol[:ville]+ " de #{vol[:duree]} jours"
end
puts "\n"
puts "DEFI N°3 - Mes vacances de rêve (enfin presque)"
voyages.each do |vol|
if vol[:duree] <= 5
puts "Voyage à " +vol[:ville]+ " de #{vol[:duree]} jours"
end
end
| true |
42e3594fad5f8b62555c0734b4973b8b533f2e59 | Ruby | ecliptik/tcpwrapper-update | /app.rb | UTF-8 | 505 | 2.75 | 3 | [] | no_license | require "sinatra"
require "erb"
#Disable exceptions
disable :show_exceptions
#Update hosts.allow file using erb template
def update_file(ip)
#Template of hosts.allow
template = File.read("hosts.allow.erb")
renderer = ERB.new(template).result(binding)
#Write out file and return success or error
File.write('hosts.allow', renderer)
return "Updated to #{ip}"
end
#Single route to call update_file method and print result
get "/update" do
result = update_file request.ip
"#{result}"
end
| true |
69fd4a7441de8fb6f9716a6b88b2f52538ef729c | Ruby | ennuiiii/cse413-Programming-Languages | /hw7/scan.rb | UTF-8 | 7,715 | 3.640625 | 4 | [] | no_license | # CSE 413
# Assignment # 7
# Qiubai Yu
# 1663777
class Token
attr_reader :kind, :value
def initialize(kind, value = nil)
@kind = kind
@value = value
end
def kind
@kind
end
def value
@value
end
def to_s
# some lexical classes descriptions
# NUM - numbers
# ID - identifiers
# operators: +, -, *, /, (, ), **, =
# ADD - +
# SUB - -
# MUL - *
# DIV - /
# LPAREN - (
# RPAREN - )
# POW - **
# EQUAL - =
# statement operations: sqrt, clear, list, quit, exit
# SQRT - sqrt
# CLEAR - clear
# LIST - list
# QUIT - quit
# EXIT - exit
# EOL - end of line
if @value == nil
return @kind
else
return @kind + "(" + @value + ")"
end
end
end
class Scanner
# definitions of lexical classes
OPERATION = /^[\+\-\*\/\(\)\=]$/
KEYWORD = /^list$|^quit$|^exit$|^clear$|^sqrt$/
NUMBER = /^[0-9]+(\.[0-9]+)?([Ee][\+\-]?[0-9]+)?$/
EOL = /^;$/
IDENTIFIER = /^[a-zA-Z][a-zA-Z0-9_]*$/
def initialize
@tokens = Array.new
@tokenIndex = -1
@processIndex = 0
end
def scan
raw = gets
if raw != "\n"
raw = raw.gsub(/\n/, "") << ";"
else
raw = ";"
end
process(raw)
end
def process(inp)
@processIndex = 0
# input is not nil, I can keep extract a token from it
if inp && inp != ""
# if the first char of string matches the OPERATIONs
if (inp[0].match OPERATION)
if inp[0] == "*"
if inp[1] && inp[1] == "*"
@tokens.push(Token.new("POW", "**"))
process(inp[2..-1])
else
@tokens.push(Token.new("MUL", "*"))
process(inp[1..-1])
end
elsif inp[0] == "+"
@tokens.push(Token.new("ADD", "+"))
process(inp[1..-1])
elsif inp[0] == "-"
@tokens.push(Token.new("SUB", "-"))
process(inp[1..-1])
elsif inp[0] == "/"
@tokens.push(Token.new("DIV", "/"))
process(inp[1..-1])
elsif inp[0] == "("
@tokens.push(Token.new("LPAREN", "("))
process(inp[1..-1])
elsif inp[0] == ")"
@tokens.push(Token.new("RPAREN", ")"))
process(inp[1..-1])
elsif inp[0] == "="
@tokens.push(Token.new("EQUAL", "="))
process(inp[1..-1])
end
# if the first char of string matches the identifier(including the keywords)
elsif (inp[@processIndex].match IDENTIFIER)
temp = String.new
temp += inp[@processIndex]
while (inp[0..(@processIndex + 1)].match IDENTIFIER) && (@processIndex + 1) != inp.length
@processIndex += 1
temp += inp[@processIndex]
end
if (temp.match KEYWORD)
@tokens.push(Token.new(temp.upcase, temp))
else
@tokens.push(Token.new("ID", temp))
end
process(inp[(@processIndex + 1)..-1])
elsif (inp[@processIndex].match NUMBER)
temp = String.new
temp += inp[@processIndex]
while (inp[0..(@processIndex + 1)].match NUMBER) && (inp[(@processIndex + 1)])
@processIndex += 1
temp += inp[@processIndex]
end
# right here, temp will be a pure number, since 1. or 1e is not considered a number
# do further tests
if inp[@processIndex + 1] =~ /[Ee]/
if inp[@processIndex + 2] && inp[@processIndex + 2] =~ /[+-]/
if inp[@processIndex + 3] && (inp[@processIndex + 3].match NUMBER)
temp += inp[(@processIndex + 1)..(@processIndex + 3)]
@processIndex += 3
while (inp[0..(@processIndex + 1)].match NUMBER) && (inp[(@processIndex + 1)])
@processIndex += 1
temp += inp[@processIndex]
end
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
else
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
end
elsif inp[@processIndex + 2] && (inp[@processIndex + 2].match NUMBER)
temp += inp[(@processIndex + 1)..(@processIndex + 2)]
@processIndex += 2
while (inp[0..(@processIndex + 1)].match NUMBER) && (inp[(@processIndex + 1)])
@processIndex += 1
temp += inp[@processIndex]
end
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
else
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
end
elsif inp[@processIndex + 1] == "."
if (inp[@processIndex + 2] =~ NUMBER)
temp += inp[(@processIndex + 1)..(@processIndex + 2)]
@processIndex += 2
while (inp[0..(@processIndex + 1)].match NUMBER) && (inp[(@processIndex + 1)])
@processIndex += 1
temp += inp[@processIndex]
end
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
else
temp += inp[@processIndex + 1]
@processIndex += 1
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
end
else
@tokens.push(Token.new("NUMBER", temp))
process(inp[(@processIndex + 1)..-1])
end
elsif inp[0].match EOL
@tokens.push(Token.new("EOL", ";"))
else
#invalid characters or white spaces, skip them
process(inp[1..-1])
end
end
end
# pre-processing the input and stores several tokens in @tokens
# return one element in @tokens each call
def next_token
if @tokenIndex != @tokens.length
@tokenIndex += 1
return @tokens[@tokenIndex]
end
end
def peek
if (@tokenIndex + 1 != @tokens.length)
return @tokens[(@tokenIndex + 1)]
end
end
def twoahead
if (@tokenIndex + 2 != @tokens.length)
return @tokens[(@tokenIndex + 2)]
end
end
end
| true |
1bfa804b40f67f91043c433bece77125c9a49ada | Ruby | michaeltelford/rack_cache | /helpers.rb | UTF-8 | 1,282 | 2.828125 | 3 | [] | no_license |
def html(body, javascript: nil)
<<~HTML
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
#{"<script>#{javascript}</script>" if javascript}
</head>
<body>
#{body}
</body>
</html>
HTML
end
def login_form
<<~HTML
<br />
<form method="post" action="/auth" onsubmit="encodePassword();">
<div>
<label for="username">Username</label>
<br />
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">Password</label>
<br />
<input type="password" name="password" id="password">
</div>
<div>
<br />
<input type="submit" value="Login">
</div>
</form>
HTML
end
def encode_password
<<~JS
function encodePassword() {
const password_el = document.getElementById('password');
const password = password_el.value;
const passwordBase64 = btoa(password);
password_el.value = passwordBase64;
}
JS
end
def auth(username, password)
return false unless username && password
decoded_password = Base64.decode64(password)
puts "login: #{username}:#{decoded_password}"
(username == 'admin') && (decoded_password == 'Admin101')
end
| true |
0d344e169972ee7202df4bc26359d017989c343c | Ruby | chadellison/exercismio | /word-count/word_count.rb | UTF-8 | 280 | 3.15625 | 3 | [] | no_license | class Phrase
VERSION = 1
def initialize(words)
@words = words.delete(":!!.&@$%^\n").downcase
end
def word_count
word_count = Hash.new(0)
words = @words.gsub(",", " ").scan(/\b[\w']+\b/)
words.each { |word| word_count[word] += 1 }
word_count
end
end
| true |
5db18f4df2796fd1ee1526d8d4ee4a215e08faf5 | Ruby | billylittlefield/ruby-chess | /pieces/steppable.rb | UTF-8 | 413 | 2.6875 | 3 | [] | no_license | module Steppable
def generate_possible_moves(delta_1, delta_2)
possible_moves = []
generate_all_deltas(delta_1, delta_2).each do |deltas|
shifted_pos = pos_with_deltas(pos, deltas)
possible_moves << shifted_pos
end
possible_moves.select do |possible_move|
piece = board[*possible_move] if board.in_bounds?(possible_move)
piece && piece.color != color
end
end
end
| true |
b29f4fca4b7600d1d1d4feeabb339f238568087f | Ruby | partyof5/partyof5_playlister | /playlister/lib/models/artist.rb | UTF-8 | 829 | 3.21875 | 3 | [] | no_license | class Artist
attr_accessor :name, :songs
@@artists = []
def initialize
@songs = []
@@artists << self
end
def add_song(song)
self.songs << song
end
def add_song_object_by_name(song_name)
song = Song.new
song.name = song_name
add_song(song)
end
def genres
self.songs.collect do |song|
song.genre
end
end
def url
"#{self.name.downcase.gsub(" ", "_")}.html"
end
def self.reset_artists
@@artists.clear
end
def self.all
@@artists
end
def self.count
@@artists.size
end
def self.find_or_create_by_name(string)
find_by_name(string) || create_by_name(string)
end
def self.find_by_name(string)
@@artists.detect{|a| a.name == string}
end
def self.create_by_name(string)
Artist.new.tap{|a| a.name = string}
end
end | true |
f20c412cc4ef31288ed4a166229407837cc05b46 | Ruby | Level-turing-team/level_front_end | /app/poros/circle.rb | UTF-8 | 250 | 2.53125 | 3 | [] | no_license | class Circle
attr_reader :profile_picture,
:username,
:id
def initialize(data)
@profile_picture = data[:attributes][:profile_picture]
@username = data[:attributes][:username]
@id = data[:id].to_i
end
end
| true |
0d05dad69cefdc5f13b1f1112786a914a9e8a78d | Ruby | stmichael/spinning_jenny | /spec/spinning_jenny/blueprint_spec.rb | UTF-8 | 811 | 2.796875 | 3 | [] | no_license | require 'spinning_jenny/blueprint'
describe SpinningJenny::Blueprint do
let(:sample_class) { Class.new }
subject { SpinningJenny::Blueprint.new sample_class }
describe "#initialize" do
it "stores the class that the blueprint describes" do
blueprint = SpinningJenny::Blueprint.new(sample_class)
blueprint.describing_class.should == sample_class
end
end
describe "property methods" do
it "sets the default value for a specific property" do
subject.my_property :value
subject.default_values['my_property'].should == :value
end
it "sets a block as a default value" do
subject.my_property { :value }
subject.default_values['my_property'].should be_kind_of(Proc)
subject.default_values['my_property'].call.should == :value
end
end
end
| true |
7576f5196664f25b9c945a70af24af38bfc8712e | Ruby | FlipTech9/ttt-6-position-taken-rb-bootcamp-prep-000 | /lib/position_taken.rb | UTF-8 | 242 | 3.5 | 4 | [] | no_license | # code your #position_taken? method here!
def position_taken? (board, index)
isTaken = nil
if(board[index] == " " || board[index] == "" || board[index] == nil)
isTaken = false
elsif
isTaken = true
end
isTaken
end | true |
3736353b9707e2cb010192a688e730e7c62a4b07 | Ruby | Dujota/reinforcement_tdd_simon | /simon_says.rb | UTF-8 | 361 | 3.578125 | 4 | [] | no_license | def echo(input)
input
end
def shout(input)
input.upcase
end
def repeat(string, multiple)
# prodcuce the desired string and then remove the leading whitespace to make it the test result
(" #{string}" * multiple).lstrip
end
def start_of_word(string, how_many_chars)
string[0..(how_many_chars-1)]
end
def first_word(input)
input.split(" ")[0]
end
| true |
f62931fc2b2d26381455cf614ce826681c1d7efd | Ruby | rawls/cricket-scoreboard | /lib/cricinfo/structs/team.rb | UTF-8 | 1,153 | 3.03125 | 3 | [] | no_license | module Cricinfo
module Structs
# Represents a cricket team
class Team < Base
attr_reader :id, :name, :short_name, :players
def initialize(opts)
@id = opts[:id]
@name = opts[:name]
@short_name = opts[:short_name]
@players = {}
end
# Construct a team object from a Cricinfo JSON hash
def self.parse(teamj)
team = new(
id: string(teamj, 'team_id'),
name: string(teamj, 'team_name'),
short_name: string(teamj, 'team_abbreviation')
)
team.add_players(teamj)
team
end
# Fetch a specific player from this team
def player(player_id)
@players[player_id]
end
# Add players to the team from a Cricinfo JSON hash
def add_players(teamj)
type = %w[player squad].detect { |t| !teamj[t].nil? }
return unless type
teamj[type].each do |playerj|
player = Player.parse(playerj)
@players[player.id] = player
end
@players
rescue StandardError => e
Cricinfo.logger.error(e)
end
end
end
end
| true |
a83dd7ed54190764af02d0842218d78bd036fad4 | Ruby | hectorhuertas/headcount | /test/economic_profile_test.rb | UTF-8 | 1,450 | 3.265625 | 3 | [] | no_license | require 'economic_profile'
require 'minitest'
class EconomicProfileTest < Minitest::Test
attr_reader :ep
def setup
data = { name: 'turing',
median_household_income: { [2005, 2009] => 50_000, [2008, 2014] => 60_000 },
children_in_poverty: { 2012 => 0.1845 },
free_or_reduced_price_lunch: { 2014 => { percentage: 0.023, total: 100 } },
title_i: { 2015 => 0.543 }
}
@ep = EconomicProfile.new(data)
end
def test_it_exists
assert EconomicProfile
end
def test_it_is_created_with_name
assert_equal "TURING", ep.name
end
def test_it_calculates_median_household_income_in_year
assert_equal 50000, ep.estimated_median_household_income_in_year(2005)
assert_equal 55000, ep.estimated_median_household_income_in_year(2009)
assert_equal 60000, ep.estimated_median_household_income_in_year(2010)
end
def test_it_calculates_median_household_income_average
assert_equal 55000, ep.median_household_income_average
end
def test_it_calculates_poverty_in_year
# binding.pry
assert_equal 0.184, ep.children_in_poverty_in_year(2012)
end
def test_lunch_help_percentage
assert_equal 0.023, ep.free_or_reduced_price_lunch_percentage_in_year(2014)
end
def test_lunch_help_total
assert_equal 100, ep.free_or_reduced_price_lunch_number_in_year(2014)
end
def test_title_i
assert_equal 0.543, ep.title_i_in_year(2015)
end
end
| true |
116f112a556d2a5ad65efa903c36a353dac23e14 | Ruby | stade/Saas-code | /hw2/Saas22.rb | UTF-8 | 1,282 | 3.890625 | 4 | [] | no_license | class CartesianProduct
include Enumerable
attr_accessor :cartesian_array
def initialize(firstarr, secondarr)
@cartesian_array = Array.new
if firstarr.count == 0 && secondarr.count == 0
return
elsif
max_index_first = firstarr.count-1
max_index_second = secondarr.count-1
first = firstarr
second = secondarr
current_index_first = 0
current_index_second = 0
while max_index_first >= current_index_first
while max_index_second >= current_index_second
@cartesian_array.push([first[current_index_first], second[current_index_second]])
current_index_second += 1
end
current_index_second = 0
current_index_first += 1
end
end
end
def each
max_index = self.cartesian_array.count-1
first = @cartesian_array
current_index = 0
while max_index >= current_index
yield self.cartesian_array[current_index]
current_index += 1
end
end
end
#c = CartesianProduct.new([:a,:b], [4,5])
#c.each { |elt| puts elt.inspect }
#[:a, 4]
# [:a, 5]
# [:b, 4]
# [:b, 5]
#c = CartesianProduct.new([:a,:b], [])
#c.each { |elt| puts elt.inspect }
# (nothing printed since Cartesian product
# of anything with an empty collection is empty)
| true |
fab88fe167b60e0a4268134e348a6e8e04f9383c | Ruby | iseitz/Connect-4-Ruby | /lib/board.rb | UTF-8 | 1,936 | 3.734375 | 4 | [] | no_license | require_relative 'game_turn'
require_relative 'board_space'
class Board
LETTERS = ("a".."z").to_a
attr_accessor :game_board
attr_reader :col_num
attr_reader :row_num
attr_reader :letter_to_index
def initialize(col_num = 10, row_num = 10)
@col_num = col_num
@row_num = row_num
@game_board = build_board
end
def build_board
new_board = []
@row_num.times do
row = []
@col_num.times do
row << BoardSpace.new
end
new_board << row
end
new_board
end
def rows
@game_board
end
def print_board
board_output = ""
@game_board.each do |row|
row.each_with_index do |space, index|
if index == 0
board_output += "|#{space.to_char} "
elsif index == @col_num - 1
board_output += "#{space.to_char}|\n"
else
board_output += "#{space.to_char} "
end
end
end
bottom_row = ""
LETTERS.each_with_index do |letter, index|
if index + 1 <= @col_num
bottom_row += " #{letter.capitalize}"
end
end
bottom_row += " \n"
board_output += bottom_row
end
def letter_to_index (column)
LETTERS.each_with_index do |letter, index|
if column == letter
column = index
end
end
column
end
def add_turn(player, column)
@last_turn = GameTurn.new(self, player, column)
@last_turn.take!
end
def has_empty_spaces?
@game_board.each do |row|
row.each do |space|
if !space.occupied?
return true
end
end
end
return false
end
def column_full?(column)
column = letter_to_index(column)
@game_board.each do |row|
if !row[column].occupied?
return false
else
return true
end
end
end
def winner?
if @last_turn
@last_turn.winner?
else
false
end
end
end
| true |
920ec33d8a6cd1787c25236d8c4d662daacf210a | Ruby | balthisar/mm_tool | /lib/mm_tool/mm_movie_stream.rb | UTF-8 | 18,255 | 2.859375 | 3 | [
"MIT"
] | permissive | module MmTool
#=============================================================================
# A stream of an MmMovie. Instances contain simple accessors to the data
# made available by ffmpeg, and have knowledge on how to generate useful
# arguments for ffmpeg and mkvpropedit.
#=============================================================================
class MmMovieStream
require 'streamio-ffmpeg'
require 'mm_tool/mm_movie'
#------------------------------------------------------------
# Given an array of related files, this class method returns
# an array of MmMovieStreams reflecting the streams present
# in each of them.
#------------------------------------------------------------
def self.streams(with_files:)
# Arrays are passed around by reference; when this array is created and
# used as a reference in each stream, and *also* returned from this class
# method, everyone will still be using the same reference. It's important
# below to build up this array without replacing it with another instance.
streams = []
with_files.each_with_index do |path, i|
ff_movie = FFMPEG::Movie.new(path)
ff_movie.metadata[:streams].each do |stream|
streams << MmMovieStream.new(stream_data: stream, source_file: path, file_number: i, streams_ref: streams)
end
end
streams
end
#------------------------------------------------------------
# Initialize
#------------------------------------------------------------
def initialize(stream_data:, source_file:, file_number:, streams_ref:)
@defaults = MmUserDefaults.shared_user_defaults
@data = stream_data
@source_file = source_file
@file_number = file_number
@streams = streams_ref
end
#------------------------------------------------------------
# Attribute accessors
#------------------------------------------------------------
attr_accessor :file_number
attr_accessor :source_file
#------------------------------------------------------------
# Property - returns the index of the stream.
#------------------------------------------------------------
def index
@data[:index]
end
#------------------------------------------------------------
# Property - returns the input specifier of the stream.
#------------------------------------------------------------
def input_specifier
"#{@file_number}:#{index}"
end
#------------------------------------------------------------
# Property - returns the codec name of the stream.
#------------------------------------------------------------
def codec_name
@data[:codec_name]
end
#------------------------------------------------------------
# Property - returns the codec type of the stream.
#------------------------------------------------------------
def codec_type
@data[:codec_type]
end
#------------------------------------------------------------
# Property - returns the coded width of the stream.
#------------------------------------------------------------
def coded_width
@data[:coded_width]
end
#------------------------------------------------------------
# Property - returns the coded height of the stream.
#------------------------------------------------------------
def coded_height
@data[:coded_height]
end
#------------------------------------------------------------
# Property - returns the number of channels of the stream.
#------------------------------------------------------------
def channels
@data[:channels]
end
#------------------------------------------------------------
# Property - returns the channel layout of the stream.
#------------------------------------------------------------
def channel_layout
@data[:channel_layout]
end
#------------------------------------------------------------
# Property - returns the language of the stream, or 'und'
# if the language is not defined.
#------------------------------------------------------------
def language
if @data.key?(:tags)
lang = @data[:tags][:language]
lang = @data[:tags][:LANGUAGE] unless lang
lang = 'und' unless lang
else
lang = 'und'
end
lang
end
#------------------------------------------------------------
# Property - returns the title of the stream, or nil.
#------------------------------------------------------------
def title
if @data.key?(:tags)
@data[:tags][:title]
else
nil
end
end
#------------------------------------------------------------
# Property - returns the disposition flags of the stream as
# a comma-separated list for compactness.
#------------------------------------------------------------
def dispositions
MmMovie.dispositions
.collect {|symbol| @data[:disposition][symbol]}
.join(',')
end
#------------------------------------------------------------
# Property - returns an appropriate "quality" indicator
# based on the type of the stream.
#------------------------------------------------------------
def quality_01
if codec_type == 'audio'
channels
elsif codec_type == 'video'
coded_width
else
nil
end
end
#------------------------------------------------------------
# Property - returns a different appropriate "quality"
# indicator based on the type of the stream.
#------------------------------------------------------------
def quality_02
if codec_type == 'audio'
channel_layout
elsif codec_type == 'video'
coded_height
else
nil
end
end
#------------------------------------------------------------
# Property - returns a convenient label indicating the
# recommended actions for the stream.
#------------------------------------------------------------
def action_label
"#{output_specifier} #{actions.select {|a| a != :interesting}.join(' ')}"
end
#------------------------------------------------------------
# Property - indicates whether or not the stream is the
# default stream per its dispositions.
#------------------------------------------------------------
def default?
@data[:disposition][:default] == 1
end
#------------------------------------------------------------
# Property - indicates whether or not the stream is
# considered "low quality" based on the application
# configuration.
#------------------------------------------------------------
def low_quality?
if codec_type == 'audio'
channels.to_i < @defaults[:min_channels].to_i
elsif codec_type == 'video'
coded_width.to_i < @defaults[:min_width].to_i
else
false
end
end
#------------------------------------------------------------
# Property - stream action includes :drop?
#------------------------------------------------------------
def drop?
actions.include?(:drop)
end
#------------------------------------------------------------
# Property - stream action includes :copy?
#------------------------------------------------------------
def copy?
actions.include?(:copy)
end
#------------------------------------------------------------
# Property - stream action includes :transcode?
#------------------------------------------------------------
def transcode?
actions.include?(:transcode)
end
#------------------------------------------------------------
# Property - stream action includes :set_language?
#------------------------------------------------------------
def set_language?
actions.include?(:set_language)
end
#------------------------------------------------------------
# Property - stream action includes :interesting?
#------------------------------------------------------------
def interesting?
actions.include?(:interesting)
end
#------------------------------------------------------------
# Property - indicates whether or not the stream will be
# unique for its type at output.
#------------------------------------------------------------
def output_unique?
@streams.count {|s| s.codec_type == codec_type && !s.drop? } == 1
end
#------------------------------------------------------------
# Property - indicates whether or not this stream is the
# only one of its type.
#------------------------------------------------------------
def one_of_a_kind?
@streams.count {|s| s.codec_type == codec_type && s != self } == 0
end
#------------------------------------------------------------
# Property - returns the index of the stream in the output
# file.
#------------------------------------------------------------
def output_index
@streams.select {|s| !s.drop? }.index(self)
end
#------------------------------------------------------------
# Property - returns a specific output specifier for the
# stream, such as v:0 or a:2.
#------------------------------------------------------------
def output_specifier
idx = @streams.select {|s| s.codec_type == codec_type && !s.drop?}.index(self)
idx ? "#{codec_type[0]}:#{idx}" : ' ⬇ '
end
#------------------------------------------------------------
# Property - returns the -i input instruction for this
# stream.
#------------------------------------------------------------
def instruction_input
src = if @file_number == 0
File.join(File.dirname(@source_file), File.basename(@source_file, '.*') + @defaults[:suffix] + File.extname(@source_file))
else
@source_file
end
"-i \"#{src}\" \\"
end
#------------------------------------------------------------
# Property - returns the -map instruction for this stream,
# according to the action(s) determined.
#------------------------------------------------------------
def instruction_map
drop? ? nil : "-map #{input_specifier} \\"
end
#------------------------------------------------------------
# Property - returns an instruction for handling the stream,
# according to the action(s) determined.
#------------------------------------------------------------
def instruction_action
if copy?
"-codec:#{output_specifier} copy \\"
elsif transcode?
if codec_type == 'audio'
encode_to = @defaults[:codecs_audio_preferred][0]
elsif codec_type == 'video'
encode_to = @defaults[:codecs_video_preferred][0]
else
raise Exception.new "Error: somehow the program branched where it shouldn't have."
end
"-codec:#{output_specifier} #{encoder_string(for_codec: encode_to)} \\"
else
nil
end
end
#------------------------------------------------------------
# Property - returns instructions for setting the metadata
# of the stream, if necessary.
#------------------------------------------------------------
def instruction_metadata
return [] if @actions.include?(:drop)
# We only want to set fixed_lang if options allow us to fix the language,
# and we want to set subtitle language from the filename, if applicable.
fixed_lang = @defaults[:fix_undefined_language] ? @defaults[:undefined_language] : nil
lang = subtitle_file_language ? subtitle_file_language : fixed_lang
result = []
result << "-metadata:s:#{output_specifier} language=#{lang} \\" if set_language?
result << "-metadata:s:#{output_specifier} title=\"#{title}\" \\" if title && ! @defaults[:ignore_titles]
result
end
#------------------------------------------------------------
# Property - returns an instruction for setting the stream's
# default disposition, if necessary.
#------------------------------------------------------------
def instruction_disposition
set_disposition = output_unique? && !default? && !drop? ? "default " : nil
if set_disposition
"-disposition:#{output_specifier} #{set_disposition}\\"
else
nil
end
end
#============================================================
private
#============================================================
#------------------------------------------------------------
# Property - returns an array of actions that are suggested
# for the stream based on quality, language, codec, etc.
#------------------------------------------------------------
def actions
#------------------------------------------------------------
# Note: logic below a result of Karnaugh mapping of the
# selection truth table for each desired action. There's
# probably an excel file somewhere in the repository.
#------------------------------------------------------------
if @actions.nil?
@actions = []
#––––––––––––––––––––––––––––––––––––––––––––––––––
# subtitle stream handler
#––––––––––––––––––––––––––––––––––––––––––––––––––
if codec_type == 'subtitle'
a = @defaults[:keep_langs_subs]&.include?(language)
b = @defaults[:codecs_subs_preferred]&.include?(codec_name)
c = language.downcase == 'und'
d = title != nil && ! @defaults[:ignore_titles]
if (!a && !c) || (!b)
@actions |= [:drop]
else
@actions |= [:copy]
end
if (b && c) && (@defaults[:fix_undefined_language])
@actions |= [:set_language]
end
if (!a || !b || c || (d))
@actions |= [:interesting]
end
#––––––––––––––––––––––––––––––––––––––––––––––––––
# video stream handler
#––––––––––––––––––––––––––––––––––––––––––––––––––
elsif codec_type == 'video'
a = codec_name.downcase == 'mjpeg'
b = @defaults[:codecs_video_preferred]&.include?(codec_name)
c = @defaults[:keep_langs_video]&.include?(language)
d = language.downcase == 'und'
e = title != nil && ! @defaults[:ignore_titles]
f = @defaults[:scan_type] == 'quality' && low_quality?
if (a)
@actions |= [:drop]
end
if (!a && b)
@actions |= [:copy]
end
if (!a && !b)
@actions |= [:transcode]
end
if (!a && d) && (@defaults[:fix_undefined_language])
@actions |= [:set_language]
end
if (a || !b || !c || d || e || f)
@actions |= [:interesting]
end
#––––––––––––––––––––––––––––––––––––––––––––––––––
# audio stream handler
#––––––––––––––––––––––––––––––––––––––––––––––––––
elsif codec_type == 'audio'
a = @defaults[:codecs_audio_preferred]&.include?(codec_name)
b = @defaults[:keep_langs_audio]&.include?(language)
c = language.downcase == 'und'
d = title != nil && ! @defaults[:ignore_titles]
e = @defaults[:scan_type] == 'quality' && low_quality?
if (!b && !c)
@actions |= one_of_a_kind? ? [:set_language] : [:drop]
end
if (a && b) || (a && !b && c)
@actions |= [:copy]
end
if (!a && !b && c) || (!a && b)
@actions |= [:transcode]
end
if (c) && (@defaults[:fix_undefined_language])
@actions |= [:set_language]
end
if (!a || !b || c || d || e)
@actions |= [:interesting]
end
#––––––––––––––––––––––––––––––––––––––––––––––––––
# other stream handler
#––––––––––––––––––––––––––––––––––––––––––––––––––
else
@actions |= [:drop]
end
end # if @actions.nil?
@actions
end # actions
#------------------------------------------------------------
# Given a codec, return the ffmpeg encoder string.
#------------------------------------------------------------
def encoder_string(for_codec:)
case for_codec.downcase
when 'hevc'
"libx265 -crf 28 -x265-params log-level=error -force_key_frames chapters"
when 'h264'
"libx264 -crf 23"
when 'aac'
"libfdk_aac"
else
raise Exception.new "Error: somehow an unsupported codec '#{for_codec}' was specified."
end
end
#------------------------------------------------------------
# If the source file is an srt, and there's a language, and
# it's in the approved language list, then return it;
# otherwise return nil.
#------------------------------------------------------------
def subtitle_file_language
langs = @defaults[:keep_langs_subs]&.join('|')
lang = @source_file.match(/^.*\.(#{langs})\.srt$/)
lang ? lang[1] : nil
end
end # class
end # module
| true |
06e264c2316406709005e06656beae9017721506 | Ruby | BJSherman80/backend_module_0_capstone | /day_3/exercises/bretts_game.rb | UTF-8 | 1,191 | 3.90625 | 4 | [] | no_license | puts "You walk into a hotel room to find two people standing there. A beautiful
girl in a bikini and a well dressed man in all black holding a suit case."
puts " 1. You go with the girl."
puts " 2. You go with the guy."
print "enter response here> "
input = $stdin.gets.chomp
if input == "1"
puts "1. She asks you if you want to play a game."
puts "2. She asks you to go swimming."
print "enter reponse here>"
input_2 = $stdin.gets.chomp
if input_2 == "1"
puts "Death by a thousand cuts as she throws cards at you."
elsif input_2 == "2"
puts "She throws you in the shower and drowns you."
else
puts "Good job, run away she was a psycho killer!!!"
end
elsif input == "2"
puts "He takes you up to the master suite and introduces himslef as Morpheus."
puts "#1 the red pill and #2 the blue pill, which one do you take?"
print "enter response here>"
input_3 = $stdin.gets.chomp
if input_3 == "1"
puts "You are in fact Mr. Anderson and you implode in a couple years."
elsif input_3 == "2"
puts " You enter the matrix and find out life is a program, you win."
else
puts "They decide your not the right person and throw you off the deck."
end
end
| true |
bab68785422c6df6ca5437eac8d05d65727a83d3 | Ruby | MattManson/record-shop | /models/artist.rb | UTF-8 | 1,945 | 3.234375 | 3 | [] | no_license | require_relative('../db/sql_runner')
require_relative('./album.rb')
class Artist
attr_reader :id, :name, :logo
def initialize(options)
@id = options['id'].to_i
@name = options['name']
@logo = options['logo']
end
def save
sql = "INSERT INTO artists
( name, logo )
VALUES
( $1, $2)
RETURNING *"
values = [@name, @logo]
artist = SqlRunner.run(sql, values)
@id = artist.first()['id'].to_i
end
def self.find( id )
sql = "SELECT * FROM artists
WHERE id = $1"
values = [id]
artist = SqlRunner.run( sql, values )
result = Artist.new( artist.first )
return result
end
def self.all
sql = "SELECT * FROM artists"
values = []
artists = SqlRunner.run( sql, values )
result = artists.map { |artist| Artist.new( artist ) }
return result
end
def update
sql = "UPDATE artists
SET( name, logo ) = ( $1, $2)
WHERE id = $3"
values = [@name, @logo, @id]
SqlRunner.run( sql, values )
end
def delete(id)
sql = "DELETE FROM artists WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def delete_all
sql = "DELETE FROM artists"
values = []
SqlRunner.run( sql, values )
end
def num_albums
sql = "SELECT COUNT(*)
FROM albums
WHERE artist = $1"
values = [@id]
album_count = SqlRunner.run( sql, values )[0]["count"]
# result = Album.new(albums.count)
return album_count
end
def albums
sql = "SELECT *
FROM albums
WHERE artist = $1"
values = [@id]
all_albums = SqlRunner.run(sql, values)
result = all_albums.map{ |album| Album.new( album ) }
return result
end
def self.search_artist(search)
sql = "SELECT *
FROM artists
WHERE (name LIKE $1 OR name LIKE lower($1))"
values = ["%#{search}%"]
artists = SqlRunner.run(sql, values)
return artists.map{|artist| Artist.new(artist)}
end
end
| true |
a90fb744076f3b9948e5c53dc6f251e699b0e0ab | Ruby | priit/ubiquo_core | /lib/ubiquo/extensions/filters_helper.rb | UTF-8 | 16,861 | 3 | 3 | [
"MIT"
] | permissive | require 'ostruct'
#= How to include filters on Ubiquo listings
#
#FiltersHelper module provide some commonly used filters. By default, the module is included in <tt>app/helpers/ubiquo_area_helper.rb</tt>:
#
# module UbiquoAreaHelper
# include FiltersHelper
# ...
# end
#
#* The filter itself, containing the HTML that displays the filter on the lateral panel. It contains a header and a link to disable the filter when it is active.
#
#* The info filter that appears on top of the index listing. It displays textual info about all the active filters and contains a link to disable them all.
#
# Filters are automatically added to the index view, you only have to fill the helper (example for controller _example_controller_):
#
# # app/helpers/ubiquo/example_helper.rb
# module Ubiquo::UbiquoUsersHelper
# def ubiquo_users_filters_info(params)
# # Put your filters info here (filter_info)
# end
#
# def ubiquo_users_filters(url_for_options = {})
# # Put your filters here (render_filter)
# end
#
# end
#
#
#== String filter
#
#link:../images/filter_string.png
#
#It consists of an input text tag with a search button.
#
# string_filter = render_filter(:string, {},
# :field => :filter_text,
# :caption => t('text'))
#
#First parameter is the filter name (:string) and the second is the ''url_for_options'' hash that will be merged with the filter params. If you want to submit the filter to the same action/controller you are in, simply pass an empty hash.
#
# string_filter = filter_info(:string, params,
# :field => :filter_text,
# :caption => t('text'))
#
# build_filter_info(string_filter)
#
#== Links filter
#
#link:../images/filter_link.png
#
#Given an attribute to filter, generate a link for each possible value. There are two common cases:
#
#* You have a separated model (one-to-many relationship). On this case, you have to pass the collection of values and the associated model tablename (plural, underscore form).
#
# asset_types_filter = render_filter(:links, {},
# :caption => t('type'),
# :all_caption => t('-- All --'),
# :field => :filter_type,
# :collection => @asset_types,
# :id_field => :id,
# :name_field => :name)
#
# build_filter_info(asset_types_filter)
# ---
# asset_types_filter = filter_info(:links, params,
# :caption => t('type'),
# :all_caption => t('-- All --'),
# :field => :filter_type,
# :collection => @asset_types,
# :model => :asset_types,
# :id_field => :id,
# :name_field => :name)
#
#* The possible values for an attribute but directly a list of them on the model. Let's see an example:
#
# class Link
# TARGET_OPTIONS = [[t("Link|blank"), "blank"], [t("Link|self"), "self"]]
# validates_inclusion_of :target, :in => TARGET_OPTIONS.map { |name, key| key }
# end
#
#
# # On the controller
# @target_types = Link::TARGET_OPTIONS.collect do |name, value|
# OpenStruct.new(:name => name, :value => value)
# end
#
# # On the view
# asset_types_filter = render_filter(:links, {},
# :caption => t('type'),
# :field => :filter_type,
# :collection => @target_types,
# :id_field => :value,
# :name_field => :name)
#
# asset_types_filter = filter_info(:links, params,
# :caption => t('target'),
# :field => :filter_type,
# :translate_prefix => 'Link')
#
# build_filter_info(asset_types_filter)
#
#== Select filter
#
#link:../images/filter_select_1.png
#
#link:../images/filter_select_2.png
#
#Generate a select tag given an array of items.
#
#It works exactly on the same way than the links filter, only that an extra option (options[:all_caption]) is needed to add a "all" option that disables the filter:
#
# asset_types_filter = render_filter(:select, {},
# :caption => t('type'),
# :all_caption => t('-- All --'),
# :field => :filter_type,
# :collection => @asset_types,
# :id_field => :id,
# :name_field => :name)
#
# build_filter_info(asset_types_filter)
#
#== Links or Select filter
#
#This filter renders a select filter if the collection items length is greater than ''options[:max_size_for_links]''; it uses a link filter otherwise. Pass the same options needed by a select filter. An example of the filter info code:
#
# asset_types_filter = render_filter(:links_or_select, {},
# :caption => t('type'),
# :all_caption => t('-- All --'),
# :field => :filter_type,
# :collection => @asset_types,
# :id_field => :id,
# :name_field => :name,
# :max_size_for_links => 2)
#
# build_filter_info(asset_types_filter)
#
#== Boolean Filter
#
#link:../images/bolean_filter.png
#
#For boolean attributes use a link or select filter, but instead of ''collection/id_field/name_field'' options, pass ''boolean/caption_true/caption_false''.
#
# admin_filter = render_filter(:links, {},
# :caption => t('ubiquo_user type'),
# :boolean => true,
# :caption_true => t('Admin'),
# :caption_false => t('Non-admin'),
# :field => :filter_admin)
# ---
# admin_filter = filter_info(:links, params,
# :caption => t('ubiquo_user type'),
# :boolean => true,
# :caption_true => t('Admin'),
# :caption_false => t('Non-admin'),
# :field => :filter_admin)
#
# build_filter_info(admin_filter)
#
#== Date filter
#
#link:../images/date_filter_1.png
#link:../images/date_filter_2.png
#
#Date filters employ the plugin [http://code.google.com/p/calendardateselect/ calendardateselect]. If you need to change the stylesheets, edit <tt>public/stylesheets/calendar_date_select/ubiquo.css</tt>. To use the lateral filter on your listing, you have to indicate the caption and the start/end date field names:
#
# date_filter = render_filter(:date, {},
# :caption => t('creation'),
# :field => [:date_start, :date_end])
# ---
# date_filter = filter_info(:date, params,
# :caption => t('creation'),
# :field => [:date_start, :date_end])
#
# build_filter_info(date_filter)
#
#== Single Date filter
# Used to filter with only one date. It's like last filter but with just one date field:
#
# date_filter = render_filter(:single_date, {},
# :caption => t('creation'),
# :field => :filter_date)
# ---
# date_filter = filter_info(:single_date, params,
# :caption => t('creation'),
# :field => :filter_date)
#
# build_filter_info(date_filter)
module Ubiquo
module Extensions
module FiltersHelper
def lateral_filter(title, fields=[], &block)
content = capture(&block)
concat(render(:partial => "shared/ubiquo/lateral_filter",
:locals => {:title => title,
:content => content,
:fields => [fields].flatten}))
end
# Render a lateral filter
#
# filter_name (symbol): currently implemented: :date_filter, :string_filter, :select_filter
# url_for_options: route used by the form (string or hash)
# options_for_filter: options for a filter (see each *_filter_info helpers for details)
def render_filter(filter_name, url_for_options, options_for_filter = {})
if options_for_filter[:boolean]
# Build a mock :collection object (use OpenStruct for simplicity)
options_for_filter[:collection] = [
OpenStruct.new(:option_id => 0, :name => options_for_filter[:caption_false]),
OpenStruct.new(:option_id => 1, :name => options_for_filter[:caption_true]),
]
# Don't use :id as :id_field but, as :id is internally used by Ruby and will fail
options_for_filter.update(:id_field => :option_id, :name_field => :name)
end
partial_template = case filter_name.to_sym
when :links_or_select
if options_for_filter[:collection].size <= (options_for_filter[:max_size_for_links] || Ubiquo::Config.get(:max_size_for_links_filter))
"shared/ubiquo/filters/links_filter"
else
"shared/ubiquo/filters/select_filter"
end
else
"shared/ubiquo/filters/#{filter_name}_filter"
end
link = params.reject do |key, values|
filter_fields = [options_for_filter[:field]].flatten.map(&:to_s)
toremove = %w{commit controller action page} + filter_fields
toremove.include?(key)
end.to_hash
locals = {
:partial_locals => {
:options => options_for_filter,
:url_for_options => url_for_options,
:link => link,
},
:partial => partial_template,
}
render :partial => "shared/ubiquo/filters/filter", :locals => locals
end
# Return the informative string about a filter process
#
# filter_name (symbol). Currently implemented: :date_filter, :string_filter, :select_filter
# params: current 'params' controller object (hash)
# options_for_filter: specific options needed to build the filter string (hash)
#
# Return array [info_string, fields_used_by_this_filter]
def filter_info(filter_name, params, options_for_filter = {})
helper_method = "#{filter_name}_filter_info".to_sym
raise "Filter helper not found: #{helper_method}" unless self.respond_to?(helper_method, true)
info_string, fields0 = send(helper_method, params, options_for_filter)
return unless info_string && fields0
fields = fields0.flatten.uniq
[info_string, fields]
end
# Return the pretty filter info string
#
# info_and_fields: array of [info_string, fields_for_that_filter]
def build_filter_info(*info_and_fields)
fields, string = process_filter_info(*info_and_fields)
return unless fields
info = content_tag(:strong, string)
# Remove keys from applied filters and other unnecessary keys (commit, page, ...)
remove_fields = fields + [:commit, :page]
new_params = params.clone
remove_fields.each { |field| new_params[field] = nil }
link_text = "[" + t('ubiquo.filters.remove_all_filters', :count => fields.size) + "]"
message = [ t('ubiquo.filters.filtered_by', :field => info), link_to(link_text, new_params)]
content_tag(:p, message.join(" "), :class => 'search_info')
end
# Return the pretty filter info string
#
# info_and_fields: array of [info_string, fields_for_that_filter]
def process_filter_info(*info_and_fields)
info_and_fields.compact!
return if info_and_fields.empty?
# unzip pairs of [text_info, fields_array]
strings, fields0 = info_and_fields[0].zip(*info_and_fields[1..-1])
fields = fields0.flatten.uniq
[fields, string_enumeration(strings)]
end
private
# Return info to show a informative string about a date search
#
# Return an array [text_info, array_of_fields_used_on_that_filter]
def single_date_filter_info(filters, options_for_filter)
date_field = options_for_filter[:field].to_sym
date = filters[date_field]
return unless date
info = t('ubiquo.filters.filter_simple_date', :date => date)
info = options_for_filter[:caption] + " " + info if options_for_filter[:caption]
[info, [date_field]]
end
# Return info to show a informative string about a date search
#
# Return an array [text_info, array_of_fields_used_on_that_filter]
def date_filter_info(filters, options_for_filter)
date_start_field, date_end_field = options_for_filter[:field].map(&:to_sym)
process_date = Proc.new do |key|
filters[key] if !filters[key].blank? #&& is_valid_date?(filters[key])
end
date_start = process_date.call(date_start_field)
date_end = process_date.call(date_end_field)
return unless date_start or date_end
info = if date_start and date_end
t('ubiquo.filters.filter_between', :date_start => date_start, :date_end => date_end)
elsif date_start
t('ubiquo.filters.filter_from', :date_start => date_start)
elsif date_end
t('ubiquo.filters.filter_until', :date_end => date_end)
end
info2 = options_for_filter[:caption] + " " + info if options_for_filter[:caption]
[info2, [date_start_field, date_end_field]]
end
# Return info to show a informative string about a string search
#
# filters: hash containing
# :filter_string
#
# Return an array [text_info, array_of_fields_used_on_that_filter]
def string_filter_info(filters, options_for_filter)
field = options_for_filter[:field].to_s
string = !filters[field].blank? && filters[field]
return unless string
info = options_for_filter[:caption].blank? ?
t('ubiquo.filters.filter_text', :string => string) :
"#{options_for_filter[:caption]} '#{string}'"
[info, [field]]
end
# Return info to show a informative string about a selection filter
#
# filters: hash containing filter keys
#
# options_for_filters: Default select (non-boolean)
# field: field name (symbol)
# id_field: attribute of the record to search the field value (symbol)
# name_field: field of the record to be shown (symbol)
# model: model name where the search has been made (symbol or string)
#
# options_for_filters Boolean selection
# boolean: true
# caption_true: message when selection is true
# caption_false: message when selection is false
#
# Return an array [text_info, array_of_fields_used_on_that_filter]
def select_filter_info(filters, options_for_filter)
field_key = options_for_filter[:field] || raise("options_for_filter: missing 'field' key")
field = !filters[field_key].blank? && filters[field_key]
return unless field
name = if options_for_filter[:boolean]
caption_true = options_for_filter[:caption_true] || raise("options_for_filter: missing 'caption_true' key")
caption_false = options_for_filter[:caption_false] || raise("options_for_filter: missing 'caption_false' key")
(filters[field_key] == "1") ? caption_true : caption_false
else
if options_for_filter[:model]
id_field = options_for_filter[:id_field] || raise("options_for_filter: missing 'id_field' key")
model = options_for_filter[:model].to_s.classify.constantize
record = model.find(:first, :conditions => {id_field => filters[field_key]})
return unless record
name_field = options_for_filter[:name_field] || raise("options_for_filter: missing 'name_field' key")
record.send(name_field)
elsif options_for_filter[:collection]
value = options_for_filter[:collection].find do |value|
value.send(options_for_filter[:id_field]).to_s == filters[field_key]
end.send(options_for_filter[:name_field]) rescue filters[field_key]
else
prefix = options_for_filter[:translate_prefix]
prefix ? t("#{prefix}.filters.#{filters[field_key]}") : filters[field_key]
end
end
info = "#{options_for_filter[:caption]} '#{name}'"
[info, [field_key]]
end
# Return info to show a informative string about a link filter
def links_filter_info(filters, options_for_filter)
select_filter_info(filters, options_for_filter)
end
# Return info to show a informative string about a links_or_select filter
def links_or_select_filter_info(filters, options_for_filter)
select_filter_info(filters, options_for_filter)
end
# From an array of strings, return a human-language enumeration
def string_enumeration(strings)
strings.reject(&:empty?).to_sentence()
end
def build_hidden_field_tags(hash)
hash.map do |field, value|
if value.is_a? Array
value.map {|val| hidden_field_tag field+"[]", val}.flatten
else
hidden_field_tag field, value, :id => nil
end
end.join("\n")
end
end
end
end
| true |
cc3abed20852d79e37d7c3c4e19e8b1681d190e2 | Ruby | L-rodrigue/6_exo_ruby | /exo_4.rb | UTF-8 | 2,202 | 3.71875 | 4 | [] | no_license | # ## exo 4 - Calcul de la moyenne
# Un instituteur souhaite pouvoir aller plus vite en saisissant
# les notes de ces élèves et en obtenir le nombre est la moyenne pour le trimestre.
# Pour cela, Albert qui a suivi une formation dans l’informatique,
# il y a fort longtemps, lui a proposé de l’aider. Malheureusement,
# les cours d’Albert sont un peu loin et il vous demande votre aide.
# Donc, comme vous êtes de bonnes personnes, vous lui avez tou.te.s dit ouI
# Le script devra permettre de saisir note par note,
# une fois les notes saisies on stoppera la saisie avec le mot STOP
# Afin de ne pas obtenir d’erreur, on s’assure que _les saisies soient bien des chiffres_.
# Un fois le mot « STOP » saisie,
# Le programme répondra de lui même qu’il y a eu X notes de saisies et que la moyenne est de Y / 20
# 1ere variante (optionnelle)
# À la saisie des notes, au lieu de saisir note par note,
# on saisie toutes les notes sur une seule saisie séparée par des espaces,
# la validation vaudrait l’envoi des note.
# 2eme variante (optonnelle)
# Au lieu de faire une moyenne sur 20 on pourrait imaginer faire une moyenne sur 10 20 30
# mais aussi permettre de saisir des notes non plus sur 20 mais elles aussi sur 10 20 30,
# sasvhant que bien entendu, il est possible de saisir en même temps des notes sur 10 et des notes sur 20.
# Je defini ma fonction
def NoteTable()
# message pour l'utilisateur
puts 'Saisissez les notes et finir avec le mot stop'
# variable qui recevras les notes de la variable note
notes = []
# Je defini une variable stop
stop = false
while !stop
# Je defini une variable pour saisir les notes
note = gets.chomp
# Si le mot stop est saisie le tableau ce termine
if note == "stop"
stop = true
# Sinon les notes saisies dans la variable note continue a rentrer dans le tableau de la variable notes
else
notes.push(note.to_i)
end
end
# il affiche le nombre de note saisie et la moyenne
puts "il y a eu #{notes.length()} notes de saisies et que la moyenne est de #{notes.sum/notes.length()} / 20"
end
NoteTable() | true |
65b1bf18df2abe20e30b7981ee32e9c86d88cce1 | Ruby | itggot-erik-jergeus/Slutprojekt | /creation-slutprojekt-sinatra/sinatra-skeleton-master/models/activity.rb | UTF-8 | 1,211 | 2.515625 | 3 | [] | no_license | class Activity
include DataMapper::Resource
property :id, Serial
property :title, String, required: true
property :type, String, required: true
property :subject, String
property :planning, String
property :time, Integer
property :date, DateTime, required: true
property :hidden, Boolean, required: true
property :parent, Boolean, required: true
def plan(plan_length:)
due = self.date
time = self.time
# Start of the intervall
bed_time = (User.get(self.user_id)).bed_time - plan_length*60
amount = 0
while time > 0
amount += 1
time -= plan_length
end
# Amount of days left to due date.
left = (due - Date.today)
intervalls = left/(amount+1)
day = 1
while amount > 0
next_training = Date.today+intervalls*day
date = DateTime.new(next_training.year,next_training.month,next_training.day,bed_time.hour,bed_time.min)
Activity.create(title: "#{self.title} Training", type: "Training", subject: self.subject,
date: date, planning: nil,
hidden: self.hidden, parent: self.parent, user_id: self.user_id)
day += 1
amount -= 1
end
end
belongs_to :user
end | true |
b34d66def8c85d39c1b6b9cb2582163cfdefb08f | Ruby | theghymp/courses | /algo/dijkstra.rb | UTF-8 | 1,330 | 3.21875 | 3 | [] | no_license | # Encoding: utf-8
class DistanceGraph
attr_accessor :vertices
def initialize(filename)
@vertices = {}
File.new(filename).readlines.each do |line|
line = line.chop
line_array = line.split("\t")
vertex = line_array[0].to_i
edges = []
(1..(line_array.size - 1)).each do |i|
edge = line_array[i].split(',')
edges << { connected_vertex: edge[0].to_i, distance: edge[1].to_i }
end
@vertices[vertex] = edges
end
end
def find_shortest_paths(starting_vertex_id)
shortest_paths = {}
shortest_paths[starting_vertex_id] = 0
(@vertices.size - 1).times do |v|
low_greedy_score = nil
low_greedy_vertex = nil
shortest_paths.each do |vertex_id, shortest_path|
edges = @vertices[vertex_id]
edges.each do |edge|
connected_vertex = edge[:connected_vertex]
unless shortest_paths.include? connected_vertex
distance = edge[:distance]
if low_greedy_score.nil? || shortest_path + distance < low_greedy_score
low_greedy_score = shortest_path + distance
low_greedy_vertex = connected_vertex
end
end
end
end
shortest_paths[low_greedy_vertex] = low_greedy_score
end
shortest_paths
end
end
| true |
48007c68aa2f5049f4754e42f3f0b234710f93a7 | Ruby | quarkgluant/rubymonk | /Ruby Primer - Ascent/Handling and Raising - Inline Rescue.rb | UTF-8 | 268 | 2.6875 | 3 | [] | no_license | EXAMPLE_SECRETS = ["het", "keca", "si", nil, "iel"]
def decode(jumble)
secret = jumble.split("").rotate(3).join("")
announce(secret)
secret
end
def decode_all(tab_chaines)
tab_chaines.each{|tab_chaine| decode(tab_chaine)} rescue "it's okay, little buddy."
end | true |
eba854f4919080367d822b9ed30901bf77a02ffb | Ruby | ahnlak-dragonruby/LRtanks | /mygame/app/player.rb | UTF-8 | 2,464 | 3.359375 | 3 | [] | no_license | # player.rb - part of LRTank
#
# Defines the player; knows how to render her and handles all actions
class Player
# Attributes
attr_accessor :player_x, :player_y, :angle
# Some useful constants
PLAYER_WIDTH=9
PLAYER_HEIGHT=9
PLAYER_OFFSET_X=4
PLAYER_OFFSET_Y=4
# Initialisor
def initialize args
# Spawn ourselves in the middle of the world
@player_x = World::WORLD_WIDTH / 2
@player_y = World::WORLD_HEIGHT / 2
@angle = 0
@momentum_x = 0.0
@momentum_y = 0.0
@bullet_weight = 0.2
end
# Update handler
def update args
# Deal with any user input - turning first
if args.inputs.keyboard.key_down.left || args.inputs.keyboard.key_down.a
@angle = ( @angle == 360 - World::ANGLE_STEPS ) ? 0 : @angle + World::ANGLE_STEPS
end
if args.inputs.keyboard.key_down.right || args.inputs.keyboard.key_down.d
@angle = ( @angle == 0 ) ? 360 - World::ANGLE_STEPS : @angle - World::ANGLE_STEPS
end
# And then firing, in the direction we're facing
if args.inputs.keyboard.key_down.space || args.inputs.keyboard.key_down.w
# Two things happen we we shoot. First, a bullet is (obviously) spawned
args.state.bullets << Bullet.new(
args,
@angle,
@player_x + @angle.vector_x(2),
@player_y + @angle.vector_y(2),
@angle.vector_x,
@angle.vector_y
)
# And then we apply recoil in the other direction, bumping up the momentum
# along the reverse vector
@momentum_x -= @angle.vector_x @bullet_weight
@momentum_y -= @angle.vector_y @bullet_weight
end
# Ask the world to update the momentum, taking the player's position into
# consideration.
@momentum_x = args.state.world.check_x @player_x, @momentum_x
@momentum_y = args.state.world.check_y @player_y, @momentum_y
# Apply any resulting momentum
@player_x += @momentum_x
@player_y += @momentum_y
# And update the camera to reflect it
args.state.world.set_camera @player_x, @player_y
end
# Render handler
def render args
# Translate our location from world to camera co-ordinates
my_x, my_y = args.state.world.world_to_camera @player_x, @player_y
args.lowrez.sprites << {
x: my_x - PLAYER_OFFSET_X,
y: my_y - PLAYER_OFFSET_Y,
w: PLAYER_WIDTH,
h: PLAYER_HEIGHT,
path: "sprites/player-#{args.state.world.direction(@angle)}.png",
}
end
end | true |
4971d49cbd0fa23ccc4685bfb7c1b82935177b52 | Ruby | zpixley/Portfolio | /Software Quality Assurance (Ruby)/D4/verifier_test.rb | UTF-8 | 5,847 | 2.671875 | 3 | [] | no_license | require 'simplecov'
SimpleCov.start
require 'set'
require 'minitest/autorun'
require_relative 'block'
require_relative 'wallet'
require_relative 'helper'
# Class VerifierTest contains all the tests to verify functionaility of Verifier.rb
class VerifierTest < Minitest::Test
# Create new instance of the helper class to use for testing
def setup
@testing = Helper.new
end
# Testing to see if there are the correct amount of parts to the block
# EXPECTING RETURN VALUE OF 1
def test_check_format_1
@testing.curr_str = '0|0SYSTEM>569274(100)|1553184699.650330000|288d'
value = @testing.check_format
assert_equal(1, value)
end
# Testing invlaid transaction format
# EXPECTING RETURN VALUE OF 3
def test_check_format_2
@testing.curr_str = '0|0|SYSTEM>569274(100)::|1553184699.650330000|288d'
value = @testing.check_format
assert_equal(3, value)
end
# Testing invlaid timestamp format
# EXPECTING RETURN VALUE OF 5
def test_check_format_3
@testing.curr_str = '0|0|SYSTEM>569274(100)|1553184699650330000|288d'
value = @testing.check_format
assert_equal(5, value)
end
# Testing to see if the hash values are formatted incorrectly
# EXPECTED RETURN VALUE OF 9
def test_check_format_4
@testing.curr_str = '0|0|SYSTEM>569274(100)|1553184699.650330000|2888d'
value = @testing.check_format
assert_equal(9, value)
end
#---------------TESTS FOR parse_block----------------------------------------------
# Testing to see what happens with incorrect line number
# EXPECTING validity VALUE OF 2
def test_parse_block_1
@testing.curr_str = '0|0|SYSTEM>569274(100)|1553184699.650330000|288d'
@testing.p_s = 0
@testing.p_ns = 0
@testing.p_h = '0'
@testing.curr_line = 1
value = @testing.parse_block
assert_equal(2, value.validity)
end
# Testing to see if the previos hash does not match block's previous hash
# EXPECTING A validity VALUE OF 8
def test_parse_block_2
@testing.curr_str = '9|7777|402207>794343(10):402207>780971(13):794343>236340(16)
:717802>717802(1):SYSTEM>689881(100)|1553184699.691433000|7ad7'
@testing.p_s = 0
@testing.p_ns = 0
@testing.p_h = 'a91'
@testing.curr_line = 9
value = @testing.parse_block
assert_equal(7, value.validity)
end
# Testing to see if the previous timestamp is less than the present timestamp
# EXPECTING validity value of 6
def test_parse_block_3
@testing.curr_str = '9|a91|402207>794343(10):402207>780971(13):794343>236340(16)
:717802>717802(1):SYSTEM>689881(100)|1553184699.0|9852'
@testing.p_s = 1_553_184_699
@testing.p_ns = 685_386_000
@testing.p_h = 'a91'
@testing.curr_line = 9
value = @testing.parse_block
assert_equal(6, value.validity)
end
# Testing to see if the calculated hash matched the block hash
# EXPECTING THE validity VALUE TO BE 7
def test_parse_block_4
@testing.curr_str = '9|a91|402207>794343(10):402207>780971(13):794343>236340(16)
:717802>717802(1):SYSTEM>689881(100)|1553184699.691433000|abcd'
@testing.p_s = 1_553_184_699
@testing.p_ns = 685_386_000
@testing.p_h = 'a91'
@testing.curr_line = 9
value = @testing.parse_block
assert_equal(7, value.validity)
end
#------------------Tests for Calc_hash-----------------------------------------------------------------
# Testing to see of the hash value being return for the block is correct
# Expecting
def test_calc_hash_1
value = @testing.calc_hash('0|0|SYSTEM>569274(100)|1553184699.650330000')
assert_equal('288d', value)
end
#------------------Tests for complete_transaction ------------------------------------------------
# Testing to see if the transaction is formatted incorrectly
# Expecting a return value of 1
def test_complete_transaction_1
@negs = []
value = @testing.complete_transaction('SYSTEM569274(100)')
assert_equal(1, value)
end
# Testing to see if the addresses are validly formatted
# Expecting the return value to be 1
def test_complete_transaction_2
@negs = []
value = @testing.complete_transaction('SYSTEM>5569274(100)')
assert_equal(1, value)
end
#-------------------Tests for verify blockchain Errors-----------------------------------------------------------
def test_verify_blockchain_1
value = @testing.verify_blockchain(File.read('invalid_format.txt').split("\n"))
assert_equal(3, value)
end
def test_verify_blockchain_2
value = @testing.verify_blockchain(File.read('bad_number.txt').split("\n"))
assert_equal(2, value)
end
def test_verify_blockchain_3
value = @testing.verify_blockchain(File.read('bad_prev_hash.txt').split("\n"))
assert_equal(8, value)
end
def test_verify_blockchain_4
value = @testing.verify_blockchain(File.read('bad_block_hash.txt').split("\n"))
assert_equal(7, value)
end
def test_verify_blockchain_5
value = @testing.verify_blockchain(File.read('bad_timestamp.txt').split("\n"))
assert_equal(6, value)
end
def test_verify_blockchain_6
value = @testing.verify_blockchain(File.read('invalid_transaction.txt').split("\n"))
assert_equal(4, value)
end
def test_verify_blockchain_7
value = @testing.verify_blockchain(File.read('sample.txt').split("\n"))
assert_equal(0, value)
end
def test_verify_blockchain_8
value = @testing.verify_blockchain(File.read('bad_block.txt').split("\n"))
assert_equal(1, value)
end
def test_verify_blockchain_9
value = @testing.verify_blockchain(File.read('no_timestamp.txt').split("\n"))
assert_equal(5, value)
end
def test_verify_blockchain_10
value = @testing.verify_blockchain(File.read('invalid_hash_length.txt').split("\n"))
assert_equal(9, value)
end
end
| true |
64542295469b2a2b1b080354b0dc71305729bdd3 | Ruby | tijn/virginity | /benchmark/string_benchmark.rb | UTF-8 | 239 | 2.515625 | 3 | [
"MIT"
] | permissive | # encoding: UTF-8
# require "#{File.dirname(__FILE__)}/benchmark_helper"
require 'rubygems'
require "memprof"
text = <<end_text
fòó
bär
baß
end_text
Memprof.start
text.each_char { |ch| ch }
puts Memprof.stats
result = Memprof.stop
| true |
927008cf494a342502c84d18a8eb48b6efa2045a | Ruby | ethanhust/devs | /lib/devs/behavior.rb | UTF-8 | 6,392 | 2.984375 | 3 | [
"MIT"
] | permissive | module DEVS
# The {Behavior} mixin provides models with several behavior methods
# in line to the DEVS functions definition (δext, δint, δcon, λ and ta) and
# the DEVS variables (σ, e, t).
# The class must call {#initialize_behavior} during its initialization in
# order to allocate instance variables.
module Behavior
extend ActiveSupport::Concern
include AttrState
included do
attr_state :elapsed, default: 0.0
attr_state :time, default: 0
attr_state :sigma, default: INFINITY
end
attr_accessor :elapsed, :time, :sigma, :next_activation
alias_method :next_activation, :sigma
# @!attribute sigma
# Sigma is a convenient variable introduced to simplify modeling phase
# and represent the next activation time (see {#time_advance})
# @return [Numeric] Returns the sigma (σ) value
# @!attribute elapsed
# This attribute is updated along simulation. It represents the elapsed
# time since the last transition.
# @return [Numeric] Returns the elapsed time since the last transition
# @!attribute time
# This attribute is updated along with simulation clock and
# represent the last simulation time at which this model
# was activated. Its default assigned value is {INFINITY}.
# @return [Numeric] Returns the last activation time
# @!group DEVS functions
# The external transition function (δext)
#
# @abstract Override this method to implement the appropriate behavior of
# your model or define it with {self.external_transition}
# @see self.external_transition
# @param messages [Hash<Port,Object>] the messages generated by other
# {Model}s, indexed by input {Port}s.
# @example
# def external_transition(messages)
# messages.each { |port, value|
# puts "#{port} => #{value}"
# }
#
# self.sigma = 0
# end
# @return [void]
def external_transition(messages); end
# Internal transition function (δint), called when the model should be
# activated, e.g when {#elapsed} reaches {#time_advance}
#
# @abstract Override this method to implement the appropriate behavior of
# your model or define it with {self.internal_transition}
# @see self.internal_transition
# @example
# def internal_transition; self.sigma = DEVS::INFINITY; end
# @return [void]
def internal_transition; end
# This is the default definition of the confluent transition. Here the
# internal transition is allowed to occur and this is followed by the
# effect of the external transition on the resulting state.
#
# Override this method to obtain a different behavior. For example, the
# opposite order of effects (external transition before internal
# transition). Of course you can override without reference to the other
# transitions.
#
# @see AtomicModel.reverse_confluent_transition!
# @todo see elapsed time reset
def confluent_transition(messages)
internal_transition
external_transition(messages)
end
# Time advance function (ta), called after each transition to give a
# chance to <tt>self</tt> to be active. By default returns {#sigma}
#
# @note Override this method to implement the appropriate behavior of
# your model or define it with {self.time_advance}
# @see self.time_advance
# @example
# def time_advance; self.sigma; end
# @return [Numeric] the time to wait before the model will be activated
def time_advance
@sigma
end
# The output function (λ)
#
# @abstract Override this method to implement the appropriate behavior of
# your model or define it with {AtomicModel.output}
# @see AtomicModel.output
# @example
# def output
# post(@some_value, @output_ports[:output])
# end
# @return [void]
def output; end
# @!endgroup
module ClassMethods
# @!group Class level DEVS functions
# Defines the external transition function (δext) using the given block
# as body.
#
# @see #external_transition
# @example
# external_transition do |messages|
# messages.each { |msg| }
# puts "#{msg.port} => #{msg.payload}"
# end
#
# self.sigma = 0
# end
# @return [void]
def external_transition(&block)
define_method(:external_transition, &block) if block
end
# Defines the internal transition function (δint) using the given block
# as body.
#
# @see #internal_transition
# @example
# internal_transition { self.sigma = DEVS::INFINITY }
# @return [void]
def internal_transition(&block)
define_method(:internal_transition, &block) if block
end
# Defines the confluent transition function (δcon) using the given block
# as body.
#
# @see #confluent_transition
# @example
# confluent_transition do |messages|
# internal_transition
# external_transition(messages)
# end
# @return [void]
def confluent_transition(&block)
define_method(:confluent_transition, &block) if block
end
# Defines the opposite behavior of the default confluent transition
# function (δcon).
#
# @see #confluent_transition
# @example
# class MyModel < AtomicModel
# reverse_confluent_transition!
# # ...
# end
def reverse_confluent_transition!
define_method(:confluent_transition) do |messages|
external_transition(messages)
internal_transition
end
end
# Defines the time advance function (ta) using the given block as body.
#
# @see #time_advance
# @example
# time_advance { self.sigma }
# @return [void]
def time_advance(&block)
define_method(:time_advance, &block) if block
end
# Defines the output function (λ) using the given block as body.
#
# @see #output
# @example
# output do
# post(@some_value, output_ports.first)
# end
# @return [void]
def output(&block)
define_method(:output, &block) if block
end
# @!endgroup
end
end
end
| true |
f91db8988e12309cdc8aecd898d85a719b4a1aff | Ruby | knikadass/array-methods-lab-onl01-seng-pt-070620 | /lib/array_methods.rb | UTF-8 | 529 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_include(array, element)
array.include?(element)
end
def using_sort(array)
famous_dogs = ["wow", "I", "arrays!"]
famous_dogs.sort
end
def using_reverse(array)
famous_dogs = ["wow", "I", "arrays!"]
famous_dogs.reverse
end
def using_first(array)
famous_dogs = ["wow", "I", "arrays!"]
famous_dogs.first
end
def using_last(array)
famous_dogs = ["wow", "I", "arrays!"]
famous_dogs.last
end
def using_size(array)
famous_dogs = ["wow", "I", "arrays!", "Simba", "Nala", "Bentley"]
famous_dogs.size
end
| true |
9c1f921e754a348efa39a77ce678a38efd43a4dc | Ruby | ehundt/gartenkalender | /app/models/season_old.rb | UTF-8 | 1,282 | 2.609375 | 3 | [] | no_license | class SeasonOld < ApplicationRecord
PHAENOLOG_SEASONS = [ :vorfrühling, :erstfrühling, :vollfrühling,
:frühsommer, :hochsommer, :spätsommer,
:frühherbst, :vollherbst, :spätherbst,
:winter ]
enum season: PHAENOLOG_SEASONS
REGIONS = [ :deutschland ]
enum region: REGIONS
def self.seasons_with_mean_dates
# for a good forecast for the next years,
# we use the oldest entry 1990 which is actually a mean value for the years
# between 1961 and 1990
# region: 0 == Germany
output = {}
seasons = Season.where(region: 0).group(:season).order(:season).limit(Task.starts.length).select(:season, "max(start) AS start", "max(stop) AS stop")
seasons.each do |season|
output[season.season] = season
end
output
end
def self.current
self.season_for(Date.today)
end
def self.season_for(date, region=0)
season = self.where('start <= ? and stop >= ?', date, date).where(region: region).first
if season.nil?
old_date = Date.new(1990, date.month, date.day)
season = self.where('start <= ? and stop >= ?', old_date, old_date).where(region: region).first
end
season
end
def season_index
Season.seasons[self.season]
end
end
| true |
707847ad9cf6bafa9fce673ecc13f1647d692cbf | Ruby | niklas/partial_dependencies | /lib/partial_dependencies/graph.rb | UTF-8 | 2,950 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'stringio'
module PartialDependencies
class Graph
def initialize(base_path = File.expand_path(File.join(Rails.root,"app", "views")))
@base_path = base_path
end
def base_path=(base_path)
@base_path = base_path
@views = nil
end
def dot(type = "png", view_set = "used", fn = "partial_dependencies")
prog = view_set == "unused" ? "neato" : "dot"
IO.popen("#{prog} -T#{type} -o #{fn}-#{view_set}.#{type}", "w") do |pipe|
pipe.puts dot_input(view_set)
end
end
private
def dot_input(view_set)
possible_view_sets = ["used", "unused", "all"]
unless possible_view_sets.include?(view_set)
raise "Wrong view_set. Only #{possible_view_sets.inspect} possible. Was #{view_set.inspect}"
end
str = StringIO.new
parse_files
str.puts "digraph partial_dependencies {"
name_to_node = {}
instance_variable_get("@#{view_set}_views").each_with_index do |view, index|
str.puts "Node#{index} [label=\"#{view}\"]"
name_to_node[view] = "Node#{index}"
end
if (["used", "all"].include?(view_set))
@edges.each do |view, partials|
partials.each do |partial|
str.puts "#{name_to_node[view]}->#{name_to_node[partial]}"
end
end
end
str.puts "}"
str.rewind
return str.read
end
def parse_files
@edges = Hash.new {|hash,key| hash[key] = []}
@used_views = {}
@all_views = []
views.each do |view|
@all_views << pwfe(view)
File.open("#{view[:path]}") do |contents|
contents.each do |line|
if partial_name = scan_line(line)
found_render partial_name, view
end
end
end
end
@used_views = @used_views.keys
@unused_views = @all_views - @used_views
end
def scan_line(line)
# Modified
# Fixed the line below to allow spaces between the opening ( and "partial" text.
# Also modified to allow Rails 3 symbol syntax.
if line =~ /=\s*render\s*\(?\s*((?::partial\s*=>)|(?:partial:))\s*["'](.*?)["']/
return $2
elsif line =~ /=\s*render\s*\s*["'](.*?)["']/
return $1
end
end
def found_render(partial_name, view)
if partial_name.index("/")
partial_name = partial_name.gsub(/\/([^\/]*)$/, "/_\\1")
else
partial_name = "#{File.dirname(view[:name])}/_#{partial_name}"
end
@edges[pwfe(view)] << partial_name
@used_views[pwfe(view)] = true
@used_views[partial_name] = true
end
def pwfe(view)
view[:name].split(".")[0]
end
def views
return @views if @views
@views = Dir.glob(File.join(@base_path, "**", "*")).reject do |vp|
File.directory?(vp)
end.map {|vp| {:name => vp.gsub(@base_path, "").gsub(/^\//,''), :path => vp}}
end
end
end
| true |
175c2245311868dacd5ea7f2168d4b8759dcb7af | Ruby | SmithKirk/takeaway_challenge | /lib/menu.rb | UTF-8 | 537 | 3.859375 | 4 | [] | no_license | class Menu
attr_accessor :dishes
def initialize(dishes)
@dishes = dishes
end
def add_dish(dish, price)
@dishes[dish.to_sym] = price
end
def remove_dish(dish)
raise 'Error: That dish is not on the menu' unless has_dish?(dish)
@dishes.delete(dish.to_sym)
end
def print_menu
@dishes.map do |title, price|
"%s £%.2f" % [title.to_s.capitalize, price]
end.join(", ")
end
def has_dish?(dish)
@dishes.has_key?(dish.to_sym)
end
def price(dish)
@dishes[dish.to_sym]
end
end
| true |
378dd4cffc2b59f6943ec4f6921617b16ea1e419 | Ruby | ljonesfl/iprogrammer | /ep7_hw_oop/ruby/oop.rb | UTF-8 | 349 | 3.3125 | 3 | [] | no_license |
class Car
def initialize
puts "Car created."
end
def openAshtray
puts "Ashtray opened."
end
end
class SpyCar < Car
def initialize
puts "SpyCar created."
end
def openAshtray
method(:openAshtray).super_method.call
puts "Ejector seat deployed."
end
end
car = Car.new()
spyCar = SpyCar.new()
car.openAshtray
spyCar.openAshtray
| true |
9c3773065d8704e61b4c05ff9d16323559081c77 | Ruby | Sambi85/ruby-enumerables-cartoon-collections-lab-part-2-nyc01-seng-ft-060120 | /cartoon_collections.rb | UTF-8 | 487 | 3.3125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def square_array(array)
array.collect do |num| num * num end
end
def summon_captain_planet(planeteer_calls)
planeteer_calls.map do |names| "#{names.capitalize}"+"!" end
end
def long_planeteer_calls(planeteer_calls)
planeteer_calls.any? do |string| string.length > 4
end
end
def find_valid_calls(planeteer_calls)
valid_calls = ["Earth!", "Wind!", "Fire!", "Water!", "Heart!"]
planeteer_calls.find do |call|
valid_calls.find do |targets| call == targets end
end
end | true |
26ec655e9c32d3776dd114a703ed58035e91df69 | Ruby | tenkoma/object-brain | /ch3/3.5/bucho.rb | UTF-8 | 205 | 3.078125 | 3 | [] | no_license | require_relative 'syain'
class Bucho < Syain
def standup
puts '部長がだるそうに起立しました。'
end
def salary
puts "私の給料は#{@basic_salary * 3}円です。"
end
end
| true |
4cbbd56634b8248a12b327ee0d36adae72d8b88c | Ruby | sonialin/launchschool | /Exercises/101-109 Small Problems/Easy 8/08_double_char_pt2.rb | UTF-8 | 400 | 3.5625 | 4 | [] | no_license | def double_consonants(str)
new_str = ""
str.chars.each do |char|
if /[a-zA-Z&&[^aeiouAEIOU]]/.match(char)
new_str << char * 2
else
new_str << char
end
end
new_str
end
puts double_consonants('String') == "SSttrrinngg"
puts double_consonants("Hello-World!") == "HHellllo-WWorrlldd!"
puts double_consonants("July 4th") == "JJullyy 4tthh"
puts double_consonants('') == "" | true |
71622637f9465d5f0dabb6390dfef5a8feeeb2ca | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/raindrops/132631b3e8bb4b7ab6c22cfbb837573c.rb | UTF-8 | 439 | 3.609375 | 4 | [] | no_license | require 'prime'
class Raindrops
def convert number
@factors = number.prime_division
return number.to_s unless factors_contain?(3) || factors_contain?(5) || factors_contain?(7)
drops = ""
drops << 'Pling' if factors_contain? 3
drops << 'Plang' if factors_contain? 5
drops << 'Plong' if factors_contain? 7
drops
end
def factors_contain? number
@factors.any? { |factor| factor[0] == number }
end
end
| true |
e0c8ac8506fc4049b8507721bf32aec7df91fbce | Ruby | papapabi/project-euler | /29.rb | UTF-8 | 489 | 3.421875 | 3 | [] | no_license | require 'benchmark'
# Finds all distinct terms in the expression a^b given
# inclusive range [a, b] where a and b are both at least 2.
def distinct_terms(a:, b:)
ar = []
(2..a).each do |i|
(2..b).each do |j|
ar << i ** j
end
end
ar.uniq
end
time = Benchmark.measure do
puts 'The cardinality of the distinct terms generated by a^b '\
"for a in [2, 100] and b in [2, 100] is #{distinct_terms(a: 100, b: 100).length}"
end
puts "Time elapsed (in seconds): #{time}"
| true |
ba76e8a8fed02cc14a171ec69ad27eb7515bbe6b | Ruby | jayshenk/algorithms | /binary_tree_level_order_traversal.rb | UTF-8 | 721 | 3.859375 | 4 | [] | no_license | # Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
#
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its level order traversal as:
# [
# [3],
# [9,20],
# [15,7]
# ]
def level_order(root)
return [] if root.nil?
result = []
queue = [root]
current_level = 0
until queue.empty?
queue.size.times do
node = queue.shift
result[current_level] = [] unless result[current_level]
result[current_level] << node.val
queue.push(node.left) if node.left
queue.push(node.right) if node.right
end
current_level += 1
end
result
end
| true |
409dd05e7c2d5e853d687091d743bf9043604b57 | Ruby | Aetherus/phantom | /lib/phantom/fork_error.rb | UTF-8 | 214 | 2.5625 | 3 | [
"MIT"
] | permissive | module Phantom
class ForkError < Exception
attr_reader :pid, :pid_file
def initialize(message, pid_file)
super(message)
@pid_file = pid_file
@pid = File.read @pid_file
end
end
end | true |
ccdd6e6df4cbf8de67d731c24ca0d14e288f118a | Ruby | dldinternet/regexp-examples | /lib/regexp-examples/repeaters.rb | UTF-8 | 1,709 | 2.859375 | 3 | [
"MIT"
] | permissive | module RegexpExamples
class BaseRepeater
attr_reader :group
def initialize(group)
@group = group
end
def result(min_repeats, max_repeats)
group_results = @group.result[0 .. RegexpExamples.MaxGroupResults-1]
results = []
min_repeats.upto(max_repeats) do |repeats|
if repeats.zero?
results << [ GroupResult.new('') ]
else
results << RegexpExamples.permutations_of_strings(
[group_results] * repeats
)
end
end
results.flatten.uniq
end
end
class OneTimeRepeater < BaseRepeater
def initialize(group)
super
end
def result
super(1, 1)
end
end
class StarRepeater < BaseRepeater
def initialize(group)
super
end
def result
super(0, RegexpExamples.MaxRepeaterVariance)
end
end
class PlusRepeater < BaseRepeater
def initialize(group)
super
end
def result
super(1, RegexpExamples.MaxRepeaterVariance + 1)
end
end
class QuestionMarkRepeater < BaseRepeater
def initialize(group)
super
end
def result
super(0, 1)
end
end
class RangeRepeater < BaseRepeater
def initialize(group, min, has_comma, max)
super(group)
@min = min || 0
if max
# Prevent huge number of results in case of e.g. /.{1,100}/.examples
@max = smallest(max, @min + RegexpExamples.MaxRepeaterVariance)
elsif has_comma
@max = @min + RegexpExamples.MaxRepeaterVariance
else
@max = @min
end
end
def result
super(@min, @max)
end
private
def smallest(x, y)
(x < y) ? x : y
end
end
end
| true |
de1773195d73987e9dc857566c9674eec3b00e23 | Ruby | samnissen/adomain | /spec/adomain_spec.rb | UTF-8 | 4,767 | 2.53125 | 3 | [
"MIT"
] | permissive | RSpec.describe Adomain do
it "has a version number" do
expect(Adomain::VERSION).not_to be nil
end
describe "#[]" do
context "subdomains the string by default" do
subject { Adomain["http://abc.google.com"] }
it { is_expected.to eq "abc.google.com" }
end
context "domains when no subdomain is present" do
subject { Adomain["http://google.com"] }
it { is_expected.to eq "google.com" }
end
context "domains the string with www subdomain" do
subject { Adomain["http://www.google.com"] }
it { is_expected.to eq "google.com" }
end
context "domains the string when first boolean is true" do
subject { Adomain["http://abc.google.com", true] }
it { is_expected.to eq "google.com" }
end
context "subdomain_www the string when both booleans false, true" do
subject { Adomain["http://www.google.com", false, true] }
it { is_expected.to eq "www.google.com" }
end
end
describe "#domain" do
context "string represents a URL" do
subject { Adomain.domain "http://www.name.com" }
it { is_expected.to eq "name.com" }
end
context "string represents an invalid URL" do
it "should return nil for partial urls" do
expect( Adomain.domain "http://aloha" ).to be_nil
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.domain "::::::::::" ).to be_nil
end
it "should return nil for Addressable-breaking strings" do
expect{ Adomain.domain "{}" }.not_to raise_error
expect( Adomain.domain "{}" ).to be_nil
end
end
end
describe "#subdomain" do
context "string represents a URL" do
subject { Adomain.subdomain "http://sam.name.com" }
it { is_expected.to eq "sam.name.com" }
end
context "string represents an invalid URL" do
it "should return nil for partial urls" do
expect( Adomain.subdomain "http://aloha" ).to be_nil
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.subdomain "::::::::::" ).to be_nil
end
end
end
describe "#subdomain_www" do
context "string represents a URL" do
subject { Adomain.subdomain_www "http://www.name.com" }
it { is_expected.to eq "www.name.com" }
end
context "string represents an invalid URL" do
it "should return nil for partial urls" do
expect( Adomain.subdomain_www "http://aloha" ).to be_nil
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.subdomain_www "::::::::::" ).to be_nil
end
end
end
describe "#scheme" do
context "string represents a URL" do
subject { Adomain.scheme "http://www.name.com" }
it { is_expected.to eq "http" }
end
context "string represents an invalid URL" do
it "should return scheme even for partial urls" do
expect( Adomain.scheme "http://aloha" ).to eq("http")
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.scheme "::::::::::" ).to be_nil
end
end
end
describe "#path" do
context "string represents a URL" do
subject { Adomain.path "http://www.name.com/custom/path" }
it { is_expected.to eq "/custom/path" }
end
context "string represents a partial URL with www" do
subject { Adomain.path "www.name.com/custom/path" }
it { is_expected.to eq "/custom/path" }
end
context "string represents a partial URL with other subdomain" do
subject { Adomain.path "abc.name.co.uk/custom/path" }
it { is_expected.to eq "/custom/path" }
end
context "string represents a partial URL with no subdomain" do
subject { Adomain.path "name.co.nz/custom/path" }
it { is_expected.to eq "/custom/path" }
end
context "string represents an invalid URL" do
it "should return an empty string for partial urls" do
expect( Adomain.path "http://aloha" ).to eq("")
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.scheme "::::::::::" ).to be_nil
end
end
end
describe "#query_values" do
context "string represents a URL" do
subject { Adomain.query_values "http://www.name.com/custom/path?params=123&other=abc" }
it { is_expected.to eq({"params" => "123", "other" => "abc"}) }
end
context "string represents an invalid URL" do
it "should return empty strings for partial urls" do
expect( Adomain.query_values "http://aloha?&=" ).to eq({"" => ""})
end
it "should return nil for wholly irrelevant strings" do
expect( Adomain.query_values ":::::::::?:" ).to be_nil
end
end
end
end
| true |
9911c66e7d4ca8521c01353cacf9b76266e7e544 | Ruby | JHawk/ruby_euler_solutions | /lib/problem14.rb | UTF-8 | 719 | 3.625 | 4 | [] | no_license | # Find the longest sequence using a starting number under one million.
class Problem14 < Problem
attr_accessor :steps
def initialize
@steps = {}
super
end
def get_steps(start)
return @steps[start] if @steps[start]
if start == 1
return @steps[start] = start
elsif start % 2 == 0
return @steps[start] = get_steps(start / 2) + 1
else
return @steps[start] = get_steps(3*start + 1) + 1
end
end
def problem(top=1000000)
n = 0
longest_seq = 0
most_steps = 0
while n < top
n += 1
steps = get_steps(n)
if most_steps < steps
longest_seq = n
most_steps = steps
end
end
longest_seq
end
end
| true |
c14bc26b91e49ee6e268a2797873ded1162b9b1d | Ruby | nahiluhmot/readgex | /lib/readgex/simple_parser.rb | UTF-8 | 2,276 | 2.890625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # This module defines the basic parsers used in Readgexes. Note that all of
# these methods are private since they are only supposed to be used in the DSL.
module Readgex::SimpleParser
include Readgex::Motion
private
# Given a character, will try to match the input against that character. Will
# raise a Readgex::MismatchError on failure.
def char(ch)
if ch == one_forward
@last_result = ch
block_given? ? yield(ch.dup) : self
else
one_backward
raise Readgex::MismatchError, "{ 'input_position': #{position}, 'expected': '#{peek}', 'got': '#{ch}' }"
end
end
# Given a string, will attempt to match it against the input. Will raise a
# Readgex::MismatchError on failure.
def string(str)
original_position = @position
str.each_char { |ch| char(ch) }
@last_result = str
block_given? ? yield(str.dup) : self
rescue Readgex::MismatchError => ex
@position = original_position
raise ex
end
def option(*parsers)
success = parsers.map(&:to_proc).reduce(nil) do |output, parser|
if output
output
else
begin
original_position = @position
instance_eval(&parser)
true
rescue Readgex::ReadgexError
@position = original_position
nil
end
end
end
unless success.nil?
block_given? ? yield(@last_result.dup) : self
else
raise Readgex::MismatchError, "{'input_position': #{position}, 'message': 'No matches in #option' }"
end
end
# Defines #char? and #string?. These methods are the same as #char and
# #string, respectively, with the exception that they will return the
# position to it's starting point on failure, then yield nil.
def method_missing(name, *args, &block)
if name =~ /\A(?<method>.+)\?\Z/
method = Regexp.last_match['method'].to_sym
if Readgex::SimpleParser.private_instance_methods.include?(method)
begin
original_position = @postition
send(method, *args, &block)
rescue Readgex::MismatchError
@postition = original_position
@last_result = nil
block.nil? ? self : block.call(nil)
end
else
super
end
else
super
end
end
end
| true |
1eb77352c1a95cdce81e6d0dfebdabb2245eeaf1 | Ruby | Andsbf/robot_exercise | /lib/robot.rb | UTF-8 | 1,344 | 3.640625 | 4 | [] | no_license | require_relative 'custom_exception_classes'
class Robot
attr_accessor :equipped_weapon
attr_reader :items, :health
def initialize
@position = {horizontal:0, vertical:0}
@items = []
@health = 100
@equipped_weapon = nil
end
def position
@position.values
end
def move_left
@position[:horizontal] -= 1
@position.values
end
def move_right
@position[:horizontal] += 1
@position.values
end
def move_up
@position[:vertical] += 1
end
def move_down
@position[:vertical] -= 1
end
def pick_up(obj)
if( (items_weight + obj.weight) <= 250)
@equipped_weapon = obj if obj.kind_of? Weapon
items << obj
else
false
end
end
def items_weight
@items.inject(0){|sum, item| sum + item.weight}
end
def wound(value)
@health -= value
@health = 0 if @health < 0
end
def heal(value)
@health += value
@health = 100 if @health > 100
end
def attack!(enemy)
raise EnemyHasToBeRobotError, "enemy has to be a robot" unless (enemy.kind_of? Robot)
if equipped_weapon == nil
enemy.wound(5)
else
self.equipped_weapon.hit(enemy)
end
end
def heal!
raise RobotAlreadyDeadError, "Robot is alread dead" if @health <= 0
@health += value
@health = 100 if @health > 100
end
end
| true |
8627b7bbfbd6f61b96c859ae601a79f301522658 | Ruby | danielfone/imaginary-problem | /micro_test.rb | UTF-8 | 1,000 | 3.703125 | 4 | [] | no_license | class MicroTest
ANSI_GREEN = 32
ANSI_RED = 31
def initialize(&test)
@test = test
@pass_count = 0
@fail_count = 0
end
def check(values)
values.each { |input, expected| check_result input, expected }
puts_totals
end
def passed?
@fail_count == 0
end
private
def check_result(input, expected)
actual = @test.call input
if actual == expected
pass "#{input.inspect} => #{actual.inspect}"
else
fail "Expected #{input.inspect} => #{expected.inspect}: got #{actual.inspect}"
end
end
def pass(message)
@pass_count += 1
puts_color ANSI_GREEN, message
end
def fail(message)
@fail_count += 1
puts_color ANSI_RED, message
end
def puts_color(color_code, message)
puts "\e[0;#{color_code}m" << message << "\e[0m"
end
def puts_totals
puts '---'
puts_color ANSI_GREEN, "Passed: #{@pass_count}" if @pass_count > 0
puts_color ANSI_RED, "Failed: #{@fail_count}" if @fail_count > 0
end
end
| true |
ac84f5f58d1858f66631e70836827d8d899e9f80 | Ruby | taw/ctf-tools | /lib/gf2m_field.rb | UTF-8 | 493 | 3.3125 | 3 | [] | no_license | class GF2mField
attr_reader :poly, :degree
def initialize(poly)
raise "GF(2^m) requires irreducible polynomial" unless poly.is_a?(BinaryPoly)
raise "Polynomial must be irreducible" unless poly.irreducible?
@poly = poly
@degree = poly.degree
end
def ==(other)
other.is_a?(GF2mField) and @poly == other.poly
end
def eql?(other)
self == other
end
def hash
@poly.hash
end
def elements
(0...2**@degree).map{|i| GF2m.new(i, self) }
end
end
| true |
fc6f0615bb86aae09dbc8318c731a0657db428fe | Ruby | jawanng/ttt-with-ai-project-cb-000 | /lib/board.rb | UTF-8 | 765 | 3.984375 | 4 | [] | no_license | require 'pry'
class Board
attr_accessor :cells
def initialize
self.reset!
end
def reset!
@cells = Array.new(9, " ")
end
def display
inside = "-" * 11
puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} "
puts inside
puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} "
puts inside
puts " #{@cells[6]} | #{@cells[7]} | #{@cells[8]} "
puts
end
def position(num)
@cells[num.to_i-1]
end
def full?
@cells.none? { |x| x == " " }
end
def turn_count
9 - @cells.count {|x| x == " "}
end
def taken?(num)
!(self.cells[num.to_i - 1] == " ")
end
def valid_move?(num)
num.to_i > 0 && !self.taken?(num)
end
def update(num, player)
@cells[num.to_i - 1] = player.token
end
end
| true |
2cb7e1e3da016541bb4c048c3b270800b2884381 | Ruby | JulietDeRozario/THP_Exercices | /Week-3/J3-Sauvegardes/data_saved/lib/mairie_chistmas.rb | UTF-8 | 2,462 | 3.421875 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'rubygems'
class Program
#===> On va récupérer les liens de chaque mairie de chaque commune
def get_townhall_links(doc)
townhall_links = [] #==> Tableau dans lequel je vais stoquer mes liens
doc.css("p > a").each do |link| #==> Je parcours tous les liens vers le site de chaque commune
townhall_link = link["href"][1..-1] #=> Je supprime le "." au début de l'url
townhall_links << "https://annuaire-des-mairies.com" + townhall_link #==> Je complète le chemin de chaque lien pour qu'il soit utilisable et je le stoque dans mon tableau
end
return townhall_links
end
#==> On va récupérer les noms des différentes communes
def get_townhall_names(doc)
townhall_names = [] #==> Tableau pour stoquer les noms
doc.css("p > a").each do |link| #==> Je parcours mes liens
townhall_names << link.content #==> Je range chaque nom dans mon tableau
end
return townhall_names
end
#===> On va récupérer les emails sur le site des mairies de chaque commune
def get_townhall_emails(townhall_links)
townhall_emails = [] #==> Tableau qui va stoquer ces emails
townhall_links.each do |link| #==> Je parcours le tableau qui contient les liens vers les sites de chaque mairie
new_doc = Nokogiri::HTML(URI.open(link)) #==> Je scrappe vers chaque lien
email = new_doc.css("table.table:nth-child(1) > tbody:nth-child(3) > tr:nth-child(4) > td:nth-child(2)")
townhall_emails << email.text #==> J'y récupère l'email que je stoque dans mon tableau
end
return townhall_emails
end
#===> On va réunir ces valeurs dans un hash
def get_the_emails_hash(townhall_names, townhall_emails)
townhall_emails_hash = Hash.new
townhall_infos_arr = []
counter = 0 #==> Counter pour faire tourner ma boucle
while counter < townhall_names.length #==> J'associe dans un hash le nom de chaque commune avec son adresse mail en utilisant mes deux tableaux précédents
townhall_emails_hash.merge!(Hash[townhall_names[counter] => townhall_emails[counter]])
counter +=1
end
return townhall_emails_hash
end
#===> Méthode perform pour lancer mon programme
def perform(doc)
townhall_links = get_townhall_links(doc)
townhall_names = get_townhall_names(doc)
townhall_emails = get_townhall_emails(townhall_links)
get_the_emails_hash(townhall_names, townhall_emails)
end
end | true |
f2a9e1762b741779b92ec1825ff3b0cf5d3d6164 | Ruby | georgebrock/readline-example | /main.rb | UTF-8 | 728 | 3.203125 | 3 | [] | no_license | require "readline"
CHARACTER_NAMES = [
"Arthur Dent",
"Ford Prefect",
"Tricia McMillan",
"Zaphod Beeblebrox",
].freeze
Readline.completer_quote_characters = "\"'"
Readline.completer_word_break_characters = " "
Readline.quoting_detection_proc = proc do |input, index|
index > 0 && input[index - 1] === "\\" &&
!Readline.quoting_detection_proc.call(input, index-1)
end
Readline.completion_proc = proc do |input|
options = CHARACTER_NAMES
if Readline.completion_quote_character.nil?
options = options.map { |o| o.gsub(" ", "\\ ") }
end
options.select { |name| name.start_with?(input) }
end
puts "Who's your favourite Hitchiker's Guide character?"
input = Readline.readline("> ", false)
if input
puts "You entered: #{input}"
end
| true |
7042e5cf5fac7d2f608ece5419993e716d319b34 | Ruby | yuzixun/algorithm_exercise | /main/20170323-89.rb | UTF-8 | 397 | 3.71875 | 4 | [] | no_license | # @param {Integer} n
# @return {Integer[]}
def gray_code(n)
# results = [0]
# n.times do |index|
# puts '-------'
# results += results.reverse.map do |e|
# a = e + 2**index
# puts "#{e.to_s(2)} => #{a.to_s(2)}"
# a
# end
# end
# results
n.times.reduce([0]) { |results, index| results += results.reverse.map { |e| e + 2**index } }
end
puts "#{gray_code(3)}" | true |
8c348ea00644691e0307f9733188229fd9916923 | Ruby | strider-/AstrosmashClone | /lib/bullet.rb | UTF-8 | 367 | 2.640625 | 3 | [] | no_license | class Bullet
include Collidable
MOVE_STEP = 5
def initialize(window:, start_position:)
super(window: window, image_name: 'bullet.png')
set_position *start_position
end
def update
offset(0, -MOVE_STEP)
end
def draw
image.draw(x, y, 0)
end
def out_of_bounds?
y < -image.height
end
end | true |
078a190e3093d4941409ff66dc282d17c8cfb11c | Ruby | lingdudefeiteng/pipette | /bulk/filter.rb | UTF-8 | 3,759 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env ruby
FILTER_MATCH = File.expand_path(File.join(File.dirname(__FILE__), "..", "bin", "fast_filter_matching_vcfs.rb"))
FILTER = File.expand_path(File.join(File.dirname(__FILE__), "..", "bin", "filter_vcf.rb"))
ANNOTATE = File.expand_path(File.join(File.dirname(__FILE__), "..", "bin", "annotate_vcf.rb"))
ANNOTATE_CONFIG = File.expand_path(File.join(File.dirname(__FILE__), "variant_config.yml"))
LINKS = File.expand_path(File.join(File.dirname(__FILE__), "..", "bin", "add_igv_links.rb"))
INDEX_VCF = "java -Xmx1500m -Djava.awt.headless=true -jar /n/local/stage/igv_tools/current/igvtools.jar index"
starting_dir = ARGV[0]
control_name = "Control"
def filter_matching_vcfs vcf_files, control_name, starting_dir
control_snp_vcf_filename = File.expand_path(File.join(starting_dir, control_name, "#{control_name}.snps.vcf"))
control_indel_vcf_filename = File.expand_path(File.join(starting_dir, control_name, "#{control_name}.indels.vcf"))
vcf_files.each do |vcf_file|
puts vcf_file
dir_name = File.dirname(vcf_file)
Dir.chdir(dir_name) do
vcf_basename = File.basename(vcf_file)
filter_file = vcf_basename.split(".")[1] == "indels" ? control_indel_vcf_filename : control_snp_vcf_filename
command = "#{FILTER_MATCH} #{vcf_basename} #{filter_file}"
puts command
system(command)
end
end
end
def filter_vcfs vcf_files
vcf_files.each do |vcf_file|
puts vcf_file
dir_name = File.dirname(vcf_file)
Dir.chdir(dir_name) do
vcf_basename = File.basename(vcf_file)
filter_name = File.basename(vcf_file, File.extname(vcf_file)) + ".filter.vcf"
command = "#{FILTER} #{vcf_basename} #{filter_name}"
puts command
system(command)
end
end
end
def annotate_vcfs vcf_files
vcf_files.each do |vcf_file|
puts vcf_file
dir_name = File.dirname(vcf_file)
Dir.chdir(dir_name) do
vcf_basename = File.basename(vcf_file)
command = "#{ANNOTATE} -y #{ANNOTATE_CONFIG} -i #{vcf_basename}"
puts command
system(command)
end
end
end
def add_links tsv_files
tsv_files.each do |tsv_file|
puts tsv_file
dir_name = File.dirname(tsv_file)
Dir.chdir(dir_name) do
basename = File.basename(tsv_file)
command = "#{LINKS} #{basename}"
puts command
system(command)
end
end
end
def copy_results results_files, results_dir
system("mkdir -p #{results_dir}")
results_files.each do |result_file|
command = "cp #{result_file} #{results_dir}"
puts command
system(command)
end
end
def index_vcf_files vcf_files
vcf_files.each do |vcf_file|
Dir.chdir(File.dirname(vcf_file)) do
command = "#{INDEX_VCF} #{File.basename(vcf_file)}"
puts command
system(command)
end
end
end
vcf_files = Dir.glob(File.join(starting_dir, "**", "*.vcf"))
filter_matching_vcfs vcf_files, control_name, starting_dir
vcf_files = Dir.glob(File.join(starting_dir, "**", "*.unique_from_#{control_name}.*.vcf"))
filter_vcfs(vcf_files)
vcf_files = Dir.glob(File.join(starting_dir, "**", "*.unique_from_#{control_name}.*.filter.vcf"))
annotate_vcfs vcf_files
output_dir = File.join("results", "vcf_files")
copy_results vcf_files, output_dir
vcf_files = Dir.glob(File.join(output_dir, "*.vcf"))
index_vcf_files vcf_files
tsv_files = Dir.glob(File.join(starting_dir, "**", "*filter*.collapse.txt"))
add_links(tsv_files)
result_files = Dir.glob(File.join(starting_dir, "**", "*filter*.links.xls"))
output_dir = File.join("results", "linked_files")
copy_results result_files, output_dir
output_dir = File.join("results", "summary_files")
result_files = Dir.glob(File.join(starting_dir, "**", "*filter*.snpeff.summary.html"))
copy_results result_files, output_dir
| true |
f0c79c62d34718eb48389e3d9e65ed55b5e23a10 | Ruby | viniciusoyama/rapidoc | /lib/rapidoc/controller_extractor.rb | UTF-8 | 1,510 | 2.984375 | 3 | [
"MIT"
] | permissive | module Rapidoc
##
# This class open controller file and get all documentation blocks.
# Lets us check if any of this blocks is a `rapidoc` block
# and return it using `json` format.
#
# Rapidoc blocks must:
# - have YAML format
# - begin with `#=begin action` for actions description
# - begin with `#=begin resource` for resource description
# - end with `#=end`
#
class ControllerExtractor
def initialize( controller_file )
lines = IO.readlines( controller_dir( controller_file ) )
blocks = extract_blocks( lines )
@resource_info = YamlParser.extract_resource_info( lines, blocks, controller_file )
@actions_info = YamlParser.extract_actions_info( lines, blocks, controller_file )
end
def get_actions_info
@actions_info
end
def get_action_info( action )
@actions_info.select{ |info| info['action'] == action.to_s }.first
end
def get_resource_info
@resource_info
end
def get_controller_info
{ "description" => @resource_info["description"], "actions" => @actions_info }
end
private
##
# Gets init and end lines of each comment block
#
def extract_blocks( lines )
init_doc_lines = lines.each_index.select{ |i| lines[i].include? "=begin" }
end_doc_lines = lines.each_index.select{ |i| lines[i].include? "=end" }
blocks = init_doc_lines.each_index.map do |i|
{ :init => init_doc_lines[i], :end => end_doc_lines[i] }
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.