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
b99d7bc3608b451871ecd747c13fca6ca95a995a
Ruby
jchu4483/ruby-music-library-cli-v-000
/lib/musiclibrarycontroller.rb
UTF-8
2,047
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MusicLibraryController def initialize(path = './db/mp3s') MusicImporter.new(path).import end def call help loop do puts "Please enter a command:" input = gets.chomp case input when "help" help when "list songs" list_songs when "list artists" list_artists when "list genres" list_genres when "play song" play_song when "list artist" list(:artist) when "list genre" list(:genre) when "exit" exit_music_library break end end end def exit_music_library puts "Goodbye" end def help puts %q(I accept the following commands: - list songs : displays a list of songs - list artists : displays a list of artists - list genres : displays a list of genres - play song : plays a song you choose - list artist : displays the songs of an artist you choose - list genre : displays the songs of a genre you choose) end def display_song(song) "#{song.artist.name} - #{song.name} - #{song.genre.name}" end def list_songs Song.all.each_with_index do |song, index| puts "#{index + 1}. " + display_song(song) end end def list_artists Artist.all.each { |artist| puts artist.name } end def list_genres Genre.all.each { |genre| puts genre.name } end def list(type) puts "Please enter #{type.to_s}:" input = gets.chomp if type == :artist object = Artist.find_by_name(input) elsif type == :genre object = Genre.find_by_name(input) else object = nil end if object object.songs.each { |song| puts display_song(song) } else puts "Invalid input, please try again" end end def play_song puts "Please enter song number:" input = gets.chomp.to_i if (1..Song.all.count).include?(input) song = Song.all[input - 1] puts "Playing " + display_song(song) else puts "Invalid input, please try again" end end end
true
a321b8a704c85ab885223a87113fea41c59c539b
Ruby
edgar/RRDSimple
/lib/rrdsimple.rb
UTF-8
2,053
2.640625
3
[]
no_license
require 'rubygems' gem 'redis', '>= 2.0.3' require 'redis' class RRDSimple VERSION = "0.0.1" def initialize(opts) @buckets = opts[:buckets] @step = opts[:step] @debug = opts[:debug] || false @db = opts[:db] || Redis.new end def current_epoch Time.now.utc.to_i / @step end def current_bucket current_epoch % @buckets end def last_epoch_key(k) "#{k}:epoch" end def last_epoch(k) @db.get(last_epoch_key(k)).to_i end def set_last_epoch(k,v = Time.now.utc.to_i) @db.set(last_epoch_key(k), v) end def last_bucket(set) last_epoch(set) % @buckets end def bucket_key(k,i) "#{k}:#{i}" end def bucket(k,i) @db.get(bucket_key(k,i)).to_i end def relative_bucket(value, i) b = value - i b = (b < 0) ? @buckets + b : b end def epochs_ago(k, num) bucket_key(k, relative_bucket(current_bucket,num)) end def buckets(k) a = [] i = 0 last_b = last_bucket(k) while (i < @buckets) do a.push bucket_key(k,relative_bucket(last_b,i)) i += 1 end a end def values(k) a = [] i = 0 last_e = last_epoch(k) last_b = last_bucket(k) while (i < @buckets) do v = bucket(k,relative_bucket(last_b,i)) a.push({:value => v, :epoch => last_e - i}) if v != 0 i += 1 end a end def epoch(k) current_e = current_epoch last_e = last_epoch(k) if current_e != last_e [(current_e - last_e).abs, @buckets].min.times do |n| clear_bucket(epochs_ago(k, n)) end set_last_epoch(k, current_e) end bucket_key(k, current_bucket) end def incr(k, val=1) debug [:incr, epoch(k), val] @db.incrby(epoch(k), val).to_i end def set(k, val) debug [:set, epoch(k), val] @db.set(epoch(k), val) end def clear(k) @db.del(last_epoch_key(k)) buckets(k){|b| clear_bucket(b)} end protected def clear_bucket(b) debug [:clearing_epoch, b] @db.del(b) end def debug(msg); puts msg if @debug; end end
true
dd071d1d02312d3b9ac1b0a5eb750dbd5fee370d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/src/1542.rb
UTF-8
187
3.03125
3
[]
no_license
def compute(first, second) arr1 = first.chars arr2 = second.chars length = 0 arr1.size.times do |i| length += 1 unless arr1[i] == arr2[i] end length end
true
83d03b9cb1fdd06f79143a4add44df5c51a5b6cd
Ruby
DDarrow123/crud-with-validations-lab-nyc-web-091718
/app/models/song.rb
UTF-8
841
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base validates :title, presence: true validates :title, uniqueness: { scope: %i[release_year artist_name], message: 'Artist cannot release the same song more than once in a year' } validates :artist_name, presence: true validates :released, inclusion: { in: [true, false] } validate :release_year_must_not_be_nil_if_released validate :release_year_must_not_be_in_the_future def release_year_must_not_be_nil_if_released if released == true && !release_year.present? errors.add(:release_year, "release year must be set if the item is released") end end def release_year_must_not_be_in_the_future if release_year.present? && release_year >= Date.today.year errors.add(:release_year, "release year must not be greater than the current date") end end end
true
d58ad01f0b95b988734969ed2ffb8af9c4bec7e8
Ruby
sogapalag/contest
/aizu/acpc2017day1/a.rb
UTF-8
73
2.9375
3
[]
no_license
n=gets.to_i s=gets.chomp if k=s.index('xx') puts k+1 else puts n end
true
e2957c4449b6edf4e534242f73e178e6fa7e2c76
Ruby
danielng09/App-Academy
/w2d2 Chess/chess/lib/stepping_piece.rb
UTF-8
1,290
3.6875
4
[]
no_license
require_relative "piece.rb" class SteppingPiece < Piece #deleted delta attribute def initialize(color, pos, moved, board, type) super(color, pos, moved, board) @type = type end def display case @type when :knight case @color when :black print "\u265E" when :white print "\u2658" end when :king case @color when :black print "\u265A" when :white print "\u2654" end end end # switched name of valid_moves and moves in this file to make them consister # -> moves are the movements you can make while valid_moves are the positions you can move to! # moved contents of valid_moves to the end of moves for consistentcy def valid_moves super end # moves should output all possible positions a piece can move to (without filtering for other pieces) # changed name is valid_moves & changed 'list' to 'deltas' def moves case @type when :knight deltas = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]] when :king deltas = [[0,1],[1,0],[-1,0],[0,-1],[1,1],[-1,-1],[-1,1],[1,-1]] end super(deltas) end end # # board = Board.new # knight = SteppingPiece.new(:black, [0, 0], false, board, :knight) # p knight.moves
true
78fb6588e8f3ece8f0872423e038474128c91fcc
Ruby
Jenna424/rails-github-api-v-000
/app/controllers/repositories_controller.rb
UTF-8
2,969
3.1875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class RepositoriesController < ApplicationController def index response = Faraday.get("https://api.github.com/user") do |request| request.headers['Authorization'] = "token #{session[:token]}" request.headers['Accept'] = 'application/json' # tells GitHub's server that we'll accept JSON as a response end @login = JSON.parse(response.body)['login'] resp = Faraday.get("https://api.github.com/user/repos") do |req| req.headers['Authorization'] = "token #{session[:token]}" req.headers['Accept'] = 'application/json' end @repos_array = JSON.parse(resp.body) # @repos_array stores an array of repo hashes end def create Faraday.post("https://api.github.com/user/repos") do |request| request.body = {'name': params[:name]}.to_json request.headers['Authorization'] = "token #{session[:token]}" request.headers['Accept'] = 'application/json' end redirect_to root_url end end # repositories#create explanation: # form in app/views/repositories/index.html.erb submits via a # POST request to '/repositories/create', which maps to 'repositories#create' # According to GitHub docs: # Create a new repository for the authenticated user - POST /user/repos # Parameter Required: name parameter, which points to the string name of the repository. # We get the value for the string name of the repository from the # <input type="text" name="name" id="new-repo"> text field in form, # which is accessed as params[:name] upon form submission # GitHub API expects POST data as well-formatted JSON text string in request body # to_json returns a JSON string representing the hash. # repositories#index explanation: # Call the GitHub API from within repositories#index # to retrieve and display the current user's login username in app/views/repositories/index.html.erb. # From the GitHub API Documentation: # Use the access token to access the API # The access token allows you to make requests to the API on a behalf of a user. # Example: # GET https://api.github.com/user?access_token=... # You can pass the token in the query params as shown above, # but a cleaner approach is to include it in the Authorization header. # Authorization: token OAUTH-TOKEN # For example, in curl you can set the Authorization header like this: # curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user # Get the authenticated user - GET /user # "https://api.github.com/user" # The body of our JSON response is a string, and we use JSON.parse() to parse it into a Ruby hash # The 'login' key of this Ruby hash points to the string value of the GitHub username, # which we store in @login variable # hash[key] = value # Call the API a second time using https://api.github.com/user/repos # to retrieve and display a list of repositories on app/views/repositories/index.html.erb # List your repositories (repositories that the authenticated user has explicit permission to access): # GET /user/repos
true
13c20ac06e543f611b02723d4fcbff933d4a4670
Ruby
foreverLoveWisdom/Ruby-Lab
/closures/ampersand_to_proc.rb
UTF-8
342
3.671875
4
[]
no_license
[1, 2, 3].inject(0) { |result, element| result + element } class Symbol def to_proc lambda do |x, args| # puts "current object is: #{x}" # puts "current argument is: #{args}" # puts "the method is: #{self}" x.send(self, *args) end end end puts([1, 2, 10, 20].inject(&:+)) puts(1.+(2)) puts(1.send(:+, 2))
true
e50bb16b217c26aa0e676ec6096a7cd53dd34411
Ruby
guynicolas/blackjack
/blackjack_solution.rb
UTF-8
2,737
4.28125
4
[]
no_license
# Interactive procedural blackjack game # Calculating total def calculate_total(cards) # [['S', '6'], ['C', '8'], ...] value_array = cards.map{ |e| e[1] } total = 0 value_array.each do |card_value| if card_value == "A" # Aces total += 11 elsif card_value.to_i == 0 # Q, J, and K total += 10 else total += card_value.to_i # numbered cards end end # Correct for Aces value_array.select{|e| e == "A"}.count.times do total -= 10 if total > 21 end total end suits = ['H', 'C', 'D', 'S'] cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Q', 'J', 'K', 'A'] deck = suits.product(cards) deck.shuffle! # Deal cards playercards = [] dealercards = [] playercards << deck.pop dealercards << deck.pop playercards << deck.pop dealercards << deck.pop playertotal = calculate_total(playercards) dealertotal = calculate_total(dealercards) puts "Player dealt: #{playercards[0]} and #{playercards[1]} with a total of #{playertotal}." puts "Dealer dealt: #{dealercards[0]} and #{dealercards[1]} with a total of #{dealertotal}." if playertotal == 21 puts "Congratulations, you hit the blackjack. You won!" exit end if dealertotal == 21 puts "Sorry, the Dealer wins. You lost!" exit end # Player's turn while playertotal < 21 puts "What would you like to do? 1) hit 2) stay" answer = gets.chomp if !['1', '2'].include?(answer) puts "Error: you must enter either 1 or 2!" next end if answer == '2' puts "You chose to stay." break end # hit newcard = deck.pop playercards << newcard playertotal = calculate_total(playercards) puts "Player dealt: #{newcard} and the new total is #{playertotal}." if playertotal == 21 puts "Congratulations, you hit the blackjack. You won!" exit elsif playertotal > 21 puts "Sorry, it looks you busted. You lost!" exit end end # Dealer's turn while dealertotal < 17 newcard = deck.pop dealercards << newcard dealertotal = calculate_total(dealercards) puts "Dealer dealt: #{newcard} and the new total is #{dealertotal}." if dealertotal == 21 puts "Sorry, Dealer hit the blackjack. You lost!" exit elsif dealertotal > 21 puts "Congratulations, Dealer is busted! You won!" exit end end # Compare hands puts "Player's cards: " playercards.each do |card| puts "=> #{card}" end puts "Your total is: #{playertotal}." puts "Dealer's cards: " dealercards.each do |card| puts "=> #{card}" end puts "Dealer's total is: #{dealertotal}." if playertotal > dealertotal puts "Congratulations, you won!" exit elsif dealertotal > playertotal puts "Sorry, Dealer wins. You lost!" exit else puts "It's a tie!" exit end
true
21103bbcf4b23876ee0d9e7a2751566a02799c1c
Ruby
usman-tahir/rubyeuler
/neweuler26.rb
UTF-8
731
3.203125
3
[]
no_license
#!/usr/bin/env ruby # https://projecteuler.net/problem=26 require 'prime' def phi(n) t = [] n.prime_division.each { |e| t << (e[0] - 1); t << (e[0] ** (e[1] - 1)) } t.inject(:*) end non_reptends = (1..1000).to_a - [7, 17, 19, 23, 29, 47, 59, 61, 97, 109, 113, 131, 149, 167, 179, 181, 193, 223, 229, 233, 257, 263, 269, 313, 337, 367, 379, 383, 389, 419, 433, 461, 487, 491, 499, 503, 509, 541, 571, 577, 593, 619, 647, 659, 701, 709, 727, 743, 811, 821, 823, 857, 863, 887, 937, 941, 953, 971, 977, 983] # zero out all indices which aren't reptend primes! # reptend primes get replaced with phi(reptend) val = [0,0] + (2..1000).to_a.map { |i| non_reptends.include?(i) ? 0 : phi(i) } p val.find_index(val.max)
true
143045bbc41be572b22fc008ee4e75b901f0c2a5
Ruby
lsewilson/learn_to_program
/ch11-reading-and-writing/build_a_better_playlist.rb
UTF-8
511
2.828125
3
[]
no_license
def music_shuffle filenames num_of_shuffles = 0 n = filenames.length shuffled = [] while num_of_shuffles <= 10 until n == 0 shuffled.push(filenames.delete_at(rand(n))) n -= 1 end num_of_shuffles += 1 end shuffled end songlist = Dir['/Users/laurawilson/Music/**/*.{mp3,MP3,m4a,M4A,wma,WMA}'] playlist = "Playlist.m3u" numberofsongs = 10 songs = music_shuffle(songlist.sample(numberofsongs)) File.open playlist, 'w' do |f| songs.each do |song| f.puts(song) end end
true
12e24b740fc833e7a0eaebb892adc28b80a8d5ec
Ruby
Tenzinwangchuk95/poke_move_finder
/lib/poke_stats/moves.rb
UTF-8
892
3.375
3
[ "MIT" ]
permissive
class PokeStats::Moves def pokemon_movelist puts "Enter the PokeDex number of the Pokemon you would like to know what moves it is able to learn" puts "Enter 'exit' to exit" PokeStats::API.new.pokemon_info end def number_input number = gets.strip if number == 'exit' PokeStats::CLI.new.menu elsif number.to_i > PokeStats::Pokemon.all.length puts "That is not a valid number" self.number_input elsif number.to_i == Float puts "That is not a valid number" self.number_input elsif number.to_i < 1 puts "That is not a valid number" self.number_input elsif number.to_i.to_s == number number else puts "That is not a valid number" self.number_input end end end
true
7ca7843c15ef68e3fb2ce84ed6865751e3d56717
Ruby
MahmudH/ruby-kickstart
/session2/3-challenge/8_array.rb
UTF-8
719
4.25
4
[ "MIT" ]
permissive
# Given an array of elements, return true if any element shows up three times in a row # # Examples: # got_three? [1, 2, 2, 2, 3] # => true # got_three? ['a', 'a', 'b'] # => false # got_three? ['a', 'a', 'a'] # => true # got_three? [1, 2, 1, 1] # => false def got_three? arr i = 0 output = false while i < arr.length if arr[i] == arr[i+1] && arr[i+1] == arr[i+2] output = true break else i+=1 end end output end # def got_three? arr # count = 0 # arr2 = [] # arr.each_with_index do |x, index| # if x == arr[index + 1] # if arr[index + 1] == arr[index + 2] # count = 3 # arr2 << x, arr[index + 1], arr[index + 2] # end # end # end # if count == 3 # arr2 # end # end
true
7f1c6baa0a6cbcf729d29666e94b391c421ce3c9
Ruby
franktisellano/titlecase_checker
/title_case.rb
UTF-8
2,809
3.71875
4
[]
no_license
require 'nokogiri' require 'open-uri' require 'formatador' def url_array_from_file(f) if File::exists?(f) && !File.zero?(f) file = File.open(f, 'r') data = file.read file.close return data.split("\n") else Formatador.display_line("[red]File does not exist or is empty.") return false end end def url_is_properly_title_cased(url) properly_title_cased = true table_data = [] begin file = open(url) html = Nokogiri::HTML(file) rescue OpenURI::HTTPError => e Formatador.display_line("[yellow]#{url} could not be reached: #{e}[/]") return false rescue SocketError Formatador.display_line("[yellow]#{url} could not be reached.[/]") return false end headers = html.css('h1, h2, h3, h4, h5, h6') headers.each do |header| if !header_is_properly_title_cased(header) table_data.push({ :text => "[red]#{header.text}[/]", :tag_name => header.name }) properly_title_cased = false end end if properly_title_cased return true else Formatador.display_line("[red]#{url} has issues. Here's the deets.[/]") Formatador.display_table(table_data) Formatador.display_line("") end end def header_is_properly_title_cased(header) words = header.text.split words.each_with_index do |word, index| # If first or last if (index == 0 || index == words.size - 1) return false if !word_is_properly_title_cased(word, true) # If not else return false if !word_is_properly_title_cased(word, false) end end return true end def word_is_properly_title_cased(word, is_either_first_or_last) always_lowercase = [ "as", "at", "by", "for", "in", "of", "off", "on", "per", "to", "up", "via", "and", "but", "or", "as", "if", "so", "nor", "now", "a", "an", "the" ] # If it's either first or last, it should always be capitalized, so let's just get that out of the way return (word == word.capitalize) if is_either_first_or_last # If it's in the always-lowercase list and is capitalized return false if (always_lowercase.include? word.downcase) && (word != word.downcase) return (word == word.downcase) if (always_lowercase.include? word.downcase) return word == word.capitalize end # Run the program! # Needs to take exactly one argument if ARGV.empty? || (ARGV.size > 1) puts "\n This tool takes a list of URLs in a text file as its only argument.\n Each URL in the text file should be on its own line." Formatador.display_line("[red]Usage: ruby title_case.rb /path/to/filename.txt[/]\n") else puts "\n" urls = url_array_from_file(ARGV[0]) if (urls != false) urls.each do |url| if url_is_properly_title_cased(url) Formatador.display_line("[blue]#{url} is OK![/]") end end end end puts "\n"
true
7b46e43f7beab870b62e59b1c41ff1c09d60f76b
Ruby
plai217/project-euler-10001st-prime-e-000
/lib/10001st_prime.rb
UTF-8
343
3.484375
3
[]
no_license
# Implement your procedural solution here! def prime_number_for(num) nthprime = 0 counter = 2 until nthprime == num if prime(counter) nthprime += 1 end counter +=1 end counter - 1 end def prime(num) Math.sqrt(num).to_i.downto(2) do |x| if num % (x) == 0 return false end end return true end
true
7922022e17815a527cf461dd9c6a621fc0d2b688
Ruby
danilogcastro/teaching
/batch-760/regex/reboot/instacart/instacart.rb
UTF-8
1,537
3.78125
4
[]
no_license
# DISPLAY WELCOME MESSAGE puts "--------------------" puts "Welcome to Instacart" puts "--------------------" # CREATE A HASH FOR THE STORE STORE = { kiwi: { price: 1.25, stock: 5 }, banana: { price: 0.5, stock: 3 }, mango: { price: 4, stock: 6 }, asparagus: { price: 9, stock: 2 } } # DISPLAY THE STORE TO THE USER puts "In our store today:" STORE.each do |item, info| puts "#{item}: $#{info[:price]} - #{info[:stock]} available" end # ASK THE USER WHAT THEY WANT TO BUY # cart = [] cart = {} loop do puts "Which item? (or 'quit' to checkout)" item = gets.chomp.downcase.to_sym break if item == :quit puts "How many?" quantity = gets.chomp.to_i if STORE.include?(item) && quantity <= STORE[item][:stock] if cart.include?(item) cart[item] += quantity else cart[item] = quantity end STORE[item][:stock] -= quantity elsif STORE.include?(item) && quantity > STORE[item][:stock] puts "Sorry, there are only #{STORE[item][:stock]} #{item}s left..." else puts "Sorry, we don't have #{item} today." end end # SHOW THE CART TO THE USER # puts "Please review your cart:" # print cart # CALCULATE THE CART'S TOTAL # prices = cart.map do |item| # STORE[item.to_sym] # end prices = cart.keys.map do |item| STORE[item][:price] * cart[item] end # DISPLAY THE BILL TO USER puts "-------BILL---------" cart.each do |item, quantity| puts "#{quantity} #{item} x #{STORE[item][:price]} = $ #{quantity * STORE[item][:price]}" end puts "TOTAL: $ #{prices.sum}" puts "--------------------"
true
3d00148b19667cfb01367eed40f318953c5521a5
Ruby
andrewmpierce/MusicCollection
/music_collection.rb
UTF-8
1,385
3.71875
4
[]
no_license
require './album' class MusicCollection attr_reader :collection def initialize(collection = {}) @collection = collection end def add(title, artist) album = Album.new(title, artist) if @collection[title] puts 'That title is already in your collection!' else @collection[title] = album end puts "Added #{title} by #{artist}" end def play(title) album = @collection[title] album.play() puts "Played #{title} by #{album.artist}" end def show_all @collection.each do |title, album| album = @collection[title] puts "#{album.title} by #{album.artist} (#{played_or_unplayed(album)})" end end def show_unplayed @collection.each do |title, album| album = @collection[title] puts "#{album.title} by #{album.artist}" if album.unplayed? end end def show_all_by(artist) @collection.each do |title, album| album = @collection[title] puts "#{album.title} by #{album.artist} (#{played_or_unplayed(album)})" if album.artist == artist end end def show_unplayed_by(artist) @collection.each do |title, album| album = @collection[title] if album.artist == artist && album.unplayed? puts "#{album.title} by #{album.artist}" end end end private def played_or_unplayed(album) album.played ? 'played' : 'unplayed' end end
true
7dce29a581fcad7f370e6162efbc61f1a7b851db
Ruby
deepak-webonise/Ruby
/shop_inventory/version2/modules/file_operations.rb
UTF-8
1,937
3.078125
3
[]
no_license
# /usr/bin/ruby -w # Fileoperations Module module FileOperations FILE_PATH = './database/' def self.read_mode(file_name) begin File.open(FILE_PATH + file_name, 'r').readlines rescue Exception => e puts 'Error in reading file' end end def self.write_mode(file_name) File.open(FILE_PATH + file_name, 'w') end def self.append_mode(file_name) File.open(FILE_PATH + file_name, 'a') end def self.add(obj) file = append_mode("#{obj.class}.csv") file.puts convert_obj_arr(obj).join(';') end def self.update(obj) new_list = [] file = read_mode("#{obj.class}.csv") file.each do | line| row = line.split(';') (obj.id.to_i != row[0].to_i ) ? new_list.push(line) : new_list.push(convert_obj_arr(obj).join(';')) end file = write_mode("#{obj.class}.csv") file.puts new_list file.close end def self.id_exist?(obj) file = read_mode("#{obj.class}.csv") file.each do |row| attribute = row.split(';') if obj.id.to_i == attribute[0].to_i return true end end false end def self.search_by_name(obj) list = [] file = read_mode("#{obj.class}.csv") file.each do |row| attribute = row.split(';') if obj.name.to_s == attribute[1].to_s list.push(row) end end (list.length > 0)? list : false end def self.delete(obj) new_list = [] file = read_mode("#{obj.class}.csv") file.each do |row| attribute = row.split(';') if obj.id.to_i != attribute[0].to_i new_list.push(row) end end file = write_mode("#{obj.class}.csv") file.puts new_list file.close end def self.find_all(obj) read_mode("#{obj.class}.csv") end def self.convert_obj_arr(obj) rows = [] obj.instance_variables.map do |attribute| rows.push(obj.instance_variable_get("#{attribute}").to_s) end rows end end
true
7044d2aa32b372f422225291b54a88216f042dc2
Ruby
davepodgorski/Ruby_Text_Adventure
/exercise2.rb
UTF-8
184
3.265625
3
[]
no_license
puts 55 * 0.15 puts "apples" + 77.to_s puts "The universe is #{45628 * 7839} years old." #True! puts (10 < 20 && 30 < 20) || !(10 == 11) #https://www.youtube.com/watch?v=bnKaOo67mLQ
true
dd387e553d3b436e611f6d4f360b3aec6e135025
Ruby
amaranth0203/Sources
/ruby/html.rb
UTF-8
527
2.6875
3
[]
no_license
class Html DEFAULT_BROWSER = 'firefox' def run file , args if args.empty ? `#{DEFAULT_BROWSER} #{file}` else despatch_on_parameters file , args end end def dispatch_on_parameters file , args cmd = args.shift send "do_#{cmd}" , file , args end def do_opera file , args = nil system "opera #{file} #{args}" end def do_konq file , args = nil system "konqueror #{file} #{args}" end end
true
87ba5d111bc991e5a4ea845b81aad6f04727966c
Ruby
codeforkansascity/Neighborhood-Dashboard
/lib/entities/multi_dataset_geo_json.rb
UTF-8
853
2.578125
3
[ "MIT" ]
permissive
require 'json' module Entities class MultiDatasetGeoJson < GeoJson extend Utilities::AttributesList include Utilities::AttributesListInstance attr_accessor :datasets def initialize(args = {}) super(args) @datasets = [] end def add_dataset(dataset) @datasets.push(dataset) end def disclosure_attributes @datasets.map(&:disclosure_attributes).flatten.uniq end def properties {} end def geometry {} end def mappable? false end def to_h hash = {} hash[:type] = 'Feature' hash[:geometry] = geometry hash[:properties] = properties.dup hash[:properties][:disclosure_attributes] = disclosure_attributes hash end def self.deserialize(hash) self.new(JSON.parse(hash.to_json)) end end end
true
d27332515cbed522e99e0f4d6f91e8b029294709
Ruby
garfiny/kinetic_stream
/lib/kinetic_stream/record_processor.rb
UTF-8
2,052
2.546875
3
[ "MIT" ]
permissive
module KineticStream # TODO failover, recovery, and load balancing functionality class RecordProcessor RUNNING = 'running' CLOSED = 'closed' READY = 'ready' ABORT = 'abort_on_error' attr_reader :status def initialize(stream, shard, client) @client = client @stream = stream @shard = shard @options = {stream_name: stream.name, shard_id: shard.id} @status = READY @shutdown_triggered = false end {process_after_seq: 'AFTER_SEQUENCE_NUMBER' , process_from_seq: 'AT_SEQUENCE_NUMBER'}.each do |method_name, value| define_method(method_name) do |starting_sequence_number, limit = 20, abort_on_fail = false, block = nil| opts = @options.merge({ shard_iterator_type: value, starting_sequence_number: starting_sequence_number }) process(opts, limit, abort_on_fail, block) end end {process_from_latest: 'LATEST' , process_from_oldest: 'TRIM_HORIZON'}.each do |method_name, value| define_method(method_name) do |limit = 20, abort_on_fail = false, block = nil| opts = @options.merge({ shard_iterator_type: value }) process(opts, limit, abort_on_fail, block) end end def terminate! @shutdown_triggered = true end private def process(opts, limit, abort_on_fail = false, &block) @status = RUNNING next_shard_iterator = kinesis_client.get_shard_iterator(opts) while next_shard_iterator break if @shutdown_triggered response = kinesis_client.get_records(shard_iterator: next_shard_iterator, limit: limit) next_shard_iterator = response[:next_shard_iterator] records = response[:records] if block begin block.call(records) rescue => e if abort_when_fail @status = ABORT return end end end end @status = CLOSED end def kinesis_client @client.kinesis_client end end end
true
f0e8ba7fe3c34e05bc4a3ba7c8c76ef305037629
Ruby
yumojin/Example-Sketches
/samples/processing_app/basics/form/primitives.rb
UTF-8
637
3.09375
3
[ "MIT" ]
permissive
# Primitives 3D. # # Placing mathematically 3D objects in synthetic space. # The lights() method reveals their imagined dimension. # The box() and sphere() functions each have one parameter # which is used to specify their size. These shapes are # positioned using the translate() function. def setup size 640, 360, P3D background 0 lights no_stroke push_matrix translate 130, height/2, 0 rotate_y 1.25 rotate_x -0.4 box 100 pop_matrix no_fill stroke 255 push_matrix translate 500, height*0.35, -200 sphere 280 pop_matrix end
true
a5167362e01cb5ee293faaae624f15f002906cee
Ruby
2called-chaos/MCIR
/lib/mcir/core/helper.rb
UTF-8
6,216
2.8125
3
[ "MIT" ]
permissive
# Encoding: utf-8 class Mcir::Core # Contains helper methods. module Helper # Log each line of the given string seperately. # # @param [String] str String to log per line. def eachlog str str.split("\n").each{|s| log(s) } end # Shows a warning message and/or the help and/or abort the application. # You can omit the message if you don't need one (or pass nil). # # @param [String] msg Message to abort with. # @option opts [Boolean] exit (true) Exit the application (SystemExit). # @option opts [Integer] code (1) The exit code when exiting the application. # @option opts [Boolean] help (false) Print the application help. def abort msg, opts = {} opts = msg if msg.is_a?(Hash) opts = { exit: true, code: 1, help: false }.merge(opts) if !msg.is_a?(Hash) && msg.present? Array.wrap(msg).flatten.each do |m| @logger.log(m, :abort) end end show_help(false) if opts[:help] self.exit_code = opts[:code] if opts[:code] exit(opts[:code]) if opts[:exit] end # Shows the application help. # # @param [Boolean] exit Exit the application with code 0 after showing the help. def show_help exit = true puts "\n#{opt}\n" # actions unless @called_action col_length = @actions.keys.map(&:length).max + 2 puts "Available actions".purple.underline.rjust(col_length + 25) @actions.keys.sort_by(&:downcase).each do |key| action = @actions[key] puts "#{action.name.rjust(col_length)}" << " … ".blue << "#{action.description}".yellow end end abort(code: 0) if exit end # Statushelper, returns colored strings based on the condition. # # @param condition Uses green text if condition evaluates to true, red text otherwise. # @param [String] green Green or true text # @param [String] red Red or false text # @example # cgr instance.online?, "ONLINE", "OFFLINE" def cgr condition, green, red condition ? green.green : red.red end # Same as {#cgr} but with a prefix. The prefix and green/red text is automatically separated by an # space character. # # @param condition (see #cgr) # @param [String] desc Description text which will be prefixed. Will be colorized yellow. # @param green (see #cgr) # @param red (see #cgr) # @example # cgr! instance.online?, "Server is", "ONLINE", "OFFLINE" def cgr! condition, desc, green, red desc.yellow << " " << cgr(condition, green, red) end # Handles exceptions depending on kind and the application's debug setting. # # * `SystemExit` exceptions will just be ignored. # * `Interrupt` exceptions will be silently raised again. # * All other exceptions will cause an application {#abort termination}. It will display a decent # error message unless the debug mode is enabled. Then it would just raise the exception giving # you a stack trace. # # @param [Exception] e Any kind of exception. # @param [String] msg A message to print in the abort message. def trap_exception e, msg return if e.is_a?(SystemExit) throw_further = @logger.debug? || e.is_a?(Interrupt) msg = Array.wrap(msg) msg << " => Message: #{e.message.presence || e.inspect}".yellow msg << " => Run with --debug to get a stack trace".yellow if !throw_further abort msg, exit: !throw_further raise e if throw_further end # distinct optional-required-optional arguments # @note This method is considered private API, do not use it. # @private def distinct_action_and_instance fa = ARGV.shift.presence unless ARGV[0].to_s.start_with?("-") sa = ARGV.shift.presence unless ARGV[0].to_s.start_with?("-") if fa && sa return [sa, fa] else return [fa, nil] end end # Get's and parses a list of available screens. # # @param [Symbol] by The field to use as index for the result hash. (pid/name/rest/line) # @return [Hash] A hash with some information about running screens. # @example # { # "mcir_my_instance" => { # pid: 1234, # name: "mcir_my_instance", # attached: true, # rest: "(07/17/2013 01:11:23 AM)(Detached)", # line: "1234.mcir_my_instance\t(07/17/2013 01:11:23 AM)\t(Detached)", # } # } def screen_list by = :pid screens = {}.tap do |r| rows = `screen -ls`.split("\n").select{ |l| l.start_with?("\t") }.map(&:strip) rows.each do |row| cols = row.split("\t").map(&:strip) scr = cols.shift.split(".") rest = cols.join fatt = rest.downcase.include?("attached") || rest.downcase.include?("detached") res = { pid: scr.first.to_i, name: scr[1..-1].join("."), rest: rest, line: row, } res[:attached] = rest.downcase.include?("attached") if fatt r[res[by]] = res end end end # Measures the time needed by a given block. # # @return [Hash] Result hash (see example) # @example # mcir.measure { sleep 5 } # { # start: Time<2013-07-21 23:25:54 UTC>, # Start time # result: 5, # Return value of the block # stop: Time<2013-07-21 23:25:59 UTC>, # Stop time # diff: 5.000099503, # Runtime in seconds # time: Time<1970-01-01 00:00:05 UTC>, # Runtime as Time object # dist: "05.000" # Humand friendly representation of :diff # } def measure &block {}.tap do |r| r[:start] = Time.now.utc r[:result] = block.call r[:stop] = Time.now.utc r[:diff] = r[:stop] - r[:start] r[:time] = Time.at(r[:diff]).utc format = ".%L" format = "%S#{format}" if r[:diff] > 1 format = "%M:#{format}" if r[:diff] > 60 format = "%H:#{format}" if r[:diff] > 3600 r[:dist] = r[:time].strftime(format) end end end end
true
ff3c20a478e374feb1d5be1608c4f7a97ae238a0
Ruby
ken1882/MLPRPG_VODL
/Old Data Scripts/254_MOG_Boss_HP_Meter.rb
UTF-8
32,061
2.671875
3
[]
no_license
#============================================================================== # +++ MOG - Boss HP Meter (V1.5) +++ #============================================================================== # By Moghunter # https://atelierrgss.wordpress.com/ #============================================================================== # Apresenta um medidor animado com o HP do inimigo. # #============================================================================== # UTILIZAÇÃO #============================================================================== # Coloque o seguinte comentário na caixa de notas do inimigo. # # <Boss HP Meter> # # Caso desejar ocultar o valor numérico do HP use o código abaixo. # # <Boss HP Hide Number> # #============================================================================== # Caso precisar mudar a posição do medidor no meio do jogo use o código abaixo # # boss_hp_position(X,Y) # #============================================================================== # Serão necessários as imagens. # # Battle_Boss_Meter.png # Battle_Boss_Meter_Layout.png #============================================================================== # FACES (Opcional) #============================================================================== # Nomeie o arquivo da face da seguinte maneira. (Graphics/Faces/) # # Enemy_Name + _F.png (Slime_F.png) # # ou # # BF_ + ID.png (BF_11.png) # #============================================================================== # Definindo o LEVEL (Opcional) #============================================================================== # Coloque o seguinte comentário na caixa de notas do inimigo. # # <Level = X> # #============================================================================== #============================================================================== # Histórico #============================================================================== # v1.5 - Definição do nome da face pelo ID do battler # v1.4 - Melhoria de compatibilidade de scripts. #============================================================================== $imported = {} if $imported.nil? $imported[:mog_blitz_commands] = true module MOG_BOSS_HP_METER #Posição geral do layout. LAYOUT_POSITION = [60,30] #Posição do medidor. METER_POSITION = [3,3] #Posição do nome do inimigo. NAME_POSITION = [16,8] #Posição da face. FACE_POSITION = [0,-30] #Posição do level do inimigo. LEVEL_POSITION = [150, -24]#[290, 0] #Posição do numero de HP HP_NUMBER_POSITION = [230, 5] #Definição do espaço da palavra HP e o valor de numérico. HP_STRING_SPACE = 36 #Ativar efeito wave HP_NUMBER_WAVE_EFFECT = true #Definição da palavra Level. LEVEL_WORD = "Level " #Velocidade de animação do medidor METER_ANIMATION_SPEED = 10 #Definição do tamanho da fonte. FONT_SIZE = 16 #Ativar contorno na fonte. FONT_BOLD = true #Fonte em itálico. FONT_ITALIC = true #Definição da cor da fonte. FONT_COLOR = Color.new(255,255,255) #Definição da prioridade da HUD. PRIORITY_Z = 50 end #============================================================================== # ■ Game System #============================================================================== class Game_System attr_accessor :boss_hp_meter #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- alias mog_boss_hp_meter_initialize initialize def initialize ix = MOG_BOSS_HP_METER::LAYOUT_POSITION[0] iy = MOG_BOSS_HP_METER::LAYOUT_POSITION[1] @boss_hp_meter = [ix,iy,false,"",0,1,0,nil,0,false] mog_boss_hp_meter_initialize end end #============================================================================== # ■ Game Enemy #============================================================================== class Game_Enemy < Game_Battler attr_accessor :boss_hp_meter attr_accessor :boss_hp_number attr_accessor :class attr_accessor :level #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- alias mog_boss_hp_meter_initialize initialize def initialize(index, enemy_id) mog_boss_hp_meter_initialize(index, enemy_id) @boss_hp_meter = enemy.note =~ /<Boss HP Meter>/ ? true : false @boss_hp_number = enemy.note =~ /<Boss HP Hide Number>/ ? false : true @level = enemy.note =~ /<Level = (\d+)>/i ? $1.to_i : define_enemy_level.to_i @class = enemy.note =~ /<Boss HP Meter>/ ? "Boss" : "Minon" @class = enemy.note =~ /<Elite>/ ? "Elite" : "Minon" end def define_enemy_level return (self.atk + self.def + self.mat + self.mdf + self.luk)/20 + self.agi/10 end end #============================================================================== # ■ Game Temp #============================================================================== class Game_Temp attr_accessor :battle_end #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- alias mog_boss_hp_meter_initialize initialize def initialize @battle_end = false mog_boss_hp_meter_initialize end end #============================================================================== # ■ Game Interpreter #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- def boss_hp_position(x = 0,y = 0) $game_system.boss_hp_meter[0] = x $game_system.boss_hp_meter[1] = y end end #============================================================================== # ■ Game Temp #============================================================================== class Game_Temp attr_accessor :cache_boss_hp #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- alias mog_boss_hp_initialize initialize def initialize mog_boss_hp_initialize cache_bosshp end #-------------------------------------------------------------------------- # ● Cache Bosshp #-------------------------------------------------------------------------- def cache_bosshp @cache_boss_hp = [] @cache_boss_hp.push(Cache.system("Battle_Boss_Meter_Layout")) @cache_boss_hp.push(Cache.system("Battle_Boss_Meter")) @cache_boss_hp.push(Cache.system("Battle_Boss_Number")) end end #============================================================================== # ■ Boss HP Meter #============================================================================== class Boss_HP_Meter include MOG_BOSS_HP_METER #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- def initialize(viewport = nil) clear_enemy_setup @hp_vieport = nil check_boss_avaliable end #-------------------------------------------------------------------------- # ● Clear Enemy Setup #-------------------------------------------------------------------------- def clear_enemy_setup @name = "" @hp = 0 @hp2 = 0 @hp3 = 0 @maxhp = 0 @hp_old = 0 @level = nil $game_system.boss_hp_meter[2] = false $game_system.boss_hp_meter[3] = "" $game_system.boss_hp_meter[4] = 0 $game_system.boss_hp_meter[5] = 1 $game_system.boss_hp_meter[7] = nil $game_system.boss_hp_meter[8] = 0 $game_system.boss_hp_meter[9] = true end #-------------------------------------------------------------------------- # ● Check Boss Avaliable #-------------------------------------------------------------------------- def check_boss_avaliable return if $game_troop.all_dead? for i in $game_troop.members if i.boss_hp_meter and !i.hidden? and i.hp > 0 create_boss_hp_meter(i) break end end end #-------------------------------------------------------------------------- # ● Create Boss HP Meter #-------------------------------------------------------------------------- def create_boss_hp_meter(i) $game_system.boss_hp_meter[2] = true $game_system.boss_hp_meter[3] = i.name $game_system.boss_hp_meter[4] = i.hp $game_system.boss_hp_meter[5] = i.mhp $game_system.boss_hp_meter[6] = i.hp $game_system.boss_hp_meter[7] = i.level rescue nil $game_system.boss_hp_meter[8] = 0 $game_system.boss_hp_meter[9] = i.boss_hp_number $game_system.boss_hp_meter[10] = i.enemy_id refresh_hp_meter create_layout create_meter create_name create_face create_level create_hp_number end #-------------------------------------------------------------------------- # ● Create Layout #-------------------------------------------------------------------------- def create_layout return if @layout != nil @layout = Sprite.new @layout.bitmap = $game_temp.cache_boss_hp[0] @layout.x = $game_system.boss_hp_meter[0] @layout.y = $game_system.boss_hp_meter[1] @layout.viewport = @hp_vieport @layout.z = PRIORITY_Z end #-------------------------------------------------------------------------- # ● Create Meter #-------------------------------------------------------------------------- def create_meter return if @meter_image != nil hp_setup @meter_image = $game_temp.cache_boss_hp[1] @meter_cw = @meter_image.width / 3 @meter_ch = @meter_image.height / 2 @meter = Sprite.new @meter.bitmap = Bitmap.new(@meter_cw,@meter_ch) @meter.z = @layout.z + 1 @meter.x = @layout.x + METER_POSITION[0] @meter.y = @layout.y + METER_POSITION[1] @meter.viewport = @hp_vieport @hp_flow = 0 @hp_flow_max = @meter_cw * 2 update_hp_meter end #-------------------------------------------------------------------------- # ● Create Name #-------------------------------------------------------------------------- def create_name @name_sprite = Sprite.new @name_sprite.bitmap = Bitmap.new(200,32) @name_sprite.z = @layout.z + 2 @name_sprite.x = @layout.x + NAME_POSITION[0] @name_sprite.y = @layout.y + NAME_POSITION[1] @name_sprite.bitmap.font.size = FONT_SIZE @name_sprite.bitmap.font.bold = FONT_BOLD @name_sprite.bitmap.font.italic = FONT_ITALIC @name_sprite.bitmap.font.color = FONT_COLOR @name_sprite.viewport = @hp_vieport refresh_name end #-------------------------------------------------------------------------- # ● Create Face #-------------------------------------------------------------------------- def create_face @face_sprite = Sprite.new @face_sprite.x = @layout.x + FACE_POSITION[0] @face_sprite.y = @layout.y + FACE_POSITION[1] @face_sprite.z = @layout.z + 2 @face_sprite.viewport = @hp_vieport refresh_face end #-------------------------------------------------------------------------- # ● Create Level #-------------------------------------------------------------------------- def create_level @level_sprite = Sprite.new @level_sprite.bitmap = Bitmap.new(120,32) @level_sprite.z = @layout.z + 2 @level_sprite.x = @layout.x + LEVEL_POSITION[0] @level_sprite.y = @layout.y + LEVEL_POSITION[1] @level_sprite.bitmap.font.size = FONT_SIZE @level_sprite.bitmap.font.bold = FONT_BOLD @level_sprite.bitmap.font.italic = FONT_ITALIC @level_sprite.bitmap.font.color = FONT_COLOR @level_sprite.viewport = @hp_vieport refresh_level end #-------------------------------------------------------------------------- # ● Create HP Number #-------------------------------------------------------------------------- def create_hp_number @hp2 = $game_system.boss_hp_meter[4] @hp3 = @hp2 @hp_old2 = @hp2 @hp_ref = @hp_old2 @hp_refresh = false @hp_number_image = $game_temp.cache_boss_hp[2] @hp_cw = @hp_number_image.width / 10 @hp_ch = @hp_number_image.height / 2 @hp_ch2 = 0 @hp_ch_range = HP_NUMBER_WAVE_EFFECT == true ? @hp_ch / 3 : 0 @hp_number_sprite = Sprite.new @hp_number_sprite.bitmap = Bitmap.new(@hp_number_image.width, @hp_ch * 2) @hp_number_sprite.z = @layout.z + 2 @hp_number_sprite.x = @layout.x + HP_NUMBER_POSITION[0] @hp_number_sprite.y = @layout.y + HP_NUMBER_POSITION[1] @hp_number_sprite.viewport = @hp_vieport @hp_number_sprite.visible = $game_system.boss_hp_meter[9] refresh_hp_number end #-------------------------------------------------------------------------- # ● update_hp_number #-------------------------------------------------------------------------- def update_hp_number return if @hp_number_sprite == nil @hp_number_sprite.visible = $game_system.boss_hp_meter[9] if @hp_old2 < $game_system.boss_hp_meter[4] number_refresh_speed @hp2 += @hp_ref reset_hp_number if @hp2 >= $game_system.boss_hp_meter[4] elsif @hp_old2 > $game_system.boss_hp_meter[4] number_refresh_speed @hp2 -= @hp_ref reset_hp_number if @hp2 <= $game_system.boss_hp_meter[4] end end #-------------------------------------------------------------------------- # ● Number Refresh Speed #-------------------------------------------------------------------------- def number_refresh_speed @hp_refresh = true @hp_ref = (3 * (@hp_old2 - $game_system.boss_hp_meter[4]).abs / 100) rescue nil @hp_ref = 1 if @hp_ref == nil or @hp_ref < 1 end #-------------------------------------------------------------------------- # ● Refresh HP Number #-------------------------------------------------------------------------- def refresh_hp_number return if @hp_number_sprite == nil @hp_refresh = false @hp_number_sprite.bitmap.clear number = @hp2.abs.to_s.split(//) @hp_ch2 = 0 for r in 0..number.size - 1 number_abs = number[r].to_i nsrc_rect = Rect.new(@hp_cw * number_abs, 0, @hp_cw, @hp_ch) @hp_ch2 = @hp_ch2 == @hp_ch_range ? 0 : @hp_ch_range @hp_number_sprite.bitmap.blt(HP_STRING_SPACE + (@hp_cw * r), @hp_ch2, @hp_number_image, nsrc_rect) end nsrc_rect = Rect.new(0, @hp_ch, @hp_number_image.width, @hp_ch) @hp_number_sprite.bitmap.blt(0, 0, @hp_number_image, nsrc_rect) end #-------------------------------------------------------------------------- # ● Reset HP Number #-------------------------------------------------------------------------- def reset_hp_number @hp_refresh = true @hp_old2 = $game_system.boss_hp_meter[4] @hp2 = $game_system.boss_hp_meter[4] @hp_ref = 0 refresh_hp_number end #-------------------------------------------------------------------------- # ● Refresh Level #-------------------------------------------------------------------------- def refresh_level return if @level_sprite == nil @level_sprite.bitmap.clear @level = $game_system.boss_hp_meter[7] return if @level == nil level_text = LEVEL_WORD + @level.to_s @level_sprite.bitmap.draw_text(0,0,120,32,level_text.to_s) end #-------------------------------------------------------------------------- # ● Refresh Face #-------------------------------------------------------------------------- def refresh_face return if @face_sprite == nil dispose_bitmap_face @face_sprite.bitmap = Cache.face(@name + "_f") rescue nil @face_sprite.bitmap = Cache.face("BF_" + $game_system.boss_hp_meter[10].to_s) rescue nil if @face_sprite.bitmap == nil @face_sprite.bitmap = Cache.face("") if @face_sprite.bitmap == nil end #-------------------------------------------------------------------------- # ● Refresh Name #-------------------------------------------------------------------------- def refresh_name return if @name_sprite == nil @name = $game_system.boss_hp_meter[3] @name_sprite.bitmap.clear @name_sprite.bitmap.draw_text(0,0,190,32,@name.to_s) refresh_face refresh_level reset_hp_number @hp_old = @meter_cw * @hp / @maxhp end #-------------------------------------------------------------------------- # ● HP Setup #-------------------------------------------------------------------------- def hp_setup @hp = $game_system.boss_hp_meter[4] @maxhp = $game_system.boss_hp_meter[5] end #-------------------------------------------------------------------------- # ● Dispose #-------------------------------------------------------------------------- def dispose dispose_layout dispose_meter dispose_name dispose_face dispose_level dispose_hp_number end #-------------------------------------------------------------------------- # ● Dispose Name #-------------------------------------------------------------------------- def dispose_name return if @name_sprite == nil @name_sprite.bitmap.dispose @name_sprite.dispose @name_sprite = nil end #-------------------------------------------------------------------------- # ● Dispose Layout #-------------------------------------------------------------------------- def dispose_layout return if @layout == nil @layout.dispose @layout = nil end #-------------------------------------------------------------------------- # ● Dispose Meter #-------------------------------------------------------------------------- def dispose_meter return if @meter == nil @meter.bitmap.dispose @meter.dispose @meter = nil end #-------------------------------------------------------------------------- # ● Dispose Face #-------------------------------------------------------------------------- def dispose_face return if @face_sprite == nil dispose_bitmap_face @face_sprite.dispose @face_sprite = nil end #-------------------------------------------------------------------------- # ● Dispose Bitmap Face #-------------------------------------------------------------------------- def dispose_bitmap_face return if @face_sprite == nil return if @face_sprite.bitmap == nil @face_sprite.bitmap.dispose rescue nil @face_sprite.bitmap = nil end #-------------------------------------------------------------------------- # ● Dispose Level #-------------------------------------------------------------------------- def dispose_level return if @level_sprite == nil @level_sprite.bitmap.dispose @level_sprite.dispose @level_sprite = nil end #-------------------------------------------------------------------------- # ● Dispose HP Number #-------------------------------------------------------------------------- def dispose_hp_number return if @hp_number_sprite == nil @hp_number_sprite.bitmap.dispose @hp_number_sprite.dispose end #-------------------------------------------------------------------------- # ● Update #-------------------------------------------------------------------------- def update refresh_hp_meter refresh_hp_number if @hp_refresh update_hp_meter update_hp_number update_fade_end update_visible end #-------------------------------------------------------------------------- # ● Update Visible #-------------------------------------------------------------------------- def update_visible return if @meter_image == nil vis = bhp_visible? @layout.visible = vis @meter.visible = vis @name_sprite.visible = vis @face_sprite.visible = vis @level_sprite.visible = vis @hp_number_sprite.visible = vis end #-------------------------------------------------------------------------- # ● Bhp Visible? #-------------------------------------------------------------------------- def bhp_visible? return false if $game_message.visible return true end #-------------------------------------------------------------------------- # ● Update Fade End #-------------------------------------------------------------------------- def update_fade_end return if !$game_temp.battle_end return if @meter_image == nil @layout.opacity -= 5 @meter.opacity -= 5 @name_sprite.opacity -= 5 @face_sprite.opacity -= 5 @level_sprite.opacity -= 5 @hp_number_sprite.opacity -= 5 end #-------------------------------------------------------------------------- # ● Refresh HP Meter #-------------------------------------------------------------------------- def refresh_hp_meter return if !$game_system.boss_hp_meter[2] $game_system.boss_hp_meter[2] = false hp_setup refresh_name if @name != $game_system.boss_hp_meter[3] end #-------------------------------------------------------------------------- # ● Update HP Meter #-------------------------------------------------------------------------- def update_hp_meter return if @meter_image == nil @meter.bitmap.clear hp_width = @meter_cw * @hp / @maxhp execute_damage_flow(hp_width) hp_src_rect = Rect.new(@hp_flow, 0,hp_width, @meter_ch) @meter.bitmap.blt(0,0, @meter_image, hp_src_rect) @hp_flow += METER_ANIMATION_SPEED @hp_flow = 0 if @hp_flow >= @hp_flow_max end #-------------------------------------------------------------------------- # ● Execute Damage Flow #-------------------------------------------------------------------------- def execute_damage_flow(hp_width) return if @hp_old == hp_width n = (@hp_old - hp_width).abs * 3 / 100 damage_flow = [[n, 2].min,0.5].max @hp_old -= damage_flow @hp_old = hp_width if @hp_old <= hp_width src_rect_old = Rect.new(0,@meter_ch, @hp_old, @meter_ch) @meter.bitmap.blt(0,0, @meter_image, src_rect_old) end end #============================================================================== # ■ Spriteset Battle #============================================================================== class Spriteset_Battle #-------------------------------------------------------------------------- # ● Initialize #-------------------------------------------------------------------------- alias mog_enemy_bhp_initialize initialize def initialize mog_enemy_bhp_initialize create_boss_hp_meter end #-------------------------------------------------------------------------- # ● Create Boss HP Meter #-------------------------------------------------------------------------- def create_boss_hp_meter @boss_hp_meter = Boss_HP_Meter.new(@viewport1) end #-------------------------------------------------------------------------- # ● Dispose #-------------------------------------------------------------------------- alias mog_enemy_bhp_dispose dispose def dispose dispose_boss_hp_meter mog_enemy_bhp_dispose end #-------------------------------------------------------------------------- # ● Dispose Boss HP Meter #-------------------------------------------------------------------------- def dispose_boss_hp_meter return if @boss_hp_meter == nil @boss_hp_meter.dispose @boss_hp_meter = nil end #-------------------------------------------------------------------------- # ● Update #-------------------------------------------------------------------------- alias mog_enemy_bhp_update update def update mog_enemy_bhp_update update_boss_hp_meter end #-------------------------------------------------------------------------- # ● Update Boss HP Meter #-------------------------------------------------------------------------- def update_boss_hp_meter return if @boss_hp_meter == nil @boss_hp_meter.update end end #============================================================================== # ■ Game_Battler #============================================================================== class Game_Battler < Game_BattlerBase #-------------------------------------------------------------------------- # ● Item Apply #-------------------------------------------------------------------------- alias mog_boss_hp_item_apply item_apply def item_apply(user, item) check_boss_hp_before mog_boss_hp_item_apply(user, item) check_boss_hp_after end #-------------------------------------------------------------------------- # ● Regenerate HP #-------------------------------------------------------------------------- alias mog_boss_hp_regenerate_hp regenerate_hp def regenerate_hp check_boss_hp_before mog_boss_hp_regenerate_hp check_boss_hp_after end #-------------------------------------------------------------------------- # ● Check Boss HP Before #-------------------------------------------------------------------------- def check_boss_hp_before return if self.is_a?(Game_Actor) return if !self.boss_hp_meter $game_system.boss_hp_meter[6] = self.hp end #-------------------------------------------------------------------------- # ● Check Boss HP After #-------------------------------------------------------------------------- def check_boss_hp_after return if self.is_a?(Game_Actor) return if !self.boss_hp_meter $game_system.boss_hp_meter[2] = true $game_system.boss_hp_meter[3] = self.name $game_system.boss_hp_meter[4] = self.hp $game_system.boss_hp_meter[5] = self.mhp $game_system.boss_hp_meter[7] = self.level rescue nil $game_system.boss_hp_meter[9] = self.boss_hp_number end end #============================================================================== # ■ Game_Interpreter #============================================================================== class Game_Interpreter #-------------------------------------------------------------------------- # ● Check Boss Meter #-------------------------------------------------------------------------- def check_boss_meter return if !SceneManager.scene_is?(Scene_Battle) iterate_enemy_index(@params[0]) do |enemy| if enemy.boss_hp_meter $game_system.boss_hp_meter[2] = true $game_system.boss_hp_meter[3] = enemy.name $game_system.boss_hp_meter[4] = enemy.hp $game_system.boss_hp_meter[5] = enemy.mhp $game_system.boss_hp_meter[6] = enemy.hp $game_system.boss_hp_meter[7] = enemy.level rescue nil $game_system.boss_hp_meter[9] = enemy.boss_hp_number end end end #-------------------------------------------------------------------------- # ● Command 331 #-------------------------------------------------------------------------- alias mog_boss_meter_command_331 command_331 def command_331 mog_boss_meter_command_331 check_boss_meter end #-------------------------------------------------------------------------- # ● Command 334 #-------------------------------------------------------------------------- alias mog_boss_meter_command_334 command_334 def command_334 mog_boss_meter_command_334 check_boss_meter end end #============================================================================== # ■ BattleManager #============================================================================== class << BattleManager #-------------------------------------------------------------------------- # ● Init Members #-------------------------------------------------------------------------- alias mog_boss_meter_init_members init_members def init_members $game_temp.battle_end = false mog_boss_meter_init_members end #-------------------------------------------------------------------------- # ● Process Victory #-------------------------------------------------------------------------- alias mog_boss_meter_process_victory process_victory def process_victory $game_temp.battle_end = true mog_boss_meter_process_victory end #-------------------------------------------------------------------------- # ● Process Abort #-------------------------------------------------------------------------- alias mog_boss_meter_process_abort process_abort def process_abort $game_temp.battle_end = true mog_boss_meter_process_abort end #-------------------------------------------------------------------------- # ● Process Defeat #-------------------------------------------------------------------------- alias mog_boss_meter_process_defeat process_defeat def process_defeat $game_temp.battle_end = true mog_boss_meter_process_defeat end end
true
ae5f9ef0cab2e644354cdcea234b9bbfd59e9075
Ruby
btreim/ruby
/RSpec/lib/string_calculator.rb
UTF-8
183
3.40625
3
[]
no_license
class StringCalculator def self.add(input) if input.empty? 0 else numbers = input.split(",").map{|num| num.to_i} numbers.inject { |mem, num| mem + num } end end end
true
5abf6a6f07152fbdf890f3d77407598a2bcddeb3
Ruby
m3talsmith/expectations
/lib/expectations/mock_recorder.rb
UTF-8
518
2.515625
3
[ "Ruby" ]
permissive
module Expectations::MockRecorder def receive!(method) method_stack << [:expects, [method]] self end def method_stack @method_stack ||= [] end def method_missing(sym, *args) super if method_stack.empty? method_stack << [sym, args] self end def subject! method_stack.inject(subject) { |result, element| result.send element.first, *element.last } subject end def verify subject.verify end def mocha_error_message(ex) ex.message end end
true
89b071e9936f8005cf8d6e791938b98df87102c5
Ruby
LuciferBlade/Ruby-assignments
/ruby uzduotis 2/3/tc_ruby_2_3_re.rb
UTF-8
1,011
2.90625
3
[]
no_license
# frozen_string_literal: true require_relative 'ruby_2_3_re' require 'test/unit' # Unit test class class TestSolutionFinder < Test::Unit::TestCase def test_intro_message assert(true, SolutionFinder.new.intro_message) end def test_count_signs assert_equal(0, SolutionFinder.new.count_signs) end def test_value_reader assert_equal('123', SolutionFinder.new.value_reader) end def test_number_grouping assert_equal(0, SolutionFinder.new.number_groping([1, 2, 3, 4], [0, 0, 0])) end def test_number_multiplication assert_equal(0, SolutionFinder.new.number_multiplication(1, [1, 2], [2])) end def test_number_sum assert_equal(0, SolutionFinder.new.number_sum(1, [1, 2], [1])) end def test_answer_writer assert(true, SolutionFinder.new.answer_writer([1, 2, 3, 4, 5], 123)) end def test_sign_change assert_not_nil(SolutionFinder.new.sign_change, 'it is nil') end def test_run # asser_not_nil(SolutionFinder.new.run, 'it is nil') end end
true
d7f86957b011061eeeb5a6f84d1754fc0e214829
Ruby
carloscortegagna/sigeol
/test/unit/building_test.rb
UTF-8
1,644
2.859375
3
[]
no_license
#QuiXoft - Progetto ”SIGEOL” #NOME FILE: building_test.rb #AUTORE: Grosselle Alessandro require 'test_helper' class BuildingTest < ActiveSupport::TestCase def setup @b=Building.new end #test13: un oggetto con attributi nulli, non deve essere valido. Se non è valido non viene salvato # nel database test"Il contenuto degli attributi non deve essere nullo"do #caso di prova13.1: @b contiene un oggetto con attributi nulli. #obiettivo: il sistema deve riconoscere @b come non valido; in particolare deve riscontrare #l'errore nell'unico attributo che possiede(name) assert !@b.valid? assert @b.errors.invalid?(:name) end #test14: non devono esistere due palazzi con lo stesso nome test"Non devono esistere due palazzi con lo stesso nome"do #caso di prova 14.1: assegno a @b un nome che è già stato assegnato ad un altro palazzo #obiettivo: il sistema deve riconoscere @b come non valido perchè ha lo stesso nome #un altro palazzo già presente come tupla @b.name= buildings(:building_1).name assert !@b.valid? assert_equal "Esiste già un palazzo con questo nome", @b.errors.on(:name) end #test15: eliminazione di un palazzo test"Eliminazione di un palazzo"do #caso di prova 15.1: si elimina la tupla buildings_1 #obiettivo: eliminandola non deve più esistere l'indirizzo associato e tutte le classi appartenenti. #buildings_1 è associato ad un indirizzo(address_2) e ad una classe(classroom_1) @b=buildings(:building_1) assert @b.destroy assert_raise(ActiveRecord::RecordNotFound){Address.find(@b.address_id)} assert !Classroom.find_by_building_id(@b.id) end end
true
d8c1aa4672116365a17843f6befa39b4243f001b
Ruby
docodon/hplanner_bakend
/lib/helper_functions.rb
UTF-8
316
3.21875
3
[]
no_license
module HelperFunctions def HelperFunctions.binary_search ar,val lo , hi = 0 , ar.size - 1 while 1 mid = (lo + hi)/2 (lo..hi).each do |i| return i if ar[i]>=val end if hi-lo<=3 if ar[mid] > val hi = mid elsif ar[mid] == val return mid else lo = mid + 1 end end end end
true
c9c3f57a1ae8981a63464305cbe0202e863ad0d8
Ruby
wkoszek/sivers
/db-api/core/test.rb
UTF-8
4,215
2.703125
3
[ "BSD-2-Clause" ]
permissive
require '../test_tools.rb' class CoreTest < Minitest::Test include JDB def setup @raw = "<!-- This is a title -->\r\n<p>\r\n\tAnd this?\r\n\tThis is a translation.\r\n</p>" @lines = ['This is a title', 'And this?', 'This is a translation.'] @fr = ['Ceci est un titre', 'Et ça?', 'Ceci est une phrase.'] super end def test_strip_tags res = DB.exec_params("SELECT core.strip_tags($1)", ['þ <script>alert("poop")</script> <a href="http://something.net">yuck</a>']) assert_equal 'þ alert("poop") yuck', res[0]['strip_tags'] end def test_escape_html res = DB.exec_params("SELECT core.escape_html($1)", [%q{I'd "like" <&>}]) assert_equal 'I&#39;d &quot;like&quot; &lt;&amp;&gt;', res[0]['escape_html'] end def test_currency_from_to res = DB.exec("SELECT * FROM core.currency_from_to(1000, 'USD', 'EUR')") assert (881..882).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.currency_from_to(1000, 'EUR', 'USD')") assert (1135..1136).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.currency_from_to(1000, 'JPY', 'EUR')") assert (7..8).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.currency_from_to(1000, 'EUR', 'BTC')") assert (4..5).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.currency_from_to(9, 'BTC', 'JPY')") assert (248635..248636).cover? res[0]['amount'].to_f end def test_money_to res = DB.exec("SELECT * FROM core.money_to(('USD',1000), 'EUR')") assert (881..882).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.money_to(('EUR',1000), 'USD')") assert (1135..1136).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.money_to(('JPY',1000), 'EUR')") assert (7..8).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.money_to(('EUR',1000), 'BTC')") assert (4..5).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.money_to(('BTC',9), 'JPY')") assert (248635..248636).cover? res[0]['amount'].to_f end def test_add_money res = DB.exec("SELECT * FROM core.add_money(('USD', 10), ('EUR', 10))") assert_equal 'USD', res[0]['currency'] assert (21..22).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.add_money(('EUR', 10), ('USD', 10))") assert_equal 'EUR', res[0]['currency'] assert (18..19).cover? res[0]['amount'].to_f end def test_subtract_money res = DB.exec("SELECT * FROM core.subtract_money(('USD', 20), ('EUR', 10))") assert_equal 'USD', res[0]['currency'] assert (8..9).cover? res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.subtract_money(('EUR', 20), ('USD', 10))") assert_equal 'EUR', res[0]['currency'] assert (11..12).cover? res[0]['amount'].to_f end def test_multiply_money res = DB.exec("SELECT * FROM core.multiply_money(('USD', 20), 0.456789)") assert_equal 'USD', res[0]['currency'] assert_equal 9.13578, res[0]['amount'].to_f res = DB.exec("SELECT * FROM core.multiply_money(('EUR', 20), 1.55)") assert_equal 'EUR', res[0]['currency'] assert_equal 31, res[0]['amount'].to_f end def test_all_currencies qry("core.all_currencies()") assert_equal 34, @j.size assert_equal({code: 'AUD', name: 'Australian Dollar'}, @j[0]) assert_equal({code: 'ZAR', name: 'South African Rand'}, @j[33]) end def test_currency_names qry("core.currency_names()") assert_equal 34, @j.size assert_equal 'Singapore Dollar', @j[:SGD] assert_equal 'Euro', @j[:EUR] end def test_changelog_nodupe DB.exec("INSERT INTO core.changelog(person_id, schema_name, table_name, table_id) VALUES (1, 'now', 'urls', 1)") res = DB.exec("SELECT * FROM core.changelog WHERE person_id=1") assert_equal 1, res.ntuples assert_equal '1', res[0]['id'] DB.exec("INSERT INTO core.changelog(person_id, schema_name, table_name, table_id) VALUES (1, 'now', 'urls', 1)") res = DB.exec("SELECT * FROM core.changelog WHERE person_id=1") assert_equal 1, res.ntuples DB.exec("UPDATE core.changelog SET approved=TRUE WHERE id=1") DB.exec("INSERT INTO core.changelog(person_id, schema_name, table_name, table_id) VALUES (1, 'now', 'urls', 1)") res = DB.exec("SELECT * FROM core.changelog WHERE person_id=1") assert_equal 2, res.ntuples end end
true
8adc264bd7ad39d64d8a9cebf6a8515cfdce717a
Ruby
Jevaughnmckenzie/oo-student-scraper-v-000
/lib/scraper.rb
UTF-8
1,613
3.0625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'pry' require_relative '../config' class Scraper def self.scrape_index_page(index_url) html = open(index_url) nested_html = Nokogiri::HTML(html) student_cards = nested_html.css('.student-card') # binding.pry scraped_array = [] student_cards.each do |student_card| scraped_array << { name: student_card.css('a .card-text-container .student-name').text, location: student_card.css('a .card-text-container .student-location').text, profile_url: student_card.css('a').attr('href').value } # binding.pry end # binding.pry scraped_array end def self.scrape_profile_page(profile_url) profile_html = open(profile_url) nested_html = Nokogiri::HTML(profile_html) scraped_hash = {} # for social media links # grab links # place in hash with appropriate keys # method 1: use regex to identify the root uri social_media = nested_html.css('.social-icon-container a') social_media.each do |anchor| link = anchor.attr('href') uri = link.gsub(/.com.*/, "") root_uri = uri.gsub(/.*\/{2}w*\.*/, "") case root_uri when 'twitter', 'github', 'linkedin' scraped_hash[root_uri.to_sym] = link else scraped_hash[:blog] = link end end scraped_hash[:profile_quote] = nested_html.css('.profile-quote').text scraped_hash[:bio] = nested_html.css('.bio-content .description-holder p').text # binding.pry scraped_hash end end
true
d1e9c94b20a524a522ffd6f6ca18b4a8cf5c8ef1
Ruby
upenn-libraries/subpop
/app/models/content_type.rb
UTF-8
228
2.609375
3
[]
no_license
class ContentType < ActiveRecord::Base validates :name, uniqueness: true validates :name, presence: true def <=> other self.sort_name <=> other.sort_name end def sort_name self.name.sub /^\W+/, '' end end
true
bbfb55b397b0224d7e13b57c0914c299fafed18e
Ruby
TeddyBradsher/ruby-oo-fundamentals-classes-and-instances-lab-nyc01-seng-ft-071320
/lib/person.rb
UTF-8
174
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Person attr_accessor :name def initialize (name) @name = name end end adele_goldberg = Person.new("adele goldberg") alan_kay = Person.new("alan kay")
true
1cb49d00d055edda016ffff9b72427d2c6c007b9
Ruby
Supernich/internship_nvo
/Rakefile
UTF-8
1,396
2.703125
3
[]
no_license
task :create_directory, [:dir_name] => :check_directory do |task, args| if @dir_exist p 'Directory already exist' return end create_directory(args[:dir_name]) end task :check_directory, :directory do |task, args| check_directory(args[:dir_name] || args[:directory]) end def create_directory(dir_path) check_directory(dir_path) return if @dir_exist dir = dir_path.split('/') dir.delete(dir.first) if dir.length > 1 dir.each do |path| mkdir path cd path end end def check_directory(dir_path) pathname = "./#{dir_path}" @dir_exist = Dir.exist?(pathname) end task :create_file, [:file_path] => :check_file do |task, args| if @file_exist p 'File already exist' return end path = args[:file_path].split('/') if path.length > 1 path_string = '' (path.length - 1).times do |i| path_string += "/#{path[i]}" end create_directory(path_string) end touch(args[:file_path]) unless @file_exist end task :check_file, :path_to_file do |task, args| path = args[:file_path] || args[:path_to_file] @file_exist = File.exist?(path) end desc 'Set timezone' task :set_timezone do ENV['TZ'] = 'UTC' end desc 'Show time' task default: :set_timezone do puts "#{Time.now}" end namespace :work_with_files do task :create_directory do mkdir_p('New_directory') cd('New_directory') touch('Some_file.rb') end end
true
2cb7be7d1ff8c1c23907d6194f46b01ef9ca0115
Ruby
apeiros/halsbe
/implementation/lib/minheap.rb
UTF-8
1,234
3.453125
3
[]
no_license
class MinHeap attr_reader :heap def initialize(size) @heap = [nil] end def pop value = @heap.at(1) index = 1 child_index = nil child_index_a = 2 child_index_b = 3 child_a = @heap.at(child_index_a) child_b = @heap.at(child_index_b) while child_a or child_b if child_a then if child_b then if child_a < child_b then # switch a with parent (== index) else end else # only child_a end else # only child_b end child_a = @heap.at(child_index_a) child_b = @heap.at(child_index_b) child_index_a = child_index child_index_b = child_index_a+1 end end def insert(*values) values.each { |value| self << value } end def <<(value) index = @heap.size parent = index >> 1 parval = @heap.at(parent) @heap << value until parent.zero? or parval <= value @heap[parent] = value @heap[index] = parval index = parent parent = parent >> 1 parval = @heap.at(parent) end self end def parent(index) @heap.at(index >> 1) end def children(index) @heap[index << 1, 2] end def parent_index(own_index) own_index >> 1 end def child_indices(index) a = index << 1 [a, a+1] end end
true
daec801d8ae2c4b050f604d7f15a79baa7cf7237
Ruby
omnitest/fog-samples
/compute_v2/detach_volume.rb
UTF-8
2,035
2.671875
3
[]
no_license
#!/usr/bin/env ruby # This example demonstrates how to manage volumes on an existing server instance. # # Services used: # - [Delete Volume Attachment](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Volume_Attachment.html) require 'fog' require File.expand_path('../../sample_helper', __FILE__) #create Next Generation Cloud Server service compute_service = Fog::Compute.new({ :provider => 'rackspace', :rackspace_username => SampleHelper.rackspace_username, :rackspace_api_key => SampleHelper.rackspace_api_key, :version => :v2, # Use Next Gen Cloud Servers :rackspace_region => SampleHelper.rackspace_region, # e.g. ord :rackspace_auth_url => SampleHelper.authentication_endpoint }) cbs_service = Fog::Rackspace::BlockStorage.new({ :rackspace_username => SampleHelper.rackspace_username, :rackspace_api_key => SampleHelper.rackspace_api_key, :rackspace_region => SampleHelper.rackspace_region, # e.g. ord :rackspace_auth_url => SampleHelper.authentication_endpoint }) # retrieve list of servers servers = compute_service.servers # prompt user for server server = SampleHelper.select_server(servers) # get attached volumes --also know as attachments attachments = server.attachments # prompt user for volume to detach attachment = SampleHelper.select_attachment(attachments) raise "No attachment to delete" if attachment.nil? volume = cbs_service.volumes.get attachment.volume_id puts "Detaching Volume #{volume.display_name} From Server #{server.name}" retriable do attachment.detach end puts "\n" delete_confirm = SampleHelper.get_required_option 'CONFIRM_DELETE', "Would You Like To Destroy Volume #{volume.display_name} (y/n)" if delete_confirm.downcase == 'y' # wait for server to finish detaching before attempting to delete volume.wait_for(600) do print "." STDOUT.flush puts "State: #{volume.state}" puts "Attachments: #{attachments.size}" ready? end volume.destroy puts "\n\nThe Volume Has been Destroyed" end
true
e6f279215867e7ea66246c9b121b14a0d47a3ec1
Ruby
kbrock/wsdl_dsl
/app/models/simple_type_def.rb
UTF-8
1,617
2.53125
3
[]
no_license
## currently used for simple types class SimpleTypeDef < NamespacedNode def self.all if not defined? @@types @@types=[] #skipped 'byte' 'decimal' 'integer' 'long' 'short' 'unsignedByte' 'unsignedInt' 'unsignedShort' ['boolean', 'dateTime','date','double', 'float','int', 'string', 'time', 'duration'].each do |name| @@types << SimpleTypeDef.new(name) end end @@types end #used for optionals or arrays @@java_objects={'boolean'=>'Boolean', 'datetime'=>'Date', 'date'=>'Date', 'double'=>'Double', 'float'=>'Float', 'integer'=>'Integer', 'int'=>'Integer', 'string'=>'String', 'time'=>'Date'} #used for primitives @@java_primitives={'boolean'=>'boolean', 'datetime'=>'Date', 'date'=>'Date', 'double'=>'double', 'float'=>'float', 'integer'=>'int', 'int'=>'int', 'string'=>'String', 'time'=>'Date'} def initialize(name) super(name,{:namespace => "http://www.w3.org/2001/XMLSchema", :namespace_abbr=>'xs', :plural => false, :file_name => ''}) end #the name that this type goes by #this was defined by this name # for most namespaced_nodes def soap_name @name end ## display the java type ## basically convert the xsd types to java types def java_name(array=false,optional=false) if optional or array str2=@@java_objects[@name.downcase] str2="List<#{str2}>" if array else str2=@@java_primitives[@name.downcase] end str2 end def complex? false end def to_s(prepend="") "#{prepend} simple_type #{soap_name}" end end
true
97ed9ca4ba40af99ca13695b721491be55d668e9
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/strain/3505bcb6f3444df69b94fa02b64e5948.rb
UTF-8
174
2.84375
3
[]
no_license
class Array def keep each_with_object([]) do |item, object| object << item if yield(item) end end def discard keep {|item| !yield(item)} end end
true
90f182b1a329a30207103f2198d44b5cda3825ee
Ruby
tky3a/spec
/lib/calc.rb
UTF-8
87
2.890625
3
[]
no_license
class Calc def add(a, b) # 5 # 仮実装 a + b #明らかな実装 end end
true
eaf5df35f2dc097bd8e087414840cfe52b22c931
Ruby
jof/tommy
/lib/tommy/libtftp.rb
UTF-8
20,932
2.6875
3
[]
no_license
#!/usr/bin/env ruby # library for TFTP functions require 'socket' require 'timeout' require 'stringio' include Socket::Constants class TFTPOpCode RRQ = 1 WRQ = 2 DATA = 3 ACK = 4 ERROR = 5 OACK = 6 end class TFTPException < Exception end class TFTPImplementation attr_accessor :socket, :timeout, :client, :request_callback def initialize(socket, timeout, client, request_callback) @socket = socket @timeout = timeout || 5 @client = client || [] @request_callback = request_callback || nil end def get_options(args) options = {} if not args.nil? or args.empty? o = args.split("\x00") if 1 == (o.length % 2) o.push("") end options = Hash[*o] end end def trace(msg) $LOG.debug(msg) if $LOG end def trace_received_with_options(msg, args) options = get_options(args) opts = "" options.each {|k,v| opts.insert(-1, ", %s=%s" % [k,v]) } $LOG.debug("received %s%s>" % [msg, opts]) end def trace_received(msg, client) data = msg.unpack("n") opcode = data[0] case opcode when TFTPOpCode::RRQ opcode, filename, mode, rest = msg.unpack("nZ*Z*a*") trace_received_with_options("RRQ <file=%s, mode=%s" % [filename, mode], rest) when TFTPOpCode::WRQ opcode, filename, mode, rest = msg.unpack("nZ*Z*a*") trace_received_with_options("WRQ <file=%s, mode=%s" % [filename, mode], rest) when TFTPOpCode::ACK opcode, blocknum = msg.unpack("nn") trace "received ACK <block=%s>" % blocknum when TFTPOpCode::OACK opcode, blocknum, rest = msg.unpack("nna*") trace_received_with_options("OACK <block=%d" % [blocknum], rest) when TFTPOpCode::DATA opcode, blocknum, rest = msg.unpack("nna*") trace "received DATA <block=%s>" % blocknum when TFTPOpCode::ERROR opcode, code, errmsg = msg.unpack("nna*") trace "received ERROR <code=%s, msg=%s>" % [code, errmsg] else trace "unknown opcode [%s]" % opcode end end # return a request object or nil def get_request_handler(socket = @socket) while TRUE begin msg, client = socket.recvfrom(65535) trace_received(msg, client) data = msg.unpack("nZ*Z*Z*Z*Z*Z*Z*Z*") opcode = data[0] if TFTPOpCode::RRQ == opcode or TFTPOpCode::WRQ == opcode then requested_filename = data[1] mode = data[2] if requested_filename.nil? or requested_filename.empty? or mode.nil? or mode.empty? then $LOG.warn("Request packet is missing a filename or transfer mode") next end case mode.downcase when "netascii", "octet" when "mail" # deprecated else $LOG.warn("Received a bad transfer mode ('%s') from [%s:%s]" % [mode, client[3], client[1]]) next end # options options = Hash[*data[3..-1]] case opcode when TFTPOpCode::RRQ $LOG.info("Incoming read request packet for [%s] from [%s:%s]" % [requested_filename, client[3], client[1]]) when TFTPOpCode::WRQ $LOG.info("Incoming write request packet for [%s] from [%s:%s]" % [requested_filename, client[3], client[1]]) end ### begin # The request callback should return a nil or an IO-type object that can be written or read to (depending on the opcode) request_callback = @request_callback.call(@socket, client, opcode, requested_filename, mode, options) if request_callback.nil? TFTPError.UnknownError(@socket, "Denied.", client) next end case request_callback when String request_callback = StringIO.new(request_callback) when StringIO when File when IO else raise ArgumentError.new("The request_callback [%s] is of non-IOable type [%s]" % [request_callback.inspect, request_callback.class]) end case opcode when TFTPOpCode::RRQ return TFTPServerRead.new(request_callback, mode, client, options) when TFTPOpCode::WRQ return TFTPServerWrite.new(request_callback, mode, client, options) end rescue Exception => e $LOG.debug("Caught error calling request_callback and/or handling it: #{e.inspect}") e.backtrace.each{|x| puts x} exit end ## else #The opcode is not a RRQ or WRQ $LOG.warn("Mangled packet received: %s" % msg) end end end end def rrq(addr, port, filename, mode, options = {}) extra_options = "" opts = "" options.each {|k,v| extra_options.insert(-1, [k.to_s,v.to_s].pack("Z*Z*")) opts.insert(-1, ", %s=%s" % [k,v]) } trace "sent RRQ <file=%s, mode=%s%s>" % [filename, mode, opts] socket.send( [ TFTPOpCode::RRQ, filename, mode ].pack("nZ*Z*") + extra_options, 0, addr, port ) end def wrq(addr, port, filename, mode, options = {}) extra_options = "" opts = "" options.each {|k,v| extra_options.insert(-1, [k.to_s,v.to_s].pack("Z*Z*")) opts.insert(-1, ", %s=%s" % [k,v]) } trace "sent WRQ <file=%s, mode=%s%s>" % [filename, mode, opts] socket.send( [ TFTPOpCode::WRQ, filename, mode ].pack("nZ*Z*") + extra_options, 0, addr, port ) end def data_read(blocknum, socket = @socket, timeout = @timeout) Timeout::timeout(timeout) do # wait for data block while TRUE trace "waiting for data: block %d" % blocknum msg, client = socket.recvfrom(65535) trace_received(msg, client) if client[3] == @client[3] then if @client[1].nil? then # no port exists @client[1] = client[1] elsif client[1] == @client[1] # matched else # bad TID TFTPError.BadTID(@socket, client) next end data = msg.unpack "nn" if TFTPOpCode::ERROR == data[0] then raise TFTPException.new("%s (%d:%s)" % [ msg.unpack("nnZ*")[2], data[1], TFTPError::CodeToMsg(data[1]), ]) elsif TFTPOpCode::DATA == data[0] and blocknum == data[1] then data_block = msg[4..-1] return data_block end end end end end def ack_read(blocknum, socket = @socket, timeout = @timeout) Timeout::timeout(@timeout) do # wait for ack while TRUE trace "waiting for ack: block %d" % blocknum msg, client = @socket.recvfrom(65535) trace_received(msg, client) if client[3] == @client[3] then if @client[1].nil? then # no port exists @client[1] = client[1] elsif client[1] == @client[1] # matched else # bad TID TFTPError.BadTID(@socket, client) next end data = msg.unpack "nn" if TFTPOpCode::ERROR == data[0] then raise TFTPException.new("%s (%d:%s)" % [ msg.unpack("nnZ*")[2], data[1], TFTPError::CodeToMsg(data[1]), ]) elsif TFTPOpCode::ACK == data[0] and blocknum == data[1] then return end end end end end def oack_read(blocknum, socket = @socket, timeout = @timeout) if 0 != blocknum raise Exception("bad blocknum %s" % blocknum) end Timeout::timeout(@timeout) do # wait for oack/ack while TRUE trace "waiting for oack: block %d" % blocknum msg, client = @socket.recvfrom(65535) trace "received from #{client}" trace_received(msg, client) if client[3] == @client[3] then if @client[1].nil? then # no port exists @client[1] = client[1] elsif client[1] == @client[1] # matched else # bad TID TFTPError.BadTID(@socket, client) next end data = msg.unpack "nn" if TFTPOpCode::ERROR == data[0] then raise TFTPException.new("%s (%d:%s)" % [ msg.unpack("nnZ*")[2], data[1], TFTPError::CodeToMsg(data[1]), ]) elsif TFTPOpCode::OACK == data[0] and blocknum == data[1] then data = msg.unpack("nnZ*Z*Z*Z*Z*Z*") options = Hash[*data[2..-1]] return options, nil elsif TFTPOpCode::ACK == data[0] and blocknum == data[1] then return {}, nil elsif TFTPOpCode::DATA == data[0] and ((blocknum + 1) % 65536) == data[1] then data_block = msg[4..-1] return {}, data_block end end end end end def error(errorcode, errmsg, socket = @socket, timeout = @timeout) trace "sent ERROR <code=%s, msg=%s>" % [errorcode, errmsg] socket.send( [ TFTPOpCode::ERROR, errorcode, errmsg ].pack("nnZ*"), 0, @client[3], @client[1] ) end def data_write(blocknum, data, socket = @socket, timeout = @timeout) trace "sent DATA <block=%d, size=%d>" % [blocknum, data.length] socket.send( [ TFTPOpCode::DATA, blocknum, data, ].pack("nna*"), 0, @client[3], @client[1] ) end def ack_write(blocknum, socket = @socket, timeout = @timeout) # send an ACK trace "sent ACK <block=%d>" % blocknum ack_packet = [TFTPOpCode::ACK, blocknum].pack("nn") socket.send(ack_packet, 0, @client[3], @client[1]) end def oack_write(blocknum, options = {}, socket = @socket, timeout = @timeout) # send an OACK oack_packet = "" opts = "" options.each {|k,v| oack_packet.insert(-1, [k,v].pack("Z*Z*")) opts.insert(-1, ", %s=%s" % [k,v]) } ack_packet = [TFTPOpCode::OACK, blocknum].pack("nn") + oack_packet trace "sent OACK <block=%d%s>" % [blocknum, opts] socket.send(ack_packet, 0, @client[3], @client[1]) end end class TFTPError NOT_DEFINED = 0 FILE_NOT_FOUND = 1 ACCESS_VIOLATION = 2 DISK_FULL_OR_ALLOCATION_EXCEEDED = 3 ILLEGAL_TFTP_OPERATION = 4 UNKNOWN_TRANSFER_ID = 5 FILE_ALREADY_EXISTS = 6 NO_SUCH_USER = 7 OPTION_NEGOTIATION_REFUSED = 8 def TFTPError.CodeToMsg(code) return case (code) when 0 then "Not defined, see error message (if any)." when 1 then "File not found." when 2 then "Access violation." when 3 then "Disk full or allocation exceeded." when 4 then "Illegal TFTP operation." when 5 then "Unknown transfer ID." when 6 then "File already exists." when 7 then "No such user." when 8 then "Option negotiation refused." else "No message" end end def TFTPError.GenericError(socket, code, client) TFTPImplementation.new(socket, 5, client, nil).error( code, CodeToMsg(code) ) end def TFTPError.UnknownError(socket, msg, client) TFTPImplementation.new(socket, 5, client, nil).error( NOT_DEFINED, msg.to_s.empty? ? CodeToMsg(NOT_DEFINED) : msg.to_s ) end def TFTPError.FileNotFound(socket, client) GenericError(socket, FILE_NOT_FOUND, client) end def TFTPError.AccessViolation(socket, client) GenericError(socket, ACCESS_VIOLATION, client) end def TFTPError.FileExists(socket, client) GenericError(socket, FILE_ALREADY_EXISTS, client) end def TFTPError.BadOptions(socket, client) GenericError(socket, OPTION_NEGOTIATION_REFUSED, client) end def TFTPError.BadTID(socket, client) GenericError(socket, UNKNOWN_TRANSFER_ID, client) end def TFTPError.IllegalOperation(socket, client) GenericError(socket, ILLEGAL_TFTP_OPERATION, client) end end # Handle an incoming read request. class TFTPServerRead def initialize(io, mode, client, options) @io = io @mode = mode @client = client @options = options # set some defaults @retransmit = 4 @timeout = 5 @blocksize = 512 trace "read request for [%s] from [%s:%s]" % [@io.inspect, @client[3], @client[1]] @socket = UDPSocket.new @socket.bind(0,0) @tftp = TFTPImplementation.new(@socket, @timeout, @client, nil) end def trace(msg) $LOG.debug(msg) if $LOG end def process begin blocksize = @blocksize size = @io.size blocknum = 0 retransmit = @retransmit oack_response = {} @options.each do |k,v| if not k.empty? and not v.empty? then case k.downcase when "blksize" t = v.to_i if 8 <= t and t <= 65464 then blocksize = t oack_response[k] = v else TFTPError.BadOptions(@socket, @client) raise TFTPException("invalid option value; %s: %s" % [k,v]) end when "timeout" t = v.to_i if 1 <= t and t <= 255 then timeout = t oack_response[k] = v else TFTPError.BadOptions(@socket, @client) raise TFTPException("invalid option value; %s: %s" % [k,v]) end when "tsize" if "0" == v then oack_response[k] = size.to_s else TFTPError.BadOptions(@socket, @client) raise TFTPException("invalid option value; %s: %s" % [k,v]) end end end end if not oack_response.empty? then # send an OACK while retransmit > 0 begin trace "sending an OACK" @tftp.oack_write(blocknum, oack_response) @tftp.ack_read(blocknum) # data sent, ack received break rescue Timeout::Error $LOG.warn("Got a timeout sending an OACK response to [%s:%s]" % [client[3], client[1]]) retransmit -= 1 rescue Errno::ECONNREFUSED $LOG.warn("Connection refused from client while sending an OACK response to [%s:%s]. Spoofers?" % [client[3], client[1]]) return end end end written = 0 while buf = @io.read(blocksize) blocknum = (blocknum + 1) % 65536 retransmit = @retransmit while retransmit > 0 begin # send data @tftp.data_write(blocknum, buf) @tftp.ack_read(blocknum) # data sent, ack received break rescue Timeout::Error $LOG.warn("Got a timeout sending a data block to [%s:%s]" % [client[3], client[1]]) retransmit -= 1 rescue Errno::ECONNREFUSED $LOG.warn("Connection refused from client while sending a data block to [%s:%s]. Spoofers?" % [client[3], client[1]]) return end end if 0 == retransmit then # timedout $LOG.warn("Timed out sending data to [%s:%s]" % [client[3], client[1]]) return end written += blocksize end # FIXME / WTF if 0 == size % blocksize: # send an extra @tftp.data_write((blocknum + 1) % 65536, "") end # trace "completed file read" rescue TFTPException => e trace "read: caught TFTP exception: " + e.to_s rescue Exception => e trace "read: caught exception: " + e.to_s + "\n" + e.backtrace.join("\n") TFTPError.UnknownError(@socket, e, @client) end end end # Handle an incoming write request class TFTPServerWrite def initialize(io, mode, client, options) @io = io @mode = mode @client = client @options = options # set some defaults @retransmit = 4 @timeout = 5 @blocksize = 512 trace "write request for [%s] from [%s:%s]" % [@io.inspect, @client[3], @client[1]] @socket = UDPSocket.new @socket.bind(0,0) @tftp = TFTPImplementation.new(@socket, @timeout, @client, nil) end def trace(msg) $LOG.debug(msg) if $LOG end def process begin blocksize = @blocksize size = 0 written = 0 blocknum = 0 retransmit = @retransmit oack_response = {} @options.each do |k,v| if not k.empty? and not v.empty? then case k.downcase when "blksize" t = v.to_i if 8 <= t and t <= 65464 then blocksize = t oack_response[k] = v end when "timeout" t = v.to_i if 1 <= t and t <= 255 then @tftp.timeout = t oack_response[k] = v end when "tsize" oack_response[k] = v end end end file = nil keep_writing = TRUE first = TRUE while keep_writing retransmit = @retransmit data_block = nil while retransmit > 0 begin if (not oack_response.empty?) and first then @tftp.oack_write(blocknum, oack_response) else @tftp.ack_write(blocknum) end data_block = @tftp.data_read((blocknum + 1) % 65536) # ack sent, data received break rescue Timeout::Error $LOG.warn("Got a timeout reading a data block from [%s:%s]" % [client[3], client[1]]) retransmit -= 1 rescue Errno::ECONNREFUSED $LOG.warn("Connection refused from [%s:%s] while reading data blocks. Spoofers?" % [client[3], client[1]]) return end end first = FALSE if 0 == retransmit then # timedout $LOG.warn("Timed out reading data from [%s:%s]" % [client[3], client[1]]) return end @io.write(data_block) @io.flush # block written blocknum = (blocknum + 1) % 65536 if data_block.length < blocksize then io.close keep_writing = FALSE end end # final ack @tftp.ack_write(blocknum) rescue TFTPException => e trace "write: caught TFTP exception: " + e.to_s rescue Exception => e trace "write: caught exception: " + e.to_s + "\n" + e.backtrace.join("\n") TFTPError.UnknownError(@socket, e, @client) end end end class TFTPServer def initialize(host, port, request_callback) $LOG.info("TFTP Server starting...") @host = host || '0.0.0.0' @port = port || 6969 @request_callback = request_callback @socket = UDPSocket.new @socket.bind @host, @port @tftp = TFTPImplementation.new(@socket, 5, [], request_callback) @tftp.request_callback = request_callback end def trace(msg) $LOG.debug(msg) if $LOG end def process_request(request) begin trace "processing request: " + request.to_s request.process() rescue Exception => e trace "Caught exception: %s\n%s" % [ e.message , e.backtrace ] end Thread.exit end def listen keep_looping = TRUE threads = [] while keep_looping begin request = @tftp.get_request_handler if not request.nil? then threads << Thread.new { self.process_request(request) } end rescue Interrupt threads.each {|t| if t.alive? then trace "waiting on thread: %s" % t.to_s t.join end } keep_looping = FALSE end end end end
true
d957a2ed5ab0374033af776eec50442c823e7252
Ruby
RomAnoX/appfuel
/lib/appfuel/storage/repository/expr.rb
UTF-8
2,707
3.125
3
[]
no_license
module Appfuel module Repository # Domain expressions are used mostly by the criteria to describe filter # conditions. The class represents a basic expression like "id = 6", the # problem with this expression is that "id" is relative to the domain # represented by the criteria. In order to convert that expression to a # storage expression for a db, that expression must be fully qualified in # the form of "features.feature_name.domain.id = 6" so that the mapper can # correctly map to database attributes. This class provides the necessary # interfaces to allow a criteria to qualify all of its relative expressions. # It also allows fully qualifed expressions to be used. class Expr attr_reader :feature, :domain_basename, :domain_attr, :attr_list, :op, :value def initialize(domain_attr, op, value) @attr_list = parse_domain_attr(domain_attr) @op = op.to_s.strip @value = value fail "op can not be empty" if @op.empty? fail "attr_list can not be empty" if @attr_list.empty? end def qualify_feature(feature, domain) fail "this expr is already qualified" if qualified? attr_list.unshift(domain) attr_list.unshift(feature) attr_list.unshift('features') self end def qualify_global(domain) fail "this expr is already qualified" if qualified? attr_list.unshift(domain) attr_list.unshift('global') self end def global? attr_list[0] == 'global' end def conjunction? false end def qualified? attr_list[0] == 'global' || attr_list[0] == 'features' end def feature index = global? ? 0 : 1 attr_list[index] end def domain_basename index = global? ? 1 : 2 attr_list[index] end def domain_name "#{feature}.#{domain_basename}" end def domain_attr start_range = global? ? 2 : 3 end_range = -1 attr_list.slice(start_range .. end_range).join('.') end def to_s "#{attr_list.join('.')} #{op} #{value}" end def validate_as_fully_qualified unless qualified? fail "expr (#{to_s}) is not fully qualified, mapping will not work" end true end private def parse_domain_attr(list) list = list.split('.') if list.is_a?(String) unless list.is_a?(Array) fail "Domain attribute must be a string in the form of " + "(foo.bar.id) or an array ['foo', 'bar', 'id']" end list end end end end
true
c73be37015e18a2c288fa19cd9204d4a45d732ff
Ruby
thomasbeckett/sparta_stuff
/week-8/data_parsing/json/mockaroo/lib/mockaroo.rb
UTF-8
2,464
3.09375
3
[]
no_license
require 'json' class Mockaroo attr_accessor :mockaroo def initialize json_file @mockaroo = JSON.parse(File.read(json_file)) end def get_company @mockaroo.each do |company| unless company["Company"].is_a? String return false end end return true end def get_features comp @mockaroo.each do |company| if company["Company"] == comp return company["Features"] end end return false end def get_staff key @mockaroo.each do |company| company["Staff"].each do |staff| unless staff.key? key return false end end end return true end def get_numbers @mockaroo.each do |company| company["Staff"].each do |staff| unless staff["numbers"].is_a? Hash return false end end end return true end def staff_num @mockaroo.each do |company| company["Staff"].each do |staff| unless staff["numbers"]["row"].is_a? Integer return false end end end return true end def unique_id previous = "" @mockaroo.each do |company| company["Staff"].each do |staff| if staff["numbers"]["id"] == previous return false end previous = staff["numbers"]["id"] end end return true end def get_pets @mockaroo.each do |company| company["Staff"].each do |staff| unless staff["pets"].is_a? Array return false end end end return true end def pets_age @mockaroo.each do |company| company["Staff"].each do |staff| staff["pets"].each do |pet| unless pet["age"].is_a? Integer return false end end end end return true end def pets_type @mockaroo.each do |company| company["Staff"].each do |staff| staff["pets"].each do |pet| unless pet["animal"].is_a? String return false end end end end return true end def get_name @mockaroo[1]["Staff"][1]["lastName"] end def get_job title people = [] @mockaroo.each do |company| company["Staff"].each do |staff| if staff["job"] == title people.push "#{staff["firstName"]} #{staff["lastName"]}" end end end if people.empty? return false else return people end end end
true
e9ff0448e2c8bacfc8ead2aa904f796ca3c7ef3a
Ruby
kousuke1201abe/intern-line-bot
/app/models/messaging_api_client.rb
UTF-8
1,502
2.578125
3
[]
no_license
class MessagingAPIClient < Line::Bot::Client attr_reader :request def initialize(request:, &block) super(&block) @request = request end def reply build_reply_messages if signatured? end private def signatured? validate_signature( request.body.read, request.env['HTTP_X_LINE_SIGNATURE'], ) end def build_reply_messages parse_events_from(request.body.read).each do |event| return true unless event.is_a?(Line::Bot::Event::Message) return true unless event.type == "text" if event.message['text'].split(' ', 2).first == "詠んで" event.message['text'] = WikipediaAPIClient.new(query: event.message['text'].split(' ', 2).last).search_text begin haiku = HaikuGenerator.generate(phrase: event.message['text']) reply_message( event['replyToken'], { type: 'text', text: MatsuoBasho.new(haiku).reply_message } ) rescue reply_message( event['replyToken'], { type: 'text', text: "その記事に 俳句はなかった みたいです" } ) end else haiku = HaikuGenerator.generate(phrase: event.message['text']) reply_message( event['replyToken'], { type: 'text', text: MatsuoBasho.new(haiku).reply_message } ) end end end end
true
18a696387c55a2ee0fdc7228bc56f2b3b552dd8d
Ruby
bitcoinctf/download_tv
/test/downloader_test.rb
UTF-8
5,474
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "test_helper" describe DownloadTV::Downloader do config_path = File.realdirpath("#{__dir__}/test_config") before do Dir.chdir(__dir__) create_dummy_config(config_path) unless File.exist?(config_path) end after do File.delete(config_path) if File.exist?(config_path) end describe "when creating the object" do it "should store the first argument as @offset" do DownloadTV::Downloader.new(3, path: config_path).offset.must_equal 3 DownloadTV::Downloader.new(-3, path: config_path).offset.must_equal 3 end it "should receive an integer for the offset" do ->{ DownloadTV::Downloader.new("foo") }.must_raise NoMethodError end it "can receive an optional configuration hash" do dl = DownloadTV::Downloader.new(0, auto: true, grabber: "KAT", path: config_path) dl.config[:auto].must_equal true dl.config[:grabber].must_equal "KAT" end end describe "the fix_names method" do it "should remove apostrophes, colons and parens" do shows = ["Mr. Foo S01E02", "Bar (UK) S00E22", "Let's S05E03", "Baz: The Story S05E22"] result = ["Mr. Foo S01E02", "Bar S00E22", "Lets S05E03", "Baz The Story S05E22"] dl = DownloadTV::Downloader.new(0, ignored: [], path: config_path) dl.fix_names(shows).must_equal result end it "should remove ignored shows" do shows = ["Mr. Foo S01E02", "Bar (UK) S00E22", "Ignored S20E22", "Let's S05E03"] result = ["Mr. Foo S01E02", "Bar S00E22", "Lets S05E03"] dl = DownloadTV::Downloader.new(0, ignored: ["ignored"], path: config_path) dl.fix_names(shows).must_equal result end end describe "the check_date method" do it "exits the script when up to date" do begin dl = DownloadTV::Downloader.new(0, date: Date.today, path: config_path) run_silently { dl.check_date } flunk rescue SystemExit end end it "uses the offset to adjust the date" do # Would exit with offset 0 dl = DownloadTV::Downloader.new(1, date: Date.today, path: config_path) date = dl.check_date date.must_equal (Date.today-1) dl.config[:date].must_equal Date.today end end describe "the filter_shows method" do it "removes names with 2160p in them" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link 1", ""], ["Link 2 2160p", ""], ["Link 3", ""]] res = [["Link 1", ""], ["Link 3", ""]] dl.filter_shows(links).must_equal res end it "removes names with 1080p in them" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link.1080p", ""], ["Link 2 2160p", ""], ["Link 3", ""]] res = [["Link 3", ""]] dl.filter_shows(links).must_equal res end it "removes names with 720p in them" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link 1", ""], ["Link 2 720p", ""], ["Link.720p.rip", ""]] res = [["Link 1", ""]] dl.filter_shows(links).must_equal res end it "removes names with WEB in them" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link 1 WEBRIP", ""], ["Link 2 rip", ""], ["Link.720p.rip", ""]] res = [["Link 2 rip", ""]] dl.filter_shows(links).must_equal res end it "removes names without PROPER or REPACK in them" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link 1", ""], ["Link 2 2160p", ""], ["Link 3", ""], ["Link 4 PROPER", ""], ["Link REPACK 5", ""]] res = [["Link 4 PROPER", ""], ["Link REPACK 5", ""]] dl.filter_shows(links).must_equal res end it "doesn't apply a filter if it would reject every option" do dl = DownloadTV::Downloader.new(0, path: config_path) links = [["Link 1 720p", ""], ["Link 2 2160p", ""], ["Link 720p 3", ""]] res = [["Link 1 720p", ""], ["Link 720p 3", ""]] dl.filter_shows(links).must_equal res end end describe "the get_link method" do it "returns an empty string when it can't find links" do t = Minitest::Mock.new show = "Example Show S01E01" t.expect(:get_links, [], [show]) dl = DownloadTV::Downloader.new(0, auto: true, path: config_path) dl.get_link(t, show).must_equal "" t.expect(:get_links, [], [show]) dl = DownloadTV::Downloader.new(0, auto: false, path: config_path) dl.get_link(t, show).must_equal "" end it "returns the first link when auto is set to true" do t = Minitest::Mock.new show = "Example Show S01E01" t.expect(:get_links, [["Name 1", "Link 1"], ["Name 2", "Link 2"]], [show]) dl = DownloadTV::Downloader.new(0, auto: true, path: config_path) dl.get_link(t, show).must_equal "Link 1" end end describe "the detect_os method" do it "returns xdg open for linux" do prev = RbConfig::CONFIG['host_os'] RbConfig::CONFIG['host_os'] = "linux-gnu" dl = DownloadTV::Downloader.new(0, path: config_path) dl.detect_os.must_equal "xdg-open" RbConfig::CONFIG['host_os'] = prev end it "returns open for mac" do prev = RbConfig::CONFIG['host_os'] RbConfig::CONFIG['host_os'] = "darwin15.6.0" dl = DownloadTV::Downloader.new(0, path: config_path) dl.detect_os.must_equal "open" RbConfig::CONFIG['host_os'] = prev end it "exits when it can't detect the platform" do prev = RbConfig::CONFIG['host_os'] RbConfig::CONFIG['host_os'] = "dummy" dl = DownloadTV::Downloader.new(0, path: config_path) begin run_silently { dl.detect_os.must_equal "xdg-open" } flunk rescue SystemExit end RbConfig::CONFIG['host_os'] = prev end end end
true
c84e3527faa87ee7519cd575a0e7adc9c53b2055
Ruby
cdunn2001/Yapura
/lib/yapura/data_type.rb
UTF-8
334
2.5625
3
[ "MIT" ]
permissive
module Yapura class DataType attr_accessor :id, :name, :type, :options def initialize(type) self.type = type end def []=(id, called, options = {}) self.name = called self.id = id self.options = options self end def [](id, called) self[id, called] = {} end end end
true
d33ef0028a00a6d734ad59ee3f619838b391ab50
Ruby
aconstandinou/ls-exercises
/101_109_small_problems/medium_1/1000_lights.rb
UTF-8
331
3.4375
3
[]
no_license
hash = Hash.new (1..1000).each_with_index { |k, idx| hash[k] = 1 } counter = 2 loop do break if counter == 1001 hash.each do |k, v| if k % counter == 0 if v == 1 hash[k] = 0 else hash[k] = 1 end end end counter += 1 end lights_on = hash.select { |k, v| v == 1 } puts lights_on
true
b760db9e467a4fed27c5be0e4ec9b798ec0d1df6
Ruby
derouett/Exo_Tang_Hugues
/exo_10.rb
UTF-8
120
2.875
3
[]
no_license
puts "En quelle année es-tu née ? ?" annee_de_naissance = gets.chomp.to_i date = 2017 puts date - annee_de_naissance
true
9a1eab69385ff65460c178bb7be3f8deedf23f64
Ruby
briankennedy1/mlb-event-api
/db/add_pitcher_homers.rb
UTF-8
914
2.609375
3
[ "MIT" ]
permissive
PLAYERS.each do |player| all_hits = Event.find_by_sql("SELECT events.* FROM events WHERE events.pit_id = '#{player}' AND events.event_cd = '23' ") all_hits.sort! { |x, y| [x.game_date, x.id] <=> [y.game_date, y.id] } pbar = ProgressBar.create( starting_at: 0, total: all_hits.length, format: "Current player: #{player} %a %e %P% Processed: %c from %C" ) all_hits.each do |current_event| season_group = all_hits.select do |hit| hit.game_date.year == current_event.game_date.year end game_group = all_hits.select do |hit| hit.game_id == current_event.game_id end current_event.update_columns( pitcher_career_home_run: all_hits .index(current_event) + 1, pitcher_season_home_run: season_group.index(current_event) + 1, pitcher_game_home_run: game_group.index(current_event) + 1 ) pbar.increment end end
true
f3e825adcd0c95571d449437d1ef318d2b074158
Ruby
prabhu-sunderaraman/Advent_Of_Code
/2017/Ruby/2017_day_1_part_2.rb
UTF-8
1,009
4.3125
4
[]
no_license
#http://adventofcode.com/2017/day/1 # Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of elements. # # For example: # # 1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead. # 1221 produces 0, because every comparison is between a 1 and a 2. # 123425 produces 4, because both 2s match each other, but no other digit has a match. # 123123 produces 12. # 12131415 produces 4. class Captcha_2 def calc input output = 0 input = input.to_s steps = input.length/2 for i in 0..input.length - 1 next_index = i + steps if next_index >= input.length next_index = next_index - input.length end if input[i] == input[next_index] output += input[i].to_i end end output end end
true
67fd4f77131c63cd467f214bcb1e43582070abd3
Ruby
r00takaspin/appbooster-timeserver
/src/date_calculator.rb
UTF-8
1,055
3.59375
4
[]
no_license
require 'tzinfo' # # Formatted date output depending on city name # class DateCalculator attr_reader :date attr_reader :cities attr_reader :city_times # # Useful structure for storing city name and time # class CityTime attr_reader :name attr_reader :time def initialize(name, time) @name = name @time = time end def print "#{@name}: #{self.class.format_date(time)}" end def self.format_date(date) date.strftime('%Y-%m-%d %H:%M:%S') end end def initialize(date = Time.now.utc, cities = []) @date = date @cities = cities @repository = CityRepository.new @city_times = [CityTime.new('UTC', @date)] fill_cities end def print @city_times.map(&:print).join("\n") end private def fill_cities if @cities @cities.each do |city| utc = @repository.utc_by_name(city) if utc tz = TZInfo::Timezone.get(utc) @city_times << CityTime.new(city, tz.utc_to_local(@date)) end end end end end
true
e24007ac67fe0705e93afbf63b93e55e78a3cda6
Ruby
Cfowke81/Connect-4
/lib/board.rb
UTF-8
1,680
3.625
4
[]
no_license
require 'pry' require 'colorize' require_relative './player' require_relative './piece' require_relative './board_space' class Board attr_accessor :board def initialize(num_columns, num_rows) @board = [] num_columns.times do column = [] num_rows.times do column << BoardSpace.new end @board << column end end def columns @board end # #2 how does this work in a turn? #should player represent the player name and game piece color? def drop_piece(player, col_index) # inputs: player and column # player selects column - they do not select row # piece lands in first open slot in column # by default until the first row is occupied by a player's piece that is where the piece will drop # return where the piece landed # @board[row_index][col_index].player = player empty_space = find_empty_space(col_index) if empty_space empty_space.piece = Piece.new(player) else puts "column is full" end end def find_empty_space(col_index) @board[col_index].each do |space| return space if space.empty? end false end def stalemate? @board.each do |column| column.each do |space| return true if space.occupied? end end return false end def winner? end def display printout = '' @board.each_with_index do |column, row| spots = [] column.each do |space| if space.nil? spots << '-' else spots << space end end printout << "|" + spots.join(' ') + "|" + "\n" end printout + "---------------\n" + "|| ||\n" end end
true
d4c6f7b64e6319467ba0a473f3f1292ba60816eb
Ruby
nwtnni/game-of-life
/game.rb
UTF-8
355
2.9375
3
[]
no_license
#!/usr/bin/ruby require "./game_board" require "./game_view" unless ARGV.length == 3 then puts "Usage: ruby game.rb <m> <n> <density>" Kernel.exit(-1) end m, n, density = ARGV m = m.to_i n = n.to_i density = density.to_i game = GameBoard.new(m, n, density) view = GameView.new(game) view.draw loop do sleep 0.2 game.step view.draw end
true
8622aead8049425c0dc1d446b6d2230a8b2b1f1c
Ruby
ThiagoCasao/api_cep
/app/services/comunicacao_viacep.rb
UTF-8
526
2.5625
3
[]
no_license
class ComunicacaoViacep def buscar(cep) url = "https://viacep.com.br/ws/#{cep}/json/" retorno = JSON.parse(Net::HTTP.get(URI(url))) if retorno["erro"] { erro: 'CEP não existe' } else endereco = GravacaoViacep.new(retorno).gravar { end: endereco, municipio: endereco.cidade } end rescue JSON::ParserError => exception { erro: "O CEP é inválido" } rescue SocketError => exception { erro: "Falha de rede" } rescue => exception { erro: "Ligar no suporte" } end end
true
fc3834bf1d5eccdf800cfce86f4d8d4c40986757
Ruby
jameswilliamiii/world_cup_cli
/lib/world_cup_cli.rb
UTF-8
723
2.796875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require_relative '../config/environment.rb' banner = "* World Cup CLI: Quickly check table standings and scores *" opt_parser = OptionParser.new do |opt| opt.banner = ("\n" + "*" * banner.length + "\n" + banner + "\n" + "*" * banner.length).colorize(:light_blue) opt.separator "Commands".colorize(:red) opt.separator " standings: See latest group table standings".colorize(:red) opt.separator " scores: See scores and upcoming matches".colorize(:red) opt.separator "" opt.separator "Usage example: world_cup_cli standings" end opt_parser.parse! case ARGV[0] when "standings" puts Standings.latest_updates when "scores" puts Scores.latest_updates else puts opt_parser end
true
64372bad9b531f71dc321f5db37879e709f23006
Ruby
charliecorrigan/homework
/bad_connection.rb
UTF-8
504
3.40625
3
[]
no_license
ready_to_quit = false bye = 0 puts "HELLO, THIS IS A GROCERY STORE!" until ready_to_quit do input = gets.chomp if input.empty? puts "HELLO?!" elsif input == input.downcase puts "I AM HAVING A HARD TIME HEARING YOU." elsif input == "GOODBYE!" && bye == 0 bye +=1 puts "ANYTHING ELSE I CAN HELP WITH?" elsif input == "GOODBYE!" && bye > 0 ready_to_quit = true else puts "NO, THIS IS NOT A PET STORE" end end puts "THANK YOU FOR CALLING!"
true
bb83c7b4dab1d59bc8139c0e818e7305d8f6bd1d
Ruby
fjordllc/bootcamp
/app/models/link_checker/extractor.rb
UTF-8
711
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true module LinkChecker module Extractor MARKDOWN_LINK_REGEXP = %r{\[(.*?)\]\((#{URI::DEFAULT_PARSER.make_regexp}|/.*?)\)}.freeze module_function def extract_links_from_multi(documents) documents.flat_map { |document| extract_links_from_a(document) } end def extract_links_from_a(document) document.body.scan(MARKDOWN_LINK_REGEXP).map do |title, url_or_path| title = title.strip url_or_path = url_or_path.strip url_or_path = "https://bootcamp.fjord.jp#{url_or_path}" if url_or_path.match?(%r{^/}) Link.new(title, url_or_path, document.title, "https://bootcamp.fjord.jp#{document.path}") end end end end
true
33c34d37dc01db1817e931c9561096873be704ef
Ruby
Gargantua88/char_gen
/lib/spell.rb
UTF-8
313
3.015625
3
[]
no_license
class Spell attr_reader :name, :casting_time, :components, :duration, :range, :level def initialize(name, casting_time, components, duration, range, level) @name = name @casting_time = casting_time @components = components @duration = duration @range = range @level = level end end
true
46452be561ede027acbd3f3f23727f4daf82c1f8
Ruby
netzay/diy-json-serializer-lab-v-000
/app/serializers/product_serializer.rb
UTF-8
428
2.609375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class ProductSerializer def self.serialize(product) # open brace s_prod = '{' # product data s_prod += '"id": ' + product.id.to_s + ', ' s_prod += '"name": "' + product.name + '", ' s_prod += '"price": ' + product.price.to_s + ', ' s_prod += '"inventory": ' + product.inventory.to_s + ', ' s_prod += '"description": "' + product.description + '"' # closing brace s_prod += '}' end end
true
b29acb27ae7f49d3d46ffad5936df6be21d5e198
Ruby
ndlib/sipity
/app/repositories/sipity/commands/permission_commands.rb
UTF-8
1,967
2.734375
3
[ "Apache-2.0" ]
permissive
require 'active_support/core_ext/array/wrap' module Sipity # :nodoc: module Commands # Commands related to the permission model # # TODO: Need to come up with a better way of handling this. Exposing # module functions and instance methods is a bit insane. It works, but # increases coupling. Possible solution, module provides a means for # delegation to a proper class? The design goal is to provide a way for # accessing repository services in other contexts. So the question is: # How is that different from module functions and instance methods via # mixin? Something to think about. module PermissionCommands def grant_creating_user_permission_for!(entity:, user: nil, group: nil, actor: nil) # REVIEW: Does the constant even make sense on the data structure? Or # is it more relevant here? acting_as = Models::Role::CREATING_USER actors = [user, group, actor] grant_permission_for!(entity: entity, actors: actors, acting_as: acting_as) end # @api public def grant_permission_for!(entity:, actors:, acting_as:) Array.wrap(actors).flatten.compact.each do |an_actor| grant_processing_permission_for!(entity: entity, actor: an_actor, role: acting_as) end end # @api private def grant_processing_permission_for!(entity:, actor:, role:) Services::GrantProcessingPermission.call(entity: entity, actor: actor, role: role) end # @api public def revoke_permission_for!(entity:, actors:, acting_as:) Array.wrap(actors).flatten.compact.each do |an_actor| revoke_processing_permission_for!(entity: entity, actor: an_actor, role: acting_as) end end # @api private def revoke_processing_permission_for!(entity:, actor:, role:) Services::RevokeProcessingPermission.call(entity: entity, actor: actor, role: role) end end end end
true
428b7ea00a610cf49fb865e27aad7d9f5f728412
Ruby
matos89/ruby-music-library-cli-v-000
/lib/music_importer.rb
UTF-8
460
2.953125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MusicImporter attr_accessor :path def initialize(path) @path = path end def files files = Dir.glob(@path + "/" + "*.mp3") files.collect {|file| file.gsub(@path + "/", "")} end # Why is this considered hardcoded? because i didn't use @path? # files.collect {|file| file.split("./spec/fixtures/mp3s/")[1]} # end def import files.each do |song| Song.create_from_filename(song) end end end
true
745c8dacb361ebc51c529adf144013ee2339e704
Ruby
GikuyuNderitu/dojo_ruby
/tdd_1/ruby_tdd/apple_tree/spec_appletree.rb
UTF-8
1,998
3.046875
3
[]
no_license
require_relative "appletree" RSpec.describe AppleTree do before(:each) do @a1 = AppleTree.new end it "has an age attribute with getter and setter methods" do @a1.age = 1 expect(@a1.age).to eq(1) end it "has a height attribute with only a getter method. You should raise a NoMethodError if anyone tries to set the height attribute directly" do expect(@a1.height).to eq(1.0) expect{@a1.height = 2}.to raise_error(NoMethodError) end it "has an apple count attribute with only a getter method" do expect(@a1.apple_count).to eq(0) expect{@a1.apple_count = 40}.to raise_error(NoMethodError) end it "has a year_gone_by method that functions correctly" do @a1.year_gone_by expect(@a1.age).to eq(1) expect(@a1.height).to eq(1.1) expect(@a1.apple_count).to eq(0) @a1.age = 3 @a1.year_gone_by expect(@a1.apple_count).to eq(2) end it "has method pick apples that takes all of the apples off of the tree" do @a1.age = 3 @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by expect(@a1.apple_count).to eq(8) @a1.pick_apples expect(@a1.apple_count).to eq(0) end context "Turning 4 years old" do before(:each) do @a1 = AppleTree.new @a1.age = 2 end it "can grow apples" do expect(@a1.apple_count).to eq(0) @a1.year_gone_by @a1.year_gone_by expect(@a1.apple_count).to eq(2) end end context "is under 3 years old" do before(:each) do @a1 = AppleTree.new end it "can't grow apples" do @a1.year_gone_by expect(@a1.apple_count).to eq(0) end end context "is older than 10" do before(:each) do @a1 = AppleTree.new @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by @a1.year_gone_by end it "can't grow apples because it is older than 10" do expect(@a1.apple_count).to eq(14) @a1.year_gone_by expect(@a1.apple_count).to eq(14) end end end
true
e8775155682a7dfcbefd1abb477970bd1eaa1f66
Ruby
Mr-Bowtie/Intro_to_programming
/variables/name.rb
UTF-8
189
3.71875
4
[]
no_license
puts "What's your first name?" first_name = gets.chomp puts "Last name?" last_name = gets.chomp puts "Well howdy, #{first_name} #{last_name}" 10.times do puts first_name + last_name end
true
d8debac6dfd7921ae8d42ffdd1f78296ea5b0c1b
Ruby
sg552/iteye_blog_fetcher
/fetcher.rb
UTF-8
1,576
2.640625
3
[]
no_license
# -*- encoding : utf-8 -*- require 'nokogiri' require 'httparty' class Fetcher include HTTParty BASE_URL = 'http://sg552.iteye.com' MAX_PAGE = 1 headers 'User-Agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Referer' => BASE_URL, 'Host' => 'sg552.iteye.com', 'Accept-Language' => 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4' def self.fetch your_post_urls = [] (1..MAX_PAGE).each do |index| remote_result = Fetcher.get("#{BASE_URL}?page=#{index}").body your_post_urls += self.extract_post_link remote_result end your_post_urls.each do |url| information = self.extract_post_information_from_single_page url insert_as_local_posts(information) end end private def self.insert_as_local_posts information LocalBlog.create! :body=> information[:content], :title => information[:title], :created_at => information[:created_at], :published_at => information[:created_at], :user_id => 1 end def self.extract_post_link content return Nokogiri::HTML(content).css('.blog_title h3 a').map { |a| a.attr('href') } end def self.extract_post_information_from_single_page url remote_result = Fetcher.get(url).body result = {} return { :content => Nokogiri::HTML(remote_result).css('#blog_content').to_html, :title => Nokogiri::HTML(remote_result).css('.blog_title h3 a').text, :created_at => Nokogiri::HTML(remote_result).css('.blog_bottom li')[0].text + ':00' } end end
true
e70534437511eff2687e6801c7482de9879129b3
Ruby
eduardodeoh/RubyLearning
/Week3/Exercises/progExercise7.rb
UTF-8
4,872
3.8125
4
[]
no_license
# #Exercise7. First of all, I'd like to thank Peter Cooper for allowing me to use this exercise. # #The application you're going to develop will be a text analyzer. You will be working on it this and next week. Your Ruby code will read in text supplied in a separate file, analyze it for various patterns and statistics, and print out the results for the user. It's not a 3D graphical adventure or a fancy Web site, but text processing programs are the bread and butter of systems administration and most application development. They can be vital for parsing log files and user-submitted text on Web sites, and manipulating other textual data. With this application you'll be focusing on implementing the features quickly, rather than developing an elaborate object-oriented structure, any documentation, or a testing methodology. # #Your text analyzer will provide the following basic statistics: # #Character count #Character count (excluding spaces) #Line count #Word count #Sentence count #Paragraph count #Average number of words per sentence #Average number of sentences per paragraph #In the last two cases, the statistics are easily calculated from the word count, sentence count, and paragraph count. That is, once you have the total number of words and the total number of sentences, it becomes a matter of a simple division to work out the average number of words per sentence. # #Before you start to code, the first step is to get some test data that your analyzer can process. You can find the text at: #http://rubylearning.com/data/text.txt # #Save the file in the same folder as your other Ruby programs and call it text.txt. Your application will read from text.txt by default (although you'll make it more dynamic and able to accept other sources of data later on). # #Let me outline the basic steps you need to follow: # #Load in a file containing the text or document you want to analyze. #As you load the file line by line, keep a count of how many lines there are (one of your statistics taken care of). #Put the text into a string and measure its length to get your character count. #Temporarily remove all whitespace and measure the length of the resulting string to get the character count excluding spaces. #Split on whitespace to find out how many words there are. #Split on full stops (.), '!' and '?' to find out how many sentences there are. #Split on double newlines to find out how many paragraphs there are. #Perform calculations to work out the averages. #Create a new, blank Ruby source file and save it as analyzer.rb in your Ruby folder. # # #Verify scan and split methods that yield different results linecount = 0 spacecount = 0 wordcount = 0 charcount = 0 charcountwospace = 0 paragraphcount = 1 sentencecount = 0 filestatistics = File.open('text.txt','r') #filestatistics.each_with_index do |line,index| filestatistics.each do |line| linecount += 1 charcount += line.length # charcountwospace += line.scan(/\w+/).join.length charcountwospace += line.split.join.length # charcountwospace += line.gsub(/\s+/,'').length # spacecount += line.chomp.scan(/[[:space:]]/).length # spacecount += line.chomp.scan(/ /).length # spacecount += line.count(' ') # spacecount += line.chomp.scan(/\s/).length # wordcount += line.split(/\s/).length # wordcount += line.split(/[[:space:]]/).length wordcount += line.split.length # wordcount += line.split(' ').length # wordcount += line.scan(/\w+/).length paragraphcount += 1 if line =~ /^\s$/ sentencecount += 1 if line =~ /[\.!\?]/ # puts "Linha #{linecount} = #{line.split(/ /),'\n'}" #puts "Linha #{linecount} = #{line.split(/\w+/)}" #puts "Linha #{linecount} = #{line.split(/[\.\!\?]/)}" # puts "Linha #{linecount} = #{line.split("\n\n")}" #puts "Line #{linecount} = #{line.count(' ')} spaces" # puts "Line #{linecount} = #{line.scan(/\w/).join}" # puts "Line #{linecount} = #{line.split.join}" # puts "Line #{linecount} = #{line.gsub(/\s+/,'')}" # puts "Line #{linecount} = #{line}" if line =~ /^\s$/ # puts "Line #{linecount} = #{line.chomp.split(/[\.!\?]/)}" end #charcountwospace = charcount - spacecount puts "No lines = #{linecount}" puts "No words = #{wordcount}" puts "No characters = #{charcount}" puts "No character without blank spaces = #{charcountwospace}" puts "No paragraph counts = #{paragraphcount}" puts "No sentence counts = #{sentencecount}" puts "Average number of words per setence = #{(wordcount / sentencecount).round(2)}" puts "Average number of sentences per paragraph = #{(sentencecount / paragraphcount).round(2)}" #others #https://github.com/luchmhor/rubylearning/blob/master/analyzer.rb # #http://books.google.com.br/books?id=A78bYfzYKZ4C&pg=PA88&lpg=PA88&dq=count+paragraphs+ruby&source=bl&ots=vFerkjp7EG&sig=NaSu7rPo9CHs6Zlrs7Qmm-Hsfx8&hl=pt-BR&sa=X&ei=LB9BT9XJDdLwggeB5eiJCA&ved=0CHgQ6AEwCDgK#v=onepage&q&f=false
true
1f9b078153a7efa0f7ee09b39857ad51f4724304
Ruby
lyuehh/vimwiki
/ruby.md
UTF-8
1,458
2.734375
3
[]
no_license
## Ruby ### vim `# vim: set ft=ruby:` ### rake参数 ```ruby task :test, :p1 do |t, args| puts args[:p1] end rake test["test"] # -> "test" ``` 更好的方式 `$ ver=20130101 rake test` ```ruby ver = ENV['ver'] # -> '20130101' ``` ### 更新vagrant 虚拟机中的vbox guest 版本 `gem install vagrant-vbguest` ### 多行注释 ```ruby =begin def a puts 'a' end =end ``` ### Proc.new vs Lambda in ruby ```ruby def foo f = Proc.new { return "return from foo from inside proc" } f.call # control leaves foo here return "return from foo" end def bar f = lambda { return "return from lambda" } f.call # control does not leave bar here return "return from bar" end puts foo # prints "return from foo from inside proc" puts bar # prints "return from bar" ``` ### Lazy Enumerator `(0..Float::INFINITY).lazy.map{|i| ((-1) ** i) / (2*i + 1).to_f}.take(655360).reduce(:+) * 4` ### inject ```ruby def fib(n) (0..n).inject([1,0]) { |(a,b), _| [b, a+b] }[0] end ``` [1,0] ### FileUtil ```ruby FileUtils.rm_rf '/tmp/home' FileUtils.mkdir '/tmp/home' ``` ### nokogiri ```ruby page = Nokogiri::HTML(open(PAGE_URL)) news_links = page.css("a").select{|link| link['data-category'] == "news"} news_links.each{|link| puts link['href'] } page.css('p').css("a[data-category=news]").css("strong") ``` ### gemspec辅助 `jeweler` ```ruby require 'optparse' $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib') require 'pru' ```
true
6e793d736bbb25ff4cd7d6bd0e86884c67280786
Ruby
SaturdayAM/ruby-objects-has-many-lab-dc-web-031218
/lib/author.rb
UTF-8
587
3.40625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' require_relative 'post.rb' class Author attr_accessor :name, :posts #Class vars @@post_count = 0 ALL_POSTS = [] def initialize(name = nil) #instance vars @name = name @posts = [] end #Add post object def add_post(post_obj) self.posts << post_obj post_obj.author = self post_obj end #Create and add new post with title def add_post_by_title(title) post = Post.new(title, self) self.posts << post post end def self.ALL_POSTS ALL_POSTS end def self.post_count @@post_count end def self.post_count=(v) @@post_count=v end end
true
f2f1672c169ad3b6f1802db3714d765080f2883b
Ruby
mzulli/ruby-misc
/reverse_words_mod.rb
UTF-8
199
3.3125
3
[]
no_license
def reverse_words_mod(str) word_array = str.split word_array = word_array.map do |word| if word[0] != '@' || word[0] != '#' word.reverse end end str = word_array.join(' ') return str end
true
a1587220ee7e9411287ec68e9687ad5dd82448ad
Ruby
JudeQuintana/service_monitor
/lib/service_monitor/service_control.rb
UTF-8
2,017
2.765625
3
[ "MIT" ]
permissive
module ServiceMonitor class ServiceControl attr_accessor :service_name, :service_start, :service_stop, :service_status STATUSES = [ OKAY = 'OK', RUNNING = 'RUNNING', STOPPED = 'STOPPED', DEAD = 'DEAD', FAILED = 'FAILED' ] def self.build(config) new(:service_name => config.fetch('service_name'), :service_start => ServiceStart.new(:cmd => config.fetch('start_cmd')), :service_stop => ServiceStop.new(:cmd => config.fetch('stop_cmd')), :service_status => ServiceStatus.new(:cmd => config.fetch('status_cmd')) ) end def initialize(service_name:, service_start:, service_stop:, service_status:) self.service_name = service_name self.service_start = service_start self.service_stop = service_stop self.service_status = service_status end def determine_restart! puts "[>] " + Time.now.to_s + "\n\n" status_output = status check_restart(status_output) puts "\n------------------------------" end def status puts "[+] Status for #{service_name} service\n" status_output = service_status.call puts "[+] " + status_output status_output end def start puts "[+] Starting #{service_name} service\n" start_output = service_start.call check_failure(start_output) end def stop puts "[+] Stopping #{service_name} service\n" stop_output = service_stop.call check_failure(stop_output) end def restart stop start end private def check_restart(output) match = output.match(/#{STOPPED}|#{DEAD}/i) if match puts "[+] #{service_name} needs a RESTART\n" restart end end def check_failure(output) match = output.match(/#{FAILED}/i) if match puts "\n[+] There is an issue starting/stopping #{service_name}\nPlease investigate!" exit end end end end
true
c31bb5438cb3c0cd711173aef18ee15ddab77895
Ruby
syagi/aoj
/alds1_6_C.rb
UTF-8
1,039
3.796875
4
[]
no_license
class Card attr_reader :suit, :number def initialize(suit, number) @suit = suit @number = number.to_i end def <=(other) @number <= other.number end def prints print "#{suit} #{number}\n" end def <=>(other) @number - other.number end end def quick_sort(a, p, r) if p < r q = partition(a, p, r) quick_sort(a, p, q-1) quick_sort(a, q+1, r) end end def partition(a, p, r) x = a[r] i = p-1 p.upto(r-1) do |j| if a[j] <= x i += 1 tmp = a[i] a[i] = a[j] a[j] = tmp end end tmp = a[r] a[r] = a[i+1] a[i+1] = tmp return i+1 end n = STDIN.gets.to_i inputs = STDIN.read.split("\n") cards = [] inputs.each do |input| card = input.split(" ") cards.push(Card.new(card[0],card[1])) end orig_cards = cards.dup quick_sort(cards,0,cards.length-1) if cards==orig_cards.sort print "Stable\n" else print "Not stable\n" end cards.each do |card| card.prints end
true
fb480ef9963ee9b10f559d9e663cc59dfa71990e
Ruby
shyouhei/crypt_checkpass
/lib/crypt_checkpass/sha2.rb
UTF-8
4,875
2.59375
3
[ "MIT" ]
permissive
#! /your/favourite/path/to/ruby # -*- mode: ruby; coding: utf-8; indent-tabs-mode: nil; ruby-indent-level: 2 -*- # -*- frozen_string_literal: true -*- # -*- warn_indent: true -*- # Copyright (c) 2018 Urabe, Shyouhei # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # The sha256crypt / sha512crypt by Ulrich Drepper. Default for `/etc/shadow` # of most Linux distributions. Also no security flaws are known at the moment. # # ### Newhash: # # You can use `crypto_newhash` to create a new password hash using SHA2: # # ```ruby # crypt_newhash(password, id: 'sha256', rounds: 1024) # ``` # # where: # # - `password` is the raw binary password that you want to digest. # # - `id` is either "sha256" or "sha512". # # - `rounds` is for iteration rounds. # # The generated password hash has following format. # # ### Format: # # Hash strings generated by sha256crypt is constructed like this: # # ```ruby # %r{ # (?<id> 5 ){0} # (?<rounds> rounds=[1-9]\d{3,8} ){0} # (?<salt> [A-Za-z0-9./]{,16} ){0} # (?<csum> [A-Za-z0-9./]{43} ){0} # # \A [$] \g<id> # (?: [$] \g<rounds> )? # [$] \g<salt> # [$] \g<csum> # \z # }x # ``` # # That of sha512crypt is constructed like this: # # ```ruby # %r{ # (?<id> 6 ){0} # (?<rounds> rounds=[1-9]\d{3,8} ){0} # (?<salt> [A-Za-z0-9./]{,16} ){0} # (?<csum> [A-Za-z0-9./]{86} ){0} # # \A [$] \g<id> # (?: [$] \g<rounds> )? # [$] \g<salt> # [$] \g<csum> # \z # }x # ``` # # - `id` is 5 for sha256crypt, 6 for sha512crypt. # # - `rounds` is, if present, the stretch rounds in decimal integer. Should be # in range of 1,000 to 999,999,999 inclusive. # # - `salt` and `csum` are the salt and checksum strings. Both are encoded in # base64-like strings that do not strictly follow RFC4648. The only # difference between `$5$` and `$6$` is the length of csum. # # @see https://www.akkadia.org/drepper/SHA-crypt.txt # @example # crypt_newhash 'password', id: 'sha256' # # => "$5$eWGIDuRO1LEg8sAB$Pjdxj3AVy4GnFfeOfz8Ek1Gn.vDwTFMMyNk56x/lc.4" # @example # crypt_checkpass? 'password', '$5$eWGIDuRO1LEg8sAB$Pjdxj3AVy4GnFfeOfz8Ek1Gn.vDwTFMMyNk56x/lc.4' # # => true # @example # crypt_newhash 'password', id: 'sha512' # # => "$6$oIlkXbDGlU.HktGx$L7xkRSQYLe/yCbz6hIM2JSY6EMtkr/CyvR71Bhr9VkotfEOUiwY8A0rAuSFmO1titWLA8hTKQXWl3ZX0QqokS0" # @example # crypt_checkpass? 'password', '$6$oIlkXbDGlU.HktGx$L7xkRSQYLe/yCbz6hIM2JSY6EMtkr/CyvR71Bhr9VkotfEOUiwY8A0rAuSFmO1titWLA8hTKQXWl3ZX0QqokS0' # # => true class CryptCheckpass::SHA2 < CryptCheckpass # (see CryptCheckpass.understand?) def self.understand? str md = %r{ (?<id> 5 | 6 ){0} (?<rounds> rounds=[1-9]\d{3,8} ){0} (?<salt> [A-Za-z0-9./]{,16} ){0} (?<csum> [A-Za-z0-9./]{43,86} ){0} \A [$] \g<id> (?: [$] \g<rounds> )? [$] \g<salt> [$] \g<csum> \z }x.match str return false unless md case md['id'] when '5' then return md['csum'].length == 43 when '6' then return md['csum'].length == 86 end end # (see CryptCheckpass.checkpass?) def self.checkpass? pass, hash __require return UnixCrypt.valid? pass, hash end # (see CryptCheckpass.provide?) def self.provide? id case id when 'sha256', 'sha512' then return true else return false end end # (see CryptCheckpass.newhash) # # @param pass [String] raw binary password string. # @param id [String] name of the algorithm. # @param rounds [Integer] rounds of stretching. def self.newhash pass, id: 'sha256', rounds: nil require 'unix-crypt', 'unix_crypt' case id when 'sha256' then klass = UnixCrypt::SHA256 when 'sha512' then klass = UnixCrypt::SHA512 else raise ArgumentError, 'unknown id: %p', id end return klass.build pass, nil, rounds end def self.__require require 'unix-crypt', 'unix_crypt' end private_class_method :__require end
true
05270e1411f1f1716b2b6110ed0efe2af11a2dd1
Ruby
fabcipriano/hello-ruby-test
/utils/httptest.rb
UTF-8
1,646
2.828125
3
[]
no_license
require 'rest_client' require 'pp' class MyTimer def initialize() @run = true end def repeat_every(interval) #Ctrl-C Signal.trap("INT") { stop() } Signal.trap("TERM") { stop() } while @run do start_time = Time.now yield elapsed = Time.now - start_time sleep([interval - elapsed, 0].max) end puts "MyTimer STOPPED!" end def stop() @run = false puts "Stopping MyTimer ... " end end #BEGIN puts("Calling http urls...") #puts response.body, response.code, response.message, response.headers.inspect #pp Page.get('http://www.google.com') MyTimer.new.repeat_every(60) do puts("========================================== Requisicao HTTP ==========================================") puts Time.now.strftime("%T,%L") puts "----------------- request LOGIN" response = RestClient.get('http://osmhom.network.ctbc:7003/oms/XMLAPI/login?username=oss&password=ctbc2012') sessionid = response.cookies["JSESSIONID"] puts response.code puts "session_id[#{sessionid}]" pp response.body puts "----------------- request REFRESH" response = RestClient.get('http://osmhom.network.ctbc:7003/oms/XMLAPI/worklist?xmlDocAdmin=OMSAdminSignal.Request&signal=RefreshServer&refreshItems=Workgroup', {:cookies => {:JSESSIONID => sessionid}}) puts response.code pp response.body puts "----------------- request LOGOUT" response = RestClient.get('http://osmhom.network.ctbc:7003/oms/XMLAPI/logout') puts response.code pp response.body end #END
true
699d87a87f76e2c205e2e1ea67390868b6046804
Ruby
wise-king-sullyman/chess
/lib/game.rb
UTF-8
3,408
3.4375
3
[]
no_license
# frozen_string_literal: true require_relative 'board' require_relative 'player' require_relative 'ai' require_relative 'move_validation' require_relative 'saving_and_loading' require_relative 'check_detection' # manage the game class Game include MoveValidation include SavingAndLoading include CheckDetection attr_reader :board, :players, :file_name def initialize @players = [] @board = Board.new(players) @file_name = 'chess_save.yaml' end def move_piece(piece, location) at_location = board.piece_at(location) at_location&.player&.remove_piece(at_location) piece.move(location) end def player_input_1_or_2 input = gets.chomp.to_i until input.between?(1, 2) puts 'Choice must be "1" or "2"' input = gets.chomp.to_i end input end def add_players puts 'Enter 1 for single player (against computer) or 2 for two player game' player_input_1_or_2 == 1 ? setup_single_player_game : setup_two_player_game end def setup_single_player_game puts 'Enter 1 to be the white player, 2 to be the black player' if player_input_1_or_2 == 1 white = Player.new('player 1', 'white', self) black = AI.new('player 2', 'black', self) else white = AI.new('player 1', 'white', self) black = Player.new('player 2', 'black', self) end players.push(white, black) end def setup_two_player_game white = Player.new('player 1', 'white', self) black = Player.new('player 2', 'black', self) players.push(white, black) end def play ask_to_load_game if File.exist?(file_name) add_players if players.empty? announce_winner(game_loop) end def announce_winner(winner) if winner print_winner(winner) else print_draw end end def game_loop loop do players.each do |player| ply_setup(player) return other_player(player) if player_in_checkmate?(player) return nil if player.mated? player.move clear_terminal end end end def ply_setup(player, game_board = board) save_game(player) previous_move = other_player(player).last_move print_previous_move(previous_move) unless previous_move.empty? game_board.refresh print_game_board(game_board) print_check_announcement(player.name) if player_in_check?(player) end def enemy_king_location(calling_player) enemy_player = other_player(calling_player) enemy_player.king_location end def enemy_at?(calling_player, location) enemy_player = other_player(calling_player) at_location = board.piece_at(location) at_location.respond_to?(:player) && at_location.player == enemy_player end def piece_at(location) board.piece_at(location) end def other_player(calling_player) player1 = players.first player2 = players.last player1 == calling_player ? player2 : player1 end private attr_writer :players, :board def clear_terminal system('clear') || system('cls') end def print_previous_move(move) puts "Last move: #{move.first} to #{move.last}" end def print_check_announcement(name) puts "#{name} in check" end def print_game_board(game_board) puts game_board end def print_winner(winner) puts "#{other_player(winner).name} in checkmate! #{winner.name} won!" end def print_draw puts 'Draw game' end end
true
392200d9576dd4ba2b16637f172c032db48952df
Ruby
edisonesc/Learn_To_Code_With_Ruby
/The_First_And_Last_Method.rb
UTF-8
288
3.671875
4
[]
no_license
arr = [1,2,3,4,5,6,7,8] p arr.first(1) #First 3 p arr.last (1) #last 3 p arr.first p arr.last def custom_first(arr, num = 0) p num != 0 ? arr[0, num] : arr[0] end def custom_last(arr, num = 0 ) p num != 0 ? arr[-num..-1] : arr[-1] end custom_first(arr, 3) custom_last(arr, 4)
true
ee14d93ea855359409168ebc00c7473d502ed668
Ruby
santiagoladavaz/katas-eis
/tenis/spec/marcador_spec.rb
UTF-8
3,324
2.890625
3
[]
no_license
require 'rspec' require_relative '../model/marcador' require_relative '../model/jugador' require_relative '../model/partido' describe 'Marcador' do describe 'initialize' do it 'deberia comenzar con games 0-0' do marcador = Marcador.new marcador.games.count.should eq 0 end it 'deberia comenzar con sets 0-0' do marcador = Marcador.new marcador.sets.count.should eq 0 end end end describe 'Jugador' do describe 'initialize' do it 'deberia comenzar con 0 puntos' do jugador = Jugador.new('Santi') jugador.puntos.should eq 0 end it 'deberia tener un punto si hace un tanto' do jugador = Jugador.new('Santi') jugador_dos = Jugador.new('Federer') marcador = Marcador.new partido = Partido.new(jugador, jugador_dos, marcador) jugador.sumarPunto(jugador_dos, partido) jugador.puntos.should eq 1 end it 'deberia restar un punto si el oponente tiene ventaja y hago un punto' do jugador = Jugador.new('Santi') jugador_dos = Jugador.new('Federer') marcador = Marcador.new partido = Partido.new(jugador, jugador_dos, marcador) jugador.sumarPunto(jugador_dos, partido) jugador_dos.sumarPunto(jugador, partido) jugador.sumarPunto(jugador_dos, partido) jugador_dos.sumarPunto(jugador, partido) jugador.sumarPunto(jugador_dos, partido) jugador_dos.sumarPunto(jugador, partido) jugador_dos.sumarPunto(jugador, partido) jugador.sumarPunto(jugador_dos, partido) jugador_dos.puntos.should eq 3 end it 'deberia ganar game si hago 4 puntos y los puntos deben ser 0 nuevamente' do jugador = Jugador.new('Santi') jugador_dos = Jugador.new('Federer') marcador = Marcador.new partido = Partido.new(jugador, jugador_dos, marcador) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) marcador.games.count(jugador.nombre).should eq 1 jugador.puntos.should eq 0 jugador_dos.puntos.should eq 0 end it 'deberia ganar set si gano un game y tengo otros 5 games ganados' do jugador = Jugador.new('Santi') jugador_dos = Jugador.new('Federer') marcador = Marcador.new marcador.games.insert(0,'Santi','Santi','Santi','Santi','Santi') partido = Partido.new(jugador, jugador_dos, marcador) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador_dos.sumarPunto(jugador, partido) jugador.sumarPunto(jugador_dos, partido) marcador.sets.count(jugador.nombre).should eq 1 marcador.games.count.should eq 0 jugador.puntos.should eq 0 jugador_dos.puntos.should eq 0 end it 'deberia ganar partido si gano un set y ya tengo uno ganado' do jugador = Jugador.new('Santi') jugador_dos = Jugador.new('Federer') marcador = Marcador.new marcador.games.insert(0,'Santi','Santi','Santi','Santi','Santi') marcador.sets.insert(0,'Santi','Federer') partido = Partido.new(jugador, jugador_dos, marcador) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) jugador.sumarPunto(jugador_dos, partido) marcador.sets.count(jugador.nombre).should eq 2 partido.ganador.should eq 'Santi' end end end
true
9c9639a27c1a1d61acd81a99cc9374c83a07c907
Ruby
rossenhansen/Ruby
/079_CONDITIONAL_ASSIGNMENT_operator.rb
UTF-8
718
2.953125
3
[]
no_license
<<<<<<< HEAD # y = nil # p y # y ||= 5 #IfNill: Assign the value only if the value is nil # p y # y ||= 10 #Does not assign the value 10 to y # p y greeting = "Hello" extraction = 10 #valid values (0,1,2,3,4) letter = greeting[extraction] #gets letter at position extraction letter ||="not found" #IfNill: display <<not found>> p letter ======= # y = nil # p y # y ||= 5 #IfNill: Assign the value only if the value is nil # p y # y ||= 10 #Does not assign the value 10 to y # p y greeting = "Hello" extraction = 10 #valid values (0,1,2,3,4) letter = greeting[extraction] #gets letter at position extraction letter ||="not found" #IfNill: display <<not found>> p letter >>>>>>> 7ef69471c05545b0a0cf66f70f2a2c782620f9ed
true
f3032f61db7708df6f43bcbf45fd40c7490b952e
Ruby
slavakisel/coursera-ruby-starters
/data-structures/week2/build_heap.rb
UTF-8
581
3.703125
4
[]
no_license
n = gets.to_i data = gets.split(' ').map(&:to_i) swaps = [] # The following naive implementation just sorts # the given sequence using selection sort algorithm # and saves the resulting sequence of swaps. # This turns the given array into a heap, # but in the worst case gives a quadratic number of swaps. # # TODO: replace by a more efficient implementation for i in 0...data.size for j in 0...data.size if data[i] > data[j] swaps << [i, j] data[i], data[j] = data[j], data[i] end end end puts swaps.size swaps.each do |swap| puts swap.join(' ') end
true
edefb0a07a6d92a289daef2d3c2d121a368f8245
Ruby
rleer/diamondback-ruby
/tests/parser/large_examples/test_alias.rb
UTF-8
647
2.546875
3
[ "BSD-3-Clause" ]
permissive
require 'test/unit' class TestAlias < Test::Unit::TestCase class Alias0 def foo; "foo" end end class Alias1<Alias0 alias bar foo def foo; "foo+" + super end end class Alias2<Alias1 alias baz foo undef foo end class Alias3<Alias2 def foo defined? super end def bar defined? super end def quux defined? super end end def test_alias x = Alias2.new assert_equal("foo", x.bar) assert_equal("foo+foo", x.baz) # test_check for cache assert_equal("foo+foo", x.baz) x = Alias3.new assert(!x.foo) assert(x.bar) assert(!x.quux) end end
true
b0f7cbf0a1146d5402d1e59338ba8325c01a09b4
Ruby
aspiers/mutt.pub
/bin/create-gmail-month-filters
UTF-8
1,669
2.90625
3
[]
no_license
#!/usr/bin/ruby # # Create gmail filters file for import into gmail web UI # via gmail labs 'import/export filters' feature. # # Note that importing these filters and selecting the "Apply new # filters to existing email" checkbox will cause *all* messages in an # existing discussion thread to receive the new label, which means # that monthly IMAP folders will get very fat with all the duplicates # caused by discussion threads spanning multiple months. The # duplicates can be cleaned up via an IMAP client which operates on # individual messages when it comes to labelling operations (as # opposed to the web UI which operates on entire threads). ME = File.basename($0) unless ARGV.length == 1 $stderr.puts "Usage: #{ME} year" exit 1 end require 'erb' puts <<EOHEADER <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'> <title>Mail Filters</title> <author> <name>Adam Spiers</name> <email>adam.spiers@gmail.com</email> </author> EOHEADER template = ERB.new <<EOTEMPLATE <entry> <category term='filter'></category> <title>Mail Filter</title> <apps:property name='hasTheWord' value='after:<%= start_year %>/<%= start_month %>/01 before:<%= end_year %>/<%= end_month %>/01'/> <apps:property name='label' value='<%= start_year %>-<%= start_month %>'/> </entry> EOTEMPLATE start_year = ARGV[0] (1..11).each do |month| start_month = "%02d" % month end_month = "%02d" % (month+1) end_year = start_year puts template.result(binding) end start_month = '12' end_month = '01' end_year = start_year.to_i + 1 puts template.result(binding) puts "</feed>"
true
834c78034ef4ca378412986389107f51f50ff905
Ruby
uwgnol1612/Tic-Tac-Toe
/human_player.rb
UTF-8
293
3.8125
4
[]
no_license
class HumanPlayer attr_reader :mark def initialize(mark, board) @mark = mark @board = board end def display @board.print end def get_move puts 'Please give two numbers (0-2) seperated by a space, ex. 1 2' move = gets.chomp.split(" ").map(&:to_i) end end
true
9b44040f14ce71b114b00cef2341e1b31bd3ceb2
Ruby
svenyurgensson/candy
/lib/candy/factory.rb
UTF-8
1,314
3.25
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'candy/qualified_const_get' module Candy # Utility methods that can generate new methods or classes for some of Candy's magic. module Factory # Creates a method with the same name as a provided class, in the same namespace as # that class, which delegates to a given class method of that class. (Whew. Make sense?) def self.magic_method(klass, method, params='') ns = namespace(klass) my_name = klass.name.sub(ns, '').to_sym parent = (ns == '' ? Object : qualified_const_get(ns)) if parent.class == Class unless parent.method_defined?(my_name) parent.class_eval <<-CLASS def #{my_name}(#{params}) #{klass}.#{method}(#{params.gsub(/\s?=(.+?),/,',')}) end CLASS end else # Module unless parent.public_methods.include?(my_name) parent.class_eval <<-CLASS def self.#{my_name}(#{params}) #{klass}.#{method}(#{params.gsub(/\s?=(.+?),/,',')}) end CLASS end end end private # Retrieves the 'BlahModule::BleeModule::' part of a class name, so that we # can put other things in the same namespace. def self.namespace(receiver) receiver.name[/^.*::/] || '' # Hooray for greedy matching end end end
true
bbf770a0cebad34039b7659c636880622c89e50f
Ruby
viktorrehnqvist/fifaappen
/app/models/achievements/big_wins_night_achievement.rb
UTF-8
744
2.671875
3
[]
no_license
class BigWinsNightAchievement < Achievement def self.check_conditions_for(player) # Check if achievement is already awarded before doing possibly expensive # operations to see if the achievement conditions are met. @achievement = false if player.big_score_by_night player.award(self) @achievement = true end @achievement_hash = { "HasIt" => @achievement, "type" => "fame", "name" => "BigWins", "description" => "Vinn 3 matcher med minst 5 mål på en kväll", "score" => 10, "img" => "bigwins.png"} end def self.hash_me @achievement_hash = { "HasIt" => @achievement, "type" => "fame", "name" => "BigWins", "description" => "Vinn 3 matcher med minst 5 mål på en kväll", "score" => 10, "img" => "bigwins.png"} end end
true
cd6268f2953c1b3f0a0539d04d79c13b0951dc48
Ruby
MarielJHoepelman/square_array-v-000
/square_array.rb
UTF-8
110
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) squares = Array.new array.each do |n| squares.push(n**=2) end squares end
true
2d3dfb73d8db50c959846b964b5a56aea739bb0a
Ruby
SahanaSanjeeva/TWB-Recorder
/web/lib/users.rb
UTF-8
292
2.53125
3
[ "MIT" ]
permissive
class Users attr_reader :path def initialize path @path = path end def map_uuids Dir["#{path}/users/*/metadata.json"].inject([]) do |result, file| file.gsub! %r{/metadata.json}, '' uuid = File.basename file result << yield(uuid) end end end
true
fc350ba37d53dccbd8cf3882b55e60914649cc2c
Ruby
nicoledow/programming-univbasics-4-square-array-online-web-prework
/lib/square_array.rb
UTF-8
224
3.734375
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) counter = 0 array_of_squares = [] while counter < array.length square_num = array[counter] * array[counter] array_of_squares << square_num counter += 1 end array_of_squares end
true
0aea2655cb58a83805c95ee36feb50e7540476cb
Ruby
Tsutomu19/StudyingAlgorithms
/0512.rb
UTF-8
6,857
3.546875
4
[]
no_license
# 23:30 堀越 優希 data = gets.split(" ").map(&:to_i) student_count = data[0] question_count = data[1] student_data = (1..student_count).map{gets.chomp!.split(" ").map(&:to_i)} @single_point = 100 / question_count def calc(delay,collect) score = collect * @single_point if delay >= 1 && delay <= 9 score *= 0.8 score = score.floor elsif delay >= 10 score = 0 end if score >= 0 && score <= 59 "D" elsif score >= 60 && score <= 69 "C" elsif score >= 70 && score <= 79 "B" elsif score >= 80 && score <=100 "A" end end student_data.each do |delay, correct| # 一つ一つに以下の処理 puts calc(delay,correct) end # ///この問題を解くためにはどうしたらいいか # ///問題を読み取る力 # 引き出しの数 # プログラミングの書き方 # 分解する力がないので解けない # 自分の口で説明する # 振り返る # ///コード解説 # 引数はメソッドに情報をプラスしている # メソッドを呼び出すときに引数を一緒に渡してあげると、 # メソッドの中でその引数の値を使える。 # 戻り値がある場合、呼び出した先がそのまま戻り値に置き換えられる。 # c034 # あなたは小学校一年生の先生です。今週の授業で、足し算と引き算を教えます。あなたは、足し算と引き算を用いた宿題を作る必要があり、そのためのプログラムを書くことにしました。 # 以下の手順で問題をランダム生成するプログラムはもうできているのですが、その答えを求めるプログラムはまだできていません。答えを求めるプログラムを書いてください。 # [問題生成の手順] # 1. 正しい式 a + b = c, あるいは a - b = c (a, b, c, は整数) を生成する # 2. a, b, c のうちいずれか 1 つを空欄にする # この空欄に入れるべき整数が「答え」となります。 # ここに、足し算、引き算の問題について例を一つずつ示します。 # 図の問題において、答えは、それぞれ 4, 3 となります。これらはそれぞれ入力例 1, 2 に対応しています。 # 評価ポイント # 10回のテストケースで、正答率、実行速度、メモリ消費量をはかり得点が決まります。 # より早い回答時間で提出したほうが得点が高くなります。 # 複数のテストケースで正しい出力がされるか評価(+50点) # 解答までの速さ評価(+50点) # 入力される値 # 入力は以下のフォーマットで与えられます。 # a op b = c # ・文字 a, op, b, "=" (半角等号), c がこの順に半角スペース区切りで与えられ、これらの並びが 1 つの問題を表します。 #  ・op には足し算あるいは引き算を表す記号が入ります。 #  ・a, b, c は "x" (英字小文字), "0", "1",..., "9" のうちいずれかで、"x" は空欄を表します。 # 入力値最終行の末尾に改行が1つ入ります。 # それぞれの値は文字列で標準入力から渡されます。標準入力からの値取得方法はこちらをご確認ください # 期待する出力 # 入力が表す問題の答え (空欄に入れるべき整数) を出力してください。 # 出力の末尾に改行を 1 つ入れ、余計な文字、空行を含んではいけません。 # 22:33 堀越 優希 data = gets.chomp.split(" ") a = data[0].to_i b = data[2].to_i c = data[4].to_i sign = data[1] if a = "x" && sign == "+" && b >= c p c - b elsif a = "x" && sign == "+" && c >= b p b - c elsif a = "x" && sign == "-" p b + c elsif b = "x" && sign == "+" && a >= c p a - c elsif b = "x" && sign == "+" && c >= a p c - a elsif b = "x" && sign == "-" p a + c elsif c = "x" && sign == "+" && a >= b p b + a elsif c = "x" && sign == "+" && b >= a p a + b elsif c = "x" && sign == "-" p a + b end # 22:34 竹田 つとむ input = gets.split(' ') if input[0] == "x" && input[1] == "+" p input[4].to_i - input[2].to_i elsif input[0] == "x" && input[1] == "-" p input[4].to_i - input[2].to_i elsif input[2] == "x" && input[1] == "+" p input[4].to_i - input[2].to_i elsif input[2] == "x" && input[1] == "-" p input[0].to_i - input[4].to_i elsif input[4] == "x" && input[1] == "+" p input[0].to_i + input[2].to_i elsif input[4] == "x" && input[1] == "-" p input[0].to_i - input[2].to_i end # 22:56 けんご formula = gets.chomp.split(" ") idx = formula.index("x") p case idx when 0 if formula[1] == "-" formula[4].to_i + formula[2].to_i else formula[4].to_i - formula[2].to_i end when 2 if formula[1] == "-" (formula[4].to_i - formula[0].to_i) * -1 else (formula[4].to_i + formula[0].to_i) end when 4 if formula[1] == "-" formula[0].to_i - formula[2].to_i else formula[0].to_i + formula[2].to_i end end # indexメソッドとは、最初から何番目にあるかを整数で返すメソッドのこと。 # 一つの値に対して解(例えばxなど。複数の候補の中で一致するものを)を探すような場合にはcase文をしようすると便利 # D092 lines = [] while line = gets lines << line.chomp.split(' ').map(&:to_i) end x1 = lines[0][0] y1 = lines[0][1] price1 = lines[0][2] x2 = lines[1][0] y2 = lines[1][1] price2 = lines[1][2] if price1 / (x1 * y1) < price2 / (x2 * y2) p lines[0] elsif price1 / x1 * y1 > price2 / x2 * y2 p lines[1] elsif iprice1 / x1 * y1 == price2 / x2 * y2 p "DRAW" end lines = [] while line = gets lines << line.chomp.split(' ').map(&:to_i) end x1 = lines[0][0] y1 = lines[0][1] price1 = lines[0][2] x2 = lines[1][0] y2 = lines[1][1] price2 = lines[1][2] if price1 / (x1 * y1) < price2 / (x2 * y2) puts lines[0].join(" ") elsif price1 / (x1 * y1) > price2 / (x2 * y2) puts lines[1].join(" ") elsif price1 / (x1 * y1) == price2 / (x2 * y2) p "DRAW" end # 浮動小数点の理解について # 一言で言えば、浮動小数点というのは一般の人が想像するような小数ではなく、計算で誤差が発生することを前提とした数値データのことです。 # 逆に言えば、浮動小数点を使う時は常に近似計算であることを意識し、結果の精度を考えろということでもあります。 # to_fは浮動小数点に変換 # 循環小数(じゅんかんしょうすう、recurring decimal, repeating decimal)とは、ある桁から先で同じ数字の列が無限に繰り返される小数のことである。繰り返される数字の列を循環節という
true
8c12a6bce43f81566a1ac4c1f3cf2bb4f93be75b
Ruby
wave2future/fingerpoken
/lib/fingerpoken/target.rb
UTF-8
2,048
2.96875
3
[]
no_license
require "logger" class FingerPoken::Target def initialize(config) @channel = config[:channel] @logger = Logger.new(STDERR) @logger.level = ($DEBUG ? Logger::DEBUG: Logger::WARN) end def register if @registered @logger.warn("Ignoring extra call to #{self.class.name}#register. Trace:\n#{caller[0..3].join("\n")}") return end @registered = true @logger.debug(:register => self.class.name) @channel.subscribe do |obj| request = obj[:request] callback = obj[:callback] @logger.debug(:request => request) response = case request["action"] when "mousemove_relative" mousemove_relative(request["rel_x"], request["rel_y"]) when "mousemove_absolute" mousemove_absolute(request["percent_x"], request["percent_y"]) when "move_end" move_end() when "click" click(request["button"]) when "mousedown" mousedown(request["button"]) when "mouseup" mouseup(request["button"]) when "type" type(request["string"]) when "keypress" keypress(request["key"]) else p ["Unsupported action", request] end if response.is_a?(Hash) callback.call(response) end end # @channel.subscribe end # def register # Subclasses should implement this. def mousemove_relative(x, y) @logger.info("mousemove not supported") end def mousedown(button) @logger.info("mousedown not supported") end def mouseup(button) @logger.info("mouseup not supported") end def click(button) mousedown(button) mouseup(button) end def type(string) @logger.info("typing not supported") end def keypress(key) @logger.info("keypress not supported") end def keydown(key) @logger.info("keydown not supported") end def keyup(key) @logger.info("keyup not supported") end def move_end() @logger.info("move_end not supported") end end # class FingerPoken::Target
true
793eda16e1414b516a63d81a2403b3228587c673
Ruby
charleschu/tianya-topic-text
/tianya.rb
UTF-8
3,327
2.640625
3
[]
no_license
#encoding: utf-8 require 'debugger' require 'nokogiri' require 'open-uri' time_start = Time.now #url = "http://bbs.tianya.cn/post-develop-1868959-1.shtml" class Topic attr_accessor :author_id, :text, :pages # REPLY_REGEX = /^(\r\n\t\t\t\t\t\t\t\u3000\u3000)@(.+\s(\d+\u697C)?.+)/ # REPLY_REGEX = /^(\r\n\t\t\t\t\t\t\t\u3000\u3000)@(.+\s)\d/ REPLY_REGEX=/@(.+\s)(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})|@(.+\s)(\d+\u697C\s)(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})/ CONTENT_BOX_SELECTOR = 'div.atl-item' TEXT_BOX_SELECTOR = 'div.bbs-content' def self.create(url, from_page_no=1, to_page_no) topic = Topic.new(url, from_page_no, to_page_no) topic.write_to_file end def initialize(first_page_url, from_page_no=1, to_page_no) raise "请输入网址" unless first_page_url @first_page_url = first_page_url @from_page_no = from_page_no @to_page_no = to_page_no set_pages set_author_id set_content_text end def set_pages @pages ||= [] (@from_page_no..@to_page_no).each do |no| url = @first_page_url.gsub(/(\d{1,})\.shtml$/,"#{no}.shtml") page = Page.new url puts "=======set page #{no} success" @pages << page end end def set_author_id first_content_box = ContentBox.new pages.first.content_boxes.first @author_id = first_content_box.get_author_id end def set_content_text @text ||= '' pages.each_with_index do |page, index| @text += page.get_content_text(author_id) end end def title @title ||= pages.first.html.title.gsub(/\s+/, "-") end def write_to_file File.open("#{title}.txt", 'a'){|f|f.write(text)} puts "***帖子已保存于 #{title}.txt***" end class Page attr_accessor :url, :content_boxes, :html def initialize(url) @url = url set_content_boxes end def set_content_boxes begin doc = open(url) rescue OpenURI::HTTPError => e server_error = Topic::ServerError.new e puts server_error.message raise server_error end @html = Nokogiri::HTML doc @content_boxes = html.css('div.atl-item') end def get_content_text(author_id) text = '' content_boxes.each_with_index do |content_box, index| content_box = Topic::ContentBox.new(content_box) if content_box.get_author_id == author_id box_text = content_box.text text += box_text if !content_box.is_a_reply? end end text end end class ContentBox instance_methods.each { |m| undef_method m unless m =~ /(^__|^send$|^object_id$)/ } def initialize(content_box_object) @content_box_object = content_box_object end def get_author_id @content_box_object['_host'] end def is_a_reply? !!(text =~ Topic::REPLY_REGEX) end def text @content_box_object.css(Topic::TEXT_BOX_SELECTOR).text end # set a proxy for all of the content_box_object's method def method_missing(name, *args, &block) @content_box_object.send(name, *args, &block) end end class ServerError < StandardError def initialize(open_uri_error_object) @message = open_uri_error_object.message @message = "请检查网址" if @message == "404 Not Found" super(@message) end end end
true
7ce937c26373b06a3ffe69a1e9b52020d25453c6
Ruby
kswang2400/app-academy-kwang
/week-1-day-5/knight.rb
UTF-8
1,790
3.625
4
[]
no_license
require './00_tree_node.rb' class KnightPathFinder attr_accessor :visited_positions attr_reader :start_position, :root def initialize(start_position) @start_position = start_position @visited_positions = [start_position] @root = build_move_tree end def self.valid_moves(pos) possible_moves = [] (-2..2).each do |i| if i.abs == 2 if valid_space?([pos[0] + i, pos[1] + 1]) possible_moves << [pos[0] + i, pos[1] + 1] end if valid_space?([pos[0] + i, pos[1] - 1]) possible_moves << [pos[0] + i, pos[1] - 1] end elsif i.abs == 1 if valid_space?([pos[0] + i, pos[1] + 2]) possible_moves << [pos[0] + i, pos[1] + 2] end if valid_space?([pos[0] + i, pos[1] - 2]) possible_moves << [pos[0] + i, pos[1] - 2] end end end return possible_moves end def self.valid_space?(pos) return (0..7).include?(pos[0]) && (0..7).include?(pos[1]) end def build_move_tree @move_tree = start_position root = PolyTreeNode.new(start_position) queue = [root] until queue.empty? current = queue.shift new_pos = new_move_positions(current.value) new_pos.each do |pos| position = PolyTreeNode.new(pos) position.parent = current end queue += current.children end root end def find_path(end_position) finish = root.dfs(end_position) finish.trace_path_back end def new_move_positions(pos) new_moves = self.class.valid_moves(pos) new_moves.select! { |move| !visited_positions.include?(move) } self.visited_positions += new_moves new_moves end end knight = KnightPathFinder.new([0,0]) p knight.find_path([7, 6]) p knight.find_path([6, 2])
true
73b364252bf82a2a2832fcdc00b75ba0cddc96f1
Ruby
chmodawk/Study_Ruby
/基本语法/异常处理.rb
UTF-8
1,278
3.640625
4
[]
no_license
# 当错误触发时,会有两个变量被自动赋值: # $! :最后一次发生的异常(对象) # $@ :最后一次发生异常的位置信息 # 异常对象具有方法: # class 异常种类 # message 异常信息 # backtrace 异常发生的位置信息($@与此等价) # rescue 有对应的修饰符,如下: # 如果出错,就赋值为后面的值 a = Integer("abc") rescue 0 # 可以将该错误赋值到变量里,使用如下方法 # rescue => ex (用于多个错误对象的分别捕获) begin rescue NoMethodError, NameError => e1 e1 rescue TimeoutError => e2 e2 end # 可以在方法调用时使用 def foo rescue puts "方法调用失败" ensure # 一些处理 end # 也可以在类创建时使用 # 但类创建不成功会直接引发后面的错误,所以一般不这么使用 class Foo rescue puts "类创建失败" ensure # 一些处理 end # 错误捕获顺序: # 不指定类名时一般捕获 StandardError 类及其子类的异常 # 所以自定义异常类一般先继承 StandardError # 抛出异常 # raise 异常类 信息(均可省略),全部省略会默认抛出 RuntimeError,在 rescue 中会默认抛出最后一次发生的异常 $! raise "一个错误"
true
c08323b929bda6e0effbc544314820415580c38d
Ruby
EricPMulligan/best_quotes
/sqlite_test.rb
UTF-8
699
3.015625
3
[]
no_license
require 'sqlite3' require 'rulers/sqlite_model' class MyTable < Rulers::Model::SQLite def method_missing(name, *args, &block) method = name.to_s if self.class.schema.has_key?(method) self.class.instance_eval do define_method(method) { @hash[method] } end self.send(method) end end end STDERR.puts MyTable.schema.inspect # Create row mt = MyTable.create 'title' => 'I saw it again!', 'posted' => 1, 'body' => 'What?' mt['title'] = 'I really did!' mt.save! mt2 = MyTable.find mt.id puts "Title: #{mt2.title}" puts "Count: #{MyTable.count}" top_id = mt.id.to_i (1..top_id).each do |id| mt_id = MyTable.find(id) puts "Found title #{mt_id.title}." end
true
29d4cfb21b60edf4cfea981ef643954f885a3f44
Ruby
skroutz/string_metric
/benchmarks/dictionary.rb
UTF-8
1,194
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'string_metric' require 'benchmark' require 'pp' Benchmark.bmbm(7) do |x| options = {} max_distance = 2 dict = [] trie = StringMetric::Levenshtein::TrieNode.new File.open('/usr/share/dict/words', 'r').each_line do |line| word = line.chomp trie.insert(word) dict << word end randomWords = [] File.open('spec/fixtures/dictionary_input.txt', 'r').each_line do |word| randomWords << word.chomp end matrixResults = [] x.report("two_matrix_rows_v2 implementation") do randomWords.each do |from| dict.each do |to| matrixResults << to if StringMetric::Levenshtein::IterativeWithTwoMatrixRowsOptimized.distance(from, to, options) <= max_distance end end end trieResults = [] x.report("trie_radix_tree implementation") do randomWords.each do |from| trieResults << StringMetric::Levenshtein::TrieRadixTree.distance(from, trie, max_distance: max_distance) end end trieResultsExt = [] x.report("trie_radix_tree_ext implementation") do randomWords.each do |from| trieResultsExt << StringMetric::Levenshtein::TrieRadixTreeExt.distance(from, trie, max_distance: max_distance) end end end
true
413978bacbd7dfcdeba76b4434f2b113378cb6c7
Ruby
bangms92/whois-store
/app/models/domain.rb
UTF-8
383
2.5625
3
[]
no_license
require 'whois' class Domain < ApplicationRecord validates_format_of :name, :with => /\A(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$\Z/ def populate name = self.name record = Whois.whois(name) self.whois_response = record end end
true
2e56fd7e85b45430ef51f14e541c39a8bce90385
Ruby
Kirill-lesnikh/CucumberLearn
/features/pages/my_content.rb
UTF-8
1,681
2.609375
3
[]
no_license
require_relative 'video_list_channels' class MyContent < VideoListChannels # Elements def btn_edit_properties browser.element(xpath:"//ul[contains(@class, 'allego-index-menu')]//span[contains(., 'Edit properties')]/..") end def btn_make_a_copy browser.element(xpath:"//ul[contains(@class, 'allego-index-menu')]//span[contains(., 'Make a copy')]/..") end def btn_list_in browser.element(xpath:"//ul[contains(@class, 'allego-index-menu')]//span[contains(., 'List in')]/..") end def created_video browser.element(xpath:"//span[@class='item-title' and contains(., '#{ENV['VIDEO_NAME']}')]/..") end def video_by_id browser.element(xpath:"//div[@data-id='#{@video_id}']") end # Methods def get_video_id(video = created_video) video.attribute_value('data-id') end def copy_video @video_id = get_video_id created_video.click btn_make_a_copy.click # TODO do i need this sleep? sleep 1 browser.refresh end # TODO - refactor this godzilla. Change method i use to choose copied video def choose_rename_and_make_a_copy copy_video browser.wait_until{browser.elements(xpath:"//span[@class='item-title' and contains(., '#{ENV['VIDEO_NAME']}')]/..").size > 1} elements = browser.elements(xpath:"//span[@class='item-title' and contains(., '#{ENV['VIDEO_NAME']}')]/..") for i in elements.to_a if get_video_id(i) != @video_id @video_id = get_video_id(i) i.click btn_edit_properties.click set_description('copy ') set_title('copy ') share_channels choose_channel_to_share share break end end end end
true
e73ce26bffc31c075c1dcf8a1ce0d77cc698ce48
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/gigasecond/a0a5707ed02d4231a2569e2320b7d9c3.rb
UTF-8
248
3.265625
3
[]
no_license
class Gigasecond def initialize(date) @date = date end def date Time.at(anniversary_in_seconds).to_date end private def anniversary_in_seconds seconds + 1_000_000_000 end def seconds @date.to_time.to_i end end
true
fda872d9a37e3f9d6a155663a2413cae6397fdae
Ruby
emmiehayes/little-shop-redux
/spec/models/merchant_spec.rb
UTF-8
5,049
2.625
3
[]
no_license
RSpec.describe Merchant do describe "Validations" do it "should have a name" do merchant = Merchant.new(name: nil) expect(merchant).to_not be_valid end end describe "Instance Methods" do it ".total_merchant_items" do merchant_1 = Merchant.create(name: "Dogs4Life") merchant_2 = Merchant.create(name: "Cats, wow") item_1 = Item.create( title: 'dog bed', description: 'a bed for dogs', price: 700, image: 'image url', merchant_id: merchant_1.id ) item_2 = Item.create( title: 'cat bed', description: 'a bed for cats', price: 500, image: 'image url', merchant_id: merchant_2.id ) item_3= Item.create( title: 'dog bone', description: 'a bone for dogs', price: 20, image: 'image url', merchant_id: merchant_1.id ) expect(merchant_1.total_merchant_items).to eq(2) expect(merchant_2.total_merchant_items).to eq(1) end it ".average_item_price" do merchant_1 = Merchant.create(name: "Dogs4Life") item_1 = Item.create( title: 'dog bed', description: 'a bed for dogs', price: 3, image: 'image url', merchant_id: merchant_1.id ) item_3= Item.create( title: 'dog bone', description: 'a bone for dogs', price: 1, image: 'image url', merchant_id: merchant_1.id ) expect(merchant_1.average_item_price).to eq(2) end it ".total_price_all_items" do merchant_1 = Merchant.create(name: "Dogs4Life") item_1 = Item.create( title: 'dog bed', description: 'a bed for dogs', price: 700, image: 'image url', merchant_id: merchant_1.id ) item_3= Item.create( title: 'dog bone', description: 'a bone for dogs', price: 20, image: 'image url', merchant_id: merchant_1.id ) expect(merchant_1.total_price_all_items).to eq(720) end end describe "Class Methods" do it ".most_items" do merchant_1 = Merchant.create(name: "Dogs4Life") merchant_2 = Merchant.create(name: "Cats, wow") item_1 = Item.create( title: 'dog bed', description: 'a bed for dogs', price: 700, image: 'image url', merchant_id: merchant_1.id ) item_2 = Item.create( title: 'cat bed', description: 'a bed for cats', price: 500, image: 'image url', merchant_id: merchant_2.id ) item_3= Item.create( title: 'dog bone', description: 'a bone for dogs', price: 20, image: 'image url', merchant_id: merchant_1.id ) expect(Merchant.most_items).to eq(merchant_1) end it ".highest_priced_item" do merchant_1 = Merchant.create(name: "Dogs4Life") merchant_2 = Merchant.create(name: "Cats, wow") item_1 = Item.create( title: 'dog bed', description: 'a bed for dogs', price: 700, image: 'image url', merchant_id: merchant_1.id ) item_2 = Item.create( title: 'cat bed', description: 'a bed for cats', price: 500, image: 'image url', merchant_id: merchant_2.id ) item_3= Item.create( title: 'dog bone', description: 'a bone for dogs', price: 20, image: 'image url', merchant_id: merchant_1.id ) expect(Merchant.highest_priced_item).to eq(merchant_1) end end end
true
d9404c89961892bf422473ea087457e0fdee802c
Ruby
manavt/Bunny
/lib/import.rb
UTF-8
453
2.53125
3
[]
no_license
class Import def self.import_from_link r = RestClient.get ("http://localhost:4000/products/download_in_json.json") data = JSON.load(r.body) data.each do | each_record | each_record.delete_if {|key, _| key == "id"} if p = Product.create!(each_record) Rails.logger.info "Successfully saved the object #{p}" else Rails.logger.debug "Something went wrong with object #{p.errors}" end end end end
true
e7b10b5f3c6e02419f2ff0c9a0d18aac2f0496f5
Ruby
HirokiTachiyama/jack-of-all-trades
/functions/todo.rb
UTF-8
835
3.078125
3
[]
no_license
# coding: utf-8 =begin *** *** File name: todo.rb *** Create: 2016, 11/2(Wed) 00:54 *** Author: Hiroki Tachiyama *** * DO NOT USE CYGWIN TERMINAL !! to operate mysql and ruby gem while development. * -> To operate mysql, use MySQL Workbench or of MySQL's terminal. * -> To operate ruby gem, use Ruby's terminal. * Because of imperfection in setting of environment variables. * =end require_relative "super_function" class Todo < super_function def main_loop while print "joat ? Todo : " or input = STDIN.gets #exit or quit, both of uppercase letter and lower letter break if input.chomp! =~ /exit|quit/i case input when /help/i then puts "HELP" when /todo/i then Todo.new.main_loop else puts "ELSE" end # - case end puts "end Todo" end end
true
903e0efbe6f2ba8039a4c6e74627550d9bbd1d62
Ruby
bstiber/launch_school_exercises
/small_problems_2nd_round/ruby_basics/loops2/4.rb
UTF-8
672
4.71875
5
[]
no_license
# Get the Sum. The code below asks the user "What does 2 + 2 equal?" and uses #gets to retrieve # the user's answer. Modify the code so "That's correct!" is printed and the loop stops when # the user's answer equals 4. Print "Wrong answer. Try again!" if the user's answer doesn't # equal 4. # input # - 'user answer', and integer # # output # - number # # rules # - break the loop when user input == 4 # - print "thats correct" when user output is correct, == 4 # - print "wrong answer, try again" if answer == wrong loop do puts 'What does 2 + 2 equal?' answer = gets.chomp.to_i break puts "That's correct!" if answer == 4 puts "Wrong answer, try again!" end
true
8b6a6bcc86ba489193ce2c70b418b9932e8ebb03
Ruby
brundage/odifferous
/old_stuff/bin/processYtube.rb
UTF-8
841
2.78125
3
[]
no_license
#!/usr/bin/ruby require 'csv' require 'pp' require 'y_tube_fly' if ARGV[0].nil? p "Need ARGV[0]" exit 2 else infilename = ARGV[0] end today = Time.now.strftime("%Y-%m-%d") outfilename = ARGV[1].nil? ? "#{File.basename(infilename)}-output-#{today}.csv" : ARGV[1] infile = File.open( infilename, "rb" ) outfile = File.open( outfilename, "wb" ) line = 1 CSV::Writer.generate(outfile) do |csv_out| csv_out << YTubeFly.headers begin CSV::Reader.parse( infile ) do |row| date = row.shift gender = row.shift number = row.shift fly = YTubeFly.new( "data" => row, "date" => date, "gender" => gender, "number" => number ) csv_out << fly.dump line += 1 end rescue RuntimeError => err p "Error on line #{line}: #{err}" end end outfile.close; infile.close
true