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
e5c1b6935e9fa46c2952a00c4178324a51d5eea8
Ruby
caroledou/shoprite
/db/seeds.rb
UTF-8
12,758
2.890625
3
[]
no_license
require 'open-uri' require 'json' puts "Cleaning DB" Review.destroy_all Delivery.destroy_all OrderDetail.destroy_all Order.destroy_all User.destroy_all Composant.destroy_all Ingredient.destroy_all Recipe.destroy_all # ------------------------ USER ------------------------ puts "Creating account carole-albert" account = User.new(email: "[email protected]", first_name: "Carole", name: "Albert", address: "Rue du Port-Franc 22, 1003 Lausanne", phone_number: "079 546 78 98", password: "123456" ) account.save! # ------------------------ RECIPES SEED ------------------------ puts "Parsing 188 Recipe IDs from 12 Categories..." recipe_id_db = [] Recipe::RECIPE_CATEGORIES.each do |category| url = "https://www.themealdb.com/api/json/v1/1/filter.php?c=#{category}" categ_serialized = open(url).read categ = JSON.parse(categ_serialized) array_recipe_id = categ["meals"].map do |e| e["idMeal"].to_i end array_recipe_id.each do |id| recipe_id_db << id end end puts "Done!" puts "Creating Recipes Database... this will take a while..." puts "...." puts "------------------------------------------" recipe_counter = 0 recipe_id_db.each do |id| url_recipe = "https://www.themealdb.com/api/json/v1/1/lookup.php?i=#{id}" recipe_serialized = open(url_recipe).read recipe = JSON.parse(recipe_serialized) new_recipe = Recipe.new( name: recipe["meals"].first["strMeal"], category: recipe["meals"].first["strCategory"], description: recipe["meals"].first["strInstructions"], cooking_time: rand(30..60).to_i) photo = recipe["meals"].first["strMealThumb"] new_recipe.remote_photo_url = photo new_recipe.save! recipe_counter += 1 puts "Recipe #{recipe_counter} created" # ------------------------ COMPOSANTS FOR A GIVEN RECIPE ------------------------ puts "...." puts "Creating Composants for recipe #{recipe_counter}..." composant_counter = 0 (1..20).each do |number| recipe = "https://www.themealdb.com/api/json/v1/1/lookup.php?i=#{recipe['meals'].first['idMeal']}" recipe_serialized = open(url_recipe).read recipe = JSON.parse(recipe_serialized) if recipe["meals"].first["strIngredient#{number}"] != "" && recipe["meals"].first["strIngredient#{number}"] != nil if recipe["meals"].first["strMeasure#{number}"].start_with?(/^[1-9]/) quantity = recipe["meals"].first["strMeasure#{number}"] else quantity = rand(1..7).to_i end price = rand(1..2) new_composant = Composant.new( recipe_id: new_recipe.id, ingredient: recipe["meals"].first["strIngredient#{number}"], quantity: quantity, price_cents: price, # price_cents: rand(0.1..2).to_i ) new_composant.save! composant_counter += 1 p "Composant #{composant_counter} for recipe #{recipe_counter} created!" end end puts "....." puts "All composants for recipe #{recipe_counter} created" puts "------------------------------------------" end puts "Recipes Database created!" puts "Composants Database created!" puts "---------------------" # ------------------------ REVIEWS ------------------------ puts "Creating reviews" contents = ["WOW! This was really yummy! All the family loved it -- ⭐️️⭐️️⭐️️⭐️️⭐️ ", "Delicious recipe I recommend for cosy diner with friends -- ⭐️️️️⭐️️⭐️️⭐️", "Looking forward to making this recipe again. Easy and tasty! -- ⭐️️️️⭐️️⭐️️⭐️", "BEST. RECIPE. EVER -- ⭐️️⭐️️⭐️️⭐️️⭐️", "Take time to cook but this recipe turned out to be AMAZING -- ⭐️️⭐️️⭐️️⭐️️⭐️", "I tried this recipe and my kids weren't very impressed... -- ⭐️⭐️", "This recipe is OK -- ⭐️⭐️⭐️", "Not as tasty as expected but globally good -- ⭐️⭐️⭐️", "Convenient food for lazy cook -- ⭐️️⭐️⭐️⭐️", "Not worth the cooking time! -- ⭐️️⭐️️", "Sorry, I found it bland. Won't be making it again -- ⭐️", "Terrible - worst ever. Waste of my time & money -- ⭐️️", "I do not recommend this recipe, it's a disaster... -- ⭐️️", "This one was a thumbs down unfortunately, missing something -- ⭐️⭐️", "Followed each step of this recipe, turned out horrible! -- ⭐️️" ] avatars = [ "http://www.roblaceyphotographer.co.uk/wp-content/uploads/2017/02/Headshot-square.jpg", "http://www.hilbgroup.com/wp-content/uploads/2018/03/hilb-group-headshots-6617-web-square.jpg", "https://philadelphiacorporateheadshots.org/wp-content/gallery/people/True-Capital-July-2014-36-Square.jpg", "https://jkaplanortho.com/wp-content/uploads/2018/10/dr-kaplan-headshot-square.jpg", "https://www.boutiquephotographer.net/wp-content/uploads/2015/04/WORK_Headshot-Square.003_WEB.jpg", "https://www.christenseninstitute.org/wp-content/uploads/2018/08/Mark-Johnson-Headshot-Square.jpg", "https://lyrictheatreokc.com/wp-content/uploads/2015/09/Geno-Square-Headshot.jpeg", "https://www.surfmedia.com/wp-content/uploads/2014/07/Camron-headshot-square.jpg", "http://www.homexpertsuk.com/wp-content/uploads/2016/10/headshot-colour-1-square.jpg", "https://halifaxcomedyfest.ca/wp-content/uploads/2018/11/andrew-barr-headshot-2015-SQUARE-1.jpg", "https://1e28aybmvig19yc0648l8lth-wpengine.netdna-ssl.com/wp-content/uploads/2015/07/Mark-2012-Headshot-Square.jpg", "https://billgladwelllive.com/wp-content/uploads/2018/07/cropped-Bill-Gladwell-%E2%80%94-Outside-Headshot-%E2%80%94-Square.jpg", "http://www.ramahsportsacademy.org/wp-content/uploads/2018/10/Mendy-Headshot-Square-2018.jpg", "https://dstudiosphotography.com/wp-content/uploads/2015/09/headshot-ciran-square.jpg", "https://automatedinsights.com/wp-content/uploads/2018/05/headshot-square-asmith.jpg", "https://www.cncf.io/wp-content/uploads/2017/09/Headshots-282-Square.jpg", "https://images-na.ssl-images-amazon.com/images/I/61NJ7HxHPrL._UX250_.jpg", "https://karencampbellphoto.com/wp-content/gallery/headshots/IMG_0199-Edit2_square_web.jpg", "https://www.college.columbia.edu/alumni/sites/default/files/David%20Barry%20Headshot%20-%20JJ%20Dinner%202017%20--%20SQUARE.jpg", "https://ww1.prweb.com/prfiles/2017/05/17/15170775/gI_62627_Kevin%20Harrigan.png", "https://blacksmithroofing.com/wp-content/uploads/2017/10/Cylas-Square-Headshot-1-of-1.jpg", "http://thebluepaper.com/wp-content/uploads/bud-navero-headshot-square.jpg", "https://gocrossway.org/wp-content/uploads/2018/02/Moses-2-20170912_140103-square-headshot.png", "http://www.sovereignrisksolutions.com/wp-content/uploads/2016/01/square-Taylor-Westbrook-Headshot-768x768.jpg", "http://www.parisoma.com/system/images/W1siZiIsIjIwMTgvMDkvMjgvNDNyZnN6Zmp2MF9Kb2VfSGVhZHNob3RfU3F1YXJlX0hSXzEuanBnIl1d/Joe_Headshot-Square-HR-1.jpg", "http://static.squarespace.com/static/52e84526e4b0713dd6db1cdd/5337a883e4b0fa0f8f50e47a/5342e7bae4b0cccdfc3cd7b8/1396893627863/headshotsquaresmall.jpg?format=750w", "http://airan-lab.stanford.edu/wp-content/uploads/2016/11/AiranRD-headshot-square-300x300.jpg", "https://ne9dcc0wbd-flywheel.netdna-ssl.com/wp-content/uploads/2015/11/synergy_headshots_medaest_square_drcollins-300x300.jpg", "http://www.parisoma.com/system/images/W1siZiIsIjIwMTgvMDkvMjgvNWN3cXJjNzRtbl9QaWVycmVfSGVhZHNob3RfU3F1YXJlX0hSXzEuanBnIl1d/Pierre_Headshot_Square-HR-1.jpg", "https://cities-today.com/wp-content/uploads/2019/02/StefanSchaffer_Headshot_Square_FINAL-1024x1024.jpg", "https://cdn2.sportngin.com/attachments/roster_player_info/b0cf-110880334/TOCA_Headshot_Square_medium.jpg", "https://www.ridgewine.com/wp-content/uploads/2016/02/paul-headshot-square.jpg", "https://cdn3.sportngin.com/attachments/roster_player_info/1033/3686/David_Reppucci_Headshot_Square_medium.jpg", "https://pros.weddingwire.com/hs-fs/hubfs/Alan%20Berg-headshot-square%20200x200.jpg?width=200&height=200&name=Alan%20Berg-headshot-square%20200x200.jpg", "https://static1.squarespace.com/static/598c8d49f5e23146af538e93/t/5a00a73171c10beb61f322ab/1509992247455/Tom-Severini---Jean-Headshot-Square.jpg?format=500w", "https://static1.squarespace.com/static/57bf08f0b3db2b9f084ac5eb/t/5c06dbdf4d7a9cdeb595da4c/1543953395076/Headshot+-+square.jpg", "https://www.college.columbia.edu/alumni/sites/default/files/Toomas%20Hendrik%20Ilves%20Headshot%20Cropped%20-%20JJ%20Dinner%202017%20-%20Credit%20Hindrek%20Maasik%20--%20SQUARE.jpg", "http://csforum2013.com/wp-content/uploads/2013/04/kristina-headshot-square-624x609.png", "http://girliemom.com/wp-content/uploads/2014/09/Headshots-square-1.jpg", "https://aladygoeswest.com/wp-content/uploads/2015/02/Ashley-Pitt-headshot-square.jpg", "https://www.medvetforpets.com/wp-content/uploads/2017/05/Gade-headshot-square-1.jpg", "https://orgcommunity.com/wp-content/uploads/2018/05/Website-Headshot-Square-Format-1.png", "https://vacationmavens.com/wp-content/uploads/2015/12/Headshot-Square-StuffedSuitcase.jpg", "http://thecivicedge.com/wp-content/uploads/2018/07/Anouk-Versavel-Headshot-Square.jpg", "http://ecdental.org/wp-content/uploads/2018/03/employee-headshot-Philadelphia-185.jpg", "http://legalhotlines.org/wp-content/uploads/sites/6/2016/12/Ellen-Cheek-Headshot-Square-min.png", "http://www.greengaragedetroit.com/site/wp-content/uploads/2017/10/Gracie-Headshot-square-1.png", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR13Wcn7T-IZ98Tcjbm83vaKciFb9OeQXptPKn3sS5AbcHxTOs", "https://customerex2018.aci.aero/wp-content/uploads/2018/08/Starr-Cunningham-Headshot-2018-square.jpg", "https://www.disabilityrightswa.org/wp-content/uploads/2018/07/Anna-Square-Headshot.jpg", "http://www.momentumsolutionsteam.com/wp-content/uploads/2017/03/Denise-headshot-square.jpg", "https://orami.org/wp-content/uploads/sites/32/2018/07/elana-headshot-square.jpg", "https://thestemlaboratory.com/wp-content/uploads/2015/11/kelly-square-headshot-1.jpeg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTUMaJxlrTmbfPdQLclLOH1kkKyoKOge7BHsBscc5wXtQIAgNoDzw", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSFt0fGIBUCipW16qa36YiLjxYiDlmjU1l_kHMqebmdyakKsIBX", "https://goldoller.com/wp-content/uploads/2016/03/jill-headshot-square.jpg", "https://www.famhealthcare.org/wp-content/uploads/2015/04/Jill-Head-Shot.jpg", "https://dml-group.com/wp-content/uploads/2018/09/dml-group-headshots-11Sept18-02-IMG_3141ss-square-bw-e1537534008592.jpg", "https://bodhispiritualcenter.org/wp-content/uploads/2016/08/Joan-headshot-square.jpg", "https://www.surfmedia.com/wp-content/uploads/2018/03/Caitlin-Headshot-square.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS4QX33kLPuKQ4uH--ncIKkii50lJ39Clnz0JXtHwOnnI-VfBNB", "https://www.revolutionpr.com/wp-content/uploads/2016/11/Use-this-headshot-for-the-website-Zaina-Copy-square.jpg", "https://www.uprisingtheatreco.com/wp-content/uploads/2017/08/Sulentic-Maggie-Mae.jpg", "https://arthausdecorah.org/wp-content/uploads/2016/08/Geier-Headshot-Square-400x400.jpg", "https://static1.squarespace.com/static/5a6f9af7268b966fdfcff367/t/5b18528803ce64e055c88f98/1528320657142/lauren+headshot+square+pixels+%281%29.jpg", "https://static1.squarespace.com/static/52b7e285e4b0f630e3bafa05/58730aced1758e4368de9c5e/58730acf2994ca0ccdef5b44/1483934428434/Headshot+-+Square.jpg?format=500w", "https://www.thoughtco.com/thmb/aUMN6WNeySX4uffIhNN6ZYwmwP8=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/R-Flynn-headshot-square-copy-56a7359b3df78cf7729352e4.jpg", "https://wecollide.net/wp-content/uploads/2017/09/010-square-headshots-2017-jen-fox_-1024x1024.jpg", "https://acceleprise.vc/wp-content/uploads/2017/12/fullsizeoutput_273.jpeg", "https://s3-us-west-2.amazonaws.com/rets-mls/advisors/header_images/000/000/148/medium/Tiffany_Headshot_Square_Color_adjust.jpg?1519949919", "http://www.annerogersrealtygroup.com/assets/img/realtors/Sondra%20Headshot%20SQUARE.jpg?Action=thumbnail&algorithm=fill_proportional&width=240&height=240", "https://www.thefield.org/sites/default/files/Jennifer%20Cenda%C3%B1a%20Armas%20headshot%20square.jpg", "https://www.bandcfinancial.com/wp-content/uploads/2018/12/Genny-Headshot-Crop-Square-300x300.jpg", "https://payload.cargocollective.com/1/9/317970/13619359/Proske_headshot_Square_670.jpg", "https://refb.org/wp-content/uploads/2018/03/RFB-HEADSHOTS_-46-Square.jpg", "http://thecivicedge.com/wp-content/uploads/2018/07/Cheryl-Reiss-Headshot-Square.jpg", "https://rockhealth.com/wp-content/uploads/2015/07/halle-headshot-square-2.jpg" ] 2.times do Recipe.all.each do |recipe| recipe.reviews.create( content: contents.sample, rating: avatars.sample ) end end puts "Done!"
true
f3c8dea869a6f63b5bbc6b43ae5d46816db82cae
Ruby
robacarp/nemucod_decrypt
/uncrypt_nemucod/decrypt.rb
UTF-8
928
2.578125
3
[]
no_license
require 'fileutils' require_relative 'shared' module UncryptNemucod class Decrypt include Shared def initialize(crypted_file:, key_file:) decrypted_file = crypted_file.gsub(/.crypted$/,'') FileUtils.cp crypted_file, decrypted_file @decrypted_file = File.open decrypted_file, 'r+b' @crypted_file = File.open crypted_file, 'rb' @key_file = File.open key_file, 'rb' end def decrypt offset = 0 while offset < KEY_LENGTH && offset < @crypted_file.size @key_file.pos = offset @crypted_file.pos = offset @decrypted_file.pos = offset key_byte = @key_file.read 1 crypted_byte = @crypted_file.read 1 decrypt_byte = pack( unpack(key_byte) ^ unpack(crypted_byte) ) @decrypted_file.write decrypt_byte offset += 1 end @crypted_file.close @key_file.close end end end
true
eb51b7a3736cc4e389fd7b6cfa30558292889caf
Ruby
cbronzo/model-class-methods-lab-v-000
/app/models/captain.rb
UTF-8
552
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Captain < ActiveRecord::Base has_many :boats def self.catamaran_operators includes(boats: :classifications).where(classifications: {name: "Catamaran"}) end def self.sailors includes(boats: :classifications).where(classifications: { name: 'Sailboat' }).uniq end def self.motorboats includes(boats: :classifications).where(classifications: { name: 'Motorboat' }) end def self.talented_seafarers self.where(id: self.sailors & self.motorboats) end def self.non_sailors where.not("id IN (?)", self.sailors.pluck(:id)) end end
true
1155e372abbbabeb1bbcdfd921d115410cff8fe0
Ruby
zuk/glowstick
/lib/glowstick/glowstick.rb
UTF-8
2,135
2.8125
3
[ "MIT" ]
permissive
class Glowstick ########################################################################### # Class class << self attr_accessor :graphs end self.graphs = [] def self.register(graph) self.graphs << graph end def self.clear self.graphs.clear end ########################################################################### # Instance def initialize(handler) @window = Box.new(0, 1, 0, 1) @handler = handler @w = 800 @h = 400 end def display # clear the buffer glClear(GL_COLOR_BUFFER_BIT) # # calculate and apply the current view size boxes = Glowstick.graphs.map { |g| g.bounding_box } if boxes.empty? @window = Box.new(0, 1, 0, 1) else @window = Box.container(boxes).inset_percent(10) end reshape # draw each graph Glowstick.graphs.each do |graph| graph.draw end # swap buffer glutSwapBuffers() end def reshape(w = @w, h = @h) @w = w @h = h glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() GLU.Ortho2D(@window.l, @window.r, @window.b, @window.t) end def keyboard(key, x, y) case key when 27 # Escape exit end end def idle should_draw = @handler && @handler.idle if should_draw glutPostRedisplay end end def start glutInit glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA) glutInitWindowSize(@w, @h) glutInitWindowPosition(100, 100) glutCreateWindow("Glowstick") glClearColor(0.0, 0.0, 0.0, 0.0) glEnable(GL_LINE_SMOOTH) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE) glShadeModel(GL_FLAT) @handler.init if @handler && @handler.respond_to?(:init) glutDisplayFunc(self.method(:display).to_proc) glutReshapeFunc(self.method(:reshape).to_proc) glutKeyboardFunc(self.method(:keyboard).to_proc) glutIdleFunc(self.method(:idle).to_proc) if @handler && @handler.respond_to?(:idle) glutMainLoop() end end
true
26943f2d1436308695975ee13a21c4b4b488ad7f
Ruby
eivindhagen/dirscan
/lib/file_pile_dir.rb
UTF-8
1,559
3.1875
3
[]
no_license
# manages the directory structure for a File Pile class FilePileDir private def dir_structure [ {path: 'filedata', doc: 'file data, named by content sha256'}, {path: 'metadata', doc: 'meta data, catalog information for each file in the pile'}, {path: 'logs', doc: 'log files, generated by various file pile operations'}, {path: 'temp', doc: 'temporary files, generated by various file pile operations and removed when no longer needed'}, ] end # create object by specifying the location of the File Pile directory (even if it doesn't exist) # the necessary directories will be created if they do not already exist public def initialize(filepile_root) puts "FilePileDir::initialize(#{filepile_root})" @root = filepile_root # ensure the root folder exist, or create it unless Dir.exist?(@root) FileUtils.mkdir_p(@root) puts "root created: #{@root}" else puts "root exists: #{@root}" end # ensure each standard sub-dir exist, or create it dir_structure.each do |dir| fullpath = File.join @root, dir[:path] unless Dir.exist? fullpath FileUtils.mkdir_p fullpath puts "sub-dir created: #{fullpath}" else puts "sub-dir exists: #{fullpath}" end end end def filedata File.join @root, 'filedata' end def metadata File.join @root, 'metadata' end def logs File.join @root, 'logs' end def temp File.join @root, 'temp' end end
true
5fa81c0cd40c995f9dc5ebf1035bcbd27f99da36
Ruby
micahstubbs/connections-to-csv
/app/models/user.rb
UTF-8
1,838
2.609375
3
[]
no_license
class User < ActiveRecord::Base attr_accessible :email, :provider, :name, :uid def self.from_omniauth(auth) where(auth.slice("provider", "uid")).first || create_from_omniauth(auth) end def self.create_from_omniauth(auth) create! do |user| user.provider = auth["provider"] user.name = auth["info"]["nickname"] user.email = auth["info"]["email"] user.uid = auth["uid"] user.token = auth["extra"]["access_token"] user.secret = auth["extra"]["access_token"] end end =begin # an attempt to call the LinkedIn API from within rails def self.retrieve_connections() access_token = LinkedInOAuth2::access_token response = access_token.get("http://api.linkedin.com/v1/people/~?format=json") puts response end def self.retrieve_profile # Fill the keys and secrets you retrieved after registering your app api_key = ENV['LINKEDIN_KEY'] api_secret = ENV['LINKEDIN_SECRET'] user_token = ENV['LINKEDIN_OAUTH_USER_TOKEN'] user_secret = ENV['LINKEDIN_OAUTH_USER_SECRET'] # Specify LinkedIn API endpoint configuration = { :site => 'https://api.linkedin.com' } # Use your API key and secret to instantiate consumer object client = OAuth2::Client.new(api_key, api_secret, configuration) # Use your developer token and secret to instantiate access token object access_token = OAuth2::AccessToken.new(client, user_token, user_secret) # Make call to LinkedIn to retrieve your own profile #response = access_token.get("http://api.linkedin.com/v1/people/~") # By default, the LinkedIn API responses are in XML format. If you prefer JSON, simply specify the format in your call response = access_token.get("http://api.linkedin.com/v1/people/~?format=json") puts response end =end end
true
c4f8e47290d9b3a217431d52b1aa7256d097ede9
Ruby
arizansari80/C-Programs
/SPOJ/Simple Airtmatic/mult.rb
UTF-8
878
3.171875
3
[]
no_license
puts "Enter the string"; r=gets; $arr=r.split("*"); a=$arr[0].to_i; b=$arr[1].to_i; c=$arr[1].split(""); r=a*b; r=r.to_s; $dash=""; $dashtemp=""; l0=$arr[0].length; l1=$arr[1].length-1; $lr=r.length; if l0>=l1 i=0; while i<l0 do $dash+="-"; i+=1; end if l0==l1 $dash+="-"; end else i=0; while i<l1 do $dash+="-"; i+=1; end $dash+="-"; end ld=$dash.length; $temp0=""; $temp1=""; i=l0; while i<$lr do $temp0+=" "; i+=1; end i=l1; while i<$lr-1 do $temp1+=" "; i+=1; end ld=$dash.length; i=ld; while i<$lr do $dashtemp+=" "; i+=1; end $temp1+="*"; puts $temp0 + $arr[0]; puts $temp1 + $arr[1]; puts $dashtemp + $dash; i=0; while i<l1 do $temp0=""; t=c[l1-i-1].to_i; k=t*a; k=k.to_s; lk=k.length; j=lk; while j<$lr-i do $temp0+=" "; j+=1; end puts $temp0 + k; i+=1; end $dash=""; i=0; while i<$lr do $dash+="-" i+=1; end puts $dash; puts r;
true
3aad0cad1c9cbc0235ba6dd94ff042196c6ca360
Ruby
akoltun/form_obj
/lib/form_obj/form/array.rb
UTF-8
1,684
2.65625
3
[ "MIT" ]
permissive
module FormObj class Form < FormObj::Struct class Array < FormObj::Struct::Array def persisted? empty? || all?(&:persisted?) end def mark_as_persisted each(&:mark_as_persisted) end def mark_for_destruction each(&:mark_for_destruction) end def marked_for_destruction select(&:marked_for_destruction?) end private # Should return hash with 3 keys: :create, :update, :destroy # In default implementation: # :create - array of hashes of new attribute values # :update - hash where key is the item to update and value is a hash of new attribute values # :destroy - array of items to be destroyed def define_items_for_CUD(items) to_be_created = [] to_be_updated = {} to_be_destroyed = [] items.each do |item_hash| item_hash = HashWithIndifferentAccess.new(item_hash) _destroy = item_hash.delete(:_destroy) item = find_by_primary_key(primary_key(item_hash)) if item if _destroy to_be_destroyed << item else to_be_updated[item] = item_hash end elsif !_destroy to_be_created << item_hash end end { create: to_be_created, update: to_be_updated, destroy: to_be_destroyed } end # Do not do resort since update_attributes parameter may have not full list of items def resort_items_after_CUD!(items) end # items - array of items to be destroyed def destroy_items(items) items.each(&:mark_for_destruction) end end end end
true
27093a7f09a25d7a40a3b54404eb73aa2b140acc
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz38_sols/solutions/Christian Neukirchen/serializableproc.rb
UTF-8
670
2.671875
3
[ "MIT" ]
permissive
require 'delegate' class SerializableProc < DelegateClass(Proc) attr_reader :__code def initialize(code) @__code = code.lstrip super eval("lambda { #@__code }") end def marshal_dump; @__code; end def marshal_load(code); initialize code; end def to_yaml Object.instance_method(:to_yaml).bind(self).call end def to_yaml_properties; ["@__code"]; end def to_yaml_type; "!ruby/serializableproc"; end end # .oO(Is there no easier way to do this?) YAML.add_ruby_type( /^serializableproc/ ) { |type, val| type, obj_class = YAML.read_type_class( type, SerializableProc ) o = YAML.object_maker( obj_class, val ) o.marshal_load o.__code }
true
2a097847a5aa9cc855c4f462d18918917df902ca
Ruby
drhoten/summerofruby2014
/week_01/hello/add_it_up.rb
UTF-8
541
4.25
4
[]
no_license
class AddItUp # Instance method def add1 1+1 2+2 3+3 end # Class method def self.add2 a=1 b=2 c=a+b d=4 c end def add3 a=1 b=2 return a c=a+b end def self.is_even?(a_number) a_number.even? end print "The result of the first verse is #{AddItUp.new.add1}.\n" print "The result of the second verse is #{self.add2}.\n" instance_a = AddItUp.new print "The result of the third verse is #{instance_a.add3}.\n" puts self.is_even?(2) puts self.is_even?(3) end
true
55597c547552a76ac57153189bc2ae305e3a455c
Ruby
brendanthomas1/ruby-blockchain
/blockchain.rb
UTF-8
520
3.03125
3
[]
no_license
class Blockchain def initialize @chain = [Block.new(index: 0)] end def chain @chain.dup end def add_block @chain << Block.new(index: @chain.length, previous_hash: @chain.last.hash) end class Block require 'digest' attr_reader :hash def initialize(index:, previous_hash: nil) @index = index @timestamp = Time.now.utc @hash = calc_hash @previous_hash = previous_hash end private def calc_hash Digest::SHA256.new.to_s end end end
true
2923f921d92b2f2d7761d70f237f3c446c13bba0
Ruby
brianvh/dry-types
/lib/dry/types/definition/hash.rb
UTF-8
1,871
2.546875
3
[ "MIT" ]
permissive
module Dry module Types class Definition class Hash < Definition def self.safe_constructor(types, hash) types.each_with_object({}) do |(key, type), result| if hash.key?(key) result[key] = type[hash[key]] elsif type.is_a?(Default) result[key] = type.evaluate end end end def self.symbolized_constructor(types, hash) types.each_with_object({}) do |(key, type), result| if hash.key?(key) result[key] = type[hash[key]] else key_name = key.to_s if hash.key?(key_name) result[key] = type[hash[key_name]] elsif type.is_a?(Default) result[key] = type.evaluate end end end end def self.strict_constructor(types, hash) types.each_with_object({}) do |(key, type), result| begin value = hash.fetch(key) result[key] = type[value] rescue TypeError raise SchemaError.new(key, value) rescue KeyError raise SchemaKeyError.new(key) end end end def strict(type_map) schema(type_map, :strict_constructor) end def symbolized(type_map) schema(type_map, :symbolized_constructor) end def schema(type_map, meth = :safe_constructor) types = type_map.each_with_object({}) { |(name, type), result| result[name] = case type when String, Class then Types[type] else type end } fn = self.class.method(meth).to_proc.curry.(types) constructor(fn, schema: types) end end end end end
true
80f3d5cd09b946a734a92b0036db6f0c78405e14
Ruby
codyaray/judgeme
/app/helpers/asset_tag_helpers.rb
UTF-8
2,417
2.578125
3
[]
no_license
# Adapted from SinatraMore: https://github.com/nesquena/sinatra_more/ module AssetTagHelpers # Creates a link element with given name, url and options # link_to 'click me', '/dashboard', :class => 'linky' def link_to(name, url = 'javascript:void(0);', options = {}) options = { :href => url }.merge(options) content_tag(:a, name, options) end # Creates an image element with given url and options # image_tag('icons/avatar.png') def image_tag(url, options={}) options = { :src => image_path(url) }.merge(options) tag(:img, options) end # Returns a stylesheet link tag for the sources specified as arguments # stylesheet_link_tag 'style', 'application', 'layout' def stylesheet_link_tag(*sources) opts = sources.last.is_a?(Hash) ? sources.pop : {} sources.collect { |sheet| stylesheet_tag(sheet, opts) }.join("\n") end # javascript_include_tag 'application', 'special' def javascript_include_tag(*sources) options = sources.last.is_a?(Hash) ? sources.pop : {} sources.collect { |script| javascript_tag(script, options) }.join("\n") end # Returns the path to the image, either relative or absolute def image_path(src) src.gsub!(/\s/, '') src =~ %r{^\s*(/|http)} ? src : File.join('/images', src) end protected # stylesheet_tag('style', :media => 'screen') def stylesheet_tag(source, options={}) options = {:href => stylesheet_path(source), :media => 'screen', :rel => 'stylesheet', :type => 'text/css'}.merge(options.dup) tag(:link, options) end # javascript_tag 'application', :src => '/javascripts/base/application.js' def javascript_tag(source, options={}) options = { :src => javascript_path(source), :type => 'text/javascript', :content => "" }.merge(options.dup) tag(:script, options) end def javascript_path(source) return source if source =~ /^http/ result_path = "/javascripts/#{source.gsub(/.js$/, '')}" result_path << ".js" unless source =~ /\.js\w{2,4}$/ stamp = File.exist?(result_path) ? File.mtime(result_path) : Time.now.to_i "#{result_path}?#{stamp}" end def stylesheet_path(source) return source if source =~ /^http/ result_path = "/stylesheets/#{source.gsub(/.css$/, '')}" result_path << ".css" unless source =~ /\.css\w{2,4}$/ stamp = File.exist?(result_path) ? File.mtime(result_path) : Time.now.to_i "#{result_path}?#{stamp}" end end
true
80cbdd6534d6afe14b9903d1f99983ece8446a47
Ruby
Davigl/kattis-solutions
/licensetolaunch/solution.rb
UTF-8
76
3.140625
3
[]
no_license
x = gets.chomp.to_i y = gets.chomp.split.map(&:to_i) puts y.index(y.min)
true
1cf316b34455657e31d87497e89fefe79ac0edf1
Ruby
wtfspm/advent_of_code
/2019/09/compute.rb
UTF-8
366
3.15625
3
[]
no_license
#!/usr/bin/env ruby require_relative './lib/computer' if $0 == __FILE__ memory = ARGF.readlines.map(&:strip).first memory = memory.split(',').map(&:to_i) computer = Computer.new(memory, [1], []) computer.compute! puts "Part 1: #{computer.outputs}" computer = Computer.new(memory, [2], []) computer.compute! puts "Part 2: #{computer.outputs}" end
true
2d2c6977ec8d52117cbe24fed31306e713762ae6
Ruby
Luke-Shepp/Advent-Of-Code-2019
/Day 4/Part 2.rb
UTF-8
274
3.4375
3
[]
no_license
count = 0 147981.upto(691423).each do |num| digits = num.digits consecutive = digits.each_cons(2).all? { |a, b| a >= b } double = digits.chunk(&:itself).any? { |_, chunk| chunk.size == 2 } count += 1 if consecutive && double end puts "Answer: #{count}"
true
db04bc4aad5dc68796501fa80b0fd13470289533
Ruby
fumikony/kondate
/lib/kondate/host_plugin/file.rb
UTF-8
1,139
2.75
3
[ "MIT" ]
permissive
require 'yaml' module Kondate module HostPlugin # YAML format # # host1: [role1, role2] # host2: [role1, role2] class File < Base # @param [HashWithIndifferentAccess] config def initialize(config) super raise ConfigError.new('file: path is not configured') unless config.path @path = config.path @roles_of_host = YAML.load_file(@path) @hosts_of_role = {} @roles_of_host.each do |host, roles| roles.each do |role| @hosts_of_role[role] ||= [] @hosts_of_role[role] << host end end end # @param [String] host hostname # @return [String] environment name def get_environment(host) ENV['ENVIRONMENT'] || 'development' end # @param [String] host hostname # @return [Array] array of roles def get_roles(host) @roles_of_host[host] end # @param [String] role role # @return [Array] array of hosts # # Available from kondate >= 0.3.0 def get_hosts(role) @hosts_of_role[role] end end end end
true
9905669503b28b4a7be9b0551872da20dd7abcb2
Ruby
ColinMcCulloch/battle
/lib/player.rb
UTF-8
170
3.34375
3
[]
no_license
class Player STARTING_HP = 50 attr_reader :name, :hp def initialize(name) @name = name @hp = STARTING_HP end def reduce_hp @hp -= 10 end end
true
e54c96f6806c2a0087c13d76191dd1530f32a87e
Ruby
cha63506/fuzed-old
/gems/erlectricity/test/decode_spec.rb
UTF-8
4,146
3.03125
3
[ "BSD-3-Clause" ]
permissive
require File.dirname(__FILE__) + '/test_helper.rb' context "When unpacking from a binary stream" do specify "an erlang atom should decode to a ruby symbol" do get("haha").should == :haha end specify "an erlang number encoded as a small_int (< 255) should decode to a fixnum" do get("0").should == 0 get("255").should == 255 end specify "an erlang number encoded as a int (signed 27-bit number) should decode to a fixnum" do get("256").should == 256 get("#{(1 << 27) -1}").should == (1 << 27) -1 get("-1").should == -1 get("#{-(1 << 27)}").should == -(1 << 27) end specify "an erlang number encoded as a small bignum (1 byte length) should decode to fixnum if it can" do get("#{1 << 27 - 1}").should == 1 << 27 - 1 get("#{-(1 << 27) - 1}").should == -(1 << 27) - 1 get("#{(1 << word_length) - 1}").should == (1 << word_length) - 1 get("#{-(1 << word_length)}").should == -(1 << word_length) end specify "an erlang number encoded as a small bignum (1 byte length) should decode to bignum if it can't be a fixnum" do get("#{(1 << word_length)}").should == (1 << word_length) get("#{-(1 << word_length) - 1}").should == -(1 << word_length) - 1 get("#{(1 << (255 * 8)) - 1}").should == (1 << (255 * 8)) - 1 get("#{-((1 << (255 * 8)) - 1)}").should == -((1 << (255 * 8)) - 1) end specify "an erlang number encoded as a big bignum (4 byte length) should decode to bignum" do get("#{(1 << (255 * 8)) }").should == (1 << (255 * 8)) get("#{-(1 << (255 * 8))}").should == -(1 << (255 * 8)) get("#{(1 << (512 * 8)) }").should == (1 << (512 * 8)) get("#{-(1 << (512 * 8))}").should == -(1 << (512 * 8)) end specify "an erlang float should decode to a Float" do get("#{1.0}").should == 1.0 get("#{-1.0}").should == -1.0 get("#{123.456}").should == 123.456 get("#{123.456789012345}").should == 123.456789012345 end specify "an erlang reference should decode to a Reference object" do ref = get("make_ref()") ref.should.be.instance_of Erlectricity::NewReference ref.node.should.be.instance_of Symbol end specify "an erlang pid should decode to a Pid object" do pid = get("spawn(fun() -> 3 end)") pid.should.be.instance_of Erlectricity::Pid pid.node.should.be.instance_of Symbol end specify "an erlang tuple encoded as a small tuple (1-byte length) should decode to an array" do ref = get("{3}") ref.length.should == 1 ref.first.should == 3 ref = get("{3, a, make_ref()}") ref.length.should == 3 ref[0].should == 3 ref[1].should == :a ref[2].class.should == Erlectricity::NewReference tuple_meat = (['3'] * 255).join(', ') ref = get("{#{tuple_meat}}") ref.length.should == 255 ref.each{|r| r.should == 3} end specify "an erlang tuple encoded as a large tuple (4-byte length) should decode to an array" do tuple_meat = (['3'] * 256).join(', ') ref = get("{#{tuple_meat}}") ref.length.should == 256 ref.each{|r| r.should == 3} tuple_meat = (['3'] * 512).join(', ') ref = get("{#{tuple_meat}}") ref.length.should == 512 ref.each{|r| r.should == 3} end specify "an empty erlang list encoded as a nil should decode to an array" do get("[]").should == [] end specify "an erlang list encoded as a string should decode to an array of bytes (less than ideal, but consistent)" do get("\"asdasd\"").should == "asdasd".split('').map{|c| c[0]} get("\"#{'a' * 65534}\"").should == [?a] * 65534 end specify "an erlang list encoded as a list should decode to a array" do get("[3,4,256]").should == [3,4,256] get("\"#{'a' * 65535 }\"").should == [97] * 65535 get("[3,4, foo, {3,4,5,bar}, 256]").should == [3,4, :foo, [3,4,5,:bar], 256] end specify "an erlang binary should decode to a string" do get("<< 3,4,255 >>").should == "\003\004\377" get("<< \"whatup\" >>").should == "whatup" end def get(str) bin = run_erl("term_to_binary(#{str})") # p bin Erlectricity::Decoder.read_any_from(bin) end end
true
299ac794f4412225cbff42ed27c7fb76a00d51af
Ruby
aar10n/ImageRepository
/server/app/helpers/json.rb
UTF-8
3,493
3.09375
3
[]
no_license
module Json module Scope ROOT = "root" OBJECT = "object" ARRAY = "array" end class JsonBuilder def initialize(scope: nil, &block) @builders = [] @scope = Scope::ROOT @value = nil init_scope(scope) unless scope.nil? instance_eval(&block) end def build @value end # builder functions # Defines a property of an object # @param key [String, Symbol] # @param value [Any] def property(key, value = nil, &block) key = unwrap(key) value = unwrap(value) assert_scope Scope::OBJECT assert_type key, String, Symbol value = block_given? ? self.class.new(&block).build : value @value[key] = value end # Defines an element of an array # @param value [Any] def element(value = nil, &block) value = unwrap(value) assert_scope Scope::ARRAY value = block_given? ? self.class.new(&block).build : value @value << value end # Merges an object with the current scope. # @param obj [Hash] # @param deep [Boolean] deep merge def merge(obj, deep: false) obj = unwrap(obj) assert_scope Scope::OBJECT assert_type obj, Hash if deep @value.deep_merge obj else @value.merge unwrap(obj) end end # Joins an array to the current scope. # @param arr [Array] # @param unique [Boolean] unique join def concat(arr, unique: false) arr = unwrap(arr) assert_scope Scope::ARRAY assert_type arr, Array if unique @value |= arr else @value + arr end end # scopes # creates a new object def object(&block) return {} unless block_given? self.class.new(scope: Scope::OBJECT, &block).build end # creates a new array def array(&block) return [] unless block_given? self.class.new(scope: Scope::ARRAY, &block).build end private def assert_scope(scope) init_scope(scope) if @scope == Scope::ROOT return if scope == @scope Rails.logger.error "Expected scope to be '#{scope}' but got '#{@scope}'" raise JSON::ParserError end def assert_type(arg, *types) types = types.flatten return if types.empty? return if types.map { |t| arg.is_a? t }.any? msg = if types.length == 1 "Expected argument of type #{types[0]} but got #{arg.class}" else "Expected argument of type #{types} but got #{arg.class}" end Rails.logger.error msg raise ArgumentError end def init_scope(scope) raise ArgumentError unless scope.in? [Scope::OBJECT, Scope::ARRAY] @scope = scope @value = scope == Scope::OBJECT ? {} : [] end def unwrap(value) return value.call if value.is_a? Proc value end end # Creates a new json-like object from the given block. # This will either return a hash or an array. # @param root [String, Symbol, Array<String, Symbol>] # Wrap the result in the given root key(s). # @return [Hash, Array] def self.json(root: nil, &block) return wrap_result(root, nil) unless block_given? result = JsonBuilder.new(&block).build wrap_result(root, result) end def self.wrap_result(root, obj) return obj if root.nil? return [obj] if root.is_a? Array and root.empty? root = [root] unless root.is_a? Array root.reverse.inject(obj) { |a, n| { n => a } } end end
true
090d5a8ef5579660c25f71a697688a475343aa8f
Ruby
jentle/pumaServer
/app/models/dcapi.rb
UTF-8
1,374
2.609375
3
[]
no_license
require 'net/http' require 'uri' module DCAPI SCI_URI = "http://login.etherios.com/ws/sci" def self.send_data(api_url, data) url = URI.parse(api_url) headers = { 'Accept' => 'application/xml' } # Create a HTTPRequest Object based on HTTP Method. req = Net::HTTP::Post.new(url.path, headers) # Sets The Request up for Basic Authentication. # Replace YourUsername and YourPassword with your username and password respectively. req.basic_auth 'jentlelong', 'Gujiang2010+' # Injects XML Content into Request Body. req.body='<!-- See http://www.digi.com/wiki/developer/index.php/Rci for an example of a python implementation on a NDS device to handle this SCI request --> <sci_request version="1.0"> <send_message> <targets> <device id="00000000-00000000-1C4BD6FF-FFCFF8DA"/> </targets> <rci_request version="1.1"> <do_command target="xig"> <at hw_address="00:13:A2:00:40:B1:C1:79" command="AP"/> </do_command> </rci_request> </send_message> </sci_request> ' # Informs Server that the input is in XML format. req.set_content_type('text/xml') # Create an HTTP connection and send data to capture response. res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) } # Print the Response! puts res.body end def get_data(api_url) end end
true
a45717b9079db2fabfed8fa7ede86ed7837f3d36
Ruby
bendee48/blogger
/app/models/article.rb
UTF-8
389
2.578125
3
[]
no_license
class Article < ApplicationRecord has_many :comments has_many :taggings has_many :tags, through: :taggings def tag_list tags.join(', ') end def tag_list=(tag_string) tag_names = tag_string.split(",").collect { |tag| tag.strip.downcase }.uniq new_or_found_tags = tag_names.map { |tag| Tag.find_or_create_by(name: tag)} self.tags = new_or_found_tags end end
true
0a84abcf78bb78aabb2a106382f694f36b0b7326
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/robot-name/d760d513d88644bf85b2534e209e779b.rb
UTF-8
297
3.0625
3
[]
no_license
class Robot def name @name ||= random_letter + random_letter + random_three_digit_number end def reset @name = nil end private def random_letter ('A'..'Z').to_a.sample end def random_three_digit_number (0..9).to_a.sample(3).join end end
true
0030b9b76c852e7931cfb7119f5921bff1a11764
Ruby
xjvcm/bank_account
/JonathanManzano/bank_account.rb
UTF-8
2,077
3.453125
3
[]
no_license
class BankAccount attr_writer :accNum, :name attr_accessor :chkBal, :savBal, :total @@count = 0 private def initialize (name) @name = name @chkBal = 0 @savBal = 0 @accNum = bankNumGen @@count +=1 end def interest @interest_rate = rand(0.1..10.9).to_f end def bankNumGen rand(9999999999999999999999) end public def checkBal puts "Current Checking Balance: $"[email protected]_s self end def saveBal puts "Current Saving Balance: $"[email protected]_s self end def depositCheck(x) @chkBal +=x self end def depositSave(x) @savBal +=x self end def withdrawChk(x) if @chkBal > x @chkBal -=x else puts "\n\n!~YOU DO NOT HAVE ENOUGH IN YOUR #{@name.upcase} CHECKING ACCOUNT~!" end self end def withdrawSav(x) if @savBal > x @savBal -=x else puts "\n\n!~YOU DO NOT HAVE ENOUGH TO WITHDRAW IN YOUR #{@name.upcase} SAVING ACCOUNT~!" end self end # def total # puts @total = @checkBal + @savBal # self # end def account_information @total = @chkBal + @savBal puts "\n\n________"[email protected]+"________" checkBal saveBal puts "Interest Rate: " + interest.to_s + "%" puts "Account Number: "[email protected]_s puts "Total Balance: " + "$"+ @total.to_s puts "You currently have #{@@count} with us today!\n\n" self end end Chase = BankAccount.new("Chase") Wells_Fargo = BankAccount.new("Wells Fargo") Bank_of_America = BankAccount.new("Bank of America") Citigroup = BankAccount.new("Citigroup") Capital_One = BankAccount.new("Capital One") Chase.depositCheck(500).withdrawChk(600).account_information Wells_Fargo.depositCheck(3000).depositSave(50000).withdrawChk(399).account_information Bank_of_America.depositCheck(4).withdrawChk(5).account_information Citigroup.depositCheck(45).depositCheck(700).account_information Capital_One.depositCheck(777).withdrawChk(69).depositSave(131313131313).withdrawSav(171717171717171717).account_information # Chase.account_information
true
b37c60e7aaf454238df4d062928d254ebab7a9d5
Ruby
whatalnk/cpsubmissions
/atcoder/ruby/arc008/arc008_2/1079935.rb
UTF-8
618
3.265625
3
[]
no_license
# Contest ID: arc008 # Problem ID: arc008_2 ( https://atcoder.jp/contests/arc008/tasks/arc008_2 ) # Title: B. 謎のたこ焼きおじさん # Language: Ruby (1.9.3) # Submitted: 2017-01-27 09:13:59 +0000 UTC ( https://atcoder.jp/contests/arc008/submissions/1079935 ) n, m = gets.chomp.split.map(&:to_i) names = Hash.new(0) gets.chomp.split("").each do |k| names[k] += 1 end kit = Hash.new(0) gets.chomp.split("").each do |k| kit[k] += 1 end nkit = 0 names.keys.each do |key| if kit.has_key?(key) then nkit = [nkit, (names[key].to_f / kit[key])].max else puts -1 exit end end puts nkit.ceil
true
e6974d13b1abbed128b47916e28eaffc49892496
Ruby
BCerki/math_game
/math_game_planning.rb
UTF-8
353
3.53125
4
[]
no_license
# player--prompts # number--parts of the question asked # lives--each player gets three # turn--who's getting asked the question # winner--who's still alive # goodbye--game over class Player def initialize @lives = 3 @current_player = false end end class Question def initialize @number1 @number2 end def write_question end end
true
ef78a7c8e79c77235cfc36c0120e3d5ab0be1296
Ruby
cruzjorge/tutorialruby
/sobreescritura.rb
UTF-8
85
2.625
3
[]
no_license
require_relative 'clsPerro.rb' dog = Perro.new('Fido', 'Chiahuahua') puts dog.ruido
true
66c7a90524955d0c610e3c3c9982ad8e59b6b8bd
Ruby
ahuhn14/burner
/lib/burner/util/string_template.rb
UTF-8
1,332
2.875
3
[ "MIT" ]
permissive
# frozen_string_literal: true # # Copyright (c) 2020-present, Blue Marble Payroll, LLC # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # module Burner module Util # Can take in a string and an object and use the object for formatting string interpolations # using tokens of form: {attribute_name}. This templating class does not understand nested # structures, so input should be a flat object/hash in the form of key-value pairs. # A benefit of using Objectable for resolution is that it can understand almost any type of # object: Hash, Struct, OpenStruct, custom objects, etc. # For more information see underlying libraries: # * Stringento: https://github.com/bluemarblepayroll/stringento # * Objectable: https://github.com/bluemarblepayroll/objectable class StringTemplate include Singleton attr_reader :resolver def initialize @resolver = Objectable.resolver(separator: '') freeze end # For general consumption def evaluate(expression, input) Stringento.evaluate(expression, input, resolver: self) end # For Stringento consumption def resolve(value, input) resolver.get(input, value) end end end end
true
24742fac57b46f9a71c45efc366fab2ce368bbc6
Ruby
londondata/Ruby-Fundamentals
/Sorting Algorithms/insertion_sort.rb
UTF-8
297
3.34375
3
[ "MIT" ]
permissive
class Array def insertion_sort (1...size).each do |n| value_to_insert = delete_at(n) insertion_index = n insertion_index -= 1 while insertion_index > 0 && self[insertion_index - 1] > value_to_insert insert(insertion_index, value_to_insert) end self end end
true
233947e3defc01e70c125d8796a8d9d060c5ccc4
Ruby
akr/htree
/test/test-traverse.rb
UTF-8
1,744
2.59375
3
[ "Ruby" ]
permissive
require 'test/unit' require 'htree/traverse' require 'htree/parse' require 'htree/equality' class TestTraverse < Test::Unit::TestCase def test_filter l = HTree.parse('<a><b>x</b><b/><a/>').make_loc l2 = l.filter {|n| n.path != 'doc()/a/b[1]' } assert_equal(HTree.parse('<a><b/><a/>'), l2) end def test_title inputs = [ HTree.parse('<html><title>aaa</title></html>'), HTree.parse(<<'End') <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://purl.org/rss/1.0/"> <channel> <title>aaa</title> </channel> </rdf:RDF> End ] result = HTree::Text.new('aaa') inputs.each {|input| assert_equal(result, input.title) } inputs.each {|input| assert_equal(result, input.make_loc.title) } end def test_author inputs = [ HTree.parse('<html><meta name=author content=xxx></html>'), HTree.parse('<html><link rev=made title=xxx></html>'), HTree.parse(<<'End'), <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://purl.org/rss/1.0/"> <channel> <dc:creator>xxx</dc:creator> </channel> </rdf:RDF> End HTree.parse(<<'End') <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns="http://purl.org/rss/1.0/"> <channel> <dc:publisher>xxx</dc:publisher> </channel> </rdf:RDF> End ] result = HTree::Text.new('xxx') inputs.each {|input| #assert_equal(result, input.author) } inputs.each {|input| assert_equal(result, input.make_loc.author) } end end
true
569ad3d525718a8ea72d37e7f6a775e782dfadc0
Ruby
maalston/myrubyprograms
/3_week/1e_ten_for_fifty.rb
UTF-8
260
3.28125
3
[]
no_license
# 1e_ten_for_fifty.rb # # Exercise1. Why is the output of this program: # def method a = 50 puts a end # a = 10 method puts a # # The scope of variable "a" inside the method is private and different from the # variable "a" outside the method definition.
true
3ad7268b4368b907d6efa1956a46bc72f40eeb42
Ruby
deependersingla/ruby_script
/thread.rb
UTF-8
1,051
3.421875
3
[]
no_license
require 'open-uri' #for open require 'benchmark' def conRead(urls) #urls is an array of string #containing website urls thread_list = [] #keep track of our threads urls.each do |f| thread_list << Thread.new { #add a new thread to #download each site open(f) do |x| x.read end puts "read: " + f #show what we’ve done } end thread_list.each {|x| x.join} #wait for each thread #to complete end urls = [] #set up an array of urls urls << "http://google.com" urls << "http://slashdot.com" urls << "http://dreamincode.net" urls << "http://xkcd.com" urls << "http://engadget.com" urls << "http://lifehacker.com" #conRead(urls) #read them concurrently def seqRead(urls) urls.each do |f| open(f) do |x| x.read end puts "read: " + f end end #seqRead(urls) Benchmark.bm do |x| #urls is the same array of site names used before #run concurrent read method x.report("Thr:") { conRead(urls) } #run sequential read method x.report("Seq:") { seqRead(urls) } end
true
c284846cb97051f1e2e7a58c2a7ca8a2592574e9
Ruby
mloberg/ReMQ.rb
/lib/ReMQ/Worker.rb
UTF-8
2,012
2.953125
3
[ "MIT" ]
permissive
module ReMQ class Worker # Create a new ReMQ worker. # # @param [String] name Optional name of the queue def initialize(name = nil) @queues = [] add_queue(name) if name end # Return the list of quques that this worker will run. # # @return [Array] Array of queues def queues @queues.map { |name| name.gsub(/^remq\:/, '') } end # Add a queue to the worker. # # @param [String] name Queue name def add_queue(name) queues = find_queues(name) queues << ReMQ.normalize_queue_name(name) @queues = @queues.concat(queues).uniq end # Remove a queue from the worker. # # @param [String] name Queue name def remove_queue(name) @queues.delete(ReMQ.normalize_queue_name(name)) end # Run the worker # # @param [Integer] time Seconds to run the worker for # @param [Integer] count Number of jobs to run def run(args = {}) if args[:time] start = Time.now while (start + args[:time]) > Time.now do process(1) end elsif args[:count] args[:count].times do process(0) end else loop do process(0) end end end private # Find queues in Redis # # @param [String] match def find_queues(match) match = ReMQ.normalize_queue_name(match) ReMQ.redis.keys(match) end # Handle the job processing # # @param [Integer] timeout Redis BLPOP timeout def process(timeout) queues = @queues << timeout begin queue, job = ReMQ.redis.blpop(*queues) if job body = JSON.parse(job) job_class = body.shift if ReMQ.is_valid_job?(job_class) Object.const_get(job_class).perform(*body) end end rescue Exception => e ReMQ.redis.rpush(queue, job) raise e end end end end
true
01cd311494f1316dcee2eba0d37a827f3883538c
Ruby
martindemello/QBBS
/db/db_bulletins.rb
UTF-8
1,853
2.96875
3
[]
no_license
def b_total res = @db.exec("SELECT COUNT(*) FROM bulletins") result = single_result(res).to_i return result end def create_bulletin_table puts "-DB: Creating Bulletins Table" @db.exec("CREATE TABLE bulletins (name varchar(40), \ locked boolean DEFAULT false, number int, \ modify_date timestamp, b_path varchar(40),\ id serial PRIMARY KEY)") end def delete_bulletin(ind) @db.exec("DELETE FROM bulletins WHERE number = '#{ind}'") end def update_bulletin(r) r.name.gsub!("'",QUOTE) if r.name != nil r.path.gsub!("'",QUOTE) if r.path != nil @db.exec("UPDATE bulletins SET name = '#{r.name}', \ locked = #{r.locked}, modify_date = '#{r.modify_date}', \ b_path = '#{r.path}' WHERE number = #{r.number}") end def fetch_bulletin(record) res = @db.exec("SELECT * FROM bulletins WHERE number = #{record}") temp = result_as_array(res).flatten t_name = temp[0] t_locked = db_true(temp[1]) t_number = temp[2].to_i t_modify_date = temp[3] t_path = temp[4] t_name.gsub!(QUOTE,"'") if t_name != nil t_path.gsub!(QUOTE,"'") if t_path != nil result = DB_bulletin.new( t_name,t_locked,t_number, \ t_modify_date,t_path) return result end def renumber_bulletins if b_total > 0 then hash = hash_table("bulletins") for i in 0..hash.length - 1 puts("UPDATE bulletins SET number = #{i+1} WHERE id = #{hash[i]}") @db.exec("UPDATE bulletins SET number = #{i+1} WHERE id = #{hash[i]}") end end end def add_bulletin(name, path) name.gsub!("'",QUOTE) path.gsub!("'",QUOTE) number = b_total + 1 msg_date = Time.now.strftime("%m/%d/%Y %I:%M%p") @db.exec("INSERT INTO bulletins (name, number, modify_date, b_path) \ VALUES ('#{name}', #{number},'#{msg_date}', '#{path}')") end
true
eefac4f6c2b347ba8db01b724c7b79f31e6058a9
Ruby
ongaeshi/milkode
/lib/milkode/cdweb/lib/package_list.rb
UTF-8
3,032
2.515625
3
[ "MIT", "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- # # @file # @brief パッケージ一覧 # @author ongaeshi # @date 2012/05/25 require 'milkode/cdweb/lib/database' module Milkode class PackageList VIEW_NUM = 7 ADD_NUM = 5 UPDATE_NUM = 5 FAV_NUM = 7 FAVORITE_LIST_NUM = 7 NEWS_ITEM_NUM = 20 EXCLUDE_UPDATE_SEC = 300 def initialize(grndb, suburl) @grndb = grndb @suburl = suburl end # topページへの表示数の調整は結構大切 # view .. 7 # add .. 5 # update .. 5 # fav .. 5 # def top_view grndb_list("viewtime", VIEW_NUM) end def top_add grndb_list("addtime", ADD_NUM) end def top_update grndb_list("updatetime", UPDATE_NUM) end def top_fav a = @grndb.packages.favs.map{|r| r.name} top_list(a[0...FAV_NUM], 'favtime') end def favorite_list_size @grndb.packages.favs.size end def favorite_list(params) names = @grndb.packages.favs.map{|r| r.name}[0..FAVORITE_LIST_NUM-1] list = names.map_with_index {|v, index| "<strong><a id='favorite_list_#{index}' href='#{Mkurl.new(@suburl + '/home/' + v, params).inherit_query_shead}' onclick='topic_path(\"favorite_list_#{index}\");'>#{v}</a></strong>" }.join("&nbsp;&nbsp;\n") <<EOF #{list}&nbsp;&nbsp; <a href="#{@suburl}/home?sort=favtime">...</a> EOF end def news_items(locale) updates = @grndb.packages.sort('updatetime')[0...NEWS_ITEM_NUM].map do |v| { kind: :update_news, package: v, timestamp: v.updatetime, } end adds = @grndb.packages.sort('addtime')[0...NEWS_ITEM_NUM].map do |v| { kind: :add_news, package: v, timestamp: v.addtime, } end items = (updates + adds).sort_by {|item| item[:timestamp] }.reverse .find_all {|v| if v[:kind] == :update_news && v[:timestamp] - v[:package].addtime < EXCLUDE_UPDATE_SEC false else true end }[0...NEWS_ITEM_NUM] items.map {|item| v = item[:package] message = I18n.t(item[:kind], {package_name: "<a href=\"#{@suburl}/home/#{v.name}\">#{v.name}</a>", locale: locale}) "<div class='news-item'>#{message} <span class='time'>#{news_time(item[:timestamp])}</span></div>" }.join("\n") end # ------------------------------------------------------ private def grndb_list(column_name, num) a = @grndb.packages.sort(column_name).map {|r| r.name} top_list(a[0...num], column_name) end def top_list(list, column_name) list = list.map {|v| " <li><a href=\"#{@suburl}/home/#{v}\">#{v}</a></li>" }.join("\n") <<EOF <ul class="unstyled_margin"> #{list} <li><a href=\"#{@suburl}/home?sort=#{column_name}">next >></a></li> </ul> EOF end def news_time(timestamp) timestamp.strftime("%Y-%m-%d %R") end end end
true
005c71cf6956dd09c592bdce1902e648c0649ecd
Ruby
sonata/mongoid
/lib/mongoid/associations/has_one.rb
UTF-8
2,742
2.53125
3
[ "MIT" ]
permissive
# encoding: utf-8 module Mongoid #:nodoc: module Associations #:nodoc: class HasOne #:nodoc: include Proxy # Build a new object for the association. def build(attrs = {}, type = nil) @target = attrs.assimilate(@parent, @options, type); self end # Creates the new association by finding the attributes in # the parent document with its name, and instantiating a # new document for it. # # All method calls on this object will then be delegated # to the internal document itself. # # Options: # # document: The parent +Document+ # attributes: The attributes of the target object. # options: The association options. # # Returns: # # A new +HashOne+ association proxy. def initialize(document, attrs, options) @parent, @options = document, options @target = attrs.assimilate(@parent, @options, attrs.klass) extends(options) end # Used for setting the association via a nested attributes setter on the # parent +Document+. Called when using accepts_nested_attributes_for. # # Options: # # attributes: The attributes for the new association # # Returns: # # A new target document. def nested_build(attributes) build(attributes) end class << self # Preferred method of instantiating a new +HasOne+, since nil values # will be handled properly. # # Options: # # document: The parent +Document+ # options: The association options. # # Returns: # # A new +HasOne+ association proxy. def instantiate(document, options) attributes = document.raw_attributes[options.name] return nil if attributes.blank? new(document, attributes, options) end # Returns the macro used to create the association. def macro :has_one end # Perform an update of the relationship of the parent and child. This # will assimilate the child +Document+ into the parent's object graph. # # Options: # # child: The child +Document+ or +Hash+. # parent: The parent +Document+ to update. # options: The association +Options+ # # Example: # # <tt>HasOne.update({:first_name => "Hank"}, person, options)</tt> # # Returns: # # A new +HasOne+ association proxy. def update(child, parent, options) child.assimilate(parent, options) instantiate(parent, options) end end end end end
true
6fc903903424d73b533230078262e0f1f06cd867
Ruby
benmicol/trading-web
/trading-web/lib/scrapping/base_scrapping_parser.rb
UTF-8
1,847
2.953125
3
[ "Apache-2.0" ]
permissive
require File.dirname(__FILE__) + '/../log_util' module BaseScrappingParser EMPTY = '' EMPTY_SPACE = ' ' NA = 'n.a.' def self.logger= log @@logger =log end attr_reader :soup, :failed def initialize body if body.kind_of? BeautifulSoup @soup = body else @soup = BeautifulSoup.new body end @failed = false @@logger ||= Logger.logger_for_scrap_parser end protected def extract_rows @@logger.debug 'start extracting rows...' rows = @soup.find_all 'tr' rows ||= [] if rows.empty? @@logger.warn 'NO rows for extraction!' return rows end @row_size = rows.size @@logger.debug "Rows to be extracted: #{@row_size}" rows end def row_size @row_size||=0 (@row_size - 1)/2 end def clean_html_tags tag value = tag.to_s.gsub(/<.*?>/,EMPTY ) value.gsub!(/(\&nbsp;)|(\%nbsp)/, EMPTY_SPACE) value.strip! value end def validates_numericality_of value return nil unless value =~ /^[+-]?\d+$/ value end def persist obj saved = obj.save if not saved fail error = obj.errors.inject(" "){|result, e| result + " " + e.to_s} error = error.nil? ? error : error.to_s @@logger.error "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SAVE ERROR <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " @@logger.error "Can't save #{obj.class} with id=#{obj.id.nil? ? 'nil' : obj.id} | " << error end end def fail @failed = true end def log_exception row_number=nil begin yield rescue Exception => e fail @@logger.error "\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ERROR <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " @@logger.error e @@logger.error 'for row: ' + row_number.to_s if row_number end end def reset_soup @soup = nil; end end
true
5d27b35b518e3019cf3ddb99bb1f449cb61862fc
Ruby
nettan20/vanity
/lib/vanity/store/mock.rb
UTF-8
1,406
2.671875
3
[ "MIT", "CC-BY-4.0" ]
permissive
module Vanity module Store # @since 1.3.0 class Mock @@hash = {} def initialize(options = {}) end def get(key) @@hash[key] end alias :[] :get def set(key, value) @@hash[key] = value.to_s end alias :[]= :set def del(*keys) keys.flatten.each do |key| @@hash.delete key end end def setnx(key, value) @@hash[key] = value.to_s unless @@hash.has_key?(key) end def incr(key) @@hash[key] = (@@hash[key].to_i + 1).to_s end def incrby(key, value) @@hash[key] = (@@hash[key].to_i + value).to_s end def mget(keys) @@hash.values_at(*keys) end def exists(key) @@hash.has_key?(key) end def keys(pattern) regexp = Regexp.new(pattern.split("*").map { |r| Regexp.escape(r) }.join(".*")) @@hash.keys.select { |key| key =~ regexp } end def flushdb @@hash.clear end def sismember(key, value) y = get(key) y ? YAML.load(y).member?(value.to_s) : false end def sadd(key, value) y = get(key) s = Set.new(y ? YAML.load(y) : []) s.add value.to_s set key, YAML.dump(s.to_a) end def scard(key) y = get(key) y ? YAML.load(y).size : 0 end end end end
true
b49555a108d030a68a2cd8150177e13cb38ba9f7
Ruby
tidydee/lhl_web_intructor
/phone_num_exercise/phone.rb
UTF-8
2,194
3.703125
4
[]
no_license
@data = { 'A' => '2', 'B' => '2', 'C' => '2', 'D' => '3', 'E' => '3', 'F' => '3', 'G' => '4', 'H' => '4', 'I' => '4', 'J' => '5', 'K' => '5', 'L' => '5', 'M' => '6', 'N' => '6', 'O' => '6', 'P' => '7', 'Q' => '7', 'R' => '7', 'S' => '7', 'T' => '8', 'U' => '8', 'V' => '8', 'W' => '9', 'X' => '9', 'Y' => '9', 'Z' => '9' } puts @data puts "Enter your word: " ten_char_str = gets.chomp puts "You entered: " + ten_char_str def phone_num_gen(ten_char_str) # => ["1", "2", "3", "4"] str_arr = ten_char_str.split("") puts str_arr phone_num = [] # print "phone_num = " + phone_num.to_s str_arr.each do |i| # print str_arr[i] if i == "A" || "B" || "C" phone_num.push(2) elsif i == "D" || "E" || "F" phone_num.push(3) elsif i == "G" || "H" || "I" phone_num.push(4) elsif i == "J" || "K" || "L" phone_num.push(5) elsif i == "M" || "N" || "O" phone_num.push(6) elsif i == "P" || "Q" || "R" || "S" phone_num.push(7) elsif i == "T" || "U" || "V" phone_num.push(8) elsif i == "W" || "X" || "Y" || "Z" phone_num.push(9) else puts "Invalid Input - Err 61!" end # case str_arr # when i == ("A".."C") # phone_num.push(2) # # when str_arr[i] == @data[:3[:d]] || @data[:3[:e]] || @data[:3[:f]] # # phone_num.push(3) # # when str_arr[i] == @data[:4[:g]] || @data[:4[:h]] || @data[:4[:i]] # # phone_num.push(4) # # when str_arr[i] == @data[:5[:j]] || @data[:5[:k]] || @data[:5[:l]] # # phone_num.push(5) # # when str_arr[i] == @data[:6[:m]] || @data[:6[:n]] || @data[:6[:o]] # # phone_num.push(6) # # when str_arr[i] == @data[:7[:p]] || @data[:7[:q]] || @data[:7[:r]] || @data[:7[:s]] # # phone_num.push(7) # # when str_arr[i] == @data[:8[:t]] || @data[:8[:u]] || @data[:8[:v]] # # phone_num.push(8) # # when str_arr[i] == @data[:9[:w]] || @data[:9[:x]] || @data[:9[:y]] || @data[:9[:z]] # # phone_num.push(9) # else # puts "Invalid Input - Err 61!" # end end puts "Your phone number is: #{phone_num}" end phone_num_gen(ten_char_str) # puts phone_num_gen.new(ten_char_str)
true
4fe32558b52e8d823bd65dbf3cbaf191bb47f572
Ruby
gjdame/learning_ruby
/webserver/server3.rb
UTF-8
1,124
3.140625
3
[]
no_license
require 'socket' routes = { "/" => "Hi, thanks for sitting through this guys. I know its the highlight of your week. \n Other available routes are about and pun", "/about" => "My middle name is James. I have one sister. I like cheese.", "/pun" => "6:30 is the best time on a clock. Hands down!" } PAGE_ERROR = "Sorry, come back later. I probably still won't have anything here" server = TCPServer.new 7777 loop do session = server.accept request = session.gets puts request #parse path to get method (GET, POST, etc) and path method, full_path = request.split(' ') #get query path, query = full_path.split('?') if routes.keys.include? path status = "200 OK" response_body = routes[path] else status = "404 Not Found" response_body = PAGE_ERROR end session.print "HTTP/1.1 #{status}\r\n" #headers.each do |key, value| # session.print "#{key}: #{value}\r\n" #end session.print "\r\n" session.print response_body session.close end
true
9fe163dc0975a2bdd7fd992d47866700179cbf67
Ruby
yahor/qoolife-api
/lib/qoolife-api/paginated_collection.rb
UTF-8
802
2.59375
3
[ "MIT" ]
permissive
module QoolifeApi class PaginatedCollection < ActiveResource::Collection attr_accessor :first_page, :prev_page, :next_page, :last_page def initialize(elements = []) @elements = elements response = QoolifeApi::Base.connection.http_response response = pagination_header_response_to_hash response['Link'] @first_page = response[:first] @prev_page = response[:prev] @next_page = response[:next] @last_page = response[:last] end private def pagination_header_response_to_hash(response) response.to_s.split(',').each_with_object({}) do |item, h| items = item.split(';') key = items.last.gsub('rel=', '').gsub("\"", '').to_sym value = items.first h[key] = value end end end end
true
357fadd7156a96b89e26c370a4846ba77c634f83
Ruby
TheGuth/launch_school
/launch_school_review/ruby_oop_book/inheritance_exercises.rb
UTF-8
4,898
4.3125
4
[]
no_license
# Exercise 1. # Create a superclass called Vehicle for your MyCar class to inherit from and move the # behavior that isn't specific to the MyCar class to the superclass. Create a constant # in your MyCar class that stores information about the vehicle that makes it different # from other types of Vehicles. # Then create a new class called MyTruck that inherits from your superclass that also # has a constant defined that separates it from the MyCar class in some way. class Vehicle def self.gas_mileage(gallons, miles) puts "#{miles / gallons} miles per gallon of gas" end end class My_Car > Vehicle NUMBER_OF_DOORS = 4 TOWABLE = false end class My_Truck > Vehicle NUMBER_OF_DOORS = 2 TOWABLE = true end # Exercise 2. # Add a class variable to your superclass that can keep track of the number of # objects created that inherit from the superclass. Create a method to print out # the value of this class variable as well. class Vehicle @@number_of_vehicles = 0 def iniitialize @@number_of_vehicles += 1 end def self.gas_mileage(gallons, miles) puts "#{miles / gallons} miles per gallon of gas" end end class My_Car > Vehicle NUMBER_OF_DOORS = 4 TOWABLE = false end class My_Truck > Vehicle NUMBER_OF_DOORS = 2 TOWABLE = true end # Exercise 3. # Create a module that you can mix in to ONE of your subclasses that describes a # behavior unique to that subclass. module Towable def can_tow?(pounds) pounds < 2000 ? true : false end end # Exercise 4. # Print to the screen your method lookup for the classes that you have created. puts My_Car.ancestors puts My_Truck.ancestors puts Vehicle.ancestors # Exercise 5. # Move all of the methods from the MyCar class that also pertain to the MyTruck class # into the Vehicle class. Make sure that all of your previous method calls are # working when you are finished. module Towable def can_tow?(pounds) pounds < 2000 ? true : false end end class Vehicle attr_accessor :color attr_reader :model, :year @@number_of_vehicles = 0 def initialize(year, model, color) @year = year @model = model @color = color @current_speed = 0 @@number_of_vehicles += 1 end def speed_up(number) @current_speed += number puts "You push the gas and accelerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake and decelerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down puts "Let's park this bad boy!" end def self.gas_mileage(gallons, miles) puts "#{miles / gallons} miles per gallon of gas" end def spray_paint(color) self.color = color puts "You new #{color} paint job looks great!" end end class MyTruck < Vehicle include Towable NUMBER_OF_DOORS = 2 def to_s "My truck is a #{self.color}, #{self.year}, #{self.model}!" end end class MyCar < Vehicle NUMBER_OF_DOORS = 4 def to_s "My car is a #{self.color}, #{self.year}, #{self.model}!" end end lumina = MyCar.new(1997, 'chevy lumina', 'white') lumina.speed_up(20) lumina.current_speed lumina.speed_up(20) lumina.current_speed lumina.brake(20) lumina.current_speed lumina.brake(20) lumina.current_speed lumina.shut_down MyCar.gas_mileage(13, 351) lumina.spray_paint("red") puts lumina puts MyCar.ancestors puts MyTruck.ancestors puts Vehicle.ancestors # Exericse 6. # Write a method called age that calls a private method to calculate the age of the # vehicle. Make sure the private method is not available from outside of the class. # You'll need to use Ruby's built-in Time class to help. class Vehicle # code omitted for brevity... def age "Your #{self.model} is #{years_old} years old." end private def years_old Time.now.year - self.year end end # code omitted for brevity... puts lumina.age #=> "Your chevy lumina is 17 years old" # Exercise 7. # Create a class 'Student' with attributes name and grade. Do NOT make the grade # getter public, so joe.grade will raise an error. Create a better_grade_than? # method, that you can call like so... class Student def initialize(name, grade) @name = name @grade = grade end def better_grade_than?(other_student) grade > other_student.grade end protected def grade @grade end end joe = Student.new("Joe", 90) bob = Student.new("Bob", 84) puts "Well done!" if joe.better_grade_than?(bob) # Exercise 8. # Given the following code... bob = Person.new bob.hi # And the corresponding error message... # NoMethodError: private method `hi' called for #<Person:0x007ff61dbb79f0> # from (irb):8 # from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>' # What is the problem and how would you go about fixing it? # the method hi is private which means we don't have access to it.
true
9674a48841987d2a544c6734e2bd28dce8b41ff2
Ruby
CodingSoeren/client-ruby
/spec/support/game_state_helpers.rb
UTF-8
1,483
2.828125
3
[]
no_license
# frozen_string_literal: true require_relative '../../lib/software_challenge_client/util/constants' require_relative '../../lib/software_challenge_client/color' module GameStateHelpers include Constants class BoardFormatError < StandardError end def field_from_descriptor(coordinates, descriptor) piece = nil if descriptor != '__' and descriptor != '_' unless Color.to_a.map(&:value).include? descriptor[0] raise BoardFormatError.new("unknown color descriptor #{descriptor[0]}") end color = Color.find_by_value(descriptor[0]) unless PieceType.to_a.map(&:value).include? descriptor[1] raise BoardFormatError.new("unknown piecetype descriptor #{descriptor[1]}") end type = PieceType.find_by_value(descriptor[1]) piece = Piece.new(color, type, coordinates) end Field.new(coordinates.x, coordinates.y, piece) end # NOTE that this currently does not update undeployed pieces! def state_from_string!(string, gamestate) fields = Board.new.field_list field_descriptors = string.split(' ') board_fields = [] fields.each do |field| board_fields << field_from_descriptor(field.coordinates, field_descriptors[field.y * BOARD_SIZE + field.x]) end gamestate.turn = 4 gamestate.round = 2 gamestate.add_player(Player.new(Color::RED, "ONE", 0)) gamestate.add_player(Player.new(Color::BLUE, "TWO", 0)) gamestate.board = Board.new(board_fields) end end
true
5693a11f5bc470f0574df083eda1a047efe85ee5
Ruby
Rae-Kwon/bubble-sort
/bubblesort.rb
UTF-8
355
3.609375
4
[ "MIT" ]
permissive
def bubble_sort (array) length = array.length (0..length - 2).each do |index| (0..length - index - 2).each do |curr| if array[curr] > array[curr + 1] array[curr + 1], array[curr] = array[curr], array[curr + 1] end end end p array end array = [4, 3, 78, 2, 0, 2] bubble_sort(array)
true
cca7904551a1f7261e80d83ec50b0c12895d0720
Ruby
dkotvan/challenge
/backend/models/product.rb
UTF-8
850
3.015625
3
[]
no_license
class Product # use type to distinguish each kind of product: physical, book, digital, membership, etc. attr_reader :name, :type def initialize(name:, type:) @name, @type = name, type end def shippable? false end end class PhysicalProduct < Product def initialize(name:) super(name: name, type: :physical) end def shippable? true end def shipping_annotations end end class PhysicalBookProduct < PhysicalProduct def initialize(name:) super(name: name) end def shipping_annotations "\nItem isento de impostos conforme disposto na Constituição Art. 150, VI, d." end end class DigitalProduct < Product def initialize(name:) super(name: name, type: :digital) end end class SubscriptionProduct < Product def initialize(name:) super(name: name, type: :subscription) end end
true
56b6bfc17dd499cac36741841e70e2d83a02aacd
Ruby
ktcannell/ttt-game-status-v-000
/lib/game_status.rb
UTF-8
1,215
3.953125
4
[]
no_license
# Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], # Top row [3,4,5], # Middle row [6,7,8],# Bottom row [0,4,8],# Diagonal left to right [2,4,6],# Diagonal right to left [0,3,6],# First column [1,4,7],# Second column [2,5,8] # Third column ] def won?(board) board.all? {|i| i != " " || i != ""} winning_array = WIN_COMBINATIONS.detect do |win_array| if win_array.all? {|position| board[position] == "X" } == true winning_array.inspect elsif win_array.all? {|position| board[position] == "O" } == true winning_array.inspect end end end def full?(board) board.none? {|i| i == "" || i == " "} end def draw?(board) won?(board) == nil && full?(board) == true end def over?(board) if (draw?(board) == true) || (won?(board) != nil) over = true else over = false end end def winner(board) if won?(board) != nil winner = board[won?(board)[0]] end end def play(board) until over?(board) == true turn(board) end if draw?(board) == true puts "Cats Game!" else puts "Congratulations #{winner(board)}!" end end
true
844ef704d8d20d0392b2c2381c294d0518ce002c
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/nucleotide-count/4ae36b43f73544bfb334c96c26e75207.rb
UTF-8
402
3.421875
3
[]
no_license
class Nucleotide DNA = ['A', 'C', 'G', 'T'] class << self alias_method :from_dna, :new end def initialize(input) raise ArgumentError if input.match(/[^#{DNA.join('')}]/) @dna = input end def count(input) @dna.count(input) end def histogram DNA.each_with_object Hash.new do |nucleotide, result| result[nucleotide] = @dna.count(nucleotide) end end end
true
a11057a43f7d4caba6b01cd46146a7cf512c0792
Ruby
svanderbleek/stocksy
/test/models/stock_test.rb
UTF-8
525
2.5625
3
[]
no_license
require 'test_helper' class StockTest < ActiveSupport::TestCase test "trend up/down" do up_arrow = '^' down_arrow = 'v' up_trend = stocks(:one).trend(up: up_arrow, down: down_arrow) down_trend = stocks(:two).trend(up: up_arrow, down: down_arrow) no_trend = Stock.new.trend(up: up_arrow, down: down_arrow) assert up_trend == up_arrow assert down_trend == down_arrow assert no_trend.nil? end test "value" do assert stocks(:two).value == 6 assert Stock.new.value.nil? end end
true
27edfb677ed35a5d4a978f5756d60cfadf7ae8df
Ruby
velvelshteynberg/Practicingruby
/firstmethod.rb
UTF-8
1,569
4.65625
5
[]
no_license
#first method: the def is the defintion of the method # def hey # puts "Hello" # end # hey # puts "It is a great day" # hey # puts "Have fun" # hey # def ask_name # puts "What is your name?" # my_name = gets.chomp # end # ask_name # if my_name == nil # ask_name # else # puts "hello" # end # # invoking the method # def hi (user_name) # puts "Hello #{user_name}" # end # # way of invoking the method with a variable within the bracket # hi ('sree') # hi ('elvis') # hi ('ron') # hi ('velvel') # def give_me_the_total (first, second) # #first = number_of_cats # #second = number_of_dogs # puts "Thanks for using this method " # sum = first + second # #This is the value that will be printed by ruby because you used the return command # return sum # end # number_of_cats = 35 # number_of_dogs = 25 # total_number_of_pets = give_me_the_total(number_of_dogs, number_of_cats) # puts total_number_of_pets # def total (first, second) # puts "your final number is...." # sum = first + second # return sum # end # number_of_movies = 120 # number_of_series = 230 # total_media = total(number_of_movies, number_of_series) # puts "Your total media is #{total_media}" # explicit return = when you use the word return # implicit return = returns the last line in the method def say_hello(name, city) return puts("Hello #{name} from #{city}!") end say_hello("emma", "toronto") say_hello("jackie", "toronto") say_hello("Brian", "toronto") #puts prints the string that was written but returns nil
true
08b5d2c32500a87de66847981125eadbab26aee9
Ruby
byu/serf
/lib/serf/middleware/parcel_freezer.rb
UTF-8
536
2.59375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'ice_nine' require 'optser' module Serf module Middleware ## # Middleware to add uuids to freeze the parcel. # class ParcelFreezer attr_reader :app attr_reader :freezer ## # @param app the app # def initialize(app, *args) opts = Optser.extract_options! args @app = app @freezer = opts.get :freezer, IceNine end ## # Chains the call, but deep freezes the parcel. def call(parcel) freezer.deep_freeze parcel app.call parcel end end end end
true
a5065ebe211606d454ef26b6ed4d2eabd8195207
Ruby
VulnerabilityHistoryProject/vulnerability-history
/lib/taggers/bounty_tagger.rb
UTF-8
1,170
3.171875
3
[ "MIT" ]
permissive
require_relative '../writing' class BountyTagger def initialize end def create_tags @bounty_tag = Tag.find_or_create_by!( name: 'Bounty Awarded', shortname: 'bounty', color: '#25C322', icon: 'money', description: Writing.tag_article('bounty'), family: 'bounty' ) end def apply_tags Vulnerability.all.each do |v| begin if has_bounty?(v) VulnerabilityTag.create!( vulnerability: v, tag: @bounty_tag, note: "$#{v.notes.dig('bounty', 'amount').to_s} awarded.", importance: importance(v.notes.dig('bounty', 'amount').to_s.to_f) ) end rescue require 'byebug'; byebug end end end # We're going to mark the importance of a bounty tag according to our # unscientific method roughly based on logarithm def importance(bounty) case bounty when 0.0 then 0.0 when 0.01..1000.0 then 0.25 when 1000.01..10000 then 0.75 when 10000.01..100000 then 0.95 else 0.99 # over $100k?!?! wow. end end def has_bounty?(v) v.notes.dig('bounty', 'amount').to_i > 0 end end
true
5c4cba4adb797b8dc10e131fa14f79befea38867
Ruby
RickCarlino/NMEA-Geo-Tagger
/main.rb
UTF-8
1,258
3.1875
3
[]
no_license
require "nmea_plus" require "rubyserial" # === CONFIGURATION === # You can change these if you need to, but make sure you # understand what you're changing. GPS_PORT = ENV["GPS_PORT"] || "/dev/ttyACM0" FILE_LOCATION = "geo.csv" CSV_HEADERS = "" # <= Customize this # === DATA INITIALIZATION === decoder = NMEAPlus::Decoder.new serialport = Serial.new GPS_PORT # Defaults to 9600 baud, 8 data bits, and no parity state = { lat: nil, lng: nil, alt: nil, ready: false } File.write(FILE_LOCATION, CSV_HEADERS) unless File.file?(FILE_LOCATION) Thread.new do puts "Waiting for signal. This could take a while." loop do raw = serialport.gets chunk = raw[1..5] if chunk == "GPGGA" # safer way to do what we did above message = decoder.parse(raw) state[:alt] = message.altitude state[:lat] = message.latitude state[:lng] = message.longitude puts "Begin." unless state[:ready] state[:ready] = true end end end loop do if state[:ready] val = gets.chomp lat = state.fetch(:lat) lng = state.fetch(:lng) alt = state.fetch(:alt) msg = "#{lat}, #{lng}, #{alt}, #{val}\n" Thread.new { `espeak #{val.inspect}` } puts msg open(FILE_LOCATION, "a") { |f| f << msg } end end
true
99c1bdfc02f0d9f46bbcaa4bf39659398bb7011f
Ruby
jdeepee/holbertonschool-sysadmin_devops
/use_a_regular_expression_against_a_problem_now_you_have_2_problems/0-letters_and_numbers.rb
UTF-8
78
2.5625
3
[]
no_license
#!/usr/bin/ruby arg = ARGV[0].dup out = arg.gsub!(/[^0-9a-zA-Z]/, '') puts out
true
70e2c992e638a05aa85f8e9b6b59585ba295a1c6
Ruby
upinetree/depcop
/lib/depcop/rule/efferent_couplings.rb
UTF-8
710
2.59375
3
[ "MIT" ]
permissive
module Depcop module Rule class EfferentCouplings CONFIG_DEFAULTS = { "Max" => 5 } def initialize(nodes, edges, config) efferent_deps = Hash[nodes.map { |n| [n.join("::"), []] }] edges.each do |edge| to = edge["to"].join("::") from = edge["from"].join("::") efferent_deps[from] << to end @efferent_deps = efferent_deps @config = CONFIG_DEFAULTS.merge(config || {}) end def run @efferent_deps.select { |_from, to| to.size > @config["Max"] }.map { |from, to| "Efferent couplings (Ce) too high [#{to.size}/#{@config["Max"]}]: #{from}" } end end end end
true
fe62becd42a09e3bffda28d40338539ae8bc7041
Ruby
bhavikakhare/link-to-jobs
/test/models/company_test.rb
UTF-8
2,667
2.5625
3
[]
no_license
# == Schema Information # # Table name: companies # # id :bigint not null, primary key # address :string # avg_rating :decimal(, ) # count_ratings :integer # description :text # email :string # name :string # phone_number :bigint # size :string # sum_ratings :decimal(, ) # year_established :integer # created_at :datetime not null # updated_at :datetime not null # recruiter_id :bigint # # Indexes # # index_companies_on_recruiter_id (recruiter_id) # # Foreign Keys # # fk_rails_... (recruiter_id => users.id) # require "test_helper" class CompanyTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "fixtures are valid" do companies.each do |c| assert c.valid?, c.errors.full_messages.inspect end end test "name is present" do c = companies(:one) c.name = "" assert_not c.valid? end test "size is present" do c = companies(:one) c.size = nil assert_not c.valid? end test "email is present" do c = companies(:one) c.email = nil assert_not c.valid? end test "description is present" do c = companies(:one) c.description = "" assert_not c.valid? end test "name is within length limits" do c = companies(:one) c.name = "abc defghijklmnopqrstuvwxyz" assert_not c.valid? end test "size is valid" do c = companies(:one) c.size = "xyz" assert_not c.valid? end test "email is valid" do c = companies(:one) c.email = "ab c" assert_not c.valid? end test "description is within length limits" do c = companies(:one) c.description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus vehicula quis urna non sollicitudin. Cras erat quam, interdum volutpat felis eget, volutpat dictum quam. Sed fringilla blandit libero in efficitur. Phasellus vehicula tempus orci, non dictum urna volutpat finibus. Nunc at vehicula orci. Aliquam ut magna tortor. Aenean imperdiet justo et velit lobortis, in pretium ante mattis. Quisque dapibus quam fringilla mollis lobortis. Phasellus pretium nibh non velit hendrerit malesuada sit." assert_not c.valid? end # numericality tests left test "avg_rating is valid" do c = companies(:one) c.avg_rating = -2 assert_not c.valid? end test "year_established is valid" do c = companies(:one) c.year_established = 2040 assert_not c.valid? end test "phone_number is valid" do c = companies(:one) c.phone_number = 10000000000 assert_not c.valid? end end
true
eb5dbf03c2952c43e9aa42210bba7cc976323541
Ruby
JeremyVe/danebook
/spec/models/user_spec.rb
UTF-8
1,882
2.625
3
[]
no_license
require 'rails_helper' describe User do let(:user){ create(:user) } context "validation" do it "should be valid with common attributes" do expect(user).to be_valid end it "should not be valid if email is missing" do invalid_email = [nil, "", " "] invalid_email.each do |email| user.email = email expect(user).not_to be_valid end end it "should not be valid if email is invalid" do invalid_email = ["an_email", "my@email", "email.com"] invalid_email.each do |email| user.email = email expect(user).not_to be_valid end end it "should not be valid if password is missing" do invalid_password = [nil, "", " "] invalid_password.each do |password| user.password = password expect(user).not_to be_valid end end it "should not be valid if the password is too short or too long" do invalid_password = ["a"*7, "a"*25] invalid_password.each do |password| user.password = password expect(user).not_to be_valid end end end context "association" do it "shoud respond to a Profile association" do expect(user).to respond_to(:profile) end it "shoud respond to a Posts association" do expect(user).to respond_to(:posts) end it "should respond to the Comments association" do expect(user).to respond_to(:comments) end it "should respond to the Liked_posts association" it "should respond to the Liked_comments association" end context "classMethod" do describe "#full_name" do it "should return the full_name of the user" do profile = create(:profile, user: user) profile.first_name = "john" profile.last_name = "youth" expect(user.full_name).to eq("john youth") end end end end
true
e7a6d43e5efe925cfb5ec0b3299029208ddcd4bd
Ruby
justed-tests/rails-api
/app/models/order.rb
UTF-8
460
2.734375
3
[]
no_license
# order for tables =) class Order < ApplicationRecord belongs_to :table has_many :order_items has_many :items, through: :order_items def build_new_item(params) existing_item = OrderItem.find_by(order: self, item_id: params[:item_id]) if existing_item existing_item.increment(:quantity) else order_items.build(params) end end def total_amount items.inject(0) do |sum, item| sum + item.price end end end
true
67077e2f5569d1457356a20f300eacb218d260a2
Ruby
jomno/How-Do-Rails-Work
/http/response/test/file_steam.rb
UTF-8
118
2.90625
3
[]
no_license
File.open("test", "rb") do |file| while chunk = file.read(12) puts chunk puts "hi" sleep(0.5) end end
true
5b0f13f4fe97db00d50bf3f0060979e95464f659
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/leap/c4dd0831ec02443c8d6de9e88538a6ad.rb
UTF-8
297
3.40625
3
[]
no_license
class Year def initialize(year) @year = year end def leap? exceptional_century? || (vanilla_leap_year? && not_century) end def vanilla_leap_year? @year % 4 == 0 end def exceptional_century? @year % 400 == 0 end def not_century @year % 100 != 0 end end
true
3deb49f5ca543c973ae6a6a3e92486a218bb7309
Ruby
akami11/Dmm-PF
/app/controllers/sorts_controller.rb
UTF-8
849
2.578125
3
[]
no_license
class SortsController < ApplicationController # ソート機能やり方は検索機能と同じ、orderメソッドで降順、昇順が選べるよ # ASCが昇順「1、2、3、・・」、DESCが降順「10、9、8・・・」 def sort @nutrition = params["nutrition"] @updown = params["updown"] @conclude = sort_for(@nutrition,@updown).page(params[:page]).per(12) @categories = Category.all @tip = Tip.find(Tip.pluck(:id).sample) # @foods = params["foods"] end private def sort_for(nutrition,updown) if nutrition == "熱量" if updown == "高い順" Food.order(calorie: :DESC) else Food.order(calorie: :ASC) end else if updown == "高い順" Food.order(protein: :DESC) else Food.order(protein: :ASC) end end end end
true
b6cd0bf17693c104a0c2dbf984e72ae30636393e
Ruby
rafaeldwan/learn_to_program
/variables/name.rb
UTF-8
426
3.359375
3
[]
no_license
puts "I ALWAYS NEED NAMES. NOW IS WHEN YOU GIVE ME A FIRST NAME." first_name = gets.chomp puts "LAST NAME IS ALSO REQUIRED." last_name = gets.chomp name = first_name + " " + last_name puts "THANK YOU SO MUCH #{name.upcase}. I AM FOREVER IN YOUR DEBT." filename = "names.txt" File.open(filename, 'a') do |file| file.puts name end 10.times {print name.upcase + ". "} puts "IT IS A GOOD NAME. I SHALL REMEMBER IT IN ME BITS."
true
1e675e755a877f5e2194977b3d29b3fb322bf89e
Ruby
shinara03/aa_classwork
/w4d5/octopus_hw.rb
UTF-8
1,221
3.890625
4
[]
no_license
#['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] #=> "fiiiissshhhhhh" # Sluggish Octopus O(n^2) def sluggish_octopus(arr) longest = arr[0] arr.each_with_index do |ele1, idx1| arr.each_with_index do |ele2, idx2| if ele2.length > ele1.length longest = arr[idx2] end end end longest end #Dominant Octopus O(n * log n) def dominant_octopus(arr) mid = arr.length / 2 right = arr[mid..-1] end # clever octopus O(n) def clever_octopus(arr) longest = arr[0] arr.each do |ele| longest = ele if ele.length > longest end longest end #slow dance O(n) def slow_dance(dir, arr) arr.each_with_index do |ele, idx| return idx if ele == dir end end #constant dance O(1) def fast_dance(dir, hash) hash[dir] end tiles_array = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up" ] puts slow_dance("up",tiles_array) puts slow_dance("right-down", tiles_array) tiles_hash = { "up" => 0, "right-up" => 1, "right" => 2, "right-down" => 3, "down" => 4, "left-down" => 5, "left" => 6, "left-up" => 7 } puts fast_dance("up", tiles_hash) puts fast_dance("right-down", tiles_hash)
true
7887269498b5674774d7adec4c70856b16393e67
Ruby
chintas1/ormproject
/app/views/user/display_fav_movie.rb
UTF-8
123
2.6875
3
[]
no_license
class DisplayFavMovieView def render(movie) puts "\nYour favorite movie is currently set as: #{movie.name}" end end
true
429a5ee00e1a5566c64c2fdc8c826e4e63118297
Ruby
Pennylele/Ruby
/script5.rb
UTF-8
932
4.3125
4
[]
no_license
print "Thstring, pleathe!: " user_input = gets.chomp user_input.downcase! if user_input.include? "s" user_input.gsub!(/s/, "th") else puts "Nothing to do here!" end puts "You string is: #{user_input}" #We can do that using Ruby's .include? method, which evaluates to true if it finds what it's looking for and false otherwise. #As a general rule, Ruby methods that end with ? evaluate to the boolean values true or false. #As a general rule, Ruby methods that end with ? evaluate to the boolean values true or false. #Note: you cannot put a space between gsub! and the bit in parentheses. puts "****************************" while true print 'Please put your string here!' user_input = gets.strip.downcase case user_input when '' next when /s/ user_input.gsub!(/s/, "th") puts "transformed string: #{user_input}!" break else puts "no \"S\" in the string" break end end
true
4daac4107fdd43f43d9d97709e0f7fdddc6933f5
Ruby
stevenbeales/ehr-march
/api/lib/activation.rb
UTF-8
163
2.875
3
[]
no_license
module Activation def self.code(size = 5) (0...size).map{ (1..9).to_a.sample }.join end def self.colour SecureRandom.hex(3).upcase end end
true
369aaca8915a504a7bb6906a78f451c9d2663881
Ruby
pagood/micropost
/test/models/user_test.rb
UTF-8
932
2.59375
3
[]
no_license
require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end def setup @user = User.new(email:'111',password: '123',password_confirmation: '123') @user2 = User.new(email:'[email protected]',password: '123456',password_confirmation: '123456') @user3 = User.new(email:'[email protected]',password: '123',password_confirmation: '123') end test "valid user" do assert @user2.valid? end test "have nonblank email" do @user.email = '' assert_not @user.valid? end test "should follow and unfollow a user" do x = users(:one) y = users(:two) assert_not x.following?(y) x.follow(y) assert x.following?(y) x.unfollow(y) assert_not x.following?(y) end test "have long enough password" do @user.email = '[email protected]' @user.password = "123456" @user.password_confirmation = "123456" assert @user.valid? end end
true
91564ea02fe5fb84c10aaa6be6c03a671f62d97a
Ruby
kola22/Ruby
/ruby.tmbundle-master/Support/vendor/rcodetools/test/data/attic/rspec-output.rb
UTF-8
1,360
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "Ruby", "LicenseRef-scancode-boost-original" ]
permissive
class X Y = Struct.new(:a) def foo(b) ; b ? Y.new(2) : 2 end def bar; raise "No good" end def baz; nil end def fubar(x) ; x ** 2.0 + 1 end def babar; [1, 2] end A = 1 A = 1 # !> already initialized constant A end describe "xmpfilter's expectation expansion" do before do @o = X.new end it "should expand should == expectations" do (@o.foo(true)).should be_a_kind_of(X::Y) (@o.foo(true).inspect).should == ("#<struct X::Y a=2>") (@o.foo(true).a).should == (2) (@o.foo(false)).should == (2) end it "should expand should raise_error expectations" do lambda { @o.bar }.should raise_error(RuntimeError) end it "should expand should be_nil expectations" do (@o.baz).should be_nil end it "should expand correct expectations for complex values" do (@o.babar).should == ([1, 2]) end it "should expand should be_close expectations" do (@o.fubar(10)).should be_close(101.0, 0.0001) end end describe "xmpfilter's automagic binding detection" do it "should expand should == expectations" do a = b = c = 1 d = a (d).should == (a) (d).should == (b) (d).should == (c) (d).should == (1) end end
true
010a0d6d1d77c539a65977e5820d21ad9c51dd6d
Ruby
arver/arver
/lib/arver/node_with_script_hooks.rb
UTF-8
881
2.59375
3
[ "MIT" ]
permissive
module Arver module NodeWithScriptHooks attr_accessor :pre_open, :pre_close, :post_open, :post_close def script_hooks_to_yaml yaml = "" yaml << "'pre_open': '#{pre_open}'\n" unless pre_open.nil? yaml << "'pre_close': '#{pre_close}'\n" unless pre_close.nil? yaml << "'post_open': '#{post_open}'\n" unless post_open.nil? yaml << "'post_close': '#{post_close}'\n" unless post_close.nil? yaml end def script_hooks_from_hash( hash ) hash.each do | name, data | self.pre_open= data if name == "pre_open" self.pre_close= data if name == "pre_close" self.post_open= data if name == "post_open" self.post_close= data if name == "post_close" end hash.delete("pre_open") hash.delete("pre_close") hash.delete("post_open") hash.delete("post_close") end end end
true
f2d17c56a0d0e16df05d307c34ee99276e171138
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/secret-handshake/3da4611b38e546008cc368280efa27ea.rb
UTF-8
377
3.328125
3
[]
no_license
class SecretHandshake attr_reader :commands def initialize(n) if n.is_a?(Integer) digits = n.to_s(2).reverse ops = ["wink", "double blink", "close your eyes", "jump", nil] @commands = digits.chars.map.with_index { |d, i| d == "1" ? ops[i] : nil }.compact @commands.reverse! if digits.length == 5 else @commands = [] end end end
true
7fc44d497517c462aae0b50ee9b7d82142c84304
Ruby
alphagov-mirror/vcloud-converter
/bin/convert
UTF-8
732
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require "bundler/setup" require "vcloud/converter" require "optparse" ARGV << '-h' if ARGV.empty? options = {} OptionParser.new do |opts| opts.banner = "Usage: ./bin/convert -t vcloud-net_launcher -p path/to/file.yaml" opts.on('-t', '--type TYPE', 'Type of YAML file for conversion.') { |v| options[:type] = v } opts.on('-p', '--path PATH', 'Path to YAML file for conversion.') { |v| options[:path] = v } opts.on_tail("-h", "--help", "Show this help message.") do puts opts exit end end.parse! if File.exists?(File.expand_path(options[:path])) Vcloud::Converter.convert(options[:type], options[:path]) else puts "The file you specified - #{options[:path]} - doesn't exist." exit end
true
ad7f6445ec64848492332c108eb3ba3efab8de44
Ruby
speckworks/programming-univbasics-3-labs-with-tdd-dumbo-web-82619
/calculator.rb
UTF-8
228
2.890625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Add your variables here first_number = a second_number = b second_number != 0 sum = a + b product = a * b difference = a - b quotient = a/b a = gets.chomp b = gets.chomp puts sum puts product puts difference puts quotient end
true
c5360513eff0b9894bee63f6391fe9ab8d749696
Ruby
jesus9ias/exercises
/diceware/diceware.rb
UTF-8
488
3.625
4
[]
no_license
require "json" puts "How many words do you want?" tot_words = gets.chomp tot_dice = tot_words.to_i * 5 rand_nums = [] num_keys = [] wordlist = File.read('wordlist.json') word_hash = JSON.parse(wordlist) words = {} tot_dice.times{ rand_nums << rand(1..6) } rand_nums = rand_nums.each_slice(5).to_a num_keys = rand_nums.map { |x| x.join() } words = num_keys.map { |y| word_hash[y] } #puts word_hash #puts rand_nums.join() puts rand_nums.to_s puts num_keys.to_s puts words.join(" ")
true
49e48568381ed979c2d1a99041208f62ab7cbe30
Ruby
jmromer/vendtriloquist
/app/models/money.rb
UTF-8
1,440
2.75
3
[]
no_license
# coding: utf-8 # frozen_string_literal: true require "models/application_record" require "services/change_maker" require "utils/counter" require "utils/currency" class Money < ApplicationRecord VALID_DENOMINATIONS = [ 2_00, 1_00, 50, 20, 10, 5, 2, 1, ].freeze validates :denomination_value, presence: true, uniqueness: true, numericality: { greater_than: 0 }, inclusion: { in: VALID_DENOMINATIONS } validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0 } def self.valid?(denomination) VALID_DENOMINATIONS.include?(denomination) end def self.till_values pluck(:denomination_value, :quantity).to_h end def self.add_to_till!(value_counts:) update_quantities!(value_counts) { |curr_qty, delta| curr_qty + delta } end def self.remove_from_till!(value_counts:) update_quantities!(value_counts) { |curr_qty, delta| curr_qty - delta } end def self.update_quantities!(value_counts) return if value_counts.to_h.empty? transaction do where(denomination_value: value_counts.keys).find_each do |till_slot| curr_qty = till_slot.quantity delta_qty = value_counts.fetch(till_slot.denomination_value) updated_qty = yield(curr_qty, delta_qty) till_slot.quantity = updated_qty till_slot.save! end end end end
true
d0ce1f602dabbab863b3768ac7deb93beb6b734c
Ruby
Archeia/iek
/lib/iek/xpresso/xpresso.rb
UTF-8
1,370
3.25
3
[]
no_license
# The simpliest script for 'mixing' items module IEK class Xpresso class MixResultItem attr_accessor :kind attr_accessor :id attr_accessor :number def initialize(kind, id, number) @kind, @id, @number = kind, id, number end def item case @kind when 0 nil when 1 $data_items[id] when 2 $data_weapons[id] when 3 $data_armors[id] when 4 $data_skills[id] end end end class MixResult attr_accessor :items # Array<MixResultItem> attr_accessor :message # String def initialize(items, message) @items = items @message = message end def valid? [email protected]? end def gain_items(target) @items.each do |mix_result_item| target.gain_item mix_result_item.item, number end end end attr_reader :mix_table def initialize @mix_table = {} end def mix(item1, item2) if !item1 || !item2 return MixResult.new([], 'Invalid items') end key = [item1.to_mix_key, item2.to_mix_key] mix_results = @mix_table[key] if mix_results return MixResult.new(mix_results, 'Mixed!') end MixResult.new([], 'No mix result') end end end
true
5efce94a61fe4af841b0467ee812956c10319600
Ruby
bluespheal/etapa3
/semana1/miercoles/gallinita_tdd/lib/laying_hen.rb
UTF-8
317
3.65625
4
[]
no_license
class LayingHen attr_reader :age, :basket def initialize(age = 0) @age = 0 @basket=[] end # Ages the hen one month, and lays 4 eggs if the hen is older than 3 months def age! @age += 1 if @age >= 4 4.times {@basket << Egg.new} end end end class Egg end
true
6b878a6367cb4184615e48d911d7ab15eb877610
Ruby
crazycode/cap-recipes
/test.rb
UTF-8
2,868
2.75
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require "net/http" require "uri" require "json" class CmdbService def self.get_app_role(cse_base, unit_code, stage) url = "#{cse_base}/deploy/get-server.do?deployUnitCode=#{unit_code}&stage=#{stage}" resp = Net::HTTP.get_response(URI.parse(url)) data = resp.body # we convert the returned JSON data to native Ruby # data structure - a hash result = JSON.parse(data) # if the hash has 'Error' as a key, we raise an error if !result.has_key? 'success' raise "web service error" end unless result['success'] raise "#{unit_code}@#{stage} get_app_role faile!" end server = result['servers'] if server.nil? raise "Not fout servers for #{unit_code}@#{stage}" end server.collect {|s| "#{s['ip']}:#{s['sshPort']}"} end def self.start_deploy(cse_base, unit_code, stage) url = URI.parse("#{cse_base}/deploy/start-deploy.do") param = { 'deployUnitCode' => unit_code, 'stage' => stage, 'deployer' => 'capistrano', 'version' => '1.0.1' } http = Net::HTTP.new(url.host, url.port) resp = http.post(url.path, param.to_json) data = resp.body puts "data=#{data}" # we convert the returned JSON data to native Ruby # data structure - a hash result = JSON.parse(data) # if the hash has 'Error' as a key, we raise an error if !result.has_key? 'success' raise "web service error" end unless result['success'] raise "#{unit_code}@#{stage} start_deploy faile!" end result['deploymentId'] end #deployUnitCode : 发布单元编号 #deploymentId : 开始发布接口生成的唯一标识 #success : 是否发布成功 #description : 发布结果描述 def self.complete_deploy(cse_base, unit_code, deployment_id, is_success, description) url = URI.parse("#{cse_base}/deploy/complete-deploy.do") param = { 'deployUnitCode' => unit_code, 'deploymentId' => deployment_id, 'success' => is_success, 'description' => description } http = Net::HTTP.new(url.host, url.port) resp = http.post(url.path, param.to_json) data = resp.body puts "data=#{data}" # we convert the returned JSON data to native Ruby # data structure - a hash result = JSON.parse(data) # if the hash has 'Error' as a key, we raise an error if !result.has_key? 'success' raise "web service error" end unless result['success'] puts "#{unit_code}@#{stage} start_deploy faile!" return false end return true end end s = CmdbService.get_app_role("http://10.241.14.166:8080/cse", "zf00032", "test") puts "s=#{s}" did = CmdbService.start_deploy("http://10.241.14.166:8080/cse", "zf00032", "test") puts "deploy=#{did}" r = CmdbService.complete_deploy("http://10.241.14.166:8080/cse", "zf00032", did, true, "发布成功") puts "r=#{r}"
true
1f2784c141ad4206a9b74e763250432d74019c47
Ruby
clintonjnelson/twitteresque_webapp_rails
/app/controllers/users_controller.rb
UTF-8
3,086
2.53125
3
[]
no_license
class UsersController < ApplicationController # We can use whatever the before filter avails to us - IV's, etc. (See "edit") before_filter :signed_in_user, only: [:edit, :update, :index, :followers, :following] before_filter :correct_user, only: [:edit, :update] before_filter :admin_user, only: [:destroy] before_filter :protect_newcreate, only: [:new, :create] ############# Creation Actions ############# def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:success] = "Your signup was successful - Welcome to the sample app!" sign_in @user # Loads user's :remember_token into cookies on browser redirect_to @user else render 'new' end end ############# Individual User Actions ############# def edit # @user = User.find(params[:id]) # Before_filter sets it for edit & update end def update # @user = User.find(params[:id]) # Before_filter sets it for edit & update if @user.update_attributes(params[:user]) # Returns true if successful flash[:success] = 'Profile Updated' sign_in @user redirect_to @user else render 'edit' end end def show # Grab the user info per the passed :id, so we can use & display it as desired. @user = User.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page]) end def followers @title = "Followers" @user = User.find(params[:id]) @users = @user.followers.paginate(page: (params[:page])) render "show_follow" end def following @title = 'Following' @user = User.find(params[:id]) @users = @user.followed_users.paginate(page: (params[:page])) render 'show_follow' end ############# ADMIN or All User Actions ############# def index @users = User.paginate(page: params[:page]) end def destroy @user = User.find(params[:id]) if @user.admin? flash[:error] = "Admin Cannot Be Deleted" else @user.destroy flash[:success] = "User Deleted." end redirect_to users_path end private ## MOVED THIS TO THE SESSIONS HELPER TO ALLOW ACCESS FROM MICROPOSTS CONTROLLER TOO # def signed_in_user # unless signed_in? # store_location # redirect_to signin_path, notice: "Please sign in." # end # # OLD: redirect_to signin_path, notice: "Please Sign In" unless signed_in? # end # Method to verify if the user is the same as current_user. # HOW DOES THIS VERIFY USERS AGAINST TRYING TO ACCESS OTHERS??? # OH, BECAUSE THE PARAMS PASSED FOR AN EDIT ATTEMPT COULD BE ANOTHER"S... # SO checks attempted access user against the remember_token user. def correct_user @user = User.find(params[:id]) redirect_to(root_path) unless current_user?(@user) end def admin_user redirect_to root_path unless current_user.admin? end def protect_newcreate redirect_to root_path if signed_in? end end
true
b428d979a84d1a2700bf1cf02ec3b3b8a4cc969c
Ruby
thebravoman/software_engineering_2013
/class6_belt_exam/Hristiqn_Zarkov_1.rb
UTF-8
385
2.84375
3
[]
no_license
require 'csv' all = Array.new() CSV.foreach(ARGV[0]) do |row| val = row[4].split(" ") if (val[0] == ARGV[1]) all << [row[0],row[1],row[2],row[3],row[4],row[5]] end end CSV.open("bank_result.csv","w") do |csv| all.sort_by{|a,b,c,d,e,f| c}.each do |row| csv << [row[0],row[1],row[2],row[3],row[4],row[5]] end end
true
768d9b0ce560322a67fc7a1eb47306f55172c6f3
Ruby
MichaelCrockett/snowman
/spec/player_spec.rb
UTF-8
673
2.75
3
[]
no_license
require ('minitest/autorun') require ('minitest/rg') require_relative ('../player') require_relative ('../game') require_relative ('../hidden_word') class TestPlayer < MiniTest::Test def setup @player1 = Player.new("Jo") end def test_has_lives? assert_equal(true, @player1.has_lives?) end def test_lose_life @player1.lose_life @player1.lose_life @player1.lose_life assert_equal(3, @player1.number_of_lives) end def test_lost_all_lives @player1.lose_life @player1.lose_life @player1.lose_life @player1.lose_life @player1.lose_life @player1.lose_life assert_equal(false, @player1.has_lives?) end end
true
54a123c217cda41ac7e7496d4075132f05d7b746
Ruby
sshaw/explain-dependencies
/lib/xdep.rb
UTF-8
2,857
2.75
3
[ "MIT" ]
permissive
require "fileutils" require "tempfile" require "xdep/npm" require "xdep/ruby" require "xdep/version" class XDep Error = Class.new(StandardError) REPORT_BASENAME = "dependencies".freeze REPORT_EXTENSION = ".explained".freeze FORMAT_HANDLERS = { :csv => [ Bundler::CSVOutput, RubyGems::CSVOutput, Npm::CSVOutput ], :source => [ Bundler::GemfileOutput, RubyGems::GemspecOutput ] } def initialize(options = nil) @options = options || {} @format = @options[:format] || :csv raise ArgumentError, "Unknown output format: #{@format}" unless FORMAT_HANDLERS.include?(@format) end def process(sources) sources = normalize_sources(sources) raise ArgumentError, "No dependency files found" if sources.empty? if @format == :csv output_as_csv(sources) else output_as_original(sources) end end private def output_as_original(sources) handlers = create_handlers(sources) sources.each do |source| File.open(source) do |input| output = Tempfile.new(REPORT_BASENAME) begin # TODO: Not sure this is the right interface handlers[File.basename(source)].process(input, output) output.close # On Win files must be closed before moving. dest = source dest += REPORT_EXTENSION unless @options[:add] FileUtils.mv(output.path, dest) ensure output.close unless output.closed? end end end end def output_as_csv(sources) handlers = create_handlers(sources) report = File.open("#{REPORT_BASENAME}.csv", "w") begin sources.each do |source| # Each handler must append report.seek(0, :END) File.open(source) do |input| handlers[File.basename(source)].process(input, report) end end ensure report.close end end def normalize_sources(sources) sources.flat_map do |source| if File.directory?(source) find_sources(source) elsif !File.file?(source) raise ArgumentError, "No such file: #{source}" elsif find_handler(File.basename(source)).nil? raise ArgumentError, "Don't know how to output #{source} in #@format format" else source end end end def create_handlers(sources) sources.each_with_object({}) do |source, h| basename = File.basename(source) unless h.include?(basename) klass = find_handler(basename) raise Error, "#{basename} does not support format #@format" unless klass h[basename] = klass.new(@options) end end end def find_handler(filename) FORMAT_HANDLERS[@format].find { |handler| handler.accepts?(filename) } end def find_sources(root) Dir[ File.join(root, "*") ].reject { |path| find_handler(File.basename(path)).nil? } end end
true
9d247a3101bee81cb21cd55ba8ade2f0547dfd45
Ruby
mashiro-no-rabo/githubVisual
/cook_data.rb
UTF-8
1,322
2.65625
3
[]
no_license
# encoding: utf-8 require 'rubygems' require 'redis' require 'byebug' @days = [31,28,31,30,31,30,31,31,30,31,30,31] @redis = Redis.new(port: 7755) # calc jan hours def calc_jan_hours tmp = [] 24.times { tmp << 0} (1..31).each do |day| (0..23).each do |hour| hdata = @redis.hgetall "2013-1-#{day}-#{hour}" hdata.each { |k,v| tmp[hour] += v.to_i } end end byebug tmp.each { |v| @redis.rpush "2013-1_hours", v } end // calc jan langs hours def calc_jan_langs (1..31).each do |day| (0..23).each do |hour| ss = @redis.hgetall "2013-1-#{day}-#{hour}" ss.each do |k,v| @redis.hincrby "2013-1_hour_#{hour}", k, v.to_i end end end end # @redis.hincrby "2013", event["repository"]["language"], size # @redis.hincrby "2013-#{month}", event["repository"]["language"], size # @redis.hincrby "2013-#{month}-#{day}", event["repository"]["language"], size # @redis.hincrby "2013-#{month}-#{day}-#{hour}", event["repository"]["language"], size # @redis.hincrby "2013_push", event["repository"]["language"], size # @redis.hincrby "2013-#{month}_push", event["repository"]["language"], size # @redis.hincrby "2013-#{month}-#{day}_push", event["repository"]["language"], size # @redis.hincrby "2013-#{month}-#{day}-#{hour}_push", event["repository"]["language"], size
true
42d3010ce16d7d160909c7a1dde68b95b21c4dc2
Ruby
WeatherVine/back_end
/spec/services/wine_service_spec.rb
UTF-8
1,727
2.5625
3
[]
no_license
require 'rails_helper' require 'ostruct' RSpec.describe WineService do describe 'happy path' do it 'fetches wine data and returns the correct object' do VCR.use_cassette("wine_microservice_fetch") do response = WineService.fetch_wine("5f065fb5fbfd6e17acaad294") expect(response).to be_an(OpenStruct) expect(response).to respond_to("api_id") expect(response).to respond_to("name") expect(response).to respond_to("area") expect(response).to respond_to("vintage") expect(response).to respond_to("eye") expect(response).to respond_to("nose") expect(response).to respond_to("mouth") expect(response).to respond_to("finish") expect(response).to respond_to("overall") end end it 'can test the data structure of the API data received from the call' do VCR.use_cassette("wine_microservice_fetch") do response = WineService.fetch_wine("5f065fb5fbfd6e17acaad294") expect(response.api_id).to eq("5f065fb5fbfd6e17acaad294") expect(response.name).to eq("Duckhorn The Discussion Red 2012") expect(response.area).to eq("Napa Valley") expect(response.vintage).to eq("2012") expect(response.eye).to eq("Translucent rim, Translucent depth") expect(response.nose).to eq("Oak, Berry, Blackberry aromas") expect(response.mouth).to eq("Oak, Berry, Blackberry flavours, Flat sweetness, Flat acidity, Rich tannins, Warm alcohol") expect(response.finish).to eq("Medium duration, Good quality, Late peaktime") expect(response.overall).to eq("Subtle complexity, Memorable interest, Expected typicity, Harmonious balance") end end end end
true
1d8f00e7c3620fdf6334de4d3c3cb7a49923d667
Ruby
albertbahia/wdi_june_2014
/w01/d05/jon_porras/main_pokemon.rb
UTF-8
777
2.765625
3
[]
no_license
require 'pry' require_relative 'pokemon.rb' require_relative 'trainer' require_relative 'nurse.rb' charmander = Pokemon.new("Charmander", 004, "fire", 39, 52, 43, 65) pikachu = Pokemon.new("Pikachu", 025, "electric", 35, 55, 40, 50) squirtle = Pokemon.new("Squirtle", 007, "water", 44, 48, 65, 50) croconaw = Pokemon.new("Croconaw", 159, "water", 65, 80, 80, 59) misdreavus = Pokemon.new("Misdreavus", 200, "ghost", 50, 60, 60, 85) raikou = Pokemon.new("Raikou", 243, "electric", 50, 85, 75, 115) gothita = Pokemon.new("Gothita", 574, "psychic", 0, 30, 50, 55) klang = Pokemon.new("Klang", 600, "steel", 0, 80, 95, 70) alexa = Trainer.new("Alexa", 27, "San Diego", [charmander, pikachu, squirtle, croconaw, misdreavus]) nurse_jon = Nurse.new("Jon", 18, "NYC") binding.pry
true
bf6437d70bc5f4b05a47afada45b454f41a9e40d
Ruby
sugye/prolabo201610
/takarunn.rb
UTF-8
1,526
3.34375
3
[]
no_license
sleep 1 $scene = 'select1' $kuzi = 0 $ret = 0 def story_do(paramsa,paramsb,question,reanswer,goa,gob) case $scene when 'select1' puts "#{question}" sleep 1 puts "選択肢 a:#{paramsa}, b:#{paramsb}" #①フ繰り返し(~の間) while true input_country = gets case input_country.chomp when 'a' scene = goa #ブレイクで①を破壊する。 break when 'b' scene = gob #ブレイクで①を破壊する。 break else #入力みすなのでブレイクさせない、もう一度入力させる。 puts (reanswer) end end #ループの終了後のsceneの戻り値 return scene end end while true case $ret when 0 #一番目のプログラム $ret = story_do('バカンス気分、ハワイ','誰も知らない、無人島',"船で旅行しに出かけます。\n何所へ向かいますか?",'a か bを入力してください。',1,2) puts 'ret:' + $ret.to_s when 1 #一番目の実行結果が一の時ときに実行 $ret = story_do('カジノ','海水浴','何所で遊びますか?','a か b 入力してください。',4,5) puts 'ret:' + $ret.to_s when 2 puts "帰れなくなりました。fin" break when 4 puts "カジノで遊びました。HAPPY,fin" $kuzi = 1 break when 5 puts "海水浴でクラゲに刺され痒い思いをしました。fin" $kuzi = 0 break end end
true
f9ab4db581d91fcb96f376519e466139ed27c17c
Ruby
markus851/eddy
/lib/definitions/segments/generated/n3.rb
UTF-8
1,234
2.734375
3
[ "MIT" ]
permissive
module Eddy module Segments # ### Segment Summary: # # - Id: N3 # - Name: Address Information # - Purpose: To specify the location of the named party class N3 < Eddy::Models::Segment # @param store [Eddy::Data::Store] # @return [void] def initialize(store) @id = "N3" @name = "Address Information" @n301 = Eddy::Elements::E166.new(ref: "N301", req: "M") @n302 = Eddy::Elements::E166.new(ref: "N302", req: "O") super( store, @n301, @n302, ) end # ### N301 # # - Id: 166 # - Name: Address Information # - Type: AN # - Min/Max: 1/55 # - Description: Address information # # @param arg [String] # @return [void] def N301=(arg) @n301.value = arg end alias AddressInformation1= N301= # ### N302 # # - Id: 166 # - Name: Address Information # - Type: AN # - Min/Max: 1/55 # - Description: Address information # # @param arg [String] # @return [void] def N302=(arg) @n302.value = arg end alias AddressInformation2= N302= end end end
true
fe8e230b140fc1714f51222934c93e41f9afccf5
Ruby
postace/ruby
/lrthw/alias_sample.rb
UTF-8
425
3.25
3
[]
no_license
# Introduce to alias class CelestialBody attr_accessor :type, :name end # Hash default blocks bodies = Hash.new do |hash,key| # Create new object for current key body = CelestialBody.new body.type = "planet" # Assign to the hash and returns the new value hash[key] = body end bodies['Mars'].name = 'Mars' bodies['Europa'].name = 'Europa' bodies['Europa'].type = 'moon' bodies['Venus'].name = 'Venus' p bodies
true
83146822fd60d4d39d3c27cc03a543123a3db2d2
Ruby
jsuchy/brewbook
/features/step_definitions/create_recipe_of_grains_steps.rb
UTF-8
836
2.734375
3
[]
no_license
require 'brewery/use_cases/calculate_strike_temperature_and_volume' Given /^I need (\d*\.?\d+) pounds of grain$/ do |pounds| @pounds = pounds.to_f end Given /^I need (\d*\.?\d+) ounces of grain$/ do |ounces| @ounces = ounces.to_f end Given /^a target mash temperature of (\d+)$/ do |temp| @target_temp = temp.to_i end Given /^a water to grist ratio of (\d*\.?\d+)$/ do |ratio| @ratio = ratio.to_f end When /^the strike water calculations are done$/ do @result = Brewery::UseCase::CalculateStrikeTemperatureAndVolume.new(@pounds, (@ounces || 0), @target_temp, @ratio).execute end Then /^the strike water temperature is (\d*\.?\d+)$/ do |temp| @result[:strike_water_temperature].should == temp.to_f end Then /^the water volume needed is (\d*\.?\d+)$/ do |volume| @result[:mash_water_volume].should == volume.to_f end
true
b2542330a3d9fd48b43928c52add83f654c383b0
Ruby
Gevanstron/triangle-classification-v-000
/lib/triangle.rb
UTF-8
881
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Triangle attr_accessor :first_side, :second_side, :third_side, :equilateral, :isosceles, :scalene def initialize(first_side, second_side, third_side) @first_side = first_side @second_side = second_side @third_side = third_side end def kind if first_side <= 0 || second_side <= 0 || third_side <= 0 raise TriangleError elsif (first_side >= second_side + third_side) || (second_side >= first_side + third_side) || (third_side >= first_side + second_side) raise TriangleError else if (first_side == second_side) && (first_side == third_side) :equilateral elsif (first_side == second_side) || (first_side == third_side) || (second_side == third_side) :isosceles else :scalene end end end end class TriangleError < StandardError def message "illegal triangle" end end
true
d818d4cb448ed176558ebda7d09e9e5ed4d513f9
Ruby
iomaraa/hw_week_07_day_01_Ruby_Loops
/rubyhw.rb
UTF-8
1,982
3.203125
3
[]
no_license
# x = (1..20).to_a # puts x # Question 1 # i = 1 # while i < 21 do # p i # i = i +1 # end # Question 2 # x = 0 # while x < 201 do # if x % 2 == 0 # p x # end # x = x +1 # end # Question 3 # wolfy = ["Wolfy", "wolf", 16, "Yukon Territory"] # sharky = ["Sharky", "shark", 20, "Left Coast"] # plantee = ["Plantee", "plant", 5000 , "Mordor"] # porgee = ["Porgee", "Porg", 186, "Ahch-To"] # dart = ["D'Art" , "Demogorgan Dog", 2, "Upside Down"] # plantee[2]= 5001 # wolfy[3]= 'Gotham City' # dart.push('Hawkins') # wolfy[0]= "GameBoy" # p plantee # p wolfy # p dart # Question 4 # ninja = ['Donatello', 'Leonardo', 'Raphael', 'Michaelangelo'] # i =0 # while i < 4 do # ninja[i] = ninja[i].upcase # i = i +1 # end # p ninja # Question5 # favMov = ['Jaws', 'The Fellowship of the Ring', 'Howl\'s Moving Castle', 'Django Unchained', 'Cloud Atlas', 'The Usual Suspects', 'Toy Story', 'Conan the Barbarian', 'Titanic', 'Harry Potter', 'Fried Green Tomatoes', 'Volver', 'Oculus', 'Seven', 'Black Panther', 'Imitation of Life', 'Snatch', 'Fast and Furious'] # favMov.shift # favMov= favMov.sort # favMov.pop # favMov.push("Guardians of the Galaxy") # Newlist = ["Spiderman","Thor","Ant-Man"] # faves = favMov + Newlist # if faves.include?("Imitation of Life") # p 'already here' # else # faves.push("Imitation of Life") # end # p faves # Question6 # whereIsWaldo = [["Timmy", "Frank"], "Eggbert", # ["Lucinda", "Jacc", "Neff", "Snoop"], # ["Petunia", ["Baked Goods", "Waldo"]]]; # whereIsWaldo[2][2]= "No one" # p whereIsWaldo[3][1][1] # puts whereIsWaldo # Question7 # i = 1 # while i < 21 do # p "Love me, pet me! HSSSSSS!" # if i % 2 === 0 # p "...human...why you taking pictures of me?..." # end # i = i + 1 # end i = 0 loop do p 'Hello' input = gets.chomp i = i + 1 if input == 'Goodbye' break end end
true
fffc95007f7260e1d97b113d072e47737d935c49
Ruby
rainbough/class-day-1
/bank.rb
UTF-8
3,028
4.03125
4
[]
no_license
class BankAccount def initialize @balance = 0.00 puts "What is the first name on this account?" @first_name = gets.chomp puts "What is the last name on this account?" @last_name = gets.chomp puts "Please deposit money into this account." @available_credit = 10000.00 @credit_balance = 0.00 end def deposit(amount) if amount > 0 @balance = @balance + amount else puts "Please enter a positive number." end end def withdraw(amount) if amount > 0 if @balance < amount puts "You are attempting to withdraw more funds than you have available. You will be charged a $10 fee." @balance = @balance - 10.00 puts "Remaining balance: #{@balance}" else @balance = @balance - amount puts "Remaining balance: #{@balance}" end else puts "Please enter a positive number." end end def use_credit_card puts "What is the purchase amount you would like to put on your credit card?" purchase = gets.chomp.to_f if purchase > @available_credit puts "Decline. Credit available: #{@available_credit}" else @credit_balance = @credit_balance + purchase @available_credit = @available_credit - purchase puts "Your credit debt is now #{@credit_balance} and your available credit is #{@available_credit}." end end def pay_credit_card_bill puts "How much would you like to pay to your credit card bill?" bill_pay = gets.chomp.to_f if bill_pay < @balance && bill_pay > 0 @balance = @balance - bill_pay @credit_balance = @credit_balance - bill_pay @available_credit = @available_credit + bill_pay elsif bill_pay < 0 puts "Please enter a positive amount." else puts "You do not have #{bill_pay} funds available in your account." end end def balance_check puts "This account belongs to #{@first_name} #{@last_name} and has $#{@balance} available." puts "You have a balance of $#{@credit_balance} on your credit card and $#{@available_credit} available credit." end def interest accrued_interest = @credit_balance * 0.015 puts "Your interest is #{accrued_interest}" end end #menu account = BankAccount.new() command = "active" while command != "q" puts "__________________________" puts "What would you like to do?" puts "Commands: int = calculate interest" puts "pay = pay credit card bill." puts "bc = balance check" puts "use = use credit card" puts "dep = deposit" puts "with = withdraw" puts "q = quit" command = gets.chomp.downcase case command when command = "pay" account.pay_credit_card_bill when command = "int" account.interest when command = "bc" account.balance_check when command = "use" account.use_credit_card when command = "dep" puts "How much would you like to deposit?" amount=gets.chomp.to_f account.deposit(amount) when command = "with" puts "How much would you like to withdraw?" amount=gets.chomp.to_f account.withdraw(amount) when "q" break else puts "input not understood" end end
true
e82ace0e79fc548d3557778bda408ea937812faf
Ruby
Carlumbo/programming-univbasics-4-array-simple-array-manipulations-online-web-prework
/lib/intro_to_simple_array_manipulations.rb
UTF-8
1,132
3.578125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def using_push(colors_of_the_rainbow, next_color) next_color = "violet" updated_array = colors_of_the_rainbow.push(next_color) end def using_unshift(bouroughs_in_nyc, new_neighborhood) new_neighborhood = "Staten Island" updated_array = bouroughs_in_nyc.unshift(new_neighborhood) end def using_pop(contenients) updated_array = contenients.pop end def pop_with_args(dog_breeds) small_dogs= dog_breeds.pop(2) end def using_shift(my_favorite_cities) im_so_over_this_city= my_favorite_cities.shift end def shift_with_args(ice_cream_brands) brands_removed= ice_cream_brands.shift(2) end def using_concat(my_favorite_things, more_favs) all_my_favs = my_favorite_things.concat(more_favs) end def using_insert(list_of_programming_languages, another_language) new_array = list_of_programming_languages.insert(4,another_language) end def using_uniq(haircuts) new_array = haircuts.uniq end def using_flatten(array) new_array = array.flatten end def using_delete(instructors,string) no_offense_steven = instructors.delete("Steven") end def using_delete_at(array,integer) new_array = array.delete_at(2) end
true
2620f82a8e468821ff5d04e444895815c1da5a39
Ruby
kares/ruby_speech
/lib/ruby_speech/grxml/item.rb
UTF-8
5,110
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'ruby_speech/xml/language' module RubySpeech module GRXML ## # # The item element is one of the valid expansion elements for the SGR rule element # # http://www.w3.org/TR/speech-grammar/#S2.4 --> XML Form # # The item element has four (optional) attributes: weight, repeat, repeat-prob, and xml:lang (language identifier) # # http://www.w3.org/TR/speech-grammar/#S2.4.1 # http://www.w3.org/TR/speech-grammar/#S2.3 # # A weight may be optionally provided for any number of alternatives in an alternative expansion. Weights are simple positive floating point values without exponentials. Legal formats are "n", "n.", ".n" and "n.n" where "n" is a sequence of one or many digits. # # A weight is nominally a multiplying factor in the likelihood domain of a speech recognition search. A weight of 1.0 is equivalent to providing no weight at all. A weight greater than "1.0" positively biases the alternative and a weight less than "1.0" negatively biases the alternative. # # repeat has several valid values... # # Any repeated legal rule expansion is itself a legal rule expansion. # # Operators are provided that define a legal rule expansion as being another sub-expansion that is optional, that is repeated zero or more times, that is repeated one or more times, or that is repeated some range of times. # # repeat probability (repeat-prob) indicates the probability of successive repetition of the repeated expansion. It is ignored if repeat is not specified # # xml:lang declares declaration declares the language of the grammar section for the item element just as xml:lang in the <grammar> element declares for the entire document # class Item < Element %w{ rule one_of ruleref tag token }.each { |f| require "ruby_speech/grxml/#{f}" } include XML::Language Inf = 1.0 / 0.0 register :item VALID_CHILD_TYPES = [Nokogiri::XML::Element, Nokogiri::XML::Text, OneOf, Item, String, Ruleref, Tag, Token].freeze ## # # The optional weight attribute # # @return [Float] # def weight read_attr :weight, :to_f end ## # # The weight attribute takes a positive (floating point) number # NOTE: the standard says a format of "n" is valid (eg. an Integer) # TODO: possibly support string and check to see if its a valid digit with regex... # # @param [Numeric] w # def weight=(w) raise ArgumentError, "A Item's weight attribute must be a positive floating point number" unless w.to_s.match(/[^0-9\.]/) == nil and w.to_f >= 0 self[:weight] = w end ## # # The repeat attribute # # @return [String] # def repeat repeat = read_attr :repeat return nil unless repeat if repeat.include?('-') min, max = repeat.split('-').map &:to_i (min || 0)..(max || Inf) else repeat.to_i end end ## # # TODO: Raise ArgumentError after doing checking. See # http://www.w3.org/TR/speech-grammar/#S2.5 # # @param [String] r # def repeat=(r) r = "#{r.min}-#{r.max unless r.max == Inf}" if r.is_a?(Range) r = r.to_s error = ArgumentError.new "A Item's repeat must be 0 or a positive integer" raise error unless r.match(/[^0-9-]/) == nil and r.scan("-").size <= 1 raise error if case di = r.index('-') when nil r.to_i < 0 # must be 0 or a positive number when 0 true # negative numbers are illegal else if di == r.length - 1 # repeat 'm' or more times, m must be 0 or a positive number r[0, r.length - 1].to_i < 0 else # verify range m,n is valid m, n = r.split('-').map &:to_i m < 0 || n < m end end self[:repeat] = r end ## # # The optional repeat-prob attribute # # @return [Float] # def repeat_prob read_attr :'repeat-prob', :to_f end ## # @param [Numeric] ia # def repeat_prob=(rp) raise ArgumentError, "A Item's repeat probablity attribute must be a floating point number between 0.0 and 1.0" unless rp.to_s.match(/[^0-9\.]/) == nil and rp.to_f >= 0 and rp.to_f <= 1.0 self['repeat-prob'] = rp end def <<(arg) raise InvalidChildError, "A Item can only accept String, Ruleref, Tag or Token as children" unless VALID_CHILD_TYPES.include? arg.class super end def eql?(o) super o, :weight, :repeat end def regexp_content # :nodoc: case repeat when Range "#{super}{#{repeat.min},#{repeat.max unless repeat.max == Inf}}" when Integer "#{super}{#{repeat}}" else super end end end # Item end # GRXML end # RubySpeech
true
0efa8ce56d3e7aba2855cd6a1b12c6965f3726fb
Ruby
shaneoston72/takeaway-challenge
/lib/order.rb
UTF-8
510
2.96875
3
[]
no_license
class Order attr_reader :time, :order def initialize(menu) @time = Time.now @order = {} @menu = menu end def add_item(dish, quantity) dish = dish.downcase.to_sym @order[dish] = quantity if @menu.on_menu?(dish) end def total total = 0 @order.each do |dish, quantity| total += (@menu.price dish.downcase.to_sym) * quantity end total end def compile_order # @selection.each do |item| # item.each do |dish| # menu.items end end
true
b9dd851615039e1608b16c791874a4454281ea43
Ruby
akicho8/albatro
/lib/albatro/graphviz_support.rb
UTF-8
6,129
2.625
3
[]
no_license
# -*- coding: utf-8 -*- require "fileutils" require "pathname" module Albatro module GraphvizSupport def initialize(*) super @@gv_auto_index ||= 0 @@gv_auto_index += 1 @gv_id = @@gv_auto_index end # # 文字列やPNGやバイナリを返す # # to_dot #=> dot_as_string と同等 # to_dot(:binary => true) #=> pngの中身 # to_dot(:file => "output.png") #=> "output.png" の出力 # def to_dot(options = {}) case when options[:binary] dot_as_binary(options) when options[:file] dot_as_file(options[:file], options) else dot_as_string(options) end end protected # ノードの文字列 # オーバーライド必須 def dot_label_attrs(options = {}) attrs = {} attrs[:label] = (options[:label] || simple_value).to_s.gsub(/"/, "\\\"") attrs end # 自分からtargetを指す矢印 # オーバーライドしたかったらどうぞ def dot_edge_attrs(target, options = {}) {} end # graphviz用のユニークなノード名 # オーバーライド禁止 def dot_node_name "n#{@gv_id}" end # graphviz用のラベル # オーバーライド禁止 def dot_label_name(options = {}) %{#{dot_node_name} [#{dot_params_to_s(dot_label_attrs(options))}];} end # dot表記の文字列を返す # # 例: # # digraph sample { # graph [charset="UTF-8", ranksep=0.2, size="10.0,10.0", rankdir=LR]; # node [fontsize=20, fontname="azukiP"] # root -> n1 -> n2 -> n3; # root -> n4 -> n5 -> n6; # root -> n7 -> n8 -> n9; # n1 [label="私"]; # n2 [label="は"]; # n3 [label="ファミコン"]; # n4 [label="は"]; # n5 [label="ファミコン"]; # n6 [label="です"]; # n7 [label="ファミコン"]; # n8 [label="です"]; # n9 [label="。"]; # } # def dot_as_string(options = {}) options = { # dot_as_string 自身のオプション :root_display => true, # 自分を含めるか? :root_label => nil, # 自分を含める場合に指定すると名前を変更できる # テンポラリ :depth => 0, # graphviz の設定 :charset => "UTF-8", # 文字コード(日本語を使う場合はこれ必須) :fontname => "azukiP", # ノードのフォント(あずきプロポーショナル) :rankdir => "LR", # グラフの向き :ranksep => nil, # ノードのレベル毎の間隔 :nodesep => nil, # ノードとノードの間隔 :size => nil, # グラフ全体の大きさ。"10.0,10.0" のように指定。1.0 = 2.54センチ :fontsize => nil, # ノードのフォントサイズ :concentrate => true, # エッジが重なりそうな場合、束ねるか? :labelloc => "t", # グラフのラベルをつけるとしたらどこに?(t=上) }.merge(options) out = [] if options[:depth] == 0 out << "digraph g#{object_id} {" graph = dot_params_build(options, [:labelloc, :fontname, :charset, :ranksep, :nodesep, :size, :rankdir, :graph_label, :concentrate], {:graph_label => :label}) node = dot_params_build(options, [:fontname, :fontsize]) out << " graph [#{graph}];" out << " node [#{node}];" if options[:root_display] out << " " + dot_label_name(options.merge(:label => options[:root_label])) end end children.each{|node| out << " " + node.dot_label_name(options) if options[:root_display] || options[:depth] >= 1 out << " #{dot_node_name} -> #{node.dot_node_name} [#{dot_params_to_s(dot_edge_attrs(node, options))}];" end out << node.dot_as_string(options.merge(:depth => options[:depth].next)) } if options[:depth] == 0 out << "}" out.flatten.join("\n") else out end end private # # バイナリを返す # # dot_as_binary => "PNG......" # def dot_as_binary(options = {}) options = { :format => "png", }.merge(options) IO.popen("dot -q -T#{options[:format]}", "w+"){|io| io.puts dot_as_string(options) io.close_write io.read } end # # ファイルに出力 # # dot_as_string("output.png") # def dot_as_file(filename, options = {}) filename = Pathname(filename).expand_path unless filename.extname.match(/(png|jpg|gif)/) raise ArgumentError, "#{filename} の拡張子を画像の拡張子にしてください" end FileUtils.makedirs(filename.dirname) filename.open("w"){|f|f << dot_as_binary(options)} end def dot_params_build(options, keys, table = {}) hash = {} keys.each{|key| unless options[key].nil? hash[table[key] || key] = options[key] end } dot_params_to_s(hash) end def dot_params_to_s(hash) hash.collect{|k, v|"#{k}=\"#{v}\""}.join(", ") end end end if $0 == __FILE__ require "simple_node" root = Albatro::SimpleNode.new(:word => "(root)") node1 = root.nodes_create(:word => "アヒル") node4 = root.nodes_create(:word => "チルドレン") node5 = node4.nodes_create(:word => "です") node2 = node1.nodes_create(:word => "と") node3 = node1.nodes_create(:word => "です") node2.nodes_create(:word => "ピエロ") node2.nodes_create(:word => "カモ") # puts root.tree root.to_dot(:binary => true) root.to_dot(:file => "_output1.png", :root_display => true) root.to_dot(:file => "_output2.png", :root_display => true, :root_label => "トップ") root.to_dot(:file => "_output3.png", :root_display => false) root.to_dot(:file => "_output4.png", :root_display => false, :graph_label => "グラフのラベル") # puts root.to_dot end
true
6404d664eb61ed20027e184175955f366bef9bfb
Ruby
joshado/triton-internal-gem
/spec/api_base_spec.rb
UTF-8
11,811
2.53125
3
[ "MIT" ]
permissive
require 'spec_helper' describe "ApiMapping" do let(:fakeapi) do Class.new(Triton::ApiBase) do self.name = "fakeapi" call("TestMethod", { :method => :post, :path => "/testmethod/path" }) call("GetMethod", { :path => "/testmethod/path" }) call("GetThing", { :path => "/things/:thing/foo" }) call("PostThing", { :method => :post, :path => "/things/:thing" }) call("GetThingWithQueryString", { :path => "/things/:thing/foo?a=b" }) call("SetTags", { :method => :post, :path => "/thing/:id/tag", :body_param => :metadata }) call("QueryStringParameterExisting", { :path => '/test/path?a=1', :method => :post, :querystring => 'foo' }) call("QueryStringParameterNew", { :path => '/test/path2', :method => :post, :querystring => ['bar', :baz] }) call('ArrayResponse', :path => '/array/response', :response => :json_lines) call('CustomResponse', :path => '/array/response', :response => lambda { |a| Marshal.load(a) }) end end describe "instance behaviour" do subject { fakeapi.new("TestMethod") } it "should memoise the request" do first_request = subject.request expect(subject.request.object_id).to eq(first_request.object_id) end it "should pass execute to the request" do expect(subject.request).to receive(:execute).and_return("{}") subject.execute end it "should have a shortcut to execute the method from the class" do expect(fakeapi).to respond_to(:execute) end end describe "init - when the call isn't defined" do it "should raise an exception if the call isn't recognised" do expect { fakeapi.new("Unknown") }.to raise_exception(Triton::ApiBase::UnknownCall) end it "should be a NoMethodError" do expect(Triton::ApiBase::UnknownCall.new).to be_a(NoMethodError) end end describe "response handling" do subject { fakeapi.new("TestMethod") } it "should decode the payload as JSON" do allow(subject.request).to receive(:execute).and_return('{"something": "here"}') expect(subject.execute).to eq({"something" => "here"}) end it "should return a hash with indifferent key access" do allow(subject.request).to receive(:execute).and_return('{"something": "here", "nested": {"something": "inner"}}') expect(subject.execute[:something]).to eq("here") expect(subject.execute['something']).to eq("here") expect(subject.execute[:nested][:something]).to eq("inner") expect(subject.execute[:nested]['something']).to eq("inner") end it "should decode the payload as an array of JSON lines if :parse => :json_lines is set" do api = fakeapi.new("ArrayResponse") allow(api.request).to receive(:execute).and_return(%[{"line":1}\n{"line":2}\n{"line":3}\n]) expect(api.execute).to be_an(Array) end it "should allow a custom parser to be provided" do api = fakeapi.new("CustomResponse") allow(api.request).to receive(:execute).and_return(Marshal.dump('hello' => 'world')) expect(api.execute).to eq('hello' => 'world') end end describe "response exception handling" do subject { fakeapi.new("TestMethod") } let(:exception) { RestClient::Exception.new(double("Response", :body => "body"))} before do # Simulate a RestClient exception when we execute allow(subject.request).to receive(:execute).and_raise(exception) end it "should re-raise the original RestClient exception if the body doesn't contain valid JSON" do expect { subject.execute }.to raise_exception(exception) end it "should raise a Triton::RemoteException if the JSON decoded, but doesn't contain a 'code' field" do allow(exception.response).to receive(:body).and_return("{}") expect { subject.execute }.to raise_exception(Triton::RemoteException) end it "should synthesize an exception class if a 'code' is present" do allow(exception.response).to receive(:body).and_return('{"code": "ItScrewedUp"}') expect { subject.execute }.to raise_exception(Triton::RemoteExceptions::ItScrewedUp) end it "should be possible to raise a RemoteException with a struct" do expect do raise Triton::RemoteExceptions::RemoteException, { 'code' => 'ResourceNotFound', 'message' => 'VM not found'} end.to raise_exception(Triton::RemoteExceptions::ResourceNotFound, 'VM not found') end it "should be possible to raise a RemoteException with a message directly" do expect do raise Triton::RemoteExceptions::ResourceNotFound, 'VM not found' end.to raise_exception(Triton::RemoteExceptions::ResourceNotFound, 'VM not found') end it "should be possible to raise a RemoteException from a mock with a message in a test" do object = Object.new allow(object).to receive(:crash).and_raise(Triton::RemoteExceptions::ResourceNotFound, 'VM not found') expect do object.crash end.to raise_exception(Triton::RemoteExceptions::ResourceNotFound, 'VM not found') end end describe "request" do subject { fakeapi.new("TestMethod").request } it "should build a RestClient request" do expect(subject).to be_a(RestClient::Request) end it "should use the specified name as the first part of the hostname" do expect(subject.url).to match(%r{^http://fakeapi}) end it "should append the configured suffix to the hostname" do expect(subject.url).to match(%r{^http://fakeapi.test/}) end it "should append the path to the url" do expect(URI.parse(subject.url).path).to eq("/testmethod/path") end it "should set the method" do expect(subject.method).to eq(:post) end it "should default the method to :get" do expect(fakeapi.new("GetMethod").request.method).to eq(:get) end end describe "path parametisation" do it "should replace any :<word> values with the associated argument" do expect(URI.parse(fakeapi.new("GetThing", :thing => "IDENT").request.url).path).to eq("/things/IDENT/foo") end it "should URL encode any value" do expect(URI.parse(fakeapi.new("GetThing", :thing => "IDE/NT").request.url).path).to eq("/things/IDE%2FNT/foo") end it "should exclude any arguments used to build the URL from the query string of GET requests" do request = fakeapi.new("GetThing", 'thing' => "123", :foo => "bar").request expect(URI.parse(request.url).query).to eq("foo=bar") end it "should exclude any arguments used to build the URL from the payload of non-get requests" do request = fakeapi.new("PostThing", 'thing' => "123", :foo => "bar").request expect(URI.parse(request.url).path).to eq("/things/123") expect(JSON.load(request.payload)).to eq("foo" => "bar") end end it "should accept application/json" do expect(fakeapi.new("GetThing", :thing => "IDENT").request.headers['Accept']).to eq("application/json") expect(fakeapi.new("TestMethod").request.headers['Accept']).to eq("application/json") end describe "arguments - GET requests" do subject { fakeapi.new("GetMethod", :foo=>"bar/baz", :bar=>"baz").request } it "should urlencode and append to the URL as a query string" do expect(URI.parse(subject.url).query).to eq("foo=bar%2Fbaz&bar=baz") end it "should append carefully if there is already a query string" do url = fakeapi.new("GetThingWithQueryString", :thing => 1, :foo=>"bar", :bar=>"foo/bar").request.url expect(URI.parse(url).query).to eq("a=b&foo=bar&bar=foo%2Fbar") end it "should not set a payload" do expect(subject.payload).to be_nil end it "should not set a Content-Type header" do expect(subject.headers["Content-Type"]).to be_nil end end describe "arguments - non-GET" do subject { fakeapi.new("TestMethod", 'some' => 'args', :live => :here).request } it "should set the Content-Body to application/json" do expect(subject.headers["Content-Type"]).to eq("application/json") end it "should serialize the arguments to JSON as the payload" do expect(JSON.load(subject.payload)).to eq({'some' => 'args', 'live' => 'here'}) end end it "should generate a snake-case function call from the Api name" do expect(fakeapi).to respond_to(:get_method) end describe "camelise" do it "should return a camel_case string" do expect("foo".camelise).to eq("Foo") expect("foo_bar".camelise).to eq("FooBar") expect("foo_bar_baz".camelise).to eq("FooBarBaz") expect("foo______bar_baz".camelise).to eq("FooBarBaz") end it "should return nil if an unexpected string is encountered" do expect("something-wrong".camelise).to eq(nil) expect("Capsyousay".camelise).to eq(nil) expect("wow!".camelise).to eq(nil) end end describe "test_mode" do before do Triton.test_mode = true end it "should raise an exception if a request is attempted when test_mode is set" do expect do fakeapi.test_method() end.to raise_exception(Triton::TestModeLeak) end it "should include the Api call name in the exception" do expect do fakeapi.test_method() end.to raise_exception do |ex| expect(ex.message).to include("TestMethod") end end it "should include the call route in the exception" do expect do fakeapi.test_method() end.to raise_exception do |ex| expect(ex.message).to include("POST /testmethod/path") end end it "should include the parameters in the exception" do expect do fakeapi.test_method("param" => "value") end.to raise_exception do |ex| expect(ex.message).to include(%{"param": "value"}) end end end describe "body_param option" do subject { fakeapi.new('SetTags', :id => "the-id", :other_param => "other_value", :key => 'value', :metadata => { "tag1" => "value1", "tag2" => "value2" })} it "should write the value of the body_param to the body" do expect(JSON.load(subject.request.payload)).to eq({ "tag1" => "value1", "tag2" => "value2" }) end it "should set any additional parameters on the query-string" do expect(URI.parse(subject.request.url).query).to eq("other_param=other_value&key=value") end end describe ":querystring parameters" do it "should not change the query string if the parameters aren't included" do expect(fakeapi.new('QueryStringParameterExisting', {}).request.url).to eq('http://fakeapi.test/test/path?a=1') expect(fakeapi.new('QueryStringParameterNew', {}).request.url).to eq('http://fakeapi.test/test/path2') end it "should set the query string when there is no existing query string" do expect(fakeapi.new('QueryStringParameterNew', {'bar' => 'barvalue'}).request.url).to eq('http://fakeapi.test/test/path2?bar=barvalue') expect(fakeapi.new('QueryStringParameterNew', {'bar' => 'barvalue','baz' => 'bazvalue'}).request.url).to eq('http://fakeapi.test/test/path2?bar=barvalue&baz=bazvalue') end it "should append the query string parameter correctly to existing parameters" do expect(fakeapi.new('QueryStringParameterExisting', {'foo' => 'foovalue'}).request.url).to eq('http://fakeapi.test/test/path?a=1&foo=foovalue') end it "should write other parameters to the payload as normal" do expect(fakeapi.new('QueryStringParameterExisting', {'foo' => 'foovalue', 'bar' => 'barvalue'}).request.payload.to_s).to eq(%[{"bar":"barvalue"}]) end end end
true
19a03c64ec9f4c11169197adcfefed5ba2af12bc
Ruby
powersjcb/notes
/w1-review/merge_sort.rb
UTF-8
481
3.953125
4
[]
no_license
require 'byebug' class Array def merge_sort return self if count < 2 left, right = self.take(count/2), self.drop(count/2) merge(left.merge_sort, right.merge_sort) end def merge(left, right) # merges two sorted arrays onto the end of Array merged_array = [ ] until left.empty? || right.empty? merged_array << ((left.first < right.first) ? left.shift : right.shift) end merged_array + left + right end end [1,2,3,4].merge_sort
true
7eab7609b10d9126ac8f7a312ce8e8277f93aaf0
Ruby
jamesdphillips/throttling
/lib/throttling/limit.rb
UTF-8
1,190
2.859375
3
[ "MIT" ]
permissive
module Throttling class Limit attr_accessor :name, :interval, :limit, :values, :default_value def initialize(name, opts = {}) self.name = name self.interval = opts[:period].to_i self.limit = opts[:limit].nil? ? nil : opts[:limit].to_i self.values = opts[:values] self.default_value = opts[:default_value] end def interval=(val) raise ArgumentError, "Invalid or no 'period' parameter in the #{name} limit." if val < 1 @interval = val end def limit=(val) raise ArgumentError, "Invalid 'limit' parameter in the #{name} limits." if !val.nil? && val < 0 @limit = val end def self.from_action(action) limits = Throttling.limits[action] if limits[:period] if limits[:values] limits[:values] = limits[:values].sort_by { |name, params| params && params[:limit] } end [new('global', limits)] else limits.sort_by do |name, params| params && params[:period] end.map do |name, params| new(name, params) end end end def ttl interval - Time.now.to_i % interval end end end
true
e2904c11be064bc3201c8b9dfc570fc398622ef8
Ruby
makevoid/jasonette-roda-app
/comp/audio.rb
UTF-8
571
2.578125
3
[]
no_license
def Audio(url:, text: "Play >", type: "label", feature: {}) { "type": type, "text": text, "action": { "type": "$audio.play", "options": { "url": url } } }.merge feature end # from the default example - head.actions # # { # actions: { # hahaha: { # type: "$audio.play", # options: { # url: "https://s3-us-west-2.amazonaws.com/fm.ethan.jason/hahaha.mp3" # } # } # } # } # example: # audio_url = "https://jasonette.github.io/Jasonpedia/assets/1up.mp3" # # Audio( # url: audio_url # )
true
e7faf018dced0a1c5cac29f4fb97251b80bc60dd
Ruby
YizheWill/aA_Classwork
/W4D5/two_sum_problem.rb
UTF-8
1,360
3.921875
4
[]
no_license
def bad_two_sum?(array, target) (0...array.length-1).each do |idx1| (idx1+1...array.length).each do |idx2| return true if array[idx1] + array[idx2] == target end end false end arr = [0, 1, 5, 7] # p bad_two_sum?(arr, 6) # => should be true # p bad_two_sum?(arr, 10) # => should be false def ok_two_sum?(array, target) sorted = array.sort count = 0 sorted.each do |num| count += 1 if num.zero? end sorted.delete(0) if count = 1 && target = 0 sorted.each do |num| number_we_want = target - num res = b_search(array, number_we_want) return true if res end # sorted.each_with_index do |n, i| # res = b_search(array[0...i] + array[i+1..-1], target-n) # return true if res # end return false end def b_search(array, target) return nil if array.length == 0 mid = array.length/2 case array[mid] <=> target when 0 return mid when 1 b_search(array[0...mid], target) else search = b_search(array[mid+1..-1], target) search && search + mid + 1 end end # p ok_two_sum?([3,4,5,6, 1000], 1000) # p ok_two_sum?([-1, 0, 1, 2,2,3], 0) def two_sum_good?(array, target) hash = Hash.new(0) array.each do |num| return true if hash[target-num] == 1 hash[num] += 1 end false end #O(n) # p two_sum_good?([3,4,5,6, 1000], 1000) # p two_sum_good?([ 0, 1, 2,2,3], 0)
true
b66dc0addb331cb8834c04a631f9106bab9cbb78
Ruby
hj1994412/teleost_genomes_immune
/S23_S25_MHC_I_target_sequence_generation_and_read_count/scripts/produce_majority_rule_consensus.rb
UTF-8
3,292
3.609375
4
[]
no_license
# This script produces majority rule consensus sequences from aligned fasta files. # Run this with like # ruby produce_majority_rule_consensus.rb -f inputfilename -o outputfilename class String def identical_with(str) return false unless str.class == String str1 = self.downcase str2 = str.downcase identical = true if str1.size != str2.size identical = false else str1.size.times do |x| if str1[x] != "n" and str1[x] != "-" and str1[x] != "?" and str2[x] != "n" and str2[x] != "-" and str2[x] != "?" identical = false unless str1[x] == str2[x] end end end identical end def informative_sites count = 0 str = self.downcase str.size.times {|x| count += 1 unless str[x] == "n" or str[x] == "-" or str[x] == "?"} count end def more_informative_than(str) return true unless str.class == String str1 = self.downcase str2 = str.downcase more_informative = false more_informative = true if str1.informative_sites > str.informative_sites more_informative end end # Read the command line arguments. if ARGV.include?("-f") fasta_file_name = ARGV[ARGV.index("-f")+1] else raise "The fasta file name should be specified with the '-f' option!" end if ARGV.include?("-o") output_file_name = ARGV[ARGV.index("-o")+1] else raise "The output file name should be specified with the '-o' option!" end # Open the fasta file. fasta_file = File.open(fasta_file_name) fasta_lines = fasta_file.readlines fasta_file.close # Read the fasta file. seqs = [] fasta_lines.each do |l| line = l.strip if line[0..0] == ">" seqs << "" elsif line != "" seqs.last << line end end # Make sure all sequences have the same length. 1.upto(seqs.size-1) {|x| raise "Sequences in file #{fasta_file_name} do not have the same length!" unless seqs[x].size == seqs[0].size} # Remove identical sequences. seqs.uniq! # Remove sequences that are identical with others, taking into account gaps and ns. 0.upto(seqs.size-2) do |x| (x+1).upto(seqs.size-1) do |y| unless seqs[x] == nil if seqs[x].identical_with(seqs[y]) if seqs[x].more_informative_than(seqs[y]) seqs[y] = nil else seqs[x] = nil end end end end end seqs.compact! consensus = "" seqs[0].size.times do |pos| characters_at_this_site = [] frequencies_of_characters_at_this_site = [] only_gaps_at_this_pos = true seqs.size.times {|x| only_gaps_at_this_pos = false if seqs[x][pos..pos] != "-"} if only_gaps_at_this_pos consensus << "-" else seqs.size.times do |x| character = seqs[x][pos..pos].downcase unless ["n","-","?"].include?(character) if characters_at_this_site.include?(character) frequencies_of_characters_at_this_site[characters_at_this_site.index(character)] += 1 else characters_at_this_site << character frequencies_of_characters_at_this_site << 1 end end end if characters_at_this_site == [] consensus << "n" else consensus << characters_at_this_site[frequencies_of_characters_at_this_site.index(frequencies_of_characters_at_this_site.max)] end end end output_string = ">Consensus\n" while consensus.size > 0 do output_string << "#{consensus.slice!(0..59)}\n" end output_string << "\n" output_file = File.new(output_file_name,"w") output_file.write(output_string) output_file.close
true