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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
028e49bd329ab3f18f8f23c537e417e688281a33 | Ruby | gijs/popHealth | /app/models/user.rb | UTF-8 | 3,977 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | require 'uniq_validator'
class User < MongoBase
include ActiveModel::Conversion
add_delegate :password, :protect
add_delegate :username
add_delegate :first_name
add_delegate :last_name
add_delegate :email
add_delegate :company
add_delegate :company_url
add_delegate :registry_id
add_delegate :registry_name
add_delegate :npi
add_delegate :tin
add_delegate :reset_key, :protect
add_delegate :validation_key, :protect
add_delegate :validated, :protect
add_delegate :_id
add_delegate :effective_date
validates_presence_of :first_name, :last_name
validates :email, :presence => true,
:length => {:minimum => 3, :maximum => 254},
:format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i},
:uniq=>true
validates :username, :presence => true, :length => {:minimum => 3, :maximum => 254}
validates :username, :uniq => true, :if => :new_record?
validates :password, :presence => true
# Lookup a user by the username and password,
# param [String] username the username to look for
# param [Sting] password the clear text password to look for, pass will be hashed to check
def self.authenticate(username, password)
u = mongo['users'].find_one(:username => username)
if u
bcrypt_pw = BCrypt::Password.new(u['password'])
if bcrypt_pw.is_password?(password)
return User.new(u)
end
end
return nil
end
# See if the username already exists
# param [String] username
def self.check_username(username)
mongo['users'].find_one(:username => @attributes[:username])
end
# Find users based on hash of key value pairs
# param [Hash] params key value pairs to use as a filter - same as would be passed to mongo collection
def self.find(params)
mongo['users'].find(params).map do |model_attributes|
create_user_from_db(model_attributes)
end
end
# Find one user based on hash of key value pairs
# param [Hash] params key value pairs to use as a filter - same as would be passed to mongo collection
def self.find_one(params)
model_attributes = mongo['users'].find_one(params)
create_user_from_db(model_attributes)
end
# Merge the attributes with the record
# @param [Hash] attributes the attributes to merge into this record
def update(attributes)
@attributes.merge!(attributes)
end
def salt_and_store_password(new_password)
@attributes[:password] = BCrypt::Password.create(new_password)
end
#Save the user to the db, save only takes place if the record is valid based on the validation
def save
if valid?
User.mongo['users'].save(@attributes)
return true
end
return false
end
def validate_account!
self.validation_key = nil
self.validated = true
save
end
def reset_password!
self.reset_key = nil
save
self.password = nil
end
def unverified?
validated.nil?
end
# Is this a new record, ie it has not been saved yet so there is no _id
def new_record?
_id.nil?
end
# Remove the user from the db
def destroy
User.mongo['users'].remove(@attributes)
end
# reload the user from the stored values in the db, this only works for saved records
def reload
unless new_record?
@attributes = mongo['users'].find_one({'_id' => _id})
end
end
def persisted?
! new_record?
end
def id
_id
end
private
# Creates a User from a Hash. This method will also ensure that attributes protected from
# mass assignment are set. So this method should only be used when pulling information from
# MongoDB. It should not be used to handle params hashes from web requests.
def self.create_user_from_db(user_document)
user = nil
if user_document
user = User.new(user_document)
protected_attributes.each {|attribute| user.send("#{attribute}=", user_document[attribute])}
end
user
end
end
| true |
501d37c2461fd8996512a3183ca8e800e8079612 | Ruby | ezmac/gatling_talk | /lotek/uri_stats.rb | UTF-8 | 3,317 | 2.609375 | 3 | [] | no_license | require './log_parse'
require 'pry'
require 'colorize'
# Parse the command line
src_access_log=""
options = {}
begin
opts = OptionParser.new
opts.banner = "Usage: #{$PROGRAM_NAME} [options] ..."
opts.separator ''
opts.separator 'Options:'
opts.on('-s src_access_log',
'--src_access_log src_access_log',
String,
'Set source access log file') {|key| options[:src_access_log] = key}
opts.on('-d src_access_log_dir',
'--src_access_log_dir src_access_log_dir',
String,
'Set source access log file directory') {|key| options[:src_access_log_dir] = key}
opts.on('-h', '--help', 'Show this message') do
puts opts
exit
end
rescue OptionParser::ParseError
puts "Oops... #{$!}"
puts opts
exit
end
begin
opts.parse!
mandatory = [:src_access_log, :src_access_log_dir] # Enforce the presence of
missing = mandatory.select{ |param| options[param].nil? }
if not missing.length==1
puts "Missing options: #{missing.join(', ')}"
puts opts
exit -1
end
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts $!.to_s
puts opts#
exit -1
end
if (options[:src_access_log])
requests = AWSELBAccessLogParser.new().parse_log_file(options[:src_access_log])
end
if (options[:src_access_log_dir])
files = Dir.entries(options[:src_access_log_dir]).select {|f| !File.directory? f}
requests = files.reduce([]) {|accumulator, file| accumulator.concat AWSELBAccessLogParser.new().parse_log_file("#{options[:src_access_log_dir]}/#{file}" ) }
end
#byuser = requests.reduce(OpenStruct.new){ |a, r|
#if a[r.client].nil?
#a[r.client]=[]
#end
#a[r.client].push(r)
#a
#}
# [:timestamp, :elb, :client, :client_port, :backend, :backend_port, :request_processing_time, :backend_processing_time, :response_processing_time, :elb_status_code, :backend_status_code, :received_bytes, :sent_bytes, :request, :user_agent, :ssl_cipher, :ssl_protocol]
byRequest= requests.group_by {|r| r.request}
byRequest.sort_by {|r, requests| requests.length } .each do |requestKey, requests|
# each user has N requests, requests have the above keys/methods
# so
#print "#{requestKey}".red, " #{requests.length}".blue, "\r\n"
end
byTime= requests.group_by {|r| r.timestamp.split('.').first}
# [:timestamp, :elb, :client, :client_port, :backend, :backend_port, :request_processing_time, :backend_processing_time, :response_processing_time, :elb_status_code, :backend_status_code, :received_bytes, :sent_bytes, :request, :user_agent, :ssl_cipher, :ssl_protocol]
byTime.sort_by {|r, requests| requests.length }.reverse.take(20) .each do |time, requests|
# each user has N requests, requests have the above keys/methods
# so
if requests.length >10
puts "[time, count]"
print "#{time}".red, " #{requests.length}".blue, "\r\n"
puts "[request, count]"
byRequest= requests.group_by {|r| r.request}
byRequest.sort_by {|r, requests| requests.length }.reverse .each do |requestURI, requests|
if requests.length >=1
print " #{requestURI}".red, " #{requests.length}".blue, "\r\n"
end
end
end
end
## Hat tip : https://gist.github.com/jibing57/ea180bfc3f7cb96e4a1fa67aa7a7c0c2
## Hat tip : https://gist.github.com/jibing57/ea180bfc3f7cb96e4a1fa67aa7a7c0c2
| true |
e97d95286c86497e13ae9790c7adf3f7f6df7e31 | Ruby | vdmgolub/kloudless-ruby | /lib/kloudless/http.rb | UTF-8 | 3,021 | 2.65625 | 3 | [
"MIT"
] | permissive | require "net/http"
require "json"
module Kloudless
# Net::HTTP wrapper
class HTTP
# Public: Headers global to all requests
def self.headers
@headers ||= {}
end
def self.request(method, path, params: {}, data: {}, headers: {},
parse_request: true, parse_response: true)
uri = URI.parse(Kloudless::API_URL + path)
uri.query = URI.encode_www_form(params) if !params.empty?
if ['post', 'put', 'patch'].member?(method)
headers["Content-Type"] ||= "application/json"
end
request = Net::HTTP.const_get(method.capitalize).new(uri)
request.initialize_http_header(headers)
if !data.empty?
data = data.to_json if parse_request
request.body = data
end
execute(request, parse_response: parse_response)
end
def self.get(path, **kwargs)
self.request('get', path, **kwargs)
end
def self.post(path, params: {}, data: {}, headers: {}, **kwargs)
self.request('post', path, params: params, data: data,
headers: headers, **kwargs)
end
def self.put(path, params: {}, data: {}, headers: {}, **kwargs)
self.request('put', path, params: params, data: data,
headers: headers, **kwargs)
end
def self.patch(path, params: {}, data: {}, headers: {}, **kwargs)
self.request('patch', path, params: params, data: data,
headers: headers, **kwargs)
end
def self.delete(path, params: {}, headers: {}, **kwargs)
self.request('delete', path, params: params, headers: headers, **kwargs)
end
def self.execute(request, parse_response: true)
uri = request.uri
@last_request = request
headers.each {|k,v| request[k] = v}
response = @mock_response || Net::HTTP.start(uri.hostname, uri.port, use_ssl: (uri.scheme == "https")) {|http|
http.request(request)
}
if parse_response
json = JSON.parse(response.body)
raise Kloudless::Error.from_json(json) if json["error_code"]
json
else
response.body
end
end
# Internal: Returns `response` the next time #execute is invoked for the
# duration of `blk`. Used for testing.
#
# mock = Struct.new(:body).new("{}")
# Kloudless::HTTP.mock_response(mock) do
# Kloudless::HTTP.get "/foo" # returns {}
# end
def self.mock_response(response = nil, &blk)
@mock_response = response || Struct.new(:body).new("{}")
blk.call
ensure
@mock_response = nil
end
require 'minitest/mock'
def self.expect(method, returns: nil, args: [], &blk)
begin
mock = MiniTest::Mock.new
Kloudless.http = mock
mock.expect(method, returns, args)
blk.call
mock.verify
ensure
Kloudless.http = Kloudless::HTTP
end
end
# Internal: Returns the last Net::HTTP request sent by #execute.
def self.last_request
@last_request
end
end
end
| true |
db7a5d0cb1653844e027fd14a7bc6a4e0eaf8f65 | Ruby | ylluminarious/comp_science_ecot | /bubble_sort/main.rb | UTF-8 | 1,207 | 4.3125 | 4 | [] | no_license | def bubble_sort(array, length)
# The loop that iteratively goes through the array and sorts it
array.each do |element|
# Some pretty self-explanatory variables
current_element = array.index(element)
next_element = current_element + 1
# The first check is to make sure that the current element is not the last
# because the last element has no next element to look to, so the program will crash
if array[current_element] != array.last
# The following bit of conditional logic compares the current element to the next element and
# replaces the current one with the next one if the next one is smaller
# (so that it bubbles up the index chain)
if array[next_element] < array[current_element]
array.insert(current_element, array.delete_at(next_element))
end
end
end
# This bit of logic makes sure that the method recurs if it
# has not iterated through the array for it's length of times
if length == 0
print array
else
bubble_sort(array, length - 1)
end
end
array_to_be_sorted = [4,3,78,2,0,2] # insert your array to be sorted
bubble_sort(array_to_be_sorted, array_to_be_sorted.length) | true |
b17b1a73f75b8e49ee402afdc3e10b0cef2e2cde | Ruby | hivehand/util | /jj | UTF-8 | 443 | 2.875 | 3 | [] | no_license | #!/usr/bin/env ruby -w
# Pretty-print JSON input from a file, or stdin.
require 'json'
# To do (maybe):
# - Add an option to insert a splitting line between the prettifications of
# multiple sources. (Easy.)
# - Add an option to convert multiple sources into a single array.
# (Trickier, but doable.)
input = String.new
ARGF.each_line do |line|
input << line
if ARGF.eof?
jj JSON.parse(input)
input.clear
end
end
| true |
f8ecfca9054b9bab0224e5c5a1dfccf33495122f | Ruby | Daniel-Muriano/learn_ruby | /02_calculator/calculator.rb | UTF-8 | 201 | 3.359375 | 3 | [] | no_license | def add (a,b)
a+b
end
def subtract(a,b)
a-b
end
def sum(a)
b=a.length
i=0
c=0
while (i<b)
c=c+a[i]
i=i+1
end
c
end
def multiply (a,b)
a*b
end
| true |
e615a89a616d712aaa8f7c8351415beb196bfd02 | Ruby | grinchrb/grinch | /lib/cinch/rubyext/module.rb | UTF-8 | 601 | 2.578125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Extensions to Ruby's Module class.
class Module
# Like `attr_reader`, but for defining a synchronized attribute
# reader.
#
# @api private
def synced_attr_reader(attribute)
undef_method(attribute)
define_method(attribute) do
attr(attribute)
end
define_method("#{attribute}_unsynced") do
attr(attribute, false, true)
end
end
# Like `attr_accessor`, but for defining a synchronized attribute
# accessor
#
# @api private
def synced_attr_accessor(attr)
synced_attr_reader(attr)
attr_accessor(attr)
end
end
| true |
cbbf03b9688aa631282c5f0581ae60d66a419ac8 | Ruby | mikewagner/ledes_parser | /spec/ledes/parser_spec.rb | UTF-8 | 3,336 | 2.6875 | 3 | [] | no_license | require 'helper'
require 'ledes/parser'
require 'ledes/exceptions'
describe Ledes::Parser do
describe ".new" do
end
describe "#contents" do
let(:file) { fixture(:ledes) }
context "from file" do
before do
@parser = Ledes::Parser.new( file )
end
it "should return contents as array" do
@parser.contents.should be_instance_of Array
end
it "should return format specification as first element" do
@parser.contents.first.should == 'LEDES1998B'
end
end
context "from string" do
before do
string = "LEDES1998B[]INVOICE_DATE|INVOICE_NUMBER|CLIENT_ID[] "
@parser = Ledes::Parser.new( string )
end
it "should return lines formatted as array" do
@parser.contents.should == ['LEDES1998B', 'INVOICE_DATE|INVOICE_NUMBER|CLIENT_ID']
end
end
end
describe "#map_line_to_headers" do
let (:line) {
[ '19990225',
'96542',
'00711',
'0528',
'700',
'19990101',
'19990131',
'For services rendered',
'1',
'F',
'2.00',
'0',
'700',
'19990115',
'L510',
'',
'A102',
'22547',
'Research attorney\'s fees, Trial pleading',
'24-6437381',
'350','Arnsley, Robert',
'PT',
'423-987' ]
}
it "should split the line and map values to headers" do
parser = Ledes::Parser.new ''
result = parser.map_line_to_headers(line.join('|'))
result.keys.each_with_index do |key, index|
result[key].should == line[index]
end
end
end
describe "#valid_format?" do
it "should return true if format valid" do
file = fixture(:ledes)
parser = Ledes::Parser.new(file)
parser.should be_valid_format
end
it "should return false if format invalid" do
file = fixture(:ledes_with_invalid_format)
parser = Ledes::Parser.new(file)
parser.should_not be_valid_format
end
end
describe "#valid_header?" do
it "should return true if header valid" do
file = fixture(:ledes)
parser = Ledes::Parser.new(file)
parser.should be_valid_header
end
it "should return false if header invalid" do
file = fixture(:ledes_with_invalid_headers)
parser = Ledes::Parser.new(file)
parser.should_not be_valid_header
end
end
describe "#parse" do
context "invalid input" do
it "should raise error when file contains invalid format" do
file = fixture(:ledes_with_invalid_format)
@parser = Ledes::Parser.new( file )
lambda {
@parser.parse
}.should raise_error(Ledes::InvalidFormat)
end
it "should raise error when file contains invalid headers" do
file = fixture(:ledes_with_invalid_headers)
@parser = Ledes::Parser.new( file )
lambda {
@parser.parse
}.should raise_error(Ledes::InvalidHeader)
end
end
context "valid input" do
let(:file) { fixture(:ledes_single_line_item) }
it "should return array of entries" do
entry = Ledes::Entry.new
Ledes::Entry.stub(:new).and_return(entry)
Ledes::Parser.new(file).parse.should == [entry]
end
end
end
end
| true |
e468e175d7ae4e5691c4f7bd93cb8d18cba0af47 | Ruby | JamesDawson/TheDivisionGearBrain | /lib/inventory.rb | UTF-8 | 2,538 | 3.078125 | 3 | [] | no_license | require 'oj'
class Inventory
attr_reader :statistics, :required_items, :items, :vests, :masks, :kneepads, :backpacks, :gloves, :holsters
def initialize(data_file)
@statistics = ['firearms', 'stamina', 'electronics', 'armor']
@required_items = ['vests','masks','kneepads','backpacks','gloves','holsters']
@vests = []
@masks = []
@kneepads = []
@backpacks = []
@gloves = []
@holsters = []
@mods = []
@perf_mods = []
json = File.read(data_file)
# puts "json: #{json}"
@items = Oj.load(json)
@items.each do |i|
case i['item_type'].downcase
when 'vest'
@vests.push(i)
when 'mask'
@masks.push(i)
when 'kneepads'
@kneepads.push(i)
when 'backpack'
@backpacks.push(i)
when 'gloves'
@gloves.push(i)
when 'holster'
@holsters.push(i)
end
end
end
def generate_builds_cache(cache_file)
if File.exist?(cache_file)
File.delete(cache_file)
end
f = File.open(cache_file, 'w')
begin
num_builds = find_builds(f, @required_items[0])
rescue
#handle the error here
ensure
f.close unless f.nil?
end
return num_builds
end
private
def find_builds(cache_file, item_type, items_in_build = [], count = 0)
got_all_required_items = false
current_item_type_index = @required_items.index(item_type)
if current_item_type_index == @required_items.count - 1
got_all_required_items = true
else
next_item_type = @required_items[current_item_type_index + 1]
end
send(item_type).each do |i|
items_in_build.push(i)
if !got_all_required_items
count = find_builds(cache_file, next_item_type, items_in_build, count)
else
# output current build (as a set of items) and their aggregate stats to cache file
count += 1
aggregate_stats = create_aggregated_build_stats(items_in_build)
cache_object = { 'items' => items_in_build, 'statistics' => aggregate_stats }
cache_object_as_json = Oj.dump cache_object
cache_file.puts cache_object_as_json
end
# remove the last item before looping around to the next
items_in_build.pop
end
if count % 1000 == 0 then print '.'; $stdout.flush end
return count
end
def create_aggregated_build_stats(build_items)
result = {}
@statistics.each do |stat|
result[stat] = build_items.inject(0){|sum, item| sum + item[stat].to_i}
end
return result
end
end
| true |
9904e6cafc7202265ebafc5b861ad63eabd38b2f | Ruby | shoutm/ScoreUpGolf | /app/controllers/service/player_service_controller.rb | UTF-8 | 2,141 | 2.515625 | 3 | [] | no_license | class Service::PlayerServiceController < ApplicationController
# == 概要
# 引数にplayer_idが指定されていた場合、playerが所属するコンペにおけるスコアを全て取得する
# 引数のcompetition_idが指定されていた場合、引数のcompetition_idとログイン中のユーザ情報からplayerを特定し、所属するコンペにおけるスコアを取得する
#
# == 引数
# 以下のどちらかの引数を指定
# player_id
# competition_id
#
# == 出力例
# [
# {
# "created_at": "2012-07-12T23:45:07Z",
# "golf_hole_id": 101,
# "id": 201,
# "pat_num": 2,
# "player_id": 2,
# "shot_num": 3,
# "updated_at": "2012-07-12T23:45:07Z"
# },
# ...
# ]
def get_scores
if params[:player_id]
p = Player.find(params[:player_id])
elsif params[:competition_id]
c = Competition.find(params[:competition_id])
party = PartyUtils::get_joined_party(c.parties, @user)
p = PartyUtils::get_player(@user, party)
end
respond_to do |format|
format.json { render json: p.shot_results }
end
rescue ActiveRecord::RecordNotFound => e
# TODO
render json: nil
end
# == 概要
# 指定されたplayeridに対して指定されたスコアをセットする
#
# ==引数
# player_id
# golf_hole_id
# shot_num
# pat_num
#
# == 返り値
# 成功 : 200(httpステータスコードとして)
# 失敗 : 400(httpステータスコードとして)
def set_score
# TODO 認証
unless params[:player_id] && params[:golf_hole_id] && params[:shot_num] && params[:pat_num]
render status: 400, text: nil
return
end
shot_result = ShotResult.new({player_id: params[:player_id],
golf_hole_id: params[:golf_hole_id],
shot_num: params[:shot_num],
pat_num: params[:pat_num]})
shot_result.save
render status: 200, text: nil
rescue Exception => e
render status: 400, text: nil
end
end
| true |
992e16f00ce0e04b374a604f3c1cdc2986f3face | Ruby | yangliyi/coursera-algorithmic-toolbox | /week5/assignments/4-dynprog-starter-files/knapsack/knapsnack.rb | UTF-8 | 676 | 3.28125 | 3 | [] | no_license | def optimal_weight(capacity, item_weights)
n = item_weights.size
item_weights.unshift(0)
values = Array.new(n+1)
values.map!{|i|i = Array.new(capacity+1, 0)}
for i in 1..n do
for w in 1..capacity do
values[i][w] = values[i-1][w]
if item_weights[i] <= w
val = values[i-1][w-(item_weights[i])] + item_weights[i]
if values[i][w] < val
values[i][w] = val
end
end
end
end
values[n][capacity]
end
$/ = "END"
user_input = STDIN.gets.chomp.split("\n")
capacity = user_input.first.split(" ").first.to_i
item_weights = user_input.last.split(" ").map{ |s| s.to_i }
puts optimal_weight(capacity, item_weights) | true |
51d5edd21b581d7c9341b520d212eb8328c12443 | Ruby | tatomolina/entrega1 | /caesar_cipher.rb | UTF-8 | 495 | 2.84375 | 3 | [] | no_license | require_relative './autenticador.rb'
require 'caesar_cipher'
require 'bcrypt'
class Caesar_cipher < Autenticador
attr_accessor :caesar
def initialize
end
def valido?(user_password, password)
return password_plano(user_password) == password
end
def password_plano(password)
return CaesarCipher::Caesar.new.decipher(password)
end
def password_caesar(password)
return password
end
def password_bcrypt(password)
return BCrypt::Password.create(password_plano password)
end
end | true |
8f72bb5daba3563d378ddd1616e7462379879448 | Ruby | johnofsydney/exercisms | /ruby/matrix/matrix.rb | UTF-8 | 426 | 3.328125 | 3 | [] | no_license | class Matrix
attr_reader :rows, :columns
def initialize input
@rows = input.each_line.map do
|r| r.split.map(&:to_i)
end
@columns = rows.transpose
end
end
# class Matrix
#
# def initialize input
# @input = input
# end
#
# def rows
# @input.scan(/.+/).map do
# |r| r.split(" ").map { |n| n.to_i }
# end
# end
#
# def columns
# rows.transpose
# end
#
# end
| true |
cec445e9a654b7cfb2746238b8c38592038723bf | Ruby | AymanMagdy/Ruby | /Day1/2.rb | UTF-8 | 385 | 3.9375 | 4 | [] | no_license | #!/bin/usr/ruby -w
print <<"EOF"
2) Given two int values, return their sum. Unless the two values are the same, then
return double their sum.
EOF
puts "Enter 2 number: "
first_number = gets.chomp
second_number = gets.chomp
if first_number == second_number
puts (first_number.to_i() + second_number.to_i()) * 2
else
puts first_number.to_i() + second_number.to_i()
end | true |
a467bf53b3c48fc67af708575c6c530ddc8ae352 | Ruby | dpmontooth/rb101 | /lesson_5/practice_8.rb | UTF-8 | 400 | 3.75 | 4 | [] | no_license | # use the each method to output all of the vowels from given strings
hsh = {
first: ['the', 'quick'], second: ['brown', 'fox'], third: ['jumped'],
fourth: ['over', 'the', 'lazy', 'dog']
}
vowels_reference = %w(a e i o u A E I O U) # vowel reference array
char_dump =[]
hsh.each do |_, word|
char_dump << word.join.chars
end
char_dump.flatten.keep_if{|char| vowels_reference.include?(char)}
| true |
ba018f9aa6a42564eafb95caff7a7d356cf3c3f9 | Ruby | alsemyonov/vk | /lib/vk/api/board/methods/get_topics.rb | UTF-8 | 4,067 | 2.625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'vk/api/methods'
module Vk
module API
class Board < Vk::Schema::Namespace
module Methods
# Returns a list of topics on a community's discussion board.
class GetTopics < Schema::Method
# @!group Properties
self.open = true
self.method = 'board.getTopics'
# @method initialize(arguments)
# @param [Hash] arguments
# @option arguments [Integer] :group_id ID of the community that owns the discussion board.
# @option arguments [Array] :topic_ids IDs of topics to be returned (100 maximum). By default, all topics are returned.; ; If this parameter is set, the 'order', 'offset', and 'count' parameters are ignored.
# @option arguments [Integer] :order Sort order:; '1' — by date updated in reverse chronological order.; '2' — by date created in reverse chronological order.; '-1' — by date updated in chronological order.; '-2' — by date created in chronological order.; ; If no sort order is specified, topics are returned in the order specified by the group administrator. Pinned topics are returned first, regardless of the sorting.
# @option arguments [Integer] :offset Offset needed to return a specific subset of topics.
# @option arguments [Integer] :count Number of topics to return.
# @option arguments [Boolean] :extended '1' — to return information about users who created topics or who posted there last; '0' — to return no additional fields (default)
# @option arguments [Integer] :preview '1' — to return the first comment in each topic;; '2' — to return the last comment in each topic;; '0' — to return no comments.; ; By default: '0'.
# @option arguments [Integer] :preview_length Number of characters after which to truncate the previewed comment. To preview the full comment, specify '0'.
# @return [Board::Methods::GetTopics]
# @!group Arguments
# @return [Integer] ID of the community that owns the discussion board.
attribute :group_id, API::Types::Coercible::Int
# @return [Array] IDs of topics to be returned (100 maximum). By default, all topics are returned.; ; If this parameter is set, the 'order', 'offset', and 'count' parameters are ignored.
attribute :topic_ids, API::Types::Coercible::Array.member(API::Types::Coercible::Int).optional.default(nil)
# @return [Integer] Sort order:; '1' — by date updated in reverse chronological order.; '2' — by date created in reverse chronological order.; '-1' — by date updated in chronological order.; '-2' — by date created in chronological order.; ; If no sort order is specified, topics are returned in the order specified by the group administrator. Pinned topics are returned first, regardless of the sorting.
attribute :order, API::Types::Coercible::Int.enum("1", "2", "-1", "-2").optional.default(nil)
# @return [Integer] Offset needed to return a specific subset of topics.
attribute :offset, API::Types::Coercible::Int.optional.default(nil)
# @return [Integer] Number of topics to return.
attribute :count, API::Types::Coercible::Int.optional.default(40)
# @return [Boolean] '1' — to return information about users who created topics or who posted there last; '0' — to return no additional fields (default)
attribute :extended, API::Types::Form::Bool.optional.default(nil)
# @return [Integer] '1' — to return the first comment in each topic;; '2' — to return the last comment in each topic;; '0' — to return no comments.; ; By default: '0'.
attribute :preview, API::Types::Coercible::Int.optional.default(nil)
# @return [Integer] Number of characters after which to truncate the previewed comment. To preview the full comment, specify '0'.
attribute :preview_length, API::Types::Coercible::Int.optional.default(90)
end
end
end
end
end
| true |
f111310179d28c6130556a8c1abd2d6cf721b797 | Ruby | h4hany/yeet-the-leet | /algorithms/Medium/1358.number-of-substrings-containing-all-three-characters.rb | UTF-8 | 1,191 | 3.703125 | 4 | [] | no_license | #
# @lc app=leetcode id=1358 lang=ruby
#
# [1358] Number of Substrings Containing All Three Characters
#
# https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/description/
#
# algorithms
# Medium (58.32%)
# Total Accepted: 12.9K
# Total Submissions: 22.1K
# Testcase Example: '"abcabc"'
#
# Given a string s consisting only of characters a, b and c.
#
# Return the number of substrings containing at least one occurrence of all
# these characters a, b and c.
#
#
# Example 1:
#
#
# Input: s = "abcabc"
# Output: 10
# Explanation: The substrings containing at least one occurrence of the
# characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab",
# "bcabc", "cab", "cabc" and "abc" (again).
#
#
# Example 2:
#
#
# Input: s = "aaacb"
# Output: 3
# Explanation: The substrings containing at least one occurrence of the
# characters a, b and c are "aaacb", "aacb" and "acb".
#
#
# Example 3:
#
#
# Input: s = "abc"
# Output: 1
#
#
#
# Constraints:
#
#
# 3 <= s.length <= 5 x 10^4
# s only consists of a, b or c characters.
#
#
# @param {String} s
# @return {Integer}
def number_of_substrings(s)
end
| true |
3c03b966070557e4d621e547147dc91b28a7e11d | Ruby | mekowalski/ruby-music-library-cli-v-000 | /lib/music_library_controller.rb | UTF-8 | 1,337 | 2.890625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class MusicLibraryController
def initialize(path = "./db/mp3s")
importer = MusicImporter.new(path)
importer.import
end
def call
puts "Initializing Music Library"
puts "Select an Option"
reply = nil
until reply == "exit"
reply= gets.strip
case reply
when "list songs"
Song.list_songs.each_with_index do |info, index|
puts "#{index + 1}. #{info} "
end
when "list artists"
Artist.all.each {|artist| puts artist.name}
when "list genres"
Genre.all.each {|genre| puts genre.name}
when "play song"
puts "Select song by track number"
track = gets.strip.to_i - 1
info = Song.list_songs[track]
puts "Playing #{info}"
when "list artist"
puts "Select Artist's song"
name = gets.strip
artist = Artist.find_by_name(name)
artist.songs.each_with_index do |song, index|
puts "#{index + 1}. #{song.artist.name} - #{song.name} - #{song.genre.name}"
end
when "list genre"
puts "Select Genre's song"
name = gets.strip
genre = Genre.find_by_name(name)
genre.songs.each_with_index do |song, index|
puts "#{index + 1}. #{song.artist.name} - #{song.name} - #{song.genre.name}"
end
end
end
end
end
| true |
05b8a6dad0e74ebd7c35f63fe77c2102b45951b9 | Ruby | tiluser/bloccit | /app/helpers/users_helper.rb | UTF-8 | 464 | 2.65625 | 3 | [] | no_license | module UsersHelper
def user_has_posts?
if @user.posts.count > 0
true
else
false
end
end
def user_has_favorited_posts?
favorited_count = 0
@user.posts.each do |post|
if current_user.favorite_for(post)
favorited_count += 1
end
end
if favorited_count > 0
true
else
false
end
end
end
| true |
5092c98f48c40920324298a036330a75638a1626 | Ruby | Harkame/M2 | /meta_programmation/project/TPOtherLanguages/ruby/inspector/inspector.rb | UTF-8 | 4,009 | 4.03125 | 4 | [] | no_license | # Author : Louis Daviaud
# This module is used to format output
module Util
@@lineSeparator = "-----------------------"
def self.get_line_separator
@@lineSeparator
end
end
# Class who inspect other object
class Inspector
# This method is called to inspect an object
# It call inspect_instance
# @param [Object] object_to_inspect The object to inspect
def inspect object_to_inspect
inspect_instance object_to_inspect, object_to_inspect.class
end
# This method is call to inspect an instance + class
# It call all other inspection methods
# @param [Object] object_to_inspect The instance to inspect
# @param [Class] object_to_inspect_class The class of inspected object
def inspect_instance object_to_inspect, object_to_inspect_class
inspect_hierarchy object_to_inspect, object_to_inspect_class
puts "Class methods"
inspect_public_methods object_to_inspect_class
inspect_private_methods object_to_inspect_class
puts "Object methods"
inspect_public_methods object_to_inspect
inspect_private_methods object_to_inspect
puts "Attributs"
inspect_class_attributs object_to_inspect_class
inspect_object_attributs object_to_inspect
end
# Inspect hierarchy of the inspected object
# @param [Object] object_to_inspect
# @param [Class] object_to_inspect_class
def inspect_hierarchy(object_to_inspect, object_to_inspect_class)
puts "#{object_to_inspect} instance of \"#{object_to_inspect_class.name}\""
print "Hierarchy : "
object_to_inspect_class.ancestors.each do |ancestor|
print "#{ancestor} -> "
end
puts
puts "#{Util::get_line_separator}"
end
# Inspect public methods of inspected object
# @param object_to_inspect
def inspect_public_methods(object_to_inspect)
puts "- Public methods :"
object_to_inspect.public_methods(false).each do |method|
puts "\t- #{method} "
end
puts "#{Util::get_line_separator}"
end
# Inspect private methods of inspected object
# @param object_to_inspect
def inspect_private_methods(object_to_inspect)
puts "- Private methods :"
object_to_inspect.private_methods(false).each do |method|
puts "\t- #{method}"
end
puts "#{Util::get_line_separator}"
end
# Inspect class attributs of inspected object
# @param class_to_inspect
def inspect_class_attributs(class_to_inspect)
puts "- Class attributs :"
class_to_inspect.class_variables.each do |attribute|
value = class_to_inspect.class_eval attribute.to_s
puts "\t- Name : #{attribute}"
puts "\t\t- Type : #{value.class}"
puts "\t\t- Value : #{value.inspect}"
end
puts "#{Util::get_line_separator}"
end
# Inspect object attributs of inspected object
# @param object_to_inspect
def inspect_object_attributs(object_to_inspect)
puts "- Instance attributs :"
object_to_inspect.instance_variables.each do |attribute|
value = object_to_inspect.instance_eval attribute.to_s
puts "\t- Name : #{attribute}"
puts "\t\t- Type : #{value.class}"
puts "\t\t- Value : #{value.inspect}"
end
puts "#{Util::get_line_separator}"
end
# Private methods
private :inspect_hierarchy
private :inspect_public_methods
private :inspect_private_methods
private :inspect_class_attributs
private :inspect_object_attributs
end
# Class to inspect
class Person
# Static attributs
@@default_name = "Toto"
@@default_age = 42
# Initializer with parameters
# @param [Object] name The name of the person
# @param [Object] age The age of the person
def initialize name, age
@name = name
@age = age
end
# Print foo
def foo
puts "foo"
end
end
# Creation of 2 persons
person1 = Person.new "Tata", 29
person2 = Person.new "Titi", 42
inspector = Inspector.new
# Inspection of person1
inspector.inspect person1
# Some format
puts "#{Util::get_line_separator}"
puts "#{Util::get_line_separator}"
puts "#{Util::get_line_separator}"
inspector.inspect person2
| true |
966f4c17138724870b9106ce46e66d081168e5b1 | Ruby | at-huynguyen2/AT_Intern_Spring_2017_Huy_Nguyen | /exercise_day_08/exercise_03.rb | UTF-8 | 257 | 3.515625 | 4 | [] | no_license | require "pry"
require "benchmark"
#a = (1..n).collect {|i| i*i if i*i<n}
#a.compact!
def get_squares n
a = Array.new
(1..n).map do |i|
a.push(i*i) if i*i<n
end
return a
end
puts "input n: "
puts "Perfect square array is #{get_squares gets.to_i}"
| true |
1b6266ee736eb41691d121b6b4bf995de8f93679 | Ruby | cider-load-test/como_vamos | /vendor/plugins/make_permalink/spec/make_permalink_spec.rb | UTF-8 | 2,295 | 3 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
require File.dirname(__FILE__) + "/spec_helper"
describe "MakePermalink" do
it "creates a permalink with just AlphaNumeric characters" do
t = NonAsciiPermalinks.new("foo*.,/\<>%&[]{}bar")
t.permalink.should == "1-foo-bar"
t = NonAsciiPermalinks.new("It's-a-me, Mario! ")
t.permalink.should == "1-it-s-a-me-mario"
t = NonAsciiPermalinks.new("It's-a-me, $10 Mario!") #Notice the $ sign
t.permalink.should == "1-it-s-a-me-10-mario"
t = NonAsciiPermalinks.new("Let's rock & roll") #Notice the & sign
t.permalink.should == "1-let-s-rock-roll"
t = NonAsciiPermalinks.new("This.should.remove.the.dots..")
t.permalink.should == "1-this-should-remove-the-dots"
t = NonAsciiPermalinks.new("Simple English Text")
t.permalink.should == "1-simple-english-text"
end
it "fails if the field is not defined" do
lambda { bad = BadThingie.new; bad.permalink }.should raise_error
end
it "creates a permalink from nonascii chars" do
t = Thingie.new("Simple English Text")
t.permalink.should == "1-simple-english-text"
t = Thingie.new("mateMáticas")
t.permalink.should == "1-matematicas"
t = Thingie.new("fooñÑá[]bar")
t.permalink.should == "1-foonna-bar"
t = Thingie.new("It's-a-me, Mario!")
t.permalink.should == "1-its-a-me-mario"
t = Thingie.new("Its-a-me, Mario!")
t.permalink.should == "1-its-a-me-mario"
end
it "should change nonascii symbols to words" do
t = Thingie.new("6 pack for $10")
t.permalink.should == "1-6-pack-for-10-dollars"
t = Thingie.new("Let's Rock & Roll")
t.permalink.should == "1-lets-rock-and-roll"
t = Thingie.new("Sex & Drugs & Helvetica Bold")
t.permalink.should == "1-sex-and-drugs-and-helvetica-bold"
end
class NonAsciiPermalinks
include MakePermalink
attr_reader :a, :id
make_permalink :a, :replace_nonascii => false
def initialize(value)
@a = value; @id = 1
end
end
class Thingie
include MakePermalink
attr_reader :a, :id
make_permalink :a
def initialize(value)
@a = value; @id = 1
end
end
class BadThingie
include MakePermalink
make_permalink :i_dont_exist
end
end
| true |
ef496e5550f3c723b5921babfb93afe7016eb295 | Ruby | Arithmetics/chess | /chess.rb | UTF-8 | 23,330 | 3.578125 | 4 | [] | no_license | require 'yaml'
require 'colorize'
class Game
attr_accessor :pieces, :turn
def initialize
@turn = "white"
@pieces = []
row7 = [Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook]
row6 = [Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn]
row1 = [Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn,Pawn]
row0 = [Rook,Knight,Bishop,Queen,King,Bishop,Knight,Rook]
column = 0
row7.each do |piece|
@pieces.push(piece.new([column,7], "black"))
column += 1
end
column = 0
row6.each do |piece|
@pieces.push(piece.new([column, 6], "black"))
column += 1
end
column = 0
row1.each do |piece|
@pieces.push(piece.new([column, 1], "white"))
column += 1
end
column = 0
row0.each do |piece|
@pieces.push(piece.new([column, 0], "white"))
column += 1
end
end
def swap_turn
if @turn == "black"
@turn = "white"
else
@turn = "black"
end
end
def draw
squares_array = (" " * 64).split('')
@pieces.each do |piece|
x = piece.location[0]
y = piece.location[1]
index = (7-y) * 8 + x
squares_array[index] = (piece.unicode)
end
line_1 = (" " + "_"*48 + "\n")
line_2 = "7|" + (" |"*8 + "\n")
line_3 = " |"
8.times do |x|
sample = squares_array[x]
line_3 += (" #{sample} |")
end
line_3 += "\n"
line_4 = " |" + ("_____|"*8)
top_square = (line_1 + line_2 + line_3 + line_4)
puts top_square
7.times do |y|
line_2 = "#{-y+6}|" + (" |"*8 + "\n")
line_3 = " |"
8.times do |x|
sample = squares_array[(x+8)+(y*8)]
line_3 += (" #{sample} |")
end
line_3 += "\n"
line_4 = " |" + ("_____|"*8)
mid_square = (line_2 + line_3 + line_4)
puts mid_square
end
puts " 0 1 2 3 4 5 6 7".yellow
end
def select_piece(x,y)
@pieces.find { |piece| piece.location[0] == x && piece.location[1] == y }
end
def space_color(x,y)
if select_piece(x,y)
select_piece(x,y).color
else
nil
end
end
def space_empty?(x,y)
if !select_piece(x,y)
true
else
false
end
end
def list_all_legal_moves(x1,y1)
if select_piece(x1,y1)
piece_moves = select_piece(x1,y1).allowed_moves
piece_moves.select do |r|
view?(x1,y1,r[0],r[1]) && (space_color(r[0],r[1]) != space_color(x1,y1))
end
end
end
def move_piece(x1,y1,x2,y2)
#find out if target_square is an allowed move for specific piece
if select_piece(x1,y1) && select_piece(x1,y1).allowed_moves.find {|move| move == [x2,y2]}
if view?(x1,y1,x2,y2)
#is square being moved to occupied? if so, if it's diff color, no move, else, take the piece there
if !space_empty?(x2,y2)
if space_color(x2,y2) != space_color(x1,y1)
if !puts_self_in_check?(x1,y1,x2,y2)
delete_piece(x2,y2)
select_piece(x1,y1).moved = true
select_piece(x1,y1).location = [x2,y2]
end
end
else
if !puts_self_in_check?(x1,y1,x2,y2)
select_piece(x1,y1).moved = true
select_piece(x1,y1).location = [x2,y2]
end
end
end
end
end #move_piece
def move_piece_in_shadow_game(x1,y1,x2,y2)
#find out if target_square is an allowed move for specific piece
if select_piece(x1,y1) && select_piece(x1,y1).allowed_moves.find {|move| move == [x2,y2]}
if view?(x1,y1,x2,y2)
#is square being moved to occupied? if so, if it's diff color, no move, else, take the piece there
if !space_empty?(x2,y2)
if space_color(x2,y2) != space_color(x1,y1)
delete_piece(x2,y2)
select_piece(x1,y1).moved = true
select_piece(x1,y1).location = [x2,y2]
end
else
select_piece(x1,y1).moved = true
select_piece(x1,y1).location = [x2,y2]
end
end
end
end #move_piece
def dummy_move(x1,y1,x2,y2)
if select_piece(x1,y1) && select_piece(x1,y1).allowed_moves.find {|move| move == [x2,y2]}
if view?(x1,y1,x2,y2)
#is square being moved to occupied? if so, if it's diff color, no move, else, take the piece there
if !space_empty?(x2,y2)
if space_color(x2,y2) != space_color(x1,y1)
deleted_piece = select_piece(x2,y2)
move_successful = true
end
else
move_successful = true
end
end
end
return [move_successful, deleted_piece]
end #move_piece
def view?(x1,y1,x2,y2)
#diff conditions for line of sight depending of what type of piece is being moved
continue = false
if select_piece(x1,y1).class == Pawn
#but can also take an opposite color piece diagonally
if select_piece(x1,y1).color == "black"
continue = false
if black_pawn_helper(x1,y1,x2,y2)
continue = true
end
#had to make a white method since white moves diff direction
elsif select_piece(x1,y1).color == "white"
continue = false
if white_pawn_helper(x1,y1,x2,y2)
continue = true
end
end
#pawn moving up and down, will be good
if !cross_view?(x1,y1,x2,y2) && !diagonal_view?(x1,y1,x2,y2)
continue = false
end
elsif select_piece(x1,y1).class == Knight
continue = true
elsif select_piece(x1,y1).class == Bishop
if diagonal_view?(x1,y1,x2,y2)
continue = true
end
elsif select_piece(x1,y1).class == Rook
if cross_view?(x1,y1,x2,y2)
continue = true
end
elsif select_piece(x1,y1).class == Queen
if diagonal_view?(x1,y1,x2,y2) || cross_view?(x1,y1,x2,y2)
continue = true
end
elsif select_piece(x1,y1).class == King
if diagonal_view?(x1,y1,x2,y2) || cross_view?(x1,y1,x2,y2)
continue = true
end
end
continue
end
def delete_piece(x,y)
i = @pieces.find_index { |piece| piece.location[0] == x && piece.location[1] == y }
@pieces.delete_at(i)
end #delete_piece
def diagonal_view?(x1,y1,x2,y2)
if (x2-x1).abs == (y2-y1).abs
sight = true
x_squares = []
y_squares = []
if x1 < x2
((x1+1)..(x2-1)).to_a.each {|r| x_squares.push(r)}
swap1 = 1
else
((x2+1)..(x1-1)).to_a.each {|r| x_squares.push(r)}
swap1 = -1
end
if y1 < y2
((y1+1)..(y2-1)).to_a.each {|r| y_squares.push(r)}
swap2 = 1
else
((y2+1)..(y1-1)).to_a.each {|r| y_squares.push(r)}
swap2 = -1
end
if swap1 * swap2 == -1
y_squares.reverse!
end
x_squares.each_with_index do |x,i|
if select_piece(x,y_squares[i])
sight = false
end
end
else
sight = false
end
sight
end
def cross_view?(x1,y1,x2,y2)
if x2 == x1 || y2 == y1
sight = true
x_squares = []
y_squares = []
if x1 < x2
((x1+1)..(x2-1)).to_a.each do |r|
x_squares.push(r)
y_squares.push(y1)
end
elsif x2 < x1
((x2+1)..(x1-1)).to_a.each do |r|
x_squares.push(r)
y_squares.push(y1)
end
end
if y1 < y2
((y1+1)..(y2-1)).to_a.each do |r|
y_squares.push(r)
x_squares.push(x1)
end
elsif y2 < y1
((y2+1)..(y1-1)).to_a.each do |r|
y_squares.push(r)
x_squares.push(x1)
end
end
x_squares.each_with_index do |x,i|
if select_piece(x,y_squares[i])
sight = false
end
end
else
sight = false
end
sight
end
def white_pawn_helper(x1,y1,x2,y2)
allowed = true
if x1 != x2
if select_piece(x2,y2) && select_piece(x2,y2).color == "black"
allowed = true
else
allowed = false
end
elsif x1 == x2
if select_piece(x2,y2) && select_piece(x2,y2).color == "black"
allowed = false
else
allowed = true
end
end
end #white_pawn_helper
def black_pawn_helper(x1,y1,x2,y2)
allowed = true
#only allow a diagonal move if space is occupied by piece of opposite color
if x1 != x2
if select_piece(x2,y2) && select_piece(x2,y2).color == "white"
allowed = true
else
allowed = false
end
#only allow a straight move is space is unoccupied by piece of opposite color
elsif x1 == x2
if select_piece(x2,y2) && select_piece(x2,y2).color == "white"
allowed = false
else
allowed = true
end
end
end #black_pawn_helper
def player_in_check?
king_at_risk = false
@pieces.each do |piece|
if piece.color != @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |legal_move|
move_check = dummy_move(piece.location[0],piece.location[1],legal_move[0],legal_move[1])
if move_check[1].class == King
king_at_risk = true
end
end
end
end
king_at_risk
end
def puts_self_in_check?(x1,y1,x2,y2)
potential_game = Game.new
potential_game.turn = self.turn
potential_game.pieces = []
self.pieces.each do |piece|
potential_game.pieces.push(piece.clone)
end
potential_game.move_piece_in_shadow_game(x1,y1,x2,y2)
king_at_risk = false
potential_game.pieces.each do |piece|
if piece.color != @turn
potential_game.list_all_legal_moves(piece.location[0],piece.location[1]).each do |legal_move|
move_check = potential_game.dummy_move(piece.location[0],piece.location[1],legal_move[0],legal_move[1])
if move_check[1].class == King
king_at_risk = true
end
end
end
end
king_at_risk
end
def player_in_checkmate?
if player_in_check?
checkmate = true
@pieces.each do |piece|
if piece.color == @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |legal_move|
if !puts_self_in_check?(piece.location[0],piece.location[1],legal_move[0],legal_move[1])
checkmate = false
end
end
end
end
else
checkmate = false
end
checkmate
end
def stalemate?
if !player_in_check?
stalemate = true
@pieces.each do |piece|
if piece.color == @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |legal_move|
if !puts_self_in_check?(piece.location[0],piece.location[1],legal_move[0],legal_move[1])
stalemate = false
end
end
end
end
else
stalemate = false
end
stalemate
end
def pawn_conversion
#white pawns
@pieces.select do |piece|
if piece.class == Pawn && piece.color == "white" && piece.location[1] == 7
x = piece.location[0]
y = piece.location[1]
delete_piece(x,y)
choices = [Rook,Knight,Bishop,Queen]
p choices
pick = -1
until pick > -1 && pick < choices.length
puts 'pick with array number format what this piece is to become'.blue
pick = gets.chomp.to_i
end
@pieces.push(choices[pick].new([x,y],"white"))
end
end
#black pawns
@pieces.select do |piece|
if piece.class == Pawn && piece.color == "black" && piece.location[1] == 0
x = piece.location[0]
y = piece.location[1]
delete_piece(x,y)
choices = [Rook,Knight,Bishop,Queen]
p choices
pick = -1
until pick > -1 && pick < choices.length
puts 'pick what this piece is to become'.blue
pick = gets.chomp.to_i
end
@pieces.push(choices[pick].new([x,y],"black"))
end
end
end
def castle_right_white
allowed = false
#no pieces in between
if !select_piece(5,0) && !select_piece(6,0)
#king and rook havnt been moved
if !select_piece(4,0).moved? && !select_piece(7,0).moved?
#check other color pieces to confirm the middle squares are not threatened
allowed = true
@pieces.each do |piece|
if piece.color != @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |move|
if move == [5,0] || move == [6,0]
allowed = false
end
end
end
end
end
end
if allowed && !player_in_check?
select_piece(4,0).location = [6,0]
select_piece(7,0).location = [5,0]
end
end
def castle_left_white
allowed = false
#no pieces in between
if !select_piece(1,0) && !select_piece(2,0) && !select_piece(3,0)
#king and rook havnt been moved
if !select_piece(0,0).moved? && !select_piece(4,0).moved?
#check other color pieces to confirm the middle squares are not threatened
allowed = true
@pieces.each do |piece|
if piece.color != @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |move|
if move == [1,0] || move == [2,0] || move == [3,0]
allowed = false
end
end
end
end
end
end
#also cant castle if in check
if allowed && !player_in_check?
select_piece(4,0).location = [2,0]
select_piece(0,0).location = [3,0]
end
end
def castle_right_black
allowed = false
#no pieces in between
if !select_piece(5,7) && !select_piece(6,7)
#king and rook havnt been moved
if !select_piece(4,7).moved? && !select_piece(7,7).moved?
#check other color pieces to confirm the middle squares are not threatened
allowed = true
@pieces.each do |piece|
if piece.color != @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |move|
if move == [5,7] || move == [6,7]
allowed = false
end
end
end
end
end
end
#also cant castle if in check
if allowed && !player_in_check?
select_piece(4,7).location = [6,7]
select_piece(7,7).location = [5,7]
end
end
def castle_left_black
allowed = false
#no pieces in between
if !select_piece(1,7) && !select_piece(2,7) && !select_piece(3,7)
#king and rook havnt been moved
if !select_piece(0,7).moved? && !select_piece(4,7).moved?
#check other color pieces to confirm the middle squares are not threatened
allowed = true
@pieces.each do |piece|
if piece.color != @turn
list_all_legal_moves(piece.location[0],piece.location[1]).each do |move|
if move == [1,7] || move == [2,7] || move == [3,7]
allowed = false
end
end
end
end
end
end
#also cant castle if in check
if allowed && !player_in_check?
select_piece(4,7).location = [2,7]
select_piece(0,7).location = [3,7]
end
end
def get_castle_direction
puts "please choose left or right".blue
x = ""
until x == "left" || x == "right"
x = gets.chomp.to_s
end
x
end
def make_player_castle
success = false
direction = get_castle_direction
if @turn == "white"
if direction == "right" && castle_right_white
success = true
elsif direction == "left" && castle_left_white
success = true
end
elsif @turn == "black"
if direction == "right" && castle_right_black
success = true
elsif direction == "left" && castle_left_black
success = true
end
end
success
end
def get_player_turn_input
choices = ["move", "castle", "save game"]
input = ""
until choices.any? {|x| x == input}
puts "please choose an option:".blue
p choices
input = gets.chomp.to_s
end
input
end
def get_player_move
puts "create a move in format [x1,y1,x2,y2]".blue
puts "enter x1".blue
x1 = gets.chomp.to_i
puts "enter y1".blue
y1 = gets.chomp.to_i
puts "enter x2".blue
x2 = gets.chomp.to_i
puts "enter y2".blue
y2 = gets.chomp.to_i
input = [x1,y1,x2,y2]
until input.all? { |x| x.class == Fixnum && x > -1 && x < 9 }
puts "create a move in format [x1,y1,x2,y2]".blue
puts "enter x1".blue
x1 = gets.chomp.to_i
puts "enter y1".blue
y1 = gets.chomp.to_i
puts "enter x2".blue
x2 = gets.chomp.to_i
puts "enter y2".blue
y2 = gets.chomp.to_i
input = [x1,y1,x2,y2]
end
input
end
def make_player_move
moved = false
input = get_player_move
if input.any? {|x| x != nil }
if select_piece(input[0],input[1]) && select_piece(input[0],input[1]).color == @turn && move_piece(input[0],input[1],input[2],input[3])
moved = true
pawn_conversion
end
end
moved
end
def save
puts "what should we name your saved game?".blue
input = gets.chomp.to_s
save_game(self,input)
end
def save_game(game, name)
File.open("saved_games/#{name}.yaml", "w") do |file|
file.puts YAML::dump(game)
end
puts "game saved, should be here for you when you come back!".green
puts "saved game with name #{name}".green
end
def game_flow
until player_in_checkmate? || stalemate?
draw
puts "\n It is #{@turn}'s turn \n".green
if player_in_check?
puts "#{@turn} is in check!".red
end
input = get_player_turn_input
if input == "save game"
save
elsif input == "castle"
if make_player_castle
swap_turn
else
puts "not a legal move".red
end
elsif input == "move"
if make_player_move
swap_turn
else
puts "not a legal move".red
end
end
end #checkmate or stalemate?
if player_in_checkmate?
puts "#{@turn} is in checkmate! game over".yellow
exit
elsif stalemate?
puts "that's stalemate! game over".yellow
exit
end
end #game_flow
end #GAME
class Piece
attr_accessor :location, :moved, :shifts, :unicode
def initialize(location, color)
@location = location
@color = color
@moved = false
end
def moved?
if @moved
true
else
false
end
end
end
class Pawn < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265F}"
else
"\u{2659}"
end
end
def allowed_moves
allowed_squares = []
#creates shifts for each color
if @color == "black"
shifts = [[-1,-1],[1,-1],[0,-1],[0,-2]]
elsif @color == "white"
shifts = [[1,1],[-1,1],[0,1],[0,2]]
end
#removes 2 move if piece has been moved
if moved?
shifts.pop
end
#find squares in those shift rays
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end
class Knight < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265E}"
else
"\u{2658}"
end
end
def allowed_moves
allowed_squares = []
shifts = [[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1]]
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end
class Bishop < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265D}"
else
"\u{2657}"
end
end
def allowed_moves
allowed_squares = []
shifts = []
#creates diagonal shifts
8.times do |m|
if m != 0
shifts.push([-m,-m])
shifts.push([-m,m])
shifts.push([m,-m])
shifts.push([m,m])
end
end
#find squares in those shift rays
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end #BISHOP
class Rook < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265C}"
else
"\u{2656}"
end
end
def allowed_moves
allowed_squares = []
shifts = []
#creates cross shifts
8.times do |m|
if m != 0
shifts.push([0,-m])
shifts.push([0,m])
shifts.push([-m,0])
shifts.push([m,0])
end
end
#find squares in those shift rays
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end # ROOK
class Queen < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265B}"
else
"\u{2655}"
end
end
def allowed_moves
allowed_squares = []
shifts = []
#creates cross shifts
8.times do |m|
if m != 0
shifts.push([0,-m])
shifts.push([0,m])
shifts.push([-m,0])
shifts.push([m,0])
end
end
#creates diagonal shifts
8.times do |m|
if m != 0
shifts.push([-m,-m])
shifts.push([-m,m])
shifts.push([m,-m])
shifts.push([m,m])
end
end
#find squares in those shift rays
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end
class King < Piece
attr_accessor :color
def unicode
if @color == "white"
"\u{265A}"
else
"\u{2654}"
end
end
def allowed_moves
allowed_squares = []
shifts = [[0,1],[0,-1],[1,0],[1,-1],[1,1],[-1,0],[-1,1],[-1,-1]]
#find squares in those shift rays
shifts.each do |r|
r[0] += @location[0]
r[1] += @location[1]
if r[0] > -1 && r[0] < 8 && r[1] > -1 && r[1] < 8
allowed_squares.push(r)
end
end
allowed_squares
end
end
def startup_game
puts 'hello, welcome to chess!'.cyan
choice = 0
until choice == 1 || choice == 2
puts "Please select a choice"
puts "1) New Game \n2) Load Game".green
choice = gets.chomp.to_i
end
if choice == 1
game = Game.new
game.game_flow
elsif choice == 2
chosen_game = -1
until chosen_game > -1 && chosen_game < (list_saved_games.length + 1)
puts "please choose a game"
list_saved_games
chosen_game = gets.chomp.to_i
end
chosen_game_string = list_saved_games[chosen_game-1]
game = load_game(chosen_game_string)
puts "nice, you loaded a game"
game.game_flow
end
end
def list_saved_games
games = Dir["./saved_games/*.yaml"]
games.map! { |x| x.scan(/(?<=saved_games\/)(.*)(?=\.yaml)/) }
games.flatten!
games.each_with_index {|x,i| puts "#{i+1}) #{x} \n"}
end
def load_game(name)
array = []
$/="\n\n"
File.open("saved_games/#{name}.yaml", "r").each do |object|
array << YAML::load(object)
end
array[0]
end
| true |
76d5a6dba0c3874094b55cc9de7bab431d4a5953 | Ruby | jiyaping/rigrate | /lib/rigrate/parser.rb | UTF-8 | 6,681 | 2.71875 | 3 | [] | no_license | # encoding : utf-8
module Rigrate
class Parser
include Migration
module TokenType
FROM = :FROM_TAG
TO = :TO_TAG
UNION = :UNION_TAG
JOIN = :JOIN_TAG
MINUS = :MINUS_TAG
ON = :ON_TAG
USING = :USING_TAG
RUBY_STR = :RUBY_STR_TAG
end
module StringType
DOUBLE_QUOTE = :DQ_STR
SINGLE_QUOTE = :SQ_STR
end
module LexStatus
INIT = :INIT_STATUS
IN_KEYWORD = :IN_KEYWORD_STATUS
IN_RUBY_CODE= :IN_RUBY_CODE_STATUS
IN_RUBY_STR = :IN_RUBY_STR_STATUS
IN_COMMENT = :IN_COMMENT_STATUS
end
Token = Struct.new(:type, :value)
attr_accessor :tokens
##
# load script str -> tokens
# TODO there is a bug need to fixed, when comment str include FROM key word will praser error.
def lex(str)
status = LexStatus::INIT
@tokens = []
t_token = ''
t_sub_token = ''
string_type = StringType::DOUBLE_QUOTE
char_arr = str.chars
loop do
c = char_arr.shift
if c == nil
token = Token.new TokenType::RUBY_STR, t_token
@tokens << token
break
end
if status == LexStatus::IN_KEYWORD && c =~ /\s/
if is_a_token?(t_token)
@tokens << (Token.new get_token_type(t_token), t_token)
t_token = ''
t_sub_token = ''
status = LexStatus::INIT
next
else
status = LexStatus::IN_RUBY_CODE
end
end
if status != LexStatus::IN_RUBY_CODE && status != LexStatus::IN_RUBY_STR
(status = LexStatus::INIT && next) if c =~ /\s/
end
t_token << c
t_sub_token << c
if status == LexStatus::IN_RUBY_CODE ||
status == LexStatus::IN_KEYWORD
if c == '"'
string_type = StringType::DOUBLE_QUOTE
status = LexStatus::IN_RUBY_STR
next
elsif c == "'"
string_type = StringType::SINGLE_QUOTE
status = LexStatus::IN_RUBY_STR
next
end
end
if status == LexStatus::IN_RUBY_STR
is_matched = false
if (string_type == StringType::DOUBLE_QUOTE && c == '"') ||
(string_type == StringType::SINGLE_QUOTE && c == "'")
is_matched = true
end
if is_matched && t_token[-1] != "\\"
status = LexStatus::IN_RUBY_CODE
elsif c =~ /\s/
t_sub_token = ''
end
end
if status == LexStatus::IN_RUBY_CODE && c =~ /\s/
if is_a_token? t_sub_token
token = Token.new TokenType::RUBY_STR, t_token.sub(/#{t_sub_token}$/, '')
@tokens << token
token = Token.new get_token_type(t_sub_token), t_sub_token
@tokens << token
status = LexStatus::INIT
t_token = ''
end
t_sub_token = ''
end
if status == LexStatus::INIT
status = LexStatus::IN_KEYWORD
end
end
self
end
def parsing
full_parse tokens.dup
end
#private
def full_parse(tks)
while tks.size > 0
parse_rs_or_migrate_exp(tks)
end
end
def parse_rs_or_migrate_exp(tks)
token = tks.shift
if token.type == TokenType::RUBY_STR
v1 = self_eval token.value
else
tks.unshift token
v1 = parse_migrate_exp(tks)
end
v1
end
def parse_migrate_exp(tks)
token = tks.shift
if token.type == TokenType::FROM
v1 = parse_operate_exp(tks)
sub_token = tks.shift
if sub_token.type == TokenType::TO
v2 = parse_rs_exp(tks)
v3 = parse_condition_exp(tks)
v4 = parse_using_exp(tks)
migrate(v1, v2, v3, v4)
# sub_token_1 = tks.shift
# if not sub_token_1.nil?
# if sub_token_1.type == TokenType::ON
# cond = tks.shift
# migrate(v1, v2, cond)
# else
# tks.unshift sub_token_1
# migrate(v1, v2)
# end
# else
# migrate(v1, v2)
# end
else
raise ParserError.new("Syntax Error: need TO expression")
end
end
end
def parse_operate_exp(tks)
v1 = parse_rs_exp(tks)
while true
token = tks.shift
if token.type != TokenType::UNION &&
token.type != TokenType::JOIN &&
token.type != TokenType::MINUS
tks.unshift token
break
end
v2 = parse_rs_exp(tks)
if token.type == TokenType::UNION
v1 = union(v1, v2)
elsif token.type == TokenType::MINUS
v1 = minus(v1, v2)
elsif token.type == TokenType::JOIN
sub_token = tks.shift
if not sub_token.nil?
if sub_token.type == TokenType::ON
cond = tks.shift
v1 = join(v1, v2, cond.value)
else
tks.unshift sub_token
v1 = join(v1, v2)
end
else
v1 = join(v1, v2)
end
end
end
v1
end
def parse_condition_exp(tks)
token = tks.shift
return if token.nil?
if token.type == TokenType::ON
v1 = parse_rs_exp(tks)
if v1.nil?
raise ParserError.new("ON expression should end with a [RUBY_STR]")
end
else
tks.unshift token
return
end
v1
end
def parse_using_exp(tks)
token = tks.shift
return if token.nil?
if token.type == TokenType::USING
v1 = parse_rs_exp(tks)
if v1.nil?
raise ParserError.new("USING expression should end with a [RUBY_STR]")
end
else
tks.unshift token
return
end
v1
end
# TODO return value should change
def parse_rs_exp(tks)
token = tks.shift
return if token.nil?
if token.type == TokenType::RUBY_STR
return token.value
else
raise ParserError.new("Invalid Syntax")
end
end
def is_a_token?(str)
TokenType.constants.include? str.strip.upcase.to_sym
end
def get_token_type(str)
TokenType.const_get(str.strip.upcase)
end
end
end | true |
1b6802a049b23466cd3ecbc474e6bf5edefae52c | Ruby | Rodrigoefo/DesafioCiclosP | /solo_pares.rb | UTF-8 | 258 | 3.5 | 4 | [] | no_license | ##Crea un programa llamado solo_pares.rb que muestre los primeros n números pares, donde n
##es ingresado por el usuario.
datos=ARGV[0].to_i
i=0
contador=0
while contador<datos
if i.even?
puts i
i+=1
contador+=1
else
i+=1
end
end
| true |
a50e462821bd1ff5babe2ce04f728efe2e326783 | Ruby | thorncp/raspi-simon | /button.rb | UTF-8 | 347 | 3.125 | 3 | [] | no_license | require "pi_piper"
class Button
attr_reader :pin_number
def initialize(pin_number)
@pin_number = pin_number
end
def pushed(&block)
PiPiper.after pin: pin_number, goes: :low do
block.call(self)
end
end
def released(&block)
PiPiper.after pin: pin_number, goes: :high do
block.call(self)
end
end
end
| true |
ff611effce1f61f72e367aaa7bbcaa9b9f152dd4 | Ruby | rubyunworks/ko | /lib/ko/context.rb | UTF-8 | 1,884 | 2.96875 | 3 | [
"ISC",
"Apache-2.0"
] | permissive | module KO
# DEPRECATE: Use Test module instead.
def self.contexts
Test.constexts
end
# DEPRECATE: Use Test module instead.
def self.context(label=nil, &block)
Test.context(label, &block)
end
# Context defines a system "state". A context might specify
# a set of requirments, database fixtures, objects, mocks,
# or file system setups --any presets that need to be in
# place for a testcase to operate.
#
# Test.context "Instance of Dummy String" do
#
# before :all do
# @string = "dummy"
# end
#
# end
#
# NOTE: Some contexts cannot be fully isolated. For instance,
# once a library is required it cannot be unrequired.
class Context < Module
# Initialize new Context.
def initialize(label=nil, &block)
@label = label
super(&block)
end
# The name of the context.
attr :label
# Options such as pwd, and stage.
#attr_accessor :options
# Define a per-test setup procedure.
def before(type=:each, &block)
raise ArgumentError, "invalid before-type #{type}" unless [:each, :all].include?(type)
type_method = "before_#{type}"
remove_method(type_method) rescue nil #if method_defined?(:setup)
define_method(type_method, &block)
end
# Define a per-test teardown procedure.
def after(type=:each, &block)
raise ArgumentError, "invalid after-type #{type}" unless [:each, :all].include?(type)
type_method = "after_#{type}"
remove_method(type_method) rescue nil #if method_defined?(:teardown)
define_method(type_method, &block)
end
# DEPRECATE: Use #before instead.
def setup(&block)
before(:each, &block)
end
# DEPRECATE: Use #after instead.
def teardown(&block)
after(:each, &block)
end
alias_method :Before, :before
alias_method :After, :after
end
end
| true |
a71a7d24e761743cb93f70330f6af0564a89d8d5 | Ruby | irwanhub2016/dkatalis | /API/spec/api_spec.rb | UTF-8 | 2,570 | 2.65625 | 3 | [] | no_license | require 'api_base'
require_relative "../lib/json_comparison"
include JsonComparison
describe ApiBase do
before(:each) do
@url_target = "https://reqres.in/api/users/"
@request_method = "Get"
end
it 'Test API with two JSON data for static user id' do
result_json_1 = ApiBase.send_api(@url_target, @request_method, "2")
result_json_2 = ApiBase.send_api(@url_target, @request_method, "2")
expect(boolean=compare_json(result_json_1,result_json_2)).to be true
p "Compare request user ID #{result_json_1['data']['id']} and #{result_json_2['data']['id']}: #{boolean}"
p "success run the first test scenario #{boolean}"
end
it 'Test API with two JSON data for single loop' do
# test api with random user id as parameter in endpoint. For the exist user data only 1-12
result_json_1 = ApiBase.send_api(@url_target, @request_method, rand(1...12).to_s)
result_json_2 = ApiBase.send_api(@url_target, @request_method, rand(1...12).to_s)
if ApiBase.validate_id(result_json_1['data']['id'],result_json_2['data']['id'])
expect(boolean=compare_json(result_json_1,result_json_2)).to be true
else
expect(boolean=compare_json(result_json_1,result_json_2)).to be false
end
p "Compare request user ID #{result_json_1['data']['id']} and #{result_json_2['data']['id']}: #{boolean}"
p "success run the second test scenario #{boolean}"
end
it "Test API with two JSON data for #{ENV['LOOP']} loop" do
# test api with random user id as parameter in endpoint. For the exist user data only 1-12
ENV['LOOP'].to_i.times do
result_json_1 = ApiBase.send_api(@url_target, @request_method, rand(1...12).to_s)
result_json_2 = ApiBase.send_api(@url_target, @request_method, rand(1...12).to_s)
if ApiBase.validate_id(result_json_1['data']['id'],result_json_2['data']['id'])
expect(boolean=compare_json(result_json_1,result_json_2)).to be true
else
expect(boolean=compare_json(result_json_1,result_json_2)).to be false
end
p "Compare request user ID #{result_json_1['data']['id']} and #{result_json_2['data']['id']}: #{boolean}"
end
p 'success run the third test scenario'
end
it 'Test API with empty JSON data' do
result_json_1 = []
result_json_2 = []
expect { compare_json(result_json_1,result_json_2) }.to raise_error(TypeError)
p 'success run the fourth test scenario'
end
it 'Test API with nil JSON data' do
result_json_1 = ""
result_json_2 = ""
expect { compare_json(result_json_1,result_json_2) }.to raise_error(TypeError)
p 'success run the fifth test scenario'
end
end | true |
36adc9afa0789dcf648f2f05b8a8dfd0860d5551 | Ruby | Tshamp7/App_Academy_Classwork | /two_sum_bigO/two_sum.rb | UTF-8 | 902 | 3.8125 | 4 | [] | no_license | require 'byebug'
nums = [0, 1, 5, 7]
#the time complexity of this is O(n^2)
#O(1) constant space
def bad_two_sum?(arr, target)
arr.each_with_index do |num, i|
arr.each_with_index do |num2, j|
next if i == j
return true if num + num2 == target
end
end
false
end
#p bad_two_sum?(nums, 6) > true
#p bad_two_sum?(nums, 10) > false
#O(nlogn) linearithmic time
#O(n) linear space
def okay_two_sum?(arr, target)
sorted = arr.sort
sorted.each_with_index do |el, i|
match_index = sorted.bsearch_index { |x| (target - el) == x }
return true if match_index && match_index != i
end
false
end
#p okay_two_sum?(nums, 6)
#O(n) linear time
#O(n) linear space
def best_two_sum?(arr, target_sum)
nums_hash = {}
arr.each do |el|
return true if nums_hash[target_sum - el]
nums_hash[el] = true
end
false
end
#p best_two_sum?(nums, 6) | true |
767c565c158c54065e5f1d1362c4e6b84bf030dd | Ruby | MrRogerino/phase-0-tracks | /ruby/shout.rb | UTF-8 | 608 | 3.890625 | 4 | [] | no_license | =begin
old code
module Shout
def self.yell_angrily(words)
words + "!!!" + " :("
end
def self.yell_happily(words)
words + " is awesome!" + ":^)"
end
end
=end
#mixin module
module Shout
def yell_angrily(words)
words + "!!!" + " :("
end
def yell_happily(words)
words + " is awesome!" + ":^)"
end
end
class Donald
include Shout
end
class Trump
include Shout
end
#driver
donald = Donald.new
donald.yell_angrily("obama")
donald.yell_happily("golf")
trump = Trump.new
trump.yell_angrily("hillary")
trump.yell_happily("putin")
| true |
a6bb8cfc36c1cd12ba0307dc06e0ee487ea5b117 | Ruby | jhnnyk/LS120 | /lesson_1/chap1_exercises.rb | UTF-8 | 189 | 3.375 | 3 | [] | no_license | # -----------
# Exercise 2
module Run
def run(speed)
puts "I run #{speed}!"
end
end
# ------------
# Exercise 1
class Runner
include Run
end
john = Runner.new
john.run("fast")
| true |
d8bbbfd51ed39b8c6ababf8b9297941a2caa6d78 | Ruby | jemadduxVault/Ruby | /helloworld.rb | UTF-8 | 204 | 2.921875 | 3 | [] | no_license | puts "Hello World!"
puts "Good-bye."
puts "I like" + "apple pie."
puts "I like " + "apple pie."
puts "blink " * 4
puts "12 " + "12"
puts "You're swell!"
puts 'You\'re swell!'
puts "You\'re swell!" | true |
18c10624dc3b3d6ae88495f2024fcc68c43ee3eb | Ruby | dhalverson/backend_module_0_capstone | /day_6/exercises/burrito.rb | UTF-8 | 774 | 4.09375 | 4 | [] | no_license | # Add the following methods to this burrito class and
# call the methods below the class:
# 1. add_topping
# 2. remove_topping
# 3. change_protein
class Burrito
attr_accessor :protein, :base, :toppings
def initialize(protein, base, toppings)
@protein = protein
@base = base
@toppings = toppings
end
def add_topping(topping)
@toppings << topping
end
def remove_topping(topping)
@toppings.delete(topping)
end
end
dinner = Burrito.new("Beans", "Rice", ["cheese", "salsa", "guacamole"])
p dinner.protein
p dinner.base
p dinner.toppings
# 1. add topping
dinner.add_topping("peppers")
# 2. remove topping
dinner.remove_topping("salsa")
# 3. change protein
p dinner.protein = "Chicken"
p dinner.protein
p dinner.base
p dinner.toppings
| true |
2f630205afc971ae51296c201a2cc6e11cfe23c2 | Ruby | lsantosc/metropoli | /test/models/test_city.rb | UTF-8 | 1,857 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'helper'
class TestCity < ActiveSupport::TestCase
test 'like method should find cities by name' do
assert_equal Metropoli::CityModel.like('Monterrey').count, 1
end
test 'like method should find cities with %' do
assert_equal Metropoli::CityModel.like('mo').count, 1
end
test 'like method should return all cities with blank' do
assert_equal Metropoli::CityModel.like('').count, Metropoli::CityModel.count
end
test 'like method should return all cities with nil' do
assert_equal Metropoli::CityModel.like(nil).count, Metropoli::CityModel.count
end
test 'autocomplete method should find cities with state and country or without them' do
assert_equal Metropoli::CityModel.autocomplete('Monterrey, NLE').count, 1
assert_equal Metropoli::CityModel.autocomplete('Monterrey, NLE, MX').count, 1
assert_equal Metropoli::CityModel.autocomplete('Monterrey').count, 1
end
test 'autocomplete method should find cities with state and country with full names' do
assert_equal Metropoli::CityModel.autocomplete('Monterrey, Nuevo Leon').count, 1
assert_equal Metropoli::CityModel.autocomplete('Monterrey, Nuevo Leon, Mexico').count, 1
assert_equal Metropoli::CityModel.autocomplete('Monterrey').count, 1
end
test 'autocomplete method should scope city with the provided state or country' do
assert_equal Metropoli::CityModel.autocomplete('Monterrey, NT').count, 0
assert_equal Metropoli::CityModel.autocomplete('Monterrey, NLE, BO').count, 0
end
test 'autocomplete method should return all cities with blank' do
assert_equal Metropoli::CityModel.like('').count, Metropoli::CityModel.count
end
test 'autocomplete method should return all cities with nil' do
assert_equal Metropoli::CityModel.like(nil).count, Metropoli::CityModel.count
end
end
| true |
bee4d89234bbb3d548acb44be0a428bf8b9992a6 | Ruby | harhogefoo/AtCoder_Ruby | /ABC036/CCCC.rb | UTF-8 | 247 | 3.21875 | 3 | [] | no_license | n = gets.to_i
array = Array.new
n.times do |i|
array.push(gets.to_i)
end
sorted = array.sort
tbl = Hash.new
prev = -1
idx = -1
sorted.each do |num|
tbl[num] = (idx += 1) if num != prev
prev = num
end
array.each do |i|
puts tbl[i]
end
| true |
5a08a1679a5f8e8535b250168aa8eaf89ab2f84a | Ruby | Filmscore88/ruby-music-library-cli-online-web-ft-031119 | /lib/song.rb | UTF-8 | 963 | 3.21875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Song
extend Concerns::Findable
attr_accessor :name , :artist, :genre, :song_info
@@all=[]
def initialize(name, artist=nil, genre=nil)
@name=name
self.artist= artist if artist !=nil
self.genre= genre if genre !=nil
end
def self.all
@@all
end
def artist=(artist)
@artist=artist
@artist.add_song(self)
end
def self.destroy_all
@@all.clear
end
def genre=(genre)
@genre=genre
genre.add_song(self)
end
def save
@@all << self
end
def self.create(name)
created_song= self.new(name)
created_song.save
created_song
end
def self.new_from_filename(filename)
@song_info = filename.chomp(".mp3").split(" - ")
artist=@song_info[0]
genre=@song_info[2]
song=self.new(@song_info[1])
song.artist= Artist.find_or_create_by_name(artist)
song.genre= Genre.find_or_create_by_name(genre)
song
end
def self.create_from_filename(filename)
self.new_from_filename(filename).save
end
end | true |
86df02ea39b75e88b59a975c3c3a64e4d6541157 | Ruby | vit/tj | /templatejuggler.rb | UTF-8 | 4,776 | 2.75 | 3 | [] | no_license | # coding: UTF-8
%w[haml yaml].each {|r| require r}
def YAML.load_file( filepath )
File.open( filepath, "r:utf-8" ) do |f|
load( f )
end
end
class TemplateJuggler
# Экземпляр этого класса работает загрузчиком шаблонов, считая, что id шаблона соответствует именем файла
# (с подкаталогами) внутри заданного каталога.
class SimpleLoader
attr_accessor :path
def initialize path='./views'
@path = path
end
def get_template id
path = File.join(@path, "#{id}.haml")
File::exists?(path) && File::readable?(path) ? File::open(path, 'r:utf-8') { |file| file.read } : nil
end
def get_locale lang, id
lang = [lang.to_s] unless lang.is_a? Array
locale_data = nil
-> s {
locale_data = lang.inject({}) do |acc,l|
path = File.join(@path, "#{id}.#{l}.yaml")
#data = File::exists?(path) && File::readable?(path) ? YAML.load_file( path ) : nil
data = File::exists?(path) && File::readable?(path) ? File::open(path, 'r:utf-8') { |file| YAML.load file.read } : nil
data.is_a?(Hash) ? data.merge(acc) : acc
end unless locale_data
locale_data[s.to_s] if locale_data
}
end
end
# Шаблоны обрабатываются в контексте объекта этого класса, если не задано иное.
# Через переменные этого объекта шаблон может передать данные следующим шаблонам.
class Scope
# Сюда шаблон может записать (для TJ) id шаблона, который должен быть обработан следующим
# (если не годится стандартный порядок -- с перемещением по каталогам снизу вверх
# и использованием шаблонов autohandler)
# !!! TJ пока не умеет обрабатывать относительный путь.
attr_accessor :next_template
# wrapper (обертка) -- тоже шаблон, если есть он должен быть применен к результату работы
# текущего шаблона перед применением next_template.
# Таким образом, один и тот же шаблон-wrapper может использоваться в нескольких иерархиях шаблонов.
# !!! Не реализовано.
attr_accessor :wrapper
# Сюда TJ записывает id шаблона, который обрабатывается в настоящий момент
# (на случай, если в процессе обработки шаблона понадобится его идентификатор).
attr_accessor :current_template
# Это если изнутри шаблона потребуется отрисовать другой шаблон
attr_accessor :callback_machine
attr_accessor :lang
attr_accessor :locale
def initialize machine=nil, args = {}
@args = args
@callback_machine = machine
end
def call id, args={}
@callback_machine.render id, (@args.merge args) if callback_machine.respond_to?(:render)
end
def gettext s
(@locale && @locale[s]) ? @locale[s] : s.to_s
end
alias_method :_, :gettext
end
# Объект, имеющий метод get и возвращающий шаблон по заданному id.
# Для самой TJ не важно, где именно хранятся шаблоны.
attr_accessor :template_loader
attr_accessor :locale_loader
def initialize loader=nil, locale=nil
@template_loader = template_loader || SimpleLoader.new
@locale_loader = locale_loader || @template_loader
end
def render id, args={}
id = id.to_s # id -- строка, имеющая вид полного пути ( "/aaa/bbb/ccc/fff" )
id_a = id.split '/'
base_a = id_a.dup
base_a.pop
scope = args[:scope] || Scope.new(self, args)
scope.lang = args[:lang] if args[:lang]
locals = args[:locals] || {}
body = ''
loop do
id = id_a.join('/')
next_id = nil
templ = @template_loader.get_template id
if templ
scope.locale = @locale_loader.get_locale scope.lang, id
scope.current_template = id
scope.next_template = nil
body = Haml::Engine.new(templ, :encoding => 'utf-8').render(scope, locals) { body }.force_encoding('utf-8')
scope.current_template = nil
next_id = scope.next_template if scope.respond_to?(:next_template)
end
if 'autohandler' === id_a.last
base_a.pop
break if base_a.empty?
end
id_a = next_id ? next_id.split('/') : (base_a + ['autohandler'])
end
body
end
end
TJ = TemplateJuggler
| true |
8d9d19c445a6368d86a961b0110721465f174148 | Ruby | rmascarenhas/ooo | /Ruby/url_tracker/test/test_periodic.rb | UTF-8 | 1,422 | 2.65625 | 3 | [
"MIT"
] | permissive | require_relative 'test_helper'
class TestPeriodic < MiniTest::Unit::TestCase
def setup
@p = UrlTracker::Periodic.new
end
def teardown
@p.stop
end
def test_every_with_symbol_argument
assert_equal 60, @p.every(:minute) {}
end
def test_every_with_hour_symbol
assert_equal 60*60, @p.every(:hour) {}
end
def test_two_minutes
assert_equal 2*60, @p.every(2, :minutes) {}
end
def test_two_hours
assert_equal 2*60*60, @p.every(2, :hours) {}
end
def test_invalid_first_argument
assert_raises(RuntimeError) do
@p.every(:invalid) {}
end
end
def test_invalid_time_unit
assert_raises(RuntimeError) do
@p.every(2, :invalid) {}
end
end
def test_add_named_task
@p.task("dummy").every(:minute) {}
assert_equal ["dummy"], @p.named_tasks
end
def test_remove_named_task
@p.task("dummy").every(:minute) {}
@p.remove_task("dummy")
assert_empty @p.named_tasks
end
def test_remove_inexistent_task
assert_raises(RuntimeError) do
@p.remove_task("dummy")
end
end
def test_restart
@p.stop
assert !@p.running?
@p.restart
assert @p.running?
end
def test_running
assert @p.running?, 'Expected Periodic to be running when `stop` was not called.'
end
def test_running_when_asked_to_stop
@p.stop
assert !@p.running?, 'Expected Periodic to stop'
@p.restart
end
end
| true |
8af70ae0ede2ce4305771b40d779d7838e66b337 | Ruby | ZsoltFabok/project_euler | /spec/project_euler/problems/problem_16_spec.rb | UTF-8 | 639 | 2.8125 | 3 | [] | no_license | require 'spec_helper'
describe Problems::Problem16 do
context "#calculate" do
let(:arrays) {double}
let(:number) {double}
subject(:problem) {Problems::Problem16.new(arrays, number)}
it "returns 26 as the sum of the digits of the number 2^15" do
expect(arrays).to receive(:sum).with([3,2,7,6,8]).and_return(26)
expect(number).to receive(:digits).with(32768).and_return([3,2,7,6,8])
expect(problem.calculate(15)).to eq 26
end
end
context "#execute" do
it "returns 1366 as the sum of the digits of the number 2^1000" do
expect(Problems::Problem16.execute).to eq 1366
end
end
end | true |
baa43aa13e9504ade261ef89f8ae2448e7ed4e17 | Ruby | uehara-delta/triangle | /spec/triangle_spec.rb | UTF-8 | 1,046 | 3.015625 | 3 | [] | no_license | # coding: utf-8
require File.expand_path(File.dirname(__FILE__) + '/../triangle')
describe Triangle do
specify { expect(Triangle.guess(2, 3, 4)).to eq "不等辺三角形ですね!" }
specify { expect(Triangle.guess(2, 2, 1)).to eq "二等辺三角形ですね!" }
specify { expect(Triangle.guess(1, 1, 1)).to eq "正三角形ですね!" }
specify { expect(Triangle.guess(1, 2, 3)).to eq "三角形じゃないです><" }
# 追加テストケース
specify("順序は問わない") { expect(Triangle.guess(2, 1, 2)).to eq "二等辺三角形ですね!" }
specify("直角三角形") do
expect(Triangle.guess(3, 4, 5)).to eq "直角三角形ですね!"
expect(Triangle.guess(3, 5, 4)).to eq "直角三角形ですね!"
end
# 辺の長さは整数なので直角二等辺三角形は判定不要
specify("長さが0") { expect(Triangle.guess(0, 3, 4)).to eq "三角形じゃないです><" }
specify("負の数") { expect(Triangle.guess(-1, 3, 4)).to eq "三角形じゃないです><" }
end
| true |
3e1309a48278ee4b2d326696eb4a3b69150cc0cd | Ruby | sds/slim-lint | /lib/slim_lint/sexp.rb | UTF-8 | 3,041 | 3.359375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module SlimLint
# Symbolic expression which represents tree-structured data.
#
# The main use of this particular implementation is to provide a single
# location for defining convenience helpers when operating on Sexps.
class Sexp < Array
# Stores the line number of the code in the original document that
# corresponds to this Sexp.
attr_accessor :line
# Creates an {Sexp} from the given {Array}-based Sexp.
#
# This provides a convenient way to convert between literal arrays of
# {Symbol}s and {Sexp}s containing {Atom}s and nested {Sexp}s. These objects
# all expose a similar API that conveniently allows the two objects to be
# treated similarly due to duck typing.
#
# @param array_sexp [Array]
def initialize(array_sexp)
array_sexp.each do |atom_or_sexp|
case atom_or_sexp
when Array
push Sexp.new(atom_or_sexp)
else
push SlimLint::Atom.new(atom_or_sexp)
end
end
end
# Returns whether this {Sexp} matches the given Sexp pattern.
#
# A Sexp pattern is simply an incomplete Sexp prefix.
#
# @example
# The following Sexp:
#
# [:html, :doctype, "html5"]
#
# ...will match the given patterns:
#
# [:html]
# [:html, :doctype]
# [:html, :doctype, "html5"]
#
# Note that nested Sexps will also be matched, so be careful about the cost
# of matching against a complicated pattern.
#
# @param sexp_pattern [Object,Array]
# @return [Boolean]
def match?(sexp_pattern)
# Delegate matching logic if we're comparing against a matcher
if sexp_pattern.is_a?(SlimLint::Matcher::Base)
return sexp_pattern.match?(self)
end
# If there aren't enough items to compare then this obviously won't match
return false unless sexp_pattern.is_a?(Array) && length >= sexp_pattern.length
sexp_pattern.each_with_index do |sub_pattern, index|
return false unless self[index].match?(sub_pattern)
end
true
end
# Returns pretty-printed representation of this S-expression.
#
# @return [String]
def inspect
display
end
protected
# Pretty-prints this Sexp in a form that is more readable.
#
# @param depth [Integer] indentation level to display Sexp at
# @return [String]
def display(depth = 1) # rubocop:disable Metrics/AbcSize
indentation = ' ' * 2 * depth
output = '['.dup
each_with_index do |nested_sexp, index|
output << "\n"
output += indentation
output +=
if nested_sexp.is_a?(SlimLint::Sexp)
nested_sexp.display(depth + 1)
else
nested_sexp.inspect
end
# Add trailing comma unless this is the last item
output += ',' if index < length - 1
end
output << "\n" << ' ' * 2 * (depth - 1) unless empty?
output << ']'
output
end
end
end
| true |
c67a5baaf1b407e3f3aa079d68c1f8266cedc538 | Ruby | dmitrokh/Ruby_on_Rails | /app/controllers/main_controller.rb | UTF-8 | 934 | 2.625 | 3 | [] | no_license | require_relative "../services/weather_service"
class MainController < ApplicationController
def callForm
render "main/index"
end
def index
cityToCheck = params[:city]
if City.all[cityToCheck.to_sym] == nil #no requested city exists in hash yet
@message = 'this city not in DB, create it'
render 'cities/new'
else
if @w
@temperature = (9 / 5) * (@w[:temperature] - 273) + 32
end
#city.find_by(name: cityToCheck)
end
def callView
render 'cities/view'
end
#if @w
# @temperature = (9 / 5) * (@w[:temperature] - 273) + 32
#
# city = City.new(
# name: params[:city],
# temperature: @temperature, # Using the converted temperature
# description: @w[:description]
# )
# Save the city so that it's in City.all
# city.save
#end
end
end
| true |
703e08a34e4ed702dd19044d5fc8f56bb7d99655 | Ruby | CartoDB/cartodb | /spec/models/carto/log_spec.rb | UTF-8 | 10,808 | 2.609375 | 3 | [
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
] | permissive | require 'spec_helper_unit'
describe Carto::Log do
describe '#basic' do
it 'checks basic operations' do
type = Carto::Log::TYPE_DATA_IMPORT
text1 = 'test'
text2 = 'anothertest'
timestamp = Time.now.utc
log = Carto::Log.new({ type: type })
log.append(text1, false, timestamp)
log.append(text2, false, timestamp)
# Only stores now upon explicit change
log.store
log_id = log.id
log = Carto::Log.find(log_id)
log.id.should eq log_id
log.type.should eq type
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::END_OF_LOG_MARK
end
end
describe '#circular buffer logic' do
it 'checks that buffer half works as expected' do
max_entries_per_half = 2
timestamp = Time.now.utc
text1 = '1'
text2 = '2'
text3 = '3'
text4 = '4'
text5 = '5'
text6 = '6'
Carto::Log.any_instance.stubs(:half_max_size).returns(max_entries_per_half)
log = Carto::Log.new_data_import
# Fixed half
log.append(text1, false, timestamp)
log.append(text2, false, timestamp)
# circular half
10.times do
log.append('to be deleted', false, timestamp)
end
log.append(text3, false, timestamp)
log.append(text4, false, timestamp)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
Carto::Log::END_OF_LOG_MARK
log.append(text5, false, timestamp)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
Carto::Log::END_OF_LOG_MARK
log.append(text6, false, timestamp)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text6) +
Carto::Log::END_OF_LOG_MARK
end
it 'checks that loading a log with existing entries works' do
max_entries_per_half = 2
timestamp = Time.now.utc
text1 = 'aaa'
text2 = 'bbb'
text3 = '3.4'
text4 = '5 6 7 8'
text5 = 'five'
text6 = 'six'
Carto::Log.any_instance.stubs(:half_max_size).returns(max_entries_per_half)
log = Carto::Log.new_data_import
log.append(text1, false, timestamp)
log.append(text2, false, timestamp)
log.append(text3, false, timestamp)
log.append(text4, false, timestamp)
log.store
# reload
log = Carto::Log.find(log.id)
# collect doesn't beautifies
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
Carto::Log::END_OF_LOG_MARK
# More tests
log = Carto::Log.new_data_import
log.append(text1, false, timestamp)
log.append(text2, false, timestamp)
log.append(text3, false, timestamp)
log.store
log = Carto::Log.find(log.id)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
Carto::Log::END_OF_LOG_MARK
# Check that new entries are added correctly
log.append(text4, false, timestamp)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
Carto::Log::END_OF_LOG_MARK
log.append(text5, false, timestamp)
log.append(text6, false, timestamp)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text6)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text6) +
Carto::Log::END_OF_LOG_MARK
log = Carto::Log.new_data_import
log.append(text1, false, timestamp)
log.store
log = Carto::Log.find(log.id)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
Carto::Log::END_OF_LOG_MARK
# This test checks that old logs with more lines than accepted get truncated correctly
log = Carto::Log.new_data_import
log.append(text1, false, timestamp)
log.append(text2, false, timestamp)
log.append('fill', false, timestamp)
log.append('fill more', false, timestamp)
# This goes to the circular area
log.append('fill even more', false, timestamp)
log.append(text3, false, timestamp)
log.append(text4, false, timestamp)
log.store
log = Carto::Log.find(log.id)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
Carto::Log::END_OF_LOG_MARK
# Nothing should change with this
log.send(:fix_entries_encoding)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text3) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text4) +
Carto::Log::END_OF_LOG_MARK
# Check that new entries are added correctly
log.append(text5, false, timestamp)
log.append(text6, false, timestamp)
log.send(:collect_entries).should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text6)
log.to_s.should eq format(Carto::Log::ENTRY_FORMAT, timestamp, text1) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text2) +
Carto::Log::HALF_OF_LOG_MARK +
format(Carto::Log::ENTRY_FORMAT, timestamp, text5) +
format(Carto::Log::ENTRY_FORMAT, timestamp, text6) +
Carto::Log::END_OF_LOG_MARK
end
it 'checks zero case of a new log' do
log = Carto::Log.new_data_import
log.to_s.should eq Carto::Log::END_OF_LOG_MARK
log = Carto::Log.find(log.id)
log.to_s.should eq Carto::Log::END_OF_LOG_MARK
# Forcing call without entries
log.send(:fix_entries_encoding)
log.to_s.should eq Carto::Log::END_OF_LOG_MARK
end
end
end
| true |
0af65633d5d2a1b2c13a85cf2f1fb8da33ffca0e | Ruby | bess/northwest-digital-archives | /vendor/plugins/blacklight/vendor/gems/rdoc-2.3.0/lib/rdoc/parser/f95.rb | UTF-8 | 57,112 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | require 'rdoc/parser'
##
# = Fortran95 RDoc Parser
#
# == Overview
#
# This parser parses Fortran95 files with suffixes "f90", "F90", "f95" and
# "F95". Fortran95 files are expected to be conformed to Fortran95 standards.
#
# == Rules
#
# Fundamental rules are same as that of the Ruby parser. But comment markers
# are '!' not '#'.
#
# === Correspondence between RDoc documentation and Fortran95 programs
#
# F95 parses main programs, modules, subroutines, functions, derived-types,
# public variables, public constants, defined operators and defined
# assignments. These components are described in items of RDoc documentation,
# as follows.
#
# Files :: Files (same as Ruby)
# Classes:: Modules
# Methods:: Subroutines, functions, variables, constants, derived-types,
# defined operators, defined assignments
# Required files:: Files in which imported modules, external subroutines and
# external functions are defined.
# Included Modules:: List of imported modules
# Attributes:: List of derived-types, List of imported modules all of whose
# components are published again
#
# Components listed in 'Methods' (subroutines, functions, ...) defined in
# modules are described in the item of 'Classes'. On the other hand,
# components defined in main programs or as external procedures are described
# in the item of 'Files'.
#
# === Components parsed by default
#
# By default, documentation on public components (subroutines, functions,
# variables, constants, derived-types, defined operators, defined assignments)
# are generated.
#
# With "--all" option, documentation on all components are generated (almost
# same as the Ruby parser).
#
# === Information parsed automatically
#
# The following information is automatically parsed.
#
# * Types of arguments
# * Types of variables and constants
# * Types of variables in the derived types, and initial values
# * NAMELISTs and types of variables in them, and initial values
#
# Aliases by interface statement are described in the item of 'Methods'.
#
# Components which are imported from other modules and published again are
# described in the item of 'Methods'.
#
# === Format of comment blocks
#
# Comment blocks should be written as follows.
#
# Comment blocks are considered to be ended when the line without '!' appears.
#
# The indentation is not necessary.
#
# ! (Top of file)
# !
# ! Comment blocks for the files.
# !
# !--
# ! The comment described in the part enclosed by
# ! "!--" and "!++" is ignored.
# !++
# !
# module hogehoge
# !
# ! Comment blocks for the modules (or the programs).
# !
#
# private
#
# logical :: a ! a private variable
# real, public :: b ! a public variable
# integer, parameter :: c = 0 ! a public constant
#
# public :: c
# public :: MULTI_ARRAY
# public :: hoge, foo
#
# type MULTI_ARRAY
# !
# ! Comment blocks for the derived-types.
# !
# real, pointer :: var(:) =>null() ! Comments block for the variables.
# integer :: num = 0
# end type MULTI_ARRAY
#
# contains
#
# subroutine hoge( in, & ! Comment blocks between continuation lines are ignored.
# & out )
# !
# ! Comment blocks for the subroutines or functions
# !
# character(*),intent(in):: in ! Comment blocks for the arguments.
# character(*),intent(out),allocatable,target :: in
# ! Comment blocks can be
# ! written under Fortran statements.
#
# character(32) :: file ! This comment parsed as a variable in below NAMELIST.
# integer :: id
#
# namelist /varinfo_nml/ file, id
# !
# ! Comment blocks for the NAMELISTs.
# ! Information about variables are described above.
# !
#
# ....
#
# end subroutine hoge
#
# integer function foo( in )
# !
# ! This part is considered as comment block.
#
# ! Comment blocks under blank lines are ignored.
# !
# integer, intent(in):: inA ! This part is considered as comment block.
#
# ! This part is ignored.
#
# end function foo
#
# subroutine hide( in, &
# & out ) !:nodoc:
# !
# ! If "!:nodoc:" is described at end-of-line in subroutine
# ! statement as above, the subroutine is ignored.
# ! This assignment can be used to modules, subroutines,
# ! functions, variables, constants, derived-types,
# ! defined operators, defined assignments,
# ! list of imported modules ("use" statement).
# !
#
# ....
#
# end subroutine hide
#
# end module hogehoge
class RDoc::Parser::F95 < RDoc::Parser
parse_files_matching(/\.((f|F)9(0|5)|F)$/)
class Token
NO_TEXT = "??".freeze
def initialize(line_no, char_no)
@line_no = line_no
@char_no = char_no
@text = NO_TEXT
end
# Because we're used in contexts that expect to return a token,
# we set the text string and then return ourselves
def set_text(text)
@text = text
self
end
attr_reader :line_no, :char_no, :text
end
@@external_aliases = []
@@public_methods = []
##
# "false":: Comments are below source code
# "true" :: Comments are upper source code
COMMENTS_ARE_UPPER = false
##
# Internal alias message
INTERNAL_ALIAS_MES = "Alias for"
##
# External alias message
EXTERNAL_ALIAS_MES = "The entity is"
##
# Define code constructs
def scan
# remove private comment
remaining_code = remove_private_comments(@content)
# continuation lines are united to one line
remaining_code = united_to_one_line(remaining_code)
# semicolons are replaced to line feed
remaining_code = semicolon_to_linefeed(remaining_code)
# collect comment for file entity
whole_comment, remaining_code = collect_first_comment(remaining_code)
@top_level.comment = whole_comment
# String "remaining_code" is converted to Array "remaining_lines"
remaining_lines = remaining_code.split("\n")
# "module" or "program" parts are parsed (new)
#
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
module_program_trailing = ""
module_program_name = ""
other_block_level_depth = 0
other_block_searching_flag = nil
remaining_lines.collect!{|line|
if !block_searching_flag && !other_block_searching_flag
if line =~ /^\s*?module\s+(\w+)\s*?(!.*?)?$/i
block_searching_flag = :module
block_searching_lines << line
module_program_name = $1
module_program_trailing = find_comments($2)
next false
elsif line =~ /^\s*?program\s+(\w+)\s*?(!.*?)?$/i ||
line =~ /^\s*?\w/ && !block_start?(line)
block_searching_flag = :program
block_searching_lines << line
module_program_name = $1 || ""
module_program_trailing = find_comments($2)
next false
elsif block_start?(line)
other_block_searching_flag = true
next line
elsif line =~ /^\s*?!\s?(.*)/
pre_comment << line
next line
else
pre_comment = []
next line
end
elsif other_block_searching_flag
other_block_level_depth += 1 if block_start?(line)
other_block_level_depth -= 1 if block_end?(line)
if other_block_level_depth < 0
other_block_level_depth = 0
other_block_searching_flag = nil
end
next line
end
block_searching_lines << line
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
if level_depth >= 0
next false
end
# "module_program_code" is formatted.
# ":nodoc:" flag is checked.
#
module_program_code = block_searching_lines.join("\n")
module_program_code = remove_empty_head_lines(module_program_code)
if module_program_trailing =~ /^:nodoc:/
# next loop to search next block
level_depth = 0
block_searching_flag = false
block_searching_lines = []
pre_comment = []
next false
end
# NormalClass is created, and added to @top_level
#
if block_searching_flag == :module
module_name = module_program_name
module_code = module_program_code
module_trailing = module_program_trailing
f9x_module = @top_level.add_module NormalClass, module_name
f9x_module.record_location @top_level
@stats.add_module f9x_module
f9x_comment = COMMENTS_ARE_UPPER ?
find_comments(pre_comment.join("\n")) + "\n" + module_trailing :
module_trailing + "\n" + find_comments(module_code.sub(/^.*$\n/i, ''))
f9x_module.comment = f9x_comment
parse_program_or_module(f9x_module, module_code)
TopLevel.all_files.each do |name, toplevel|
if toplevel.include_includes?(module_name, @options.ignore_case)
if !toplevel.include_requires?(@file_name, @options.ignore_case)
toplevel.add_require(Require.new(@file_name, ""))
end
end
toplevel.each_classmodule{|m|
if m.include_includes?(module_name, @options.ignore_case)
if !m.include_requires?(@file_name, @options.ignore_case)
m.add_require(Require.new(@file_name, ""))
end
end
}
end
elsif block_searching_flag == :program
program_name = module_program_name
program_code = module_program_code
program_trailing = module_program_trailing
# progress "p" # HACK what stats thingy does this correspond to?
program_comment = COMMENTS_ARE_UPPER ?
find_comments(pre_comment.join("\n")) + "\n" + program_trailing :
program_trailing + "\n" + find_comments(program_code.sub(/^.*$\n/i, ''))
program_comment = "\n\n= <i>Program</i> <tt>#{program_name}</tt>\n\n" \
+ program_comment
@top_level.comment << program_comment
parse_program_or_module(@top_level, program_code, :private)
end
# next loop to search next block
level_depth = 0
block_searching_flag = false
block_searching_lines = []
pre_comment = []
next false
}
remaining_lines.delete_if{ |line|
line == false
}
# External subprograms and functions are parsed
#
parse_program_or_module(@top_level, remaining_lines.join("\n"),
:public, true)
@top_level
end # End of scan
private
def parse_program_or_module(container, code,
visibility=:public, external=nil)
return unless container
return unless code
remaining_lines = code.split("\n")
remaining_code = "#{code}"
#
# Parse variables before "contains" in module
#
level_depth = 0
before_contains_lines = []
before_contains_code = nil
before_contains_flag = nil
remaining_lines.each{ |line|
if !before_contains_flag
if line =~ /^\s*?module\s+\w+\s*?(!.*?)?$/i
before_contains_flag = true
end
else
break if line =~ /^\s*?contains\s*?(!.*?)?$/i
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
break if level_depth < 0
before_contains_lines << line
end
}
before_contains_code = before_contains_lines.join("\n")
if before_contains_code
before_contains_code.gsub!(/^\s*?interface\s+.*?\s+end\s+interface.*?$/im, "")
before_contains_code.gsub!(/^\s*?type[\s\,]+.*?\s+end\s+type.*?$/im, "")
end
#
# Parse global "use"
#
use_check_code = "#{before_contains_code}"
cascaded_modules_list = []
while use_check_code =~ /^\s*?use\s+(\w+)(.*?)(!.*?)?$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_list = $2 || ""
used_trailing = $3 || ""
next if used_trailing =~ /!:nodoc:/
if !container.include_includes?(used_mod_name, @options.ignore_case)
# progress "." # HACK what stats thingy does this correspond to?
container.add_include Include.new(used_mod_name, "")
end
if ! (used_list =~ /\,\s*?only\s*?:/i )
cascaded_modules_list << "\#" + used_mod_name
end
end
#
# Parse public and private, and store information.
# This information is used when "add_method" and
# "set_visibility_for" are called.
#
visibility_default, visibility_info =
parse_visibility(remaining_lines.join("\n"), visibility, container)
@@public_methods.concat visibility_info
if visibility_default == :public
if !cascaded_modules_list.empty?
cascaded_modules =
Attr.new("Cascaded Modules",
"Imported modules all of whose components are published again",
"",
cascaded_modules_list.join(", "))
container.add_attribute(cascaded_modules)
end
end
#
# Check rename elements
#
use_check_code = "#{before_contains_code}"
while use_check_code =~ /^\s*?use\s+(\w+)\s*?\,(.+)$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_elements = $2.sub(/\s*?only\s*?:\s*?/i, '')
used_elements.split(",").each{ |used|
if /\s*?(\w+)\s*?=>\s*?(\w+)\s*?/ =~ used
local = $1
org = $2
@@public_methods.collect!{ |pub_meth|
if local == pub_meth["name"] ||
local.upcase == pub_meth["name"].upcase &&
@options.ignore_case
pub_meth["name"] = org
pub_meth["local_name"] = local
end
pub_meth
}
end
}
end
#
# Parse private "use"
#
use_check_code = remaining_lines.join("\n")
while use_check_code =~ /^\s*?use\s+(\w+)(.*?)(!.*?)?$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_trailing = $3 || ""
next if used_trailing =~ /!:nodoc:/
if !container.include_includes?(used_mod_name, @options.ignore_case)
# progress "." # HACK what stats thingy does this correspond to?
container.add_include Include.new(used_mod_name, "")
end
end
container.each_includes{ |inc|
TopLevel.all_files.each do |name, toplevel|
indicated_mod = toplevel.find_symbol(inc.name,
nil, @options.ignore_case)
if indicated_mod
indicated_name = indicated_mod.parent.file_relative_name
if !container.include_requires?(indicated_name, @options.ignore_case)
container.add_require(Require.new(indicated_name, ""))
end
break
end
end
}
#
# Parse derived-types definitions
#
derived_types_comment = ""
remaining_code = remaining_lines.join("\n")
while remaining_code =~ /^\s*?
type[\s\,]+(public|private)?\s*?(::)?\s*?
(\w+)\s*?(!.*?)?$
(.*?)
^\s*?end\s+type.*?$
/imx
remaining_code = $~.pre_match
remaining_code << $~.post_match
typename = $3.chomp.strip
type_elements = $5 || ""
type_code = remove_empty_head_lines($&)
type_trailing = find_comments($4)
next if type_trailing =~ /^:nodoc:/
type_visibility = $1
type_comment = COMMENTS_ARE_UPPER ?
find_comments($~.pre_match) + "\n" + type_trailing :
type_trailing + "\n" + find_comments(type_code.sub(/^.*$\n/i, ''))
type_element_visibility_public = true
type_code.split("\n").each{ |line|
if /^\s*?private\s*?$/ =~ line
type_element_visibility_public = nil
break
end
} if type_code
args_comment = ""
type_args_info = nil
if @options.show_all
args_comment = find_arguments(nil, type_code, true)
else
type_public_args_list = []
type_args_info = definition_info(type_code)
type_args_info.each{ |arg|
arg_is_public = type_element_visibility_public
arg_is_public = true if arg.include_attr?("public")
arg_is_public = nil if arg.include_attr?("private")
type_public_args_list << arg.varname if arg_is_public
}
args_comment = find_arguments(type_public_args_list, type_code)
end
type = AnyMethod.new("type #{typename}", typename)
type.singleton = false
type.params = ""
type.comment = "<b><em> Derived Type </em></b> :: <tt></tt>\n"
type.comment << args_comment if args_comment
type.comment << type_comment if type_comment
@stats.add_method type
container.add_method type
set_visibility(container, typename, visibility_default, @@public_methods)
if type_visibility
type_visibility.gsub!(/\s/,'')
type_visibility.gsub!(/\,/,'')
type_visibility.gsub!(/:/,'')
type_visibility.downcase!
if type_visibility == "public"
container.set_visibility_for([typename], :public)
elsif type_visibility == "private"
container.set_visibility_for([typename], :private)
end
end
check_public_methods(type, container.name)
if @options.show_all
derived_types_comment << ", " unless derived_types_comment.empty?
derived_types_comment << typename
else
if type.visibility == :public
derived_types_comment << ", " unless derived_types_comment.empty?
derived_types_comment << typename
end
end
end
if !derived_types_comment.empty?
derived_types_table =
Attr.new("Derived Types", "Derived_Types", "",
derived_types_comment)
container.add_attribute(derived_types_table)
end
#
# move interface scope
#
interface_code = ""
while remaining_code =~ /^\s*?
interface(
\s+\w+ |
\s+operator\s*?\(.*?\) |
\s+assignment\s*?\(\s*?=\s*?\)
)?\s*?$
(.*?)
^\s*?end\s+interface.*?$
/imx
interface_code << remove_empty_head_lines($&) + "\n"
remaining_code = $~.pre_match
remaining_code << $~.post_match
end
#
# Parse global constants or variables in modules
#
const_var_defs = definition_info(before_contains_code)
const_var_defs.each{|defitem|
next if defitem.nodoc
const_or_var_type = "Variable"
const_or_var_progress = "v"
if defitem.include_attr?("parameter")
const_or_var_type = "Constant"
const_or_var_progress = "c"
end
const_or_var = AnyMethod.new(const_or_var_type, defitem.varname)
const_or_var.singleton = false
const_or_var.params = ""
self_comment = find_arguments([defitem.varname], before_contains_code)
const_or_var.comment = "<b><em>" + const_or_var_type + "</em></b> :: <tt></tt>\n"
const_or_var.comment << self_comment if self_comment
@stats.add_method const_or_var_progress
container.add_method const_or_var
set_visibility(container, defitem.varname, visibility_default, @@public_methods)
if defitem.include_attr?("public")
container.set_visibility_for([defitem.varname], :public)
elsif defitem.include_attr?("private")
container.set_visibility_for([defitem.varname], :private)
end
check_public_methods(const_or_var, container.name)
} if const_var_defs
remaining_lines = remaining_code.split("\n")
# "subroutine" or "function" parts are parsed (new)
#
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
procedure_type = ""
contains_lines = []
contains_flag = nil
remaining_lines.collect!{|line|
if !block_searching_flag
# subroutine
if line =~ /^\s*?
(recursive|pure|elemental)?\s*?
subroutine\s+(\w+)\s*?(\(.*?\))?\s*?(!.*?)?$
/ix
block_searching_flag = :subroutine
block_searching_lines << line
procedure_name = $2.chomp.strip
procedure_params = $3 || ""
procedure_prefix = $1 || ""
procedure_trailing = $4 || "!"
next false
# function
elsif line =~ /^\s*?
(recursive|pure|elemental)?\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| type\s*?\([\w\s]+?\)\s+
| integer\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| real\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| double\s+precision\s+
| logical\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| complex\s*?(\([\w\s\=\(\)\*]+?\))?\s+
)?
function\s+(\w+)\s*?
(\(.*?\))?(\s+result\((.*?)\))?\s*?(!.*?)?$
/ix
block_searching_flag = :function
block_searching_lines << line
procedure_prefix = $1 || ""
procedure_type = $2 ? $2.chomp.strip : nil
procedure_name = $8.chomp.strip
procedure_params = $9 || ""
procedure_result_arg = $11 ? $11.chomp.strip : procedure_name
procedure_trailing = $12 || "!"
next false
elsif line =~ /^\s*?!\s?(.*)/
pre_comment << line
next line
else
pre_comment = []
next line
end
end
contains_flag = true if line =~ /^\s*?contains\s*?(!.*?)?$/
block_searching_lines << line
contains_lines << line if contains_flag
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
if level_depth >= 0
next false
end
# "procedure_code" is formatted.
# ":nodoc:" flag is checked.
#
procedure_code = block_searching_lines.join("\n")
procedure_code = remove_empty_head_lines(procedure_code)
if procedure_trailing =~ /^!:nodoc:/
# next loop to search next block
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
procedure_type = ""
contains_lines = []
contains_flag = nil
next false
end
# AnyMethod is created, and added to container
#
subroutine_function = nil
if block_searching_flag == :subroutine
subroutine_prefix = procedure_prefix
subroutine_name = procedure_name
subroutine_params = procedure_params
subroutine_trailing = procedure_trailing
subroutine_code = procedure_code
subroutine_comment = COMMENTS_ARE_UPPER ?
pre_comment.join("\n") + "\n" + subroutine_trailing :
subroutine_trailing + "\n" + subroutine_code.sub(/^.*$\n/i, '')
subroutine = AnyMethod.new("subroutine", subroutine_name)
parse_subprogram(subroutine, subroutine_params,
subroutine_comment, subroutine_code,
before_contains_code, nil, subroutine_prefix)
@stats.add_method subroutine
container.add_method subroutine
subroutine_function = subroutine
elsif block_searching_flag == :function
function_prefix = procedure_prefix
function_type = procedure_type
function_name = procedure_name
function_params_org = procedure_params
function_result_arg = procedure_result_arg
function_trailing = procedure_trailing
function_code_org = procedure_code
function_comment = COMMENTS_ARE_UPPER ?
pre_comment.join("\n") + "\n" + function_trailing :
function_trailing + "\n " + function_code_org.sub(/^.*$\n/i, '')
function_code = "#{function_code_org}"
if function_type
function_code << "\n" + function_type + " :: " + function_result_arg
end
function_params =
function_params_org.sub(/^\(/, "\(#{function_result_arg}, ")
function = AnyMethod.new("function", function_name)
parse_subprogram(function, function_params,
function_comment, function_code,
before_contains_code, true, function_prefix)
# Specific modification due to function
function.params.sub!(/\(\s*?#{function_result_arg}\s*?,\s*?/, "\( ")
function.params << " result(" + function_result_arg + ")"
function.start_collecting_tokens
function.add_token Token.new(1,1).set_text(function_code_org)
@stats.add_method function
container.add_method function
subroutine_function = function
end
# The visibility of procedure is specified
#
set_visibility(container, procedure_name,
visibility_default, @@public_methods)
# The alias for this procedure from external modules
#
check_external_aliases(procedure_name,
subroutine_function.params,
subroutine_function.comment, subroutine_function) if external
check_public_methods(subroutine_function, container.name)
# contains_lines are parsed as private procedures
if contains_flag
parse_program_or_module(container,
contains_lines.join("\n"), :private)
end
# next loop to search next block
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
contains_lines = []
contains_flag = nil
next false
} # End of remaining_lines.collect!{|line|
# Array remains_lines is converted to String remains_code again
#
remaining_code = remaining_lines.join("\n")
#
# Parse interface
#
interface_scope = false
generic_name = ""
interface_code.split("\n").each{ |line|
if /^\s*?
interface(
\s+\w+|
\s+operator\s*?\(.*?\)|
\s+assignment\s*?\(\s*?=\s*?\)
)?
\s*?(!.*?)?$
/ix =~ line
generic_name = $1 ? $1.strip.chomp : nil
interface_trailing = $2 || "!"
interface_scope = true
interface_scope = false if interface_trailing =~ /!:nodoc:/
# if generic_name =~ /operator\s*?\((.*?)\)/i
# operator_name = $1
# if operator_name && !operator_name.empty?
# generic_name = "#{operator_name}"
# end
# end
# if generic_name =~ /assignment\s*?\((.*?)\)/i
# assignment_name = $1
# if assignment_name && !assignment_name.empty?
# generic_name = "#{assignment_name}"
# end
# end
end
if /^\s*?end\s+interface/i =~ line
interface_scope = false
generic_name = nil
end
# internal alias
if interface_scope && /^\s*?module\s+procedure\s+(.*?)(!.*?)?$/i =~ line
procedures = $1.strip.chomp
procedures_trailing = $2 || "!"
next if procedures_trailing =~ /!:nodoc:/
procedures.split(",").each{ |proc|
proc.strip!
proc.chomp!
next if generic_name == proc || !generic_name
old_meth = container.find_symbol(proc, nil, @options.ignore_case)
next if !old_meth
nolink = old_meth.visibility == :private ? true : nil
nolink = nil if @options.show_all
new_meth =
initialize_external_method(generic_name, proc,
old_meth.params, nil,
old_meth.comment,
old_meth.clone.token_stream[0].text,
true, nolink)
new_meth.singleton = old_meth.singleton
@stats.add_method new_meth
container.add_method new_meth
set_visibility(container, generic_name, visibility_default, @@public_methods)
check_public_methods(new_meth, container.name)
}
end
# external aliases
if interface_scope
# subroutine
proc = nil
params = nil
procedures_trailing = nil
if line =~ /^\s*?
(recursive|pure|elemental)?\s*?
subroutine\s+(\w+)\s*?(\(.*?\))?\s*?(!.*?)?$
/ix
proc = $2.chomp.strip
generic_name = proc unless generic_name
params = $3 || ""
procedures_trailing = $4 || "!"
# function
elsif line =~ /^\s*?
(recursive|pure|elemental)?\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| type\s*?\([\w\s]+?\)\s+
| integer\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| real\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| double\s+precision\s+
| logical\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| complex\s*?(\([\w\s\=\(\)\*]+?\))?\s+
)?
function\s+(\w+)\s*?
(\(.*?\))?(\s+result\((.*?)\))?\s*?(!.*?)?$
/ix
proc = $8.chomp.strip
generic_name = proc unless generic_name
params = $9 || ""
procedures_trailing = $12 || "!"
else
next
end
next if procedures_trailing =~ /!:nodoc:/
indicated_method = nil
indicated_file = nil
TopLevel.all_files.each do |name, toplevel|
indicated_method = toplevel.find_local_symbol(proc, @options.ignore_case)
indicated_file = name
break if indicated_method
end
if indicated_method
external_method =
initialize_external_method(generic_name, proc,
indicated_method.params,
indicated_file,
indicated_method.comment)
@stats.add_method external_method
container.add_method external_method
set_visibility(container, generic_name, visibility_default, @@public_methods)
if !container.include_requires?(indicated_file, @options.ignore_case)
container.add_require(Require.new(indicated_file, ""))
end
check_public_methods(external_method, container.name)
else
@@external_aliases << {
"new_name" => generic_name,
"old_name" => proc,
"file_or_module" => container,
"visibility" => find_visibility(container, generic_name, @@public_methods) || visibility_default
}
end
end
} if interface_code # End of interface_code.split("\n").each ...
#
# Already imported methods are removed from @@public_methods.
# Remainders are assumed to be imported from other modules.
#
@@public_methods.delete_if{ |method| method["entity_is_discovered"]}
@@public_methods.each{ |pub_meth|
next unless pub_meth["file_or_module"].name == container.name
pub_meth["used_modules"].each{ |used_mod|
TopLevel.all_classes_and_modules.each{ |modules|
if modules.name == used_mod ||
modules.name.upcase == used_mod.upcase &&
@options.ignore_case
modules.method_list.each{ |meth|
if meth.name == pub_meth["name"] ||
meth.name.upcase == pub_meth["name"].upcase &&
@options.ignore_case
new_meth = initialize_public_method(meth,
modules.name)
if pub_meth["local_name"]
new_meth.name = pub_meth["local_name"]
end
@stats.add_method new_meth
container.add_method new_meth
end
}
end
}
}
}
container
end # End of parse_program_or_module
##
# Parse arguments, comment, code of subroutine and function. Return
# AnyMethod object.
def parse_subprogram(subprogram, params, comment, code,
before_contains=nil, function=nil, prefix=nil)
subprogram.singleton = false
prefix = "" if !prefix
arguments = params.sub(/\(/, "").sub(/\)/, "").split(",") if params
args_comment, params_opt =
find_arguments(arguments, code.sub(/^s*?contains\s*?(!.*?)?$.*/im, ""),
nil, nil, true)
params_opt = "( " + params_opt + " ) " if params_opt
subprogram.params = params_opt || ""
namelist_comment = find_namelists(code, before_contains)
block_comment = find_comments comment
if function
subprogram.comment = "<b><em> Function </em></b> :: <em>#{prefix}</em>\n"
else
subprogram.comment = "<b><em> Subroutine </em></b> :: <em>#{prefix}</em>\n"
end
subprogram.comment << args_comment if args_comment
subprogram.comment << block_comment if block_comment
subprogram.comment << namelist_comment if namelist_comment
# For output source code
subprogram.start_collecting_tokens
subprogram.add_token Token.new(1,1).set_text(code)
subprogram
end
##
# Collect comment for file entity
def collect_first_comment(body)
comment = ""
not_comment = ""
comment_start = false
comment_end = false
body.split("\n").each{ |line|
if comment_end
not_comment << line
not_comment << "\n"
elsif /^\s*?!\s?(.*)$/i =~ line
comment_start = true
comment << $1
comment << "\n"
elsif /^\s*?$/i =~ line
comment_end = true if comment_start && COMMENTS_ARE_UPPER
else
comment_end = true
not_comment << line
not_comment << "\n"
end
}
return comment, not_comment
end
##
# Return comments of definitions of arguments
#
# If "all" argument is true, information of all arguments are returned.
#
# If "modified_params" is true, list of arguments are decorated, for
# example, optional arguments are parenthetic as "[arg]".
def find_arguments(args, text, all=nil, indent=nil, modified_params=nil)
return unless args || all
indent = "" unless indent
args = ["all"] if all
params = "" if modified_params
comma = ""
return unless text
args_rdocforms = "\n"
remaining_lines = "#{text}"
definitions = definition_info(remaining_lines)
args.each{ |arg|
arg.strip!
arg.chomp!
definitions.each { |defitem|
if arg == defitem.varname.strip.chomp || all
args_rdocforms << <<-"EOF"
#{indent}<tt><b>#{defitem.varname.chomp.strip}#{defitem.arraysuffix}</b> #{defitem.inivalue}</tt> ::
#{indent} <tt>#{defitem.types.chomp.strip}</tt>
EOF
if !defitem.comment.chomp.strip.empty?
comment = ""
defitem.comment.split("\n").each{ |line|
comment << " " + line + "\n"
}
args_rdocforms << <<-"EOF"
#{indent} <tt></tt> ::
#{indent} <tt></tt>
#{indent} #{comment.chomp.strip}
EOF
end
if modified_params
if defitem.include_attr?("optional")
params << "#{comma}[#{arg}]"
else
params << "#{comma}#{arg}"
end
comma = ", "
end
end
}
}
if modified_params
return args_rdocforms, params
else
return args_rdocforms
end
end
##
# Return comments of definitions of namelists
def find_namelists(text, before_contains=nil)
return nil if !text
result = ""
lines = "#{text}"
before_contains = "" if !before_contains
while lines =~ /^\s*?namelist\s+\/\s*?(\w+)\s*?\/([\s\w\,]+)$/i
lines = $~.post_match
nml_comment = COMMENTS_ARE_UPPER ?
find_comments($~.pre_match) : find_comments($~.post_match)
nml_name = $1
nml_args = $2.split(",")
result << "\n\n=== NAMELIST <tt><b>" + nml_name + "</tt></b>\n\n"
result << nml_comment + "\n" if nml_comment
if lines.split("\n")[0] =~ /^\//i
lines = "namelist " + lines
end
result << find_arguments(nml_args, "#{text}" + "\n" + before_contains)
end
return result
end
##
# Comments just after module or subprogram, or arguments are returned. If
# "COMMENTS_ARE_UPPER" is true, comments just before modules or subprograms
# are returnd
def find_comments text
return "" unless text
lines = text.split("\n")
lines.reverse! if COMMENTS_ARE_UPPER
comment_block = Array.new
lines.each do |line|
break if line =~ /^\s*?\w/ || line =~ /^\s*?$/
if COMMENTS_ARE_UPPER
comment_block.unshift line.sub(/^\s*?!\s?/,"")
else
comment_block.push line.sub(/^\s*?!\s?/,"")
end
end
nice_lines = comment_block.join("\n").split "\n\s*?\n"
nice_lines[0] ||= ""
nice_lines.shift
end
##
# Create method for internal alias
def initialize_public_method(method, parent)
return if !method || !parent
new_meth = AnyMethod.new("External Alias for module", method.name)
new_meth.singleton = method.singleton
new_meth.params = method.params.clone
new_meth.comment = remove_trailing_alias(method.comment.clone)
new_meth.comment << "\n\n#{EXTERNAL_ALIAS_MES} #{parent.strip.chomp}\##{method.name}"
return new_meth
end
##
# Create method for external alias
#
# If argument "internal" is true, file is ignored.
def initialize_external_method(new, old, params, file, comment, token=nil,
internal=nil, nolink=nil)
return nil unless new || old
if internal
external_alias_header = "#{INTERNAL_ALIAS_MES} "
external_alias_text = external_alias_header + old
elsif file
external_alias_header = "#{EXTERNAL_ALIAS_MES} "
external_alias_text = external_alias_header + file + "#" + old
else
return nil
end
external_meth = AnyMethod.new(external_alias_text, new)
external_meth.singleton = false
external_meth.params = params
external_comment = remove_trailing_alias(comment) + "\n\n" if comment
external_meth.comment = external_comment || ""
if nolink && token
external_meth.start_collecting_tokens
external_meth.add_token Token.new(1,1).set_text(token)
else
external_meth.comment << external_alias_text
end
return external_meth
end
##
# Parse visibility
def parse_visibility(code, default, container)
result = []
visibility_default = default || :public
used_modules = []
container.includes.each{|i| used_modules << i.name} if container
remaining_code = code.gsub(/^\s*?type[\s\,]+.*?\s+end\s+type.*?$/im, "")
remaining_code.split("\n").each{ |line|
if /^\s*?private\s*?$/ =~ line
visibility_default = :private
break
end
} if remaining_code
remaining_code.split("\n").each{ |line|
if /^\s*?private\s*?(::)?\s+(.*)\s*?(!.*?)?/i =~ line
methods = $2.sub(/!.*$/, '')
methods.split(",").each{ |meth|
meth.sub!(/!.*$/, '')
meth.gsub!(/:/, '')
result << {
"name" => meth.chomp.strip,
"visibility" => :private,
"used_modules" => used_modules.clone,
"file_or_module" => container,
"entity_is_discovered" => nil,
"local_name" => nil
}
}
elsif /^\s*?public\s*?(::)?\s+(.*)\s*?(!.*?)?/i =~ line
methods = $2.sub(/!.*$/, '')
methods.split(",").each{ |meth|
meth.sub!(/!.*$/, '')
meth.gsub!(/:/, '')
result << {
"name" => meth.chomp.strip,
"visibility" => :public,
"used_modules" => used_modules.clone,
"file_or_module" => container,
"entity_is_discovered" => nil,
"local_name" => nil
}
}
end
} if remaining_code
if container
result.each{ |vis_info|
vis_info["parent"] = container.name
}
end
return visibility_default, result
end
##
# Set visibility
#
# "subname" element of "visibility_info" is deleted.
def set_visibility(container, subname, visibility_default, visibility_info)
return unless container || subname || visibility_default || visibility_info
not_found = true
visibility_info.collect!{ |info|
if info["name"] == subname ||
@options.ignore_case && info["name"].upcase == subname.upcase
if info["file_or_module"].name == container.name
container.set_visibility_for([subname], info["visibility"])
info["entity_is_discovered"] = true
not_found = false
end
end
info
}
if not_found
return container.set_visibility_for([subname], visibility_default)
else
return container
end
end
##
# Find visibility
def find_visibility(container, subname, visibility_info)
return nil if !subname || !visibility_info
visibility_info.each{ |info|
if info["name"] == subname ||
@options.ignore_case && info["name"].upcase == subname.upcase
if info["parent"] == container.name
return info["visibility"]
end
end
}
return nil
end
##
# Check external aliases
def check_external_aliases(subname, params, comment, test=nil)
@@external_aliases.each{ |alias_item|
if subname == alias_item["old_name"] ||
subname.upcase == alias_item["old_name"].upcase &&
@options.ignore_case
new_meth = initialize_external_method(alias_item["new_name"],
subname, params, @file_name,
comment)
new_meth.visibility = alias_item["visibility"]
@stats.add_method new_meth
alias_item["file_or_module"].add_method(new_meth)
if !alias_item["file_or_module"].include_requires?(@file_name, @options.ignore_case)
alias_item["file_or_module"].add_require(Require.new(@file_name, ""))
end
end
}
end
##
# Check public_methods
def check_public_methods(method, parent)
return if !method || !parent
@@public_methods.each{ |alias_item|
parent_is_used_module = nil
alias_item["used_modules"].each{ |used_module|
if used_module == parent ||
used_module.upcase == parent.upcase &&
@options.ignore_case
parent_is_used_module = true
end
}
next if !parent_is_used_module
if method.name == alias_item["name"] ||
method.name.upcase == alias_item["name"].upcase &&
@options.ignore_case
new_meth = initialize_public_method(method, parent)
if alias_item["local_name"]
new_meth.name = alias_item["local_name"]
end
@stats.add_method new_meth
alias_item["file_or_module"].add_method new_meth
end
}
end
##
# Continuous lines are united.
#
# Comments in continuous lines are removed.
def united_to_one_line(f90src)
return "" unless f90src
lines = f90src.split("\n")
previous_continuing = false
now_continuing = false
body = ""
lines.each{ |line|
words = line.split("")
next if words.empty? && previous_continuing
commentout = false
brank_flag = true ; brank_char = ""
squote = false ; dquote = false
ignore = false
words.collect! { |char|
if previous_continuing && brank_flag
now_continuing = true
ignore = true
case char
when "!" ; break
when " " ; brank_char << char ; next ""
when "&"
brank_flag = false
now_continuing = false
next ""
else
brank_flag = false
now_continuing = false
ignore = false
next brank_char + char
end
end
ignore = false
if now_continuing
next ""
elsif !(squote) && !(dquote) && !(commentout)
case char
when "!" ; commentout = true ; next char
when "\""; dquote = true ; next char
when "\'"; squote = true ; next char
when "&" ; now_continuing = true ; next ""
else next char
end
elsif commentout
next char
elsif squote
case char
when "\'"; squote = false ; next char
else next char
end
elsif dquote
case char
when "\""; dquote = false ; next char
else next char
end
end
}
if !ignore && !previous_continuing || !brank_flag
if previous_continuing
body << words.join("")
else
body << "\n" + words.join("")
end
end
previous_continuing = now_continuing ? true : nil
now_continuing = nil
}
return body
end
##
# Continuous line checker
def continuous_line?(line)
continuous = false
if /&\s*?(!.*)?$/ =~ line
continuous = true
if comment_out?($~.pre_match)
continuous = false
end
end
return continuous
end
##
# Comment out checker
def comment_out?(line)
return nil unless line
commentout = false
squote = false ; dquote = false
line.split("").each { |char|
if !(squote) && !(dquote)
case char
when "!" ; commentout = true ; break
when "\""; dquote = true
when "\'"; squote = true
else next
end
elsif squote
case char
when "\'"; squote = false
else next
end
elsif dquote
case char
when "\""; dquote = false
else next
end
end
}
return commentout
end
##
# Semicolons are replaced to line feed.
def semicolon_to_linefeed(text)
return "" unless text
lines = text.split("\n")
lines.collect!{ |line|
words = line.split("")
commentout = false
squote = false ; dquote = false
words.collect! { |char|
if !(squote) && !(dquote) && !(commentout)
case char
when "!" ; commentout = true ; next char
when "\""; dquote = true ; next char
when "\'"; squote = true ; next char
when ";" ; "\n"
else next char
end
elsif commentout
next char
elsif squote
case char
when "\'"; squote = false ; next char
else next char
end
elsif dquote
case char
when "\""; dquote = false ; next char
else next char
end
end
}
words.join("")
}
return lines.join("\n")
end
##
# Which "line" is start of block (module, program, block data, subroutine,
# function) statement ?
def block_start?(line)
return nil if !line
if line =~ /^\s*?module\s+(\w+)\s*?(!.*?)?$/i ||
line =~ /^\s*?program\s+(\w+)\s*?(!.*?)?$/i ||
line =~ /^\s*?block\s+data(\s+\w+)?\s*?(!.*?)?$/i ||
line =~ \
/^\s*?
(recursive|pure|elemental)?\s*?
subroutine\s+(\w+)\s*?(\(.*?\))?\s*?(!.*?)?$
/ix ||
line =~ \
/^\s*?
(recursive|pure|elemental)?\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| type\s*?\([\w\s]+?\)\s+
| integer\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| real\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| double\s+precision\s+
| logical\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| complex\s*?(\([\w\s\=\(\)\*]+?\))?\s+
)?
function\s+(\w+)\s*?
(\(.*?\))?(\s+result\((.*?)\))?\s*?(!.*?)?$
/ix
return true
end
return nil
end
##
# Which "line" is end of block (module, program, block data, subroutine,
# function) statement ?
def block_end?(line)
return nil if !line
if line =~ /^\s*?end\s*?(!.*?)?$/i ||
line =~ /^\s*?end\s+module(\s+\w+)?\s*?(!.*?)?$/i ||
line =~ /^\s*?end\s+program(\s+\w+)?\s*?(!.*?)?$/i ||
line =~ /^\s*?end\s+block\s+data(\s+\w+)?\s*?(!.*?)?$/i ||
line =~ /^\s*?end\s+subroutine(\s+\w+)?\s*?(!.*?)?$/i ||
line =~ /^\s*?end\s+function(\s+\w+)?\s*?(!.*?)?$/i
return true
end
return nil
end
##
# Remove "Alias for" in end of comments
def remove_trailing_alias(text)
return "" if !text
lines = text.split("\n").reverse
comment_block = Array.new
checked = false
lines.each do |line|
if !checked
if /^\s?#{INTERNAL_ALIAS_MES}/ =~ line ||
/^\s?#{EXTERNAL_ALIAS_MES}/ =~ line
checked = true
next
end
end
comment_block.unshift line
end
nice_lines = comment_block.join("\n")
nice_lines ||= ""
return nice_lines
end
##
# Empty lines in header are removed
def remove_empty_head_lines(text)
return "" unless text
lines = text.split("\n")
header = true
lines.delete_if{ |line|
header = false if /\S/ =~ line
header && /^\s*?$/ =~ line
}
lines.join("\n")
end
##
# header marker "=", "==", ... are removed
def remove_header_marker(text)
return text.gsub(/^\s?(=+)/, '<tt></tt>\1')
end
def remove_private_comments(body)
body.gsub!(/^\s*!--\s*?$.*?^\s*!\+\+\s*?$/m, '')
return body
end
##
# Information of arguments of subroutines and functions in Fortran95
class Fortran95Definition
# Name of variable
#
attr_reader :varname
# Types of variable
#
attr_reader :types
# Initial Value
#
attr_reader :inivalue
# Suffix of array
#
attr_reader :arraysuffix
# Comments
#
attr_accessor :comment
# Flag of non documentation
#
attr_accessor :nodoc
def initialize(varname, types, inivalue, arraysuffix, comment,
nodoc=false)
@varname = varname
@types = types
@inivalue = inivalue
@arraysuffix = arraysuffix
@comment = comment
@nodoc = nodoc
end
def to_s
return <<-EOF
<Fortran95Definition:
varname=#{@varname}, types=#{types},
inivalue=#{@inivalue}, arraysuffix=#{@arraysuffix}, nodoc=#{@nodoc},
comment=
#{@comment}
>
EOF
end
#
# If attr is included, true is returned
#
def include_attr?(attr)
return if !attr
@types.split(",").each{ |type|
return true if type.strip.chomp.upcase == attr.strip.chomp.upcase
}
return nil
end
end # End of Fortran95Definition
##
# Parse string argument "text", and Return Array of Fortran95Definition
# object
def definition_info(text)
return nil unless text
lines = "#{text}"
defs = Array.new
comment = ""
trailing_comment = ""
under_comment_valid = false
lines.split("\n").each{ |line|
if /^\s*?!\s?(.*)/ =~ line
if COMMENTS_ARE_UPPER
comment << remove_header_marker($1)
comment << "\n"
elsif defs[-1] && under_comment_valid
defs[-1].comment << "\n"
defs[-1].comment << remove_header_marker($1)
end
next
elsif /^\s*?$/ =~ line
comment = ""
under_comment_valid = false
next
end
type = ""
characters = ""
if line =~ /^\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?[\s\,]*
| type\s*?\([\w\s]+?\)[\s\,]*
| integer\s*?(\([\w\s\=\(\)\*]+?\))?[\s\,]*
| real\s*?(\([\w\s\=\(\)\*]+?\))?[\s\,]*
| double\s+precision[\s\,]*
| logical\s*?(\([\w\s\=\(\)\*]+?\))?[\s\,]*
| complex\s*?(\([\w\s\=\(\)\*]+?\))?[\s\,]*
)
(.*?::)?
(.+)$
/ix
characters = $8
type = $1
type << $7.gsub(/::/, '').gsub(/^\s*?\,/, '') if $7
else
under_comment_valid = false
next
end
squote = false ; dquote = false ; bracket = 0
iniflag = false; commentflag = false
varname = "" ; arraysuffix = "" ; inivalue = ""
start_pos = defs.size
characters.split("").each { |char|
if !(squote) && !(dquote) && bracket <= 0 && !(iniflag) && !(commentflag)
case char
when "!" ; commentflag = true
when "(" ; bracket += 1 ; arraysuffix = char
when "\""; dquote = true
when "\'"; squote = true
when "=" ; iniflag = true ; inivalue << char
when ","
defs << Fortran95Definition.new(varname, type, inivalue, arraysuffix, comment)
varname = "" ; arraysuffix = "" ; inivalue = ""
under_comment_valid = true
when " " ; next
else ; varname << char
end
elsif commentflag
comment << remove_header_marker(char)
trailing_comment << remove_header_marker(char)
elsif iniflag
if dquote
case char
when "\"" ; dquote = false ; inivalue << char
else ; inivalue << char
end
elsif squote
case char
when "\'" ; squote = false ; inivalue << char
else ; inivalue << char
end
elsif bracket > 0
case char
when "(" ; bracket += 1 ; inivalue << char
when ")" ; bracket -= 1 ; inivalue << char
else ; inivalue << char
end
else
case char
when ","
defs << Fortran95Definition.new(varname, type, inivalue, arraysuffix, comment)
varname = "" ; arraysuffix = "" ; inivalue = ""
iniflag = false
under_comment_valid = true
when "(" ; bracket += 1 ; inivalue << char
when "\""; dquote = true ; inivalue << char
when "\'"; squote = true ; inivalue << char
when "!" ; commentflag = true
else ; inivalue << char
end
end
elsif !(squote) && !(dquote) && bracket > 0
case char
when "(" ; bracket += 1 ; arraysuffix << char
when ")" ; bracket -= 1 ; arraysuffix << char
else ; arraysuffix << char
end
elsif squote
case char
when "\'"; squote = false ; inivalue << char
else ; inivalue << char
end
elsif dquote
case char
when "\""; dquote = false ; inivalue << char
else ; inivalue << char
end
end
}
defs << Fortran95Definition.new(varname, type, inivalue, arraysuffix, comment)
if trailing_comment =~ /^:nodoc:/
defs[start_pos..-1].collect!{ |defitem|
defitem.nodoc = true
}
end
varname = "" ; arraysuffix = "" ; inivalue = ""
comment = ""
under_comment_valid = true
trailing_comment = ""
}
return defs
end
end
| true |
91244929945fa64f0c18651c0277e89980ce5716 | Ruby | RemixZero/learn-ruby | /chap19.rb | UTF-8 | 886 | 4.53125 | 5 | [] | no_license | def cheese_and_crackers(cheese_count, boxes_of_crackers, cool=55) #yo this DEFINES a function
puts "you have #{cheese_count} cheeses!"
puts "you have #{boxes_of_crackers} boxes of crackers"
puts "you have #{cool} cools"
puts "man thats enough for a party!"
puts "get a blanket.\n"
end
puts "we can just give the function numbers directly:" #just a puts nothing new here
cheese_and_crackers(20, 30, 12)
puts "or, we can use varibles from our script"
amount_of_cheese = 10*2 # this varible holds a number -dad (20)
amount_of_crackers = 50 # same thing yo
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "we can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6) # same thing agian
puts "and we can combine the two, varibles and math:"
cheese_and_crackers(amount_of_cheese*100, amount_of_crackers + 1000) # agian its pretty much the same stuff
| true |
c4ca0ed5c7165e5d95b497f3f46f3d968d86a940 | Ruby | shuto0125/projecteuler | /problem5/index.rb | UTF-8 | 687 | 3.59375 | 4 | [] | no_license | my_prime = [ 1, 2 ]
i = 0
#20までの素数を出す
20.times do |i|
i += 1
if i % 2 != 0
i.times do |new_i|
if new_i != 1 && new_i % i != 0 && my_prime.include?(i) == false
my_prime.push(i)
end
end
end
end
p my_prime
target = 2520
loop do
target += 1
check_flug = false
# 2,3,5 で割れる数の場合
if target % 2 == 0 && target % 3 == 0 && target % 5 == 0
my_prime.each do |mp|
if target % mp == 0
check_flug = true
else
check_flug = false
break
end
end
#全ての素数で割れた場合
if check_flug == true
p target
break
end
end
end
| true |
68cf7fef37c65657c4fd269da3e16b06a80a359c | Ruby | Slouch07/RB101 | /Small_Problems/Easy_4/convert_string_to_number.rb | UTF-8 | 866 | 4.78125 | 5 | [] | no_license | # Convert a String to a Number! (REVIEW)
# A method that takes a String of digits, and returns the appropriate number as an integer.
# input - a string version of a number.
# output - an integer version of the input string
# separate individual charaters in the string. (array - .chars)
# iterate through each element and convert it to the integer version. (new array? map, select?)
# convert the array of integers into a single number
DIGITS = {
"0" => 0,
"1" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
"5" => 5,
"6" => 6,
"7" => 7,
"8" => 8,
"9" => 9,
}
def string_to_integer(digit_string)
array_of_chars = digit_string.chars
digit_array = array_of_chars.map { |x| DIGITS[x] }
multiplier = 0
digit_array.each { |n| multiplier = (multiplier * 10) + n }
multiplier
end
p string_to_integer('4321') == 4321
p string_to_integer('570') == 570 | true |
4906fb6714988703af72121e224e44ea7f5ebb19 | Ruby | cvallianatos/Euler | /Names_scores.rb | UTF-8 | 1,473 | 3.828125 | 4 | [] | no_license | # Names scores
# Problem 22
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file?
alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
file = File.open("names.txt", "r")
myFile = File.open("euler22-output.txt", "w")
contents = file.read
extract = contents.split(',')
arrayLength = extract.length - 1
extract.sort!
sum = 0
for i in 0..arrayLength
extract[i] = extract[i].gsub(/["]/,'')
tempStr = extract[i].split(//)
tempStrLength = tempStr.length - 1
strSum = 0
print i+1, "). "
myFile.print i+1, "). "
for j in 0..tempStrLength
loc = alfa.index(tempStr[j]) + 1
strSum = strSum + loc
print " ", loc
myFile.print " ", loc
end
print " ", extract[i], " ---> ", strSum * (i+1), "\n"
myFile.print " ", extract[i], " ---> ", strSum * (i+1), "\n"
sum = sum + (strSum * (i+1))
end
print "============================\n"
print sum, "\n"
myFile.print "============================\n"
myFile.print sum, "\n"
myFile.close
| true |
5d6e6f117248b650873af4333204468b101c62ca | Ruby | tvaroglu/enigma | /spec/file_handler_spec.rb | UTF-8 | 1,690 | 2.828125 | 3 | [] | no_license | require_relative 'spec_helper'
RSpec.describe FileHandler do
before :each do
@message = 'hello world end'
@message_file = './lib/test_files/message.txt'
@encryption_file = './lib/test_files/encrypted.txt'
@key = '67929'
@date = '130621'
end
it 'can encrypt a message' do
allow($stdin).to receive(:gets).and_return(@message)
runner = FileHandler.encrypt(@message_file, @encryption_file, @key, @date)
expect(runner).to eq("Created '#{File.basename(@encryption_file)}' with the key #{@key} and date #{@date}")
message_text = File.open(@message_file, 'r')
expect(message_text.read).to eq(@message)
message_text.close
encrypted_text = File.open(@encryption_file, 'r')
decryption = Enigma.new.decrypt(encrypted_text.read, @key, @date)
encrypted_text.close
expect(decryption[:decryption]).to eq(@message)
end
it 'can decrypt a message' do
decryption_file = './lib/test_files/decrypted.txt'
runner = FileHandler.decrypt(@encryption_file, decryption_file, @key, @date)
expect(runner).to eq("Created '#{File.basename(decryption_file)}' with the key #{@key} and date #{@date}")
decrypted_text = File.open(decryption_file, 'r')
expect(decrypted_text.read).to eq(@message)
decrypted_text.close
end
it 'can crack an encrypted message' do
cracked_file = './lib/test_files/cracked.txt'
runner = FileHandler.crack(@encryption_file, cracked_file, @date)
expect(runner).to eq("Created '#{File.basename(cracked_file)}' with the key #{@key} and date #{@date}")
cracked_text = File.open(cracked_file, 'r')
expect(cracked_text.read).to eq(@message)
cracked_text.close
end
end
| true |
0c64e9c6e24ef1d6dbcc26cf528fb3b6754f6c30 | Ruby | elorenn/Ironhack | /Week_1/Day_5/chess_validator/app.rb | UTF-8 | 4,750 | 3.46875 | 3 | [] | no_license | require_relative("lib/chesspiece.rb")
require_relative("lib/rook.rb")
require_relative("lib/king.rb")
require_relative("lib/knight.rb")
require_relative("lib/bishop.rb")
require_relative("lib/queen.rb")
require_relative("lib/pawn.rb")
require_relative("lib/board.rb")
black_rook_left = Rook.new(1, 8, "black")
black_knight_left = Knight.new(2, 8, "black")
black_bishop_left = Bishop.new(3, 8, "black")
black_queen = Queen.new(4, 8, "black")
black_king = King.new(5, 8, "black")
black_bishop_right = Bishop.new(6, 8, "black")
black_knight_right = Knight.new(7, 8, "black")
black_rook_right = Rook.new(8, 8, "black")
black_pawn_1 = Pawn.new(1, 7, "black")
black_pawn_2 = Pawn.new(2, 7, "black")
black_pawn_3 = Pawn.new(3, 7, "black")
black_pawn_4 = Pawn.new(4, 7, "black")
black_pawn_5 = Pawn.new(5, 7, "black")
black_pawn_6 = Pawn.new(6, 7, "black")
black_pawn_7 = Pawn.new(7, 7, "black")
black_pawn_8 = Pawn.new(8, 7, "black")
white_rook_left = Rook.new(1, 1, "white")
white_knight_left = Knight.new(2, 1, "white")
white_bishop_left = Bishop.new(3, 1, "white")
white_queen = Queen.new(4, 1, "white")
white_king = King.new(5, 1, "white")
white_bishop_right = Bishop.new(6, 1, "white")
white_knight_right = Knight.new(7, 1, "white")
white_rook_right = Rook.new(8, 1, "white")
white_pawn_1 = Pawn.new(1, 2, "white")
white_pawn_2 = Pawn.new(2, 2, "white")
white_pawn_3 = Pawn.new(3, 2, "white")
white_pawn_4 = Pawn.new(4, 2, "white")
white_pawn_5 = Pawn.new(5, 2, "white")
white_pawn_6 = Pawn.new(6, 2, "white")
white_pawn_7 = Pawn.new(7, 2, "white")
white_pawn_8 = Pawn.new(8, 2, "white")
# # add all pawns at once with some variation of:
# 8.times do |i|
# board.add_piece(Pawn.new(i+1, 7, "black"))
# end
# 8.times do |i|
# board.add_piece(Pawn.new(i+1, 7, "white"))
# end
my_board = Board.new
my_board.add_chess_piece(black_rook_left)
my_board.add_chess_piece(black_knight_left)
my_board.add_chess_piece(black_bishop_left)
my_board.add_chess_piece(black_queen)
my_board.add_chess_piece(black_king)
my_board.add_chess_piece(black_bishop_right)
my_board.add_chess_piece(black_knight_right)
my_board.add_chess_piece(black_rook_right)
my_board.add_chess_piece(black_pawn_1)
my_board.add_chess_piece(black_pawn_2)
my_board.add_chess_piece(black_pawn_3)
my_board.add_chess_piece(black_pawn_4)
my_board.add_chess_piece(black_pawn_5)
my_board.add_chess_piece(black_pawn_6)
my_board.add_chess_piece(black_pawn_7)
my_board.add_chess_piece(black_pawn_8)
my_board.add_chess_piece(white_rook_left)
my_board.add_chess_piece(white_knight_left)
my_board.add_chess_piece(white_bishop_left)
my_board.add_chess_piece(white_queen)
my_board.add_chess_piece(white_king)
my_board.add_chess_piece(white_bishop_right)
my_board.add_chess_piece(white_knight_right)
my_board.add_chess_piece(white_rook_right)
my_board.add_chess_piece(white_pawn_1)
my_board.add_chess_piece(white_pawn_2)
my_board.add_chess_piece(white_pawn_3)
my_board.add_chess_piece(white_pawn_4)
my_board.add_chess_piece(white_pawn_5)
my_board.add_chess_piece(white_pawn_6)
my_board.add_chess_piece(white_pawn_7)
my_board.add_chess_piece(white_pawn_8)
#(starting_x, starting_y, ending_x, starting_y)
puts ""
puts "Valid Movements:"
puts "---------------------"
#black:
my_board.board_can_move?(1, 8, 1, 5) == "yes"
my_board.board_can_move?(5, 8, 5, 7)
my_board.board_can_move?(2, 8, 3, 6)
my_board.board_can_move?(3, 8, 1, 6)
my_board.board_can_move?(4, 8, 4, 4)
my_board.board_can_move?(1, 7, 1, 5)
#white:
my_board.board_can_move?(8, 1, 8, 3)
my_board.board_can_move?(5, 1, 4, 1)
my_board.board_can_move?(7, 1, 8, 3)
my_board.board_can_move?(6, 1, 7, 2)
my_board.board_can_move?(4, 1, 7, 1)
my_board.board_can_move?(2, 2, 2, 4)
puts ""
puts "Invalid Movements:"
puts "-----------------------"
#black:
my_board.board_can_move?(1, 8, 2, 7) == "no"
my_board.board_can_move?(5, 8, 5, 4)
my_board.board_can_move?(2, 8, 2, 7)
my_board.board_can_move?(3, 8, 2, 6)
my_board.board_can_move?(4, 8, 6, 7)
my_board.board_can_move?(1, 7, 2, 6)
#white:
my_board.board_can_move?(8, 1, 3, 5)
my_board.board_can_move?(5, 1, 7, 2)
my_board.board_can_move?(7, 1, 3, 5)
my_board.board_can_move?(6, 1, 3, 5)
my_board.board_can_move?(4, 1, 2, 2)
my_board.board_can_move?(2, 2, 1, 3)
puts ""
puts ""
puts "There is No Chess Piece:"
puts "-------------------------"
my_board.board_can_move?(3, 4, 3, 5)
puts ""
puts "Not Changing Positions:"
puts "-------------------------"
my_board.board_can_move?(8, 1, 8, 1)
# puts ""
# puts "Cannot Move There:"
# puts "-------------------------"
# my_board.board_can_move?(8, 1, 3, 5)
puts ""
puts "Trying to Move Off Board:"
puts "-------------------------"
my_board.board_can_move?(8, 1, 9, 2)
my_board.board_can_move?(8, 1, 0, 2)
puts ""
| true |
a80a1c78f48fd3bb7db767cfda6435dc0e73360d | Ruby | ResignationMedia/logstash-codec-uri | /lib/logstash/codecs/uri.rb | UTF-8 | 2,043 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | # encoding: utf-8
require "logstash/codecs/base"
require "logstash/util/charset"
require "uri"
# This codec will append a string to the message field
# of an event, either in the decoding or encoding methods
#
# This is only intended to be used as an example.
#
# input {
# stdin { codec => }
# }
#
# or
#
# output {
# stdout { codec => }
# }
#
class LogStash::Codecs::URI < LogStash::Codecs::Base
# The codec name
config_name "uri"
config :charset, :validate => ::Encoding.name_list, :default => "UTF-8"
def register
@converter = LogStash::Util::Charset.new(@charset)
@converter.logger = @logger
end # def register
def decode(data)
data = @converter.convert(data)
begin
decoded = URI.decode_www_form(data)
decoded = decoded.reduce({}) do |memo, item|
memo.update({item[0] => parse(item[1])}) do |k, oldval, newval|
[oldval, newval]
end
end
yield LogStash::Event.new(decoded) if block_given?
rescue URI::Error => e
@logger.info("message" => "URI parse error: #{e}", "error" => e, "data" => data)
yield LogStash::Event.new("message" => data, "tags" => ["_uriparsefailure"]) if block_given?
end
end # def decode
# Encode a single event, this returns the raw data to be returned as a String
def encode_sync(event)
URI.encode_www_form(event.to_hash)
end # def encode_sync
private
def parse(val)
if val.is_a?(String)
if val.match?(/^[0-9.]*$/)
begin
if val.include?(".")
return Float(val)
else
return Integer(val)
end
rescue ArgumentError, TypeError
return val
end
elsif val.start_with?("{")
new_val = {}
v = val.gsub(/{|}/, "")
v.split(',').each do |vi|
vi.strip!
vals = vi.split('=>')
new_val.update({vals[0].gsub(/"/, "") => vals[1].gsub(/"/, "")})
end
return new_val
end
end
return val
end
end # class LogStash::Codecs::Uri
| true |
c1ca9b6405097d93e1b0a8b792ddab97cf03cbd1 | Ruby | justindelatorre/rb_130 | /small_problems/easy_testing/10_refutations.rb | UTF-8 | 312 | 2.90625 | 3 | [] | no_license | =begin
https://launchschool.com/exercises/4ac8e502
Write a test that will fail if 'xyz' is one of the elements in the Array list.
=end
require 'minitest/autorun'
class SampleTest < MiniTest::Test
def setup
@list = ['abc']
end
def test_refute
refute_equal(true, @list.include?('xyz'))
end
end
| true |
144a98b083e4b5deb7fe0a7e42ca9c23c8ccb997 | Ruby | AJFaraday/process_game | /lib/common_components/relative_positions.rb | UTF-8 | 1,800 | 2.96875 | 3 | [] | no_license | module CommonComponents
module RelativePositions
def closest_target
candidates = targets
if candidates.any?
candidates.sort! { |a, b| distance_to(a) <=> distance_to(b) }
candidates[0]
else
return nil
end
end
def touching?(target)
distance_to(target) < (@half_size + target.half_size) / 2
end
def on_top_of?(target)
distance_to(target) <= 5
end
def in_range_of?(target)
if target
distance_to(target) < (target.half_size + @attack_range)
else
false
end
end
def in_healing_range_of?(target)
if target
distance_to(target) < (target.half_size + @heal_range)
else
false
end
end
def distance_to(unit)
if unit.respond_to?(:x) and unit.respond_to?(:y)
Gosu.distance(x, y, unit.x, unit.y) - @half_size
else
9999999999999999999999
end
end
def right_of?(unit)
unit.respond_to?(:x) and (x - (@size - 20)) > unit.x
end
def left_of?(unit)
unit.respond_to?(:x) and (x + (@size - 20)) < unit.x
end
def higher_than?(unit)
unit.respond_to?(:y) and (y + (@size - 20)) < unit.y
end
def lower_than?(unit)
unit.respond_to?(:y) and (y - (@size - 20)) > unit.y
end
def outside_map?
@x < -100 or @y < -100 or
@x > (X_SIZE + 100) or @y > (Y_SIZE + 100)
end
def angle_to(unit)
Gosu.angle(@x, @y, unit.x, unit.y)
end
def facing_right_of?(unit)
if @angle
Gosu.angle_diff(@angle, angle_to(unit)) < 0
else
false
end
end
def facing_left_of?(unit)
if @angle
Gosu.angle_diff(@angle, angle_to(unit)) > 0
else
false
end
end
end
end | true |
780a144acaff89668f9ef3868a88c3ec756a3945 | Ruby | djmicros/tracknwin | /app/models/user.rb | UTF-8 | 1,715 | 2.53125 | 3 | [] | no_license | class User < ActiveRecord::Base
include Amistad::FriendModel
has_many :rides, dependent: :destroy
has_many :microposts, dependent: :destroy
attr_accessible :name, :email, :password, :password_confirmation, :gender, :birthdate, :team, :country
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
validates_confirmation_of :password
validates :gender, presence: true
VALID_BIRTHDATE_REGEX = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/
validates :birthdate, presence: true,
format: { with: VALID_BIRTHDATE_REGEX }
validates :country, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
def self.calculate_stats(user)
rides = user.rides
if rides.count == 0
@stats = []
@stats[0] = 0
@stats[1] = 0
@stats[2] = 0
else
@distance_sum = 0
@duration_sum = 0
@speed_sum = 0
(0..rides.count-1).each do |i|
@distance_sum = @distance_sum + rides[i].distance.to_f
@duration_sum = @duration_sum + rides[i].duration.to_f
@speed_sum = @speed_sum + rides[i].speed.to_f
end
@avg_speed = @speed_sum/rides.count
@stats = []
@stats[0] = @distance_sum.round(2)
@stats[1] = @duration_sum
@stats[2] = @avg_speed.round(2)
return @stats
end
end
end | true |
3f5873f9ca7ada53dadab29fe2b62e7173a15aff | Ruby | The-Beez-Kneez/AutomatedTesting | /lib/deck.rb | UTF-8 | 969 | 3.890625 | 4 | [] | no_license | # deck.rb
require_relative 'card'
class Deck
# Be able to be instantiated.
# Be created with 52 Card objects as attributes.
attr_reader :deck
def initialize
# FEEDBACK EDIT: COULD HAVE MADE VALUES AND SUITS INTO CONSTANTS AND REFERENCED--
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
suits = ['spades','hearts', 'diamonds', 'clubs']
@deck = []
values.each do |value|
suits.each do |suit|
@deck << Card.new(value, suit)
end
end
end
# Have a method called draw which removes a Card from the Deck and returns the removed Card.
def draw
#picks a random card from the deck
card_draw = @deck.sample
# returns a card
return card_draw
end
# Have a shuffle method
def shuffle
# shuffles the deck
@deck.shuffle
return @deck
end
# Have a count method which returns the number of cards in the Deck.
def count
deck_count = deck.count
return deck_count
end
end
| true |
2f4e48f3bc11e5434ede1588d8fbcf61a6316e4c | Ruby | ticho/tic-tac-toe | /lib/boardcase.rb | UTF-8 | 205 | 2.703125 | 3 | [] | no_license | # frozen_string_literal: true
# one case on the boardgame, contains only its own status
class BoardCase
attr_accessor :status
def initialize
@status = ' '
end
def to_s
@status
end
end
| true |
bce82da8ed5f04f354aec1abf33470abd45602a5 | Ruby | srsvybes1/ruby-objects-has-many-through-lab-onl01-seng-pt-032320 | /lib/doctor.rb | UTF-8 | 495 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Doctor
attr_accessor :name, :appointment, :patient
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def new_appointment(date, patient)
Appointment.new(date, patient, self)
end
def appointments
Appointment.all.select do |appointment|
appointment.doctor == self
#Appointment.all.select {|appointment| appointment.doctor == self}
end
end
def patients
self.appointments.collect {|appointment| appointment.patient}
end
end
| true |
3a6cd3637568b6bc944f370cc17f81774c759e1f | Ruby | bullhornfixie/makers-challenge-chitter | /lib/users.rb | UTF-8 | 545 | 2.984375 | 3 | [] | no_license | require 'pg'
require_relative 'database_connection'
class Users
attr_reader :name
# makes instances accessible to others
# returns the information asked for about the object
if ENV['ENVIRONMENT'] == 'test'
DatabaseConnection.setup(dbname: 'chitter_test')
else
DatabaseConnection.setup(dbname: 'chitter')
end
def initialize(name)
@name = name
end
def self.create(name)
inject = DatabaseConnection.query("INSERT INTO users (name) VALUES('#{name}') RETURNING id;")
object = Users.new(name)
end
end
| true |
19e30a38c4f9b23211e62ac6f88787577e98e26a | Ruby | Kighway/Engaged-Humanity-API | /db/seeds.rb | UTF-8 | 3,968 | 2.609375 | 3 | [] | no_license | #
# USERS
#
jenny = User.create({first_name: "Jenny", last_name: "Kats", username: "jennyk", email: "jenny@fake.com", profile_url: "../images/jenny.jpeg", password: "1234"})
kyle = User.create({first_name: "Kyle", last_name: "Tulod", username: "kylet", email: "kyle@fake.com", profile_url: "../images/dummy.jpeg", password: "1234"})
andrew = User.create({first_name: "Andrew", last_name: "Nease", username: "andrewn", email: "andrew@fake.com", profile_url: "../images/dummy.jpeg", password: "1234"})
kyle_friend = User.create({first_name: "Kylo", last_name: "Peterson", username: "kylop", profile_url: "../images/dummy.jpeg", email: "kylefriend@fake.com", password: "1234"})
jerk = User.create({first_name: "Donald", last_name: "Unger", username: "donaldu", email: "jerk@fake.com", profile_url: "../images/dummy.jpeg", password: "1234"})
#
# FRIENDSHIPS
#
# jenny follows kyle and andrew
jenny.followings << kyle
jenny.followings << andrew
# kyle follows jenny
kyle.followings << jenny
# andrew follows kyle
andrew.followings << kyle
# kyle's friend follows kyle
kyle_friend.followings << kyle
#
# INTERESTS
#
dogs = Interest.create(title: "dogs")
cats = Interest.create(title: "cats")
#
# ARTICLES
#
article1 = Article.create({title: "Cat are fantastic.", description: "An article about Cats.", url: "http://www.url1.com", source: "Cat Fancy Mag", author: "Caterina Snowbottom", image_url: "http://www.url1.com/cat.jpg", date: "date is a currently a string"})
article2 = Article.create({title: "Dogs are wonderful.", description: "An article about Dogs.", url: "http://www.url2.com", source: "Dog Power Mag", author: "Rex Fido", image_url: "http://www.url2.com/dog.jpg", date: "date is a currently a string"})
article3 = Article.create({title: "Puppies pee a lot.", description: "A second article about Dogs.", url: "http://www.url3.com", source: "Dog Power Mag", author: "Rex Fido", image_url: "http://www.url3.com/dog2.jpg", date: "date is a currently a string"})
article4 = Article.create({title: "It's raining cats and dogs.", description: "An article about cats and dogs.", url: "http://www.url4.com", source: "Dogs and Cats Together Mag", author: "Max Headspace", image_url: "http://www.url4.com/cat_and_dog.jpg", date: "date is a currently a string"})
article5 = Article.create({title: "Puppies pee. So what?", description: "An article about puppies still peeing.", url: "http://www.url5.com", source: "Puppy Power Mag", author: "Max Headspace", image_url: "http://www.url5.com/peeing_puppy.jpg", date: "date is still a string"})
#
# ARTICLE INTERESTS
#
article1.interests << Interest.find_by(title: "cats")
article2.interests << Interest.find_by(title: "dogs")
article3.interests << Interest.find_by(title: "dogs")
article4.interests << [Interest.find_by(title: "dogs"), Interest.find_by(title: "cats")]
article5.interests << Interest.find_by(title: "dogs")
#
# LIKES
#
# Jenny likes cat article
Like.create(user_id: 1, article_id: 1)
# Kyle likes two dog articles
Like.create(user_id: 2, article_id: 5)
Like.create(user_id: 2, article_id: 2)
Like.create(user_id: 2, article_id: 3)
# Andrew likes cat article 1, and dog article 2, but not puppies
Like.create(user_id: 3, article_id: 1)
Like.create(user_id: 3, article_id: 2)
# Donald doesn't like anything
#
# USER INTERESTS
#
jenny.interests << cats
kyle.interests << dogs
andrew.interests << cats
andrew.interests << dogs
# NOTES
# rake db:reset -- drop, create, migrate, seed
# find all of a user's likes
# User.first.likes
# find all of a user's liked articles
# User.first.articles
# find all of a user's friends
# User.first.friends
# find all of a user's friend's likes
# User.first.friends.first.likes
# find all articles about a topic
# Interest.first.articles
# find all interests associated with an article
# Article.first.interests
# find all of a user's interest's articles
# User.first.interests.first.articles
# for fun:
# User.first.articles.first.interests.first.articles.first.users
| true |
8442e6e5cb9ccb4dc6b3574fdb918240752510aa | Ruby | Stanleyyork/dewey | /app/controllers/api/alexa_controller.rb | UTF-8 | 1,617 | 2.78125 | 3 | [] | no_license | class Api::AlexaController < ApplicationController
def show
title = params[:book_title]
@book = Book.find_by_title(title)
@book = Book.where("title LIKE ?", "%#{title}%").first if @book.nil?
@book = Book.where("title LIKE ?", "%#{title.capitalize}%").first if @book.nil?
@book = Book.where("title LIKE ?", "%#{title.split(" ").map{|x| x.capitalize}.join(" ")}%").first if @book.nil?
@grid = ImageAnalysis.find_by_id(book.image_analysis_id) unless @book.nil?
if book.nil?
render json: {response: "Sorry, I can't find that book"}
else
render json: {response: "#{book.title} is near the #{relative_place}"}
end
end
private
attr_reader :book, :grid
def relative_place
book_x = book.x
book_y = book.y
location = ""
y_min = grid.y2
y_max = grid.y3
y_first_third = y_min + ((y_max - y_min)/3)
y_second_third = y_max - ((y_max - y_min)/3)
# y_mid = (y_max - y_min)/2.0
# y_q3 = y_mid + ((y_max - y_mid)/2.0)
# y_q1 = y_mid - ((y_mid - y_min)/2.0)
if book_y < y_second_third && book_y > y_first_third
location += "middle shelf "
elsif book_y < y_first_third
location += "top shelf "
else
location += "bottom shelf "
end
x_min = grid.x1
x_max = grid.x2
x_mid = (x_max - x_min)/2.0
x_q3 = x_mid + ((x_max - x_mid)/2.0)
x_q1 = x_mid - ((x_mid - x_min)/2.0)
if book_x < x_q3 && book_x > x_mid
location += "slightly to the right"
elsif book_x > x_q1 && book_x < x_mid
location += "slightly to the left"
elsif book_x < x_q1
location += "on the far left"
elsif book_x > x_q3
location += "on the far right"
end
location
end
end | true |
05b4b3d6d0a0238361a0a6a46b84ae18f25418f9 | Ruby | Imhotep504/Ruby | /class.rb | UTF-8 | 699 | 3.578125 | 4 | [] | no_license | #!/usr/bin/ruby
o = Object.new
puts o.object_id
puts "'o' is of class: #{o.class}"
class Customer
def customer_id=(customer_id)
@customer_id = customer_id
end
def customer_id
@customer_id
end
attr_reader :city
attr_writer :city
attr_accessor :place
end
c = Customer.new
puts c.object_id
puts "'c'is of class: #{c.class}"
puts c.city = "New York"
puts c.city
puts c.place = "Brooklyn"
puts c.place
c2 = Customer.new
puts c2.object_id
puts c2.city = "Miami"
puts c2.place = "Dade"
puts c2.customer_id = "007"
puts "c2 is class of: #{c2.class}"
puts c2
c3 = Customer.new(21, "chiraq", "uptown" )
puts c3.customerid
puts c3.name
puts c3.city
| true |
cd44f065dc84a55d544fb2b30781f5ac99634225 | Ruby | jordanmaguire/frontier_generators | /lib/frontier/association.rb | UTF-8 | 1,840 | 2.515625 | 3 | [] | no_license | require_relative "attribute.rb"
class Frontier::Association < Frontier::Attribute
include Frontier::ErrorReporter
attr_reader :attributes, :form_type
ID_REGEXP = /_id\z/
def initialize(model, name, properties)
super
# Convert:
# address_id -> address
# address -> address
@name = name.to_s.sub(ID_REGEXP, "")
@attributes = parse_attributes(properties[:attributes] || [])
@form_type = parse_form_type(properties[:form_type])
end
def associations
attributes.select(&:is_association?)
end
def association_class
if properties[:class_name].present?
properties[:class_name]
else
name.camelize
end
end
alias as_constant association_class
def as_factory_name
":#{association_class.underscore}"
end
# some_thing_id -> ":some_thing_id"
# some_thing -> ":some_thing_id"
def as_field_name
"#{as_symbol}_id"
end
def is_association?
true
end
def is_nested?
form_type == "inline"
end
alias model_name name
# Factories
def as_factory_declaration
Frontier::Association::FactoryDeclaration.new(self).to_s
end
private
def parse_attributes(attributes_properties)
attributes_properties.collect do |name, attribute_or_association_properties|
Frontier::Attribute::Factory.build_attribute_or_association(self, name, attribute_or_association_properties)
end
end
def parse_form_type(form_type_property)
case form_type_property.to_s
when "inline", "select"
form_type_property.to_s
else
report_error("Unknown form type: '#{form_type_property.to_s}', defaulting to 'select'")
"select"
end
end
end
require_relative "association/factory_declaration.rb"
require_relative "association/feature_spec_assignment.rb"
require_relative "association/model_implementation.rb"
| true |
5d9fec704dd6ff5e01d8a09a2c0a2e8dd5c9a560 | Ruby | slickpk/testffl2_app | /test_sql.rb | UTF-8 | 309 | 2.703125 | 3 | [] | no_license | require 'rubygems'
require 'sqlite3'
db = SQLite3::Database.new('db/development.sqlite3')
results = db.execute("Select Abrv, Team from Abbrvs")
test1 = results[0][1].downcase
test2 = test1[0..test1.index(' ') - 1] + test1[test1.index(' ') + 1..test1.length]
puts test2
| true |
fb36c52b1be5acbf0467969f580b32c327ea1dc6 | Ruby | IalyRambe/ExercicesRuby_Projet | /exo_15.rb | UTF-8 | 154 | 3.4375 | 3 | [] | no_license | puts "Bonjour, c'est quand ton année de naissance ?"
year_birth = gets.to_i
year_birth.upto(2020) do |i|
puts "- nombre = #{i} #{i - year_birth}"
end
| true |
a52ececc93c936e12efb3bcaab22db2d3593ee00 | Ruby | eedrummer/laika | /app/models/telecom.rb | UTF-8 | 2,296 | 2.734375 | 3 | [] | no_license | # Encapsulates the telecom section of a C32. Instead of having
# a bunch of telecom instances as part of a has_many, we've
# rolled the common ones into a single record. This should
# make validation easier when dealing with phone numbers
# vs. email addresses
class Telecom < ActiveRecord::Base
strip_attributes!
# AG: did you expect telecomable? ;-)
# RM: yes... yes I did...
belongs_to :reachable, :polymorphic => true
after_save { |r| r.reachable.try(:patient).try(:update_attributes, :updated_at => DateTime.now) }
def blank?
%w[ home_phone work_phone mobile_phone
vacation_home_phone email url ].all? {|a| read_attribute(a).blank? }
end
def requirements
case reachable_type
when 'Provider', 'Support', 'InsuranceProviderPatient', 'AdvanceDirective', 'Encounter':
{
:home_phone => :hitsp_r2_optional,
:work_phone => :hitsp_r2_optional,
:mobile_phone => :hitsp_r2_optional,
:vacation_home_phone => :hitsp_r2_optional,
:email => :hitsp_r2_optional,
:url => :hitsp_r2_optional,
}
end
end
def to_c32(xml= XML::Builder.new)
if home_phone && home_phone.size > 0
xml.telecom("use" => "HP", "value" => 'tel:' + home_phone)
end
if work_phone && work_phone.size > 0
xml.telecom("use" => "WP", "value" => 'tel:' + work_phone)
end
if mobile_phone && mobile_phone.size > 0
xml.telecom("use" => "MC", "value" => 'tel:' + mobile_phone)
end
if vacation_home_phone && vacation_home_phone.size > 0
xml.telecom("use" => "HV", "value" => 'tel:' + vacation_home_phone)
end
if email && email.size > 0
xml.telecom("value" => "mailto:" + email)
end
if url && url.size > 0
xml.telecom("value" => url)
end
end
def randomize()
self.home_phone = format_number()
self.work_phone = format_number()
self.mobile_phone = format_number()
end
def format_number()
@number = Faker::PhoneNumber.phone_number
@number = @number.gsub /\./, "-"
@number = @number.gsub /\)/, "-"
@number = @number.gsub /\(/, "1-"
@number = @number.gsub /\ x.*/, ""
if (@number.split("-")[0] == "1")
@number = "+" + @number
else
@number = "+1-" + @number
end
end
end
| true |
3cfdf65db78923e93b2ad50e5d45f488b5a0c15c | Ruby | griswoldbar/patterns | /lib/things/person.rb | UTF-8 | 129 | 2.734375 | 3 | [] | no_license | class Person
attr_reader :name
def initialize(name)
@name = name
end
def prod_reaction
"how dare you!"
end
end | true |
02fd35e6fd8b9b4aa902d0c0137b020a42aab82e | Ruby | dmullek/dominion | /app/cards/haven.rb | UTF-8 | 1,464 | 2.578125 | 3 | [] | no_license | class Haven < Card
def starting_count(game)
10
end
def cost(game, turn)
{
coin: 2
}
end
def type
[:action, :duration]
end
def play(game, clone=false)
CardDrawer.new(game.current_player).draw(1)
game.current_turn.add_actions(1)
@log_updater.get_from_card(game.current_player, '+1 action')
@play_thread = Thread.new {
ActiveRecord::Base.connection_pool.with_connection do
set_aside_card(game)
end
}
end
def set_aside_card(game)
hand = game.current_player.hand
if hand.count == 0
@log_updater.custom_message(nil, 'But there are no cards to set aside')
elsif hand.count == 1
hand.first.update_attribute :state, 'haven'
else
action = TurnActionHandler.send_choose_cards_prompt(game, game.current_player, hand, 'Choose a card to set aside:', 1, 1, 'set_aside')
TurnActionHandler.process_player_response(game, game.current_player, action, self)
end
end
def process_action(game, game_player, action)
if action.action == 'set_aside'
card = PlayerCard.find action.response
card.update_attribute :state, 'haven'
LogUpdater.new(game).set_aside(game_player, [card])
end
end
def duration(game)
havens = game.current_player.havens.to_a
unless havens.empty?
game.current_player.havens.update_all(state: 'hand')
LogUpdater.new(game).return_to_hand(game.current_player, havens)
end
end
end
| true |
e14889a8f4a98afdc9b723bca18c9c9d85deda17 | Ruby | violentr/First_3_weeks_at_makers | /Learn-the-ruby-hard-way-week1/ex22.rb | UTF-8 | 698 | 3.390625 | 3 | [] | no_license |
def write_file(filenameR, filenameW)
# open the source file
file =File.open(filenameR)
# open the destination file for writing
file_d = File.open(filenameW, 'w')
# read the data from the source file
contents = file.read
# write to the destination
file_d.write(contents)
# close source file
file.close
# close destination file
file_d.close
end
puts "Please enter the name of the source file:"
file_source =gets.chomp
puts "you have choisen #{file_source} filename this file #{file_source.length} bytes long"
puts "***" *10
puts "Please enter the name of the destination file:"
file_dest =gets.chomp
puts "you have choisen #{file_dest} filename: "
write_file(file_source,file_dest)
| true |
6d031b4df4185ed56ebe63db7c0a6415b95145bf | Ruby | LichP/Porp | /lib/porp/stock/entity.rb | UTF-8 | 3,223 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #!/usr/bin/env ruby
#
# Porp - The Prototype Open Retail Platform
#
# Copyright (c) 2011 Phil Stewart
#
# License: MIT (see LICENSE file)
class Stock
=begin
The StockEntity class represents physical stock. Quantities of StockEntities
are represented by StockHoldings.
=end
class Entity < Ohm::Model
attribute :description
index :description
#set :sale_entities, SaleEntity
collection :holdings, Holding, :entity
list :movements, Movement
collection :plus, PLU, :stock_entity
# Find an entity by PLU
def self.find_by_plu(plu_value)
plu = PLU.lookup(plu_value)
if !plu.nil?
self[plu.stock_entity_id]
else
nil
end
end
# Look up a holding corresponding to the passed attributes
#
# @params [Hash] attrs: attributes of the holding
# @returns the corresponding holding or nil
def holding(attrs)
if attrs.kind_of?(Hash)
holdings.find(name: attrs[:holder].to_s + "_" + attrs[:status].to_s).first
else
nil
end
end
# Check the supplied target is a MovementTarget. If a hash is passed,
# attempt to find a corresponding holding on this entity
#
# @param target: The target to check / hash to look up
def lookup_target(target)
if target.kind_of?(Hash)
target = holding(target)
end
unless target.kind_of?(MovementTarget)
raise Orp::MovementInvalidTarget, "#{target} is not a valid MovementTarget"
end
target
end
# Move stock represented by this entity
#
# @param [MovementTarget, Hash] source_target: The source of the stock
# to be moved, represented by a MovementTarget. Alternatively, if a
# Hash is passed, a Holding corresponsing to to the passed attributes
# will be used as the target.
# @param [MovementTarget, Hash] dest_target: The destination of stock to
# be mover, either as a MovementTarget or Hash specifying Holding as
# above.
# @param [Integer] qty: The number of units of stock being moved.
# @param [Rational] ucost: The cost price per unit of stock. This can be
# overrided by the source_target if the value of stock is already known.
# @return The completion status of the Movement
def move(source_target, dest_target, qty, ucost)
# Make sure the supplied target information is valid, looking up holdings
# as appropriate
source_target = lookup_target(source_target)
dest_target = lookup_target(dest_target)
# Create and conduct movement
movement = Movement.move_no_cleanup(source_target: source_target,
source_entity_id: id,
source_amount: Amount.new(qty, ucost),
dest_target: dest_target,
dest_entity_id: id)
# Return the completion status of the movement
movements << movement
movement.completed
end
def self.const_missing(name)
begin
Stock.const_get(name)
rescue NameError
Object.const_get(name)
end
end
end
end
| true |
75d4d1d72f5e833adfaaa49544799ab50b825938 | Ruby | LogaJ/ruby_prag_prog | /variables/vars.and.object.reference.properties.rb | UTF-8 | 221 | 3.46875 | 3 | [] | no_license | person = "Tim"
puts "The object in 'person' is an instance of a: #{person.class} class."
puts "The object 'person' has an object id of: #{person.object_id}."
puts "And the string referenced by 'person' is: '#{person}'."
| true |
70385583ea9e12a539b829b4706c0032803a86f4 | Ruby | fabriciojoc/ws_coordination_protocols_rails | /bank/app/models/coordination_context.rb | UTF-8 | 897 | 2.625 | 3 | [
"MIT"
] | permissive | class CoordinationContext
def initialize(coordination_type, id, registration_service, card_number, card_password, card_security_code, value)
@id = id
@coordination_type = coordination_type
@registration_service = registration_service
@card_number = card_number
@card_password = card_password
@card_security_code = card_security_code
@value = value
end
def id
@id
end
def coordination_type
@coordination_type
end
def registration_service
@registration_service
end
def card_number
@card_number
end
def card_password
@card_password
end
def card_security_code
@card_security_code
end
def value
@value
end
def tpc_service
@tpc_service
end
def set_tpc_service(service)
@tpc_service = service
end
def account
@account
end
def set_account(account)
@account = account
end
end | true |
d906855b6116a576b446d1170e2572fe4aebc683 | Ruby | kenjione/optimize_methods | /optimize.rb | UTF-8 | 1,490 | 2.515625 | 3 | [] | no_license | require 'sinatra'
require 'active_support/inflector'
require File.dirname(__FILE__)+"/methods/drawplot.rb"
require File.dirname(__FILE__)+"/methods/base_optimize_method"
BaseOptimizeMethod.require_methods
helpers do
def link_to(name, path, options = {})
params = options.map { |k, v| %|#{k}="#{v}"| }.join
params = ' ' + params unless params == ''
%|<a href="#{path}"#{params}>#{name}</a>|
end
def print_float(float, acc = 3)
"%.#{acc}f" % float
end
def render_output_form(result, params)
erb(:output_form, locals: {result: result, params: params})
end
def render_input_function_form(func="x**2 + y**2 - 2 * x * sin(y) - 3 * sin(x) * y")
erb :input_function_form, locals: {func: func}
end
end
get '/' do
erb :index
end
get '/:name' do |name|
erb :"#{name}/form"
end
post '/:name' do |name|
params[:function] = params[:opt_type].to_s + "*(" + params[:function].to_s + ")"
params[:opt_type]= params[:opt_type].to_f
params[:opt_type] == -1.0 ? params[:extremum] = "Max" : params[:extremum] = "Min"
begin
timeout(2) do
result = name.camelize.constantize.find_extremum(params)
drawplot(result.draw_points, name.to_s)
drawfunc(result.func[4...-1])
erb :"/#{name}/handler", locals: {params: params, result: result}
end
rescue TimeoutError => err
#puts err.message
erb :error, locals: {err: err}
rescue Exception => err
#puts err.message
erb :error, locals: {err: err}
end
end
| true |
5f1d553e9bb8a27870ac2960ec509de02fee53c7 | Ruby | phss/playground | /exercises/euler/problem76.rb | UTF-8 | 271 | 3.546875 | 4 | [] | no_license | def ways_to_make(amount)
values = (1..(amount-1)).to_a
ways = Array.new(amount + 1, 0)
ways[0] = 1
values.each do |value|
(value..amount).each do |idx|
ways[idx] += ways[idx - value]
end
end
return ways[amount]
end
puts ways_to_make(100)
| true |
b6e2d1e55c2ea01376d0adad6f134a1c2c677ec8 | Ruby | NiestrojMateusz/Launch-School-101 | /exercises/Easy2/1_Teddy.rb | UTF-8 | 1,440 | 4.5625 | 5 | [] | no_license | # How old is Teddy?
# Build a program that randomly generates and prints Teddy's age. To get the age, you should generate a random number between 20 and 200.
# Example Output
# Teddy is 69 years old!
age = rand(20...201)
puts "Who's age you want to know?"
name = gets.chomp.capitalize
name = "Teddy" if name == ""
puts "#{name} is #{age} yeras old"
#===========================================================================
# Other intresting solution
def print_age(name)
puts "#{name == '' ? 'Teddy' : name} is #{rand(20..200)} years old!"
end
puts '=> Enter a name: '
print_age(gets.chomp)
=begin
Understand the Problem:
input: -string (as a name)
output: -Print a sentence with name age
-When not string was passed, deafult name is "Teddy"
-Sentence is a string
Data structure:
Input: String
Rules: - need to generate a random age number
- deafult name is Teddy when method was called without argument
Output: String sentcence
Algorithm:
- Ask user to type a name
- put name as a method argument
- Generate a random number from 20 to 200(include)
-using a Random#rand method
- Assign random method to variable
- assing "Teddy" to name variable if user type a empty string
- Print out a sentence
=end
def print_age(name)
age = rand(2..200)
name = "Teddy" if name ==""
puts "#{name} is #{age} years old"
end
puts 'Enter a name:'
print_age(gets.chomp) | true |
27223540a42092abf6bb35572e1a3ac2640f0015 | Ruby | rinapratama335/belajar-ruby | /5.perulangan/1.while.rb | UTF-8 | 90 | 2.9375 | 3 | [] | no_license | nilai = 1
while nilai <= 10 do
puts "Perulangan ke #{nilai}"
nilai = nilai + 1
end | true |
2b65ca9bec33ca2edf078d7a49187f6075a53620 | Ruby | beasteim/ruby-challenges | /help.rb | UTF-8 | 269 | 3.328125 | 3 | [] | no_license | #can successfully access each index of a string
#cannot convert an index into a fixnum
dob = '0505'
first = dob[0].to_i
puts first
second = dob[1].to_i
puts second
final = first + second
yay = 123
yay.to_s
puts yay.class
darn = "yay"
yo = darn.to_i
puts yo.class
| true |
7976cbc73fb3bf47a2c22d8f726981ecb7041a42 | Ruby | gahenton/intro2programming | /Methods/chaining_methods.rb | UTF-8 | 118 | 3.28125 | 3 | [] | no_license | def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
add(20, 45)
# returns 65
subtract(80, 10)
# returns 70
| true |
48aa7d4b4ce67946028d4513bde81a5fefd44b84 | Ruby | ommiles/birdwatcher-bros | /member.rb | UTF-8 | 422 | 3.171875 | 3 | [] | no_license | class Member
attr_reader :member_name
def initialize(member_name)
@member_name = member_name
end
def create_club(club_name, location)
new_club = Club.new(club_name, location)
new_club.members << self
new_club
end
def join_club(club_name)
joiner = Club.all.find{|club| club.club_name == club_name}
joiner.members << self
joiner
end
end | true |
95cfc2e12713a0c0f09d73dc779454477ba1034c | Ruby | HiramIO/learn_ruby | /04_pig_latin/pig_latin.rb | UTF-8 | 2,405 | 3.53125 | 4 | [] | no_license | def translate(string)
output = []
words = string.split
words.each do |word|
text = word.split(//)
if text[0] == "a"
output << text.join + "ay "
elsif text[0] == "e"
output << text.join + "ay "
elsif text[0] == "i"
output << text.join + "ay "
elsif text[0] == "o"
output << text.join + "ay "
elsif text[0] == "u"
output << text.join + "ay "
else
if text[1] == "a"
output << text.rotate.join + "ay "
elsif text[1] == "e"
output << text.rotate.join + "ay "
elsif text[1] == "i"
output << text.rotate.join + "ay "
elsif text[1] == "o"
# output << text.rotate.join + "ay "
# elsif text[1] == "u"
output << text.rotate.join + "ay "
else
if text[2] == "a"
output << text.rotate(2).join + "ay "
elsif text[2] == "e"
output << text.rotate(2).join + "ay "
elsif text[2] == "i"
output << text.rotate(2).join + "ay "
elsif text[2] == "o"
# output << text.rotate(2).join + "ay "
# elsif text[2] == "u"
output << text.rotate(2).join + "ay "
else
output << text.rotate(3).join + "ay "
end
end
end
end
output.join.rstrip
end
# require 'pry'
# def translate(string)
# words = string.split
# words. do |word|
# word = string.split(//)
# if word[0] == "a"
# output << string.to_s + "ay"
# elsif word[0] == "e"
# return string.to_s + "ay"
# elsif word[0] == "i"
# return string.to_s + "ay"
# elsif word[0] == "o"
# return string.to_s + "ay"
# elsif word[0] == "u"
# return string.to_s + "ay"
# else
# if word[1] == "a"
# return word.rotate.join + "ay"
# elsif word[0] == "e"
# return word.rotate.join + "ay"
# elsif word[0] == "i"
# return word.rotate.join + "ay"
# elsif word[0] == "o"
# return word.rotate.join + "ay"
# elsif word[0] == "u"
# return word.rotate.join + "ay"
# else
# return word.rotate(2).join + "ay"
# end
# end
# end
# end | true |
39c777149b3323c27275a2d83034bbdc2537575f | Ruby | lymanwong/Ruby-Stuff | /algorithms/which_are_in/which_are_in.rb | UTF-8 | 971 | 4.34375 | 4 | [
"MIT"
] | permissive | # Given two arrays of strings a1 and a2 return a sorted array in lexicographical order and without duplicates of the strings of a1 which are substrings of strings of a2.
# Example: a1 = ["arp", "live", "strong"]
# a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
# returns ["arp", "live", "strong"]
# a1 = ["tarp", "mice", "bull"]
# a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
# returns []
# Note: Arrays are written in "general" notation. See "Your Test Cases" for examples in your language.
def in_array(arr1,arr2)
collection = []
arr1.each do |first|
arr2.each do |second|
if second.include? first
collection << first
end
end
end
return collection.uniq
end
a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
b1 = ["tarp", "mice", "bull"]
b2 = ["lively", "alive", "harp", "sharp", "armstrong"]
p in_array(a1,a2) == ["arp", "live", "strong"] #true
p in_array(b1,b2) == [] #true
| true |
c8d607abfe45a554424610377af78ed6df9eb340 | Ruby | mwakipesile/launch-school-130 | /sum_of_multiples.rb | UTF-8 | 342 | 3.71875 | 4 | [] | no_license | require 'pry'
class SumOfMultiples
attr_reader :set
def initialize(*set)
@set = set.empty? ? [3, 5] : set
end
def self.to(number)
new.to(number)
end
def to(number)
(0...number).select { |number| multiple?(number) }.inject(:+)
end
def multiple?(number)
set.any? { |factor| number % factor == 0 }
end
end
| true |
d07217e8d039a6f2d666811b6595bf655d51fdd7 | Ruby | fjohnson87/ruby-enumerables-reverse-each-word-lab-online-web-prework | /reverse_each_word.rb | UTF-8 | 188 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word
reverse_each_word = ["Hello", "there", "and", "how", "are", "you?"].join(' ')
reverse_each_word.each do |reverse_each_word|
puts "#{reverse_each_word.reverse}
end | true |
fc53ed6cc63fe0dd08b2a18b095c2de688ede713 | Ruby | DimaKrupko/Ruby2020 | /add_2.rb | UTF-8 | 300 | 3.234375 | 3 | [] | no_license |
puts "Введіть ціну товару,знижку у відсотках,та кількість товару через пробіл"
result=0
c=gets.chomp
c=c.split(" ")
price, discount, number =c[0].to_f, c[1].to_i, c[2].to_i
result=price*(discount*0.01)*number
puts result.round
| true |
e9550349b03c2f7e87600c9bbd72e778174086ab | Ruby | rrrene/ud | /bin/ud | UTF-8 | 906 | 2.984375 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env ruby
# -*- coding: UTF-8 -*-
require 'trollop'
require 'ud'
opts = Trollop.options do
version "ud #{UD.version}"
banner <<-EOS
UD is a command-line tool to scrape definitions from the Urban Dictionary.
Usage:
ud [options] <word(s)>
where [options] are:
EOS
opt :ratio, 'Filter by upvotes/downvotes ratio', :type => :float, :default => 0.0, :short => '-r'
opt :count, 'Limit the number of definitions', :type => :int, :default => 1, :short => '-n'
opt :color, 'Use colorized output', :default => true
opt :up, 'Shortcut for \'-r 2\''
end
Trollop.die :ratio, 'must be non-negative' if opts[:ratio] < 0
Trollop.die :count, 'must be non-negative' if opts[:count] < 0
opts[:ratio] = 2 if opts[:up]
if ARGV.empty?
puts 'Error: No word provided. Use -h or --help to see the help.'
exit 1
end
q = UD.query(ARGV.join(' '), opts)
puts UD.format_results(q, opts[:color])
| true |
7895c2083b64036afc1a8a58effd402be01e4e4e | Ruby | nataliagalan/advanced-hashes-hashketball-chi01-seng-ft-080320 | /hashketball.rb | UTF-8 | 6,063 | 3.34375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
# Write your code below game_hash
def game_hash
{
home: {
team_name: "Brooklyn Nets",
colors: ["Black", "White"],
players: [
{
player_name: "Alan Anderson",
number: 0,
shoe: 16,
points: 22,
rebounds: 12,
assists: 12,
steals: 3,
blocks: 1,
slam_dunks: 1
},
{
player_name: "Reggie Evans",
number: 30,
shoe: 14,
points: 12,
rebounds: 12,
assists: 12,
steals: 12,
blocks: 12,
slam_dunks: 7
},
{
player_name: "Brook Lopez",
number: 11,
shoe: 17,
points: 17,
rebounds: 19,
assists: 10,
steals: 3,
blocks: 1,
slam_dunks: 15
},
{
player_name: "Mason Plumlee",
number: 1,
shoe: 19,
points: 26,
rebounds: 11,
assists: 6,
steals: 3,
blocks: 8,
slam_dunks: 5
},
{
player_name: "Jason Terry",
number: 31,
shoe: 15,
points: 19,
rebounds: 2,
assists: 2,
steals: 4,
blocks: 11,
slam_dunks: 1
}
]
},
away: {
team_name: "Charlotte Hornets",
colors: ["Turquoise", "Purple"],
players: [
{
player_name: "Jeff Adrien",
number: 4,
shoe: 18,
points: 10,
rebounds: 1,
assists: 1,
steals: 2,
blocks: 7,
slam_dunks: 2
},
{
player_name: "Bismack Biyombo",
number: 0,
shoe: 16,
points: 12,
rebounds: 4,
assists: 7,
steals: 22,
blocks: 15,
slam_dunks: 10
},
{
player_name: "DeSagna Diop",
number: 2,
shoe: 14,
points: 24,
rebounds: 12,
assists: 12,
steals: 4,
blocks: 5,
slam_dunks: 5
},
{
player_name: "Ben Gordon",
number: 8,
shoe: 15,
points: 33,
rebounds: 3,
assists: 2,
steals: 1,
blocks: 1,
slam_dunks: 0
},
{
player_name: "Kemba Walker",
number: 33,
shoe: 15,
points: 6,
rebounds: 12,
assists: 12,
steals: 7,
blocks: 5,
slam_dunks: 12
}
]
}
}
end
# Write code here
def num_points_scored(player)
points_scored = 0
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
if stats[:player_name] == player
points_scored = stats[:points]
return points_scored
end
end
end
end
def shoe_size(player)
shoe = 0
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
if stats[:player_name] == player
shoe = stats[:shoe]
return shoe
end
end
end
end
def team_colors(team)
colors = []
game_hash.each do |home_away, team_attributes|
if team_attributes[:team_name] == team
colors = team_attributes[:colors]
return colors
end
end
end
def team_names
teams_array = []
teams_array << game_hash[:home][:team_name]
teams_array << game_hash[:away][:team_name]
return teams_array
end
def player_numbers(team)
team_numbers = []
if game_hash[:home][:team_name] == team
game_hash[:home][:players].each do |stats|
team_numbers << stats[:number]
end
else game_hash[:away][:team_name] == team
game_hash[:away][:players].each do |stats|
team_numbers << stats[:number]
end
end
return team_numbers
end
def player_stats(player)
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
if stats[:player_name] == player
return stats
end
end
end
end
def big_shoe_rebounds
biggest = 0
rebounds = 0
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
size = stats[:shoe]
if size > biggest
biggest = size
rebounds = stats[:rebounds]
end
end
end
rebounds
end
def most_points_scored
most_points = 0
player = ""
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
points = stats[:points]
if points > most_points
most_points = points
player = stats[:player_name]
end
end
end
player
end
def winning_team
home_points = 0
away_points = 0
home_array = []
away_array = []
most_points = 0
team = ""
game_hash[:home][:players].each do |stats|
home_array << stats[:points]
end
home_array.reduce(0) do |sum, points|
home_points = sum + points
end
game_hash[:away][:players].each do |stats|
away_array << stats[:points]
end
away_array.reduce(0) do |sum, points|
away_points = sum + points
end
if away_points > home_points
return game_hash[:away][:team_name]
else
return game_hash[:home][:team_name]
end
end
def player_with_longest_name
longest = " "
longest_length = 0
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
name_length = stats[:player_name].length
if name_length > longest_length
longest_length = name_length
longest = stats[:player_name]
end
end
end
return longest
end
def long_name_steals_a_ton?
most_steals = 0
player = ""
game_hash.each do |home_away, team_attributes|
team_attributes[:players].each do |stats|
steals = stats[:steals]
if steals > most_steals
most_steals = steals
player = stats[:player_name]
end
end
end
if player == player_with_longest_name
return true
end
end
| true |
999ea1eab53c19228bb6d3f5635128dd18b48017 | Ruby | free-beer/reorm | /spec/reorm/property_errors_spec.rb | UTF-8 | 3,357 | 2.875 | 3 | [
"MIT"
] | permissive | require "spec_helper"
describe Reorm::PropertyErrors do
subject {
Reorm::PropertyErrors.new
}
describe "#clear?()" do
it "returns true for an empty instance" do
expect(subject.clear?).to eq(true)
end
it "returns false for a non-empty instance" do
subject.add(:blah, "Some message.")
expect(subject.clear?).to eq(false)
end
end
describe "#reset()" do
before do
subject.add(:field1, "Message 1.")
subject.add(:field2, "Message 2.")
subject.add(:field3, "Message 3.")
end
it "removes any existing errors" do
subject.reset
expect(subject.clear?).to eq(true)
end
end
describe "#include?()" do
before do
subject.add(:field1, "An error message.")
end
it "returns false if there are no errors for the specified property" do
expect(subject.include?(:blah)).to eq(false)
end
it "returns true if there are errors for the specified property" do
expect(subject.include?(:field1)).to eq(true)
end
end
describe "#add()" do
it "adds an error message for a given property" do
subject.add(:field1, "The error message for field 1.")
expect(subject.include?(:field1)).to eq(true)
expect(subject.messages(:field1)).to eq(["The error message for field 1."])
end
it "does not add an error if the message is blank" do
subject.add(:field1, nil)
expect(subject.clear?).to eq(true)
subject.add(:field1, "")
expect(subject.clear?).to eq(true)
end
end
describe "#prperties()" do
it "returns an empty array if called when there are no errors" do
expect(subject.properties).to eq([])
end
it "returns an array with properties and no duplicates if there are errors" do
subject.add(:field1, "First error.")
subject.add(:field2, "Second error.")
subject.add(:field1, "Third error.")
expect(subject.properties).to eq([:field1, :field2])
end
end
describe "#messages()" do
it "returns an empty array where there are no messages for the specified property" do
expect(subject.messages(:blah)).to eq([])
end
it "returns an array of messages where there are message for the specified property" do
subject.add(:field1, "First error.")
subject.add(:field2, "Second error.")
subject.add(:field1, "Third error.")
expect(subject.messages(:field1)).to eq(["First error.", "Third error."])
end
end
describe "#each()" do
it "yields a property name and message array to the specified block" do
subject.add(:first, "A message.")
subject.each do |property, messages|
expect(property).to eq(:first)
expect(messages).to eq(["A message."])
end
end
it "yields once for each property with errors" do
subject.add(:field1, "An error.")
subject.add(:field1, "An error.")
subject.add(:field2, "An error.")
total = 0
subject.each {|property, messages| total += 1}
expect(total).to eq(2)
end
end
describe "#to_s" do
it "returns an empty string when there are no errors" do
expect(subject.to_s).to eq("")
end
it "returns a string containing one error per line when there are errors" do
subject.add(:field1, "has an error.")
subject.add(:field1, "has another error.")
subject.add(:field2, "also has an error.")
expect(subject.to_s).to eq("field1 has an error.\n"\
"field1 has another error.\n"\
"field2 also has an error.")
end
end
end
| true |
f8a5de2de063f0f60b6b6fb7852c2d5e05b65f1b | Ruby | wxm112/wdi8_nots | /air_conditioning.rb | UTF-8 | 674 | 3.796875 | 4 | [] | no_license | print "What's the current temperature? "
current_temperature = gets.to_i
print "If the A/C is functional? (y/n) "
air_conditional = gets.chomp.downcase
print "What temperature do you wish? "
desired_temperature = gets.to_i
def aircon(current_temperature,air_conditional,desired_temperature)
if air_conditional == "y"
if current_temperature > desired_temperature
puts "Turn on the A/C Please"
end
else air_conditional == "n"
if current_temperature > desired_temperature
puts "Fix the A/C now! It's hot!"
else
puts "Fix the A/C whenever you have the chance...It's cool..."
end
end
end
aircon(current_temperature,air_conditional,desired_temperature)
| true |
ac3d8de6e5a0116bdad2a4450526d7aaf4a342b4 | Ruby | iamdhunt/LLF | /app/models/comment.rb | UTF-8 | 1,403 | 2.578125 | 3 | [] | no_license | class Comment < ActiveRecord::Base
attr_accessor :mention
attr_accessible :content
belongs_to :member
belongs_to :commentable, polymorphic: true
has_many :mentions, as: :mentioner, dependent: :destroy
after_create :create_notification, :send_email, unless: Proc.new { |comment| comment.member.id == comment.commentable.member.id }
after_save :save_mentions
validates :content, presence: true,
length: { minimum: 2, maximum: 280 }
auto_strip_attributes :content
def create_notification
subject = "#{member.user_name}"
body = "left a <b>comment</b> on your <b>#{commentable_type.downcase}</b> <p><i>#{content}</i></p>"
commentable.member.notify(subject, body, self)
end
def send_email
CommentMailer.email_notification(member, commentable, self).deliver
end
USERNAME_REGEX = /@\w+/i
private
def save_mentions
return unless mention?
people_mentioned.each do |member|
Mention.create!(:comment_id => self.id, :mentioner_id => self.id, :mentioner_type => 'Comment', :mentionable_id => member.id, :mentionable_type => 'Member')
end
end
def mention?
self.content.match( USERNAME_REGEX )
end
def people_mentioned
members = []
self.content.clone.gsub!( USERNAME_REGEX ).each do |user_name|
member = Member.find_by_user_name(user_name[1..-1])
members << member if member
end
members.uniq
end
end
| true |
b0b0677561e3b23dd3dc58f53814a45f4bd57c4d | Ruby | sheim-dev/pager_duty | /lib/pager_duty/client/escalation_policies.rb | UTF-8 | 7,325 | 2.546875 | 3 | [
"MIT"
] | permissive | module PagerDuty
class Client
# Module encompassing interactions with the escalation policies API endpoint
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies
module EscalationPolicies
# List escalation policies
# @param options [Sawyer::Resource] A customizable set of options.
# @option options [String] :query Filters the results, showing only the escalation policies whose names contain the query.
# @option options [Array<string>] :user_ids Filters the results, showing only escalation policies on which any of the users is a target.
# @option options [Array<string>] :team_ids An array of team IDs. Only results related to these teams will be returned. Account must have the teams ability to use this parameter.
# @option options [Array<string>] :include Array of additional details to include (One or more of <tt>:services</tt>, <tt>:teams</tt>, <tt>:targets</tt>)
# @option options [String] :sort_by ("name") Sort the list by '<tt>name</tt>', '<tt>name:asc</tt>' or '<tt>name:desc</tt>'
#
# @return [Array<Sawyer::Resource>] An array of hashes representing escalation policies
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies/get_escalation_policies
def escalation_policies(options = {})
user_ids = options.fetch(:user_ids, [])
team_ids = options.fetch(:team_ids, [])
query_params = Hash.new
query_params["query"] = options[:query] if options[:query]
query_params["user_ids[]"] = user_ids.join(",") if user_ids.length > 0
query_params["team_ids[]"] = team_ids.join(",") if team_ids.length > 0
query_params["include[]"] = options[:include] if options[:include]
query_params["sort_by"] = options[:sort_by] if options[:sort_by]
response = get "/escalation_policies", options.merge({query: query_params})
response[:escalation_policies]
end
alias :list_escalation_policies :escalation_policies
#
# Gets escalation policy by id
# @param id [String] Unique identifier
# @param options [Sawyer::Resource] A customizable set of options.
#
# @return [Sawyer::Resource] Represents escalation policy
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies/get_escalation_policies_id
def escalation_policy(id, options = {})
response = get("/escalation_policies/#{id}", options)
response[:escalation_policy]
end
alias :get_escalation_policy :escalation_policy
#
# Remove an existing escalation policy
# @param id [String] PagerDuty identifier for escalation policy
#
# @return [Boolean]
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies/delete_escalation_policies_id
def delete_escalation_policy(id)
boolean_from_response :delete, "/escalation_policies/#{id}"
end
alias :delete :delete_escalation_policy
#
# Creates an escalation policy
# @param name: nil [String] name for policy
# @param escalation_rules: [] [Array<Sawyer::Resource>] List of escalation rule
# @param options [Sawyer::Resource] A customizable set of options.
# @option options [String] :description ("") description of policy
# @option options [Integer] :num_loops (0) Number of loops
# @option options [Array<Sawyer::Resource>] :services ([]) List of services
# @option options [Array<Sawyer::Resource>] :teams ([]) List of associated teams
#
# @return [Sawyer::Resource] Represents escalation policy
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies/post_escalation_policies
def create_escalation_policy(name, escalation_rules, options = {})
params = load_params(name: name,
description: options.fetch(:description, nil),
num_loops: options.fetch(:num_loops, nil),
escalation_rules: escalation_rules,
services: options.fetch(:services, []),
teams: options.fetch(:teams, []))
if options[:from_email_address]
params[:headers] ||= {}
params[:headers][:from] = options[:from_email_address]
end
response = post "/escalation_policies", options.merge(params)
response[:escalation_policy]
end
alias :create :create_escalation_policy
#
# Update an escalation policy
# @param id [String] PagerDuty ID
# @param options [Sawyer::Resource] A customizable set of options.
# @option options [String] :name Name for policy
# @option options [String] :description Description of policy
# @option options [Integer] :num_loops Number of loops
# @option options [Array<Sawyer::Resource>] :escalation_rules List of escalation rules
# @option options [Array<Sawyer::Resource>] :services List of services
# @option options [Array<Sawyer::Resource>] :teams List of associated teams
#
# @return [Sawyer::Resource] Represents escalation policy
# @see https://v2.developer.pagerduty.com/v2/page/api-reference#!/Escalation_Policies/put_escalation_policies_id
def update_escalation_policy(id, options = {})
policy = {}
policy[:type] = "escalation_policy"
policy[:name] = options[:name] if options[:name]
policy[:description] = options[:description] if options[:description]
policy[:num_loops] = options[:num_loops] if options[:num_loops]
policy[:escalation_rules] = options[:escalation_rules] if options[:escalation_rules]
policy[:services] = options[:services] if options[:services]
policy[:teams] = options[:teams] if options[:teams]
params = { escalation_policy: policy }
response = put "/escalation_policies/#{id}", options.merge(params)
response[:escalation_policy]
end
private
def load_params(name: nil, description: nil, num_loops: nil, repeat_enabled: false, escalation_rules: [], services: [], teams: [])
{
escalation_policy: {
type: "escalation_policy",
name: name,
escalation_rules: escalation_rules.map { |rule|
{
escalation_delay_in_minutes: rule[:escalation_delay_in_minutes].to_i,
targets: rule.fetch(:targets, Hash.new()).map { |target|
{
id: target[:id],
type: target[:type]
}
}
}
},
repeat_enabled: repeat_enabled,
services: services.map { |service|
{
id: service[:id],
type: service[:type]
}
},
num_loops: num_loops.to_i,
teams: teams.map { |team|
{
id: team[:id],
type: "team"
}
},
description: description.to_s,
}}
end
end
end
end | true |
194d8211d6a021ca9a7f9cd053d583c8e29a5934 | Ruby | everton/rRPG | /lib/character/modules.rb | UTF-8 | 952 | 2.671875 | 3 | [
"MIT"
] | permissive | module Character
module Modules
def self.included(base)
base.send :extend, ClassMethods
base.send :include, SingletonMethods
end
module AutoMagickInclusion
def automagicaly_require(mod_name)
require_relative "modules/#{mod_name}"
# TODO: create camelize and constantize methods
mod_name = mod_name.to_s.split('_').
collect(&:capitalize).join
Kernel.const_get(mod_name)
end
end
module ClassMethods
include Character::Modules::AutoMagickInclusion
def have(mod_name, options = {})
mod = automagicaly_require(mod_name)
include mod
mod.init(self, options)
end
end
module SingletonMethods
include Character::Modules::AutoMagickInclusion
def have(mod_name, options = {})
mod = automagicaly_require(mod_name)
extend mod
mod.init(self, options)
end
end
end
end
| true |
d62ade2d98e990f112e582997ff3e7808a92854d | Ruby | sbstn-jmnz/BasicRuby | /first.rb | UTF-8 | 46 | 2.78125 | 3 | [] | no_license | puts "Hello Mothafaka"
text = gets
puts text | true |
fc7c459cfc47444ae48a69a5cfc8d538a512b3fb | Ruby | TheoObbard/w2d4_classwork | /execution_time.rb | UTF-8 | 1,847 | 4.4375 | 4 | [] | no_license | #my_min
# Given a list of integers find the smallest number in the list.
#my_min in O(n^2) time complexity
def my_min_1(list)
smallest = nil
list.each do |el1|
smallest = el1 if smallest == nil
list.each do |el2|
if el2 < el1 && el2 < smallest
smallest = el2
end
end
end
smallest
end
#my_min in O(n) time complexity
def my_min_2(list)
smallest = list.first
list.each do |el|
if el < smallest
smallest = el
end
end
smallest
end
#Largest Contiguous Sub-sum
# You have an array of integers and you want to find the largest contiguous (together in sequence) sub-sum. Find the sums of all contiguous sub-arrays and return the max.
#
# Example:
#
# list = [5, 3, -7]
# largest_contiguous_subsum(list) # => 8
#
# # possible sub-sums
# [5] # => 5
# [5, 3] # => 8 --> we want this one
# [5, 3, -7] # => 1
# [3] # => 3
# [3, -7] # => -4
# [-7] # => -7
def largest_contiguous_subsum_1(arr)
possibles = []
arr.each_with_index do |el1,idx1|
mini = [el1]
arr.each_with_index do |el2, idx2|
if idx2 > idx1
mini << el2
end
possibles << mini.dup
end
end
possibles.map {|el| el.reduce(:+)}.max
end
# list = [-5, -1, -3]
# p largest_contiguous_subsum_1(list)
def largest_contiguous_subsum_2(array)
largest = nil
running_tally = nil
array.each_with_index do |el, i|
if i == 0
largest = el
running_tally = el
elsif i > 0
running_tally < 0 ? running_tally = el : running_tally += el
end
largest = running_tally if running_tally > largest
end
largest
end
list = [5, 3, -7]
p largest_contiguous_subsum_2(list)
list = [2, 3, -6, 7, -6, 7]
p largest_contiguous_subsum_2(list)
list = [-5, -1, -3]
p largest_contiguous_subsum_2(list)
| true |
f8e560c06658701a7334a6f0362f3dc9c0d4fc3b | Ruby | opq290/Ruby | /kadai5_10.rb | UTF-8 | 204 | 3.046875 | 3 | [] | no_license | def f(s)
f=s.to_a
f
end
def g(s)
f=f(s)
g=Array.new
for i in 0..f.length-1
g[f[i]]=i
end
g
end
def in(a,s)
g=g(s)
if g[a] != nil
return true
else
return false
end
end
| true |
7e5e69a05d5e11d1433168d27503a5f9f8913eb2 | Ruby | enspirit/predicate | /spec/predicate/test_and_split.rb | UTF-8 | 2,205 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
class Predicate
describe Predicate, "and_split" do
let(:p){ Predicate }
subject{ pred.and_split([:x]) }
context "on tautology" do
let(:pred){ p.tautology }
it{ should eq([p.tautology, p.tautology]) }
end
context "on contradiction" do
let(:pred){ p.contradiction }
it{ should eq([p.tautology, pred]) }
end
context "on identifier (included)" do
let(:pred){ p.identifier(:x) }
it{ should eq([ pred, p.tautology ]) }
end
context "on identifier (excluded)" do
let(:pred){ p.identifier(:y) }
it{ should eq([ p.tautology, pred ]) }
end
context "on not (included)" do
let(:pred){ p.not(:x) }
it{ should eq([ pred, p.tautology ]) }
end
context "on not (excluded)" do
let(:pred){ p.not(:y) }
it{ should eq([ p.tautology, pred ]) }
end
context "on eq (included)" do
let(:pred){ p.eq(:x, 2) }
it{ should eq([ pred, p.tautology ]) }
end
context "on eq (excluded)" do
let(:pred){ p.eq(:y, 2) }
it{ should eq([ p.tautology, pred ]) }
end
context "on eq with placeholder" do
let(:pred){ p.eq(:x, p.placeholder) }
it{ should eq([ pred, p.tautology ]) }
end
context "on in with placeholder" do
let(:pred){ p.in(:x, p.placeholder) }
it{ should eq([ pred, p.tautology ]) }
end
context "on match (included)" do
let(:pred){ p.match(:x, "London") }
it{ should eq([ pred, p.tautology ]) }
end
context "on match (excluded)" do
let(:pred){ p.match(:y, "London") }
it{ should eq([ p.tautology, pred ]) }
end
context "on match (included on right)" do
let(:pred){ p.match(:y, :x) }
it{ should eq([ pred, p.tautology ]) }
end
context "on intersect" do
let(:pred){ p.intersect(:x, [1, 2]) }
it{ should eq([ pred, p.tautology ]) }
end
context "on subset" do
let(:pred){ p.subset(:x, [1, 2]) }
it{ should eq([ pred, p.tautology ]) }
end
context "on superset" do
let(:pred){ p.superset(:x, [1, 2]) }
it{ should eq([ pred, p.tautology ]) }
end
end
end
| true |
d3158ba0f37dd9ffabedf517fc7c032c7739c2c6 | Ruby | arleigh-atkinson/fall_dev15 | /Day1.rb | UTF-8 | 3,243 | 4.1875 | 4 | [] | no_license |
# I need to create a variable with my first name
first_name = 'Arleigh'
# I need to create a variable with my last name
last_name = 'Atkinson'
# Be verbose with variable names
# I need to output my first and last name
#puts "#{first_name} #{last_name}"
#string interpolation: variables inside a string
# puts: outputs variable or data stucture with a new line
# print: outputs variable or data structure without a new line
#puts first_name
#puts last_name
#print first_name
#print last_name
#puts full_name
# take user input
# set first name to user input
# output user's first name
# Use print to prevent new line after colon
#print "Input your first name: "
#user_name = gets.chomp.strip # strip: beginning and end gets: just end
#puts "Hey #{user_name}"
# Contact List (just first names)
# 1. Have an option to list all contacts
# 2. Have an option to create a new contact
# Bonus:
# 1. Have an option to sort contacts by first name
# 2. Have an option to edit a contact
# 3. Store first name, last name, and phone number
# 4. Delete a contact
contact_list = ['Jake','John', 'Joe']
contact_list << 'Ashley' # << pushes the data onto the array
#print contact_list # print lists with brackets
# puts lists without brackets
# 2D array
detailed_contact_list = [['Jake ','Johnson ','111-1111 '],['John ','Bell ','222-2222'],['Joe ','From ','333-3333'],['Ashley ','Smith ','444-4444']]
intro_menu = """
1 : List all contacts
2 : Create a new contact
3 : Sort contacts by first name
4 : Delete a contact
5 : List first names, last names, and phone numbers
6 : Edit a contact
Please select an option: """
print intro_menu
user_input = gets.chomp
# Cases based upon user input
case user_input
when '1'
puts "Listing all contacts:"
puts contact_list
when '2'
print "Input new name: "
add_name = gets.chomp
contact_list << new_name
when '3'
puts "Sorting contacts by first name:\n\n"
puts contact_list.sort
when '4'
print "Input name to delete: "
delete_name = gets.chomp
contact_list.delete(delete_name)
puts "Updated contact list: "
puts contact_list
when '5'
puts "Listing all info: "
detailed_contact_list.each do |r| #formatting code for 4x3 array
puts r.each{ |p| p }.join("")
end
when '6'
print "Input a contact to edit: "
edit_name = gets.chomp
if contact_list.include?("#{edit_name}") == true
print "Input updated contact: "
edited_name = gets.chomp
contact_list[contact_list.index("#{edit_name}")] = edited_name
puts "Updated contact list:"
puts contact_list
else
puts "Error: name does not exist in your contact list."
end
else
puts 'Error: Invalid input'
end
###################################################
# Exp
| true |
e873045997e115492015b45ab28e478a045f71a1 | Ruby | isabella232/tracktor-webapp | /lib/tracktor/params_handler.rb | UTF-8 | 661 | 2.59375 | 3 | [] | no_license | class ParamsHandler
def initialize(params, user)
@params = params
@user = user
end
def update
update_device_id
update_buttons
end
private
def update_device_id
if @params[:device_id].present?
@user.update_attributes(device_id: @params[:device_id])
end
end
def update_buttons
button_params.each do |button_identifier, task_id|
number = button_identifier.split("-").last.to_i
button = @user.buttons.where(number: number).first_or_create
button.update_attributes(task: Task.find(task_id))
end
end
def button_params
@params.select { |key, _| key.include? "button-" }
end
end
| true |
af649e0dc9cd349b05dae99402396858a069be77 | Ruby | helloRupa/chess-ruby | /lib/pieces/pawn.rb | UTF-8 | 2,525 | 3.1875 | 3 | [] | no_license | require_relative './piece.rb'
class Pawn < Piece
attr_reader :en_passant
def initialize(color, board, pos)
super
@en_passant = false
end
def symbol
"\u265F"
end
def moves
all_moves = []
all_moves.concat(get_forward_moves)
all_moves.concat(get_side_attacks)
all_moves.concat(get_en_passant_attacks)
end
def promote?
at_end_row?
end
def set_en_passant
return unless @first_move
@en_passant = true if two_step? && pawns_to_left_right?
end
def en_passant_false
@en_passant = false
end
def forward_dir
@color == :black ? 1 : -1
end
private
def get_en_passant_attacks
y, x = @pos
all_moves = []
side_attacks.each do |delta_y, delta_x|
pos_to_test = [y + delta_y, x + delta_x]
next unless @board.valid_pos?(pos_to_test)
all_moves << pos_to_test if enemy_pawn_behind?(pos_to_test)
end
all_moves
end
def enemy_pawn_behind?(coords)
pos_to_test = [coords[0] - forward_dir, coords[1]]
return false unless @board.valid_pos?(pos_to_test)
piece = @board[pos_to_test]
opponent?(piece) && piece.is_a?(Pawn) && piece.en_passant
end
def two_step?
@pos[0] == start_row + (forward_dir * 2)
end
def pawns_to_left_right?
left_right_pos.each do |coords|
next unless @board.valid_pos?(coords)
piece = @board[coords]
return true if opponent?(piece) && piece.is_a?(Pawn)
end
false
end
def left_right_pos
left = [@pos[0], @pos[1] - 1]
right = [@pos[0], @pos[1] + 1]
[left, right]
end
def at_end_row?
@color == :black ? (@pos[0] == 7) : (@pos[0] == 0)
end
def at_start_row?
@pos[0] == start_row
end
def start_row
@color == :black ? 1 : 6
end
def forward_steps
steps = at_start_row? ? [1, 2] : [1]
steps.map { |num| num * forward_dir }
end
def side_attacks
[[forward_dir, -1], [forward_dir, 1]]
end
def get_forward_moves
y, x = @pos
all_moves = []
forward_steps.each do |delta_y|
pos_to_test = [y + delta_y, x]
break unless @board.valid_pos?(pos_to_test) && @board[pos_to_test].empty?
all_moves << pos_to_test
end
all_moves
end
def get_side_attacks
y, x = @pos
all_moves = []
side_attacks.each do |delta_y, delta_x|
pos_to_test = [y + delta_y, x + delta_x]
next unless @board.valid_pos?(pos_to_test)
piece = @board[pos_to_test]
all_moves << pos_to_test if opponent?(piece)
end
all_moves
end
end
| true |
bd1a35cf5d1266d940085ff45b39b63c97131c99 | Ruby | bmarini/deadpool | /lib/deadpool/state_snapshot.rb | UTF-8 | 1,885 | 2.828125 | 3 | [] | no_license |
module Deadpool
class StateSnapshot
def initialize(state)
@name = state.name
@timestamp = state.timestamp
@status_code = state.status_code
@all_messages = state.all_messages
@error_messages = state.error_messages
@children = []
end
def add_child(child)
@children << child
end
def overall_status
@children.map { |child| child.overall_status }.push(@status_code).max
end
def all_error_messages
@children.inject(@error_messages) do |arr, child|
arr + child.all_error_messages
end
end
def nagios_report
message = ''
if overall_status != OK
message += all_error_messages.join(' | ')
end
message += " last checked #{(Time.now - @timestamp).round} seconds ago."
"#{status_code_to_s(overall_status)} - #{message}\n"
end
def full_report
output = "System Status: #{status_code_to_s(overall_status)}\n\n"
output += self.to_s
return output
end
def to_s(indent=0)
indent_space = ' ' * indent
output = "#{indent_space}#{@name}\n"
output += "#{indent_space}#{status_code_to_s(@status_code)} - checked #{(Time.now - @timestamp).round} seconds ago.\n"
unless @error_messages.empty?
output += "#{indent_space}!!! #{@error_messages.join("\n#{indent_space}!!! ")}\n"
end
unless @all_messages.empty?
output += "#{indent_space}#{@all_messages.join("\n#{indent_space}")}\n"
end
output += "\n"
@children.each do |child|
output += child.to_s(indent+1)
end
return output
end
def status_code_to_s(code)
case code
when OK then 'OK'
when WARNING then 'WARNING'
when CRITICAL then 'CRITICAL'
else
'UNKNOWN'
end
end
end
end
| true |
5740566b15e18f2febd1ebc16556c1d272cd978a | Ruby | bbc/redux-client-ruby | /lib/bbc/redux/channel_category.rb | UTF-8 | 837 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | require 'virtus'
module BBC
module Redux
# Redux API Channel Category Object
#
# @example Properties of the channel category object
#
# category = redux_client.channel_categories.first
#
# category.description #=> String
# category.id #=> Integer
# category.priority #=> Integer
#
# @author Matt Haynes <matt.haynes@bbc.co.uk>
class ChannelCategory
include Virtus.value_object
# @!attribute [r] description
# @return [String] category's description, e.g. 'BBC TV'
attribute :description, String
# @!attribute [r] id
# @return [Integer] category's id
attribute :id, Integer
# @!attribute [r] priority
# @return [String] category's priority, a hint for display in views
attribute :priority, Integer
end
end
end
| true |
7976d4ada78a8c6a3c48bb3c9bf4570356b7bfbf | Ruby | YoshiMejia/ruby-oo-object-relationships-has-many-through-lab | /lib/artist.rb | UTF-8 | 497 | 3.5 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
#An artist has many genres through its songs and a genre has many artists through
#its songs.
class Artist
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def new_song(name, genre)
Song.new(name, self, genre)
end
def songs
Song.all.select {|i| i.artist == self}
end
def genres
songs.map {|i| i.genre}
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.