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
e2211ebec16bf33506232b5f87247ae80b12fb70
Ruby
aaronwtan/RB101
/small_problems/easy2/q8.rb
UTF-8
1,520
4.6875
5
[]
no_license
# Sum or Product of Consecutive Integers # Write a program that asks the user to enter an integer greater than 0, # then asks if the user wants to determine the sum or product # of all numbers between 1 and the entered integer. # Examples: # >> Please enter an integer greater than 0: # 5 # >> Enter 's' to compute the sum, 'p' to compute the product. # s # The sum of the integers between 1 and 5 is 15. # >> Please enter an integer greater than 0: # 6 # >> Enter 's' to compute the sum, 'p' to compute the product. # p # The product of the integers between 1 and 6 is 720. ABBREVIATION_TO_OPERATION = {'s' => 'sum', 'p' => 'product'} OPERATION_TO_SYMBOL = { 'sum' => :+, 'product' => :* } def prompt(message) puts ">> #{message}" end def get_positive_integer prompt("Please enter an integer greater than 0:") loop do integer = gets.to_i return integer if integer > 0 prompt("Invalid input. Please enter an integer greater than 0.") end end def get_operation prompt("Enter 's' to compute the sum, 'p' to compute the product.") loop do operation = gets.chomp.downcase return operation if %w(s p).include?(operation) prompt("Invalid input. Please enter 's' or 'p'.") end end def calculate_operation(max, operation) (1..max).inject(&OPERATION_TO_SYMBOL[operation]) end max = get_positive_integer operation = ABBREVIATION_TO_OPERATION[get_operation] total = calculate_operation(max, operation) puts "The #{operation} of the integers between 1 and #{max} is #{total}."
true
11e4a67576cf1b2e51675b2549a914b83d7f904f
Ruby
IrakliZ/webboard
/app/helpers/sessions_helper.rb
UTF-8
1,173
3.09375
3
[ "MIT" ]
permissive
## # Class for making user validation easier module SessionsHelper ## # Helper function for signing in an user, creating a cookie on the browser, so that when an user leaves # without logging off and returns, they will still be logged in. def sign_in(user) user_token = User.new_user_token cookies.permanent[:user_token] = user_token user.update_attribute(:user_token, User.encrypt(user_token)) self.current_user = user end ## # Helper function for signing out an user and deleting the cookie stored for signed in users def sign_out self.current_user = nil cookies.delete(:user_token) end ## # Helper function for setting the current user to a certain user def current_user=(user) @current_user = user end ## # Helper function for getting the current logged in user def current_user user_token = User.encrypt(cookies[:user_token]) @current_user ||= User.find_by(user_token: user_token) end ## # Helper functionn for checking if an user is currently logged in def current_user?(user) user == current_user end ## # Helper function for checking if somebody is logged in def signed_in? !current_user.nil? end end
true
014b7f2936e2cc3f08c95500f5829dc59e389996
Ruby
AJ8GH/ruby-udemy
/hashes/each_key_and_each_value_methods.rb
UTF-8
470
3.734375
4
[]
no_license
salaries = {director: 100_000, producer: 200_000, ceo: 3_000_000, assistant: 200_000} salaries.each_key {|position| puts "Employee Record: -----" puts "#{position}"} salaries.each_value {|salary| puts "The next employee earns #{salary}"} # exercise def key_arr(hash) keys = [] hash.each {|k,v| keys << k} keys end p key_arr(salaries) def value_arr(hash) values = [] hash.each {|k,v| values << v} values.uniq end p value_arr(salaries)
true
1f4ae5f5c0f6e5e31405c3d1c7778a59ee76c140
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/800/feature_try/method_source/23898.rb
UTF-8
272
3.265625
3
[]
no_license
def combine_anagrams(words) hash = Hash.new words.each do |word| key = word.downcase.split("").sort.join hash[key] = Array.new if (hash[key] == nil) array = hash[key] array.push(word) hash[key] = array array = nil end return hash.values end
true
1e3fdb52acfbd3b8a4e93cd6ab81eebf74b26e89
Ruby
diegoa314/artdaq_lme
/artdaq_dune/tools/RunDriver.rb
UTF-8
5,047
2.859375
3
[]
no_license
#!/usr/bin/env ruby # JCF, 2-11-14 # This script is meant to provide a very simple example of how one # might control an artdaq-based program from the command line. The # idea is that this script uses its command line arguments to generate # a FHiCL document which in turn is passed to the artdaq-demo's # "driver" program for processing. # DemoControl.rb, the main script used to run the full teststand # simulation, operates off of essentially the same principle -- i.e., # use command line arguments to configure a FHiCL script which is in # turn sent to executables for configuration and processing # Here, we simply create a FHiCL script designed to run the new # "ToyDump" module so as to print ADC values from fragments of type # TOY1 or TOY2 to screen (see the artdaq-demo/Overlays/ToyFragment.hh # file for more, and/or look at the online Wiki, # cdcvs.fnal.gov/redmine/projects/artdaq-demo/wiki require File.join( File.dirname(__FILE__), 'generateToy' ) require File.join( File.dirname(__FILE__), 'generateNormal' ) require File.join( File.dirname(__FILE__), 'generatePattern' ) # A common way to de-facto forward declare functions in Ruby (as is # the case here with generateToy) is to bundle the main program flow # into a function (here called "main" in honor of C/C++) and call the # function at the end of the file def main # More sophisticated programs also use the "OptionParser" class for # command line processing if ! ARGV.length.between?(2,4) puts "Usage: " + __FILE__.split("/")[-1] + " <fragment type = TOY1, TOY2> " + " <# of events> <generator = Uniform, Normal, Pattern> (nADCcounts) (saveFHiCL)" exit 1 end fragtype = ARGV[0] nEvents = ARGV[1] generator = ARGV[2] # We'll pass "nADCcounts" to the generateToy function. If nADCcounts # is "nil", generateToy will search for a FHiCL file called # "ToySimulator.fcl" for the definition of nADCcounts if ARGV.length >= 4 if (ARGV[3] != "0" && ARGV[3] != "false" && ARGV[3] != "nil") saveFHiCL = true end else saveFHiCL = false end if ARGV.length >= 5 nADCcounts = ARGV[4] else nADCcounts = nil end if fragtype == "TOY1" || fragtype == "TOY2" # From generateToy.rb : # def generateToy(startingFragmentId, boardId, # fragmentType, throttleUsecs, nADCcounts = nil) case generator when "Uniform" generatorCode = generateToy(0, 0, fragtype, 0, nADCcounts) when "Normal" generatorCode = generateNormal(0, 0, fragtype, 0, nADCcounts) when "Pattern" generatorCode = generatePattern(0, 0, fragtype, 0, nADCcounts) else puts "Invalid Generator Type Supplied!" exit end else raise "Unknown fragment type \"%s\" passed to the script" % [ fragtype ] end driverCode = generateDriver( generatorCode, nEvents) # Backticks can be used to make system calls in Ruby. Here, we # create a unique filename, and strip the trailing newline returned # by the shell filename = `uuidgen`.strip # Now dump the driver's FHiCL code to the new file handle = File.open( filename, "w") handle.write( driverCode ) handle.close # And now we call the "driver" program with the temporary FHiCL file # Note that since the backticks return stdout, we just stick the # call in front of a "puts" command to see the driver's output cmd = "demo_driver -c " + filename puts `#{cmd}` # Either remove or save the FHiCL file if saveFHiCL cmd = "mv " + filename + " renameme.fcl" else cmd = "rm -f " + filename end `#{cmd}` end def generateDriver(generatorCode, eventsToGenerate) driverConfig = String.new( "\ events_to_generate: %{events_to_generate} run_number: 101 fragment_receiver: { %{generator_code} } event_builder: { expected_fragments_per_event: 1 use_art: true print_event_store_stats: false verbose: false events_expected_in_SimpleQueueReader: @local::events_to_generate } ###################################################################### # The ART code ###################################################################### physics: { analyzers: { toyDump: { module_type: ToyDump raw_data_label: daq frag_type: @local::fragment_receiver.fragment_type num_adcs_to_show: 10 # Obviously this should be no more than ADC counts per fragment } } a1: [ toyDump ] # e1: [ out1 ] end_paths: [ a1 ] } outputs: { out1: { module_type: FileDumperOutput wantProductFriendlyClassName: true } } source: { module_type: DemoInput waiting_time: 900 resume_after_timeout: true } process_name: Driver " ) # Only two values are subbed in, although one of them is an entire # chunk of FHiCL code used to configure the fragment generator driverConfig.gsub!(/\%\{generator_code\}/, generatorCode) driverConfig.gsub!(/\%\{events_to_generate\}/, eventsToGenerate) return driverConfig end main
true
522e75101f729e6c2854833886eb021ab6651325
Ruby
uohull/hull-history-centre
/lib/import/ead/piece.rb
UTF-8
834
2.5625
3
[]
no_license
require_relative 'item' module Ead class Piece < Item class << self def root_xpath 'c[@otherlevel = "Piece"]' end # The xpath to the parent Item that the Piece belongs to # (relative path from the Piece node) def item_xpath "ancestor::#{Ead::Item.root_xpath}[1]" end # Map the name of the field to its xpath within the EAD xml def fields_map super.merge({ item_id: "#{item_xpath}/#{Ead::Item.fields_map[:id]}", item_title: "#{item_xpath}/#{Ead::Item.fields_map[:title]}", }) end def to_solr(attributes) super.merge({ 'type_ssi' => 'piece', 'item_id_ssi' => format_id(attributes[:item_id]), 'item_title_ss' => attributes[:item_title] }) end end end end
true
a85a84beab387ad351ddb692898d96fc8a874f1a
Ruby
dmullek/dominion
/app/cards/forge.rb
UTF-8
1,827
2.734375
3
[]
no_license
class Forge < Card def starting_count(game) 10 end def cost(game, turn) { coin: 7 } end def type [:action] end def play(game, clone=false) @play_thread = Thread.new { ActiveRecord::Base.connection_pool.with_connection do action = TurnActionHandler.send_choose_cards_prompt(game, game.current_player, game.current_player.hand, 'Choose any number of cards to trash:', 0, 0, 'trash') TurnActionHandler.process_player_response(game, game.current_player, action, self) end } end def process_action(game, game_player, action) if action.action == 'trash' trashed_cards = PlayerCard.where(id: action.response.split) trashed_cost = trashed_cards.map{ |c| c.calculated_cost(game, game.current_turn)[:coin] }.inject(0, :+) CardTrasher.new(game_player, trashed_cards).trash('hand') ActiveRecord::Base.connection.clear_query_cache TurnActionHandler.refresh_game_area(game, game_player.player) gain_card(game, game_player, trashed_cost) elsif action.action == 'gain' card = GameCard.find(action.response) CardGainer.new(game, game_player, card.name).gain_card('discard') end end def gain_card(game, game_player, trashed_cost) available_cards = game.cards_equal_to({coin: trashed_cost, potion: 0}) if available_cards.count == 0 LogUpdater.new(game).custom_message(nil, 'But there are no available cards to gain') elsif available_cards.count == 1 CardGainer.new(game, game_player, available_cards.first.name).gain_card('discard') else action = TurnActionHandler.send_choose_cards_prompt(game, game_player, available_cards, 'Choose a card to gain:', 1, 1, 'gain') TurnActionHandler.process_player_response(game, game_player, action, self) end end end
true
add6f98c2d9a40d77240c698ab4198a61e98042a
Ruby
LafayetteCollegeLibraries/webvtt-converter
/lib/webvtt/cue.rb
UTF-8
3,699
3.140625
3
[]
no_license
# frozen_string_literal: true module WebVTT # Small wrapper class for captions. When a caption has a speaker, their name # is put into a +<v>+ tag to identify them. class Caption attr_reader :speaker, :text # @param [Hash] options # @option [String] speaker # @option [String] text def initialize(speaker: nil, text: nil) @speaker = speaker @text = text end # @return [true, false] def speaker? !speaker.nil? && speaker != '' end # @return [String] def to_string return unless text return text unless speaker? "<v #{speaker}>#{text}</v>" end alias to_s to_string end # Teeniest class to wrap comments class Comment def initialize(text) @text = text end def to_string return if @text.nil? || @text == '' "NOTE\n#{@text}" end alias to_s to_string end # Wrapper class to normalize cue-settings class CueSettings def initialize(settings = {}) @settings = settings end def empty? @settings.nil? || @settings.empty? end def to_string return '' if empty? @settings.keep_if { |key, _val| valid_keys.include?(key.to_sym) } .map { |key, val| "#{key}:#{val}" } .join(' ') end alias to_s to_string private def valid_keys %i[vertical line position size align region] end end # Main class for VTT cue objects # # @example # cue = Cue.new(start_time: '00:00:01', # end_time: '00:00:02', # captions: [WebVTT::Caption.new(text: 'Hello!', speaker: 'Narrator')]) # cue.to_s # # => "00:00:01.000 --> 00:00:02.000\n<v Narrator>Hello!</v>" class Cue attr_reader :start_time, :end_time, :speaker, :identifier attr_accessor :captions, :settings # @param [Hash] options # @option [String] start_time # @option [String] end_time # @option [String] identifier # @option [Array<WebVTT::Caption>] captions # @option [Hash, CueSettings] settings def initialize(start_time:, end_time:, identifier: nil, captions: [], settings: {}) @start_time = start_time @end_time = end_time @identifier = identifier @captions = captions @settings = settings.is_a?(CueSettings) ? settings : CueSettings.new(settings) @speaker = speaker end # Used for sorting, converts +start_time+ to seconds # # @return [Float] def start_time_seconds @start_time_seconds ||= timestamp_to_seconds(start_time) end # Used for sorting, converts +end_time+ to seconds # # @return [Float] def end_time_seconds @end_time_seconds ||= timestamp_to_seconds(end_time) end # @return [String] def to_string [identifier, timestamp_and_settings, annotated_captions].compact.join("\n") end alias to_s to_string private # In instances where we have multiple captions, we'll display each # on a new-line with a hyphen prefix # # @return [String] def annotated_captions return captions.first.to_s unless captions.size > 1 captions.map { |caption| "- #{caption}" }.join("\n") end # @return [String] def timestamp "#{start_time} --> #{end_time}" end # timestamp and settings concatted. # # @return [String] def timestamp_and_settings return timestamp if settings.empty? "#{timestamp} #{settings}" end def timestamp_to_seconds(timestamp) hours, minutes, seconds = timestamp.split(':').map { |val| val&.to_f } ((hours || 0) * 3600.0) + ((minutes || 0) * 60.0) + (seconds || 0.0) end end end
true
2d9ccd52ea50be81f61dd268bd22772e4ef9e34a
Ruby
UjwalBattar/leet-code
/ruby/plus_one.rb
UTF-8
718
4.09375
4
[]
no_license
# Given a non-empty array of digits representing a non-negative # integer, plus one to the integer. # # The digits are stored such that the most significant digit is at # the head of the list, and each element in the array contain a # single digit. # # You may assume the integer does not contain any leading zero, except # the number 0 itself. # # Example 1: # # Input: [1,2,3] # Output: [1,2,4] # Explanation: The array represents the integer 123. # Example 2: # # Input: [4,3,2,1] # Output: [4,3,2,2] # Explanation: The array represents the integer 4321. # @param {Integer[]} digits # @return {Integer[]} def plus_one(digits) return [1] if digits.empty? (digits.join.to_i + 1).to_s.chars.map {|i| i.to_i} end
true
df9f34ff369043b070fefadf2d8a61f4ead5041e
Ruby
tekt8tket2/primary_interview
/album.rb
UTF-8
364
3.34375
3
[]
no_license
class Album attr_reader :played, :artist def initialize(title, artist) @title = title @artist = artist @played = false end def play @played = true end def listing_string "\"#{@title}\" by #{@artist} (#{played_string})" end private def played_string if @played 'played' else 'unplayed' end end end
true
8dddbe7708b0fb783edc99471e66a8b2797e05bd
Ruby
jschanker/ruby-text2code-old
/variables.rb
UTF-8
6,319
3.203125
3
[]
no_license
require './instruction.rb' class Variables def self.set(inst) # arg[0] = var name, arg[1] = "to", arg[2] = value instance_variable_set "@#{inst.variable}", inst.values[0] self.send(:attr_accessor, "#{inst.variable}") return instance_variable_get "@#{inst.variable}" #MutableNum.send(:set, args) end def self.method_missing(name, *args) # assume method name was variable if(args[0] and args[0].class == Instruction) then args[0].variable = name if(args[0].action == "divisible") then variable = instance_variable_get "@#{name}" return variable.divisible_by?(args[0].values[0]) elsif(args[0].action == "even") then variable = instance_variable_get "@#{name}" return variable.even? elsif(args[0].action == "odd") then variable = instance_variable_get "@#{name}" return variable.odd? elsif(args[0].action == "positive") then variable = instance_variable_get "@#{name}" return variable.positive? elsif(args[0].action == "negative") then variable = instance_variable_get "@#{name}" return variable.negative? elsif(args[0].action == "prime") then variable = instance_variable_get "@#{name}" return variable.prime? elsif(args[0].action == "whole") then variable = instance_variable_get "@#{name}" return variable.whole? #elsif(args[0].action == "root") then # variable = instance_variable_get "@#{name}" # return variable.sqrt end return args[0] elsif args[0] #puts args[0].class return args[0] else begin return instance_variable_get "@#{name}" rescue "Error: Unrecoverable error" end end end def self.to(val) if(val.class != Instruction) then return Instruction.new(val) else return val end end def self.by(val) Instruction.new(val) end def self.is(inst) inst end def self.of(val) if(val.class == Instruction) then return val else return Instruction.new(val) end end def self.increase(inst) variable = instance_variable_get "@#{inst.variable}" variable.send(:increase, inst.values[0]) end def self.decrease(inst) variable = instance_variable_get "@#{inst.variable}" variable.send(:decrease, inst.values[0]) end def self.multiply(inst) variable = instance_variable_get "@#{inst.variable}" variable.send(:multiply, inst.values[0]) end def self.divide(inst) variable = instance_variable_get "@#{inst.variable}" variable.send(:divide, inst.values[0]) end def self.divided(inst) if(inst.class != Instruction) then inst = Instruction.new(inst) end inst.action = "divided" inst end def self.remainder(inst) variable = instance_variable_get "@#{inst.variable}" variable.send(:remainder, inst.values[0]) end def self.divisible(inst) inst.action = "divisible" return inst end def self.even(inst) inst.action = "even" return inst end def self.odd(inst) inst.action = "odd" return inst end def self.prime(inst) inst.action = "prime" return inst end def self.positive(inst) inst.action = "positive" return inst end def self.negative(inst) inst.action = "negative" return inst end def self.whole(inst) inst.action = "whole" return inst end def self.root(inst) inst = Instruction.new(inst) unless inst.class == Instruction inst.action = "root" return inst end def self.sqrt(inst) inst = Instruction.new(inst) unless inst.class == Instruction inst.action = "root" return self.square(inst) end def self.absolute(inst) return inst.abs unless inst.class == Instruction return inst.values[0] if inst.values and inst.values.length > 0 end def self.square(inst) #inst.action = "square" unless inst.action #return inst if inst.action == "root" and inst.values.length > 0 then return inst.values[0].sqrt end end def self.get(inst) inst end def self.occurrence(inst) inst end def self.first(inst) inst.action = "first" return inst end def self.last(inst) inst.action = "last" return inst end def self.find(inst) if inst.action == "first" then inst.action = "find first" elsif inst.action == "last" then inst.action = "find last" end return inst end def self.text(inst) if inst.class == Instruction then if inst.action == "message" then inst.action = "text" end return inst else return Instruction.new(inst) end end def self.letter(val, val2=nil) inst = Instruction.new(val) if val2 then inst.addValue(val2) inst.action = "substring" else inst.action = "letter" end return inst end def self.length(inst) #str = instance_variable_get "@#{inst.variable}" #p str return inst.values[0].length end def self.substring(inst) inst.action = "substring" return inst end def self.from(inst, val=nil) if inst.class == Instruction and inst.variable then if inst.action == "letter" then str = instance_variable_get "@#{inst.variable}" return str[inst.values[0]-1..inst.values[0]-1] # .. used for pre-1.9 versions elsif inst.action == "substring" then str = instance_variable_get "@#{inst.variable}" return str[inst.values[0]-1..inst.values[1]-1] elsif inst.action == "find first" then str = instance_variable_get "@#{inst.variable}" index = str.index(inst.values[0]) return index ? index + 1 : nil elsif inst.action == "find last" then str = instance_variable_get "@#{inst.variable}" index = str.rindex(inst.values[0]) return index ? index + 1 : nil end elsif inst.class == Instruction then return inst elsif inst and val then #inst = Instruction.new(inst) inst.addValue(val) return inst else return end end def self.number(inst) if inst and inst.class == Instruction and inst.action == "message" then inst.action = "number" return inst else return self.send(:method_missing, :number, inst) end end def self.message(value) inst = Instruction.new(value) inst.action = "message" return inst end def self.with(inst) inst end def self.prompt(inst) puts inst.values[0] var input = gets.chomp return inst.action == "number" ? input.to_f : input end ''' def createNewVariable(name, value) instance_variable_set "@{name}", value self.send(:attr_accessor, ":{name}") return instance_variable_get "@{name}" end ''' end
true
0eaab6331781e99a88ed65aad3d64361a719fe34
Ruby
ruby-git/ruby-git
/lib/git/diff.rb
UTF-8
3,656
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Git # object that holds the last X commits on given branch class Diff include Enumerable def initialize(base, from = nil, to = nil) @base = base @from = from && from.to_s @to = to && to.to_s @path = nil @full_diff = nil @full_diff_files = nil @stats = nil end attr_reader :from, :to def name_status cache_name_status end def path(path) @path = path return self end def size cache_stats @stats[:total][:files] end def lines cache_stats @stats[:total][:lines] end def deletions cache_stats @stats[:total][:deletions] end def insertions cache_stats @stats[:total][:insertions] end def stats cache_stats @stats end # if file is provided and is writable, it will write the patch into the file def patch(file = nil) cache_full @full_diff end alias_method :to_s, :patch # enumerable methods def [](key) process_full @full_diff_files.assoc(key)[1] end def each(&block) # :yields: each Git::DiffFile in turn process_full @full_diff_files.map { |file| file[1] }.each(&block) end class DiffFile attr_accessor :patch, :path, :mode, :src, :dst, :type @base = nil NIL_BLOB_REGEXP = /\A0{4,40}\z/.freeze def initialize(base, hash) @base = base @patch = hash[:patch] @path = hash[:path] @mode = hash[:mode] @src = hash[:src] @dst = hash[:dst] @type = hash[:type] @binary = hash[:binary] end def binary? !!@binary end def blob(type = :dst) if type == :src && !NIL_BLOB_REGEXP.match(@src) @base.object(@src) elsif !NIL_BLOB_REGEXP.match(@dst) @base.object(@dst) end end end private def cache_full @full_diff ||= @base.lib.diff_full(@from, @to, {:path_limiter => @path}) end def process_full return if @full_diff_files cache_full @full_diff_files = process_full_diff end def cache_stats @stats ||= @base.lib.diff_stats(@from, @to, {:path_limiter => @path}) end def cache_name_status @name_status ||= @base.lib.diff_name_status(@from, @to, {:path => @path}) end # break up @diff_full def process_full_diff defaults = { :mode => '', :src => '', :dst => '', :type => 'modified' } final = {} current_file = nil @full_diff.split("\n").each do |line| if m = %r{\Adiff --git ("?)a/(.+?)\1 ("?)b/(.+?)\3\z}.match(line) current_file = Git::EscapedPath.new(m[2]).unescape final[current_file] = defaults.merge({:patch => line, :path => current_file}) else if m = /^index ([0-9a-f]{4,40})\.\.([0-9a-f]{4,40})( ......)*/.match(line) final[current_file][:src] = m[1] final[current_file][:dst] = m[2] final[current_file][:mode] = m[3].strip if m[3] end if m = /^([[:alpha:]]*?) file mode (......)/.match(line) final[current_file][:type] = m[1] final[current_file][:mode] = m[2] end if m = /^Binary files /.match(line) final[current_file][:binary] = true end final[current_file][:patch] << "\n" + line end end final.map { |e| [e[0], DiffFile.new(@base, e[1])] } end end end
true
f67a7c9fda8febf2aedca47218ba50242e444306
Ruby
jinxue447461686/docs.snap-ci.com
/lib/helpers/as_array_helper.rb
UTF-8
299
2.890625
3
[]
no_license
module AsArrayHelper def monospaced_array_to_sentence_string(input) as_array(input).collect {|i| "`#{i}`" }.join(', ') end def monospaced_array_to_bullet_list(input) as_array(input).collect {|i| "* `#{i}`" }.join("\n") end private def as_array(input) input || [] end end
true
fd49ce6a87c9bde8bbf810f51e2c0b38a71d63f9
Ruby
Tricktionary/FakeBookGraphQL
/app/graphql/resolvers/search_song_by_page.rb
UTF-8
1,014
2.65625
3
[]
no_license
# frozen_string_literal: true module Resolvers class SearchSongByPage < Resolvers::BaseResolver type Types::SongType.connection_type, null: false argument :title, String, required: true argument :page_number, Integer, required: true def resolve(title:, page_number:) if title.present? # Fuzzy search for the book title book = Book.where('title LIKE ?', "%#{title}%") if book.present? songs = Song.where(book: book) result = [] # Look for related songs in the range songs.each do |song| range_start = song.page_range_start range_end = song.page_range_end range = (range_start..range_end).to_a result.append(song) if range.include? page_number end result else raise GraphQL::ExecutionError, 'This book does not exist' end else raise GraphQL::ExecutionError, 'This book is not valid' end end end end
true
e8b867d4551498c9156cbd05693ecfa3eabbbc70
Ruby
james-wallace-nz/ls_rb109
/lesson_3/medium_1.rb
UTF-8
6,804
4.53125
5
[]
no_license
# 1 # Let's do some "ASCII Art" (a stone-age form of nerd artwork from back in the days before computers had video screens). # For this practice problem, write a one-line program that creates the following output 10 times, with the subsequent line indented 1 space to the right: # The Flintstones Rock! # The Flintstones Rock! # The Flintstones Rock! count = 0 loop do puts "#{' ' * count}The Flintstones Rock!" count += 1 break if count == 10 end # 2 # The result of the following statement will be an error: # puts "the value of 40 + 2 is " + (40 + 2) # Why is this and what are two possible ways to fix this? # TypeError: Cannot add string and integer. # Fix: puts "the value of 40 + 2 is #{40 + 2}" puts "the value of 40 + 2 is " + (40 + 2).to_s # 3 # Alan wrote the following method, which was intended to show all of the factors of the input number: # def factors(number) # divisor = number # factors = [] # begin # factors << number / divisor if number % divisor == 0 # divisor -= 1 # end until divisor == 0 # factors # end # Alyssa noticed that this will fail if the input is 0, or a negative number, and asked Alan to change the loop. How can you make this work without using begin/end/until? Note that we're not looking to find the factors for 0 or negative numbers, but we just want to handle it gracefully instead of raising an exception or going into an infinite loop. def factors(number) divisor = number factors = [] while divisor > 0 factors << number / divisor if number % divisor == 0 divisor -= 1 end factors end p factors(12) # Bonus 1 # What is the purpose of the number % divisor == 0 ? # if number is divisible without remainders then divisor is a factor of number # Bonus 2 # What is the purpose of the second-to-last line (line 8) in the method (the factors before the method's end)? # line 8 is the last evaluated expression, which means the factors method will return the factors local variable array # 4 # Alyssa was asked to write an implementation of a rolling buffer. Elements are added to the rolling buffer and if the buffer becomes full, then new elements that are added will displace the oldest elements in the buffer. # She wrote two implementations saying, "Take your pick. Do you like << or + for modifying the buffer?". Is there a difference between the two, other than what operator she chose to use to add an element to the buffer? def rolling_buffer1(buffer, max_buffer_size, new_element) buffer << new_element buffer.shift if buffer.size > max_buffer_size buffer end def rolling_buffer2(input_array, max_buffer_size, new_element) buffer = input_array + [new_element] buffer.shift if buffer.size > max_buffer_size buffer end # The return values are the same. However, in buffer1, the buffer parameter will be mutated by <<, while in buffer2 the + creates a new array which is assigned to buffer local variable and returned by the method. # 5 # Alyssa asked Ben to write up a basic implementation of a Fibonacci calculator. A user passes in two numbers, and the calculator will keep computing the sequence until some limit is reached. # Ben coded up this implementation but complained that as soon as he ran it, he got an error. Something about the limit variable. What's wrong with the code? limit = 15 def fib(first_num, second_num, limit) while first_num + second_num < limit sum = first_num + second_num first_num = second_num second_num = sum end sum end result = fib(0, 1, limit) puts "result is #{result}" # How would you fix this so that it works? # limit is a local variable that is not visible within the fib method scope - fib is a method so doesn't have access to any local variables outside of its scope. We can pass in limit as an argument to fib # 6 # What is the output of the following code? answer = 42 def mess_with_it(some_number) some_number += 8 end new_answer = mess_with_it(answer) p answer - 8 # answer is not mutated by mess_with_it method when passed in as an argument. Therefore, p answer - 8 is 42 - 8, which is 34 # 7 # One day Spot was playing with the Munster family's home computer and he wrote a small program to mess with their demographic data: munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } def mess_with_demographics(demo_hash) demo_hash.values.each do |family_member| family_member["age"] += 42 family_member["gender"] = "other" end end # After writing this method, he typed the following...and before Grandpa could stop him, he hit the Enter key with his tail: mess_with_demographics(munsters) # Did the family's data get ransacked? Why or why not? # Yes, mess_with_demographics uses the each method to iterate through each family member in the munster hash. For each family member the value associated with the age key is reassigned by an increase in 42. The value associated with the gender key is reassigned to 'other' # In Ruby, what gets passed to a method isn't the value of the object, it is the object_id of each argument to the method. The method stores these object_ids internally in locally scopped variables (named per the method definition's parameter list). # The method's demo_hash starts off pointing to the munsters hash. The program does not re-assign demo_hash so the actual hash is being messed with inside of the method # 8 # Method calls can take expressions as arguments. Suppose we define a method called rps as follows, which follows the classic rules of rock-paper-scissors game, but with a slight twist that it declares whatever hand was used in the tie as the result of that tie. def rps(fist1, fist2) if fist1 == "rock" (fist2 == "paper") ? "paper" : "rock" elsif fist1 == "paper" (fist2 == "scissors") ? "scissors" : "paper" else (fist2 == "rock") ? "rock" : "scissors" end end # What is the result of the following call? puts rps(rps(rps("rock", "paper"), rps("rock", "scissors")), "rock") # puts rps(rps('paper', 'rock'), "rock") # puts rps('paper', "rock") # puts 'paper' # rps( # rps( # rps("rock", "paper"), # paper # rps("rock", "scissors") # rock # ), # paper # "rock" # paper # ) # 9 # Consider these two simple methods: def foo(param = "no") "yes" end def bar(param = "no") param == "no" ? "yes" : "no" end # What would be the return value of the following method invocation? p bar(foo) # foo # => 'yes' # bar('yes') # 'yes' == 'no' ? 'yes' : 'no' # end # => 'no'
true
18a6c5ade8028df68b7f50ae3ccb0e55f577e62b
Ruby
qtlove/Tools
/lib/new_main.rb
UTF-8
965
2.53125
3
[]
no_license
sk = "新闻 行业 资讯,http://www.51hejia.com/xinwen/;" + "卖场,http://www.51hejia.com/maichang/;" + "博客,http://blog.51hejia.com/;" hk = {} a1 = sk.split(";") 0.upto(a1.size-1) do |i| a2 = a1[i].split(",")[0].split(" ") 0.upto(a2.size-1) do |j| k = a2[j] v = a1[i].split(",")[1] hk[k] = v end end p hk["新闻"] p hk["新闻1"] #open("deco_keywords_091015.txt").each do |fr| # # x = fr.gsub("\n", "") # p fr = "\n" + fr + "x:1" # open('output', 'a') { |f| f << fr } # #end #a = Hash.new #open("word_idfs.txt").each do |fr| # # x = fr.gsub("\n", "") # l = fr.gsub("\n", "").split("\t") # a["#{l[0]}"] = l[1] # # p fr = fr.gsub("\n", "") + " => " + fr.gsub("\n", "") + "\n" # # open('exceptions.txt', 'a') { |f| f << fr } #end #p a["组图"].to_f #open("output2").each do |fr| # # x = fr.gsub("\n", "") ## p fr = fr.gsub("\n", "") + " 1"+ "\n" # fr = fr + "x:1" + "\n" # open('output3', 'a') { |f| f << fr } # #end
true
426d90872985e3e04d0d4787b9da24d149ef7b5f
Ruby
javierrcc522/prime_numbers
/lib/prime_numbers.rb
UTF-8
212
3.296875
3
[]
no_license
#! usr/bin/env ruby class Primes def magic(num) array = (2..num).to_a i = 2 while (i < Math.sqrt(num)) do array.reject! { |r| r % i === 0 && r != i } i += 1 end array end end
true
e0330a56f493a220d7c3703f6bb625733e79c1c7
Ruby
pwinning1991/testingruby
/files.rb
UTF-8
917
3.40625
3
[]
no_license
#working with files File.open("/Users/pwinnington/ruby/teams.txt", 'w+'){|f| f.write("Twins,Mets,Yankees")} # r - reading # a - appending to a file # w - just writing # w+ - reading and writing # a+ - open a file for reading and appending # r+ - opening a file for updating both readng and writing file_to_save = File.new("/Users/pwinnington/ruby/other_teams.txt", 'w+') file_to_save.puts("Astros, Diamondbacks, Marlins") file_to_save.close #reading files in and combining them into an array teams = File.read("/Users/pwinnington/ruby/teams.txt") teams1 = File.read("/Users/pwinnington/ruby/other_teams.txt") x = teams.split(',') + teams1.split(',') p x #deltes files #files.delete("/Users/pwinnington/ruby/other_teams.txt") #appending and updating files 10.times do sleep 1 puts "Record saved" File.open("/Users/pwinnington/ruby/teams.txt", "a") {|f| f.puts "Started server at: #{Time.new}"} end
true
43bce6ec4fb39923d53941c99d160f3ed0ea2280
Ruby
eripheebs/learn_to_program
/ch14-blocks-and-procs/program_logger.rb
UTF-8
286
3.359375
3
[]
no_license
def program_log desc, &block puts "Beginning #{desc.inspect}..." result = block.call puts "...#{desc.inspect} finished, returning: #{result}" end program_log "outer block" do program_log "inner block" do "Hello" end program_log "second inner block" do "Bye" end true end
true
3c9f25cc5844162fa40110c7f8c0bc9aac5ee18d
Ruby
drish/rioter
/lib/rioter/v4/leagues.rb
UTF-8
2,714
2.59375
3
[ "MIT" ]
permissive
require "rioter/requester" require "rioter/v4/league_entry" module Rioter module V4 class Leagues < Rioter::Requester def initialize(api_key, region) super(api_key, region) end # GET_getLeagueEntries def by_queue_tier_division(queue:, tier:, division:, page:) url = "#{base_url}league/v4/entries/#{queue}/#{tier}/#{division}?page=#{page}" entries = make_request(url) entries.map { |entry| Rioter::V4::LeagueEntry.new(entry) } end # GET_getChallengerLeague def by_challenger_league(queue:) url = "#{base_url}league/v4/challengerleagues/by-queue/#{queue}" entries = make_request(url) entries["entries"].map do |entry| Rioter::V4::LeagueEntry.new(entry.merge({ "tier" => "CHALLENGER", "leagueId" => entries["leagueId"] })) end end # GET_getGrandMasterLeague def by_grandmaster_league(queue:) url = "#{base_url}league/v4/grandmasterleagues/by-queue/#{queue}" entries = make_request(url) entries["entries"].map do |entry| Rioter::V4::LeagueEntry.new(entry.merge({ "tier" => "GRANDMASTER", "leagueId" => entries["leagueId"] })) end end # GET_getMasterLeague def by_master_league(queue:) url = "#{base_url}league/v4/masterleagues/by-queue/#{queue}" entries = make_request(url) entries["entries"].map do |entry| Rioter::V4::LeagueEntry.new(entry.merge({ "tier" => "MASTER", "leagueId" => entries["leagueId"] })) end end # GET_getLeagueById def by_league_id(league_id:) url = "#{base_url}league/v4/leagues/#{league_id}" entries = make_request(url) entries["entries"].map do |entry| Rioter::V4::LeagueEntry.new(entry.merge({ "tier" => entries["tier"], "leagueId" => entries["leagueId"] })) end end # GET_getLeagueEntriesForSummoner def by_summoner(encrypted_summoner_id:) url = "#{base_url}league/v4/entries/by-summoner/#{encrypted_summoner_id}" entries = make_request(url) entries.map { |entry| Rioter::V4::LeagueEntry.new(entry) } end private def validate_queue(q) [ "RANKED_SOLO_5x5", "RANKED_TFT", "RANKED_FLEX_SR", "RANKED_FLEX_TT" ].include?(q) end def validate_tier(t) [ "DIAMOND", "PLATINUM", "GOLD", "SILVER", "BRONZE", "IRON" ].include?(d) end def validate_division(d) ["I", "II", "III", "IV"].include?(d) end end end end
true
5fc603e1c61527c23c145c2d574514c3b6d9aff2
Ruby
c0ded0g/RPi_GPIO_via_web
/RPi_GPIO_via_web.rb
UTF-8
19,088
3.03125
3
[]
no_license
################################################################################# # # # FILE: RPi_GPIO_via_web.rb # # # # USAGE: sudo ruby RPi_GPIO_via_web.rb # # # # DESCRIPTION: Access and control RPi GPIO via the web. # # My first attempt at this (Ruby, Sinatra), so lots of comments! # # # # OPTIONS: --- # # REQUIREMENTS: --- # # BUGS: --- # # NOTES: --- # # # # AUTHOR: Mark Wrigley # # COMPANY: --- # # VERSION: 0.05 # # CREATED: 01.04.2015 # # REVISION: 10.04.2015 # # # ################################################################################# ################################################################################# # CONFIGURATION # # # # tri-colour LED connected to GPIO 17, 27, 22 # # MCP3008 (ADC) connected to GPIO 18, 23 24, 25 # # # ################################################################################# ################################################################################# # NOTES: # # http://www.sinatrarb.com # # http://sinatra-org-book.herokuapp.com/ # # https://www.ruby-lang.org/en/documentation/ # # # ################################################################################# require 'sinatra' # required for web server require 'sinatra-websocket' # required for sockets require 'pi_piper' # required for GPIO access require 'rubygems' # required for ?? #===============================================================================# # ADC # #===============================================================================# def read_adc(adc_pin, clockpin, adc_in, adc_out, cspin) cspin.on clockpin.off cspin.off command_out = adc_pin command_out |= 0x18 command_out <<= 3 (0..4).each do adc_in.update_value((command_out & 0x80) > 0) command_out <<= 1 clockpin.on clockpin.off end clockpin.on clockpin.off result = 0 (0..9).each do clockpin.on clockpin.off result <<= 1 adc_out.read if adc_out.on? result |= 0x1 end end cspin.on return result end #===============================================================================# # GPIO PIN CONFIGURATION # #===============================================================================# # SPI - serial peripheral interface to MCP3008: clock = PiPiper::Pin.new :pin => 18, :direction => :out adc_out = PiPiper::Pin.new :pin => 23 adc_in = PiPiper::Pin.new :pin => 24, :direction => :out cs = PiPiper::Pin.new :pin => 25, :direction => :out # tricolour LED: pinRedLed = PiPiper::Pin.new :pin => 17, :direction => :out pinGreenLed = PiPiper::Pin.new :pin => 27, :direction => :out pinBlueLed = PiPiper::Pin.new :pin => 22, :direction => :out #===============================================================================# # CONSTANTS # #===============================================================================# # NOTE: all constants in Ruby start with upper case character # LED status possibilities (on/off): LEDon = true LEDoff = false # index values into an array containing status info of each LED IdxRedLed = 0 IdxGreenLed = 1 IdxBlueLed = 2 # Messages: client --> server M_redLedClicked = 'redled clicked' M_greenLedClicked = 'greenled clicked' M_blueLedClicked = 'blueled clicked' # Messages: server --> client M_redOff = 'redled off' M_redOn = 'redled on' M_greenOff = 'greenled off' M_greenOn = 'greenled on' M_blueOff = 'blueled off' M_blueOn = 'blueled on' #===============================================================================# # VARIABLES # #===============================================================================# # an array containing the status of each LED ledStatus = [LEDoff, LEDoff, LEDoff] flashRate = 1.0 updateRate = 5.0 #===============================================================================# # THINGS TO DO INDEPENDENTLY OF THE SERVER # #===============================================================================# # read analog pins & send updates to the clients Thread.new do loop do sleep(updateRate) (0..7).each do |channel| value = read_adc(channel, clock, adc_in, adc_out, cs) EM.next_tick { settings.sockets.each{|s| s.send("adc"+channel.to_s+" #{value}") } } end end end # temporary code to flash the red LED while testing Thread.new do loop do sleep(flashRate) if (pinRedLed.read == 0) pinRedLed.on ledStatus[IdxRedLed] == LEDon EM.next_tick { settings.sockets.each{|s| s.send(M_redOn) } } else pinRedLed.off ledStatus[IdxRedLed] == LEDoff EM.next_tick { settings.sockets.each{|s| s.send(M_redOff) } } end end end #===============================================================================# # SETTINGS # #===============================================================================# set :server, 'thin' # sets the handle used for built-in webserver set :sockets, [] # creates an empty list, called sockets set :port, 2001 # server port, default is 4567, I use 2001 to suit my router port mapping set :bind, '0.0.0.0' # server IP address #===============================================================================# # ROUTES # #===============================================================================# get '/' do if !request.websocket? # not a websocket request, serve up the home html page # NOTE: the page is defined in-line below rather than in /views/index.erb erb :index else # websocket logic: request.websocket do |ws| ws.onopen do |handshake| # send information only to the client that just connected: ws.send("Hello "+request.ip) if (pinRedLed.read == 0); ws.send(M_redOff) else ws.send(M_redOn) end if (pinGreenLed.read == 0); ws.send(M_greenOff) else ws.send(M_greenOn) end if (pinBlueLed.read == 0); ws.send(M_blueOff) else ws.send(M_blueOn) end # then add this to the list of sockets settings.sockets << ws end ws.onmessage do |msg| case msg.downcase # TO DO: put in limits to these rates when 'flash rate up' flashRate /= 2.0 when 'flash rate down' flashRate += 1 when 'refresh rate up' updateRate /= 2.0 when 'refresh rate down' updateRate += 1 # RED LED when M_redLedClicked if (pinRedLed.read == 0) ledStatus[IdxRedLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_redOn) } }; pinRedLed.on else ledStatus[IdxRedLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_redOff) } }; pinRedLed.off end when M_redOff ledStatus[IdxRedLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_redOff) } }; pinRedLed.off when M_redOn ledStatus[IdxRedLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_redOn) } }; pinRedLed.on # GREEN LED when M_greenLedClicked if (pinGreenLed.read == 0) ledStatus[IdxGreenLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_greenOn) } }; pinGreenLed.on else ledStatus[IdxGreenLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_greenOff) } }; pinGreenLed.off end when M_greenOff ledStatus[IdxGreenLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_greenOff) } }; pinGreenLed.off when M_greenOn ledStatus[IdxGreenLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_greenOn) } }; pinGreenLed.on # BLUE LED when M_blueLedClicked if (pinBlueLed.read == 0) ledStatus[IdxBlueLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_blueOn) } }; pinBlueLed.on else ledStatus[IdxBlueLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_blueOff) } }; pinBlueLed.off end when M_blueOff ledStatus[IdxBlueLed] = LEDoff; EM.next_tick { settings.sockets.each{|s| s.send(M_blueOff) } }; pinBlueLed.off when M_blueOn ledStatus[IdxBlueLed] = LEDon; EM.next_tick { settings.sockets.each{|s| s.send(M_blueOn) } }; pinBlueLed.on # OTHERWISE, send the message back to the clients else EM.next_tick { settings.sockets.each{|s| s.send(msg) } } end end ws.onclose do warn("websocket closed") settings.sockets.delete(ws) end end end end get '/params' do erb :params end __END__ @@ index <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <meta charset="UTF-8"> <title>RPi2</title> <body> <div id="container" style="width:600px; height:500px"> <FONT FACE="verdana" size="2"> <!-- ------------------------ --> <div id="header" style="background-color:#FFA500;"> <text style="margin-bottom:0;text-align:center;">Control Panel</text> <table width="100%"> <!-- th = table header cell, td = table data cell --> <tr> <th align="left">RPi 2</th> <th align="right">IP address</th> </tr> <tr> <td align="left"><label id="msg1"></label>you are :</td> <td align="right"><label id="ipaddr"></label></td> </tr> </table> </div> <!-- ------------------------ --> <form id="form" style="background-color:#FFA500;border:solid 2px black"> <input type="text" id="input" value="type a command" size="50" maxlength="20" style="background-color:#FFB500"></input> </form> <!-- ------------------------ --> <div id="LEDs" style="background-color:#EEEEEE;height:100px;width:186px;border:solid 2px black;position: absolute; top: 110px; left: 10px; "> <svg xmlns="http://www.w3.org/2000/svg"> <circle id="redLed" cx="30" cy="25" r="10" fill="gray" stroke="black" stroke-width="4"/> <circle id="greenLed" cx="60" cy="25" r="10" fill="gray" stroke="black" stroke-width="4"/> <circle id="blueLed" cx="90" cy="25" r="10" fill="gray" stroke="black" stroke-width="4"/> </svg> </div> <!-- ------------------------ --> <div id="msgs" style="background-color:#99FF99;height:346px;width:200px;overflow:scroll;border:solid 2px black;position: absolute; top: 110px; left: 200px; "> </div> <!-- ------------------------ --> <div id="status" style="background-color:#FFD700;width:186px;height:350px;border:solid 2px black;position: absolute; top: 210px; left: 10px; "> <b>analog inputs:</b><br> <FONT FACE="courier"> AN0: <label id="an0"></label> <br> <meter id="meter0" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN1: <label id="an1"></label> <br> <meter id="meter1" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN2: <label id="an2"></label> <br> <meter id="meter2" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN3: <label id="an3"></label> <br> <meter id="meter3" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN4: <label id="an4"></label> <br> <meter id="meter4" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN5: <label id="an5"></label> <br> <meter id="meter5" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN6: <label id="an6"></label> <br> <meter id="meter6" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> AN7: <label id="an7"></label> <br> <meter id="meter7" x="27" y="20" value="512" min="0" max="1024" low="100" high="900"></meter> <br> </FONT> </p> </div> <!-- ------------------------ --> <div id="buttons" style="background-color:#99FF99;height:100px;width:200px;border:solid 2px black;position: absolute; top: 460px; left: 200px; "> <input type="button" name="toggleMsgs" id="toggleMsgs" value="turn messages on/off" fill="red" style="position: absolute;left:10px; top:25px"> <input type="button" name="clearMsgs" id="clearMsgs" value="clear messages" fill="red" style="position: absolute;left:10px; top:50px"> </div> <div id="links" style="background-color:lightblue;height:146px;width:200px;overflow:scroll;border:solid 2px black;position: absolute; top: 110px; left: 402px; "> <p>Click <a href="/params"> here for the params</a></p> </div> <!-- ------------------------ --> </div> </body> <script type="text/javascript"> var displayMessages = true; function pad(num, size) { // add leading zeros to pad out a number var s = num+""; while (s.length < size) s = "0" + s; return s; } function updateMeter(meter,value){ // adjust analog meter var s1 = meter.slice(-1) document.getElementById('an'+s1).innerHTML = value document.getElementById('meter'+s1).value = parseInt(value) } window.onload = function(){ (function(){ var show = function(el){ return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; } }(document.getElementById('msgs')); var update_GPIO = function(param1,param2){ switch (param1){ case 'redled': case 'greenled': case 'blueled': update_LEDs(param1, param2) break; case 'adc0': case 'adc1': case 'adc2': case 'adc3': case 'adc4': case 'adc5': case 'adc6': case 'adc7': updateMeter(param1,param2) break; case 'hello': update_Greeting(param2) break; case 'message','msg': update_Message(param2) break; default: } } var update_LEDs = function(a,b,c) { return function(indic,msg){ if (indic == 'redled') { if (msg == 'on') {a.style.fill='red'} if (msg == 'off') {a.style.fill='brown'} } if (indic == 'greenled') { if (msg == 'on') {b.style.fill='lightgreen'} if (msg == 'off') {b.style.fill='darkgreen'} } if (indic == 'blueled') { if (msg == 'on') {c.style.fill='dodgerblue'} if (msg == 'off') {c.style.fill='darkblue'} } } }(document.getElementById('redLed'),document.getElementById('greenLed'),document.getElementById('blueLed')); var update_Greeting = function(a) { return function(x){a.innerHTML = x} } (document.getElementById('ipaddr')) var update_Message = function(a) { return function(x){ if (x == "on") {displayMessages = true} if (x == "off") {displayMessages = false} if (x == "clear") {a.innerHTML = ""} } } (document.getElementById('msgs')) // ws is my websocket connection in the client var ws = new WebSocket('ws://' + window.location.host + window.location.pathname); ws.onopen = function() { show('websocket opened'); }; // this calls function show, which returns an unnamed function that // takes 'websocket opened' as a parameter (called msg), and adds it // to the front of the HTML text in the document element referred to // by the ID 'msgs' ws.onclose = function() { show('websocket closed'); }; ws.onmessage = function(m) { // break the message into parts based on space separator // the first two words are important var received_msg = m.data.split(' '); var param1 = received_msg[0].toLowerCase() param2 = (received_msg.length > 1) ? received_msg[1].toLowerCase() : "-"; // this is a short way to write the following if else statement // if (received_msg.length > 1) { // var param2 = received_msg[1].toLowerCase() // } else { // var param2 = "-" // } // build a timestamp var d = new Date(); var hr = d.getHours(); var mn = d.getMinutes(); var sc = d.getSeconds(); hr = pad(hr,2) mn = pad(mn,2) sc = pad(sc,2) var timeStamp = '['+hr+':'+mn+':'+sc+'] ' // act on the GPIO pins as necessary update_GPIO(param1,param2) //show(timeStamp+param1+'/'+param2) if (displayMessages) {show(timeStamp+m.data)} }; // when something is typed in the input box (form), send // it to the server var sender = function(f){ var input = document.getElementById('input'); input.onclick = function(){ input.value = ">>" }; input.onfocus = function(){ input.value = ">" }; f.onsubmit = function(){ ws.send(input.value); input.value = "send a message"; return false; } }(document.getElementById('form')); // when an LED object is clicked or button pressed, send a message to the server // RED var senderRed = function(i1){ i1.onclick = function(){ws.send('redLed clicked')} }(document.getElementById('redLed')); // GREEN var senderGreen = function(i1){ i1.onclick = function(){ws.send('greenLed clicked')} }(document.getElementById('greenLed')); // BLUE var senderBlue = function(i1){ i1.onclick = function(){ws.send('blueLed clicked')} }(document.getElementById('blueLed')); // MESSAGES ON/OFF var toggleMessages = function(i1){ i1.onclick = function(){displayMessages = !displayMessages} }(document.getElementById('toggleMsgs')); // CLEAR MESSAGES var clearMessages = function(i1){ i1.onclick = function(){update_Message('clear')} }(document.getElementById('clearMsgs')); })(); } </script> </html> @@ params <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <meta charset="UTF-8"> <title>RPi2 params</title> <body> current parameter settings are: <p>Click <a href="/">here</a> to go home</p> </body> </html>
true
9ce3a90910a1f9fe06b4960231654392d69589a3
Ruby
Cobmart199/CIS282_HomeWorkLectures
/acronym_Balonwu.rb
UTF-8
575
3.671875
4
[]
no_license
############################################################ # Name : Cyril O. Balonwu # Assignment: Extra Credit Acronym # Date: 26/11/2018 # Class: CIS 282 # Description: Extra Credit Acronym ############################################################ puts "Please Enter a complete English Sentence: " var_words = gets.chomp.to_s def acronym(var_words) # In the below regular expression, the forward slash w will handle any word character. return var_words.scan(/\b\w/).join.upcase end puts "Your sentence in acronyms is: #{acronym(var_words)} "
true
5de3be1a4701db78b8cd7d7f4fa8a585f44ad7a8
Ruby
dqmrf/dive-in-ruby
/tasks/catch_and_ignore_specific_exception/bootstrap2.rb
UTF-8
816
3.078125
3
[]
no_license
require 'pry' require_relative 'my_error' require_relative 'stripe_error' class SubscriptionsHelper attr_reader :error def charge # raise StripeError.new('Error in :charge method!') update_subscription # raise StripeError.new('Error 2 in :charge method!') puts '>> :charge CODE EXECUTED!' true rescue => e handle_error(e) end private def update_subscription # raise StripeError.new("Couldn't update subscription plan!") puts '>> :update_subscription CODE EXECUTED!' rescue => e pass_error(e) end def pass_error(err) log_error(err) raise end def handle_error(err) log_error(err) end def log_error(err) self.error = err if @error.nil? end def error=(error) @error = error end end sh = SubscriptionsHelper.new p sh.charge
true
7078354572cbae2aedf4e5dd12cfa8a60704f9d2
Ruby
morganric/embedtree_old
/app/models/ability.rb
UTF-8
2,202
2.53125
3
[]
no_license
class Ability include CanCan::Ability attr_accessor :user def initialize(user) alias_action :show, :update, :index, :to => :change @user = user || User.new determine_ability end private def determine_ability if user.has_role? :admin can :manage, :all elsif user.has_role? :user user_rights elsif user.has_role? :VIP vip_rights end visitor_rights end def user_rights can [:show, :update], User, :id => user.id can [:read, :create, :featured, :popular], Post can [:read, :update], Profile can :read, Provider can :read, Author can :read, Type can :read, Category end def vip_rights user_rights can [:read, :create], CategoryPost, :category_user => { :user_id => user.id, :category_id => user.categories } end def visitor_rights can :read, Profile can [:read, :popular, :featured], Post can :read, Category can :read, Provider can :read, Author can :read, Type can :read, FacebookPage end # def initialize(user) # user ||= User.new # guest user (not logged in) # if user.has_role? :admin # can :manage, :all # end # # Define abilities for the passed in user here. For example: # # # # user ||= User.new # guest user (not logged in) # # if user.admin? # # can :manage, :all # # else # # can :read, :all # # end # # # # The first argument to `can` is the action you are giving the user permission to do. # # If you pass :manage it will apply to every action. Other common actions here are # # :read, :create, :update and :destroy. # # # # The second argument is the resource the user can perform the action on. If you pass # # :all it will apply to every resource. Otherwise pass a Ruby class of the resource. # # # # The third argument is an optional hash of conditions to further filter the objects. # # For example, here the user can only update published articles. # # # # can :update, Article, :published => true # # # # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities # end end
true
cf03eeaf3867eb35f79aff90bc52da77bcb27bcd
Ruby
CocoaPods/CocoaPods
/lib/cocoapods/sandbox/headers_store.rb
UTF-8
5,775
2.734375
3
[ "MIT" ]
permissive
module Pod class Sandbox # Provides support for managing a header directory. It also keeps track of # the header search paths. # class HeadersStore SEARCH_PATHS_KEY = Struct.new(:platform_name, :target_name, :use_modular_headers) # @return [Pathname] the absolute path of this header directory. # def root sandbox.headers_root + @relative_path end # @return [Sandbox] the sandbox where this header directory is stored. # attr_reader :sandbox # @param [Sandbox] @see #sandbox # # @param [String] relative_path # the relative path to the sandbox root and hence to the Pods # project. # # @param [Symbol] visibility_scope # the header visibility scope to use in this store. Can be `:private` or `:public`. # def initialize(sandbox, relative_path, visibility_scope) @sandbox = sandbox @relative_path = relative_path @search_paths = [] @search_paths_cache = {} @visibility_scope = visibility_scope end # @param [Platform] platform # the platform for which the header search paths should be # returned. # # @param [String] target_name # the target for which the header search paths should be # returned. Can be `nil` in which case all headers that match the platform # will be returned. # # @param [Boolean] use_modular_headers # whether the search paths generated should use modular (stricter) style. # # @return [Array<String>] All the search paths of the header directory in # xcconfig format. The paths are specified relative to the pods # root with the `${PODS_ROOT}` variable. # def search_paths(platform, target_name = nil, use_modular_headers = false) key = SEARCH_PATHS_KEY.new(platform.name, target_name, use_modular_headers) if (cached = @search_paths_cache[key]) return cached end search_paths = @search_paths.select do |entry| matches_platform = entry[:platform] == platform.name matches_target = target_name.nil? || (File.basename(entry[:path]) == target_name) matches_platform && matches_target end headers_dir = root.relative_path_from(sandbox.root).dirname @search_paths_cache[key] = search_paths.flat_map do |entry| paths = [] paths << "${PODS_ROOT}/#{headers_dir}/#{@relative_path}" if !use_modular_headers || @visibility_scope == :public paths << "${PODS_ROOT}/#{headers_dir}/#{entry[:path]}" if !use_modular_headers || @visibility_scope == :private paths end.tap(&:uniq!).freeze end # Removes the entire root directory. # # @return [void] # def implode! root.rmtree if root.exist? end # Removes the directory at the given path relative to the root. # # @param [Pathname] path # The path used to join with #root and remove. # # @return [void] # def implode_path!(path) path = root.join(path) path.rmtree if path.exist? end #-----------------------------------------------------------------------# public # @!group Adding headers # Adds headers to the directory. # # @param [Pathname] namespace # the path where the header file should be stored relative to the # headers directory. # # @param [Array<Pathname>] relative_header_paths # the path of the header file relative to the Pods project # (`PODS_ROOT` variable of the xcconfigs). # # @note This method does _not_ add the files to the search paths. # # @return [Array<Pathname>] # def add_files(namespace, relative_header_paths) root.join(namespace).mkpath unless relative_header_paths.empty? relative_header_paths.map do |relative_header_path| add_file(namespace, relative_header_path, :mkdir => false) end end # Adds a header to the directory. # # @param [Pathname] namespace # the path where the header file should be stored relative to the # headers directory. # # @param [Pathname] relative_header_path # the path of the header file relative to the Pods project # (`PODS_ROOT` variable of the xcconfigs). # # @note This method does _not_ add the file to the search paths. # # @return [Pathname] # def add_file(namespace, relative_header_path, mkdir: true) namespaced_path = root + namespace namespaced_path.mkpath if mkdir absolute_source = (sandbox.root + relative_header_path) source = absolute_source.relative_path_from(namespaced_path) if Gem.win_platform? FileUtils.ln(absolute_source, namespaced_path, :force => true) else FileUtils.ln_sf(source, namespaced_path) end namespaced_path + relative_header_path.basename end # Adds an header search path to the sandbox. # # @param [Pathname] path # the path to add. # # @param [String] platform # the platform the search path applies to # # @return [void] # def add_search_path(path, platform) @search_paths << { :platform => platform.name, :path => File.join(@relative_path, path) } end #-----------------------------------------------------------------------# end end end
true
991ea9f1b1a2475a68c814978db4ef2ccff0e980
Ruby
osmondvail81/geekmap
/app/models/linkable.rb
UTF-8
2,223
2.515625
3
[]
no_license
module Linkable ################################## ### INSTANCE METHODS ################################## #---------------------------------- # INTERFACE: Badges #---------------------------------- #User.first.links << Link.create(:website => Website.find_or_create_by_uri(:uri => "google.co.uk"), :link_type => LinkType.find(4), :name => "Homepage") def add_link(uri, label = nil, type = nil, known_site = nil) unless known_site or label # TODO - Is site a known site? (check against prefixes) end type = default_link_type if type.blank? if !has_link?(uri, type) and self.links << Link.create(:website => Website.find_or_create_by_uri(:uri => uri), :link_type => type, :name => label) true else false end end def set_link(uri, label = nil, type = nil) type = default_link_type if type.blank? link = find_link(uri, type) if link and link.name == label return true else if link link.update_attributes(:name => label, :link_type => type) else self.add_link(uri, label, type) end end end def remove_link(uri, type = nil) type = default_link_type if type.blank? if self.find_link(uri, type).destroy true else false end end def has_link?(uri, type = nil) type = default_link_type if type.blank? if find_link(uri, type) true else false end end def find_link(uri, type = nil) type = default_link_type if type.blank? website = Website.find_by_uri(uri) if website and link = self.links.find_by_link_type_id_and_website_id(type.id, website.id) link else false end end # LinkType#slug as input def links_by_type(slug) type = LinkType.find_by_slug(slug) return false unless type Array(links.find_all_by_link_type_id(type.id)) end def known_sites known_sites = self.links_by_type("known-site") known_sites.collect { |l| KnownSiteLink.find(l.id) } if known_sites end ################################## ### INTERNAL METHODS ################################## protected def default_link_type LinkType.find_by_slug("link") end end
true
ef1c6178af5def03d957e4807859e7a4c08bc0b7
Ruby
DougieDev/war_or_peace
/lib/game.rb
UTF-8
1,522
3.9375
4
[]
no_license
require './lib/card' require './lib/deck' require './lib/player' require './lib/turn' class Game attr_reader :player1, :player2, :turn_count def initialize(player1, player2) @player1 = player1 @player2 = player2 @turn_count = 1 end def welcome p "Welcome to War! (or Peace) This game will be played with 52 cards." p "The players today are Megan and Aurora" p "Type 'GO' to start the game!" p "-------------------------------------------------------------------" end def start turn = Turn.new(@player1, @player2) while @turn_count <= 1000000 @turn_count += 1 if turn.type == :basic winner = turn.winner p "Turn #{@turn_count}: #{turn.winner.name} won 2 cards" turn.pile_cards turn.award_spoils(winner) elsif turn.type == :war winner = turn.winner p "Turn #{@turn_count}: WAR - #{turn.winner.name} won 6 cards" turn.pile_cards turn.award_spoils(winner) else turn.type == :mutually_assured_destruction winner = turn.winner p "Turn #{@turn_count}: Mutually Assured Destruction - 6 cards removed from play" turn.pile_cards end if player1.has_lost? p "*~*~*~* #{player2.name} has won the game *~*~*~*" break elsif player2.has_lost? p "*~*~*~* #{player1.name} has won the game *~*~*~*" break end if @turn_count == 1000000 p "---Draw---" end end end end
true
11c8ca06c7aafaca272fea6c674e8c6a7bde9b04
Ruby
sean-yeoh/pairbnb
/spec/models/user_spec.rb
UTF-8
2,984
2.65625
3
[]
no_license
require "rails_helper" RSpec.describe User, :type => :model do let(:name) { "sean" } let(:email) { "sean@hotmail.com" } let(:password) { "12345678" } let(:sean) { User.new(name: name, email: email, password: password) } context "valid input" do describe "can be created when all attributes are present and valid" do it "saves the user" do expect(sean).to be_valid end it "increase user db count by 1" do user_db_count = User.count sean.save expect(User.count).to eq(user_db_count+1) end end end context "ivalid input" do describe "can't be created with invalid input" do it "with no name" do invalid_user = User.create(email: "sean@hotmail.com", password: "12345678") expect(invalid_user).to_not be_valid end it "with no email" do invalid_user = User.create(name: "sean", password: "12345678") expect(invalid_user).to_not be_valid end it "with no password" do invalid_user = User.create(name: "", email: "sean@hotmail.com") expect(invalid_user).to_not be_valid end it "with invalid email" do invalid_user = User.create(name: "", email: "seanhotmail.com") expect(invalid_user).to_not be_valid end it "with email that has been taken" do valid_user = User.create(name: "sean", email: "sean@hotmail.com", password: "12345678") invalid_user = User.create(name: "yeoh", email: "sean@hotmail.com", password: "12345678") expect(invalid_user).to_not be_valid end it "with password length less than 8" do invalid_user = User.create(name: "sean", email: "sean@hotmail.com", password: "1234567") expect(invalid_user).to_not be_valid end end end context "associations with dependency" do let(:name) { "test" } let(:email) { "test@hotmail.com" } let(:password) { "12345678" } let(:user) { User.create(name: name, email: email, password: password) } describe "listings" do let(:listing1) { user.listings.new( title: "Goood place in PJ", city: "PJ", address: "123, Jalan 3", description: "Near to malls", num_guests: 4, num_bedrooms: 2, num_bathrooms: 2, price: 100.00) } let(:listing2) { user.listings.new( title: "Goood place in Bangsar", city: "Bangsar", address: "123, Jalan 5", description: "Near to lrt", num_guests: 4, num_bedrooms: 2, num_bathrooms: 2, price: 100.00) } it "should have many listings" do listing1.save listing2.save expect(user.listings).to eq([listing1, listing2]) end it "should have dependent destroy" do listing1.save listing2.save expect { user.destroy }.to change { Listing.count }.by(-2) end end describe "reservations" do it { is_expected.to have_many(:reservations).dependent(:destroy) } end end end
true
0d44819fd66efced93f71bd6904ad37a1b9aa8f8
Ruby
smallm/RubyQuiz
/7-Countdown/spec/expression_spec.rb
UTF-8
1,712
3.09375
3
[]
no_license
require 'expression.rb' describe Expression do it "can get its constituent base numbers" do basenode = Expression.new(522, Operation.new( Expression.new(500, Operation.new( Expression.new(100, nil), 'x', Expression.new(5, nil) ) ), '+', Expression.new(22, Operation.new( Expression.new(11, Operation.new( Expression.new(5, nil), '+', Expression.new(6, nil) ) ), 'x', Expression.new(2, nil) ) ) ) ) basenode.getBaseNumbersUsed().should eq ([100, 5, 5, 6, 2]) end it "can print itself" do basenode = Expression.new(522, Operation.new( Expression.new(500, Operation.new( Expression.new(100, nil), 'x', Expression.new(5, nil) ) ), '+', Expression.new(22, Operation.new( Expression.new(11, Operation.new( Expression.new(5, nil), '+', Expression.new(6, nil) ) ), 'x', Expression.new(2, nil) ) ) ) ) basenode.print().should eq ('((100 x 5) + ((5 + 6) x 2))') end end
true
c49fd7d31c1c2d9de247fa329e4d61e16976c0fc
Ruby
arthurstomp/PSO
/lib/pso_binary.rb
UTF-8
1,021
2.875
3
[]
no_license
require File.join(File.dirname(__FILE__),'pso') class PSOBinary < PSO def s_function(velocity_i) 1/(1+Math.exp(-velocity_i)) end def new_position(position_i, velocity_i) s = s_function(velocity_i) if rand < s return 1 else return 0 end end def random_position(n_dimensions) random_position = Array.new(n_dimensions) n_dimensions.times do |i| random_position[i-1] = rand > 0.5 ? 0 : 1 end random_position end def evaluate_particles self.particles.each do |particle| fitness_value = self.fitness.call(particle.position) best = Best.new(:value => fitness_value,:position => particle.position.clone) if particle.best.nil? particle.best = best.clone end if best.value >= particle.best.value particle.best = best.clone end if self.g_best.nil? self.g_best = best.clone end if best.value >= self.g_best.value self.g_best = best.clone end end end end
true
b880cf925ee96f55670e3da9e57c665065d5f6e9
Ruby
keme787/API-Helper-files
/sms/sending/enqueing/ruby.rb
UTF-8
827
2.640625
3
[]
no_license
require './AfricasTalkingGateway' username = "MyAfricasTalkingUsername"; apikey = "MyAfricasTalkingAPIKey"; to = "+254711XXXYYY,+254733YYYZZZ"; message = "I'm a lumberjack and it's ok, I sleep all night and I work all day" sender = nil # sender = "shortCode or sender id" bulkSMSMode = 1 # This should always be 1 for bulk messages # enqueue flag is used to queue messages incase you are sending a high volume. # The default value is 0. enqueue = 1 gateway = AfricasTalkingGateway.new(username, apikey) begin reports = gateway.sendMessage(to, message, sender, bulkSMSMode, enqueue) reports.each {|x| puts 'number=' + x.number + ';status=' + x.status + ';messageId=' + x.messageId + ';cost=' + x.cost } rescue AfricasTalkingGatewayException => ex puts 'Encountered an error: ' + ex.message end
true
2d2e426d19fa228e91d9ef79ad778ad2fcbcbb2e
Ruby
JJavier98/Support
/2º/FIS/practicas/practica 5/decine_ruby/decine/lib/premio.rb
UTF-8
654
2.65625
3
[]
no_license
# encoding: UTF-8 # # Fundamentos de Ingenieria del Software # Grado en Ingeniería Informática # # 2014 © Copyleft - All Wrongs Reserved # # Ernesto Serrano <erseco@correo.ugr.es> # Carlos Garrancho # Pablo Martinez # module Decine class Premio def initialize(premio, categoria, año) @premio = premio @categoria = categoria @año = año end def obtener_datos resultado = "" resultado += "\n\tNombre: " + @premio.nombre resultado += "\n\tCategoria: " + @categoria resultado += "\n\tAño: " + @año.to_s resultado += "\n\t------------" return resultado end end end
true
0b36a6b6f0d92079261e5b13954862ec28595a95
Ruby
learn-co-students/chi01-seng-ft-051120
/week_2_code_along/run_file.rb
UTF-8
1,238
3.234375
3
[]
no_license
require 'bundler' Bundler.setup require_relative 'dragon.rb' require_relative 'rider.rb' require_relative 'saddle.rb' require 'pry' ### Dragon Instances ### carl = Dragon.new("Carl", "grey", "male", false) steph = Dragon.new("Steph", "yellow", "female", true) jeff = Dragon.new("Jeff", "green", "male", true) jasimine = Dragon.new("Jasimine", "purple", "female", true) drogon = Dragon.new("Drogon", "black", "male", true) ### Rider Instances ### daenarys = Rider.new("Daenarys") aerys = Rider.new("Aerys") zoe = Rider.new("Zoe") sid = Rider.new("Sid") alex = Rider.new("Alex") nick = Rider.new("Nick") derek = Rider.new("Derek") duke = Rider.new("Duke") ### Saddle Instances ### saddle_one = Saddle.new(steph, zoe) saddle_two = Saddle.new(jeff, zoe) saddle_three = Saddle.new(drogon, zoe) saddle_four = Saddle.new(steph, sid) saddle_five = Saddle.new(jasimine, sid) saddle_six = Saddle.new(jasimine, alex) # saddle_seven = Saddle.new(carl, derek) saddle_eight = Saddle.new(drogon, derek) saddle_nine = Saddle.new(jeff, nick) saddle_ten = Saddle.new(jasimine, duke) def all_instances # Returns an array of all of the dragon, saddle, and rider instances Dragon.all + Saddle.all + Rider.all end binding.pry "last thing"
true
10cefb4e483e4f9df2e5d229ee7350943f980c90
Ruby
mavenlink/brainstem
/lib/brainstem/cli.rb
UTF-8
3,395
2.890625
3
[ "MIT" ]
permissive
# Require all CLI commands. Dir.glob(File.expand_path('../cli/**/*.rb', __FILE__)).each { |f| require f } require 'brainstem/concerns/optional' # # General manager for CLI requests. Takes incoming user input and routes to a # subcommand. module Brainstem class Cli include Concerns::Optional EXECUTABLE_NAME = 'brainstem' # # Convenience for instantiating and calling the Cli object. # # @return [Brainstem::Cli] the created instance # def self.call(args, options = {}) new(args, options).call end # # Creates a new instance of the Cli to respond to user input. # # Input is expected to be the name of the subcommand, followed by any # additional arguments. # def initialize(args, options = {}) super options self._args = args.dup.freeze self.requested_command = args.shift end # # Routes to an application endpoint depending on given options. # # @return [Brainstem::Cli] the instance # def call if requested_command && commands.has_key?(requested_command) self.command_method = commands[requested_command].method(:call) end command_method.call(_args.drop(1)) self end # # Holds a copy of the initial given args for debugging purposes. # attr_accessor :_args # # Storage for the extracted command. # attr_accessor :requested_command ################################################################################ private ################################################################################ # # A whitelist of valid options that can be applied to the instance. # # @returns [Array<String>] # def valid_options super | [ :log_method ] end # # A basic routing table where the keys are the command to invoke, and where # the value is a callable object or class that will be called with the # +command_options+. # # @return [Hash] A hash of +'command' => Callable+ # def commands { 'generate' => Brainstem::CLI::GenerateApiDocsCommand } end # # Retrieves the help text and subs any placeholder values. # def help_text @help_text ||= File.read(File.expand_path('../help_text.txt', __FILE__)) .gsub('EXECUTABLE_NAME', EXECUTABLE_NAME) end # # Stores the method we should call to run the user command. # attr_writer :command_method # # Reader for the method to invoke. By default, will output the help text # when called. # # @return [Proc] An object responding to +#call+ that is used as the main # point execution. # def command_method @command_method ||= Proc.new do # By default, serve help. log_method.call(help_text) end end # # Stores the method we should use to log messages. # attr_writer :log_method # # Reader for the method to log. By default, will print to stdout when # called. # # We return a proc here because it's much tricker to make assertions # against stdout than it is to allow ourselves to inject a proc. # # @return [Proc] An object responding to +#call+ that is used to print # information. # def log_method @log_method ||= $stdout.method(:puts) end end end
true
3503a9dc5c13984934df07184a72e17ed9442b2c
Ruby
chadjs/precourse
/Chapter 5/number.rb
UTF-8
191
3.84375
4
[]
no_license
puts 'What is your favorite number?' u_number = gets.chomp.to_i n_number = u_number + 1 puts 'That\'s ok I guess.' puts 'But, ' + n_number.to_s + ' would be a bigger, better favorite number!'
true
2d946ab4169999e1a62dc767b2b7d0026308f269
Ruby
sh6khan/ruby-algo
/graphs/kruskal/edge.rb
UTF-8
154
2.90625
3
[]
no_license
class Edge attr_accessor :start_node, :end_node def initialize(start_node, end_node) @start_node = start_node @end_node = end_node end end
true
9190f0fd45b1fb9f3c5b4dc43e51a57b8e67496a
Ruby
realdev22/hackerrank-ruby
/lib/algorithms/implementation/caesar-cipher-1.rb
UTF-8
271
3.625
4
[]
no_license
gets n = gets k = gets.to_i def rotate(c, ref, k) ((c.ord - ref.ord + k) % 26 + ref.ord).chr end n.chars.each_with_index do |c, idx| if c >= 'a' && c <= 'z' n[idx] = rotate(c, 'a', k) elsif c >= 'A' && c <= 'Z' n[idx] = rotate(c, 'A', k) end end puts n
true
bcfc89ad66fb4aa99029244a9a501a6e8fa3d5ac
Ruby
colin3131/SchoolProjects
/RubyRush/rubyist.rb
UTF-8
595
3.484375
3
[]
no_license
# Rubyist Class, storing methods / details on rubyists class Rubyist def initialize(id) @id = id @real_ruby_count = 0 @fake_ruby_count = 0 @days = 0 end # Reader for accessing Rubyist instance variables attr_reader :id, :real_ruby_count, :fake_ruby_count, :days # Increments days spent prospecting def new_day @days += 1 end # Increments count of real, fake rubies def rubies_found(num_real_rubies, num_fake_rubies) @real_ruby_count += num_real_rubies if num_real_rubies > -1 @fake_ruby_count += num_fake_rubies if num_fake_rubies > -1 end end
true
e12b120750ceb1b3ee29ef0ed4663dc86b40d3f4
Ruby
burtlo/Frogger
/models/frog.rb
UTF-8
655
2.796875
3
[]
no_license
class Frog < Metro::Model property :position property :angle property :image, path: "80sFrogger.png" event :on_down, KbLeft do self.x -= horizonal_step end event :on_down, KbRight do self.x += horizonal_step end event :on_down, KbDown do self.y += veritical_step end event :on_down, KbUp do self.y -= veritical_step end def width ; image.width ; end def height ; image.height ; end def bounds Bounds.new x: x, y: y, width: width, height: height end def horizonal_step width / 2 end def veritical_step height / 2 end def draw image.draw_rot(x,y,z_order,angle) end end
true
a4d8e216e857a675c4e5c9752d4eba514f0910a5
Ruby
nilesr/wg-scraper
/wg-scraper.rb
UTF-8
3,510
2.859375
3
[]
no_license
require 'net/http' require 'open-uri' require 'digest' require 'json' if not (ARGV.length == 1 or ARGV.length == 2) then puts "Usage: ruby wg2.rb <imagedir> [database]" fail end puts "Grabbing thread index" imagesdir = ARGV[0] database = "db.json" if ARGV.length == 2 then database = ARGV[1] end catalog = JSON.parse(Net::HTTP.get("a.4cdn.org", "/wg/catalog.json")) images = Array.new urls = Array.new if imagesdir[-1] == "/" imagesdir = imagesdir[0...-1] end # Assertions if File.exists? imagesdir and not File.directory? imagesdir then puts "Images directory " + imagesdir + " is not a directory" fail end if File.exists? database and File.directory? database then puts "Database " + database + " is actually a directory" fail end if File.exists? database then begin db = JSON.parse(open(database).read()) rescue puts "Unable to parse database. Overwrite with a new empty one? [y/N]? " $stdout.flush if gets.chomp.upcase == "Y" then db = [[],[]] else puts "Unable to parse database, not overwriting." fail end end else db = [[],[]] end for page in catalog do for thread in page["threads"] do next if thread["sticky"] == 1 urls.push thread["no"] end end index = 0 not_downloaded = 0 for url in urls do index += 1 puts "On url " + url.to_s + " " + index.to_s + "/" + urls.length.to_s page = JSON.parse(Net::HTTP.get("a.4cdn.org", "/wg/thread/" + url.to_s + ".json")) in_thread = 0 for post in page["posts"] do if post.include? "filename" then remote_name = post["tim"].to_s + post["ext"] if not db[1].include? remote_name then images.push [remote_name, imagesdir + "/" + index.to_s.rjust(urls.length.to_s.length, "0") + "-" + in_thread.to_s.rjust(page["posts"].length.to_s.length,"0") + "-"] in_thread += 1; else not_downloaded += 1; end end end sleep 0.01 # Official specifications require that we limit ourselves to 100 requests per second # This doesn't actually do that because we don't run multiple connections at the same time, but better safe then sorry end puts "Eliminated " + not_downloaded.to_s + " previously downloaded images" if not_downloaded == 0 then puts "No duplicates, clearing filename database (keeping md5)" db[1] = Array.new end index = 0 for image_array in images do index = index + 1 retries = 0 puts "On image " + image_array[0] + " " + index.to_s + "/" + images.length.to_s while retries < 3 do retries += 1 begin out = open(image_array[1] + image_array[0], 'w') out.write(open("https://i.4cdn.org/wg/" + image_array[0]).read) rescue puts "Download of image " + image_array[0] + " failed. Retrying (" + retries.to_s + "/3)" else # Add to database db[1].push image_array[0] break ensure out.close unless out.nil? end end if retries == 3 then puts "Download of image " + image_array[0] + " failed. The image will not be added to the database." end end puts "Deleting downloaded duplicates by md5" for image_array in images do imagepath = image_array[1] + image_array[0] if not File.exists? imagepath then puts "Warning: Image " + imagepath + " does not exist, but it should" puts "We will not be able to compare the MD5 of this image to the database" next end md5 = Digest::MD5.file(imagepath) if db[0].include? md5 puts "Deleting duplicate image " + image_array[0] File.delete imagepath else db[0].push md5 end end puts "Writing out new database" out = open(database, 'w') out.write JSON.generate(db) out.close puts "Download complete"
true
468545729a4a17e9a4d220eb61c17bfb05b2155b
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/30728693cc60440892eafa199ab3d5e2.rb
UTF-8
334
3.53125
4
[]
no_license
class Bob def hey(stating_something) if stating_something.to_s.strip == "" response = "Fine. Be that way!" elsif stating_something == stating_something.upcase response = "Woah, chill out!" elsif stating_something[-1,1] == "?" response = "Sure." elsif response = "Whatever." end return response end end
true
dec8424ad687b45b8b4dc0e9ceea2c63f5f2a4e0
Ruby
jentrim/course_101
/lesson_5/ex15R2.rb
UTF-8
166
2.78125
3
[]
no_license
arr = [{a: [1, 2, 3]}, {b: [2, 4, 6], c: [3, 6], d: [4]}, {e: [8], f: [6, 10]}] arr.select do |h| h.values.map.all? do |v| v.all?{|int| int.even?} end end
true
f5e09f1c2999d34c0cf87127e39a520ed4002925
Ruby
jblosch/ruby-exercises
/04_pig_latin/pig_latin.rb
UTF-8
461
3.546875
4
[]
no_license
def translate(string) transformed = [] suffix = "ay" words = string.split(' ') words.each do |x| vowel_num = x =~ /[aeiou]/ if x[vowel_num] == 'u' && x[vowel_num - 1] == 'q' cut = x.slice!(0..vowel_num) transformed << x + cut + suffix else cut = x.slice!(0..vowel_num - 1) transformed << x + cut + suffix end end transformed.join(' ') end
true
dd485778af6d60357f4eda1125697430254658c6
Ruby
Kouch-Sato/AtCoderProblems
/ABC/084/084C.rb
UTF-8
43
2.515625
3
[]
no_license
if ("1" =~ /^[0-9]+$/) p 1 else p 0 end
true
d2b82b9fde1fbefc97af6c9780c56fcfcb752af1
Ruby
magdabm/ruby-exercises
/03_homework/00_prime_numbers.rb
UTF-8
830
4.09375
4
[]
no_license
# Napisz program wyszukujący wszystkie liczby pierwsze z zadanego przedziału jako argumenty wywołania metodą Sita Eratostenesa # $ ruby sieve_of_eratosthenes.rb 1 10 # Prime numbers: 2, 3, 5, 7 def prime_numbers(range) ar = range.to_a ar2 = [] if ar.min == 1 ar.delete(1) else ar.min > 2 ar2 = (2..ar.min-1).to_a ar += ar2 ar = ar.sort end i = 2 while i <= Math.sqrt(ar.max).to_i ar.each do |num| if num % i == 0 ar.delete(num) if num != i end end i += 1 end ar - ar2 end puts prime_numbers(1..10).inspect puts prime_numbers(4..20).inspect puts prime_numbers(50..100).inspect if ARGV.count == 2 range = (ARGV[0].to_i..ARGV[1].to_i) puts prime_numbers(range).inspect else puts "Range should have two numbers." end
true
b64ae89a032d2953f3a40f082293ad74081b4789
Ruby
spaek14/sinatra
/app.rb
UTF-8
221
2.75
3
[]
no_license
require 'sinatra' get '/' do 'Hello World! how are you' end get '/named-cat' do p params @name = params[:name] erb :index end get '/random-cat' do @name = ["Amigo", "Misty", "Almond"].sample erb :index end
true
6b7520d66f4d4cec592687e06ba5bc0f1e242fef
Ruby
Nicolas-Reyland/metalang
/out/euler22.rb
UTF-8
391
2.890625
3
[]
no_license
require "scanf.rb" def score( ) scanf("%*\n") len = scanf("%d")[0] scanf("%*\n") sum = 0 for i in (1 .. len) do c = scanf("%c")[0] sum += c.ord - "A".ord + 1 # print c print " " print sum print " " end return sum end sum = 0 n = scanf("%d")[0] for i in (1 .. n) do sum += i * score() end printf "%d\n", sum
true
1b498558574c8c09dfeaf2862ee797ff4c388d70
Ruby
jucdn/athome-startup
/app/helpers/peoples_helper.rb
UTF-8
247
2.515625
3
[ "MIT" ]
permissive
module PeoplesHelper def national_phone(phone) national_phone = Phonelib.parse(phone) return national_phone.national end def international_phone(phone) local_phone = Phonelib.parse(phone) return local_phone.e164 end end
true
dfbdc9a51741f5598ec60691cd31b5a2a79ef0e0
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/ea00823ecadc4c348361b58a89552a25.rb
UTF-8
504
3.6875
4
[]
no_license
class Bob def hey msg reply msg end def reply message msg = Message.new message if msg.silence? 'Fine. Be that way!' elsif msg.yelling? 'Woah, chill out!' elsif msg.asking? 'Sure.' else 'Whatever.' end end end class Message def initialize msg @msg = msg end def silence? @msg.strip == '' end def yelling? @msg.upcase == @msg and !(@msg =~ /[[:alpha:]]/).nil? end def asking? @msg.end_with? '?' end end
true
43c64f0bc1836c6f4763f5fb92b50f75a8652779
Ruby
Brendaneus/the_odin_project
/ruby_programming/merge_sort.rb
UTF-8
550
3.75
4
[]
no_license
def merge_sort arr return arr unless arr.length > 1 arr_A = merge_sort arr[0...(arr.length / 2)] arr_B = merge_sort arr[(arr.length / 2)..(-1)] arr_C = [] until arr_A.empty? and arr_B.empty? if arr_A.empty? arr_C.push arr_B.shift elsif arr_B.empty? arr_C.push arr_A.shift elsif arr_A.first < arr_B.first arr_C.push arr_A.shift else arr_C.push arr_B.shift end end return arr_C end puts "[5, 4, 3, 2, 1, 0] sorted is #{merge_sort [5,4,3,2,1,0]}\n" puts "[6, 21, -1, 5092, 3] sorted is #{merge_sort [3,6,21,-1,5092]}"
true
28ba0aa86e4ac07adc65ffbab848f773b266e6df
Ruby
iBryan6/G5-Automation-Tests-A-Team
/Main/PageObjects/Common/Auth.rb
UTF-8
607
2.734375
3
[ "MIT" ]
permissive
require "rubygems" require "webdrivers" class LoginPage def initialize(driver) @driver = driver end def goToPage(url) return @driver.navigate.to url end #ADD YOUR G5 EMAIL def typeEmail puts "***\nType your G5 email:" email = gets return @driver.find_element(:id, "user_email").send_keys(email) end #ADD YOUR G5 Password "have to find a better way to authenticate" def typePassword puts "Type your G5 password:" password = gets @driver.find_element(:id, "user_password").send_keys(password) end end
true
ca0a50e0d537da248c9b8992f74cb19da4007e7f
Ruby
sourlows/352phish
/src/facebookAPI.rb
UTF-8
3,258
2.71875
3
[]
no_license
#githubAPI.rb #author: djw223 (Dustin Walker) #email: djw223@mail.usask.ca #ruby version: 1.9.3p448 #library version: 1.9.1 require 'koala' require_relative "abstractAPI" require 'pp' class FacebookAPI < AbstractAPI def initialize @supported = [:name, :music, :email, :politician, :book, :author, :software] #@paginationLimit = 20 end def authenticate if $authDirectory.has_key?("Facebook") Koala.http_service.http_options = { :ssl => { :verify => false } } app_id = $authDirectory["Facebook"]["id"] app_secret = $authDirectory["Facebook"]["secret"] puts("enter user access token: ") token = gets @graph = Koala::Facebook::API.new(token) else abort("no authentication information for Facebook found") end end def canMakeQuery(queryTerms) queryTerms.count.times do |i| if(!@supported.include?(queryTerms[i])) puts "can't make query using Facebook" if $verbose return false end end puts "can make query using Facebook" if $verbose return true end def getQueryResults(queryTerms) #authenticate with provided credentials authenticate() #get the user's friends deepFriends = @graph.get_connections("me", "friends") if($limit && $limit < deepFriends.count) deepFriends = deepFriends[0,$limit] end #get each friend's "likes" deepFriends.each { |friend| friend["likes"] = @graph.get_connections(friend["id"], "likes") } #pp deepFriends.first if $verbose nativeQuery = getNativeQuery(queryTerms) pp nativeQuery if $verbose #remove friends without all of the required query terms deepFriends.delete_if { |friend| nativeQuery.any? {|term| friend["likes"].detect {|likedPage| likedPage["category"] == term} == nil} } pp deepFriends.count if $verbose #construct a victim from each friend and add them to the victimlist deepFriends.each{ |dFriend| attrs = Hash.new attrs[:name] = dFriend["name"] nativeQuery.each { |term| item = dFriend["likes"].detect {|likedPage| likedPage["category"] == term} globalTerm = getGlobalName(term) attrs[globalTerm] = item["name"] } victim = Victim.new(attrs) VictimList.instance.victims.push(victim) } pp VictimList.instance.victims if $verbose end def getNativeQuery(queryTerms) #don't worry about the name key, as all FB users have public names if queryTerms.include?(:name) queryTerms.delete(:name) end if queryTerms.include?(:music) queryTerms.delete(:music) queryTerms.push("Musician/band") end if queryTerms.include?(:politician) queryTerms.delete(:politician) queryTerms.push("Politician") end if queryTerms.include?(:book) queryTerms.delete(:book) queryTerms.push("Book") end if queryTerms.include?(:author) queryTerms.delete(:author) queryTerms.push("Author") end if queryTerms.include?(:software) queryTerms.delete(:software) queryTerms.push("Software") end return queryTerms end def getGlobalName(term) case term when "Musician/band" return :music when "Politician" return :politician when "Author" return :author when "Book" return :book when "Software" return :software else return :null end end end
true
a0369a6d37ae3d20247095d6c63991e617df7c53
Ruby
diegopiccinini/docrails
/activerecord/lib/active_record/relation/predicate_builder.rb
UTF-8
4,653
2.59375
3
[ "MIT", "Ruby" ]
permissive
module ActiveRecord class PredicateBuilder # :nodoc: require 'active_record/relation/predicate_builder/array_handler' require 'active_record/relation/predicate_builder/association_query_handler' require 'active_record/relation/predicate_builder/base_handler' require 'active_record/relation/predicate_builder/basic_object_handler' require 'active_record/relation/predicate_builder/class_handler' require 'active_record/relation/predicate_builder/range_handler' require 'active_record/relation/predicate_builder/relation_handler' delegate :resolve_column_aliases, to: :table def initialize(table) @table = table @handlers = [] register_handler(BasicObject, BasicObjectHandler.new(self)) register_handler(Class, ClassHandler.new(self)) register_handler(Base, BaseHandler.new(self)) register_handler(Range, RangeHandler.new(self)) register_handler(Relation, RelationHandler.new) register_handler(Array, ArrayHandler.new(self)) register_handler(AssociationQueryValue, AssociationQueryHandler.new(self)) end def build_from_hash(attributes) attributes = convert_dot_notation_to_hash(attributes.stringify_keys) expand_from_hash(attributes) end def create_binds(attributes) attributes = convert_dot_notation_to_hash(attributes.stringify_keys) create_binds_for_hash(attributes) end def expand(column, value) # Find the foreign key when using queries such as: # Post.where(author: author) # # For polymorphic relationships, find the foreign key and type: # PriceEstimate.where(estimate_of: treasure) if table.associated_with?(column) value = AssociationQueryValue.new(table.associated_table(column), value) end build(table.arel_attribute(column), value) end def self.references(attributes) attributes.map do |key, value| if value.is_a?(Hash) key else key = key.to_s key.split('.').first if key.include?('.') end end.compact end # Define how a class is converted to Arel nodes when passed to +where+. # The handler can be any object that responds to +call+, and will be used # for any value that +===+ the class given. For example: # # MyCustomDateRange = Struct.new(:start, :end) # handler = proc do |column, range| # Arel::Nodes::Between.new(column, # Arel::Nodes::And.new([range.start, range.end]) # ) # end # ActiveRecord::PredicateBuilder.register_handler(MyCustomDateRange, handler) def register_handler(klass, handler) @handlers.unshift([klass, handler]) end def build(attribute, value) handler_for(value).call(attribute, value) end protected attr_reader :table def expand_from_hash(attributes) return ["1=0"] if attributes.empty? attributes.flat_map do |key, value| if value.is_a?(Hash) associated_predicate_builder(key).expand_from_hash(value) else expand(key, value) end end end def create_binds_for_hash(attributes) result = attributes.dup binds = [] attributes.each do |column_name, value| case value when Hash attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value) result[column_name] = attrs binds += bvs when Relation binds += value.bound_attributes else if can_be_bound?(column_name, value) result[column_name] = Arel::Nodes::BindParam.new binds << Relation::QueryAttribute.new(column_name.to_s, value, table.type(column_name)) end end end [result, binds] end private def associated_predicate_builder(association_name) self.class.new(table.associated_table(association_name)) end def convert_dot_notation_to_hash(attributes) dot_notation = attributes.keys.select { |s| s.include?(".") } dot_notation.each do |key| table_name, column_name = key.split(".") value = attributes.delete(key) attributes[table_name] ||= {} attributes[table_name] = attributes[table_name].merge(column_name => value) end attributes end def handler_for(object) @handlers.detect { |klass, _| klass === object }.last end def can_be_bound?(column_name, value) !value.nil? && handler_for(value).is_a?(BasicObjectHandler) && !table.associated_with?(column_name) end end end
true
db567aaf4c65e0bd04222808c795de0623de76e1
Ruby
nwise/activeforecast
/spec/activeforecast_spec.rb
UTF-8
1,210
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe "ActiveForecast" do it "should initialize with no arguments" do ActiveForecast::Forecast.new.should_not be nil end it "should initialize with one string argument" do ActiveForecast::Forecast.new("KCAK").should_not be nil end it "should get XML forecast data when passed a valid airport code" do ActiveForecast::Forecast.new("KCAK").raw_data.content_type.should == 'text/xml' end it "should throw NoSuchAirportCodeError when initialized with a bad airport code" do error = nil begin ActiveForecast::Forecast.new("ABC") rescue ActiveForecastErrors::NoSuchAirportCode => e error = e end error.should be_a ActiveForecastErrors::NoSuchAirportCode end it "should define a method on the Forecast object for each element in the XML document" do begin forecast = ActiveForecast::Forecast.new("KCAK") parsed_response = forecast.raw_data.parsed_response parsed_response['current_observation'].each do |k,v| forecast.send(k.to_s) end result = true rescue NoMethodError result = false end result.should be true end end
true
6500fc142e621b50fc797f950e8aa69bdddee988
Ruby
MadBomber/lib_ruby
/rangify.rb
UTF-8
1,351
3.40625
3
[]
no_license
# lib_ruby/rangify.rb # convert and array of integers into an array of ranges. def rangify(an_array) result = [] list = an_array.sort.uniq prev = list[0] result = list.slice_before { |e| prev, prev2 = e, prev prev2 + 1 != e }.map{|b,*,c| c ? (b..c) : b } return result end def unrangify(an_array) result = [] an_array.each do |entry| if entry.is_a?(Range) result << entry.to_a else result << entry end end return result.flatten end __END__ an_array = [ 152, 153, 154, 155, 158, 161, 162, 165, 178, 179, 180, 181, 182, 185, 186, 187, 188, 194, 199, 206, 220, 225, 226, 228, 229, 260, 263, 264, 267, 270, 273, 276, 277, 280, 281, 284, 285, 292, 299, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 370, 371, 372, 373, 374, 379, 380, 386, 401, 406, 407, 408, 411, 422, 423, 426, 431, 432, 433, 453, 454, 455, 456, 457, 458, 462, 463, 489, 490, 492, 493, 494, 508, 509, 510, 513, 516, 517, 518, 519, 520, 523, 540, 543, 544, 545, 551, 554, 555, 556, 557, 558, 559, 563, 565, 568, 571, 572, 599, 600, 606, 607, 608, 611, 612, 613, 614, 615, 616, 617, 618, 621, 622, 623, 624, 627, 630, 634, 637, 640, 641, 646, 649, 650, 651, 652, 655, 658, 659, 666, 667, 668, 669, 670, 673, ] fixed = rangify(an_array) unfixed = unrangify(fixed) puts an_array == unfixed
true
00cba55dec29972d35b8b5fb8b458693e94a50ab
Ruby
leo-holanda/learn_ruby
/06_timer/timer.rb
UTF-8
642
3.5625
4
[]
no_license
def setTime(seconds) minutes = seconds/60 seconds = seconds%60 hours = minutes/60 minutes = minutes%60 formatted = [] if hours < 10 formatted.push("0") end formatted.push(hours.to_s) formatted.push(":") if minutes < 10 formatted.push("0") end formatted.push(minutes.to_s) formatted.push(":") if seconds < 10 formatted.push("0") end formatted.push(seconds.to_s) formatted.join() end class Timer attr_accessor :seconds def initialize @seconds = 0 end def time_string @time_string = setTime(seconds) end end
true
5e7f4fb40cb5098f8aef927f78e83b21c9458682
Ruby
dmullek/dominion
/app/cards/council_room.rb
UTF-8
455
2.65625
3
[]
no_license
class CouncilRoom < Card def starting_count(game) 10 end def cost(game, turn) { coin: 5 } end def type [:action] end def play(game, clone=false) @card_drawer = CardDrawer.new(game.current_player) @card_drawer.draw(4) game.current_turn.add_buys(1) game.game_players.each do |player| unless player.id == game.current_player.id CardDrawer.new(player).draw(1) end end end end
true
9032a0a32c125327ecc7ff438aec40c9ef3c27fe
Ruby
ChristopherDurand/Exercises
/ruby/oop/oo_basics_4/access_denied.rb
UTF-8
270
3.34375
3
[ "MIT" ]
permissive
class Person attr_reader :phone_number def initialize(number) self.phone_number = number end private attr_writer :phone_number end person1 = Person.new(1234567899) puts person1.phone_number #person1.phone_number = 9987654321 puts person1.phone_number
true
32800827083bb8f4154e2a577ae24218b499a3cb
Ruby
pramnora/ruby
/language/output/hw/hw03.rb
UTF-8
125
3.53125
4
[]
no_license
# Variable declaration... text="Hello, world!" # Print variable to output screen... puts text # Output... # Hello, world!
true
d8f69be69c2d077ecc841701870cce957cbed900
Ruby
dlewiski/Leetspeak
/lib/leetspeak.rb
UTF-8
845
3.421875
3
[]
no_license
class String def leetspeak() leet_array = [] new_words_array = [] words_array = self.split() words_array.each do |word| letters_array = word.split('') letters_array.each do |letter| if letter == "e" letter = 3 new_words_array.push(letter) elsif letter == "o" letter = 0 new_words_array.push(letter) elsif letter == "I" letter = 1 new_words_array.push(letter) elsif (letter == "s") && (letters_array[letters_array.index(letter) - 1] != " ") letter = "z" new_words_array.push(letter) else new_words_array.push(letter) end end leet_array = new_words_array.join() binding.pry end leet_array end end # leet_array.push(new_words_array) # leet_array.join('')
true
5010b8ab2584af96249097e48337ad82987f7025
Ruby
alec-horwitz/oo-email-parser-web-022018
/lib/email_parser.rb
UTF-8
474
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Build a class EmailParser that accepts a string of unformatted # emails. The parse method on the class should separate them into # unique email addresses. The delimiters to support are commas (',') # or whitespace (' '). class EmailParser attr_accessor :all def initialize(emails) self.all = emails end def parse self.all = self.all.split(/[,\s]/) self.all = self.all.map {|email| email.strip}.uniq self.all.delete_if {|email| email==""} end end
true
c644a01734c48e60cda676c9dcdd44f6cdb41377
Ruby
sho-kasama/Todo-rails
/bin/scrape_navbar.rb
UTF-8
622
2.875
3
[]
no_license
require 'open-uri' require 'nokogiri' # スクレイピング先のURL url = 'http://matome.naver.jp/tech' charset = nil html = open(url) do |f| charset = f.charset # 文字種別を取得 f.read # htmlを読み込んで変数htmlに渡す end # htmlをパース(解析)してオブジェクトを作成 doc = Nokogiri::HTML.parse(html, nil, charset) doc.xpath('//li[@class="mdTopMTMList01Item"]').each do |node| # tilte p node.css('h3').inner_text # 記事のサムネイル画像 p node.css('img').attribute('src').value # 記事のサムネイル画像 p node.css('a').attribute('href').value end
true
af5237c1db579daf8d6dc479f9bff849a16875fe
Ruby
avonderluft/radiant-banner_rotator-extension
/lib/banner_rotator/tags.rb
UTF-8
2,509
2.546875
3
[]
no_license
module BannerRotator::Tags include Radiant::Taggable desc %{ Selects a banner from the rotating banners available to this page. If no banner is found for this page and banners are enabled, the page will inherit from its parent. If no banners are found, or they are disabled for this page, then the tag will not be expanded. *Usage*: <pre><code><r:banner><!-- put some banner output code here --></r:banner></code></pre> } tag 'banner' do |tag| page = tag.locals.page tag.locals.banner = page.select_banner tag.expand if tag.locals.banner && page.show_banner? end %w{name background_image foreground_image link_url link_target image_style description}.each do |att| desc %{ Outputs the #{att} attribute of the current banner. *Usage*: <pre><code><r:banner><r:#{att} /></r:banner></code></pre> } tag "banner:#{att}" do |tag| tag.locals.banner.send(att) end desc %{ Expands the contents if there is a non-empty #{att}. *Usage*: <pre><code> <r:banner> <r:if_#{att}>Content to display</r:if_#{att}> </r:banner> </code></pre> } tag "banner:if_#{att}" do |tag| tag.expand unless tag.locals.banner[att].blank? end tag "banner:content" do |tag| if tag.locals.banner['background_image'] =~ /swf/i "<a href=\"#{tag.locals.banner['link_url']}\" target=\"#{tag.locals.banner['link_target']}\"><object class=\"banner\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"160\" height=\"140\" bgcolor=\"#f0f7fd\"><param name=\"movie\" value=\"#{tag.locals.banner['background_image']}\"><param name=\"quality\" value=\"high\"><embed src=\"#{tag.locals.banner['background_image']}\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"160\" height=\"140\" bgcolor=\"#f0f7fd\"></embed></object></a>" else "<a href=\"#{tag.locals.banner['link_url']}\" target=\"#{tag.locals.banner['link_target']}\"><img src=\"#{tag.locals.banner['background_image']}\" /></a>" end end desc %{ Expands the contents if there is no #{att}. *Usage*: <pre><code> <r:banner> <r:unless_#{att}>Content to display</r:unless_#{att}> </r:banner> </code></pre> } tag "banner:unless_#{att}" do |tag| tag.expand if tag.locals.banner[att].blank? end end end
true
d00954737fbd5f1d47546e9af779c5c16c72f344
Ruby
darthmacdougal/GARGoyle
/spec/GARGoyle_spec.rb
UTF-8
1,163
2.546875
3
[ "MIT" ]
permissive
require 'GARGoyle.rb' RSpec.describe GARGoyle do before(:each) do @sequencer = GARGoyle::JobSequencer.new end it 'is an empty sequence' do expect(@sequencer.process({})).to eq([]) end it 'has a sequence of one job' do expect(@sequencer.process(a: '')).to eq(['a']) end it 'has a sequence of three jobs' do expect(@sequencer.process(a: '', b: '', c: '')).to eq(%w[a b c]) end it 'has a sequence of three jobs with a dependency' do expect(@sequencer.process(a: '', b: 'c', c: '')).to eq(%w[a c b]) end it 'has a sequence of six jobs with chained dependencies' do expect(@sequencer.process(a: '', b: 'c', c: 'f', d: 'a', e: 'b', f: '')).to eq(%w[a f c b d e]) end it 'has a sequence of three jobs and a circular dependency' do expect do @sequencer.process(a: '', b: '', c: 'c') end.to raise_error(StandardError, "Job and dependency can't be the same") end it 'has a sequence of six jobs with a circular dependency' do expect do @sequencer.process(a: '', b: 'c', c: 'f', d: 'a', e: '', f: 'b') end.to raise_error(StandardError, 'There was a circular job dependency') end end
true
616e257d36a8b8972168cffe16b9ada73fd8bf4e
Ruby
barsoom/prawn_cocktail
/spec/recursive_closed_struct_spec.rb
UTF-8
1,085
2.765625
3
[ "MIT" ]
permissive
require_relative "spec_helper" require_relative "../lib/prawn_cocktail/utils/recursive_closed_struct" describe RecursiveClosedStruct do it "provides readers from a hash" do subject = RecursiveClosedStruct.new(key: "value") assert_equal "value", subject.key end it "raises when there's no such key" do subject = RecursiveClosedStruct.new(key: "value") assert_raises(NoMethodError) do subject.other_key end end it "recurses through hashes" do subject = RecursiveClosedStruct.new({ one: { two: { three: "four" } }, }) assert_equal "four", subject.one.two.three end describe "#include?" do it "is true if that key exists" do subject = RecursiveClosedStruct.new(real: true) assert subject.include?(:real) end it "is false if that key does not exist" do subject = RecursiveClosedStruct.new(real: true) refute subject.include?(:imaginary) end it "recurses" do subject = RecursiveClosedStruct.new(one: { two: "three" }) assert subject.one.include?(:two) end end end
true
72f9bcc8d2a8267aa071d0d5e2323d3fe4b26836
Ruby
airhorns/acm
/lib/electric_fence_solver.rb
UTF-8
595
3.5
4
[]
no_license
class ElectricFenceSolver def initialize(exit) @exit = exit.to_i end def solve self.find_routes(0, 0) + 1 end def find_routes(x, y) count = 0 both_options = true if self.valid_move?(x+1, y) count += self.find_routes(x+1, y) else both_options = false end if self.valid_move?(x, y+1) count += self.find_routes(x, y+1) else both_options = false end count += 1 if both_options count end def valid_move?(x, y) return false if x > @exit || y > @exit return false if x > y return true end end
true
4bc2151e58b64bfcc312b65f88d1a4f5b9b78831
Ruby
SebastianN97/first-ruby
/flow_control.rb
UTF-8
135
3.296875
3
[]
no_license
if 2 + 2 == 4 puts "Correct!" else puts "Uh oh, something very wrong." end #Class class House end house = House.new end
true
484d79f5777de4678ac1972e6dae770bca30fdb2
Ruby
oolzpishere/qy_jiudian_customer
/components/admin/lib/admin/processed_order.rb
UTF-8
2,418
2.734375
3
[ "MIT" ]
permissive
require_relative 'processed_payment' module Admin class ProcessedOrder attr_reader :order, :nothing_obj, :room_type_eng_name, :hotel, :room_type, :hotel_room_type, :processed_payment def initialize(order) @order = order @room_type_eng_name = order.room_type @hotel = order.hotel @room_type = Product::RoomType.find_by(name_eng: order.room_type) @hotel_room_type = Product::HotelRoomType.find_by(hotel_id: hotel.id, room_type_id: room_type.id) set_room_type_details end def get_data(request, type: nil) if type # get_type_data(request, type) else base_getter(request) end end def base_getter(request) if self.try(request) self.send(request) elsif order.try(request) order.send(request) else nil end end # def get_type_data(request, type) # type_obj = get_type_obj(type) # if type_obj # type_obj.send(request) # else # return nil # end # end # # def get_type_obj(type) # case type # when /payment/ # if order.payment # @processed_payment = Admin::ProcessedPayment.new(order.payment) # return @processed_payment # end # else # return nil # end # end ######################################## # data ######################################## def set_room_type_details # TODO: delete bed file. class_eval <<-METHODS, __FILE__, __LINE__ + 1 def #{room_type_eng_name} 1 end def #{room_type_eng_name}_price order.price.to_f end def #{room_type_eng_name}_settlement_price hotel_room_type.settlement_price.to_f end METHODS end def actual_settlement price_str = room_type_eng_name + "_settlement_price" self.send(price_str) * nights end def nights @nights ||= (order.checkout-order.checkin).to_i end def total_price # 单价 * 天数 @total_price ||= order.price * nights end def profit @profit ||= total_price - actual_settlement end def tax_rate @tax_rate ||= hotel.tax_rate end def tax_point @tax_point ||= hotel.tax_point end def actual_profit @actual_profit ||= profit - (profit * tax_rate) end end end
true
97693831b827fd05945025ec88b0feaa340c81b6
Ruby
rhoen/rails_lite
/lib/phase5/params.rb
UTF-8
1,671
3.203125
3
[]
no_license
require 'uri' module Phase5 class Params # use your initialize to merge params from # 1. query string # 2. post body # 3. route params # # You haven't done routing yet; but assume route params will be # passed in as a hash to `Params.new` as below: attr_accessor :params def initialize(req, route_params = {}) query_str = req.query_string.to_s body_str = req.body.to_s @params = {}.merge!(route_params) parse_www_encoded_form(query_str + body_str) end def [](key) params[key.to_s] end def to_s params.to_json.to_s end class AttributeNotFoundError < ArgumentError; end; private # this should return deeply nested hash # argument format # user[address][street]=main&user[address][zip]=89436 # should return # { "user" => { "address" => { "street" => "main", "zip" => "89436" } } } def parse_www_encoded_form(www_encoded_form) return if www_encoded_form.nil? query_pairs = URI::decode_www_form(www_encoded_form) query_pairs.each do |pair| keys = parse_key(pair[0]) query_value = pair[1] if keys.size == 1 params[keys[0]] = query_value next end params[keys.shift] = nest_hashes(keys, query_value) end end # this should return an array # user[address][street] should return ['user', 'address', 'street'] def parse_key(key) key.split(/\]\[|\[|\]/) end def nest_hashes(key_arr, val) if key_arr.size == 1 return {key_arr[0] => val} end {key_arr[0] => nest_hashes(key_arr[1..-1], val)} end end end
true
3359b42860ae76dfb46b5f2d435bac96e76674d7
Ruby
ThoughtGang/BGO
/lib/bgo/address.rb
UTF-8
9,145
2.984375
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env ruby # :title: Bgo::Address =begin rdoc BGO Address object Copyright 2013 Thoughtgang <http://www.thoughtgang.org> An address can contain structured data, an instruction, or raw bytes. =end require 'bgo/image' require 'bgo/instruction' require 'bgo/model_item' module Bgo =begin rdoc A definition of an address in an Image (e.g. the contents of a File or Process). Note that the contents of the address determine its properties, e.g. the type of address (code or data), what it references, etc. TODO: handle references TO address. This is the base class for Address objects. It also serves as an in-memory object when there is no backing store. =end class Address extend Bgo::ModelItemClass include Bgo::ModelItemObject =begin rdoc The address contains an Instruction object. =end CONTENTS_CODE = :code =begin rdoc The address contains a data object (pointer, variable, etc) =end CONTENTS_DATA = :data =begin rdoc The address contains no content object, i.e. just raw bytes. =end CONTENTS_UNK = :unknown =begin rdoc An ImageChangeset::ImageAccessor wrapper for the Image containing the bytes. =end attr_reader :image =begin rdoc Offset of address in image. =end attr_reader :offset =begin rdoc Load address (VMA in process, offset in file). =end attr_reader :vma =begin rdoc Size (in bytes) of address. =end attr_reader :size =begin rdoc Contents of Address (e.g. an Instruction object). =end attr_reader :contents_obj =begin rdoc Names (symbols) applied to the address or its contents. This is a hash of id-to-name mappings: :self => name of address or nil 0 => name to use in place of first operand 1 => name to use in place of second operand ...etc. Storing the names in-address (and applying them to operands) removes the need for explicit scoping. =end # In Git: if n.to_i.to_s == n, name = n else name = n.to_sym attr_reader :names =begin rdoc An Array of Reference objects. =end attr_reader :references # ---------------------------------------------------------------------- def self.dependencies # TODO: static instruction definitions [to save mem] [ Bgo::Image ] # Bgo::Instruction end # TODO: child iterators e.g. code data # ---------------------------------------------------------------------- def initialize( img, offset, size, vma=nil, contents=nil ) @image = img # Note : this allows @image to be nil @offset = offset @size = size @vma = vma || offset @contents_obj = contents @names = {} @references = [] modelitem_init end alias :ident :vma def self.ident_str(vma) "0x%02X" % vma end def ident_str self.class.ident_str(vma) end =begin rdoc Convenience function that returns the load address (VMA) of the last byte in the Address. An Address is a sequence of bytes from vma to end_vma. =end def end_vma vma + size - 1 end =begin rdoc Return String of (binary) bytes for Address. This uses @container#[] =end def raw_contents (image || [])[offset,size] end =begin rdoc Iterator over raw_contents =end def bytes raw_contents.bytes end =begin rdoc Return contents of Address, or bytes in address if Contents object has not been set. =end def contents contents_obj || raw_contents end def contents=(obj) @contents_obj = obj end =begin rdoc Nature of contents: Code, Data, or Unknown. This saves an awkward comparison on contents.class for what is a commonly-performed operation. =end def content_type return CONTENTS_UNK if not contents_obj (contents_obj.kind_of? Bgo::Instruction) ? CONTENTS_CODE : CONTENTS_DATA end =begin rdoc Return true if argument is a valid content type. =end def self.valid_content_type?(str) sym = str.to_sym [CONTENTS_UNK, CONTENTS_CODE, CONTENTS_DATA].include? sym end =begin rdoc Return true if Address contains an Instruction object. =end def code? content_type == CONTENTS_CODE end =begin rdoc Return true if Address is not code. =end def data? content_type != CONTENTS_CODE end def name(ident=:self) self.names[ident] end def set_name(ident, str) # Note: git impl overrides this method, so '@' must be used, not 'self.' @names[ident] = str end def name=(str) add_name(:self, str) end def add_ref_to(vma, access='r--') # TODO # ref = ReferenceToAddress.new(vma, access) # self.references << ref # add_ref_from ? end def add_ref_from(vma, access='r--') # TODO # ditto end # ---------------------------------------------------------------------- def image=(img) raise "Invalid Image #{img.class.name}" if (! img.respond_to? :[]) @image = img end =begin rdoc Return (and/or yield) a contiguous list of Address objects for the specified memory region. addrs is a list of Address objects defined for that region. image is the Image object containing the bytes in the memory region. load_addr is the VMA of the Image (vma for Map, or 0 for Sections). offset is the offset into Image to start the region at. length is the maxium size of the region This is used by Section and Map to provide contiguous lists of all Addresses they contain. =end def self.address_space(addrs, img, load_addr, offset=0, length=0) # this method could use some refactoring, maybe into a standalone # address_space object that gets built from a PatchableByte container list = [] length = (img.size - offset) if length == 0 prev_vma = load_addr + offset prev_size = 0 addrs.each do |a| prev_end = prev_vma + prev_size if prev_end < a.vma # create new address object addr = Bgo::Address.new(img, prev_end - load_addr, a.vma - prev_end, prev_end) yield addr if block_given? list << addr end yield a if block_given? list << a prev_vma = a.vma; prev_size = a.size end # handle edge cases if list.empty? # handle empty list addr = Bgo::Address.new(img, offset, length, load_addr) yield addr if block_given? list << addr else # handle empty space at end of section last_vma = list.last.vma + list.last.size max_vma = load_addr + offset + length if last_vma < max_vma addr = Bgo::Address.new(img, last_vma - load_addr, max_vma - last_vma, last_vma) yield addr if block_given? list << addr end end list end # ---------------------------------------------------------------------- def to_s # TODO: contents-type, flags, etc "%08X (%d bytes)" % [vma, size] end def inspect # TODO: bytes or contents "%08X %s, %d bytes" % [vma, content_type.to_s, size] end def hexdump hex = [] bytes.each { |b| hex << "%02X" % b } hex.join(" ") end =begin rdoc Return an ASCII representation of the address contents. This will invoke Address#contents.ascii, if the contents object provides it. Otherwise, Address#hexdump is invoked. =end def ascii (@contents_obj.respond_to? :ascii) ? @contents_obj.ascii : hexdump end =begin rdoc Return contents of Address as an encoded String. Example: addr.to_encoded_string(Encoding:UTF-8) =end def to_encoded_string(encoding=Encoding::ASCII_8BIT) raw_contents.dup.force_encoding(encoding) end def to_core_hash { :size => @size, :vma => @vma, :offset => @offset, # Note: content_type is not de-serialized but it is nice to have in JSON :content_type => self.content_type }.merge(to_modelitem_hash) end def to_hash to_core_hash.merge( { :contents => (@contents_obj ? @contents_obj.to_hash : nil) # TODO: names # TODO: references }) end alias :to_h :to_hash def fill_from_hash(h) fill_from_modelitem_hash h # self.image is nil or Bgo::Image # instantiate contents based on type self.contents = AddressContents.from_hash(h) # TODO: names bindings # TODO: references self end # TODO: determine if proj is needed for any instantiation besides Image def self.from_hash(h, img=nil) return nil if (! h) or (h.empty?) self.new( img, h[:offset].to_i, h[:size].to_i, h[:vma].to_i ).fill_from_hash(h) end protected def contents_obj=(obj) @contents_obj = obj end end =begin rdoc Reference to an Address. This encodes the address map, vma, and changeset. =end class AddressRef # TODO: reference type? e.g. read, write, exec attr_reader :map, :vma, :changset def initialize(map, vma, cs=map.current_changeset) @map = map @vma = vma @changeset = cs end def address map.address(vma, changeset) end end end
true
1a0f4bc660626eac8951befebc6233949e6e742b
Ruby
phddoom/scripts
/mympd.rb
UTF-8
653
3.140625
3
[]
no_license
require 'socket' require 'io/wait' class MPD attr_reader :socket def initialize @socket = TCPSocket::new "localhost", 6600 @socket.sync = true puts @socket.gets end def send_command command @socket.puts command status = nil response = "" until status while @socket.ready? tmp = @socket.gets status = :OK if tmp =~ /OK/ status = :ACK if tmp =~ /ACK/ response << tmp end end parse_response response, status end def parse_response response, type case type when :OK response when :ACK response else response end end end
true
89395c64f871df4fcc68b9793d29287fc2b663f7
Ruby
Lyforth/Some-ruby-projects
/project-09/project-09.ruby
UTF-8
501
3.671875
4
[]
no_license
#Importamos as gems necessárias para o nosso projeto require 'cpf_cnpj' require 'rainbow' #Pedimos que o usuário informe seu CPF print 'Digite seu CPF: ' cpf = gets.chomp.to_i #Criamos um método para verificar se o CPF é válido ou não def verify_cpf(cpf) if CPF.valid?(cpf) puts "-" * 15 + "\nCPF: " + Rainbow("Válido\n").green + "-" * 15 else puts "-" * 15 + "\nCPF: " + Rainbow("Inválido\n").red + "-" * 15 end end #Aqui nós chamamos o metodo verify_cpf(cpf)
true
b153a01043dac6f65d8d5d645f055396197720b8
Ruby
timcharper/misc-tools
/bin/git-treesame-commit
UTF-8
612
2.625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require "misc-tools/treesame_commit.rb" args = [] merge = false force = false usage = "usage: git-treesame-commit [--merge, --force] <ref> given a ref, git-treesame-commit <ref> will create a new merge commit that has the exact same treehash as the given ref on your current branch. if --merge is provided, <ref> is added as a parent commit." ARGV.each do |arg| if arg == "--help" abort usage elsif arg == "--merge" merge = true elsif arg == "--force" force = true else args << arg end end abort usage if args.size != 1 make_treesame args[0], merge, ".", force
true
dd6a110edbab76012b537c26616bc8bc64e84e58
Ruby
Pratt0923/data_verification_tool
/app/models/QA_LIST.rb
UTF-8
3,267
2.53125
3
[]
no_license
class QA_LIST attr_accessor :programming_grid, :qa_list_headers, :qa_list, :correct_row def initialize(programming_grid) @programming_grid = programming_grid end def sanitize_qa_list qa_row = self.qa_list_headers qa_data = self.correct_row mv_keep = [ "CUST_NO", "FIRST_NAME", "LAST_NAME", "ADDR_LINE_1", "ADDR_LINE_2", "ADDR_LINE_3", "ADDR_LINE_4", "ADDR_LINE_5", "POSTAL_CODE", "MERGE_VAR_2", "MERGE_VAR_3", "MERGE_VAR_5", "MERGE_VAR_10", "MERGE_VAR_11", "MERGE_VAR_12", "MERGE_VAR_13", "MERGE_VAR_14", "MERGE_VAR_15" ] data = [] headers = [] qa_row.each do |item| if mv_keep.include?(item) && !qa_data[qa_row.index(item)].nil? data.push(qa_data[qa_row.index(item)]) headers.push(item) end end return headers, data end def merge_variables(sheet, string_include, cust_number, email_sheet) current_row = 0 tab = [] all_merge_variables = [] until current_row == @programming_grid.qa_list.last_row + 1 do tab.push(sheet.row(current_row)) if tab.flatten.include?(string_include) all_merge_variables.push(sheet.row(current_row)) # break if ((sheet.row(current_row).all? &:blank?) == true) end if cust_number if (sheet == email_sheet) && (@programming_grid.qa_list.row(current_row).include?(cust_number.captures.first)) @correct_row = @programming_grid.qa_list.row(current_row) @qa_list_headers = @programming_grid.qa_list.row(1) end end current_row += 1 end return all_merge_variables end def clean_parameters(params) if params[:Version] then params[:Version].reject! { |c| c.empty? } end if params[:MERGE_VAR_2] then params[:MERGE_VAR_2].reject! { |c| c.empty? } end if params[:MERGE_VAR_3] then params[:MERGE_VAR_3].reject! { |c| c.empty? } end if params[:MERGE_VAR_5] then params[:MERGE_VAR_5].reject! { |c| c.empty? } end if params[:MERGE_VAR_10] then params[:MERGE_VAR_10].reject! { |c| c.empty? } end if params[:MERGE_VAR_11] then params[:MERGE_VAR_11].reject! { |c| c.empty? } end if params[:MERGE_VAR_12] then params[:MERGE_VAR_12].reject! { |c| c.empty? } end if params[:MERGE_VAR_13] then params[:MERGE_VAR_13].reject! { |c| c.empty? } end if params[:MERGE_VAR_14] then params[:MERGE_VAR_14].reject! { |c| c.empty? } end params.reject! { |t| params[t].empty? } params.reject! { |t| (t == "utf8") || (t == "authenticity_token") || (t == "commit") || (t == "controller") || (t == "action")} return params end def make_new_qa_list_and_clean headers, data = self.sanitize_qa_list data.reject! { |c| c.empty? } qa_list = Hash[headers.zip(data)] return self, qa_list end def check_for_single_version_before_version_match(params, current_email) if params["Version"].include?("One Version") return "single version" end params = self.clean_parameters(params) pg_versions = [] params.each_pair do |key, value| if key != "Version" pg_versions.push(current_email.qa_list_data[key]) end end return pg_versions end end
true
411c0a17d5d0cf566088f23574e775115d3dee24
Ruby
srijangarg24398/shopping-website
/app/models/cart.rb
UTF-8
593
2.78125
3
[]
no_license
class Cart < ActiveRecord::Base belongs_to :user has_many :cart_items def self.calculate_sub_total_price cart_id new_sub_total_price=0 # byebug cart=Cart.find(cart_id) cart.cart_items.each do |cart_item| puts "khd" new_sub_total_price=new_sub_total_price+cart_item.total_price_item end return new_sub_total_price end def self.new_subtotal_price current_cart subtotal_price=calculate_sub_total_price(current_cart.id) total_price=subtotal_price newcrt={subtotal_price:subtotal_price,total_price:total_price} current_cart.update(newcrt) end end
true
826fc39182c4c596aaec5f9077a378ccb233166a
Ruby
ashfurrow/buggy
/slack-buggybot/commands/points.rb
UTF-8
903
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'slack-buggybot/models/event' require 'slack-buggybot/models/bug' module SlackBuggybot module Commands class Points < SlackRubyBot::Commands::Base def self.call(client, data, _match) user = client.users[data[:user]] event = Event.user_current_event(user_id: user.id) if event.nil? client.say(channel: data.channel, text: "You're not in any event. Join one with `buggy join`.") return end points = Bug.user_finished_bugs(user_id: user.id, event_id: event.id).count client.say(channel: data.channel, text: "You have #{points} #{points == 1 ? 'point' : 'points'} in #{event.name_from_client(client)}.") rescue StandardError => e client.say(channel: data.channel, text: "Sorry, an oop happened: #{e.message}.") STDERR.puts e.backtrace end end end end
true
5f181b8153aa89494f91cef8bfb7196d46ea0333
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz84_sols/solutions/Mustafa Yilmaz/pp_pascal.rb
UTF-8
2,147
3.578125
4
[ "MIT" ]
permissive
# Pascal's Triangle (Ruby Quiz #84) # by Mustafa Yilmaz # # This is the second Ruby program I've ever written and it's not optimized (and probably not # leveraging the power of Ruby), so don't expect to much ;-) The code should be self-explanatory, # if you have any questions though don't hesitate to ask me. # # My approach is to create a PDF file using the PDF::Writer libraries in order to get the # centering right. Furthermore, I'm computing the binomial coefficent as discussed before to # approximate the width of the largest number in the triangle. # # One could improve the program by dynamically adjusting the used text size to scale the text # depending on the size of the triangle to make use of the whole page size. # # You can download an example pdf file from http://www.mustafayilmaz.net/pascal.pdf # begin require 'pdf/writer' rescue LoadError => le if le.message =~ %r{pdf/writer$} $LOAD_PATH.unshift("../lib") require 'pdf/writer' else raise end end class Integer def factorial self <= 1 ? 1 : self * (self-1).factorial end end class Binomial_Coefficient def self.compute(n, r) n.factorial / (r.factorial * (n-r).factorial) end end class Pascal def self.create_pdf(lines, font_size, filename) max_width = Binomial_Coefficient.compute(lines, lines / 2).to_s.length + 2 pdf = PDF::Writer.new(:paper => "A4", :orientation => :landscape) pdf.select_font "Courier" pdf.text "Pascal's Triangle (Ruby Quiz #84)\n\n\n", :font_size => 10, :justification => :center previous_result = Array.[](0, 1, 0) s = "1".center(max_width) while lines > 0 do pdf.text "#{s}\n\n", :font_size => font_size, :justification => :center current_result = Array.new previous_result[0..-2].each_index do |i| current_result << previous_result[i] + previous_result[i+1] end s = String.new current_result.each_index do |i| s << current_result[i].to_s.center(max_width) end current_result = Array.[](0).concat(current_result) << 0 previous_result = current_result lines -= 1 end pdf.save_as(filename) end end Pascal.create_pdf(20, 8, "pascal.pdf")
true
ab637587f58261e554ea7ad394aaff318ed3fa95
Ruby
NStephenson/sinatra-mvc-lab-v-000
/models/piglatinizer.rb
UTF-8
525
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class PigLatinizer def piglatinize(word) if word[0][/[aeiouAEIOU]/] && word.length > 2 if word[/[aeiou]\z/] word[/[aeiou]\z/] + word = word word[0, word.length - 1] + "ay" else word + "ay" end elsif word.length > 2 word[/[aeiou]\w*\b/] + word[/\A[^aeiou]{1,2}/] + "ay" else word end end def to_pig_latin(string) pigged = [] string.split(" ").map do |word| pigged << piglatinize(word) end pigged.join(" ").strip end end
true
c0b60df28850eb5677cf417b4934e377ea82b41f
Ruby
pombreda/hn-scraper
/lib/hn_scraper.rb
UTF-8
2,462
2.546875
3
[ "MIT" ]
permissive
require "hn_scraper/version" require 'nokogiri' require 'rest-client' require 'open-uri' module HNScraper class << self def get_submit_fnid cookie headers = { "Cookie" => "user=#{cookie}" } doc = Nokogiri::HTML(RestClient.get("https://news.ycombinator.com/submit", headers)) fnid = doc.css("input[name='fnid']")[0][:value] end def valid_hn_cookie? cookie doc = Nokogiri::HTML(open("https://news.ycombinator.com/news", "Cookie" => "user=#{cookie}")) return !doc.css('.pagetop')[1].text.match("login") end def get_login_cookie username, password doc = Nokogiri::HTML(RestClient.get("https://news.ycombinator.com/newslogin")) fnid = doc.css("input[name='fnid']")[0][:value] login_params = {u: username, p: password, fnid: fnid} cookie = nil RestClient.post('https://news.ycombinator.com/y', login_params){ |response, request, result, &block| cookie = response.cookies["user"] # if [301, 302, 307].include? response.code # response.follow_redirection(request, result, &block) # else # response.return!(request, result, &block) # end } cookie end def post_to_hn username, password, title, url, body=nil cookie = get_login_cookie(username, password) fnid = get_submit_fnid(cookie) params = { fnid: fnid, t: title } headers = { "Cookie" => "user=#{cookie}", "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Content-Type" => "application/x-www-form-urlencoded", "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31", "Origin" => "https://news.ycombinator.com", "Host" => "news.ycombinator.com" } if body.empty? params[:u] = url else params[:x] = body end res = RestClient.post("https://news.ycombinator.com/r", params, headers){ |response, request, result, &block| if [301, 302, 307].include? response.code response.follow_redirection(request, result, &block) else response.return!(request, result, &block) end } end def newest_link newest = Nokogiri::HTML(open("https://news.ycombinator.com/newest")) hn_link = newest.css('.subtext')[0].css('a:last-child')[0][:href] end end end
true
b014607cb57f9215731ece0c16e01ee01f1adae1
Ruby
ruby-fatecsp/scripts-uteis
/verifica_notas.rb
ISO-8859-1
2,398
3
3
[]
no_license
#!/usr/bin/env ruby # encoding: iso-8859-1 require 'rubygems' require 'mechanize' require 'highline/import' require 'htmlentities' CONF_ARQ = __FILE__ + '-config.txt' # Mtodo para pedir as credenciais do usurio def get_credentials user = ask('matricula: ') pass = ask("senha: " ) { |c| c.echo = "*" } exit 1 if user.empty? or pass.empty? [user,pass] end # Mtodo para salvar as credenciais em arquivo def save_credentials(user,pass) if agree('salvar dados para consulta?') config = File.new(CONF_ARQ, 'w') config.puts "{\"#{user}\"}={\"#{pass}\"}" end end # Criando o arquivo de salvamento a no ser que ele no exista File.new(CONF_ARQ, 'w').close unless File.exist?(CONF_ARQ) # Lendo linhas do arquivo config = File.readlines(CONF_ARQ) # Espera um arquivo de uma linha s no formato {"matricula"}={"senha"} # Ele s executa se tiver uma linha no arquivo seno pede usurio e senha if config.size == 1 config.first.match(/\{"([0-9]*)"\}=\{"(.*)"\}/) user = $1 pass = $2 ### Solicita o nro da matricula e senha do site da FATEC-SP unless agree('usar dados da ultima consulta?') user,pass = get_credentials save_credentials(user,pass) end else user,pass = get_credentials save_credentials(user,pass) end exit 1 if user.empty? or pass.empty? ### inicializa o Mechanize browser = WWW::Mechanize.new uri = URI.parse('http://san.fatecsp.br') ### solicita a pgina page = browser.get uri ### pede, gentilmente, para o mechanize achar o formulrio de login login_form = page.form('login') ### seta os valores login_form.userid = user login_form.password = pass ### envia o formulrio page = browser.submit(login_form) ### solicita a pgina dos conceitos finais begin con_page = browser.click page.link_with(:href => "?task=conceitos_finais") rescue puts "Houve problemas com o link, ou no logou, ou o site est com problemas" exit 1 end ### Faz o parse da pgina conceitos = con_page.body dis_ary = conceitos.scan(/<td class="sigla"[^>]*>([^<]+)<\/td>/).flatten con_ary = conceitos.scan(/<td class="conceito"[^>]*>\s*\n([^\n]+)\n\s*<\/td>/m).flatten con_ary.map{|e| e.gsub!(/<[^>]+>/,'')} ### Escreve o Resultado coder = HTMLEntities.new dis_ary.each_with_index do |elem, i| puts "#{elem} => #{coder.decode(con_ary[i].strip)}" end ### desloga do site browser.click page.link_with(:text => "Logout") exit 0
true
ccd7fae58e5f500d57032a8e3e3dbc06b88e5351
Ruby
3vcloud/linodeapi
/lib/linodeapi/errors.rb
UTF-8
1,091
2.953125
3
[ "MIT" ]
permissive
module LinodeAPI ## # A standard HTTP error with an embedded error code class HTTPError < StandardError attr_reader :code def initialize(code, msg = 'HTTP Error encountered') @code = code super(msg) end end ## # A retryable error that has exceeded its max retries class RetriedHTTPError < HTTPError attr_reader :retries def initialize(code, retries, msg = nil) @retries = retries msg ||= "HTTP Error encountered (retried #{retries} times)" super(code, msg) end end ## # A retryable API error with embedded code and requested delay class RetryableHTTPError < HTTPError attr_reader :delay def initialize(code, delay, msg = 'Retryable HTTP Error encountered') @delay = delay.to_i super(code, msg) end end ## # An API error in the body of the HTTP response class APIError < StandardError attr_reader :action, :details def initialize(resp, msg = 'API Error encountered') @action = resp['ACTION'] @details = resp['ERRORARRAY'] super(msg) end end end
true
93ebb7ca91152b1a33f42032fc9b61739943a6bd
Ruby
jeevansrivastava/pusher-whos-in-gem
/lib/whos_in.rb
UTF-8
1,095
2.609375
3
[ "MIT" ]
permissive
require_relative "whos_in/version" require 'rufus-scheduler' module WhosIn class Application def self.launch_heroku_deploy puts "Launching deployment setup on Heroku... \n\n Input a name for your app (e.g. office_whos_in) then click the 'Deploy For Free' button. \n\nWhen you're done run 'pusher-whos-in run *your_app_name* " sleep 2 `open https://heroku.com/deploy?template=https://github.com/pusher/pusher-whos-in` end def self.tell_user_and_scan_network script = File.expand_path('../../bin/local_scanner', __FILE__) pusher_url = `heroku config:get PUSHER_URL -a #{@heroku_app}` puts "Scanning local network every 2 minutes and posting to #{@heroku_url}" puts "Press Ctrl+C to interrupt" `#{script} #{@heroku_url} #{pusher_url}` end def self.run_script tell_user_and_scan_network scheduler = Rufus::Scheduler.new scheduler.every '2m' { tell_user_and_scan_network } scheduler.join end def self.run_app app_name @heroku_app = app_name @heroku_url = "http://#{app_name}.herokuapp.com/people" self.run_script end end end
true
4007a77b2a93a2868889dff3e8c0abe0251c5a49
Ruby
mikaa123/trifling-whims
/source_file.rb
UTF-8
1,206
2.515625
3
[]
no_license
class SourceFile attr_accessor :content attr_accessor :metadata attr_accessor :outline def self.archive_list @archive_list ||= Dir.glob("posts/*.{markdown,md}").sort.reverse.collect do |filename| content = File.read(filename) content =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m title = YAML.load($1)["title"] [title, "/#{filename.gsub(/\..*?$/, "")}"] end end def self.archive_data @archive_data ||= Dir.glob("posts/*.md").sort.reverse.collect do |filename| content = File.read(filename) data = Metadown.render(content) title = data.metadata['title'] updated = data.metadata['date'] summary = data.output[0..200] + '...' ["http://sokolmichael.com/#{filename.gsub(/\..*?$/, "")}", title, updated, summary] end end def self.last_updated filename = Dir.glob("posts/*.{markdown,md}").sort.reverse.first filename =~ /\/(\d\d\d\d-\d\d-\d\d)/ Date.strptime($1).to_datetime.rfc2822 end def initialize(name) base = "posts" content = "" content = File.read(File.join(base, "#{name}.md")) data = Metadown.render(content) @content = data.output @metadata = data.metadata end end
true
7b55475c82a653b13d0ec2282f24af4c5677dc6a
Ruby
alloy-d/mimi
/qt/image_preview.rb
UTF-8
1,489
2.515625
3
[]
no_license
#!/usr/bin/env ruby require 'Qt4' class ImagePreview < Qt::GraphicsWidget @@max_width = 200 def initialize(path) super() @bg_color = Qt::Color.new(rand(255), rand(255), rand(255)) image = Qt::Image.new(path) @preview = image.scaled(@@max_width, @@max_width * 3/4, Qt::KeepAspectRatio, Qt::SmoothTransformation) self.setPreferredSize(@@max_width, @@max_width * 3/4) end def self.max_width @@max_width end def self.max_width=(new_max) @@max_width = new_max end def self.max_height @@max_width * 3/4 end def self.max_height=(new_max) @@max_width = new_max * 4/3 end def paint(painter, option, widget) painter.fillRect(self.contentsRect(), @bg_color) preview_image = @preview if ((self.contentsRect.width() < preview_image.width()) or (self.contentsRect.height() < preview_image.height())) preview_image = preview_image.scaled(self.contentsRect.width(), self.contentsRect.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation) end painter.drawPixmap((self.contentsRect.width() - preview_image.width())/2, (self.contentsRect.height() - preview_image.height())/2, Qt::Pixmap.fromImage(preview_image)) end end
true
d78fdefbd193f8791be5f56cf7736299b97afc28
Ruby
ajfigueroa/pug-bot
/lib/pug/list_action.rb
UTF-8
771
2.71875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Pug # Lists all the user defined actions class ListAction < Interfaces::Action # @param actions [Array<Interfaces::Action>] # user provided actions def initialize(actions) @actions = actions @enumerator = Action::Enumerator.new end # Action overrides # Override of {Interfaces::Action#name} # @return [String] def name 'list' end # Override of {Interfaces::Action#description} # @return [String] def description Strings.list_description end # Override of {Interfaces::Action#execute} # @return [String] def execute return Strings.no_actions if @actions.empty? @enumerator.names(@actions, true).join("\n") end end end
true
f3d3ba7a2bedcb8e09d9d2dc3d433acab18c5396
Ruby
njgheorghita/sorting_suite
/bubble_sort.rb
UTF-8
444
3.953125
4
[]
no_license
class BubbleSort def sort(array) # high-level looping high_level_count = 0 while high_level_count < array.length # low-level looping count = 0 array.drop(1).each do |e| if e < array[count] array[count], array[count+1] = array[count+1], array[count] count+=1 end end high_level_count+=1 end puts array end end sorter = BubbleSort.new sorter.sort(['d','b','a','c'])
true
5bc117f70d2764d9bc996c441d850e01ffc35ca6
Ruby
nomod/energy
/app/helpers/baskets_helper.rb
UTF-8
3,114
2.765625
3
[]
no_license
module BasketsHelper #смотрим сколько у текущего пользователя товаров в корзине def numbers_in_basket if !current_user.nil? #смотрим заказ текущего пользователя в статусе оформляется @order = Order.find_by(user_id: current_user.id, order_status_id: 1) #если у пользователя есть заказ в статусе оформляется if !@order.blank? #включаем счетчик @number = 0 #ищем все товары в заказе @basket = Basket.where(order_id: @order.id) #перебираем все товары в заказе и суммируем кол-во @basket.each do |num| @number = @number + num.number end @number #если у пользователя нет товаров в корзине else @basket = 'нет' end else unknown_remember_token = cookies[:unknown_remember_token].to_s #если есть токен неизвестного пользователя в куках if unknown_remember_token #поиск по токену в таблице заказов данного пользователя #выдергиваем из куки токен, шифруем его и ищем такой же в базе #to_s - нужен, если куки пустые unknown_remember_token = Digest::SHA1.hexdigest(cookies[:unknown_remember_token].to_s) #смотрим есть ли такой пользователь @unknown_user = Unknown_User.find_by(unknown_remember_token: unknown_remember_token) if @unknown_user #смотрим заказ текущего пользователя в статусе оформляется @unknown_order = Order.find_by(user_id: @unknown_user.id, order_status_id: 1) #если нашли заказ if @unknown_order #включаем счетчик @number = 0 #ищем все товары в заказе @basket = Basket.where(order_id: @unknown_order.id) #перебираем все товары в заказе и суммируем кол-во @basket.each do |num| @number = @number + num.number end #если у данного заказа есть товары(возможен вариант когда пользователь удалил все товары из заказа, а заказ остался) if @number != 0 @number #иначе else @basket = 'нет' end #если нет заказа else @basket = 'нет' end else @basket = 'нет' end #если пусто в куках else @basket = 'нет' end end end end
true
5b24da5e3f9f4812ad191f13c2535c6fe2b30793
Ruby
iExperience/fizzbuzz
/fizzbuzz.rb
UTF-8
759
4.1875
4
[]
no_license
# while the count is not yet 100 1.upto(100) do |number| #result = "" #result += "fizz" if (number % 3 == 0) #result += "buzz" if (number % 5 == 0) result = "#{"fizz" if (number % 3 == 0)}#{"buzz" if (number % 5 == 0)}" puts result == "" ? number : result # if result == "" # puts number # else # puts result # end # fizz = (number % 3 == 0) # buzz = (number % 5 == 0) # fizzbuzz = fizz && buzz # x = "fizz" # y = "buzz" # if fizzbuzz # puts x + y # elsif fizz # puts x # elsif buzz # puts y # else # puts number # end end # print "fizz" if it's a multiple of 3 # print "buzz" if it's a multiple of 5 # print "fizzbuzz" if it's a multiple of 3 and 5 # otherwise print the current number
true
86a4f169f309bf341129e1c3b196cc64220cd413
Ruby
yrmallu/bank-app
/app/services/transactions/perform.rb
UTF-8
1,496
2.65625
3
[]
no_license
module Transactions class Perform def initialize(amount, transaction_type, bank_account_id, recipient_id) @amount = amount.try(:to_f) @transaction_type = transaction_type @bank_account_id = bank_account_id @recipient_id = recipient_id @bank_account = BankAccount.where(id: bank_account_id).first @recipient_account = BankAccount.where(account_number: recipient_id).first end def create_transaction!(bank_account, amount, transaction_type, recipient_id) Transaction.create!( bank_account: bank_account, amount: amount, transaction_type: transaction_type, recipient_id: recipient_id ) bank_account.update(balance: bank_account.balance - amount) if transaction_type == 'withdraw' bank_account.update(balance: bank_account.balance + amount) if transaction_type == 'deposit' raise ActiveRecord::Rollback unless bank_account.present? end def execute! if %w[withdraw deposit].include?(@transaction_type) ActiveRecord::Base.transaction do create_transaction!(@bank_account, @amount, @transaction_type, @recipient_id) end elsif @transaction_type.eql? 'transfer' ActiveRecord::Base.transaction do create_transaction!(@bank_account, @amount, 'withdraw', @recipient_id) create_transaction!(@recipient_account, @amount, 'deposit', @bank_account.account_number) end end @bank_account end end end
true
789bd9dac499f14cb49fa10872cd17f388846bf0
Ruby
steph-meyering/aa_classwork
/w5d3/AA_Questions/user.rb
UTF-8
820
3.03125
3
[]
no_license
require_relative 'question_database' require_relative 'question' class User attr_accessor :id, :fname, :lname def self.find_by_id(id) hash_id = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM users WHERE id = ? SQL User.new(hash_id) end def self.find_by_name(fname, lname) hash_name = QuestionDatabase.instance.execute(<<-SQL, fname, lname) SELECT * FROM users WHERE fname = ? AND lname = ? SQL User.new(hash_name) end def initialize(hash) @id = hash[0]["id"] @fname = hash[0]["fname"] @lname = hash[0]["lname"] end def authored_questions Question.find_by_author_id(self.id) end def authored_replies Reply.find_by_user_id(self.id) end end
true
5b1393ac01950e18128c3b7d3332788e6e137939
Ruby
rshiva/MyDocuments
/01-notes-programming /04-ruby+rails/ruby1.9/samples/slshellwords_1.rb
UTF-8
628
3.15625
3
[]
no_license
#--- # Excerpted from "Programming Ruby", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information. #--- require 'shellwords' include Shellwords line = %{Code Ruby Be Happy!} shellwords(line) line = %{"Code Ruby" 'Be Happy'!} shellwords(line) line = %q{Code\ Ruby "Be Happy"!} shellwords(line) shelljoin(["Code Ruby", "Be Happy"]) #!to_s!
true
7ed72e669b7e3a30b1e2d7c6ef0fbf10f51bab88
Ruby
mur-wtag/toy-robot-simulator
/lib/toy/robot/simulator/mount.rb
UTF-8
1,528
2.890625
3
[ "MIT" ]
permissive
require 'toy/robot/simulator/commands' module Toy module Robot module Simulator class Mount include Simulator::Commands attr_reader :table_size def initialize(table_size=5, output=STDOUT) @table_size = table_size @output=output end def start(command) operation, operation_details = command.to_s.downcase.split ' ' operation_details = operation_details.split(',') if operation_details fail Simulator::Errors::InvalidCommand, 'Undefined operation!' unless Simulator::Commands.public_method_defined?(operation) public_send operation.to_sym, *operation_details rescue ArgumentError fail Simulator::Errors::InvalidCommand, 'Something went wrong!' end def start_reading_file(input_file_path) File.new(input_file_path).each_line do |line| begin start(line) rescue fail Simulator::Errors::InvalidCommand, 'File contains invalid commands!' end end end private def valid_position?(x, y, face) fail Simulator::Errors::InvalidCommand, 'Position is not valid!' unless x && y && face fail Simulator::Errors::InvalidCommand, 'You are placing outside of the table!' unless (0..table_size).include? x fail Simulator::Errors::InvalidCommand, 'You are placing outside of the table!' unless (0..table_size).include? y end end end end end
true
4c80bf50fd90e63d1934c7976f8af46e30ae9153
Ruby
Kirill-Petrovskiy/courses_ROR
/lesson_3_4_5_6/route.rb
UTF-8
466
3.03125
3
[]
no_license
class Route include InstanceCounter include ValidateStation attr_reader :stations def initialize(first_station, last_station) validate_count_station! @stations = {} @stations[first_station.name] = first_station @stations[last_station.name] = last_station register_instance end def add_station(station) self.stations[station.name] = station end def delete_station(station) self.stations.delete(station.name) end end
true
3b24b41c537e8609ff73610c0a788f12f14434ef
Ruby
lovenic/vaverka_db
/lib/db/insert.rb
UTF-8
2,554
2.921875
3
[]
no_license
module DB class Insert def self.call(key: nil, value: nil) new.insert(key: key, value: value) end def insert(key:, value:) return unless input_valid?(key: key, value: value) payload_to_write = payload(key: key, value: value) file_to_write = locate_file(payload: payload_to_write) open(file_to_write, 'a') do |f| f.seek(0, IO::SEEK_END) # save index to memory index_to_write = file_to_write.gsub(Config::DB::STORAGE_FILE_EXTENSION, Config::DB::INDEX_FILE_EXTENSION) if Index::HashMap.instance.offsets[index_to_write].nil? Index::HashMap.instance.offsets[index_to_write] = {} end Index::HashMap.instance.offsets[index_to_write][key] = f.pos f.puts "#{key},#{value}" end # flush to disk wiht 20% probability # NOTE: we won't have a index for some values # 'cause we restore it only for absent files Index::HashMap.save_to_disk if rand < 0.2 "Success" end private def input_valid?(key:, value:) if key.nil? || value.nil? puts "Error: key and value are needed" return false end return true end def locate_file(payload:) files = current_files if files.length.zero? # create 1.vdb file if none yet exist filename = "#{Config::DB::DB_NAME}/1#{Config::DB::STORAGE_FILE_EXTENSION}" FileUtils.touch(filename) filename else file = files.sort[-1] edge_file = "#{Config::DB::DB_NAME}/#{file}#{Config::DB::STORAGE_FILE_EXTENSION}" if allowed_to_write?(file: edge_file, payload: payload) # in case there's enough room to not exceed the limit edge_file else # when there's no space -> create new chunk and write there incremented_file = (file.to_i + 1).to_s filename = "#{Config::DB::DB_NAME}/#{incremented_file}#{Config::DB::STORAGE_FILE_EXTENSION}" FileUtils.touch(filename) filename end end end def current_files Dir .children("#{Config::DB::DB_NAME}") .select { |f| File.extname(f) == Config::DB::STORAGE_FILE_EXTENSION } .map{ |f| File.basename(f, File.extname(f)) } end def allowed_to_write?(file:, payload:) File.size(file) + payload_size(payload: payload) <= Config::DB::CHUNK_BYTE_LIMIT end def payload(key:, value:) "#{key},#{value}" end def payload_size(payload:) payload.bytesize end end end
true
ce716e2ac92bb8d194ca2db25001544417a47865
Ruby
sendhil/wordpress-github-alfred-workflow
/autocomplete.rb
UTF-8
2,081
3
3
[ "MIT" ]
permissive
require 'net/http' require 'json' require 'nokogiri' require 'fileutils' require 'date' def cache_data(data) FileUtils.mkdir_p "cached_data" File.write("./cached_data/github_repos", JSON.dump(data)) end def retrieve_cached_data return nil unless File.exist?("./cached_data/github_repos") data = File.read("./cached_data/github_repos") parsed_data = JSON.parse(data) return nil if parsed_data.length == 0 parsed_data end def is_cache_fresh? time = File.mtime("./cached_data/github_repos") (Date.parse(time.to_s) + 7) > Date.today end def retrieve_repos_from_github uri = URI.parse("https://api.github.com/orgs/wordpress-mobile/repos?per_page=100") response = Net::HTTP.get_response(uri) repos = JSON.parse(response.body) repos end def filter_repos_by_name(repos, repo_name) repos.select { |repo| repo["name"] =~ Regexp.new("#{repo_name}", Regexp::IGNORECASE) } end def sort_repos(repos) repos.sort { |l,r| l["name"] <=> r["name"] } end def generate_xml_for_alfred(repos, search_term = nil) builder = Nokogiri::XML::Builder.new do |xml| xml.send(:items) do repos.each do |repo| arg = search_term == nil ? repo["html_url"] : "#{repo['html_url']} #{search_term}" xml.item(:uid => repo["full_name"], :arg => arg, :autocomplete => repo["name"]) do xml.send(:title, repo["name"]) xml.send(:subtitle, repo["description"]) end end end end puts builder.to_xml end repo_name = nil search_term = nil if ARGV.length >= 2 query = ARGV[1] query_values = query.split(" ") repo_name = query_values[0] search_term = query_values.slice(1, query_values.length - 1).join(" ") if query_values.length > 1 else repo_name = ARGV[0] end repos = retrieve_cached_data # Reset Cache Every Week if repos != nil repos = nil unless is_cache_fresh? end if repos == nil repos = retrieve_repos_from_github cache_data(repos) end if ARGV.length == 0 repos = sort_repos(repos) else repos = filter_repos_by_name(repos, repo_name) end generate_xml_for_alfred(repos, search_term)
true
11fe4cdac10525f436dae2e39bdde466f346557b
Ruby
olook/olook
/app/presenters/showroom_presenter.rb
UTF-8
1,750
2.59375
3
[]
no_license
class ShowroomPresenter CATEGORIES_FOR_SHOWROOM = [ Category::CLOTH, Category::SHOE, Category::BAG, Category::ACCESSORY ] WHITELISTED_BRANDS = [ "OLOOK ESSENTIAL", "Olook Concept", "Olook" ] def initialize(args={}) @recommendation = args[:recommendation] @products_limit = args[:products_limit] || 22 @looks_limit = args[:looks_limit] || 4 @products = [] @cart = args[:cart] @promotion = Promotion.select_promotion_for(@cart) end def products fetched_products = fetch_products_in_each_category organize_fetched_products_in_category_sequence(fetched_products) @products.first(@products_limit) end def looks(opts = {}) @recommendation.full_looks({limit: @looks_limit, category: Category.without_curves, brand: WHITELISTED_BRANDS}.merge(opts)) end def look(opts={}) @look ||= looks({limit:1, brand: WHITELISTED_BRANDS}.merge(opts)).first end def retail_price_with_discount(product) psd = ProductDiscountService.new(product, cart: @cart, coupon: @cart.try(:coupon), promotion: @promotion) psd.final_price end private def fetch_products_in_each_category categories_for_showroom.map do |category_id| @recommendation.products(category: category_id, limit: @products_limit) end.flatten end def organize_fetched_products_in_category_sequence(fetched_products) categories_for_showroom.cycle do |category_id| break if fetched_products.empty? || @products.size >= @products_limit p = fetched_products.find { |_p| _p.category == category_id } if p @products.push(p) fetched_products.delete(p) end end end def categories_for_showroom CATEGORIES_FOR_SHOWROOM end end
true
5d4ce1ec9a545e9122ed9e4a88074da672aa961d
Ruby
jimlindstrom/InteractiveMidiImproviser
/music/lib/note_queue_meter_detection.rb
UTF-8
5,637
2.59375
3
[]
no_license
#!/usr/bin/env ruby # assumes it is included in NoteQueue module CanDetectMeter attr_accessor :tempo, :meter def detect_meter bsm = Music::BeatSimilarityMatrix.new(self.beat_array) bsm_diags = (1..20).map{ |i| { :subbeat=>i, :score=>bsm.geometric_mean_of_diag(i) } }.sort{ |x,y| y[:score] <=> x[:score] } $log.info "\t\tbsm_diags: #{bsm_diags.inspect.gsub(/, {/, "\n\t\t {")}" if $log return false if !detect_meter_period(bsm, bsm_diags) return false if (initial_beat_position = detect_initial_beat_position(bsm)).nil? set_beat_position_of_all_notes(initial_beat_position) return true end private def detect_meter_period(bsm, bsm_diags) confidence = bsm_diags[0][:score].to_f / bsm_diags[1][:score] if confidence < 2.0 $log.info "\t\tpeak-to-next-peak ratio (#{confidence}) is too low" if $log #return false end # note: this assumes that the meter can only be 2/4, 3/4 or 4/4 case subbeats_per_measure = bsm_diags[0][:subbeat] when 2 subbeats_per_beat = 1 # 2/4 (quarter note beats) beats_per_measure = subbeats_per_measure/subbeats_per_beat when 3 subbeats_per_beat = 1 # 3/4(quarter note beats) beats_per_measure = subbeats_per_measure/subbeats_per_beat when 4 if bsm.geometric_mean_of_diag(8) > 0.1*bsm.geometric_mean_of_diag(4) subbeats_per_beat = 2 # 4/4 (eighth note beats) beats_per_measure = 4 elsif bsm.geometric_mean_of_diag(16) > 0.05*bsm.geometric_mean_of_diag(4) subbeats_per_beat = 4 # 4/4 (eighth note beats) beats_per_measure = 4 else subbeats_per_beat = 1 # 4/4 (quarter note beats) beats_per_measure = 4 end when 6 subbeats_per_beat = 2 # 3/4 (eighth note beats) beats_per_measure = subbeats_per_measure/subbeats_per_beat when 8 if bsm.geometric_mean_of_diag(16) > 0.4*bsm.geometric_mean_of_diag(8) subbeats_per_beat = 4 # 4/4 (sixteenth note beats; strong tactus) beats_per_measure = 4 else subbeats_per_beat = 2 # 4/4 (eighth note beats) beats_per_measure = subbeats_per_measure/subbeats_per_beat end when 9 subbeats_per_beat = 3 # 3/4 (triplets) beats_per_measure = subbeats_per_measure/subbeats_per_beat when 12 if bsm.geometric_mean_of_diag(3) > bsm.geometric_mean_of_diag(4) subbeats_per_beat = 3 # 4/4 (triplets) beats_per_measure = subbeats_per_measure/subbeats_per_beat else if bsm.geometric_mean_of_diag(6) > 0.4*bsm.geometric_mean_of_diag(12) subbeats_per_beat = 2 # 3/4 (eighths; two measure phrases) beats_per_measure = 3 else subbeats_per_beat = 4 # 3/4 (sixteenths) beats_per_measure = subbeats_per_measure/subbeats_per_beat end end when 16 if bsm.geometric_mean_of_diag(8) > 0.05*bsm.geometric_mean_of_diag(16) subbeats_per_beat = 2 # 4/4 (eighths; two measure phrases) beats_per_measure = 4 else subbeats_per_beat = 4 # 4/4 (sixteenths) beats_per_measure = 4 end else $log.warn "\t\tunexpected subbeats_per_measure: #{bsm_diags[0][:beat]}" if $log return false end beat_unit = 4 $log.info "\t\tMeter.new(#{beats_per_measure}, #{beat_unit}, #{subbeats_per_beat})" if $log begin @meter = Music::Meter.new(beats_per_measure, beat_unit, subbeats_per_beat) rescue ArgumentError $log.warn "\t\tFailed to instantiate meter" if $log return false # if any of the params were bogus, just return and fail end return true end def detect_initial_beat_position(bsm) $log.info "\ttrying to detect initial beat position:" if $log correl_len = @meter.subbeats_per_measure ba = self.beat_array correls = [0.0]*correl_len (0..(ba.length-1)).each do |i| if !(cur_beat = ba[i]).nil? if (cur_note = cur_beat.cur_note).class == Music::Note correls[correl_len - 1 - ((correl_len -1 + i) % correl_len)] += cur_note.duration.val end end end correls = (0..(correls.length-1)).collect { |i| { :subbeat=>i, :score=>correls[i] } }.sort{ |x,y| y[:score]<=>x[:score] } $log.info "\t\tcorrels: #{correls.inspect.gsub(/, {/, "\n\t\t {")}" if $log initial_subbeat = correls[0][:subbeat] confidence = correls[0][:score].to_f / correls[1][:score] if confidence < 1.5 $log.info "\t\tConfidence (#{confidence}) about starting subbeat (#{initial_subbeat}) is too low" if $log initial_subbeat = 0 end b = Music::BeatPosition.new b.measure = 0 b.beats_per_measure = @meter.beats_per_measure b.subbeats_per_beat = @meter.subbeats_per_beat b.beat = initial_subbeat / @meter.subbeats_per_beat b.subbeat = initial_subbeat % @meter.subbeats_per_beat $log.info "\t\tinitial beat pos: #{b.inspect}" if $log return b end def set_beat_position_of_all_notes(initial_beat_position) beat_pos = initial_beat_position self.each do |n| n.analysis[:beat_position] = beat_pos.dup beat_pos.subbeat += n.duration.val while beat_pos.subbeat >= beat_pos.subbeats_per_beat beat_pos.beat += 1 beat_pos.subbeat -= beat_pos.subbeats_per_beat end while beat_pos.beat >= beat_pos.beats_per_measure beat_pos.measure += 1 beat_pos.beat -= beat_pos.beats_per_measure end end end end
true
f4ad85ba9be0471b40202737ec788dbbc879b334
Ruby
ben20262/cli-project
/lib/command_line_interface.rb
UTF-8
4,313
3.65625
4
[ "MIT" ]
permissive
class CommandLineInterface def run # directs the program puts "Please enter the url(s) that you want processed." puts "If entering multiple please seperate them with a comma and a space." puts "Enter exit at any time to exit the application." input = gets.strip array = input.split(", ") if input == "" puts "Please enter a url" run elsif input == "exit" return end array.each do |url| if url.include?("wikipedia.org") hash = Scraper.scrape_page(url) # scrapes the information and collects it into a hash name = Person.new(hash) # passes the hash to the Person class to create a new instance and document the data else puts "#{url} was not a valid entry. Please remove or fix this entry." # puts if the input is not a wikipedia url and repeats run run end end info end def info # accesses the information of the Person instances either alone or in tandem puts "What would you like to do?" if Person.all.size > 1 # skips if there is only one instance count = 1 Person.all.each do |person| # for selecting which person or all persons you would like information on name = person.name puts "To view information on #{name} enter #{count}." count += 1 end puts "To compare all persons enter #{count}." input = gets.strip index = input.to_i if input == "exit" return elsif index < 1 || index > count puts "This is not a valid selection." info elsif index == count var = compare if var == false return else info end else person = Person.all[index - 1] name = person.name end else person = Person.all.first name = person.name end count = 1 return if person == nil person_att = person.att_array person_att.each do |att| clean_name = att.att_name.to_s.split("_").join(" ").delete("@").capitalize # cleans variable names and utilizes them as information puts "To view information on #{name}'s #{clean_name} press #{count}." count += 1 end puts "To view all information on #{name} enter #{count}." input = gets.strip index = input.to_i if input == "exit" return elsif index < 1 || index > count puts "This is not a valid selection." info elsif index == count person.show_all info else choice = person_att[index - 1] end count = 0 choice.fact_array.each do |fact| count += 1 fact_clean = fact.to_s.split("_").join(" ").delete("@").capitalize puts "To view information on #{name}'s #{fact_clean} enter #{count}." end input = gets.strip index = input.to_i if input == "exit" return elsif index < 1 || index > count puts "This is not a valid selection." info else fact_key = choice.fact_array[index - 1] puts choice.instance_variable_get(fact_key) end info end def compare # uses the mutual class method of person to find mutual tags and offers the option of viewing them in tandem across person instances mutual = Person.mutual if mutual.size == 0 puts "There are no mutual tags." else mutual.each_index do |ind| potential_key = mutual[ind].split("_").join(" ").delete("@").capitalize puts "To compare information about #{potential_key} please enter #{ind + 1}." # puts mutual tags and numbers them for easy input end input = gets.strip index = input.to_i if input == "exit" return false elsif mutual.size >= index && index > 0 mutual_key = mutual[index - 1] key_name = mutual_key.split("_").join(" ").delete("@").capitalize Person.all.each do |person| m_value = "" p_name = person.name person.att_array.each do |att| if att.fact_array.include? (mutual_key) m_value = att.instance_variable_get(mutual_key).join(" ") end end puts "#{p_name}'s #{key_name} is #{m_value}" # puts value of mutual tag for each person instance end else "That is not a valid entry" end end end end
true
01478a84cbd1e114a6b16f08e90a13d73e3bb19e
Ruby
iambanklee/vending_machine
/lib/inventory.rb
UTF-8
482
3.09375
3
[]
no_license
# frozen_string_literal: true class Inventory attr_reader :items def initialize @items = {} end def increase(name:, stock:) items[name] ||= 0 items[name] += stock end def decrease(name:, stock:) items[name] ||= 0 items[name] -= stock end def stock_of(name) items[name] end def reload_stock(list) JSON.parse(list).each { |name, stock| increase(name: name, stock: stock) } items.select { |name, _stock| list[name] } end end
true
698ad94f9664e032a1fb81d7b3f64de5a29bf6f6
Ruby
dexterfgo/foosball
/app/models/player_result.rb
UTF-8
1,179
2.546875
3
[]
no_license
class PlayerResult < ApplicationRecord belongs_to :player, class_name: "Player", foreign_key: "playerid" belongs_to :game, class_name: "Game", foreign_key: "gameid" belongs_to :teammate, class_name: "Player", foreign_key: "teammate", optional: true belongs_to :opponent, class_name: "Player", foreign_key: "opponent", optional: true validates :game, presence: true scope :most_recent_first, -> { order created_at: :desc } scope :for_game, -> (game) { where(game: game) } scope :against, -> (player) { where(opponent: player) } scope :games_played, -> { distinct.pluck(:gameid).count } scope :wins, -> {where(won: true).games_played} scope :losses, -> {where(won: false).games_played} scope :team_with, -> (player) {where(teammate: player)} scope :linegraph, -> { distinct.group_by_day(:created_at, range: 1.weeks.ago.midnight..Time.now).count} scope :linegraph_wins, -> { where(won: true).distinct.group_by_day(:created_at, range: 1.weeks.ago.midnight..Time.now).count} scope :linegraph_losses, -> { where(won: false).distinct.group_by_day(:created_at, range: 1.weeks.ago.midnight..Time.now).count} def percent_of(n) self.to_f / n.to_f * 100.0 end end
true