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
94f250bf9ffb19a424d051d4ac75f06753af81f1
Ruby
aldazj/Platform_am_v11
/app/controllers/video_clip_steps_controller.rb
UTF-8
2,878
2.515625
3
[]
no_license
##################################### # Aldaz Jayro HEPIA # ##################################### class VideoClipStepsController < ApplicationController #On inclut la librarie Wicked include Wicked::Wizard #On définit les différents états qu'on va faire passer notre element video clip #L'ordre est important steps :thumbnail_page, :select_thumbnail_page #On affiche à chaque étape notre modèle video clip def show @video_clip = VideoClip.find(params[:video_clip_id]) case step when :thumbnail_page #Pour permettre ajouter des vignettes supplémentaires à notre model video clip @video_clip.thumbnails.build end render_wizard end #A chauqe étape on met à jour notre modèle video clip et tous les autres tables qui #intéragissent avec ce dernier. Par example la table Thumbnail def update @video_clip = VideoClip.find(params[:video_clip][:video_clip_id]) case step when :thumbnail_page if @video_clip.update_attributes(video_clip_params) redirect_to wizard_path(:select_thumbnail_page, :video_clip_id => @video_clip.id), notice: 'Videoclip was successfully upload.' end when :select_thumbnail_page #On met à true la vignette selectionnée pour représenter notre video clip. #Les autres vignettes sont à faux. select_thumbnail = 0 @video_clip.thumbnails.each do |thumbnail| if thumbnail.id == params[:main_thumbnail].to_i thumbnail.main_thumbnail = true select_thumbnail += 1 else thumbnail.main_thumbnail = false end end #Vérifie si on a choisi une vignette pour finir le processus qui #met à jour la table de notre modèle petit à petit. if select_thumbnail == 1 if @video_clip.update_attributes(video_clip_params) redirect_to_finish_wizard end else redirect_to wizard_path(:select_thumbnail_page, :video_clip_id => @video_clip.id) end end end private #On vérifie si tous les paramètres obligatoires sont présents def video_clip_params params.require(:video_clip).permit(:title, :description, :is_available, :date, :views, :videoitemclip, :videoclip_from_url, thumbnails_attributes: [:id, :image, :main_thumbnail, :_destroy], formatvideos_attributes: [:id, :format, :_destroy]) end #Quand on a fini le processus wicked, on va à la page principal où on trouve tous les video clips def redirect_to_finish_wizard respond_to do |format| format.html { redirect_to video_clips_path, notice: 'Videoitem was successfully created.'} end end end
true
888d01d50b198d4420f2619c73adb8bbe6e45068
Ruby
rafaeljcadena/estudos_rspec
/spec/matchers/classes/classes_spec.rb
UTF-8
504
2.875
3
[]
no_license
require 'string_nao_vazia' describe 'Matchers de classes' do it 'be_instance_of' do expect(10).to be_instance_of(Integer) # Exatamente a classe end it 'be_kind_of' do expect(10).to be_kind_of(Integer) # Pode ser herança end it 'be_a / be_an ' do str = StringNaoVazia.new expect(str).to be_an(String) expect(str).to be_an(StringNaoVazia) expect(str).to be_a(String) expect(str).to be_a(StringNaoVazia) end it 'respond_to' do expect('rafael').to respond_to(:size) end end
true
a340aa7ff97f60bebc4894a0e23af4903848d61e
Ruby
djekels-zz/infoblox
/lib/infoblox/connection.rb
UTF-8
1,368
2.625
3
[ "MIT" ]
permissive
module Infoblox class Connection attr_accessor :username, :password, :host, :connection, :logger, :ssl_opts def get(href, params={}) wrap do connection.get(href, params) end end def post(href, body) wrap do connection.post do |req| req.url href req.body = body.to_json end end end def put(href, body) wrap do connection.put do |req| req.url href req.body = body.to_json end end end def delete(href) wrap do connection.delete(href) end end def initialize(opts={}) self.username = opts[:username] self.password = opts[:password] self.host = opts[:host] self.logger = opts[:logger] self.ssl_opts = opts[:ssl_opts] end def connection @connection ||= Faraday.new(:url => self.host, :ssl => {:verify => false}) do |faraday| faraday.use Faraday::Response::Logger, logger if logger faraday.request :json faraday.basic_auth(self.username, self.password) faraday.adapter :net_http end end private def wrap yield.tap do |response| unless response.status < 300 raise Exception.new("Error: #{response.status} #{response.body}") end end end end end
true
be7056ca1ab91a467e1edec202457080808c06b7
Ruby
zeevex/evri_rpx
/lib/evri/rpx/credentials.rb
UTF-8
1,480
2.671875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Evri module RPX class Credentials def initialize(json) @json = json end # Returns the type of credentials: # (Facebook|OAuth|WindowsLive) # # Generally, you should use the helper methods such # as #facebook?, #oauth?, #windows_live? def type @json['type'] end # Returns true if these credentials are Facebook. def facebook? type == 'Facebook' end # Returns the Facebook session key. def facebook_session_key @json['sessionKey'] end # Returns when this Facebook session expires, as a Time # object. def facebook_expires Time.at(@json['expires'].to_i) end # Returns the UID for the authorized Facebook user. def facebook_uid @json['uid'] end # Returns true if these credentials are OAuth. def oauth? type == 'OAuth' end # Returns the OAuth token. def oauth_token @json['oauthToken'] end # Returns the OAuth token secret. def oauth_token_secret @json['oauthTokenSecret'] end # Returns true if these credentials are for Windows Live def windows_live? type == 'WindowsLive' end # Returns the Windows Live eact string, which contains the # user's delegated authentication consent token. def windows_live_eact @json['eact'] end end end end
true
6cd4ddc5a5147bc5c18ab8c98ecd0f860b89e831
Ruby
devlab-oy/pupenext
/app/models/concerns/searchable.rb
UTF-8
1,655
2.78125
3
[]
no_license
module Searchable extend ActiveSupport::Concern module ClassMethods def search_like(args = {}) raise ArgumentError, "should pass hash as argument #{args.class}" unless args.is_a? Hash result = self.all args.each do |key, value| if exact_search? value result = result.where key => exact_search(value) elsif value == "true" result = result.where key => true elsif value == "false" result = result.where key => false elsif value.is_a? Array result = result.where key => value else result = result.where_like key, value end end result end def where_like(column, search_term) table_column = column.to_s.split '.' raise ArgumentError if table_column.length > 2 if table_column.length == 2 table = Arel::Table.new table_column.first column = table_column.second else table = arel_table end # Enumns don't play well with Arel::Predications#matches, so this hack is necessary if column.to_s.in?(defined_enums) ordinal_value = defined_enums[column.to_s][search_term] return self unless ordinal_value return where(column => ordinal_value) end if columns_hash[column.to_s] && columns_hash[column.to_s].type.in?(%i[integer decimal]) return where(column => search_term) end where(table[column].matches("%#{search_term}%")) end private def exact_search(value) value[1..-1] end def exact_search?(value) value[0].to_s.include? "@" end end end
true
d2d85f3efdb31f1ccbf9b6dd2e793e816a3730b4
Ruby
mikennaji/ruby-music-library-cli-cb-000
/lib/ musicimporter.rb
UTF-8
315
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MusicImporter attr_accessor :path def initialize(path) @path = path end def files directory = Dir["#{self.path}/*"] directory.map do |file| file.slice!(self.path + "/") end return directory end def import self.files.each do |file| Song.create_from_filename(file) end end end
true
f5de47d505fb965436c290cf0c81dada59259f94
Ruby
MrPowers/battleship
/spec/board_spec.rb
UTF-8
700
3.359375
3
[]
no_license
require_relative "../board.rb" describe Board do let(:board) { Board.new } context "#grid" do it "creates a grid with 11 rows" do board.grid.count.should eq 11 end it "creates a grid with 11 columns" do board.grid.transpose.count.should eq 11 end it 'the first row of the grid is [" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]' do board.grid[0].should eq [" ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] end it "each row of the grid should start with 1-10" do board.grid.transpose[0].should eq [" "] + (1..10).to_a end it "sets and gets cells of the grid" do board.set_cell(4, 3, "Meow") board.get_cell(4, 3).should eq "Meow" end end end
true
7c4aee3ac8a7ffe07da6453c9bb76575c3a568b5
Ruby
mauricioszabo/gml2svg
/spec/svg_builder_spec.rb
UTF-8
1,008
2.59375
3
[]
no_license
require 'svg_builder' describe SVGBuilder do include SVGBuilder it 'deve ser possível criar um documento vazio' do svg = build_svg {} svg.should == "<?xml version='1.0' standalone='no'?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 20010904//EN' 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'> <svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'> </svg>" end it 'deve ser possível criar uma caixa' do svg = build_svg { caixa :x => 10, :y => 20, :altura => 50, :largura => 100, :fundo => 'yellow', :cor => 'blue', :linha => '2' } svg.should include("<rect") svg.should include("width='100'") svg.should include("stroke-width='2'") end it 'deve ser possível criar uma linha' do svg = build_svg { linha :x1 => 10 } svg.should include("<line x1='10'/>") end it 'deve ser possível criar um texto' do svg = build_svg { texto("Algo", :x => 10) } svg.should include("<text x='10'>Algo</text>") end end
true
d85978dff7e54519868cb45e24b7712a65d32e1c
Ruby
deleyla/kid2camp
/app/controllers/families_controller.rb
UTF-8
2,277
2.734375
3
[]
no_license
class FamiliesController < ApplicationController # get all families from my database def index families = Family.all p "Hello i'm about to print where the user is" p current_family # if current_family # families = current_user.families # render json: families.as_json # else # render json: [] render json: families.as_json # end end # grab a single family from my database based on the id def show family = current_family p current_family render json: family.as_json end # make a new instance of family in the database def create p params family = Family.new( first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password], phone_number: params[:phone_number], street_address: params[:street_address], secondary_address: params[:secondary_address], city: params[:city], state: params[:state], zip_code: params[:zip_code], photo: params[:photo]) # save the information from user input to create a new family. family.save! if family.save! render json: family.as_json else render json: {errors: family.errors.full_messages} end end # update a family's information def update # go to params hash and get the id the_id = params['id'] # grab a single family based on the id family = Family.find_by(id: the_id) # update it if family.update!( first_name: params[:first_name], last_name: params[:last_name], email: params[:email], password: params[:password], phone_number: params[:phone_number], street_address: params[:street_address], secondary_address: params[:secondary_address], city: params[:city], state: params[:state], zip_code: params[:zip_code], photo: params[:photo]) render json: family.as_json else render json: {errors: family.errors.full_messages} end end # destroy a family def destroy #find a particular family in my database id = params['id'] family = Family.find_by(id: id) #destroy the selected family family.destroy render json: {message: "You deleted the family"} end end
true
62aeb242e67e797c131e668d7f7f14a3afbef51c
Ruby
jeffreyyyy/Ruby_Connect
/spec/models/admin_spec.rb
UTF-8
1,690
2.640625
3
[]
no_license
require 'spec_helper' describe Admin do before(:each) do @attr = { :name => "Jeffrey Jurgajtis", :email => "jeffrey@example.com" } end it "should create a new instance given a valid attribute" do Admin.create!(@attr) end it "should require a name" do no_name_admin = Admin.new(@attr.merge(:name => "")) no_name_admin.should_not be_valid end it "should require an email address" do no_email_admin = Admin.new(@attr.merge(:email => "")) no_email_admin.should_not be_valid end it "should reject names that are too long" do long_name = "a" * 51 long_name_admin = Admin.new(@attr.merge(:name => long_name)) long_name_admin.should_not be_valid end it "should accept valid email addresses" do addresses = %w[jeff@jeff.com JEFF_JEFF@jeff.jeff.com first.last@jeff.com] addresses.each do |address| valid_email_admin = Admin.new(@attr.merge(:email => address)) valid_email_admin.should be_valid end end it "should reject invalid email addresses" do addresses = %w[jeff@jeff,com jeff_at_jeff.com jeff.jeffrey@com.] addresses.each do |address| invalid_email_admin = Admin.new(@attr.merge(:email => address)) invalid_email_admin.should_not be_valid end end it "should reject duplicate email addresses" do Admin.create!(@attr) admin_with_duplicate_email = Admin.new(@attr) admin_with_duplicate_email.should_not be_valid end it "should reject email addresses identical up to case" do upcased_email = @attr[:email].upcase Admin.create!(@attr.merge(:email => upcased_email)) admin_with_duplicate_email = Admin.new(@attr) admin_with_duplicate_email.should_not be_valid end end
true
6a47c10c7c871b4c4463339f6f397ed52e4e2f6a
Ruby
radiodan-archive/frankenpins
/scratch/interrupt.rb
UTF-8
314
2.703125
3
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
require 'bundler/setup' require 'wiringpi2' INPUT = 0 PUD_UP = 2 INT_EDGE_BOTH = 3 pin = 0 io = WiringPi::GPIO.new io.pin_mode(pin,INPUT) io.pullUpDnControl(pin, PUD_UP) io.wiringpi_isr(pin, INT_EDGE_BOTH) do puts "in block" end puts "before while" while (true) puts io.digital_read(pin) sleep(0.5) end
true
0bc62612f06a6e353bc30c61b696cb1202732de5
Ruby
ercekal/bank-account-tt
/lib/account.rb
UTF-8
544
3.453125
3
[]
no_license
require_relative './log.rb' require_relative './transaction.rb' class Account attr_reader :balance, :log def initialize(log = Log.new) @balance = 0 @log = log end def deposit(number) @balance += number @log.add_to_log(number, @balance) end def withdraw(number) if @balance >= number @balance -= number @log.add_to_log(-number, @balance) else "You don't have enough funds" end end def print puts "date || credit || debit || balance" @log.log.each { |x| puts x } end end
true
fb375884998c6f83a63c80b30c52e3b644db2240
Ruby
clayton/ofcp_scoring
/lib/ofcp_scoring/organized_hand.rb
UTF-8
802
2.90625
3
[ "MIT" ]
permissive
class OfcpScoring::OrganizedHand include Enumerable def initialize(organized_hand) @hand = organized_hand end def ranks @hand[:ranks] end def sequences ranks = @hand[:ranks].reverse prev = ranks[0] ranks.slice_before { |cur| prev, prev2 = cur, prev prev2 - 1 != prev }.to_a end def suits @hand[:suits] end def two_cards_match? @hand[:two_cards_match] end def two_different_cards_match? @hand[:two_different_cards_match] end def three_cards_match? @hand[:three_cards_match] end def four_cards_match? @hand[:four_cards_match] end def all_suits_match? @hand[:all_suits_match] end def ranks_in_order? @hand[:ranks_in_order] end def three_card_hand? @hand[:three_card_hand] end end
true
b1d52b3829d536291a2fbb09d6453d96baddb990
Ruby
daveadams/sakai-info
/lib/sakai-info/hacks.rb
UTF-8
1,312
2.84375
3
[ "LicenseRef-scancode-public-domain", "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# hacks.rb # Hacks necessary to work around problems in external libraries # # Created 2012-05-20 daveadams@gmail.com # Last updated 2012-10-05 daveadams@gmail.com # # https://github.com/daveadams/sakai-info # # This software is public domain. # ###################################################################### # extensions to other objects class String def is_uuid? self =~ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i end end # terrible hack to work around mysql case issues # essentially, if the hash key asked for is a symbol and its value is # nil, then try again with the uppercased version of the symbol # this might cause problems in weird cases with other hashes, this is # definitely not a sustainable fix. # TODO: patch Sequel for case-insensitive/-fixed identifiers class Hash alias :original_brackets :[] def [](key) if not (value = original_brackets(key)).nil? return value else if key.is_a? Symbol return original_brackets(key.to_s.upcase.to_sym) else return nil end end end end # alias .to_s on Blob class to match OCI8 blob class's read method module Sequel module SQL class Blob alias :read :to_s end end end # hack to get clobs in sqlite to work correctly class String def read self end end
true
930ade4be4f6c0c7b4204654fd78ff66ab8068ed
Ruby
k16shikano/isbn.rb
/test-isbn.rb
UTF-8
354
2.78125
3
[]
no_license
require 'test/unit' require 'isbn' class TC_ISBN < Test::Unit::TestCase def setup @sicp = ISBN.new("0262011530") @sicp13 = 9780262011532.to_isbn @sicpj = 9784894711631.to_isbn end def test_sicp assert_equal(@sicp13, @sicp.isbn13) end def test_sicpj assert_equal("4 89471 163 X", @sicpj.isbn10.to_s(1,5,3," ")) end end
true
b984b31ca0d8c4ad7be44b0df742978974934152
Ruby
murayama/qiita_hackathon
/ruby/ranking_items.rb
UTF-8
604
2.65625
3
[]
no_license
require File.join(File.expand_path('../', __FILE__), 'qiita') class RankingItems < Base def execute followees = @client.list_user_followees(@current_user['id'], page: 1, per_page: 100).body followees << @current_user followees = followees.sort{|a,b| b['items_count'] <=> a['items_count']} msg = [] followees.each do |user| if user['id'] == @current_user['id'] msg << "(goldstar) #{user['id']} #{user['items_count']}" else msg << "#{user['id']} #{user['items_count']}" end end msg.join("\n") end end puts RankingItems.new.execute
true
6041ed04bc3fbace110e2c78ac93dd0c8701b252
Ruby
nkoehring/rails-batchquery
/batch_query.rb
UTF-8
1,416
2.703125
3
[]
no_license
# encoding: utf-8 class BatchQuery attr_reader :columns include Enumerable def initialize(table, fields, batch_size=10, conn=nil) @table = table # Is fields a string? I want an array! if fields.respond_to? "join" @fields = fields @fields_str = fields.join(",") else @fields = fields.split(",") @fields_str = fields end @batch_size = batch_size @last_id = 0 @conn = conn || ActiveRecord::Base.connection rescue nil raise AttributeError.new("A connection adapter is obligatory!") if @conn.nil? @columns = @conn.columns(@table).collect{|c| c.name.to_sym} @idx = @columns.index(:id) end def query_string op = @last_id>0 ? ">" : ">=" "select #{@fields_str} " + "from #{@table} " + "where (id #{op} #{@last_id}) " + "order by id asc " + "limit #{@batch_size}" end def each loop do rows = self.next raise StopIteration if rows.length == 0 yield rows end end def first if @last_id > 0 tmp = @last_id reset r = self.next @last_id = tmp else r = self.next end r end def reset @last_id = 0 end def next result = @conn.exec_query(query_string) rows = result.rows @last_id = rows.last[@idx] if rows.last rows end def reverse_each raise NotImplementedError end end
true
77bb45394e82ed638c352dba082a3ecea7237c95
Ruby
rotyflo/appacademy
/ruby/projects/recursion/deep_dup.rb
UTF-8
596
3.859375
4
[]
no_license
class Array def deep_dup dup_arr = [] self.each do |ele| ele.is_a?(Array) ? dup_arr << ele.deep_dup : dup_arr << ele end dup_arr end end arr = [1, [2], [3, [4]]] # Recursive 'deep_dup' duplicates any arrays within the top level array arr_deep_dup = arr.deep_dup arr_deep_dup[1] << "deep dup" p arr # => [1, [2], [3, [4]]] p arr_deep_dup # => [1, [2, "deep dup"], [3, [4]]] # Ruby's 'dup' only duplicates the array that calls it, not the arrays within arr_dup = arr.dup arr_dup[1] << "dup" p arr # => [1, [2, "dup"], [3, [4]]] p arr_dup # => [1, [2, "dup"], [3, [4]]]
true
968cc29d25a0196a551c4c95947194d92978d26f
Ruby
jaretogarato/portal-2018
/db/lecture_content.rb
UTF-8
35,159
2.65625
3
[]
no_license
def lecture_seed [ '<h1>Console / Input / Output Ruby</h1> <p> <img src="http://www.unixstickers.com/image/data/stickers/ruby/ruby_badge.sh.png" height="296" width="200"> </p> <p>Today is a very light day due to: getting to know you exercises, building tour, lunch, computer setup, canvas setup, canvas exploring.</p> <p>&nbsp;</p> <p> <strong>What we will learn today:</strong> </p> <ul> <li>What is ruby?</li> <li>Creating a Ruby Script</li> <li>Running a Ruby Script</li> <li>Getting and setting Variables</li> <li>Script output</li> <li>Getting User input</li> <li>Basic Array manipulation</li> </ul> <p>&nbsp;</p> <p> <strong>What is Ruby?</strong> </p> <p>Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.</p> <p>According to its creator, Ruby was influenced by Perl, Smalltalk, Eiffel, Ada, and Lisp.[12] It supports multiple programming paradigms, including functional, object-oriented, and imperative. It also has a dynamic type system and automatic memory management.&nbsp; <em>Learn More&nbsp;(</em> <a href="https://en.wikipedia.org/wiki/Ruby_(programming_language)" target="_blank" style="color: rgb(109, 82, 162);"> <em>https://en.wikipedia.org/wiki/Ruby_(programming_language&nbsp;(Links to an external site.)</em> </a> </p> <p> <br> </p> <p> <em>)</em> </p> <p>&nbsp;</p> <p> <strong>Creating a Ruby Script</strong> </p> <p>There are multiple ways of creating a file on your file system. Youve probably created a bunch of files on a file system before for example:</p> <ul> <li>my-resume.doc</li> <li>budget.xlsx</li> <li>notes.txt</li> </ul> <p>Creating a Ruby Script is no different. The only thing that changes is the file extension(a file extension is .doc, .xlsx, .txt ect...). A Ruby Script has the file extension of&nbsp; <strong>.rb</strong> </p> <p>Now that you know about file extensions, lets create our first ruby script. There are multiple ways to create files on a file system:</p> <ul> <li>Open your Terminal(iTerm2) and type in:</li> <li>touch hello_world.rb</li> <li>This creates a Ruby Script named hello_world in whatever current directory your terminal is in</li> <li>Another way to create a Ruby Script File is to:</li> <li>Open Sublime Text or Atom</li> <li>Navigate to your Desktop or any Directory on your Computer.</li> <li>Create a new File by Context(Right Clicking) on the Directory and select New File</li> <li>Name the file hello_world.rb</li> </ul> <p>&nbsp;</p> <p> <strong>Running a Ruby Script</strong> </p> <p>As long as you have the Ruby Language installed on your computer (Mac comes with it installed by default), you can run Ruby Programs.</p> <ul> <li>Open your Terminal(iTerm2)</li> <li>Navigate to where your Ruby Script is located (example: cd ~/Desktop/week1)</li> <li>The example above is assuming that I have a Directory called week1 on my Desktop and my hello_world.rb Ruby Script is inside of the week1 Directory</li> <li>type into Terminal:</li> <li>ruby hello_world.rb</li> </ul> <p>&nbsp;</p> <ul> <li> <em>DevPoint Labs Highly recommends that you keep organized</em> </li> <li> <em>Create a new Directory on your Desktop called DevPoint</em> </li> <li> <em>Inside that new Directory create Directories for each week (example: week1, week2, week3 ...)</em> </li> <li> <em>Put all work for each week in specific Directories</em> </li> <li> <em>This will help keep you more&nbsp;efficient / organized&nbsp;when you need to find / run programs</em> </li> <li> <em>Refer to the bottom of this document for a more detailed example: (</em> <a href="https://canvas.devpointlabs.com/courses/42/pages/student-tips" target="_blank" style="color: rgb(109, 82, 162);"> <em>https://canvas.devpointlabs.com$WIKI_REFERENCE$/pages/student-tips</em> </a> <em>)</em> </li> </ul> <p>&nbsp;</p> <p> <strong>Getting and setting Variables</strong> </p> <p>Now that we know what the Ruby language&nbsp;is, file extensions are, creating a Ruby Script, and running Ruby Scripts, its time to start&nbsp; <strong>CODING!!!</strong> </p> <p>The very first thing we will learn is setting variables in Ruby.</p> <p>In computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value. The variable name is the usual way to reference the stored value.&nbsp; <em>Learn More (</em> <a href="https://en.wikipedia.org/wiki/Variable_(computer_science)" target="_blank" style="color: rgb(109, 82, 162);"> <em>https://en.wikipedia.org/wiki/Variable_(computer_science)&nbsp;(Links to an external site.)</em> </a> </p> <p> <br> </p> <p> <em>)</em> </p> <p>Inside of our hello_world.rb file lets add a few lines of code:</p> <pre spellcheck="false">first_name = \'your first name\' </pre> <ul> <li>This sets a variable named first_name to a string value of \'your first name\'</li> </ul> <pre spellcheck="false">last_name = \'your last name\' </pre> <ul> <li>This sets a variable named last_name to a string value of \'your last name\'</li> </ul> <pre spellcheck="false">world = \'world\' </pre> <ul> <li>This sets a variable named world to a string value of \'world\'</li> </ul> <pre spellcheck="false">first_number = 10 </pre> <ul> <li>This sets a variable named first_number to a integer value of 10</li> </ul> <pre spellcheck="false">second_number = 2.0 </pre> <ul> <li>This sets a variable named second_number to a float value of 2.0</li> </ul> <p>&nbsp;</p> <p> <strong>Script output</strong> </p> <p>Now that we have a very basic understanding of setting variables. We need a way to show those values to the script user.</p> <p>This is where the&nbsp; <strong> <em>puts&nbsp;</em> </strong>command comes in.</p> <p>Inside of our hello_world.rb file lets add a few more lines of code:</p> <pre spellcheck="false">puts first_name </pre> <ul> <li>This will output the&nbsp; <em>value&nbsp;</em>of the&nbsp; <em>first_name&nbsp;</em>variable</li> <li>\'your first name\'</li> </ul> <pre spellcheck="false">puts last_name </pre> <ul> <li>This will output the&nbsp; <em>value&nbsp;</em>of the last <em>_name&nbsp;</em>variable\'your last&nbsp;name\'</li> </ul> <pre spellcheck="false">puts world </pre> <ul> <li>This will output the&nbsp; <em>value&nbsp;</em>of the world <em>&nbsp;</em>variable\'world\'</li> </ul> <pre spellcheck="false">puts first_number </pre> <ul> <li>This will output the&nbsp; <em>value&nbsp;</em>of the&nbsp;first_number <em>&nbsp;</em>variable10</li> </ul> <pre spellcheck="false">puts second_number </pre> <ul> <li>This will output the&nbsp; <em>value&nbsp;</em>of the second_number <em>&nbsp;</em>variable2.0</li> </ul> <p>The&nbsp; <strong> <em>puts&nbsp;</em> </strong>command will&nbsp; <em>always&nbsp;</em>have a new line after the output value</p> <p>There is another way to output in your Ruby Scripts and that is the&nbsp; <strong> <em>prints&nbsp;</em> </strong>command.</p> <p>The&nbsp; <strong> <em>prints&nbsp;</em> </strong>command will do the same thing as&nbsp; <strong> <em>puts&nbsp;</em> </strong>but wont add the new line.</p> <p>&nbsp;</p> <p> <strong>Getting User input</strong> </p> <p>Now that we know how to output data to the user that is running the Ruby Script, it would be nice if we could receive input from that user. Lucky Ruby makes this super easy to do with the&nbsp; <strong> <em>gets&nbsp;</em> </strong>command.</p> <p> <strong> <em>gets&nbsp;</em> </strong>command examples:</p> <p>gets</p> <ul> <li>Script stops and waits for user input</li> </ul> <pre spellcheck="false">user_input = gets </pre> <ul> <li>Script stops and waits for user input, after user presses return the value of the user input gets stored in the&nbsp; <em>user_input&nbsp;</em>variable</li> </ul> <pre spellcheck="false">first_name = gets </pre> <ul> <li>Script stops and waits for user input, after user presses return the value of the user input gets stored in the&nbsp;first_name <em>&nbsp;</em>variable</li> </ul> <pre spellcheck="false">last_name = gets </pre> <ul> <li>Script stops and waits for user input, after user presses return the value of the user input gets stored in the&nbsp;last_name <em>&nbsp;</em>variable</li> </ul> <p>&nbsp;</p> <p> <strong>Arrays:</strong> </p> <p>For tonights assignment we are going to need to have some very basic knowledge of a data structure in Ruby called an Array.</p> <p> <strong>Array Definition:</strong> </p> <p>Arrays are ordered, integer-indexed collections of any object.&nbsp;Array indexing starts at 0. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.&nbsp; <em>Learn More (</em> <a href="http://docs.ruby-lang.org/en/2.0.0/Array.html" target="_blank" style="color: rgb(109, 82, 162);"> <em>http://docs.ruby-lang.org/en/2.0.0/Array.html&nbsp;(Links to an external site.)</em> </a> </p> <p> <br> </p> <p> <em>)</em> </p> <p> <strong>Basic Array Usage:</strong> </p> <pre spellcheck="false">number_array = [] </pre> <ul> <li>This sets a variable named&nbsp; <em>number_array&nbsp;</em>to an empty array</li> </ul> <pre spellcheck="false">number_array &lt;&lt; 1 </pre> <ul> <li>This adds (pushes) a new item onto the&nbsp; <em>number_array</em> </li> </ul> <pre spellcheck="false">number_array &lt;&lt; 2 </pre> <ul> <li>This adds (pushes) a new item onto the&nbsp; <em>number_array</em> </li> </ul> <pre spellcheck="false">number_array &lt;&lt; 50 </pre> <ul> <li>This adds (pushes) a new item onto the&nbsp; <em>number_array</em> </li> </ul> <p> <strong>number_array now looks like this: <em>&nbsp;[1,2,50]</em> </strong> </p> <ul> <li>Items in an array are separated&nbsp;by commas</li> </ul> <p> <strong>Getting specific values from an array:</strong> </p> <pre spellcheck="false">number_array.first </pre> <ul> <li>This will return&nbsp;the first item in the array</li> <li>In our case the first item in the&nbsp; <em>number_array&nbsp;</em>is: 1</li> </ul> <pre spellcheck="false">number_array.last </pre> <ul> <li>This will return&nbsp;the last&nbsp;item in the array</li> <li>In our case the first item in the&nbsp; <em>number_array&nbsp;</em>is: 50</li> </ul> <pre spellcheck="false">number_array[0] </pre> <ul> <li>This will return&nbsp;the item at index 0&nbsp;in the array</li> <li>In our case the 0 index&nbsp;item in the&nbsp; <em>number_array&nbsp;</em>is: 1</li> </ul> <pre spellcheck="false">number_array[1] </pre> <ul> <li>This will return&nbsp;the item at index 1&nbsp;in the array</li> <li>In our case the 1 index&nbsp;item in the&nbsp; <em>number_array&nbsp;</em>is: 2</li> </ul> <pre spellcheck="false">number_array[2] </pre> <ul> <li>This will return&nbsp;the item at index 2&nbsp;in the array</li> <li>In our case the 2 index&nbsp;item in the&nbsp; <em>number_array&nbsp;</em>is: 50</li> </ul> <pre spellcheck="false">number_array[3] </pre> <ul> <li>This will return&nbsp; <strong> <em>nil</em> </strong>. We do not currently have a 4th item in our array</li> </ul> <p> <br> </p>', '<h1>Course</h1> <p>In this course, you will learn how to build web applications using HTML, CSS, JavaScript, Frameworks, Databases, &amp; Servers.</p> <p>&nbsp;</p> <p>At the completion of this course, you will be able to build dynamic web applications with rich content.&nbsp;You will be able to create apis for use with multi-platform applications (mobile &amp; web) with a single codebase for the API.</p> <p>More importantly, you will learn to think like a programmer.&nbsp;Along with instruction on how to use new tools and techniques you will understand the development process.&nbsp;</p> <p>To succeed in this course you should be able to:</p> <p>1. Follow along</p> <p>2. Ask questions</p> <p>3. Learn from constructive feedback from the instructors, mentors, &amp; peers</p> <p>4.&nbsp;You will have access to all course content.&nbsp;It is not necessary to be taking notes constantly (especially during follow along exercises)</p> <p>5. Work outside of class to strengthen concepts</p> <p>6. Practice, practice, practice</p> <p>7. Do not memorize.&nbsp;Learn the concept, not the syntax</p> <p>8. Participate in lesson discussions</p> <p>9. Watch for announcements on Canvas</p> <p>&nbsp;</p> <p>This course content is delivered in an organized way at a relatively fast pace.&nbsp;Stay away from distractions (Facebook, Reddit, etc) during class.&nbsp;Do your best not to miss time in this course. It will be incredibly difficult to catch up as each day builds on the previous.&nbsp;If you have to miss time let the instructors know ahead of time and try to sync up with another student to help you catch up.</p>", "<h1>Git / Github</h1> <h3>About</h3> <p>Git is a free open source distributed version control system.&nbsp;Git was created by LinusTorvalds&nbsp;in 2005.&nbsp;</p> <p>Git is a secure way to store your project files and easily collaborate on them with others.</p> <p>NOTE:&nbsp;Git and Github are 2 separate things.&nbsp;Git is the technology that we use and Github is a website where youc an upload a copy of your Git repository.&nbsp;Github is a Git repository hosting service.&nbsp;Bit Bucket is an alternative to GitHub.</p> <h3>Installation: (mac)</h3> <pre spellcheck=\"false\">$ brew install git </pre> <p>Next you will want to generate an ssh key ( you may already have one ).&nbsp;An SSH key is a way to securely connect to a remote machine.&nbsp;By using an SSH key you won\'t be required to enter your username and password every time you want to interact with hosted Git Repositories.</p> <h4>Check if you have an SSH key</h4> <pre spellcheck=\"false\">$ find ~/.ssh -name *id_rsa.pub* </pre> <p>If you see a directory then you already have a public key.&nbsp;If you see nothing then you need to create a key.</p> <h4>Create an SSH key (skip if you already have one)</h4> <pre spellcheck=\"false\">$ ssh-keygen -t rsa -b 4096 -C \"PUT YOUR EMAIL HERE\" </pre> <p>Hit enter a few times until you see some ascii art.&nbsp;NOTE:&nbsp;You do not need a passphrase.&nbsp;You can just hit enter to skip the passphrase.</p> <h3>Create a GitHub&nbsp;account ( <a href=\"https://github.com/\" target=\"_blank\" style=\"color: rgb(109, 82, 162);\">https://github.com&nbsp;(Links to an external site.)</a> </h3> <h3> <br> </h3> <h3>)</h3> <h4>Add your ssh key to&nbsp;GitHub</h4> <p>First we want to copy the key to our clipboard exactly as it is in the file:</p> <pre spellcheck=\"false\">$ pbcopy &lt; ~/.ssh/id_rsa.pub </pre> <p>Login to GitHub</p> <p>Click on your avatar in the top right corner and select settings</p> <p>Click on SSH and GPG keys from the left navigation.</p> <p>Click New SSH Key</p> <p>Give it a Title and paste the key into the body.</p> <p> <br> </p> <p>Now that you are setup we can begin to learn to work with Git and GitHub.</p> <h4>Objectives:</h4> <ul> <li>Git configuration</li> <li>Creating a new repository</li> <li>Status and Log</li> <li>Staging and committing files</li> <li>Branching and merging</li> <li>Create a new repository on GitHub</li> <li>Push to GitHub</li> <li>Cloning an existing repository</li> <li>Ammending a commit</li> <li>Fixing merge conflicts</li> <li>Unstaging and resetting</li> <li>Stashing a commit</li> <li>Rebasing</li> <li>Pull requests</li> <li>File diffing</li> <li>Ignoring files</li> </ul> <h4>Git Config</h4> <p>The first time you are setting up a new machine you will want to set some global config options for git</p> <pre spellcheck=\"false\">$ git config --global user.name \"John Doe\" $ git config --global user.email johndoe@example.com $ git config --global core.editor vim $ git config --global core.excludesfile ~/.gitignore </pre> <p>You will have .gitignore files in each individual repo but it is also nice to have a global gitignore file for system and IDE files so they are not tracked by Git</p> <p>Open ~/.gitignore (note if this is a new computer to you, you may need to enable viewing hidden files (defaults write com.apple.finder AppleShowAllFiles YES)</p> <p>~/.gitignore</p> <pre spellcheck=\"false\"># Mac .DS_Store #VSCODE .vscode/ </pre> <p>It is considered bad practice to ignore system files in individual repositories.</p> <h3>Warnings!!!!</h3> <p>1.&nbsp;Never make a system directory a git repository (Downloads, Desktop, Users/username, etc...)</p> <p>2.&nbsp;Never create a git repository inside of a git repository.&nbsp;</p> <p>3.&nbsp;Each project for us going forward will be in a folder, each folder will be it\'s own git repository</p> <p>4.&nbsp;If you accidentally create a git repo where you shouldn\'t have you can remove the .git/ folder in that directory</p> <p>&nbsp;</p> <h4>LOCAL GIT - Creating a repository</h4> <p>Navigate in the terminal to where you keep your course projects</p> <pre spellcheck=\"false\">$ mkdir git_practice $ cd git_practice $ git init </pre> <p>You should see the following output:</p> <p>Initialized empty Git repository in /path/to/your/project/git_practice/.git/</p> <p>The hidden folder called .git/ contains several files and configurations for this local git repository.</p> <p>Now create some files so we have something to track:</p> <pre spellcheck=\"false\">$ touch main.rb passwords.txt </pre> <p>Next we will see what git knows about and doesn\'t know about</p> <pre spellcheck=\"false\">$ git status Initial commit Untracked files: (use \"git add &lt;file&gt;...\" to include in what will be committed) main.rb passwords.txt nothing added to commit but untracked files present (use \"git add\" to track) </pre> <p>Currently we have 2 untracked files.&nbsp;Git does not yet know about these files but it does know they are in the directory.</p> <p>We don\'t want git to know about sensitive data.&nbsp;If we were to publish passwords.txt to GitHub in a public directory other people would be able to view it.</p> <p>Create a file to tell git which files not to track:</p> <pre spellcheck=\"false\">$ touch .gitignore </pre> <p>.gitignore</p>\ <pre spellcheck=\"false\">passwords.txt $ git status Initial commit Untracked files: (use \"git add &lt;file&gt;...\" to include in what will be committed) .gitignore main.rb nothing added to commit but untracked files present (use \"git add\" to track) </pre> <p>Next we want to tell git to track these two files.&nbsp;We can add files to git with git add &lt;filename&gt; or git add &lt;directory name&gt; or git add . (the . means all)</p> <p>It is common to git add . but if you make a habit of this make sure that your .gitignore file is set up properly first.</p> <pre spellcheck=\"false\">$ git add . $ git status Initial commit Changes to be committed: (use \"git rm --cached &lt;file&gt;...\" to unstage) new file: .gitignore new file: main.rb </pre> <p> <span style=\"color: rgb(0, 0, 0);\">What we have done is staged these files to be committed.&nbsp;</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">Now let\'s commit.&nbsp;Committing creates a snapshot of your changes in your repository each time the project reaches a state you want to record.</span> </p> <pre spellcheck=\"false\">$ git commit -m \'initial commit\' </pre> <p> <span style=\"color: rgb(0, 0, 0);\">We have now committed our changes and given a commit message of \"initial commit\"</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">NOTE:&nbsp;Use the following guidelines when creating a commit message:</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">1.&nbsp;Keep messages short &lt; 50 characters</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">2.&nbsp;Keep messages in the present tense ( add feature chat window / fix regression bug )</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">3.&nbsp;Use useful commit messages that identify the work done in the commit</span> </p> <pre spellcheck=\"false\">$ git status On branch master nothing to commit, working tree clean </pre> <p> <span style=\"color: rgb(0, 0, 0);\">We can see a log of all the commits in the repository by typing git log</span> </p> <pre spellcheck=\"false\">$ git log commit d8e1bdccceb8a7e1a6a7abd442d3936169133570 Author: David Jungst &lt;djungst@gmail.com&gt; Date: Mon Jul 24 11:56:57 2017 -0600 initial commit </pre> <p> <span style=\"color: rgb(0, 0, 0);\">The first line is the SHA of the commit this can be useful if you are trying to revert to a specific commit.</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">Sometimes you will want to see less information about the commits and just get a list of commits</span> </p> <pre spellcheck=\"false\">$ git log --oneline d8e1bdc initial commit </pre> <p> <span style=\"color: rgb(0, 0, 0);\">Let\'s add some code to main.rb</span> </p> <pre spellcheck=\"false\">def puts_git(cmd) puts `git #{cmd} -h` menu end def menu puts \'1: Enter git command\' puts \'2: Exit\' choice = gets.to_i case choice when 1 puts \'Enter git command\' puts_git(gets.strip) menu when 2 exit else puts \'Invalid choice\' menu end end menu $ git status Changes not staged for commit: (use \"git add &lt;file&gt;...\" to update what will be committed) (use \"git checkout -- &lt;file&gt;...\" to discard changes in working directory) modified: main.rb no changes added to commit (use \"git add\" and/or \"git commit -a\") </pre> <p> <span style=\"color: rgb(0, 0, 0);\">Since git knows about main.rb we can see that it has been modified.</span> </p> <pre spellcheck=\"false\">$ git add main.rb </pre> <p> <span style=\"color: rgb(0, 0, 0);\">Now let\'s see what happens if we try to commit without adding the -m</span> </p> <pre spellcheck=\"false\">$ git commit 1 2 # Please enter the commit message for your changes. Lines starting 3 # with \'#\' will be ignored, and an empty message aborts the commit. 4 # On branch master 5 # Changes to be committed: 6 # modified: main.rb 7 # </pre> <p> <span style=\"color: rgb(0, 0, 0);\">We are now in VIM</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\"> <img src=\"https://canvas.devpointlabs.com/courses/42/files/4337/preview\" alt=\"Screen Shot 2017-07-24 at 12.13.43 PM.png\"> </span> </p> <p>&nbsp;</p> <p>VIM has 3 modes:&nbsp;</p> <p>1.&nbsp;Command mode</p> <p>2.&nbsp;Insert Mode</p> <p>3.&nbsp;Visual Mode</p> <p>Right now we are in command mode and we need to get into insert mode so we can add a commit message</p> <p>First type: i</p> <p>At the bottom of your terminal you should see:</p> <pre spellcheck=\"false\">-- INSERT -- </pre> <p>Now you can type your commit message</p> <pre spellcheck=\"false\">1 add git help menu </pre> <p>Now we need to get out of insert mode</p> <p>type: esc</p> <p>Next we want to save and close the file using write / quite</p> <p>:wq</p> <p>Let\'s make sure our commit message shows up</p> <pre spellcheck=\"false\">$ git log --oneline 193ddd8 add git help menu d8e1bdc initial commit </pre> <p>Now add some more code</p> <pre spellcheck=\"false\">$ touch Gemfile </pre> <p>Gemfile</p> <pre spellcheck=\"false\">gem \'colorize\' $ bundle </pre> <p>main.rb</p> <pre spellcheck=\"false\">require \'colorize\' def puts_git(cmd) puts `git #{cmd} -h` menu end def menu puts \'MAIN MENU\'.colorize(:cyan) puts \'1: Enter git command\'.colorize(:cyan) puts \'2: Exit\'.colorize(:cyan) choice = gets.to_i case choice when 1 puts \Enter git command\'.colorize(:green) puts_git(gets.strip) menu when 2 exit else puts \'Invalid choice\'.colorize(:red) menu end end menu $ git add . $ git commit -m \'add colorize gem\' </pre> <h4>Un-Staging commits</h4> <p>main.rb</p> <pre spellcheck=\"false\">puts \'MAIN MENU\'.colorize(:black) $ git add . $ git status </pre> <p>There are several ways to un-stage the changes that we just added.</p> <p>1.&nbsp;I just want to unstage it but keep the file unaltered\</p> <pre spellcheck=\"false\">$ git reset HEAD main.rb </pre> <p>2.&nbsp;I want to go back to the most recent version of the file (changes will be lost)</p> <pre spellcheck=\"false\">$ git checkout main.rb </pre> <p>3.&nbsp;I want to blow away all changes and revert to the last commit</p> <pre spellcheck=\"false\">$ git reset --hard HEAD </pre> <h4>Branching</h4> <p>Often you will be working on multiple features at the same time and we can move work into different branches</p> <p>Creating a new branch:</p> <pre spellcheck=\"false\">$ git branch foo NOTE to list branches: $ git branch foo * master </pre> <p> <span style=\"color: rgb(0, 0, 0);\">Notice we are on the master branch.</span> </p> <p> <span style=\"color: rgb(0, 0, 0);\">To move to a branch called foo:</span> </p> <pre spellcheck=\"false\">$ git checkout foo $ git branch * foo master </pre> <p> <span style=\"color: rgb(0, 0, 0);\">To delete a branch you must first move off of the branch you want to delete</span> </p> <pre spellcheck=\"false\">$ git checkout master $ git branch -D foo </pre> <p>To create a branch and switch to it at the same time:</p> <pre spellcheck=\"false\">$ git checkout -b my_feature </pre> <p>When you create a branch you always are creating it from the branch you are on.&nbsp;Because of this it\'s a good idea to not work on master and keep master up to date.&nbsp;You can then create the branch while on the master branch.</p> <p>Let\'s do some work on the my_feature_branch:</p> <p>main.rb</p> <pre spellcheck=\"false\">require \'colorize\' require_relative \'git\' class Main include Git def self.menu puts \'MAIN MENU\'.colorize(:cyan) puts \'1: Enter git command\'.colorize(:cyan) puts \'2: Exit\'.colorize(:cyan) choice = gets.to_i case choice when 1 puts \'Enter git command\'.colorize(:green) Git.puts_git(gets.strip) when 2 exit else puts \'Invalid choice\'.colorize(:red) end menu end end Main.menu $ touch git.rb </pre> <p>git.rb</p> <pre spellcheck=\"false\">module Git def self.puts_git(cmd) puts `git #{cmd} -h` end end </pre> <p>Try to switch to the master branch</p> <pre spellcheck=\"false\">$ git add . $ git commit -m \'move git helper to a module\' </pre> <p>Switch back to the master branch:</p> <pre spellcheck=\"false\">$ git checkout master </pre> <p>Notice that git.rb doesn\'t exist and main.rb is the code from before.&nbsp;Notice our last commit is not here:</p> <pre spellcheck=\"false\">$ git log --oneline 6e4520e add colorize gem 193ddd8 add git help menu d8e1bdc initial commit </pre> <p>Don\'t worry your work is not lost.&nbsp;This branch doesn\'t know about the code on the other branch.</p> <p>To be sure you didn\'t lose your work:</p> <p> <br> </p> <pre spellcheck=\"false\">$ git checkout my_feature $ git log --oneline </pre> <p>Now let\'s merge this branch into master</p> <p>There are 2 ways to combine branches merging and rebasing.&nbsp;They each come with their own set of advantages.</p> <p>First we will look at merge:</p> <pre spellcheck=\"false\">$ git checkout master $ git merge my_feature Fast-forward git.rb | 5 +++++ main.rb | 39 ++++++++++++++++++++------------------- 2 files changed, 25 insertions(+), 19 deletions(-) create mode 100644 git.rb </pre> <p>You can see all of your branches and the last commit on each branch with the following command:</p> <pre spellcheck=\"false\">$ git branch -v </pre> <p>This shows as that both branches are current</p> <p>Now that all of the code from my_feature is on master it\'s a good idea to delete the my_feature branch</p> <pre spellcheck=\"false\">$ git branch -D my_feature </pre> <h4>GitHub</h4> <p>Go to&nbsp; <a href=\"https://github.com/\" target=\"_blank\" style=\"color: rgb(109, 82, 162);\">GitHub&nbsp;(Links to an external site.)</a> </p> <p> <br> </p> <p>&nbsp;and sign in.</p> <p>Click the + icon in the top right nav bar and select \"New Repository\"</p> <p>Give the repository a name \"git-practice\"</p> <p>Click on Create Repository:</p> <p>You will see some instructions on the screen: <img src=\"https://canvas.devpointlabs.com/courses/42/files/4338/preview\" alt=\"Screen Shot 2017-07-24 at 12.55.45 PM.png\"> </p> <p>Paste the line of code you have copied into the terminal</p> <pre spellcheck=\"false\">$ git remote add &lt;name of remote&gt; &lt;github url&gt; </pre> <p>List remotes</p> <pre spellcheck=\"false\">$ git remote -v </pre> <p>Push our local repository to github</p> <pre spellcheck=\"false\">$ git push origin master </pre> <p>Refresh your page on Github and you should see your code.</p> <p>Let\'s add some more code to emphasize the difference between local git and a git remote (in this case github)</p> <pre spellcheck=\"false\">$ git checkout -b git_config_menu origin/master </pre> <p>Notice we added origin/master this means create a new branch from the tip of the branch on Github</p> <p>git.rb</p> <pre spellcheck=\"false\">module Git def self.puts_git(cmd) puts `git #{cmd} -h` end def self.config puts `git config -l` end end </pre> <p>main.rb</p> <pre spellcheck=\"false\">def self.menu puts \'MAIN MENU\'.colorize(:cyan) puts \'1: Enter git command\'.colorize(:cyan) puts \'2: View git config\'.colorize(:cyan) puts \'3: Exit\'.colorize(:cyan) choice = gets.to_i case choice when 1 puts \'Enter git command\'.colorize(:green) Git.puts_git(gets.strip) when 2 Git.config when 3 exit else puts \'Invalid choice\'.colorize(:red) end menu end $ git add . $ git commit -m \'display git config\' </pre> <p>Notice this is not on GitHub but it is on our local machine.</p> <p>If we want to push this to GitHub we have 2 choices we can push to master or we can push to a remote branch</p> <pre spellcheck=\"false\">To push to a remote branch $ git push origin git_config_menu To push to master $ git push origin git_config_menu:master </pre> <p>Before we push let\'s do some work on master to create a merge conflict</p> <pre spellcheck=\"false\">$ git checkout master </pre> <p>git.rb</p> <pre spellcheck=\"false\">module Git def self.git_cmd(cmd) puts `git #{cmd} -h` end end </pre> <p>main.rb</p> <pre spellcheck=\"false\">when 1 puts \'Enter git command\'.colorize(:green) Git.git_cmd(gets.strip) $ git add . $ git commit -m \'change puts_git to git_cmd\' $ git push origin master </pre> <p>An alternative to merging branches is to rebase branches.&nbsp;This comes with it\'s own set of tradeoffs.</p> <p>Let\'s try to rebase:</p> <pre spellcheck=\"false\">$ git checkout git_config_menu </pre> <p>Now let\'s intentionally cause a merge conflict by editing a line that was just pushed to master:</p> <p>git.rb</p> <pre spellcheck=\"false\">def self.display_cmd(cmd) </pre> <p>main.rb</p> <pre spellcheck=\"false\">Git.display_cmd(gets.strip) </pre> <p>Next lets add our changes:</p> <pre spellcheck=\"false\">$ git add . $ git commit --amend //NOTE since we haven\'t pushed this commit we can choose to just amend it rather than creating a new commit </pre> <p>Back in VIM land!</p> <p>esc :wq</p> <p>Before we push we want to make sure we are up to date with what is currently on the master branch from github</p> <pre spellcheck=\"false\">$ git fetch origin master $ git rebase origin/master CONFLICT (content): Merge conflict in main.rb CONFLICT (content): Merge conflict in git.rb </pre> <p>We have two conflicts that need to be fixed before we can finish our rebase:</p> <p>NOTE:&nbsp;</p> <pre spellcheck=\"false\">$ git branch * (no branch, rebasing git_config_menu) </pre> <p>We are not on a branch right now because we are fixing conflicts</p> <pre spellcheck=\"false\">$ git status ou are currently rebasing branch \'git_config_menu\' on \'0cf2f40\'. (fix conflicts and then run \"git rebase --continue\") (use \"git rebase --skip\" to skip this patch) (use \"git rebase --abort\" to check out the original branch) Unmerged paths: (use \"git reset HEAD &lt;file&gt;...\" to unstage) (use \"git add &lt;file&gt;...\" to mark resolution) both modified: git.rb both modified: main.rb no changes added to commit (use \"git add\" and/or \"git commit -a\") </pre> <p>These are the files where conflicts exist we need to fix the conflicts and then continue the rebase</p> <p>git.rb</p> <pre spellcheck=\"false\">&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD def self.git_cmd(cmd) ======= def self.display_cmd(cmd) &gt;&gt;&gt;&gt;&gt;&gt;&gt; display git config </pre> <p>These lines conflict.&nbsp;We need to decide which one to keep and remove the comments</p> <pre spellcheck=\"false\">def self.git_cmd(cmd) puts `git #{cmd} -h` end </pre> <p>Now we need to fix our other conflicts</p> <p>main.rb</p> <pre spellcheck=\"false\">&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD Git.git_cmd(gets.strip) ======= Git.display_cmd(gets.strip) &gt;&gt;&gt;&gt;&gt;&gt;&gt; display git config #Change to Git.git_cmd(gets.strip) </pre> <p>Now that conflicts are resolved add the files and continue the rebase</p> <pre spellcheck=\"false\">$ git add . $ git rebase --continue </pre> <p>IMPORTANT:&nbsp;While rebasing never use git commit you should only use git rebase --continue | git rebase --skip | git rebase --abort</p> <p>Now let\'s push this branch to a remote branch so we can continue working on it</p> <pre spellcheck=\"false\">$ git push origin git_config_menu </pre> <p>Notice on GitHub you now have two branches.&nbsp;We can continue to work on this branch and when we are done we can push it in to master.</p> <pre spellcheck=\"false\">$ git push origin git_config_menu:master </pre> <p>Now that everything is up to date let\'s clean up our branches</p> <pre spellcheck=\"false\">$ git checkout master $ git fetch $ git rebase origin/master $ git branch -D git_config_menu </pre> <p>Now on GitHub click the branches link</p> <p>Click the trash icon to delete the remote branch.</p> <h3>Cloning a repository</h3> <p>First go back to where you keep your projects for the course</p> <pre spellcheck=\"false\">$ cd .. </pre> <p>Next clone the shopping app solution from my github</p> <pre spellcheck=\"false\">git clone git@github.com:wdjungst/ruby_class_example.git </pre> <p>Now you have access to all of the code from the shopping_app solution.</p> <p>Alternatively you can fork the repository which will make a copy for you in your own github.</p> <p>A nice feature to forking is that you can change some code and submit a pull_request to the original repository.&nbsp;If your pull request is accepted it will become part of the code base.</p>' ] end
true
c3a60bd87e7110b05a5c3ce31f2ccc7fe16ffbe0
Ruby
pdynowski/phase-0
/week-4/define-method/my_solution.rb
UTF-8
138
2.640625
3
[ "MIT" ]
permissive
# Define an Empty Method # I worked on this challenge all on my lonesome. # Your Solution Below def do_something(par1, par2, par3) end
true
fba8b385a73d7a07b89c917ce53caa7b1c909ddd
Ruby
rasensio1/Enigma
/key.rb
UTF-8
359
3.203125
3
[]
no_license
class Key attr_accessor :value def initialize(number = '') @value = number end def generate keys = (10000..99999).to_a @value = keys.sample.to_s end def create_key_from_rotation(rotation) a = rotation.a.to_s b = rotation.b.to_s c = rotation.c.to_s d = rotation.d.to_s e = rotation.e.to_s a+c+d[1] end end
true
8b77a88c55506390bd24f3a1f2e67d2b32007792
Ruby
GSpence/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
400
3.859375
4
[]
no_license
def echo(x) x end def shout(x) x=x.upcase end def repeat(word, sum=2) ([word]*sum).join ' ' end def start_of_word(word, x) word [0,x] end def first_word(string) string.split[0] end def titleize(string) y=string.split(' ') y.each do |x| if x == 'and' || x == 'over'|| x == 'the' next else x.capitalize! end end y[0].capitalize! y.join(' ') end
true
26a709459d77fbff84359dd5d4463688608dbfb4
Ruby
tbonza/CS_CS169.1x
/hw1/lib/fun_with_strings.rb
UTF-8
1,237
3.859375
4
[]
no_license
module FunWithStrings def initialize(check_string) @check_string = check_string end attr_accessor :check_string def palindrome? """ A palindrome is a word or phrase that reads the same forwards as backwards, ignoring case, punctuation, and nonword characters. (A 'nonword character' is defined for our purposes as 'a character that Ruby regular expressions would treat as a nonword character'.) You will write a method palindrome? that returns true if and only if its receiver is a palindrome. 'redivider'.palindrome? # => should return true 'adam'.palindrome? # => should return false or nil """ # strip punctuation, remove casing, and nonword characters with regex @check_string = @check_string.sub("[^A-z]", "") @check_string.lower! # Does the string read the same forwards and reversed? if @check_string == @check_string.reverse return true else return false end end def count_words # your code here end def anagram_groups # your code here end end # make all the above functions available as instance methods on Strings: class String include FunWithStrings end
true
77744738d753c47077ad50f376b120747860e1ad
Ruby
siorekoskar/Ruby-tickets
/app/models/event.rb
UTF-8
765
2.671875
3
[]
no_license
class Event < ActiveRecord::Base validates :artist, :presence => true validates :description, :presence => true validates :price_low, :presence => true, :numericality =>true validates :price_high, :presence => true, :numericality =>true validates :event_date, :presence => true validate :event_date_not_from_past validate :price_low_not_higher_than_high private def event_date_not_from_past if event_date < Date.today errors.add('Data wydarzenia', 'nie może być z przeszłości') end end def price_low_not_higher_than_high if price_high < price_low errors.add('Cena minimalna', 'nie moze byc wieksza niz najwieksza') end end has_many :tickets end
true
18ac3a2821224f444b2d77bafb7d0499efd630d1
Ruby
btdunn/codewars
/ruby/findMissingNumber.rb
UTF-8
47
2.59375
3
[]
no_license
def missing_no(nums) 5050 - nums.sum end
true
55a4f30b2c9c2447bcf782b8736109c8d93b9fdb
Ruby
bbatsov/volt
/spec/reactive/computation_spec.rb
UTF-8
2,538
2.53125
3
[ "MIT" ]
permissive
require 'spec_helper' describe Volt::Computation do it 'should trigger again when a dependent changes' do a = Volt::ReactiveHash.new values = [] -> { values << a[0] }.watch! expect(values).to eq([nil]) a[0] = 'one' Volt::Computation.flush! expect(values).to eq([nil, 'one']) a[0] = 'two' Volt::Computation.flush! expect(values).to eq([nil, 'one', 'two']) end it 'should not trigger after the computation is stopped' do a = Volt::ReactiveHash.new values = [] computation = -> { values << a[0] }.watch! expect(values).to eq([nil]) a[0] = 'one' Volt::Computation.flush! expect(values).to eq([nil, 'one']) computation.stop a[0] = 'two' Volt::Computation.flush! expect(values).to eq([nil, 'one']) end it 'should support nested watches' do a = Volt::ReactiveHash.new values = [] -> do values << a[0] -> do values << a[1] end.watch! end.watch! expect(values).to eq([nil, nil]) a[1] = 'inner' Volt::Computation.flush! expect(values).to eq([nil, nil, 'inner']) a[0] = 'outer' Volt::Computation.flush! expect(values).to eq([nil, nil, 'inner', 'outer', 'inner']) end # Currently Class#class_variable_set/get isn't in opal # https://github.com/opal/opal/issues/677 unless RUBY_PLATFORM == 'opal' describe '#invalidate!' do let(:computation) { Volt::Computation.new ->{} } before(:each) do Volt::Computation.class_variable_set :@@flush_queue, [] end describe 'when stopped' do before(:each) { computation.instance_variable_set :@stopped, true } it "doesn't add self to flush queue" do computation.invalidate! expect(Volt::Computation.class_variable_get :@@flush_queue).to be_empty end end describe 'when computing' do before(:each) { computation.instance_variable_set :@computing, true } it "doesn't add self to flush queue" do computation.invalidate! expect(Volt::Computation.class_variable_get :@@flush_queue).to be_empty end end describe 'when not stopped and not computing' do before(:each) do computation.instance_variable_set :@stopped, false computation.instance_variable_set :@computing, false end it 'adds self to flush queue' do computation.invalidate! expect(Volt::Computation.class_variable_get :@@flush_queue).to match_array([computation]) end end end end end
true
f526848019385617faff950a61572da51c49df06
Ruby
KazW/multi-buildpack
/bin/compile
UTF-8
2,704
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # Load libraries require 'uri' require 'tmpdir' require 'fileutils' require 'yaml' # Allow git commands to function locally. ENV['GIT_DIR'] = nil # Variables @last_framework = "None" @buildpacks = [] @frameworks = [] @release = {} @last_release = {} def parse_buildpack_file buildpack_file = "#{ARGV[0]}/.buildpacks" return @buildpacks unless File.exists?(buildpack_file) File.open(buildpack_file).each_line.with_index(1) do |line,line_number| line.strip! next if line.empty? || line[0] == "#" begin uri = URI.parse(line) rescue URI::InvalidURIError print "WARNING: Line #{line_number} of the .buildpacks file is invalid!\n" next end @buildpacks << { 'url' => uri.to_s.split('#').first, 'ref' => uri.fragment } end end def download_buildpack(dir, url, ref) print "=====> Downloading Buildpack: #{url}\n" if url =~ /\.tgz$/ Dir.mkdir dir `curl -s "#{url}" | tar xvz -C "#{dir}" >/dev/null 2>&1` else `git clone "#{url}" "#{dir}" >/dev/null 2>&1` Dir.chdir(dir){`git checkout "#{ref}" >/dev/null 2>&1`} unless ref.nil? if File.exists?("#{dir}/.gitmodules") print "=====> Detected git submodules. Initializing...\n" Dir.chdir(dir){`git submodule update --init --recursive`} end end end def build_buildpack(dir) Dir.chdir(dir) do # Ensure buildpack entry points are executable. `chmod -f +x ./bin/{detect,compile,release} || true` @last_framework = `./bin/detect "#{ARGV[0]}"`.strip @frameworks << @last_framework if $?.to_i.zero? print "=====> Detected Framework: #{@last_framework}\n" `./bin/compile "#{ARGV[0]}" "#{ARGV[1]}" "#{ARGV[2]}"` exit(1) unless $?.to_i.zero? end end end def export_environment(dir) return unless File.exists?("#{dir}/export") Hash[ `. "#{dir}/export" >/dev/null 2>&1 && env`. split. map{|ev| ev.split('=', 2)} ].each do |key,val| next if key.strip.empty? || val.strip.empty? ENV[key] = val end end def write_release(dir) return unless File.exists?("#{dir}/bin/release") @last_release = YAML.load(`#{dir}/bin/release "#{ARGV[0]}"`) @release.merge(@last_release) end # Actually do the builds parse_buildpack_file @buildpacks.each do |buildpack| dir = Dir.mktmpdir FileUtils.rm_rf(dir) download_buildpack(dir, buildpack['url'], buildpack['ref']) build_buildpack(dir) export_environment(dir) write_release(dir) buildpack['framework'] = @last_framework buildpack['release'] = @last_release end print "Using release info from framworks: #{@frameworks.join(', ')}" File.write("#{ARGV[0]}/last_release.out", @release.to_yaml)
true
1ba333c200d9007b0ad0015a7b362e9577a55276
Ruby
dianeyasminec/phase-3-ruby-oo-basics-object-initialization-lab
/lib/person.rb
UTF-8
84
2.5625
3
[]
no_license
class Person attr_reader :name def initialize(name) @name = name end end
true
797cae4b260aa2a02f3de2d21cf30d2bc26f190a
Ruby
mitmedialab/MediaMeter-Coder
/utilities/blacklist_duplicate_entries.rb
UTF-8
846
2.78125
3
[]
no_license
require '../config/environment.rb' @duplicate_count = 0 @previous_duplicate_string = nil @previous_abstract = nil Article.all(:conditions=>['(blacklist_tag IS NULL or blacklist_tag="" or blacklist_tag ="duplicate")'], :order=>"source, pub_date asc, headline asc, abstract").each do |article| duplicate_string = "" + article.headline.to_s[0..40] + article.source.to_s + article.pub_date.to_s + article.abstract.to_s[0..10] if duplicate_string == @previous_duplicate_string article.blacklist_tag = "duplicate" article.save # if @previous_abstract != article.abstract # puts # puts @previous_abstract # puts article.abstract # end print "x" @duplicate_count += 1 end @previous_duplicate_string = duplicate_string @previous_abstract = article.abstract end puts "Duplicate Count: #{@duplicate_count}"
true
162166a5c179090acffb4739db70e91564c6b276
Ruby
SotirisKavv/oo-email-parser-cb-gh-000
/lib/email_parser.rb
UTF-8
630
3.453125
3
[ "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 EmailAddressParser attr_accessor :email_addresses_filetext, :email_addresses def initialize(email_addresses) @email_addresses_filetext = email_addresses @email_addresses = [] end def parse self.email_addresses_filetext.split(/ |, |,/).each do |email| if !@email_addresses.include?(email) @email_addresses << email end end @email_addresses end end
true
402e20283149d6fe376c00fff01294fafdb7e26c
Ruby
oscos/launch_school
/rb101/lesson3/easy1/x07.rb
UTF-8
381
3
3
[]
no_license
=begin Launch School: RB101 Programming Foundations - Lesson 3 - Practice Problems ExerciseName: [Easy 1(https://launchschool.com/lessons/263069da/assignments/e2593fe1) FileName: ex07.rb Answered On: 09/23/2020 =end # Make this into an un-nested array. flintstones = ["Fred", "Wilma", ["Barney", "Betty"], ["BamBam", "Pebbles"]] flintstones.flatten! # destructive p flintstones
true
27f6446dc0094c283da7bda183a9b9df8282dbf9
Ruby
eggyy1224/introduction_to_programming
/array/exercise7.rb
UTF-8
84
3.328125
3
[]
no_license
def increment_by_two arr p arr.map {|x| x+2} p arr end increment_by_two [1,2,3]
true
5ce1f8d12ce2a0e9988094ab5c9747a32d5ce9a9
Ruby
samueladesoga/inec-poll
/csv_to_json.rb
UTF-8
460
2.640625
3
[]
no_license
require 'csv' require 'json' extracted_data = CSV.table('SenatorialDistrict_Massaged.csv', :headers => false , :encoding => 'ISO-8859-1') senatorial_districts = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) } extracted_data.each {|line| senatorial_districts[line[0].strip][line[1].strip]= line[2].split(',').map(&:strip) } File.open('senatorial_districts.json', 'w') do |file| file.puts JSON.pretty_generate(senatorial_districts) end
true
c04f735271a36da94ec34bd9f0bfe52e0e7c22d5
Ruby
joaocferreira/algorithms
/ruby/linked_list/linked_list.rb
UTF-8
1,283
3.84375
4
[]
no_license
class Element attr_accessor :value, :next def initialize(value) @value = value @next = nil end end class LinkedList attr_reader :head def initialize(head = nil) @head = head end def append(new_element) current = head if head while current.next do current = current.next end current.next = new_element else @head = new_element end self end def get_position(position) current = head for i in (1...position) do current = current.next end current end def insert(new_element, position) if position == 1 new_element.next = head @head = new_element else previous = get_position(position - 1) new_element.next = previous.next previous.next = new_element end end def delete(value) if head.value == value @head = head.next else current = head while current.next do if current.next.value == value return current.next = current.next.next else current = current.next end end end end def insert_first(new_element) insert(new_element, 1) end def delete_first target = get_position(1) delete(target.value) if target target end end
true
83d8826e3bacd7f250cca9120c7f03258e2cc014
Ruby
nrazam95/AA-Online-Study
/muhd_nurul_azam_recap_exercise_3/recap_exercise_3.rb
UTF-8
5,727
3.765625
4
[]
no_license
#General Problems! def no_dupes?(array) hash = {} new_array = [] hash = Hash.new {|hash, key| hash[key] = 0} array.each do |num| hash[num] += 1 end hash.each do |k, v| new_array << k if v == hash.values.min end if new_array.include?(true) || new_array.include?(false) [] else new_array end end p no_dupes?([1, 1, 2, 1, 3, 2, 4]) # => [3, 4] p no_dupes?(['x', 'x', 'y', 'z', 'z']) # => ['y'] p no_dupes?([true, true, true]) p no_dupes?([false, true, false, nil]) def no_consecutive_repeats?(array) (0...array.length).each do |i| if array[i] == array[i+1] return false end end true end p no_consecutive_repeats?(['cat', 'dog', 'mouse', 'dog']) # => true p no_consecutive_repeats?(['cat', 'dog', 'dog', 'mouse']) # => false p no_consecutive_repeats?([10, 42, 3, 7, 10, 3]) # => true p no_consecutive_repeats?([10, 42, 3, 3, 10, 3]) # => false p no_consecutive_repeats?(['x']) # => true def char_indices(str) new_str = str.split("") hash = {} hash = Hash.new {|hash, key| hash[key] = []} new_str.each_with_index do |char, i| hash[char] << i end hash end p char_indices('mississippi') # => {"m"=>[0], "i"=>[1, 4, 7, 10], "s"=>[2, 3, 5, 6], "p"=>[8, 9]} p char_indices('classroom') # => {"c"=>[0], "l"=>[1], "a"=>[2], "s"=>[3, 4], "r"=>[5], "o"=>[6, 7], "m"=>[8]} def longest_streak(str) current = "" longest = "" (0...str.length).each do |i| if str[i] == str[i - 1] || i == 0 current += str[i] else current = str[i] end if current.length >= longest.length longest = current end end longest end p longest_streak('a') # => 'a' p longest_streak('accccbbb') # => 'cccc' p longest_streak('aaaxyyyyyzz') # => 'yyyyy p longest_streak('aaabbb') # => 'bbb' p longest_streak('abc') # => 'c' def bi_prime?(num) new_array = [] (2...num).each { |i| new_array << i if num % i == 0 && prime?(i)} new_array.any? do |n| m = num / n new_array.include?(m) end end def prime?(n) if n < 2 return false end (2...n).none? {|i| n % i == 0} end p bi_prime?(14) # => true p bi_prime?(22) # => true p bi_prime?(25) # => true p bi_prime?(94) # => true p bi_prime?(24) # => false p bi_prime?(64) # => false def vigenere_cipher(str, array) new_array = [] alphabet = ("a".."z").to_a str.each_char.with_index do |char, i| old_pos = alphabet.index(char) new_pos = alphabet.index(char) + array[i % array.length] new_array << alphabet[new_pos % alphabet.length] end new_array.join("") end p vigenere_cipher("toerrishuman", [1]) # => "upfssjtivnbo" p vigenere_cipher("toerrishuman", [1, 2]) # => "uqftsktjvobp" p vigenere_cipher("toerrishuman", [1, 2, 3]) # => "uqhstltjxncq" p vigenere_cipher("zebra", [3, 0]) # => "ceerd" p vigenere_cipher("yawn", [5, 1]) def vowel_rotate(str) new_str = str[0..-1] vowels = "aeiou" indices = (0...str.length).select { |i| vowels.include?(str[i])} new_indices = indices.rotate(-1) indices.each_with_index do |idx, i| new_vowel = str[new_indices[i]] new_str[idx] = new_vowel end new_str end p vowel_rotate('computer') # => "cempotur" p vowel_rotate('oranges') # => "erongas" p vowel_rotate('headphones') # => "heedphanos" p vowel_rotate('bootcamp') # => "baotcomp" p vowel_rotate('awesome') #Proc Problems class String def select(&prc) return "" if prc.nil? new_str = "" self.each_char do |char| new_str += char if prc.call(char) end new_str end def map!(&prc) self.each_char.with_index do |char, idx| self[i] = prc.call(char, i) end end end p "app academy".select { |ch| !"aeiou".include?(ch) } # => "pp cdmy" p "HELLOworld".select { |ch| ch == ch.upcase } # => "HELLO" p "HELLOworld".select # => "" #Recursion Problems def multiply(t, b) return 0 if t == 0 if b.negative?() && t.negative?() -b + multiply(t + 1, b) elsif t.negative?() -b + multiply(t + 1, b) else b + multiply(t - 1, b) end end p multiply(3, 5) # => 15 p multiply(5, 3) # => 15 p multiply(2, 4) # => 8 p multiply(0, 10) # => 0 p multiply(-3, -6) # => 18 p multiply(3, -6) # => -18 p multiply(-3, 6) # => -18 def lucas_sequence(num) return [] if num == 0 return [2] if num == 1 return [2, 1] if num == 2 new_array = lucas_sequence(num - 1) new_arr = new_array[-1] + new_array[-2] new_array << new_arr new_array end p lucas_sequence(0) # => [] p lucas_sequence(1) # => [2] p lucas_sequence(2) # => [2, 1] p lucas_sequence(3) # => [2, 1, 3] p lucas_sequence(6) # => [2, 1, 3, 4, 7, 11] p lucas_sequence(8) # => [2, 1, 3, 4, 7, 11, 18, 29] def prime_factorization(num) (2...num).each do |i| if num % i == 0 i2 = num / i return [*prime_factorization(i), *prime_factorization(i2)] end end [num] end p prime_factorization(12) # => [2, 2, 3] p prime_factorization(24) # => [2, 2, 2, 3] p prime_factorization(25) # => [5, 5] p prime_factorization(60) # => [2, 2, 3, 5] p prime_factorization(7) # => [7] p prime_factorization(11) # => [11] p prime_factorization(2017) # => [2017]
true
c68a0eae7db3196bc02edff04eb59a2022ed5afe
Ruby
agisga/mixed_models
/examples/LMM_from_formula.rb
UTF-8
1,547
2.984375
3
[ "BSD-3-Clause" ]
permissive
require 'mixed_models' ############################################################################## # Model with numerical and categorical variables as fixed and random effects # ############################################################################## df = Daru::DataFrame.from_csv './data/alien_species.csv' # mixed_models expects all variable names to be Symbols (not Strings): df.vectors = Daru::Index.new( df.vectors.map { |v| v.to_sym } ) model_fit = LMM.from_formula(formula: "Aggression ~ Age + Species + (Age | Location)", data: df) # Print some results puts "REML criterion: \t#{model_fit.deviance}" puts "Fixed effects:" puts model_fit.fix_ef puts "Standard deviation: \t#{model_fit.sigma}" puts "Random effects:" puts model_fit.ran_ef puts "Predictions of aggression levels on a new data set:" dfnew = Daru::DataFrame.from_csv './data/alien_species_newdata.csv' # mixed_models expects all variable names to be Symbols (not Strings): dfnew.vectors = Daru::Index.new( dfnew.vectors.map { |v| v.to_sym } ) puts model_fit.predict(newdata: dfnew) puts "88% confidence intervals for the predictions:" ci = Daru::DataFrame.new(model_fit.predict_with_intervals(newdata: dfnew, level: 0.88, type: :confidence), order: [:pred, :lower88, :upper88]) puts ci.inspect puts "88% prediction intervals for the predictions:" pi = Daru::DataFrame.new(model_fit.predict_with_intervals(newdata: dfnew, level: 0.88, type: :prediction), order: [:pred, :lower88, :upper88]) puts pi.inspect
true
a1365386d7c5f768a379a125ff17469cf4240bf2
Ruby
JFVF/cucumber_022015
/Ruben/Practice3.rb
UTF-8
1,652
3.78125
4
[]
no_license
puts "type your name please..." names = gets.chomp puts "hello #{names} how are yo today" =begin commented code "Some Test".chomp(' Test') "Some Test\r\n".chomp "\tRobert Martin\r\n".strip =end puts "give me a number" firstNumber = gets.chomp.to_f defaultValue = 20 puts result = "Result = #{firstNumber + defaultValue}" def wellcome (name = "", age = 0) months = 12 days = 30 hours = 24 converted = age * months * days * hours puts "\nHI #{name.upcase}" puts "Your #{age} years is equals to #{converted} hours" end wellcome(names, 25) wellcome "ruben", 25 def transformCelsius(celsius = 1.1) fahrenheit = (((9* celsius ) /5) + 32) return fahrenheit.to_s+" fahrenheit" end puts transformCelsius 37.5 def transformfahrenheit(fahrenheit = 1.1) ((5*(fahrenheit - 32))/9).to_s+" celsius" end puts transformfahrenheit 98 puts "\ntype passenger name" name = gets.chomp.to_s puts "type destination city" destination = gets.chomp.to_s puts "type ticket price" price = gets.chomp.to_f def getPassengerInformation(passengerName = "", destinationCity = "", ticketPrice = 0.0) dolarValue = 6.97 if destinationCity.length == 0 destinationCity = "CBBA" end convertedTickedPrice = ticketPrice / dolarValue puts "\n Name: #{passengerName}\n Destination City: #{destinationCity}\n Price: #{convertedTickedPrice} $" end getPassengerInformation name,destination, price puts "\ntype seconds" secondValue = gets.chomp def calculate (seconds = 0) hour = 60 minute = 60 calculatedHours = seconds.to_i/(hour*minute) calculatedMinutes = seconds.to_i/60 return calculatedHours, calculatedMinutes end #call calculate method puts "\n#{calculate secondValue}"
true
539708c204ed68027bb917ea128f91acfe654850
Ruby
JoshvaR88/mutant
/spec/support/mutation_verifier.rb
UTF-8
1,793
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class MutationVerifier include Adamantium::Flat, Concord.new(:original_node, :expected, :generated) # Test if mutation was verified successfully # # @return [Boolean] # # @api private # def success? unparser.success? && missing.empty? && unexpected.empty? end # Return error report # # @return [String] # # @api private # def error_report unless unparser.success? return unparser.report end mutation_report end private # Return unexpected mutations # # @return [Array<Parser::AST::Node>] # # @api private # def unexpected generated - expected end memoize :unexpected # Return mutation report # # @return [String] # # @api private # # rubocop:disable AbcSize # def mutation_report message = ['Original-AST:', original_node.inspect, 'Original-Source:', Unparser.unparse(original_node)] if missing.any? message << 'Missing mutations:' message << missing.map(&method(:format_mutation)).join("\n-----\n") end if unexpected.any? message << 'Unexpected mutations:' message << unexpected.map(&method(:format_mutation)).join("\n-----\n") end message.join("\n======\n") end # Format mutation # # @return [String] # # @api private # def format_mutation(node) [ node.inspect, Unparser.unparse(node) ].join("\n") end # Return missing mutations # # @return [Array<Parser::AST::Node>] # # @api private # def missing expected - generated end memoize :missing # Return unparser verifier # # @return [Unparser::CLI::Source] # # @api private # def unparser Unparser::CLI::Source::Node.new(Unparser::Preprocessor.run(original_node)) end memoize :unparser end # MutationVerifier
true
d38036698233970cd957a2dd2c70e7e3fedaff82
Ruby
ShanaHunte/Homework
/Homework-1/problem-3.rb
UTF-8
68
2.671875
3
[]
no_license
def greeting join_strings('Hello', 'Dolly!') puts(greeting) end
true
e9e51eb316cc021470cd06c7baf7e5027d476e1b
Ruby
zwhite11/School-Work
/Ruby On Rails/Module 3/Assignment2Submission/assignment2.rb
UTF-8
535
2.984375
3
[]
no_license
#Agile Development with Ruby on Rails: assignment 2 #Zachary White words = IO.read("assignment_two_text.txt").split(/\s+/) domain_pattern = /\w+@\w+.com/ words_with_domains = words.select { |word| word =~ domain_pattern } just_domains = Array.new words_with_domains.each{ |domain| just_domains.push(domain[/\w+.com/])} unique_domains = just_domains.uniq unique_domains.sort! unique_domains.each do |domain| domain_count = just_domains.count(domain).to_s result = domain << ": " << domain_count << " time(s)" puts result.rjust(40) end
true
6202a74e5a92f6bc63eeb6d7f5a68f207b3d8ec8
Ruby
kakitaku00/RubyForProfessionl
/4/4_5/4_5_0.rb
UTF-8
365
4.25
4
[]
no_license
# 範囲(Range) # Rubyには「AからB』までといった範囲オブジェクトが存在する 1..5 # 最後の値を含む 1...5 # 最後の値を含まない (1..5).class #=> Range (1...5).class #=> Range # Rangeを変数に格納せず呼び出す際は()で囲まないとエラーとなる 1..5.include?(1) #=> NoMethodError (1..5).include?(1) #=> true
true
f5fc863331b873101d575164323dd3f53c2d5b8c
Ruby
d3vkit/battleship
/lib/game_manager.rb
UTF-8
1,266
3.140625
3
[]
no_license
require 'singleton' require_relative 'input_manager' require_relative 'text_manager' class GameManager include Singleton attr_accessor :turn, :players def initialize @turn = 0 @players = [] end def next_turn @turn = determine_next_turn end def start_turn # error if no players current_player = players[turn] opponent = players[determine_next_turn] GameManager.write("${current_player.name} Turn\n") GameManager.write('Your Ships') current_player.grid.draw GameManager.write('Enemy Ships') opponent.grid.draw(fog_of_war: true) # current_player.start_turn end def self.set_proc_title $0 = 'Battleship' Process.setproctitle('Battleship') system("printf \"\033]0;Battleship\007\"") end def self.clear_screen return if ENV['DEBUG'] system 'clear' end def self.write(text, color: nil) text = TextManager.public_send(color, text) if color puts text end def self.collect_input(prepend_text = nil) InputManager.collect_input(prepend_text) end def self.quit write('Thanks For Playing!', color: 'green') exit(true) end def self.bounds { x: 10, y: 10 } end private def determine_next_turn turn == 1 ? 0 : 1 end end
true
ec895ae2dd9b76dac4e970bb6a09710165b3037d
Ruby
idaolson/relational-rails
/spec/models/boba_shops/boba_shops_spec.rb
UTF-8
1,419
2.578125
3
[]
no_license
require 'rails_helper' describe BobaShop do describe 'associations' do it {should have_many :drinks} end describe 'methods' do before(:each) do @store_1 = BobaShop.create!( name: 'Sharetea', drive_thru: false, capacity: 25 ) @store_2 = BobaShop.create!( name: 'Cha4Tea', drive_thru: false, capacity: 25 ) @drink_1 = @store_1.drinks.create!( name: 'Okinawan Milk Tea', in_stock: true, price: 6.99 ) @drink_2 = @store_1.drinks.create!( name: 'Hazelnut Milk Tea', in_stock: true, price: 6.99 ) @drink_3 = @store_2.drinks.create!( name: 'Honey Milk Tea', in_stock: true, price: 6.99 ) @drink_4 = @store_2.drinks.create!( name: 'Taro Milk Tea', in_stock: true, price: 6.99 ) end it 'can order shops by creation time' do expected = [@store_2, @store_1] expect(BobaShop.order_by_creation_time).to eq(expected) end it 'can count the number of drinks' do expect(@store_1.drinks_count).to eq(2) end it 'can sort drinks alphabetically' do expected = [ @drink_2, @drink_1 ] expect(@store_1.sort_drinks(true)).to eq(expected) expect(@store_1.sort_drinks(false)).to eq([@drink_1, @drink_2]) end end end
true
807994c9d55de12d20d77dc42ae0d8955f176603
Ruby
kpalania/planit_app-api-scaffold
/lib/database/mongodb.rb
UTF-8
721
2.59375
3
[]
no_license
module Database module MongoDB # Save the object to MongoDB def persist object if object.save $logger.debug "..persisted to MongoDB: \n....#{object.inspect}\n" else raise Mongoid::Errors::MongoidError, "#{object.class} could not be saved" end end # TODO(krish): Not used currently. def persist_to_database object, database object.with(session: database).save! $logger.debug "..persisted to MongoDB: database: #{database.inspect}\n....#{object.inspect}\n" end def persist_and_switch object, in_database, to_database Mongoid.override_database in_database persist object Mongoid.override_database to_database end end end
true
7b39a69a46aff2257d118c0a7f458fffe534b5a3
Ruby
jmschles/codeeval
/moderate/stack_implementation.rb
UTF-8
417
3.515625
4
[]
no_license
class Stack attr_reader :stack def initialize @stack = [] end def push(el) @stack << el end def pop @stack.delete_at(-1) end end File.open(ARGV[0]).each_line do |line| next if line.chomp.empty? data = line.chomp.split(' ') s = Stack.new data.each { |el| s.push(el) } to_print = [] until s.stack.empty? to_print << s.pop s.pop end puts to_print.join(' ') end
true
5edcd8e77eade72e6548b0ef5d590b75be86d96b
Ruby
whatalnk/codejam
/kickstart/2017/Practice-2/B.rb
UTF-8
834
2.765625
3
[ "MIT" ]
permissive
T = gets.chomp.to_i R_MAX = 3000 C_MAX = 3000 T.times do |cc| r, c, k = gets.chomp.split(' ').map(&:to_i) m = Array.new(r){Array.new(c, 0)} cumsum = Array.new(r+1){Array.new(c+1, 0)} k.times do ri, ci = gets.chomp.split(' ').map(&:to_i) m[ri][ci] = 1 end r.times do |i| c.times do |j| cumsum[i+1][j+1] = m[i][j] + cumsum[i][j+1] + cumsum[i+1][j] - cumsum[i][j] end end ret = 0 [r, c].min.times do |i| i += 1 if i == 1 then # 1 ret += (r * c - k) else (i..r).each do |row| (i..c).each do |col| n_monster = cumsum[row][col] - cumsum[row-i][col] - cumsum[row][col-i] + cumsum[row-i][col-i] if n_monster == 0 then ret += 1 end end end end end # cumsum.each{|x| p x} puts "Case ##{cc+1}: #{ret}" end
true
87063989b4b9463d8af4a55c2b540a4cf47fa80c
Ruby
ChewbaccaJerky/Code-Challenges
/practice-thy-algorithms/Leetcode/ruby/container_with_most_water.rb
UTF-8
859
3.65625
4
[]
no_license
# Leetcode Problem #11 # Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). # n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). # Find two lines, which together with x-axis forms a container, such that the container contains the most water. # Note: You may not slant the container and n is at least 2. def container_with_most_water(height) max_area = 0 left = 0 right = height.length - 1 until right - left == 0 do length = height[left] < height[right] ? height[left] : height[right] width = right - left area = length * width max_area = area if max_area < area if height[left] <= height[right] left += 1 else right -= 1 end end max_area end
true
44be487655e203982eb7b693a70238ae03bcc7f5
Ruby
Ben-Gelbard/trading--robot
/main.rb
UTF-8
1,882
3.328125
3
[]
no_license
# require gems require 'stock_quote' # require modules require_relative 'methods.rb' # create User class class User attr_accessor :account_name, :account_balance, :user_stocks, :cart def initialize name @account_name = name @account_balance = 0 @user_stocks = [] @cart = [] end def add_stock_to_portfolio stock @user_stocks << stock end end # create Stock class class Stock attr_accessor :name, :symbol, :price, :pe_ratio, :change_percent, :quantity, :subtotal_cost def initialize(name, symbol) @name = name @symbol = symbol @price = StockQuote::Stock.quote(symbol).latest_price @pe_ratio = StockQuote::Stock.quote(symbol).pe_ratio @change_percent = StockQuote::Stock.quote(symbol).change_percent @quantity = quantity @subtotal_cost = subtotal_cost end end # Create User instances account1 = User.new("Ben") account2 = User.new("Aitzu") # Create Stock instances apple = Stock.new('Apple', 'AAPL') netflix = Stock.new('Netflix', "NFLX") facebook = Stock.new('Facebook', "FB") amazon = Stock.new('Amazon', "AMZN") amex = Stock.new('American Express', "AXP") tesla = Stock.new('Tesla', "TSLA") alibaba = Stock.new('Alibaba', "BABA") a_airlines = Stock.new('American Airlines', "AAL") nike = Stock.new('Nike', "NKE") brk = Stock.new('BERKSHIRE HATHAWAY', "BRK.A") # Add stocks to the user account account2.add_stock_to_portfolio(apple) account2.add_stock_to_portfolio(netflix) account2.add_stock_to_portfolio(facebook) account2.add_stock_to_portfolio(amazon) account2.add_stock_to_portfolio(amex) account2.add_stock_to_portfolio(tesla) account2.add_stock_to_portfolio(alibaba) account2.add_stock_to_portfolio(a_airlines) account2.add_stock_to_portfolio(nike) account2.add_stock_to_portfolio(brk) # run the code Methods.cash_deposit(account2)
true
9f4560144df86636472b1879a988acfc2cfd6cad
Ruby
hnamitha1/broadcaster_promotions
/run.rb
UTF-8
1,322
2.90625
3
[]
no_license
#!/usr/bin/env ruby require './lib/broadcaster' require './lib/delivery' require './lib/material' require './lib/order' require './lib/price_discount' require './lib/delivery_discount' standard_delivery = Delivery.new(:standard, 10.0) express_delivery = Delivery.new(:express, 20.0) broadcaster_1 = Broadcaster.new(1, 'Viacom') broadcaster_2 = Broadcaster.new(2, 'Disney') broadcaster_3 = Broadcaster.new(3, 'Discovery') broadcaster_4 = Broadcaster.new(4, 'ITV') broadcaster_5 = Broadcaster.new(5, 'Channel 4') broadcaster_6 = Broadcaster.new(6, 'Bike Channel') broadcaster_7 = Broadcaster.new(7, 'Horse and Country') material = Material.new('WNP/SWCL001/010') material_1 = Material.new('ZDW/EOWW005/010') price_discount = PriceDiscount.new(30, 10) delivery_discount = DeliveryDiscount.new(:express, 15, 2) order_1 = Order.new(material, delivery_discount, price_discount) order_2 = Order.new(material_1, delivery_discount, price_discount) order_1.add broadcaster_1, standard_delivery order_1.add broadcaster_2, standard_delivery order_1.add broadcaster_3, standard_delivery order_1.add broadcaster_7, express_delivery order_2.add broadcaster_1, express_delivery order_2.add broadcaster_2, express_delivery order_2.add broadcaster_3, express_delivery print order_1.output print "\n" print order_2.output print "\n"
true
c82c11f643ca19650b1118db4604f409ab832065
Ruby
Hack-Slash/sunday_afternoon
/factorial_recursive.rb
UTF-8
116
3.203125
3
[]
no_license
def factorial(number) if number == 1 return number end number * factorial(number - 1) end p factorial(5)
true
453c9ad81af5f0b9d26d621a12da14387a91f218
Ruby
Kenshincp/StringCalculator
/lib/string_calculator.rb
UTF-8
480
3.65625
4
[]
no_license
class StringCalculator def calcular valor = nil if valor != nil # Primer spilt con menos # numeros = valor.split('-').map{|str| str.to_i}.inject(0, :+) numeros = sumarValores valor numeros else "Este es el metódo" end end # definimos el método para sumar valores de un array def sumarValores cadena resultado = cadena.split('+').map{|str| str.to_i}.inject(0, :+) resultado end end
true
0ac0fc66a95b45810760f383da39414286f0bdcb
Ruby
jeffrafter/marvin
/lib/marvin/irc/server/user/handle_mixin.rb
UTF-8
4,502
2.671875
3
[]
no_license
module Marvin::IRC::Server::User::HandleMixin def handle_incoming_pass(opts = {}) @password = opts[:password] end def handle_incoming_user(opts = {}) @user = opts[:user] @mode = opts[:mode] @real_name = opts[:real_name] welcome_if_complete! end def handle_incoming_nick(opts = {}) nick = opts[:new_nick] if !nick.blank? && !Marvin::IRC::Server::UserStore.nick_taken?(nick.downcase) if !(new_nick = @nick.nil?) logger.debug "Notifying all users of nick change: #{@nick} => #{nick}" # Get all users and let them now we've changed nick from @nick to nick users = [self] @channels.each do |c| users += c.members.values end users.uniq.each { |u| u.notify :NICK, nick, :prefix => prefix } dispatch :outgoing_nick, :nick => @nick, :new_nick => nick end # Update the store values Marvin::IRC::Server::UserStore.delete(@nick.downcase) unless @nick.blank? Marvin::IRC::Server::UserStore[nick.downcase] = self # Change the nick and reset the number of attempts @nick = nick @nick_attempts = 0 # Finally, update the prefix. update_prefix! welcome_if_complete! if new_nick elsif Marvin::IRC::Server::UserStore[nick.downcase] != self # The nick is taken # TODO: Remove hard coded nick attempts limit if @nick_attempts > 5 # Handle abort here. logger.debug "User has gone over nick attempt limits - Killing connection." kill_connection! dispatch :outgoing_nick_killed, :client => self else logger.debug "Noting users nick is taken, warning" err :NICKNAMEINUSE, "*", nick, ":Nickname is already in use." @nick_attempts += 1 end end end def handle_incoming_join(opts = {}) return if @prefix.blank? opts[:target].split(",").each do |channel| # If the channel name is invalud, let the user known and dispatch # the correct event. if channel !~ Marvin::IRC::Server::UserConnection::CHANNEL logger.debug "Attempted to join invalid channel name '#{channel}'" err :NOSUCHCHANNEL, channel, ":That channel doesn't exist" dispatch :invalid_channel_name, :channel => channel, :client => self return end chan = (Marvin::IRC::Server::ChannelStore[channel.downcase] ||= Marvin::IRC::Server::Channel.new(channel)) if chan.join(self) rpl :TOPIC, channel, ":#{chan.topic.blank? ? "There is no topic" : nchan.topic}" rpl :NAMREPLY, "=", channel, ":#{chan.members.map { |m| m.nick }.join(" ")}" rpl :ENDOFNAMES, channel, ":End of /NAMES list." @channels << chan else logger.debug "Couldn't join channel '#{channel}'" end end end def handle_incoming_ping(opts = {}) command :PONG, ":#{opts[:data]}" end def handle_incoming_pong(opts = {}) # Decrease the ping count. @ping_count -= 1 @ping_count = 0 if @ping_count < 0 logger.debug "Got pong: #{opts[:data]}" end def handle_incoming_message(opts = {}) return if @prefix.blank? unless (t = target_from(opts[:target])).blank? t.message self, opts[:message] end end def handle_incoming_notice(opts = {}) return if @prefix.blank? unless (t = target_from(opts[:target])).blank? t.notice self, opts[:message] end end def handle_incoming_part(opts = {}) t = opts[:target].downcase if !(chan = Marvin::IRC::Server::ChannelStore[t]).blank? if chan.part(self, opts[:message]) @channels.delete(chan) else err :NOTONCHANNEL, opts[:target], ":Not a member of that channel" end else err :NOSUCHNICK, opts[:target], ":No such nick/channel" end end def handle_incoming_quit(opts = {}) return unless @alive @alive = false @channels.each { |c| c.quit(self, opts[:message]) } kill_connection! end def handle_incoming_topic(opts = {}) return if @prefix.blank? || opts[:target].blank? c = Marvin::IRC::Server::ChannelStore[opts[:target].downcase] return if c.blank? if !@channels.include?(c) err :NOTONCHANNEL, opts[:target], ":Not a member of that channel" elsif opts[:message].nil? t = c.topic if t.blank? rpl :NOTOPIC, c.name, ":No topic is set" else rpl :TOPIC, c.name, ":#{t}" end else c.topic self, opts[:message].strip end end end
true
f8b102dff25f1ccfb78632778b4d6c0fbe39a351
Ruby
alexisspa9/connect_four
/spec/player_spec.rb
UTF-8
1,851
3.3125
3
[]
no_license
require "./lib/connect_four/player.rb" require "./lib/connect_four/board.rb" RSpec.describe Player do context "#initialize" do it "requires input" do expect { Player.new }.to raise_error(ArgumentError) end it "initializes with a valid hash" do expect{ Player.new({name: "Bob", marker: "H"})}.to_not raise_error end end before do @player = Player.new({ name: "Laura", marker: "X"}) end context "#name" do it "returns the name" do expect(@player.name).to eql "Laura" end it "can't change the name" do expect { @player.name = "Bob" }.to raise_error(NoMethodError) end end context "#marker" do it "returns the marker" do expect(@player.marker).to eql "X" end it "works for a unicode marker" do player2 = Player.new({ name: "Lisa", marker: "\u2605" }) expect(player2.marker).to eql "★" end it "can't change the marker" do expect { @player.marker = "O" }.to raise_error(NoMethodError) end end context "#drop_token" do before do @board = Board.new @board.grid[5][2].value = "O" @board.grid[3][4].value = "O" @board.grid[0][1].value = "X" end it "drops tokens to the bottom of empty columns" do @player.drop_token(@board, 0) expect(@board.grid[5][0].value).to eql "X" end it "drops tokens on top of a bottom token" do @player.drop_token(@board, 2) expect(@board.grid[4][2].value).to eql "X" end it "drops tokens on top of higher up tokens" do @player.drop_token(@board, 4) expect(@board.grid[2][4].value).to eql "X" end it "returns error message when a column is full" do expect(@player.drop_token(@board, 1)).to eql "Invalid move: Column 1 is already full." end end end
true
9074f23a45d5753c0007d1546a2e8f59d6b1669f
Ruby
micahlagrange/adventurer-factory
/lib/adventurer_factory/dice.rb
UTF-8
1,481
3.484375
3
[]
no_license
module AdventurerFactory class ArgumentError < StandardError; end class Die attr_reader :value, :sides def initialize(sides) @sides = sides @value = roll end def > val @value > val end def < val @value < val end def to_h {sides: @sides, value: @value} end def to_s "#{self.class.name}::sides[#{@sides}]::value[#{@value}]" end alias greater_than? > alias less_than? < private def roll 1 + rand(@sides) end end module Dice def self.d20 Die.new(20) end def self.advantage(die_type = :d20) bulk(2, die_type).max_by(&:value) end def self.disadvantage(die_type = :d20) bulk(2, die_type).min_by(&:value) end def self.bulk(count, die) raise ArgumentError.new("Count must be an integer") unless count.class == Integer raise ArgumentError.new("Die type must be a symbol such as :d6") unless die.class == Symbol raise ArgumentError.new("Die type must match /^d(\d+)$/") unless die =~ /^d(\d+)$/ dice = [] count.times do dice << send(die) end return dice end def self.die_with_n_sides(n) Die.new(n) end def self.method_missing(meth, *args, &block) if meth =~ /^d\d+$/ sides = meth.to_s.match(/^d(.*)$/)[1] return die_with_n_sides(sides.to_i) end super.method_missing(meth, *args, &block) end end end
true
3ee2151cb3b8b1af7ccfe7c9e8e942d0dcaecf09
Ruby
alexandralaudon/hash-array-pair-one
/spec/bluegrass_parser_spec.rb
UTF-8
1,372
2.75
3
[]
no_license
require "spec_helper" require "bluegrass_parser" describe BluegrassParser do let(:bluegrass_parser) { BluegrassParser.new} describe "#get_artists" do it "returns an array of all artists from the data" do expect(bluegrass_parser.get_artists).to eq ["Foggy Mountain Boys", "Doc Watson"] end end describe "#foggy_mountain_boys_songs" do it "returns the songs for the Foggy Mountain Boys" do expect(bluegrass_parser.foggy_mountain_boys_songs).to eq ["Foggy Mountain Breakdown", "Polka on a Banjo"] end end describe "#doc_watson_songs" do it "returns the songs for Doc Wats" do expect(bluegrass_parser.doc_watson_songs).to eq ["Bottle of Wine", "Don't Think Twice, It's All Right"] end end describe "#the_good_ole_days" do it "returns the dates from all the songs in the data" do expect(bluegrass_parser.the_good_ole_days).to eq ["1949", "1961", "1973", "1961"] end end describe "#songs_for_artist" do it "returns the songs for the given artist" do expect(bluegrass_parser.songs_for_artist("Doc Watson")).to eq ["Bottle of Wine", "Don't Think Twice, It's All Right"] end end describe "#songs_for_year" do it "returns songs for a given year" do expect(bluegrass_parser.songs_for_year("1961")).to eq ["Polka on a Banjo", "Don't Think Twice, It's All Right"] end end end
true
d68ef0a84aa687cf0e1f39301b67fae36bbe91d7
Ruby
yuki3738/AtCoder
/abc/abc094/a/main.rb
UTF-8
74
3
3
[]
no_license
a, b, x = gets.split.map(&:to_i) puts x.between?(a, a + b) ? "YES" : "NO"
true
050c01c593a5649f9f8e69c187cad9286f6bc5ea
Ruby
SoniaSS05/basketball_teams-backend
/app/application.rb
UTF-8
5,021
2.59375
3
[]
no_license
class Application def call(env) res = Rack::Response.new req = Rack::Request.new(env) #APPLICATION ROUTES #team Index if req.path == ('/teams') && req.get? return [200, { 'Content-Type' => 'application/json' }, [Team.all.to_json ]] end #player Index if req.path == ('/player') && req.get? return [200, { 'Content-Type' => 'application/json' }, [Player.all.to_json ]] end #Game Index if req.path == ('/game') && req.get? return [200, { 'Content-Type' => 'application/json' }, [Game.all.to_json ]] end #Position Index if req.path == ('/position') && req.get? return [200, { 'Content-Type' => 'application/json' }, [Position.all.to_json ]] end #team Delete if req.path.match('/team/') && req.delete? id = req.path.split('/')[2] puts id begin team = Team.find(id) team.destroy return[200, { 'Content-Type' => 'application/json' }, [{message: "Team destroyed"}.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Team not deleted"}.to_json]] end end #player Create if req.path == ('/player') && req.post? body = JSON.parse(req.body.read) new_player = Player.create(body) return [201, { 'Content-Type' => 'application/json' }, [new_player.to_json ]] end #team Create if req.path == ('/team') && req.post? body = JSON.parse(req.body.read) new_team = Team.create(body) return [201, { 'Content-Type' => 'application/json' }, [new_team.to_json ]] end #player Show if req.path.match('/player/') && req.get? id = req.path.split('/')[2] begin player = Player.find(id) return [200, { 'Content-Type' => 'application/json' }, [player.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Player not found"}.to_json]] end end #player Update if req.path.match('/player/') && req.patch? id = req.path.split('/')[2] body= JSON.parse(req.body.read) begin player = Player.find(id) player.update(body) return [201, { 'Content-Type' => 'application/json' }, [player.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Player not found - not updated"}.to_json]] end end #player Delete if req.path.match('/player/') && req.delete? puts "entre aqui" id = req.path.split('/')[2] begin player = Player.find(id) puts player player.destroy return[200, { 'Content-Type' => 'application/json' }, [{message: "Player destroyed"}.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Player not deleted"}.to_json]] end end #Game Create #Game Show if req.path.match('/game/') && req.get? id = req.path.split('/')[2] begin game = Game.find(id) return [200, { 'Content-Type' => 'application/json' }, [game.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Game not found"}.to_json]] end end #Game Update if req.path.match('/game/') && req.put? id = req.path.split('/')[2] body= JSON.parse(req.body.read) begin game = Game.find(id) game_update = game.update(body) return [201, { 'Content-Type' => 'application/json' }, [game_update.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Game not found - not updated"}.to_json]] end end #Game Delete if req.path.match('/game/') && req.delete? id = req.path.split('/')[2] begin game = Game.find(id) game.destroy return[200, { 'Content-Type' => 'application/json' }, [{message: "Game destroyed"}.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Game not deleted"}.to_json]] end end #performance Create #performance Show if req.path.match('/performance/') && req.get? id = req.path.split('/')[2] begin performance = Performance.find(id) return [200, { 'Content-Type' => 'application/json' }, [performance.to_json]] rescue ActiveRecord::RecordNotFound return [404, { 'Content-Type' => 'application/json' }, [{message: "Performance not found"}.to_json]] end end #performance Update #performance Delete if req.path.match('/performance/') && req.delete? id = req.path.split('/')[2] begin performance = Performance.find(id) performance.destroy return[200, { 'Content-Type' => 'application/json' }, [{message: "Performance destroyed"}.to_json]] rescue return [404, { 'Content-Type' => 'application/json' }, [{message: "Performance not deleted"}.to_json]] end end res.finish end end
true
925a02493113297789f323954e0243fef92611fc
Ruby
Sajonara/Ruby
/datei/file1.rb
UTF-8
1,090
3.59375
4
[]
no_license
# Dieses Script präsentiert den Umgang mit Dateien # Datei öffnen File.open("./argv.rb", "r") do |datei| # Datei zum Lesen öffnen mit Option "r" n = 1 while zeile = datei.gets print "#{n}:" puts zeile # Inhalt Zeile für Zeile ausgeben n += 1 end end File.open("./testfile.rb", "w") do |datei| # Datei zum Schreiben öffnen mit Option "w" datei.puts("Dies ist ein Test.") end File.open("./testfile.rb", "r") do |datei| # Vorher selbst erzeugte Datei zum Lesen öffnen n = 1 while zeile = datei.gets print "#{n}: " puts zeile # Inhalt Zeile für Zeile ausgeben n += 1 end end file = File.open("./argv.rb") # Andere Art, Dateien zu öffnen lines = file.readlines p lines file.close i = 1 Dir.open(".").each do |file| # Ein Ordner-Listing erstellen und ausgeben listing = [] listing << file if File.directory?(file) # Handelt es sich um einen Ordner? print("#{i} | Verzeichnis | ") else # Oder um eine Datei? print("#{i} | Datei | ") end puts("#{file}") i += 1 end
true
e01376e80443eea7f892f7f2585b817281e16025
Ruby
alanzoppa/proforma
/lib/forms.rb
UTF-8
2,259
2.5625
3
[]
no_license
require 'validation' require 'exceptions' require 'getters' require 'formhash' class Form include TestModule if $test_env include Validation include Getters attr_accessor :fields, :errors, :valid def initialize(data=nil) _define_defaults _initialize_fields _prepare_getters _raise_usage_validations unless data.nil? # Read: If it's time to do some validation raise ArgumentError.new("You can only validate a Hash") unless data.class.ancestors.include?(Hash) @raw_data = FormHash.import(data) # Rails creates POST hashes with string keys @_cleaned_data = @raw_data.dup _run_simple_validations _run_regex_validations _run_custom_validations _run_whole_form_validations _collect_errors #Must be last end end def _define_defaults # defaults for @settings below @settings = {:wrapper => :p, :wrapper_attributes => nil} @settings = @settings.merge(redefine_defaults) if respond_to? :redefine_defaults end def _initialize_fields @fields = Array.new self.class.class_variables.each do |var| field = self.class.send("class_variable_get", var).dup # the field itself field_name = var.to_s.gsub(/^@@/, '') # the field's name with the leading "@@" stripped _attach_field_attributes(field, field_name) if field.class.ancestors.include? Field end end def _attach_field_attributes(field, field_name) field.name = field_name.to_sym field.hash_wrapper_name = "#{@settings[:hash_wrapper]}[#{field_name}]" unless @settings[:hash_wrapper].nil? field.form_settings = @settings @fields << field end def to_html(tag=@settings[:wrapper], attributes=@settings[:wrapper_attributes]) output = String.new unless @errors.nil? or @errors[:form].nil? error_list = @errors[:form].map {|error| wrap_tag(error, :li)}.join output += wrap_tag(error_list, :ul, :class => :form_errors) end @fields.each do |field| output += wrap_tag(field.to_full_html, tag, attributes) end return output end def with_defaults(hash) hash = FormHash.import(hash) hash.keys.each do |key| field = self.get_instance(key) field.set_default!(hash[key]) end return self end end
true
c61d497acc9b2f50319d9aaf5a3e6e6d1101aa2a
Ruby
nervosnetwork/ckb-explorer
/app/utils/query_key_utils.rb
UTF-8
705
2.53125
3
[ "MIT" ]
permissive
module QueryKeyUtils class << self def integer_string?(query_key) /\A\d+\z/.match?(query_key) end def valid_hex?(query_key) start_with_default_hash_prefix?(query_key) && length_is_valid?(query_key) && hex_string?(query_key) end def start_with_default_hash_prefix?(query_key) query_key.start_with?(Settings.default_hash_prefix) end def length_is_valid?(query_key) query_key.length == Settings.default_with_prefix_hash_length.to_i end def hex_string?(query_key) !query_key.delete_prefix(Settings.default_hash_prefix)[/\H/] end def valid_address?(query_key) CkbUtils.parse_address(query_key) rescue nil end end end
true
51659a6d17438181678b218ec0a5b3378914f03e
Ruby
flori/tins
/lib/tins/attempt.rb
UTF-8
3,728
3.015625
3
[ "MIT" ]
permissive
module Tins module Attempt # Attempts code in block *attempts* times, sleeping according to *sleep* # between attempts and catching the exception(s) in *exception_class*. # # *sleep* is either a Proc returning a floating point number for duration # as seconds or a Numeric >= 0 or < 0. In the former case this is the # duration directly, in the latter case -*sleep* is the total number of # seconds that is slept before giving up, and every attempt is retried # after a exponentially increasing duration of seconds. # # Iff *reraise* is true the caught exception is reraised after running out # of attempts. def attempt(opts = {}, &block) sleep = nil exception_class = StandardError prev_exception = nil if Numeric === opts attempts = opts else attempts = opts[:attempts] || 1 attempts >= 1 or raise ArgumentError, 'at least one attempt is required' exception_class = opts[:exception_class] if opts.key?(:exception_class) sleep = interpret_sleep(opts[:sleep], attempts) reraise = opts[:reraise] end return if attempts <= 0 count = 0 if exception_class.nil? begin count += 1 if block.call(count, prev_exception) return true elsif count < attempts sleep_duration(sleep, count) end end until count == attempts false else begin count += 1 block.call(count, prev_exception) true rescue *exception_class if count < attempts prev_exception = $! sleep_duration(sleep, count) retry end case reraise when Proc reraise.($!) when Exception.class raise reraise, "reraised: #{$!.message}" when true raise $!, "reraised: #{$!.message}" else false end end end end private def sleep_duration(duration, count) case duration when Numeric sleep duration when Proc sleep duration.call(count) end end def compute_duration_base(sleep, attempts) x1, x2 = 1, sleep attempts <= sleep or raise ArgumentError, "need less or equal number of attempts than sleep duration #{sleep}" x1 >= x2 and raise ArgumentError, "invalid sleep argument: #{sleep.inspect}" function = -> x { (0...attempts).inject { |s, i| s + x ** i } - sleep } f, fmid = function[x1], function[x2] f * fmid >= 0 and raise ArgumentError, "invalid sleep argument: #{sleep.inspect}" n = 1 << 16 epsilon = 1E-16 root = if f < 0 dx = x2 - x1 x1 else dx = x1 - x2 x2 end n.times do fmid = function[xmid = root + (dx *= 0.5)] fmid < 0 and root = xmid dx.abs < epsilon or fmid == 0 and return root end raise ArgumentError, "too many iterations (#{n})" result end def interpret_sleep(sleep, attempts) case sleep when nil when Numeric if sleep < 0 if attempts > 2 sleep = -sleep duration_base = compute_duration_base sleep, attempts sleep = lambda { |i| duration_base ** i } else raise ArgumentError, "require > 2 attempts for negative sleep value" end end sleep when Proc sleep else raise TypeError, "require Proc or Numeric sleep argument" end end end end
true
dc1997247b81cd95fabb053fd7ca16279da64cd9
Ruby
metaquark/eden
/test/single_character_tokenization_test.rb
UTF-8
1,946
2.65625
3
[ "MIT" ]
permissive
$: << File.dirname(__FILE__) + "/../test" require 'test_helper' class SingleCharacterTokenizationTest < Test::Unit::TestCase def setup @sf = Eden::SourceFile.new( "dummy.rb" ) end def test_single_character_tokenisation @sf.stubs(:source).returns("<>~!@% ^&*()[]{}|.: ;=? +-") @sf.tokenize! tokens = @sf.lines[0].tokens assert_equal 26, tokens.size assert_token tokens[0], :lt, "<" assert_token tokens[1], :gt, ">" assert_token tokens[2], :tilde, "~" assert_token tokens[3], :logical_not, "!" assert_token tokens[4], :at, "@" assert_token tokens[5], :modulo, "%" assert_token tokens[7], :caret, "^" assert_token tokens[8], :bitwise_and, "&" assert_token tokens[9], :multiply, "*" assert_token tokens[10], :lparen, "(" assert_token tokens[11], :rparen, ")" assert_token tokens[12], :lsquare, "[" assert_token tokens[13], :rsquare, "]" assert_token tokens[14], :lcurly, "{" assert_token tokens[15], :rcurly, "}" assert_token tokens[16], :bitwise_or, "|" assert_token tokens[17], :period, "." assert_token tokens[18], :colon, ":" assert_token tokens[20], :semicolon, ";" assert_token tokens[21], :equals, "=" assert_token tokens[22], :question_mark, "?" assert_token tokens[24], :plus, "+" assert_token tokens[25], :minus, "-" end def test_period_tokenization @sf.stubs(:source).returns("... .. .") @sf.tokenize! tokens = @sf.lines[0].tokens assert_equal 5, tokens.size assert_token tokens[0], :range_inc, "..." assert_token tokens[2], :range_exc, ".." assert_token tokens[4], :period, "." end def test_colon_tokenization @sf.stubs(:source).returns(":test :: : ") @sf.tokenize! tokens = @sf.lines[0].tokens assert_equal 6, tokens.size assert_token tokens[0], :symbol, ":test" assert_token tokens[2], :scope_res, "::" assert_token tokens[4], :colon, ":" end end
true
88e784c9d0fbb60304a38aaeed0370280d96251f
Ruby
as6730/Data-Structures-and-Algorithms
/LRU_Cache/LRU_cache_review.rb
UTF-8
769
3.4375
3
[]
no_license
# Given a doubly linked list, like the one you built, reverse it. # You can assume that this method is monkey patching the LinkedList class # that you built, so any methods and instance variables in that class are available to you. # always think of pointers class LinkedList # ..... def reverse org_first = first pointer = @head until org_first == last new_first = last new_last = last.prev pointer.next = new_first new_first.prev = pointer new_last.next = @tail @tail.prev = new_last pointer = new_first end pointer.next = last last.prev = pointer end end # What pieces do we need to make the Cache? # max size, proc # What is the API of an LRU_Cache? # What are the steps for each API?
true
cf93c197a2eb999f3cf3228fdc82b0bd12ff5a63
Ruby
GeneFunctionTeam/pooled-transposon
/scripts/inv-hiseq.rb
UTF-8
1,885
2.8125
3
[]
no_license
#!/usr/bin/ruby require 'fastqgz.rb' # Script to process and map inverse PCR products # Regexps: http://rubular.com site = "GATC" transposon = /\A\w{20,30}TCTAGGG/ sims = "TGAATTC([ATGC]{8,30}?)(TACATC|#{site})" west = "TTCGACC([ATGC]{8,30}?)(CAGTCTG|#{site})" bwa = "/apps/bwa/0.7.5a/bwa" genome = "/scratch/readonly/ensembl/release-74/fasta/mus_musculus/dna/Mus_musculus.GRCm38.74.dna.toplevel.fa" #files = Dir.glob("*R1_001.fastq") files = ARGV # Find the current directory and add a slash to construct file names with. wd = Dir.pwd+"/" class PairFastq def initialize(r1,r2) @r1=r1 @r2=r2 end def next [@r1.next,@r2.next] end def has_next? @r1.has_next? && @r2.has_next? end def each while self.has_next? yield self.next end end end while a = files.shift f = PairFastq.new(Fastqgz.new(a),Fastqgz.new(a.sub("_R1_","_R2_"))) ofs = File.open(File.basename(a.sub(".fastq.gz",".sims.fastqinv")),'w') ofw = File.open(File.basename(a.sub(".fastq.gz",".west.fastqinv")),'w') f.each do |r1,r2| puts r1.seq.match(transposon) if(r1.seq.match(transposon)) clipped = r1.seq[$~.end(0)..-1] clipq = r1.qual[$~.end(0)..-1] if (r2.seq.match(sims)) # After this match, $1 = genome sequence, $2 = restriction site, $3 = barcode # Make a FASTQ file using i to identify the read: ofs.puts("@" + $1) ofs.puts clipped ofs.puts("+") ofs.puts clipq elsif (r2.seq.match(west)) # After this match, $1 = genome sequence, $2 = restriction site, $3 = barcode # Make a FASTQ file using i to identify the read: ofw.puts("@" + $1) ofw.puts clipped ofw.puts("+") ofw.puts clipq i+=1 else i+=1 end end end ofs.close ofw.close end
true
bd8bcd491c39fe7c10d1288084a6fb96d6607b03
Ruby
faketrees/alpaca
/w3/w3d1/solutions/Jannis Harder/wordmorph.rb
UTF-8
3,891
3.078125
3
[]
no_license
#!/usr/bin/env ruby class Array def concat!(other) self.push(*other) end end module WordMorph module Helper def variation_regexp(word) out_res=[] (0...word.size).each do |index| out_res << /#{Regexp.escape(word[0,index])}.#{Regexp.escape(word[index+1..-1])}/ end Regexp.union(*out_res) end end class Morpher include Helper def initialize(words,word_list) @words=words.map{|word|word.downcase.tr("^a-z","")} if @words.map{|e|e.size}.uniq.size != 1 raise "Word size has to be the same for all words" end @size=@words.first.size @word_list = WordList.new(word_list).resize!(@size) end def morph out = [] (0...@words.size).each do |index| out.concat! morph_two(*(@words[index,2])) end out end #private def morph_two(a,b=nil) unless b return [a] end warn "Morphing #{a} to #{b}." if $DEBUG a_paths = [[a]] b_paths = [[b]] word_list = @word_list.dup word_list.drop(a,b) current_paths = a_paths next_paths = b_paths loop do # connection found? b_lasts = b_paths.map{|e|e.last} a_paths.each do |a_item| re = /^#{variation_regexp(a_item.last)}$/ b_paths.each_index do |b_index| if b_lasts[b_index] =~ re warn "Done morphing #{a} to #{b}." if $DEBUG return a_item + b_paths[b_index].reverse[0..-2] end end end # connections left? if a_paths.empty? or b_paths.empty? raise "No connection" end # next step current_paths.map! do |path| last = path.last variations = word_list.drop_variations(last) word_list.to_s variations.map do |e| path.dup << e end end current_paths.replace( current_paths.inject([]) do |result,i| result.concat!(i) end ) #next time use the other paths current_paths,next_paths = next_paths,current_paths if $DEBUG if current_paths == b_paths warn "a:" warn a_paths.map{|e|e.join" -> "}.join("\n") else warn "b:" warn b_paths.map{|e|e.join" <- "}.join("\n") end end end end end class WordList include Helper def to_s @words.dup end def dup WordList.new(@words.dup,false) end def initialize(source,cleanup=true) case source when IO @words = source.read when Array @words = source.join("\n") else @words = source.to_s end cleanup! if cleanup end def drop(*words) words.flatten.each do |word| @words.sub!(/^#{Regexp.escape word}\n/,'') end words end def resize!(length) #@words.gsub!(/^(.{0,#{length-1}}|.{#{length+1},})\n/,'') @words = @words.scan(/^.{#{length}}\n/).join self end def drop_variations(word) out = [] @words.gsub!(/^(#{variation_regexp(word)})\n/) do out << $1 '' end out end def cleanup! @words.tr!("\r |;:,.\t_","\n") @words.gsub!(/\n{2,}/,"\n") if @words[-1] != ?\n @words << "\n" end end end end if __FILE__ == $0 dict = STDIN if ARGV.include?'-d' file = ARGV.slice!(ARGV.index('-d'),2)[1] dict = File.open(file) end if ARGV.delete '-v' $DEBUG=true end if ARGV.delete '-s' single_line=true end words = ARGV out = WordMorph::Morpher.new(words,dict).morph if single_line puts out.join(' ') else puts out end dict.close end
true
38bd37cced585d52656d6f2efa9f8a90515c2991
Ruby
devkmsg/daemon_runner
/examples/example_semaphore.rb
UTF-8
614
2.734375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require_relative '../lib/daemon_runner' require 'dev/consul' @service = 'myservice' @lock_count = 3 @lock_time = 10 ::Dev::Consul.run ::Dev::Consul.wait # Get a new semaphore @semaphore = DaemonRunner::Semaphore.lock(@service, @lock_count) # Spawn a thread to handle renewing the lock @renew_thread = @semaphore.renew # Do whatever kind of work you want @lock_time.downto(0).each do |i| puts "Releasing lock in #{i} seconds" sleep 1 end # Kill the thread when you're done @renew_thread.kill # Explicitly release the semaphore when you're done @semaphore.release ::Dev::Consul.stop
true
fa22227033c17c9de6b0246d73968ca91dc0a045
Ruby
jakobbuis/updateinsight
/src/Analysers/Composer.rb
UTF-8
835
2.578125
3
[]
no_license
module Analysers class Composer def initialize logger @logger = logger end def analyse # Check for composer file existence if !File.exists?('composer.json') @logger.info "Project has no composer.json file, no composer analysis performed" return false end # Run composer analysis @logger.info "Analysing composer dependencies" command = `composer outdated -oDm -f json` packages = JSON.parse(command) # Create a JIRA-ticket if minor updates are required update_needed = packages['installed'].count > 0 @logger.info(update_needed ? "Composer updates needed" : "Composer updates not needed") update_needed end end end
true
30bcc554ebce24ebaae9f4a0d1d5c9107cac9ce6
Ruby
devscola/RTanque
/lib/rtanque/gui/shell.rb
UTF-8
811
2.609375
3
[ "MIT" ]
permissive
require 'gosu' module RTanque module Gui class Shell attr_reader :shell DEBUG = ENV["DEBUG_SHELLS"] def initialize(window, shell) @window = window @shell = shell @x0 = shell.position.x @y0 = @window.height - shell.position.y @shell_image = Gosu::Image.new(Gui.resource_path("images/bullet.png")) end def draw position = [self.shell.position.x, @window.height - self.shell.position.y] @shell_image.draw_rot(position[0], position[1], ZOrder::SHELL, 0, 0.5, 0.5) if DEBUG then white = Gosu::Color::WHITE pos = shell.position x1, y1 = pos.x, @window.height - pos.y @window.draw_line @x0, @y0, white, x1, y1, white, ZOrder::SHELL end end end end end
true
e9c68e84e9c842f22470481f090ce762bbc5b9d9
Ruby
hiby90hou/search-practice
/lib/search_cli.rb
UTF-8
7,566
3.0625
3
[ "MIT" ]
permissive
require 'json' require 'terminal-table' require 'date' require 'pry' class SearchInterface def initialize(organization_file_address, user_file_address, ticket_file_address) @organization_file_address = organization_file_address @user_file_address = user_file_address @ticket_file_address = ticket_file_address @organizations = FormElement.new(organization_file_address) @organizations.get_hash_by_address @users = FormElement.new(user_file_address) @users.get_hash_by_address @tickets = FormElement.new(ticket_file_address) @tickets.get_hash_by_address @results @display_table = DisplayTable.new() end def search(keyword) if is_keyword_a_number(keyword) keyword = keyword.to_i end organization_search_results = @organizations.find_keyword(keyword) users_search_results = @users.find_keyword(keyword) # find organization name for user users_search_results.map! do |user| organization_name = @organizations.find_element_by_id(user['organization_id'])['name'] user['organization_name'] = organization_name user end tickets_search_results = @tickets.find_keyword(keyword) # find organization name, submitter name, assignee name for ticket tickets_search_results.map! do |ticket| organization_name = @organizations.find_element_by_id(ticket['organization_id'])['name'] submitter_name = @users.find_element_by_id(ticket['submitter_id'])['name'] assignee_name = @users.find_element_by_id(ticket['assignee_id'])['name'] ticket['organization_name'] = organization_name ticket['submitter_name'] = submitter_name ticket['assignee_name'] = assignee_name ticket end @results = { "organizationSearchResults": organization_search_results, "usersSearchResults": users_search_results, "ticketsSearchResults": tickets_search_results } end def show_result() puts 'search results:' if @results[:organizationSearchResults].length > 0 puts 'organizations:' @display_table.show_organization_table(@results[:organizationSearchResults]) end if @results[:usersSearchResults].length > 0 puts 'users:' @display_table.show_user_table(@results[:usersSearchResults]) end if @results[:ticketsSearchResults].length > 0 puts 'tickets:' @display_table.show_ticket_table(@results[:ticketsSearchResults]) end end def is_keyword_a_number(keyword) keyword =~/^\d+$/?true:false end end class FormElement def initialize(file_address) @file_address = file_address @data_hash @quick_search_id_element_hash = Hash.new end def get_hash_by_address if File.file?(@file_address) File.open(@file_address) do |f| @data_hash = JSON.parse(f.read) end return @data_hash else raise "cannot find file: #{@file_address}" end end def find_keyword(keyword) results = [] @data_hash.each do |element| if find_value_in_nested_hash(element, keyword) results.push(element) end # store info in hash for quick search in next time if element.key?(element['_id']) && element.key?(element['name']) && !@quick_search_id_element_hash.key?(element['_id']) @quick_search_id_element_hash[element['_id']] = element end end return results end def find_value_in_nested_hash(data, desired_value) if desired_value == "" return find_blank_in_nested_hash(data) else data.values.each do |value| case value when desired_value return true when Hash f = find_value_in_nested_hash(value, desired_value) return f if f when Array new_hash = Hash[value.map.with_index {|x,i| [i, x]}] f = find_value_in_nested_hash(new_hash, desired_value) return f if f end end end return nil end def find_blank_in_nested_hash(data) data.values.each do |value| # binding.pry if value === '' return true elsif value === Hash f = find_blank_in_nested_hash(value) return f if f elsif value === Array new_hash = Hash[value.map.with_index {|x,i| [i, x]}] f = find_blank_in_nested_hash(new_hash) return f if f end end return nil end def find_element_by_id(input_id) result = '' if @quick_search_id_element_hash.empty? @data_hash.each do |element| if element['_id'] == input_id result = element end end elsif !@quick_search_id_element_hash.empty? result = @quick_search_id_element_hash[input_id] end return result end end class DisplayTable def show_organization_table(organizations) table = Terminal::Table.new do |t| t << ['name','domain name','create at','details','shared tickets','tags'] organizations.each do |organization| domain_names = array_to_string(organization['domain_names']) tags = array_to_string(organization['tags']) create_date = string_to_date(organization['created_at']) is_shared_tickets = boolean_to_answer(organization['shared_tickets']) t.add_row [organization['name'],domain_names,create_date,organization['details'],is_shared_tickets,tags] end end puts table end def show_user_table(users) table = Terminal::Table.new do |t| t << ['name','alias','create date','active','verified','shared','locale','email','phone','signature','organization','tags','suspended','role'] users.each do |user| tags = array_to_string(user['tags']) create_date = string_to_date(user['created_at']) is_actived = boolean_to_answer(user['actived']) is_verified = boolean_to_answer(user['verified']) is_shared = boolean_to_answer(user['shared']) is_suspended = boolean_to_answer(user['suspended']) t.add_row [user['name'],user['alias'],create_date,is_actived,is_verified,is_shared,user['locale'],user['email'],user['phone'],user['signature'],user['organization_name'],tags,is_suspended,user['role']] end end puts table end def show_ticket_table(tickets) table = Terminal::Table.new do |t| t << ['subject','created_at','type','description','priority','status','submitter name','assignee name','organization name','tags','has_incidents','due_at','via'] tickets.each do |ticket| tags = array_to_string(ticket['tags']) create_date = string_to_date(ticket['created_at']) due_date = string_to_date(ticket['due_at']) is_has_incidents = boolean_to_answer(ticket['has_incidents']) t.add_row [ticket['subject'],create_date,ticket['type'],ticket['description'],ticket['priority'],ticket['status'],ticket['submitter_name'],ticket['assignee_name'],ticket['organization_name'],tags,is_has_incidents,due_date,ticket['via']] end end puts table end def array_to_string(input_arr) new_string = '' input_arr.each do |element| if new_string.length == 0 new_string = element else new_string = new_string + ', ' + element end end return new_string end def string_to_date(input_str) if input_str return Date.parse(input_str) else return 'Unknow' end end def boolean_to_answer(input_boolean) answer = '' if input_boolean == true answer = 'yes' else answer = 'no' end return answer end end
true
eb106b1e4a349bf46b3445ef59b3b21fcf642198
Ruby
aschak/99Cats
/app/models/cat.rb
UTF-8
406
2.59375
3
[]
no_license
class Cat < ActiveRecord::Base include CatHelper validates :birth_date, :name, presence: true validates :color, inclusion: { in: COLORS, message: "%{value} is not a valid color"}, presence: true validates :sex, inclusion: { in: %w(M F), message: "%{value} is not a valid sex"}, presence: true def age (DateTime.now - self.attributes["birth_date"]).to_f end end
true
11616c603f3dbbef3660774d715470e9f3d90dd5
Ruby
davispuh/Document-Registry
/app/helpers/documents_helper.rb
UTF-8
613
2.84375
3
[ "Unlicense" ]
permissive
module DocumentsHelper # Truncate a string so it doesn't exceed specified length and also append '...' # @param str [String] string to truncate # @param length [Fixnum] target length # @return [String] truncated string def truncate(str, length) return str if str.length <= length # Rails truncate method (String.truncate(length)) has a bug with Unicode handling, so we don't want to use it here part = str.each_grapheme_cluster.take(length + 1) return str if part.length <= length omission = '.' * [3, length].min part.take(length - omission.length).join + omission end end
true
2cd7502196ce291008011edaa3789c9220b0c0ca
Ruby
emiliocm9/Facebook-Bot
/bot.rb
UTF-8
1,382
2.71875
3
[]
no_license
require "selenium-webdriver" driver = Selenium::WebDriver.for :firefox url = 'https://www.facebook.com/' driver.get(url) email = 'yourname@email.com' password = 'yourpassword ' groups = ['https://www.facebook.com/groups/275366519230814', 'https://www.facebook.com/groups/rordevelopers', 'https://www.facebook.com/groups/javascript.morioh'] text = 'write the content of your posts here' def login(email, password, driver) email_element = driver.find_element(xpath: '//*[@id="email"]') password_element = driver.find_element(xpath: '//*[@id="pass"]') email_element.clear() email_element.send_keys(email) password_element.send_keys(password) password_element.submit sleep(5) end def openGroups(groups, driver, text) groups.each do | group | driver.get(group) sleep(3) field = driver.find_element(xpath: '//span[contains(text(),"What\'s on your mind")]') WriteAndPost(field, text, driver) end end def WriteAndPost(field, text, driver) begin field.click sleep(3) driver.action.send_keys(text).perform sleep(2) driver.find_element(xpath: '/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[2]/div[1]/div[1]').click rescue sleep(2) end end login(email, password, driver) openGroups(groups, driver, text)
true
302508d0f6aa8de07b0a4959470f487ba8ba3a5f
Ruby
KitaitiMakoto/optparse-range
/lib/optparse/range.rb
UTF-8
1,468
2.6875
3
[ "BSD-2-Clause", "Ruby" ]
permissive
require 'optparse' class OptionParser class << self def accept_range(accepter, converter=nil, &block) accept accepter do |range,| return range unless range points = range.split('-') raise AmbiguousArgument if points.length > 2 points << points.first if points.length == 1 converter = block if block Range.new *points.map(&converter) end end end decimal = '\d+(?:_\d+)*' DecimalIntegerRange = /#{decimal}(?:\-#{decimal})/io accept_range DecimalIntegerRange, :to_i float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?" FloatRange = /#{float}-#{float}/io accept_range FloatRange, :to_f class StringRange; end accept_range StringRange, :to_s class DateRange; end accept_range DateRange do |date| begin Date.parse date rescue NameError retry if require 'date' raise rescue ArgumentError raise InvalidArgument, date end end class DateTimeRange; end accept_range DateTimeRange do |dt| begin DateTime.parse dt rescue NameError retry if require 'date' raise rescue ArgumentError raise InvalidArgument, dt end end class TimeRange; end accept_range TimeRange do |time| begin Time.httpdate(time) rescue Time.parse(time) rescue NoMethodError retry if require 'time' raise rescue raise InvalidArgument, time end end end
true
2082945ff3db0eabce674e00fe1b408f428b249c
Ruby
thespecial/onliner
/features/pages/product_page.rb
UTF-8
1,659
2.609375
3
[]
no_license
# frozen_string_literal: true # Product view page object class ProductPage include PageObject h1(:title, Selectors::PRODUCT_PAGE[:title]) table(:specs, Selectors::PRODUCT_PAGE[:specs]) # There is suggestions section on product page - one top and others page_section( :suggestions, ProductSuggestions, Selectors::PRODUCT_PAGE[:suggestions][:self] ) # Get some of product details def details @specs = WatirNokogiri::Document.new(specs_element.html).table { screen: spec(Constants::PRODUCT_PAGE[:specs][:screen]), sensor: spec(Constants::PRODUCT_PAGE[:specs][:sensor]), megapixels: spec(Constants::PRODUCT_PAGE[:specs][:megapixels]) } end # Add top suggestion to cart def add_top_suggestion_to_cart add_to_cart(suggestions.top) end # Add other suggestions to cart (by index) def add_other_suggestion_to_cart(index) add_to_cart(suggestions.others[index], :other) title_element.hover # To unhover suggestion wait_until { !suggestion.hovered? && suggestion.added_to_cart? } end private # Returns spec by label and remove unnecessary &nbsp; def spec(label) nbsp = Nokogiri::HTML('&nbsp;').text @specs.row(label)[1].text.gsub(nbsp, ' ') end # Add suggestion to cart def add_to_cart(suggestion, type = nil) open_suggestion(suggestion) if type == :other suggestion.add_to_cart_element.when_visible.click wait_until { suggestion.added_to_cart_element.visible? } end # Hovers "other" suggestion to make 'Add to cart' button visible def open_suggestion(suggestion) suggestion.hover wait_until { suggestion.hovered? } end end
true
adf1166a29ee47275bc3feb44d9f107d2cca1de7
Ruby
papanosuke/sudoku
/sudoku3.rb
UTF-8
14,514
3.234375
3
[]
no_license
# -*- encoding: utf-8 -*- #************************************************************* #*数独問題作成 #************************************************************* require 'win32ole' #************************************************************* #*サブルーチン #************************************************************* #***************** #*フルパス取得 #***************** def getAbsolutePath filename fso = WIN32OLE.new('Scripting.FileSystemObject') return fso.GetAbsolutePathName(filename) end #***************** #*Fileオープン #***************** def openExcelWorkbook filename filename = getAbsolutePath(filename) xl = WIN32OLE.new('Excel.Application') xl.Visible = false xl.DisplayAlerts = false book = xl.Workbooks.Open(filename) begin yield book ensure xl.Workbooks.Close xl.Quit end end #***************** #*file作成 #***************** def createExcelWorkbook xl = WIN32OLE.new('Excel.Application') xl.Visible = false xl.DisplayAlerts = false book = xl.Workbooks.Add() begin yield book ensure xl.Workbooks.Close xl.Quit end end #************************************************************* #*メインルーチン #************************************************************* =begin 問題作成の考え方 ①ランダムで1~9の数字をchoiceareaから選択する ②縦、横、四角、続行チェックの4通りのチェックを実施する ③エラーがなかったらchoiceareaから削除 ④①~③の繰り返し =end ERR_OK = 0 ERR_NG = 1 HANTEI1 = 5 HANTEI2 = 8 #************************************************************* #*クラス #************************************************************* class Array #配列からランダムで選択するインスタンスを作成 def choice at( rand( size ) ) end end class Sudoku attr_accessor :sdkarea attr_accessor :sdkarea2 attr_accessor :sdkarea3 attr_accessor :choicearea attr_accessor :levelnum attr_accessor :st_x attr_accessor :ed_x attr_accessor :st_y attr_accessor :ed_y attr_accessor :saikeisan_flg #******************** #*三次配列 #******************** def thirdarray(i,j,k) (0...i).map { (0...j).map { Array.new(k) } } end # #******************** #*二次配列 #******************** def secondarray(i,j) (0...i).map { Array.new(j) } end # #******************** #*一次配列 #******************** def firstarray(i) Array.new(i) end # #******************** #*初期化 #******************** def initialize() @sdkarea = self.secondarray(9,9) for i in 0..8 do for j in 0..8 do @sdkarea[i][j] = 0 end end @choicearea = self.secondarray(9,9) for i in 0..8 do for j in 0..8 do @choicearea[i][j] = j + 1 end ####p @choicearea[i] end ####p @choicearea[i] @st_x = 0 @st_y = 0 @ed_x = 0 @ed_y = 0 @levelnum = 0 @saikeisan_flg = 0 end #******************** #*sdkarea再初期化 #******************** def sdkareaclear(sarea,gyo) for j in 0..8 do sarea[gyo][j] = 0 end #確認 print "*-------- sdkareaクリア後 --------*\n" for j in 0..8 print @sdkarea[j],"\n" end end # #******************** #*choicearea再初期化 #******************** def choiceareaclear(carea,gyo) for j in 0..8 do carea[gyo][j] = j + 1 end #確認 print "*-------- choiceareaクリア後 --------*\n" for j in 0..8 print @choicearea[j],"\n" end end # #******************** #エラーチェック #①重複チェック #******************** def errchk(sdkarea, st_x, st_y, ed_x ,ed_y) chkarea = [] for i in 0..8 do chkarea[i] = 0 end for i in st_x..ed_x do for j in st_y..ed_y do #選択された数字の重複をチェック if sdkarea[i][j] != 0 chkarea[sdkarea[i][j] - 1] += 1 end # print " s=",sdkarea[i],chkarea,"\n" # #エラーあり=ERR_NGを返す return ERR_NG if chkarea[sdkarea[i][j] - 1] > 1 end end #エラーなし=ERR_OKを返す return ERR_OK end #******************** #エラーチェック #②続行チェック #******************** #(1,0)(2,0)(3,0)の数字が(5,0)(5,1)(5,2)の残りの数字だと処理がループになる def errchk2(sdkarea, st_x, st_y) carea = [1,2,3,4,5,6,7,8,9] for i in st_x-2..(st_x-1) for j in st_y..(st_y+2) # print "a=",sdkarea[i][j]," i=",i," j=",j,"\n" carea.delete_if{|x| x == sdkarea[i][j]} # p carea end end if st_x == 5 for j in st_y..(st_y+2) chk = [] for i in (st_x - HANTEI1)..(st_x - HANTEI1 + 2) chk << sdkarea[i][j] end chk.sort! ########print "carea=",carea," chk=",chk,"\n" if carea == chk return ERR_NG end end end return ERR_OK end # end =begin #************************************************************* #*メインルーチン #************************************************************* =end print "*----- 問題作成開始 -----*\n" print "開始時刻=",Time.now,"\n" kekka = Sudoku::new #******************** #レベル設定 #******************** while true print "*----------------------------------------------------------------------------*\n" print " レベルは?[1-4]\n" print "*----------------------------------------------------------------------------*\n" print "==> " kekka.levelnum = gets.to_i if kekka.levelnum >= 1 and kekka.levelnum <= 4 break end end # #******************** #数字埋め作業 #******************** i = 0 try = 1 # while true # j = 0 while true # #数字をランダムで生成(choiceareaから選択) chkflg = ERR_OK # #縦で使用されているものは削除しておく if i > 0 for h in 0..i-1 do kekka.choicearea[j].delete_if {|x| x == kekka.sdkarea[h][j]} end end # if kekka.choicearea[j].length == 0 print "choicearea要素数=0"," gyo=",j,"\n" break end # kekka.sdkarea[i][j] = kekka.choicearea[j].choice # j += 1 # if j > 8 break end # end # # #===>DEBUG START # if kekka.saikeisan_flg == 1 # print "i=",i," j=",j," suji=",kekka.sdkarea[i],"\n" # end #<===DEBUG END =begin (0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (0,6) (0,7) (0,8) (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (1,8) (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (2,6) (2,7) (2,8) (3,0) (3,1) (3,2) (3,3) (3,4) (3,5) (3,6) (3,7) (3,8) (4,0) (4,1) (4,2) (4,3) (4,4) (4,5) (4,6) (4,7) (4,8) (5,0) (5,1) (5,2) (5,3) (5,4) (5,5) (5,6) (5,7) (5,8) (6,0) (6,1) (6,2) (6,3) (6,4) (6,5) (6,6) (6,7) (6,8) (7,0) (7,1) (7,2) (7,3) (7,4) (7,5) (7,6) (7,7) (7,8) (8,0) (8,1) (8,2) (8,3) (8,4) (8,5) (8,6) (8,7) (8,8) =end #******************** #横チェック #******************** a = kekka.errchk(kekka.sdkarea,i,0,i,8) # #******************** #縦チェック #******************** b = [] for k in 0..8 b[k] = kekka.errchk(kekka.sdkarea,0,k,8,k) end # #******************** #四角チェック #******************** c = [] if i <= 2 c[0] = kekka.errchk(kekka.sdkarea,0,0,2,2) c[1] = kekka.errchk(kekka.sdkarea,0,3,2,5) c[2] = kekka.errchk(kekka.sdkarea,0,6,2,8) elsif i <= 5 c[0] = kekka.errchk(kekka.sdkarea,3,0,5,2) c[1] = kekka.errchk(kekka.sdkarea,3,3,5,5) c[2] = kekka.errchk(kekka.sdkarea,3,6,5,8) else c[0] = kekka.errchk(kekka.sdkarea,6,0,8,2) c[1] = kekka.errchk(kekka.sdkarea,6,3,8,5) c[2] = kekka.errchk(kekka.sdkarea,6,6,8,8) end # #******************** #続行チェック #******************** #(1,0)(2,0)(3,0)の数字が(5,0)(5,1)(5,2)の残りの数字だと処理がループになる d = [] if i == 5 d[0] = kekka.errchk2(kekka.sdkarea,5,0) d[1] = kekka.errchk2(kekka.sdkarea,5,3) d[2] = kekka.errchk2(kekka.sdkarea,5,6) end # # print "a=",a," b=",b," c=",c,"\n" # print " kekka=",kekka.sdkarea,"\n" # # #******************** #すべてのエラー確認 #******************** # chkflg = ERR_OK if a != ERR_OK chkflg = ERR_NG end for m in 0..8 if b[m] != ERR_OK chkflg = ERR_NG end end for m in 0..2 if c[m] != ERR_OK chkflg = ERR_NG end end err_z = ERR_OK if i == 5 for m in 0..2 if d[m] != ERR_OK err_z = ERR_NG end end end if err_z == ERR_NG kekka.choiceareaclear(kekka.choicearea,i) kekka.choiceareaclear(kekka.choicearea,i-1) kekka.choiceareaclear(kekka.choicearea,i-2) kekka.choiceareaclear(kekka.choicearea,i-3) kekka.choiceareaclear(kekka.choicearea,i-4) kekka.choiceareaclear(kekka.choicearea,i-5) kekka.sdkareaclear(kekka.sdkarea,i) kekka.sdkareaclear(kekka.sdkarea,i-1) kekka.sdkareaclear(kekka.sdkarea,i-2) kekka.sdkareaclear(kekka.sdkarea,i-3) kekka.sdkareaclear(kekka.sdkarea,i-4) kekka.sdkareaclear(kekka.sdkarea,i-5) print "iをマイナスします!",i,"⇒",i-5,"\n" i -= 5 kekka.saikeisan_flg = 1 end # # #******************** #choiceareaから削除 #******************** if chkflg == ERR_OK #===>debug start print "ERR_OK...",i,"\n" #<===debug end for h in 0..8 do #===>debug start #####p kekka.sdkarea[i][h] #<===debug end kekka.choicearea[h].delete_if {|x| x == kekka.sdkarea[i][h]} #===>debug start #####p kekka.choicearea[h] #<===debug end end #===>debug start # print kekka.sdkarea[i],"\n" #<===debug end i += 1 try = 0 else try += 1 for h in 0..8 do kekka.sdkarea[i][h] = 0 end end try_disp = try.to_s.reverse if try_disp[0..4] == "00000" print "try回数=",try,"\n" # for h in 0..8 # print kekka.sdkarea[h],"\n" # end end ##if try > 100000 ## print "問題の作成に失敗しました。","\n" ## exit! ##end if i > 8 break end end # #******************** #確認表示 #******************** print "*-------- 確認表示① --------*\n" for h in 0..8 print kekka.sdkarea[h],"\n" end # #******************** #ランダム空白作成 #******************** kuhaku_max = 0 case kekka.levelnum when 1 kuhaku_max = 35 when 2 kuhaku_max = 40 when 3 kuhaku_max = 45 when 4 kuhaku_max = 50 end ##kuhaku = 0 ##while true # 3.step(9,3) { |i| # 3.step(9,3) { |j| # rnd_i = rand(i) # rnd_j = rand(j) # kuhaku_num = kekka.sdkarea[rnd_i][rnd_j] # if kuhaku_num != 0 # kekka.sdkarea[rnd_i][rnd_j] = 0 # kuhaku += 1 # end # } # } # break if kuhaku >= kuhaku_max # end kuhaku = 0 while i = rand(9) j = rand(9) if kekka.sdkarea[i][j] != 0 kekka.sdkarea[i][j] = 0 kuhaku += 1 end break if kuhaku == kuhaku_max end # #******************** #回答保存 #******************** #deep copy kekka.sdkarea2 = Marshal.load(Marshal.dump(kekka.sdkarea)) #******************** #確認表示 #******************** print "*-------- 確認表示② --------*\n" for h in 0..8 print kekka.sdkarea2[h],"\n" end # #******************** #回答確認 #******************** #①昇順バックトラック kuhaku = kuhaku_max mae_kuhaku = -1 while kuhaku != 0 i = 0 while true # j = 0 # while true # if kekka.sdkarea2[i][j] == 0 # kaito = 0 kaito_bk = 0 # #順番に1から9まで当てはめていく for m in 1..9 # kekka.sdkarea2[i][j] = m a = kekka.errchk(kekka.sdkarea2,i,0,i,8) b = kekka.errchk(kekka.sdkarea2,0,j,8,j) # if i <= 2 if i <= 2 c = kekka.errchk(kekka.sdkarea2,0,0,2,2) elsif i <= 5 c = kekka.errchk(kekka.sdkarea2,0,3,2,5) else c = kekka.errchk(kekka.sdkarea2,0,6,2,8) end elsif i <= 5 if i <= 2 c = kekka.errchk(kekka.sdkarea2,3,0,5,2) elsif i <= 5 c = kekka.errchk(kekka.sdkarea2,3,3,5,5) else c = kekka.errchk(kekka.sdkarea2,3,6,5,8) end else if i <= 2 c = kekka.errchk(kekka.sdkarea2,6,0,8,2) elsif i <= 5 c = kekka.errchk(kekka.sdkarea2,6,3,8,5) else c = kekka.errchk(kekka.sdkarea2,6,6,8,8) end end # if a == ERR_OK and b == ERR_OK and c == ERR_OK kaito += 1 kaito_bk = m end # end # #複数回答があるものはゼロに戻す。1つのものは解答と断定 if kaito > 1 kekka.sdkarea2[i][j] = 0 elsif kaito == 0 kekka.sdkarea2[i][j] = 0 else kuhaku -= 1 kekka.sdkarea2[i][j] = kaito_bk end # end # j += 1 if j > 8 break end # end # i += 1 # if i > 8 break end # end # if kuhaku == mae_kuhaku print "空白=",kuhaku,"\n" print "空白が減らないため処理を中断します!\n" exit! end print "空白=",kuhaku,"\n" mae_kuhaku = kuhaku # # end #******************** #ゼロの個数を確認 #******************** ##kuhaku = 0 ##for i in 0..8 ## for j in 0..8 ## if kekka.sdkarea2[i][j] == 0 ## kuhaku +=1 ## end ## end ##end ##print "ゼロの個数=",kuhaku,"個","\n" ## #******************** #確認表示 #******************** print "*-------- 確認表示④ --------*\n" for h in 0..8 print kekka.sdkarea[h],"\n" end print "*-------- 確認表示⑤ --------*\n" for h in 0..8 print kekka.sdkarea2[h],"\n" end # #******************** #エクセル書き出し #******************** openExcelWorkbook('main.xlsx') do |book| i = 1 mondai = book.Worksheets.Item('sudoku_m') kaito = book.Worksheets.Item('sudoku_k') #オブジェクトのメソッド表示 ##p sheet.ole_methods for i in 0..8 for j in 0..8 if kekka.sdkarea[i][j] == 0 mondai.Cells(i+2,j+1).Value = "" mondai.Cells(i+2,j+1).Font.ColorIndex = 3 else mondai.Cells(i+2,j+1).Value = kekka.sdkarea[i][j] mondai.Cells(i+2,j+1).Font.ColorIndex = 1 end end end for i in 0..8 for j in 0..8 kaito.Cells(i+2,j+1).Value = kekka.sdkarea2[i][j] kaito.Cells(i+2,j+1).Font.ColorIndex = 1 end end book.save end #******************** #終了表示 #******************** print "終了時刻=",Time.now,"\n"
true
b5676dbe425c286549fe047425e435bcc64fc700
Ruby
amitzman/phase-0
/week-4/errors.rb
UTF-8
7,303
4.3125
4
[ "MIT" ]
permissive
# Analyze the Errors # I worked on this challenge by myself. # I spent 1.5 hours on this challenge. # --- error ------------------------------------------------------- cartmans_phrase = "Screw you guys " + "I'm going home." # This error was analyzed in the README file. # --- error ------------------------------------------------------- def cartman_hates(thing) while true puts "What's there to hate about #{thing}?" end end # This is a tricky error. The line number may throw you off. # 1. What is the name of the file with the error? # errors.rb # 2. What is the line number where the error occurs? # line 170 # 3. What is the type of error message? # Syntax error # 4. What additional information does the interpreter provide about this type of error? # Did not expect the end of input, but rather expecting keyword_end # 5. Where is the error in the code? # Very end of the file. # 6. Why did the interpreter give you this error? # We did not put an end for the method cartman_hates. Added end on line 17 to fix # --- error ------------------------------------------------------- # south_park # 1. What is the line number where the error occurs? # Line 36 # 2. What is the type of error message? # in `<main>' # 3. What additional information does the interpreter provide about this type of error? # undefined local variable or method 'south_park' # 4. Where is the error in the code? # There error is the whole name in itself. It's not being assigned to a value to become a variable or not being defined as a method. # 5. Why did the interpreter give you this error? # We're calling on a variable or method that isn't defined. # --- error ------------------------------------------------------- # cartman() # 1. What is the line number where the error occurs? # Line 51 # 2. What is the type of error message? # undefined method 'cartman' # 3. What additional information does the interpreter provide about this type of error? # It's a NoMethodError for the object # 4. Where is the error in the code? # The error is the name itself. It has not yet been defined as a method # 5. Why did the interpreter give you this error? # The cartman method has not been defined when it's been called # --- error ------------------------------------------------------- # def cartmans_phrase # puts "I'm not fat; I'm big-boned!" # end # cartmans_phrase('I hate Kyle') # 1. What is the line number where the error occurs? # Line 66 # 2. What is the type of error message? # wrong number of arguements (1 for 0) # 3. What additional information does the interpreter provide about this type of error? # (Argument Error) coming from line 70 # 4. Where is the error in the code? # After cartmans_phrase on line 66 # 5. Why did the interpreter give you this error? # When cartmans_phrase was defined, there was no arguement given. Neeed to add ( ) to it on line 66. # --- error ------------------------------------------------------- # def cartman_says(offensive_message) # puts offensive_message # end # cartman_says # 1. What is the line number where the error occurs? # line 85 # 2. What is the type of error message? # wrong number of arguments (0 for 1) # 3. What additional information does the interpreter provide about this type of error? # ArgumentError, comes from when it's called upon on line 89 # 4. Where is the error in the code? # The arguement from cartman_says on line 85 # 5. Why did the interpreter give you this error? # The method is supposed to have an arguement passed through, but when called on line 89, there was no arguement given. # --- error ------------------------------------------------------- # def cartmans_lie(lie, name) # puts "#{lie}, #{name}!" # end # cartmans_lie('A meteor the size of the earth is about to hit Wyoming!') # 1. What is the line number where the error occurs? # Line 106 # 2. What is the type of error message? # wrong number of arguements (1 for 2) # 3. What additional information does the interpreter provide about this type of error? # ArguementError, happens when called upon on line 110 # 4. Where is the error in the code? # In the argument for cartmans_lie # 5. Why did the interpreter give you this error? # There are supposed to be two arguments passed through for this method, but when called upon, only one out of two arugements were passed through. # --- error ------------------------------------------------------- # 5 * "Respect my authoritay!" # 1. What is the line number where the error occurs? # line 125 # 2. What is the type of error message? # String can't be coerced into Fixnum (TypeError) # 3. What additional information does the interpreter provide about this type of error? # (Type Error) # 4. Where is the error in the code? # The whole line is an error # 5. Why did the interpreter give you this error? # We can't multiply an integer by a string. It would have to be the other way around. Then we would be able to print the string five times. # --- error ------------------------------------------------------- # amount_of_kfc_left = 20/0 # 1. What is the line number where the error occurs? # Line 140 # 2. What is the type of error message? # divided by 0 # 3. What additional information does the interpreter provide about this type of error? # (ZeroDivisionError) # 4. Where is the error in the code? # What the variable is assigned to. The formula itself # 5. Why did the interpreter give you this error? # Nothing can be divided by zero, the answer is infinity. # --- error ------------------------------------------------------- # require_relative "cartmans_essay.md" # 1. What is the line number where the error occurs? # Line 156 # 2. What is the type of error message? # cannot load such file # 3. What additional information does the interpreter provide about this type of error? # Path of where the file should be # 4. Where is the error in the code? # The file being called up on # 5. Why did the interpreter give you this error? # The file that is being called upon does not exist. # --- REFLECTION ------------------------------------------------------- # Write your reflection below as a comment. #Which error was the most difficult to read? #I thought the integer trying to be multiplied by a string was most difficult to read. The language wasn't as clear as the other error messages. 'String can't be coerced into Fixnum' #How did you figure out what the issue with the error was? #I knew right away looking at the code itself what the error was. I knew that an integer can't be multiplied by a string and that the solution would be to swap the integer with the string. So the string can multiplied so the output is to print the string 5 times. #Were you able to determine why each error message happened based on the code? #Yep, I was able to see the error message occured based on the code because of practice with ruby in the previous challenges and prep work for the interview. #When you encounter errors in your future code, what process will you follow to help you debug? #Go to the line number that the error occurs. Come up with some theories as to why the error occured. Then test one theory at a time until it is fixed.
true
91bc9a6a67f3d977195966637a967aea4afa6552
Ruby
Sid-ah/hk-bc
/roman-numerals-challenge/spec/roman_numerals_spec.rb
UTF-8
490
2.75
3
[]
no_license
require_relative '../roman_numerals' describe 'converting an Arabic number to a Roman numeral' do describe 'old Roman numerals' do it 'converts 1 to I' do expect(convert_to_roman(1)).to eq "I" end it 'converts 4 to IIII' do expect(convert_to_roman(4)).to eq "IIII" end # Release 1 ... # add tests for old roman numerals here end describe 'modern Roman numerals' do # Release 3 ... # add tests for modern roman numerals here end end
true
b1f98af7cc62b063e2b9f1b9741befdedb9f427d
Ruby
delta4d/youdao-dict-cli
/bin/ydict
UTF-8
792
3.28125
3
[]
no_license
#!/usr/bin/env ruby require 'dict' # Linux terminal color codes RESET = "\e[0m" BLACK = "\e[30m" RED = "\e[31m" GREEN = "\e[32m" YELLOW = "\e[33m" BLUE = "\e[34m" MAGENTA = "\e[35m" CYAN = "\e[36m" # Prompt PROMPT = ">> " # Exit codes defination EXIT = "bye" def usage puts <<-END.gsub(/^\s*\|/, '') |Usage: |#{File.basename($0).to_s} [arg] | no arguments: starting translating! enter bye to exit the program | any arguments: display this help END end if ARGV.length > 0 usage else while true print PROMPT word = gets.chomp.force_encoding('ASCII-8BIT') if EXIT == word puts "#{CYAN}bye ^_^#{RESET}" exit 0 else translate(word) { |t| puts "#{RED}#{t[0]} #{GREEN}#{t[1..-1].join}#{RESET}" } end end end
true
ef3436eb99391c6b83d93bfe54e10f6a9ca977d7
Ruby
CEsGutierrez/hotel
/lib/booker.rb
UTF-8
3,807
3.28125
3
[]
no_license
require 'date' require_relative 'room' require_relative 'reservation' require_relative 'date_mediator' require_relative 'block' require_relative 'reporter' class Booker attr_reader :HOTEL_CAPACITY attr_accessor :rooms, :reservations, :reserved_blocks HOTEL_CAPACITY = 20 def initialize @rooms = populate_hotel @reservations = [] @reserved_blocks = [] end def populate_hotel rooms_array = [] i = 1 while i <= HOTEL_CAPACITY do rooms_array << Room.new(id: i) i = i + 1 end return rooms_array end def new_reservation(start_date: Date.today, end_date: Date.today + 1) digested_start_date = date_digester(start_date) digested_end_date = date_digester(end_date) date_validator(digested_start_date, digested_end_date) reservation_id = reservations.length + 1 selected_room = room_picker(range_start: digested_start_date, range_end: digested_end_date) unless (1..HOTEL_CAPACITY).include? selected_room raise ArgumentError.new "no room assigned for this reservation" end reservations << Reservation.new(start_date: digested_start_date, end_date: digested_end_date, room_id: selected_room, reservation_id: reservation_id) end def new_block(start_date: Date.today, end_date: Date.today + 1 , number_of_rooms: 2, block_label: 1, block_discount: 15) digested_start_date = date_digester(start_date) digested_end_date = date_digester(end_date) date_validator(digested_start_date, digested_end_date) if number_of_rooms < 2 || number_of_rooms > 5 raise ArgumentError.new "invalid number of rooms requested for block" end if lists_available_rooms_for_range(range_start: digested_start_date, range_end: digested_end_date).length < number_of_rooms raise ArgumentError.new "block exceeds hotel capacity" end block_label = block_labeler number_of_rooms.times do selected_room = room_picker(range_start: digested_start_date, range_end: digested_end_date) unless (1..HOTEL_CAPACITY).include? selected_room raise ArgumentError.new "no room assigned for this reservation" end reservations << Reservation.new(start_date: digested_start_date, end_date: digested_end_date, room_id: selected_room, reservation_id: nil, block_label: block_label, block_discount: block_discount) end reserved_blocks << Block.new(start_date: start_date, end_date: end_date, discount: block_discount, block_label: block_label, number_of_rooms: number_of_rooms) end def new_reservation_from_block(block_label) reservations.each_with_index do |reservation, index| if reservation.block_label == block_label reservation.reservation_id = reservations[index] break end end reserved_blocks.each do |block| if block_label == block.block_label block.number_of_rooms -= 1 end end end def block_labeler block_labels = [] @reserved_blocks.each do |block| block_labels << block.block_label end if !(block_labels.empty?) block_labels.uniq! return_statement = block_labels.max + 1 return return_statement else return 1 end end def date_digester(date) if date.class != Date digested_date = Date.parse("#{date}") else digested_date = date end return digested_date end def date_validator(first_date, second_date) # works with instances of date if first_date > second_date raise ArgumentError.new "Invalid date range" end end def room_picker(range_start: , range_end: ) range_start = range_start range_end = range_end available_rooms = Reporter.lists_available_rooms_for_range(range_start: range_start, range_end: range_end) if available_rooms.length > 0 return available_rooms[0] else return nil end end def self.hotel_capacity return HOTEL_CAPACITY end end
true
d2f8c3095d0ec98294f3ef07c8d3d4e42fb17b66
Ruby
seaweeddol/Ada-Jumpstart-Curriculum
/password_verification.rb
UTF-8
1,360
3.75
4
[]
no_license
password_valid = false password_error = [] # loop until password is valid until password_valid print "Enter a new password: " password = gets.chomp # check if password is valid if password.length >= 8 && password =~ /\d/ && password =~ /@|%|\*|!/ && password =~ /[a-z]/ && password =~ /[A-Z]/ print "Enter again to confirm: " password_verify = gets.chomp # make user enter exact match again to confirm until password_verify == password print "Your password did not match. Please enter it again: " password_verify = gets.chomp end puts "Your password has been accepted." password_valid = true else #check if password is long enough if password.length < 8 password_error.push("be at least 8 characters long") end # check if password contains number, special character, lowercase letter, and uppercase letter password_check = { /\d/ => 'contain a number', /@|%|\*|!/ => 'contain a special character (@, %, *, or !)', /[a-z]/ => 'contain a lowercase letter', /[A-Z]/ => 'contain an uppercase letter' } # if password does not contain an item, push string to password_error array password_check.each { |check, string| password_error.push(string) if password !~ check } puts "Password must #{password_error * ", "}" password_error = [] end end
true
1f72511276c251356fdcd43101b2133e3103fe20
Ruby
notmarkmiranda/robot_world
/test/models/robot_test.rb
UTF-8
953
2.96875
3
[]
no_license
require_relative '../test_helper' class RobotTest < Minitest::Test def test_assigns_attributes_correctly robot = Robot.new({ :name => "John", :city => "Denver", :state => "CO", :avatar => "http://www.robohash.org/John", :birthdate => Date.strptime("12/06/1981", "%m/%d/%Y"), :date_hired => Date.strptime("02/01/2016", "%m/%d/%Y"), :department => "HR" }) assert_equal "John", robot.name assert_equal "Denver", robot.city assert_equal "CO", robot.state assert_equal "http://www.robohash.org/John", robot.avatar assert_equal "12/06/1981", robot.birthdate.strftime("%m/%d/%Y") assert_equal "02/01/2016", robot.date_hired.strftime("%m/%d/%Y") assert_equal "HR", robot.department assert_equal Fixnum, robot.age.class end end
true
1674fec77d1cef26dddba23dacc32eecdeabdaf0
Ruby
wenbo/rubyg
/sample/CHAPTER06/120/nitems.19.rb
UTF-8
188
3.125
3
[]
no_license
RUBY_VERSION # => "1.9.1" ary = [1,2,false,nil,3] ary.length # => 5 ary.nitems # => # ~> -:4:in `<main>': undefined method `nitems' for [1, 2, false, nil, 3]:Array (NoMethodError)
true
cdc4c73f764ee93d097b81715f05614d5f1d0941
Ruby
richa-prof/sharetribe
/spec/models/numeric_field_value_spec.rb
UTF-8
3,616
2.515625
3
[]
no_license
# == Schema Information # # Table name: custom_field_values # # id :integer not null, primary key # custom_field_id :integer # listing_id :integer # text_value :text(65535) # numeric_value :float(24) # date_value :datetime # created_at :datetime # updated_at :datetime # type :string(255) # delta :boolean default(TRUE), not null # person_id :string(255) # # Indexes # # index_custom_field_values_on_listing_id (listing_id) # index_custom_field_values_on_person_id (person_id) # index_custom_field_values_on_type (type) # require 'spec_helper' describe NumericFieldValue, type: :model do let(:field) { FactoryGirl.create :custom_numeric_field, min: 0, max: 50, required: false } let(:required_field) { FactoryGirl.create :custom_numeric_field, min: 0, max: 50, required: true } describe "validations" do it "should treat numeric value as optional if field is not required" do value = NumericFieldValue.new(question: field) expect(value).to be_valid end it "should have numeric value" do value = NumericFieldValue.new(question: required_field) expect(value).not_to be_valid value.numeric_value = 0 expect(value).to be_valid value.numeric_value = "jee" expect(value).not_to be_valid end end describe "search", :'no-transaction' => true do let!(:short_board) { FactoryGirl.create :listing, title: "Short board" } let!(:medium_board) { FactoryGirl.create :listing, title: "Medium board" } let!(:long_board) { FactoryGirl.create :listing, title: "Long board" } let!(:board_length) { FactoryGirl.create :custom_numeric_field, min: 0, max: 200 } let!(:length_value1) { FactoryGirl.create :custom_numeric_field_value, listing: short_board, question: board_length, numeric_value: 100 } let!(:length_value2) { FactoryGirl.create :custom_numeric_field_value, listing: medium_board, question: board_length, numeric_value: 160 } let!(:length_value3) { FactoryGirl.create :custom_numeric_field_value, listing: long_board, question: board_length, numeric_value: 200 } let!(:board_width) { FactoryGirl.create :custom_numeric_field, min: 0, max: 50 } let!(:width_value1) { FactoryGirl.create :custom_numeric_field_value, listing: short_board, question: board_width, numeric_value: 30 } let!(:width_value3) { FactoryGirl.create :custom_numeric_field_value, listing: long_board, question: board_width, numeric_value: 40 } before(:each) do ensure_sphinx_is_running_and_indexed end def test_search(length, width, expected_count) with_many = [] with_many << if length then { custom_field_id: board_length.id, numeric_value: length } end with_many << if width then { custom_field_id: board_width.id, numeric_value: width } end expect(NumericFieldValue.search_many(with_many.compact).count).to eq(expected_count) end it "searches by numeric field and value pairs" do test_search((0..50), (0..20), 0) # Neither matches test_search((0..150), (0..20), 0) # Length matches 1, width matches 0 test_search((0..150), (0..35), 1) # Length matches 1, width matches 1 test_search((0..180), nil, 2) # Length matches 2 test_search((0..220), nil, 3) # Length matches 3 test_search((0..220), (20..35), 1) # Length matches 3, width matches 1 test_search((0..220), (20..50), 2) # Length matches 3, width matches 2 end end end
true
49fd9350227dc355303697fc494bc989a3da31f7
Ruby
romaindeveaud/index-app
/indexing/Listener.rb
UTF-8
3,648
2.640625
3
[]
no_license
require 'rexml/document' require 'rexml/streamlistener' include REXML class Listener include StreamListener def initialize(dico, post_file, stoplist, listing) @current_file = nil @name = nil @isName = nil @dico_indice = 0 @offset = Array.new @stoplist = Array.new @array = Array.new @post_array = Array.new @d_array = Hash.new @hf_pointing = Hash.new("") @listing = Hash.new @dico = File.new(dico, File::CREAT|File::TRUNC|File::RDWR, 0644) @posting_file = File.new(post_file, File::CREAT|File::TRUNC|File::RDWR, 0644) @listing_file = File.new(listing, File::CREAT|File::TRUNC|File::RDWR, 0644) stopfile = File.new(stoplist, File::RDONLY) @stoplist = stopfile.readlines.each { |word| word.chomp! } end def set_current_file (file) @current_file = file.chomp".xml" @array.clear end def tag_start(name, attributes) case name when "name" @isName = 1 when "collectionlink" @hf_pointing[attributes["xlink:href"].chomp!(".xml")] += @current_file+" " end end def text (text) if !@isName.nil? @name = String.new(text) @isName = nil end text.gsub!(/(\s|\W)+/u,' ') sentence = text.split sentence.compact! if !sentence.nil? sentence.each do |word| clean(word) insert(word) end end end def clean (word) word.strip! word.downcase! end def insert (word) if !@stoplist.include?(word) && word != "" @array << word end end def inverse_doc_freq (df) return (Math.log(1000/df.to_i) + 1) end def weight (tf, df) return tf*inverse_doc_freq(df) end def index_now # @post_array.collect! do |post| # buff = post.split # df = buff.length # post = "" # buff.each do |b| # buff2 = b.split(":") # b = "#{b}#{weight(buff2[0].to_i,df).to_s} " # post = "#{post} #{b}" # end # post.lstrip! # post # end @d_array = @d_array.sort @d_array.each { |word| @dico.puts "#{word[0]} #{word[1]}" } @post_array.each { |post| @posting_file.puts post } list = Array.new @listing.each { |file, value| list << "#{file}:#{value}:#{@hf_pointing[file]}" } list.each { |post| @listing_file.puts post } end def display # ce tableau est là pour éviter qu'une entrée dans le posting file # soit dupliquée si le mot apparait plusieurs fois. uniq = Hash.new @listing[@current_file] = "#{@array.length}:#{@name}" @array.each do |word| # si c'est la première fois qu'on rencontre ce mot... if !@d_array.has_key?(word)#!pos temp = @array.grep(word) @post_array << "#{temp.length.to_s}:#{@current_file}" @d_array[word] = (@post_array.length-1).to_s uniq[word] = 1 # sinon c'est qu'il est déjà dans le dico... else if !uniq[word] temp = @array.grep(word) @post_array[@d_array[word].to_i] += " #{temp.length.to_s}:#{@current_file}:" uniq[word] = 1 end end end end end
true
80dff008aab5632cb8e37b2a9d21485a73c892f3
Ruby
chen-factual/scripts
/resolve/parameter-sweeps/parse-results.rb
UTF-8
1,722
3.203125
3
[]
no_license
require 'json' B0 = "b0" B1 = "b1" OVERALL = "overall" SUMMARY_SCORE = "summary_score" INPUT_OVERFOLD = "input-overfold-rate" INPUT_REPULSION = "input-repulsion-score" INPUT_COHESIVENESS = "input-cohesiveness-score" SUMMARY_DUPE = "summary-dupe-rate" SUMMARY_OVERFOLD = "summary-overfold-rate" def attach_score(score) score[OVERALL] = score[INPUT_OVERFOLD] + score[INPUT_REPULSION] + score[INPUT_COHESIVENESS] + score[SUMMARY_DUPE] + score[SUMMARY_OVERFOLD] - 2 score[SUMMARY_SCORE] = score[SUMMARY_DUPE] + score[SUMMARY_OVERFOLD] return score end def read_results() b0 = nil b1 = nil results = [] current = {} STDIN.each_line do |line| if m = /B0\s(\S+)\sB1\s(\S+)/.match(line) # If we had previous values, save them if not current[B0].nil? and not current[B1].nil? results << attach_score(current) current = {} end # Set constants current[B0] = m[1].to_f current[B1] = m[2].to_f elsif m = /:(.*):\s+(.*)/.match(line) field = m[1] value = m[2].to_f current[field] = value end end return results end def sort_results(results) return results.sort do |a, b| a[SUMMARY_SCORE] <=> b[SUMMARY_SCORE] end end def output(sorted) sorted.each do |scores| puts "B0: #{scores[B0]} B1: #{scores[B1]}\n" puts scores[INPUT_OVERFOLD].to_s + "\n" puts scores[INPUT_REPULSION].to_s + "\n" puts scores[INPUT_COHESIVENESS].to_s + "\n" puts scores[SUMMARY_DUPE].to_s + "\n" puts scores[SUMMARY_OVERFOLD].to_s + "\n" puts scores[OVERALL].to_s + "\n" puts scores[SUMMARY_SCORE].to_s + "\n" end end results = read_results() sorted = sort_results(results) output(sorted)
true
51813c0717dfe20848e8c39f14105e8afa73b305
Ruby
annakiuber/minedmindskata
/reverse_array_3and_5.rb
UTF-8
255
3.5
4
[]
no_license
def reverseminedmindskata() array = (1..100).to_a array.map! do |num| if num % 15 == 0 num ="mined minds" elsif num % 3 == 0 num = "mined" elsif num % 5 == 0 num = "minds" else num end end array end # puts reverseminedmindskata
true
e15d2ce1b46f7e04d77455a476b5c084766efceb
Ruby
okhlybov/iop
/lib/iop/string.rb
UTF-8
2,129
3.453125
3
[]
no_license
require 'iop' module IOP # # Feed class to send arbitrary string in blocks of specified size. # # ### Use case: split the string into 3-byte blocks and reconstruct it. # # require 'iop/string' # ( IOP::StringSplitter.new('Hello IOP', 3) | IOP::StringMerger.new ).process! # # @since 0.1 # class StringSplitter include Feed # Creates class instance. # # @param string [String] string to be sent in blocks # # @param block_size [Integer] size of block the string is split into def initialize(string, block_size: DEFAULT_BLOCK_SIZE) @string = string @block_size = block_size end def process! offset = 0 (0..@string.size / @block_size - 1).each do process(@string[offset, @block_size]) offset += @block_size end process(offset.zero? ? @string : @string[offset..-1]) unless offset == @string.size process end end # # Sink class to receive data blocks and merge them into a single string. # # ### Use case: read current source file into a string. # # require 'iop/file' # require 'iop/string' # ( IOP::FileReader.new($0) | (s = IOP::StringMerger.new) ).process! # puts s.to_s # # The actual string assembly is performed by the {#to_s} method. # # @note instance of this class can be used to collect data from multiple processing runs. # # @since 0.1 # class StringMerger include Sink # Creates class instance. def initialize @size = 0 @data = [] end def process(data = nil) unless data.nil? @data << data.dup # CHECKME is duplication really needed when the upstream continuously resending its internal data buffer with new contents @size += data.size end end # Returns concatenation of all received data blocks into a single string. # # @return [String] def to_s string = IOP.allocate_string(@size) @data.each {|x| string << x} string end end end
true
7d0071175dadbbc7558e5926d086ec7f06dad075
Ruby
CaileeHarrington/learn-co-sandbox
/challenge2.rb
UTF-8
325
3.953125
4
[]
no_license
# Monday Morning Challenge Question WARM UP:car::blue_car::racing_car: #Start Here class Vehicle def initialize(color, type) @color = color @type = type end def color @color end def color=(color) @color = color end end car1 = Vehicle.new ("blue","racing") puts "Hey, I'm a #{color} #{type} car. Honk!"
true
b65060c95216263083dc52e637c512397dcbb97f
Ruby
benhamilton15/Karaoke_Classes_weekend_hw_w2
/guests.rb
UTF-8
515
3.125
3
[]
no_license
class Guests attr_reader :name, :wallet, :fav_song def initialize(name, wallet, fav_song) @name = name @wallet = wallet @fav_song = fav_song end def pay_fee(fee) if can_afford(fee) @wallet -= fee end end def can_afford(fee) return @wallet >= fee end def fav_song_playing_in_room?(room) if room.song_list.include?(@fav_song) return "This place is lit!" end return "i need more drinks for this" end #compare it to a map of the song names end
true
3532f72e793dbdc5a433ca2ceb098414c17c7751
Ruby
misslesliehsu/week-1-group-review-web-112017
/review-question-3.rb
UTF-8
995
3.703125
4
[]
no_license
# begin to build a simple program that models Instagram # you should have a User class, a Photo class and a comment class # OUR RESPONSES class User attr_accessor :name, :photos def initialize(name) @name = name @photos = [] end end class Photo attr_reader :user, :comments def initialize @comments = [] end def user=(user) @user = user @user.photos << self end def make_comment(text) comment = Comment.new(text) @comments << comment comment.photo = self end end class Comment attr_accessor :text, :photo @@all = [] def initialize(text) @@all << self end def self.all @@all end end ######### photo = Photo.new user = User.new("Sophie") photo.user = user photo.user.name # => "Sophie" user.photos # => [<photo 1>] photo.comments # => [] photo.make_comment("this is such a beautiful photo of your lunch!! I love photos of other people's lunch") photo.comments # => [<comment1>] Comment.all #=> [<comment1>]
true
e2b0c0acaeca851e228bb0c57d22bd45597395d7
Ruby
letheyue/IUI-project
/yulp_app/app/models/restaurant.rb
UTF-8
6,466
2.84375
3
[]
no_license
require 'yelp_client.rb' require 'crawler_client.rb' require 'category.rb' class Restaurant < ActiveRecord::Base has_many :reviews has_many :users, through: :reviews has_and_belongs_to_many :categories self.table_name = "restaurants" def trim_to_empty(str) if str.nil? return '' end str end def names name = Array.new(@size) index = 0 @business.each do |n| name[index] = n["name"] index = index + 1 end name end def addresses address = Array.new(@size) index = 0 @business.each do |a| hash = a['location'] address[index] = '' unless hash.nil? unless hash['address1'].nil? address[index] += hash['address1'] + ' ' end unless hash['address2'].nil? address[index] += hash['address2'] + ' ' end unless hash['address3'].nil? address[index] += hash['address3'] + ' ' end end index = index + 1 end address end def add_open_hour(id) hash = YelpClient.business(id) open_hour = Hash.new if (hash["hours"] != nil) hash["hours"][0]["open"].each do |day| s = day["day"] if (s == 0) d = 'Monday' end if (s == 1) d = 'Tuesday' end if (s == 2) d = 'Wednesday' end if (s == 3) d = 'Thursday' end if (s == 4) d = 'Friday' end if (s == 5) d = 'Saturday' end if (s == 6) d = 'Sunday' end open_hour[d] = 'start_time: ' + day["start"] + ' ' + 'close_time: ' + day["end"] end end open_hour end def get_all_popular_times(names, addresses) places = names.zip(addresses).to_h # byebug result_hash = Hash.new CrawlerClient.get_all_popular_times(places).each do |name, result| one_place_result = Hash.new result.each do |day, times| hash_times = Hash.new times.each_with_index do |time, index| hash_times[(index+7).modulo(24)] = time end one_place_result[day] = hash_times end result_hash[name] = one_place_result end result_hash end def get_all_discount_info(names, addresses) places = names.zip(addresses).to_h CrawlerClient.get_all_discount_info(places) end # Note: This function will only fetch data once # Then create the Restaurant & Categories table # address can be nil # popular_times can be nil # each element in popular_times Hash can be nil def self.setup_table_once @whole_information = YelpClient.search({}) @size = @whole_information["businesses"].size @business = @whole_information["businesses"] @fetched ||= Restaurant.all.present? if @fetched return end names = Restaurant.name addresses = Restaurant.addresses popular_times = Restaurant.get_all_popular_times(names, addresses) discounts = Restaurant.get_all_discount_info(names, addresses) @business.each do |business| restaurant = Restaurant.new restaurant.name_id = business["id"] current_instance = Restaurant.find_by name_id: business["id"] if current_instance restaurant = current_instance else restaurant.name = business["name"] restaurant.image_url = business["image_url"] || '' restaurant.url = business["url"] || '' restaurant.review_count = business["review_count"] || '' restaurant.rating = business["rating"] restaurant.phone = business["phone"] || '' restaurant.price = business["price"] || '' coordinate = Array.new coordinate << business["coordinates"]["latitude"] coordinate << business["coordinates"]["longitude"] restaurant.coordinates = coordinate location = business["location"] address = trim_to_empty(location["address1"]) + trim_to_empty(location["address2"]) + trim_to_empty(location["address3"]) restaurant.address = address restaurant.city = location["city"] restaurant.zip_code = location["zip_code"] restaurant.country = location["country"] restaurant.state = location["state"] restaurant.popular_times = popular_times[restaurant.names] restaurant.discount = discounts[restaurant.names] restaurant.open_hour = Restaurant.add_open_hour(business["id"]) restaurant.save! # Category is saved in its own Model business["categories"].each do |category_hash| category = Category.find_by title: category_hash["title"] unless category category = Category.new category.title = category_hash["title"] category.alias = category_hash["alias"] category.save! end category.restaurants << restaurant end end end @fetched = true end # The following is for Data Manipulation def self.search(search) search = search.downcase.gsub(/\-/, '') where("lower(name) LIKE ? OR lower(address) LIKE ? OR lower(city) LIKE ? OR lower(zip_code) LIKE ? OR lower(phone) LIKE ?", "%#{search}%", "%#{search}%","%#{search}%", "%#{search}%", "%#{search}%") end def self.custom_search( search_str, preference) # Apply cache technique # Do not cache if search_str == nil # => Otherwise it will cache all the restaurants if @term && (search_str && @term == search_str) logger.info('Same Term Encountered.') return @raw_results else @raw_results = Restaurant.search(search_str || '').sort{ |a,b| calculate_overall_weight_for_restaurant(b, preference) <=> calculate_overall_weight_for_restaurant(a, preference) } if search_str @term = search_str else @term = '' end logger.info("Term is:#{@term}") return @raw_results end end def self.calculate_overall_weight_for_restaurant (restaurant, prefer) # byebug if restaurant.price.size != 0 result = (restaurant.rating.to_f * prefer['weight_rating'] * 1 + (5-restaurant.price.size) * prefer['weight_price'] + restaurant.discount.to_f / 40 * prefer['weight_discount'] ) else result = (restaurant.rating.to_f * prefer['weight_rating'] * 1 + 3 * prefer['weight_price'] +restaurant.discount.to_f / 40 * prefer['weight_discount'] ) end result end end
true
21d8b1e2d03be1298f15bae20a91245d4dbf9772
Ruby
rgagnon/server_side_google_maps_api
/spec/lib/base_service_provider_spec.rb
UTF-8
1,138
2.515625
3
[ "MIT" ]
permissive
require "#{File.dirname(__FILE__)}/../spec_helper" require 'server_side_google_maps_api/apis/base' describe ServerSideGoogleMapsApi::Api::Base do let(:base) { ServerSideGoogleMapsApi::Api::Base.new } it "should be a base object" do base.should be_a ServerSideGoogleMapsApi::Api::Base end describe "Building query string from params" do it "should build the simple query from string arg" do base.send(:hash_to_query, {:test => 'test'}).should == "test=test" end it "should build the simple query from array arg" do base.send(:hash_to_query, {:test => ['test', 'test1']}).should == "test=test%7Ctest1" end it "should build the simple query with multiple args" do base.send(:hash_to_query, {:test2 =>['test', 'test3'] , :test => ['test', 'test1']}).should == "test2=test%7Ctest3&test=test%7Ctest1" end it "should build args value query from string" do base.send(:args_value_to_query, 'test').should == "test" end it "should build args value query from array" do base.send(:args_value_to_query, ['test','test1']).should == "test|test1" end end end
true
0eff704e8cf9437854a4e029697c1efd8cce52fd
Ruby
kbaba1001/flying_money
/app/models/expense_item.rb
UTF-8
933
2.515625
3
[]
no_license
class ExpenseItem < ActiveRecord::Base belongs_to :user has_many :outlays, dependent: :destroy validates :name, presence: true, uniqueness: {scope: :user_id} validates :display_order, presence: true, numericality: {only_integer: true, greater_than: 0} validates :user_id, presence: true before_validation :set_default_display_order!, if: 'display_order.blank?' DEFAULTS = %w(食費 交通費 会食費 教育費 娯楽費 医療費 雑費) scope :ordered, -> { order(:display_order) } class << self def create_default_expense_items!(user) DEFAULTS.each.with_index(1) do |name, display_order| create!( name: name, display_order: display_order, user: user ) end end end def set_default_display_order! return unless user self.display_order = ExpenseItem.where(user: user).maximum(:display_order).to_i + 1 end end
true
e1f0bf3ae550532549a1a79fe52559383fb3038c
Ruby
cacdesign/thp_ruby
/pyramide.rb
UTF-8
129
3.203125
3
[]
no_license
puts "Donne moi un nombre :) hihi" nombre = gets.chomp.to_i nombre.times do |i| puts " " * (nombre - (i+1)) + "#" * (i+1) end
true
ec7c3eaa4b662bae96e10da854b74f22552367b8
Ruby
smdecker/ruby-collaborating-objects-lab-v-000
/lib/mp3_importer.rb
UTF-8
494
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MP3Importer attr_accessor :path def initialize(path) @path = "./spec/fixtures/mp3s" end def files #loads all the mp3 files in the path directory Dir.glob("./spec/fixtures/mp3s/*.mp3") #normalizes the filename to just the mp3 filename with no path Dir.entries("./spec/fixtures/mp3s").select {|f| !File.directory? f} end def import list_of_filenames = self.files list_of_filenames.each { |filename| Song.new_by_filename(filename) } end end
true
eac80ae99b5716ed06d3b5458e2e8bdb74543e14
Ruby
carolemny/TheHackingProject-the_gossip_project
/db/seeds.rb
UTF-8
1,698
2.515625
3
[]
no_license
require 'pry' #Variables pour les tests NB_CITIES = 20 NB_USERS = 100 NB_PRIVATE_MESSAGES = 500 NB_GOSSIPS = 200 NB_TAGS = 50 gossip_ary = Array.new tag_ary = Array.new cities = [] users = [] pms= [] #Cities NB_CITIES.times do cities << City.new(name: Faker::Address.city, zip_code: Faker::Number.leading_zero_number(digits: 5)) end City.create(cities.map { |elem| elem.as_json }) #Users NB_USERS.times do users << User.create(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, city_id: Faker::Number.between(from: 1, to: NB_CITIES), email: Faker::Internet.email, age: Faker::Number.between(from: 13, to: 70), description: Faker::Lorem.paragraph(sentence_count: 3, supplemental: true), password: Faker::Internet.password(min_length: 6)) end #Gossips NB_GOSSIPS.times do gossip_ary << Gossip.new(content: Faker::Lorem.paragraph(sentence_count: 5, supplemental: true), title: Faker::Book.title[0..13], user_id: Faker::Number.between(from: 1, to: NB_USERS)) end #Tagss[] NB_TAGS.times do t = Tag.create(title: Faker::Lorem.word) tag_ary << t t.save end gossip_ary.each do |gossip| n = Faker::Number.between(from: 1, to: 5) n.times do gossip.tags << tag_ary.sample end end Gossip.create(gossip_ary.map { |elem| elem.as_json }) #NB_PRIVATE_MESSAGES.times do # pm = PrivateMessage.new(content: Faker::Lorem.paragraph(sentence_count: 5, supplemental: true), sender_id: Faker::Number.betweenfrom: 1, to: NB_USERS)) # n = Faker::Number.between(from: 1, to: 5) # n.times do # JoinTablePmRecipient.create(user_id: Faker::Number.between(from: 1, to: NB_USERS), private_message_id:pm.id) # end # pms << pm #end #PrivateMessage.create(pms.map { |elem| elem.as_json })
true
47b826742818ac982310fe6ab379a5ec5002a5a7
Ruby
CalumCannon/multiple-classes-ruby
/specs/bear_spec.rb
UTF-8
438
2.78125
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('../bear.rb') require_relative('../river.rb') class TestBear < MiniTest::Test def setup @bear = Bear.new("James", "Brown") @river = River.new("Clyde") end def test_take_fish() @bear.take_fish(@river) assert_equal(1,@bear.stomach.count) end def test_bear_food_count @bear.take_fish(@river) assert_equal(1,@bear.food_count) end end
true
7b49868233d3b7eaea3ebff156200c73efdc796f
Ruby
alexglach/project_tdd_minesweeper
/spec/cell_spec.rb
UTF-8
480
2.6875
3
[]
no_license
require 'cell' describe Cell do describe "#initialize" do let(:c) { Cell.new(3, 2) } it "should initialize with a row_index" do expect(c.row_index).to eq(3) end it "should initialize with a column_index" do expect(c.column_index).to eq(2) end it "starts with no content" do expect(c.content).to be_nil end specify "cleared? should be false to start" do expect(c.clear).to be_falsey end end end
true
82426527fbb12c2697326687daf63ffbde900718
Ruby
halogenandtoast/reconstructing_ruby
/code/chapter_2-parsing/test.rb
UTF-8
154
3.578125
4
[]
no_license
class Greeter def initialize(name) @name = name end def greet puts "Hello #{@name}" end end greeter = Greeter.new("Ruby") greeter.greet
true
7a62784722783b76a8b66b100701c6d99242837a
Ruby
briceth/diamond
/db/seeds.rb
UTF-8
962
2.59375
3
[]
no_license
Proposal.delete_all User.delete_all Activity.delete_all password = "passwordpassword" 20.times do user = User.new user.email = Faker::Internet.email user.password = password user.first_name = Faker::Name.first_name user.last_name = Faker::Name.last_name user.avatar = Faker::Avatar.image("my-own-slug", "50x50") puts "Welcome " + user.first_name if user.save end categories = ['sports', 'open', 'restaurant', 'theatre', 'exposition', 'concert', 'coffee', 'cinema'] categories.each do |category| activities = Activity.new activities.category = category puts "welcome " + activities.category if activities.save end 20.times do proposal = Proposal.new proposal.subject = Faker::Lorem.word proposal.content = Faker::Lorem.sentence proposal.location = Faker::Address.street_address proposal.price = Faker::Number.number(2) proposal.activity_id = Faker::Number.between(1, 8) puts "welcome " + proposal.subject if proposal.save end
true