text
stringlengths
10
2.61M
# Provides helper methods for writing webpack script/stylesheet tags module WebpackHelper WEBPACK_DEV_SERVER = "http://localhost:9123" WEBPACK_PROD = "https://tidywiki.com" def digested_bundle_name(bundle_name) manifest = Rails.root.join("public", "assets", "manifest.json") raise "Have you run webpack? manifest.json doesn't exist" unless File.exist?(manifest) JSON.parse(File.read(manifest))[bundle_name] end def digested_tag(bundle_name) return yield digested_bundle_name(bundle_name) if Rails.env.development? Rails.cache.fetch(["assets", bundle_name, refspec]) do yield digested_bundle_name(bundle_name) end end def webpack_include_tags(bundle_name) if stylesheet_extracted?(bundle_name) safe_join [webpack_include_javascript_tag(bundle_name), webpack_include_stylesheet_tag(bundle_name)] else if Rails.env.production? webpack_include_javascript_tag(bundle_name, host: WEBPACK_PROD) else webpack_include_javascript_tag(bundle_name, host: WEBPACK_DEV_SERVER) end end end def webpack_include_javascript_tag(bundle_name, host: nil) digested_tag("#{bundle_name}.js") do |digested_bundle_name| content_tag("script", "", src: "#{host}/assets/#{digested_bundle_name}") end end def webpack_include_stylesheet_tag(bundle_name) digested_tag("#{bundle_name}.css") do |digested_bundle_name| tag("link", rel: "stylesheet", type: "text/css", href: "/assets/#{digested_bundle_name}") end end def stylesheet_extracted?(bundle_name) !!digested_bundle_name(bundle_name + ".css") end def refspec @_refspec ||= `git rev-parse --short HEAD 2>/dev/null`.strip end end
class GenresController < Sinatra::Base # sets root as the parent-directory of the current file set :root, File.join(File.dirname(__FILE__), '..') # sets the view directory correctly set :views, Proc.new { File.join(root, "views") } get '/genres' do @genres = Genre.all erb :genres end get '/genres/new' do erb :new_song end get '/genres/:slug' do @genre = Genre.find_by_slug(params[:slug]) erb :genre end end
require 'rails_helper' RSpec.describe Room, type: :model do context 'with two rooms' do before(:all) do @date_from = "01.06.2018" @date_to = "15.06.2018" @name = "standart" @room1 = Room.create!(id:1, number_of_people: 3, name: @name ) @room2 = Room.create!(id:2, number_of_people: 3, name: @name ) @client = Client.new(name: "Bill", surname: "Clinton") Reservation.create!(date_from: @date_from, date_to: @date_to, room: @room1, client: @client) end after(:all) do Reservation.destroy_all Room.destroy_all Client.destroy_all end # it 'free_rooms? must ruturn true' do # expect(Room.free_rooms?(@type_of_room, @date_from, @date_to)).to eq(true) # end # # it 'free_rooms must return room2' do # expect(Room.free_rooms(@type_of_room, @date_from, @date_to).first).to eq(@room2) # end # # it 'free_rooms? must ruturn false' do # Reservation.create!(date_from: @date_from, date_to: @date_to, room: @room2, client: @client) # expect(Room.free_rooms?(@type_of_room, @date_from, @date_to)).to eq(false) # end end end
class AddFiledsToCoupons < ActiveRecord::Migration def change add_column :coupons, :status, :string add_column :coupons, :benefit_type_id, :integer add_column :coupons, :user_id, :integer end end
require "i18n" module OrdinalizeFull I18n.load_path += Dir[File.join(__dir__, "ordinalize_full/locales/*.yml")] def ordinalize(in_full: false, noun_gender: :masculine , noun_plurality: :singular) in_full ? ordinalize_in_full(noun_gender: noun_gender , noun_plurality: noun_plurality) : ordinalize_in_short(noun_gender: noun_gender , noun_plurality: noun_plurality) end alias_method :ordinalize_full, \ def ordinalize_in_full(noun_gender: :masculine , noun_plurality: :singular) case I18n.locale when :es value = I18n.t("ordinalize_full.n_#{self}", throw: false, default: "") if(value == "") value = [I18n.t("ordinalize_full.n_#{(self/10)*10}", throw: true),I18n.t("ordinalize_full.n_#{self%10}", throw: true)].join(" ") end if noun_gender == :feminine value = value.split.map{|value| value.chop << "a"}.join(" ") end if noun_plurality == :plural value << "s" end # if value ends in 1 or 3 shorten it , if it is masculine singular if value.end_with?("ero") value = value.chop end value else I18n.t("ordinalize_full.n_#{self}", throw: true) end rescue ArgumentError raise NotImplementedError, "Unknown locale #{I18n.locale}" end private def ordinalize_in_short(noun_gender: :masculine , noun_plurality: :singular) abs_number = to_i.abs suffix = case I18n.locale when :en if (11..13).cover?(abs_number % 100) "th" else case abs_number % 10 when 1 then "st" when 2 then "nd" when 3 then "rd" else "th" end end when :fr self == 1 ? "er" : "ème" when :it "°" when :nl [8, 1, 0].include?(self % 100) || self % 100 > 19 ? "ste" : "de" when :es full_ordinalized_val = ordinalize_in_full(noun_gender: noun_gender ,noun_plurality: noun_plurality) if full_ordinalized_val.end_with?("er") ".ᵉʳ" elsif full_ordinalized_val.end_with?("a") ".ᵃ" elsif full_ordinalized_val.end_with?("o") ".ᵒ" elsif full_ordinalized_val.end_with?("os") ".ᵒˢ" elsif full_ordinalized_val.end_with?("as") ".ᵃˢ" end end [self, suffix].join end end
module Bitstamp module Net def self.to_uri(path) return "https://www.bitstamp.net/api#{path}/" end def self.curl(verb, path, options={}) verb = verb.upcase.to_sym c = Curl::Easy.new(self.to_uri(path)) if Bitstamp.configured? options[:key] = Bitstamp.key options[:nonce] = (Time.now.to_f*10000).to_i.to_s options[:signature] = HMAC::SHA256.hexdigest(Bitstamp.secret, options[:nonce]+Bitstamp.client_id.to_s+options[:key]).upcase end c.post_body = options.to_query c.http(verb) return c end def self.get(path, options={}) request = self.curl(:GET, path, options) return request end def self.post(path, options={}) request = self.curl(:POST, path, options) return request end def self.patch(path, options={}) request = self.curl(:PATCH, path, options) return request end def self.delete(path, options={}) request = self.curl(:DELETE, path, options) return request end end end
class SafeValidator < ActiveModel::EachValidator def virus_found?(file) io = begin StringIO.new(File.read(file.file.file)) rescue StringIO.new(file.file.read) end client = ClamAV::Client.new response = client.execute(ClamAV::Commands::InstreamCommand.new(io)) response.class.name == 'ClamAV::VirusResponse' end def validate_each(record, attribute, value) if !value.nil? && !CheckConfig.get('clamav_service_path').blank? && self.virus_found?(value) record.errors.add(attribute.to_sym, "validation failed! Virus was found.") end end end
class HomeController < ApplicationController before_filter :go_to_app? def index @user = User.new @user.company = nil end end
# frozen_string_literal: true class CinemaHallSerializer include JSONAPI::Serializer attributes :name, :row_number, :row_total_seats has_many :screenings end
Popcorn::Application.routes.draw do devise_for :users resources :movies root "pages#home" get "about" => "pages#about" get "search" => "pages#search" get "recommendations" => "pages#recommendations" get "test" => "pages#test" get "action" => "pages#action" get "adventure" => "pages#adventure" get "animation" => "pages#animation" get "comedy" => "pages#comedy" get "documentary" => "pages#documentary" get "drama" => "pages#drama" get "family" => "pages#family" get "fantasy" => "pages#fantasy" get "filmnoir" => "pages#filmnoir" get "horror" => "pages#horror" get "musical" => "pages#musical" get "mystery" => "pages#mystery" get "romance" => "pages#romance" get "scifi" => "pages#scifi" get "sport" => "pages#sport" # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
module VisionboardHelper def show_intention? @show_intention == true end alias :show_intentions? :show_intention? def show_gratitude? ! show_intention? end def url_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE new_intention_url when Intention::VISIONBOARD_ADDITION_COMPONENT_TYPE intentions_url when Thank::COMPONENT_TYPE new_thank_url when Thank::VISIONBOARD_ADDITION_COMPONENT_TYPE thanks_url end end def type_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE "intention" when Intention::VISIONBOARD_ADDITION_COMPONENT_TYPE "intention" when Thank::COMPONENT_TYPE "thank" when Thank::VISIONBOARD_ADDITION_COMPONENT_TYPE "thank" end end def title_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE "Set intention" when Intention::VISIONBOARD_ADDITION_COMPONENT_TYPE "Visualize Intentions" when Thank::COMPONENT_TYPE "Build Gratitude" when Thank::VISIONBOARD_ADDITION_COMPONENT_TYPE "Visualize Gratitude" end end def description_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE ["Set a new intention.", "Affirm your future.", "What is your intention?"].sample when Intention::VISIONBOARD_ADDITION_COMPONENT_TYPE ["Add photos to your vision.", "Visualize your future.", "Expand your vision."].sample when Thank::COMPONENT_TYPE ["Be thankful.", "Express gratitude.", "Say thank you."].sample when Thank::VISIONBOARD_ADDITION_COMPONENT_TYPE ["Add photos to your vision.", "Show your gratitude.", "Expand your vision."].sample end end def activity_description_for_visionboard_action_item(ai) case ai.component_type when Intention::COMPONENT_TYPE "Identify something you want to affirm in your life." when Intention::VISIONBOARD_ADDITION_COMPONENT_TYPE "Add photos to visually affirm things you want in your life." when Thank::COMPONENT_TYPE "Identify something you appreciate in your life." when Thank::VISIONBOARD_ADDITION_COMPONENT_TYPE "Add photos to remind you of what you appreciate." end end def other_users_vision_board_entry rand(2)==0 ? other_users_vision_board_intention_entry : other_users_vision_board_thank_entry end def other_users_vision_board_intention_entry prefix = [ "A app user intends to be", "Anonymous intends to be", ].sample intent = [ "a great father.", "romantic.", "friendly.", "listen actively.", "happy.", "rich.", "stronger.", "vibrant.", "running everyday ", "saving the world", "eating healthy", "living strong", "being awesome", "smiling ", "on top of the world", "having my cake", "in love with life", "curious ", "excited", "a photographer", "a writer", "reporting the truth", "a rock", "a good son", "#WINNING", "a great listener", "the best kisser", "superman", "sincere", "a safe driver", "fearless", "responsible", "a social butterfly", "the life of the party", "my dad's friend", "my sister's rock", "a good example", ].sample "#{prefix} #{intent}" end def other_users_vision_board_thank_entry g = %w{ Acceptance Accountability Animals Animals Apologies Art Art August Bathing%Suits Bathing%Suits best%friends Blogs Blogs Books Books cartoons Challenges Change Choice Clothes Color Comfort Compassion Compliments Computers Coziness Creativity Dancing Disappointment Dogs Dreams Driving Earth Emotions Encouragement Energy Enthusiasm Excitement Family family Fears Films Food Forgiveness Freedom Friends friends Fun Generosity Gifts Glitter good%health Good%News Gratitude Growing%Up hands Handwriting Happiness Health Hearing heart Heartbreaks Holidays home Honesty Hope Housing Hugs Imagination Independence Inspiration Journals Joy Justin%Bieber Kind%strangers Kindness Kisses Knowledge Laughter Laughter Laughter Laughter Laughter Laughter legs Les%Miserable Life Life Life Life Life Life Love Love love lungs Magic Memories mind mistakes Mother%nature Movies Music Music Music my%health my%immune%system my%iPhone my%phone my%soul%mate Nature New%Places New%Places Now Opinions Organization Oxygen Pain Palm%trees parents Passion Patience Paw%prints Peace Photographs Plans Poetry Positivity Productivity Quality%Time Questions Rain Rainbows Rainbows Respect rest Sadness Safe%Landings Safety salt school Seasons Shoes Sight Sleep sleep Smell Smiles Snow Speech Spring Stars Strength Summer Sunrise Sunset Sunshine Surprises Taste Teachers Tears Technology The%Earth The%Moon%and%Stars The%Sun Therapy Thoughts Time Touch Twitter Water Weekends Winter Wonderlands Words health%insurance my%sister my%twitter%feed the%BBC good%food clean%water cartoons being%healthy good%friends music%shows a%glass%of%wine having%a%job the%Internet }.sample.gsub('%',' ') "Someone is grateful for #{g}." end def intention_image_url(intention, index) intention.image_urls[index] end def thank_image_url(thank, index) thank.image_urls[index] end end
module Output require 'colorize' def convert_to_color(number) case when number == 0 return :blue when number == 1 return :yellow when number == 2 return :red when number == 3 return :green when number == 4 return :magenta when number == 5 return :white end end def print_square(number, feedback = " ") color = convert_to_color(number) print feedback.colorize(:color => :black, :background => color) end def print_all_squares(code) code.each { |number| print_square(number) } end def clear_square print "\b\b\b\b\b\b\b" end def clear_all_squares 4.times { clear_square } end end module Input require 'io/console' def read_char #thanks @acook! STDIN.echo = false STDIN.raw! input = STDIN.getc.chr if input == "\e" then input << STDIN.read_nonblock(3) rescue nil input << STDIN.read_nonblock(2) rescue nil end ensure STDIN.echo = true STDIN.cooked! return input.upcase end def wants_to_be_codemaker? puts "Enter M if you want to be the codemaker" puts "Enter B if you want to be the codebreaker\n\n" user_choice = read_char until (user_choice == "M" or user_choice == "B") puts "Enter only M or B\n" user_choice = read_char end return true if user_choice == "M" return false if user_choice == "B" end def ask_for_secret_code secret_code = [] puts "Enter the 4 numbers that make the secret code\nAll numbers must be >= 1 and <= 5" 4.times do |i| print "#{i+1}º digit: " user_input = gets.chomp until (/[1-5]/).match(user_input) do print "Enter an integer >= 1 and <= 5: " user_input = gets.chomp end secret_code.push(user_input.to_i) end puts return secret_code end end
require 'rails_helper' RSpec.describe 'Hangar API', type: :request do before do @user = User.create(name: 'User1', password: 'Password1') end describe 'GET /hangar.json' do include_examples 'requires authentication', '/hangar.json' context 'with no owned ships' do before do get '/hangar.json', headers: authentication_for(@user) end it 'returns 200 (OK)' do expect(response).to have_http_status(:ok) end it 'returns a blank array' do expect(json.count).to eq(0) end end context 'with owned ships' do before do @ship_ownerships = (1..5).map do ship = create(:ship) ShipOwnership.create(user: @user, ship: ship) end get '/hangar.json', headers: authentication_for(@user) end it 'returns 200 (OK)' do expect(response).to have_http_status(:ok) end it 'returns all owned ships' do expect(json.count).to eq(@ship_ownerships.count) end end end describe 'POST /hangar.json' do before do @ship = create(:ship) end include_examples 'requires authentication', '/hangar.json', :post context 'with an invalid Ship ID' do before do post '/hangar.json', params: { ship: 9999 }, headers: authentication_for(@user) end it 'returns 404 (Not Found)' do expect(response).to have_http_status(:not_found) end it 'includes an error message' do expect(json).to have_key('error') end end context 'if the user owns the Ship' do before do ShipOwnership.create(user: @user, ship: @ship) post '/hangar.json', params: { ship: @ship.id }, headers: authentication_for(@user) end it 'returns 400 (Bad Request)' do expect(response).to have_http_status(:bad_request) end it 'includes an error message' do expect(json).to have_key('error') end end context 'with valid params' do before do post '/hangar.json', params: { ship: @ship.id }, headers: authentication_for(@user) end it 'returns 201 (Created)' do expect(response).to have_http_status(:created) end it 'creates a corresponding ShipOwnership' do ship_ownership = ShipOwnership.where(user: @user).where(ship: @ship).first expect(ship_ownership).not_to be_nil end end end describe 'DELETE /hangar/:id.json' do before do @ship = create(:ship) @ship_ownership = ShipOwnership.create(user: @user, ship: @ship) end include_examples 'requires authentication', '/hangar/1.json', :delete context 'with a Ship the user does not own' do before do delete '/hangar/9999.json', headers: authentication_for(@user) end it 'returns 400 (Bad Request)' do expect(response).to have_http_status(:bad_request) end it 'contains an error message' do expect(json).to have_key('error') end end context 'with valid params' do before do delete "/hangar/#{@ship.id}.json", headers: authentication_for(@user) end it 'returns 200 (OK)' do expect(response).to have_http_status(:ok) end it 'deletes the corresponding ShipOwnership' do expect { @ship_ownership.reload }.to raise_error(ActiveRecord::RecordNotFound) end end end end
require 'spec_helper' describe CreditCardsController do describe 'new edit and update' do before(:each) do @customer = create(:customer) user = create(:user, customer: @customer) @credit_card = create(:credit_card, customer_id: @customer.id) controller.stub(:current_user).and_return(user) end describe 'GET #new' do it 'renders the new template' do get :new response.should render_template('new') end end describe 'GET #edit' do it 'assigns the customer' do get :edit assigns(:customer).should eq @customer end it 'assigns the associated billing address' do get :edit assigns(:credit_card).should eq @credit_card end end describe 'POST #update' do it 'assigns the customer' do post :update assigns(:customer).should eq @customer end end end describe 'POST #create' do before(:each) do @customer = create(:customer) user = create(:user, customer: @customer) store = create(:store) controller.stub(:current_user).and_return(user) controller.stub(:current_store).and_return(store) end it 'saves the billing address to the customer' do expect { post :create, {customer_id: @customer.id, credit_card: {number: '4242424242424242', expiration_month: '12', expiration_year: '2015', security_code: '111'} } }.to change(CreditCard, :count).by(1) end end end
require "rails_helper" RSpec.feature "UserCanLogoutAndSeeHomePage", type: :feature do context "when logged in" do let!(:user) { User.create(username: "Mitchell", password: "password") } it "can see a login when not logged in" do visit root_path expect(page).to have_content("Login") end it "can log out" do visit root_path click_link "Login" fill_in "Username", with: "Mitchell" fill_in "Password", with: "password" click_button "Login" click_link "Logout" expect(page).to_not have_content("Logout") expect(page).to have_content("Login") expect(current_path).to eq root_path end end end
class AddTelephoneAndEmailToAdminPeople < ActiveRecord::Migration def change add_column :admin_people, :telephone, :string add_column :admin_people, :email, :string end end
class CreateTasks < ActiveRecord::Migration[5.0] def change create_table :tasks do |t| t.string :name, null:false t.string :description t.string :status, default: 0, null: false t.belongs_to :card, foreign_key: { on_delete: :cascade } t.timestamps end end end
class Book < ActiveRecord::Base has_many :feeds, dependent: :destroy has_and_belongs_to_many :users, join_table: :schedules end
module Freelancer module Payment #Retrieve the current user's balance and the details of the last transaction. # #http://developer.freelancer.com/GetAccountBalanceStatus def getAccountBalanceStatus request "/Payment/getAccountBalanceStatus.json" end #Retrieve the list of transactions and details for an account. # #http://developer.freelancer.com/GetAccountTransactionList # #<b>Optional:</b> # :count => (Default: 50) # :page => (Default: 0) # :datefrom => Get transactions from the date # :dateto => Get transactions up to the date def getAccountTransactionList *args options=fill_args [ :count,:page,:datefrom,:dateto ],[],*args request "/Payment/getAccountTransactionList.json", options end #Make a request to withdraw funds. # #http://developer.freelancer.com/RequestWithdrawal # #<b>Required:</b> # :amount => Withdraw amount # :method => :paypal | :moneybooker | :wire | :paynoneer (default) # :additionaltext => Required for wire withdraw # :paypalemail => Required for paypal withdraw # :mb_account => Required for moneybooker withdraw # :description => Required for wire withedraw # :country_code => Required for wire withdraw def requestWithdrawal *args options=fill_args [ :amount, :method, :additionaltext, :paypalemail, :mb_account, :description, :country_code ],[ :amount, :method, :additionaltext, :paypalemail, :mb_account, :description, :country_code ],*args request "/Payment/requestWithdrawal.json", options end #Create a milestone (escrow) payment. # #http://developer.freelancer.com/CreateMilestonePayment # #<b>Required:</b> # :projectid => Mandatory if Partial or Full payment for a project. # :amount => Milestone amount # :touserid => Userid or username create milestone payment to # :tousername => Userid or username create milestone payment to # :reasontext => Text attached to transfer # :reasontype => partial|full|other def createMilestonePayment *args options=fill_args [ :projectid, :amount, :touserid, :tousername, :reasontext, :reasontype ],[ :projectid, :amount, :reasontext, :reasontype ],*args if options[:touserid]==nil && options[:tousername]==nil raise "touserid or tousername is required" end if options[:touserid]!=nil && options[:tousername]!=nil raise "Both touserid and tousername is not allowed" end request "/Payment/createMilestonePayment.json", options end #Cancel milestone # #http://developer.freelancer.com/CancelMilestone # #<b>Required:</b> # :transactionid => Transaction Id def cancelMilestone *args options=fill_args [:transactionid],[:transactionid],*args request "/Payment/cancelMilestone.json", options end #Get the list of incoming and outgoing milestone(escrow) payments. # #http://developer.freelancer.com/GetAccountMilestoneList # #<b>Optional:</b> # :type => Incoming(default) or Outgoing # :count => (Default: 50) # :page => (Default: 0) def getAccountMilestoneList *args options=fill_args [:type,:count,:page],[],*args request "/Payment/getAccountMilestoneList.json", options end #View the list of withdrawals that have been requested and are pending. # #http://developer.freelancer.com/GetAccountWithdrawalList # #<b>Optional:</b> # :type => Incoming(default) or Outgoing # :count => (Default: 50) # :page => (Default: 0) def getAccountWithdrawalList *args options=fill_args [:type,:count,:page],[],*args request "/Payment/getAccountMilestoneList.json", options end #Send a request to payer for releasing an incoming milestone payment. # #http://developer.freelancer.com/RequestReleaseMilestone # #<b>Required:</b> # :transactionid => Transaction Id def requestReleaseMilestone *args options=fill_args [:transactionid],[:transactionid],*args request "/Payment/requestReleaseMilestone.json", options end #Release a milestone payment. # #http://developer.freelancer.com/ReleaseMilestone # #<b>Required:</b> # :transactionid => Transaction Id # :fullname => Fullname of the payer def releaseMilestone *args options=fill_args [:transactionid,:fullname],[:transactionid,:fullname],*args request "/Payment/releaseMilestone.json", options end #Retrieve the balance for current user. # #http://developer.freelancer.com/GetBalance def getBalance request "/Payment/getBalance.json" end #Validate the transfer action before actually transfer. # #http://developer.freelancer.com/PrepareTransfer # #<b>Required:</b> # :projectid => Mandatory if Partial or Full payment for a project. # :amount => Min $30 Validation # :touserid => Userid transfer money to. # :reasontype => partial|full|other def prepareTransfer *args options=fill_args [:projectid,:amount,:touserid,:reasontype],[:projectid,:amount,:touserid,:reasontype],*args request "/Payment/prepareTransfer.json", options end #Retrieve the withdrawal fee # #http://developer.freelancer.com/GetWithdrawalFees def getWithdrawalFees request "/Payment/getWithdrawalFees.json" end #Retrieve the project list and selected freelancer for transferring. # #http://developer.freelancer.com/GetProjectListForTransfer def getProjectListForTransfer request "/Payment/getProjectListForTransfer.json" end end end
require 'spec_helper' feature 'user can record manufacturer', %q{ As a car salesperson I want to record a car listing's manufacturer So that I can keep track of its manufacturer } do # I must specify a manufacturer name and country. # If I do not specify the required information, # I am presented with errors. # If I specify the required information, # the manufacturer is recorded and # I am redirected to enter another new manufacturer. context 'with valid attributes' do it 'registers a manufacturer' do visit '/manufacturers/new' fill_in 'Name', with: 'BMW' select "Germany", from: "Country", :match => :first click_on 'Create Manufacturer' expect(Manufacturer.count).to eq(1) expect(current_path).to eq new_manufacturer_path end end context 'with invalid attributes' do it 'shows error if required fields are missing' do visit '/manufacturers/new' click_on 'Create Manufacturer' expect(page).to_not have_content("Manufacturer Added to Listing") expect(page).to have_content("can't be blank") expect(page).to have_content("can't be blank") end end end
class PeopleController < ApplicationController def index @people = Person.all end def show @person = Person.find(params[:id]) end def new @person = Person.new @person.addresses.build end def create @person = Person.new(permit_params) if @person.save redirect_to people_path else render 'new' end end def edit @person = Person.find(params[:id]) end def update @person = Person.find(params[:id]) if @person.update(permit_params) redirect_to people_path else render 'edit' end end def destroy @person = Person.find(params[:id]) @person.destroy redirect_to people_path end #Esta no es la mejor forma. Ugly... def form_address @address = Person.find(params[:id]).addresses.build end def add_address person = Person.find(params[:id]) @address = person.addresses.build(permit_params_address) if person.save redirect_to people_path else render 'form_address' end end #End of ugly shit private def permit_params params.require(:person).permit(:name, :lastname, :birthday, :gender, :ci, addresses_attributes: [:line1, :line2, :city, :country, :zipcode]) end def permit_params_address params.require(:address).permit(:line1, :line2, :country, :city, :zipcode) end end
# encoding: utf-8 require_relative "support" class SeaBattle # It's random positions for new ship class RandomShip include ::SeaBattle::Support def initialize(board, length = 1) @board = board.board @length = length @horizontal = board.horizontal @vertical = board.vertical end # Add new Ship on board def add_ship if Random.rand(2) == 0 return if add_ship_of(:vertical) return if add_ship_of(:horizontal) else return if add_ship_of(:horizontal) return if add_ship_of(:vertical) end end def ship_positions(row, column, direct) result = [] @length.times do |offset| if direct.eql?(:vertical) result << [row + offset, column] if row + offset < @vertical else result << [row, column + offset] if column + offset < @horizontal end end result end def area_ship_positions(row, column, direct) result = [] first_row = row - 1 first_column = column - 1 last_row, last_column = row + 1, column + 1 last_row += @length - 1 if direct.eql?(:vertical) last_column += @length - 1 if direct.eql?(:horizontal) vertical_range = (first_row..last_row).to_a & (0...@vertical).to_a horizontal_range = (first_column..last_column).to_a & (0...@horizontal).to_a vertical_range.product(horizontal_range) end def add_ship_of(direct) mixed_board_positions.each do |row, column| next if direct.eql?(:vertical) and row + @length - 1 >= @vertical next if direct.eql?(:horizontal) and column + @length - 1 >= @horizontal if is_area_empty?(row, column, direct) positions = ship_positions(row, column, direct) positions.map do |row, column| @board[row][column].add_ship end return positions end end nil end def is_area_empty?(row, column, direct) area_ship_positions(row, column, direct).each do |row_index, column_index| return false if @board[row_index][column_index].is_in_ship? end true end end end
# frozen_string_literal: true require 'spec_helper' module Uploadcare module Entity RSpec.describe Group do subject { Group } it 'responds to expected methods' do %i[create info store delete].each do |method| expect(subject).to respond_to(method) end end context 'info' do before do VCR.use_cassette('upload_group_info') do @group = subject.info('bbc75785-9016-4656-9c6e-64a76b45b0b8~2') end end it 'represents a file group' do file_fields = %i[id datetime_created datetime_stored files_count cdn_url url files] file_fields.each do |method| expect(@group).to respond_to(method) end end it 'has files' do expect(@group.files).not_to be_empty expect(@group.files.first).to be_a_kind_of(Uploadcare::Entity::File) end end describe 'id' do it 'returns id, even if only cdn_url is defined' do group = Group.new(cdn_url: 'https://ucarecdn.com/bbc75785-9016-4656-9c6e-64a76b45b0b8~2') expect(group.id).to eq 'bbc75785-9016-4656-9c6e-64a76b45b0b8~2' end end describe 'load' do it 'performs load request' do VCR.use_cassette('upload_group_info') do cdn_url = 'https://ucarecdn.com/bbc75785-9016-4656-9c6e-64a76b45b0b8~2' group = Group.new(cdn_url: cdn_url) group.load expect(group.files_count).not_to be_nil end end end describe 'delete' do it 'deletes a file group' do VCR.use_cassette('upload_group_delete') do response = subject.delete('bbc75785-9016-4656-9c6e-64a76b45b0b8~2') expect(response).to eq('200 OK') end end it 'raises error for nonexistent file' do VCR.use_cassette('group_delete_nonexistent_uuid') do uuid = 'nonexistent' expect { subject.delete(uuid) }.to raise_error(RequestError) end end end end end end
class MessagesController < ApplicationController def index @messages = current_user.received_messages end def new @users = current_user.friends @message = Message.new end def create @message = Message.new(message_params) @message.sender_id = current_user.id if @message.save flash[:success] = "Sent message" redirect_to messages_path else flash[:error] = "Error: #{@message.errors.full_messages.to_sentence}" render 'new' end end def sent_messages @messages = current_user.sent_messages end def show @message = Message.find_by(id: params[:id]) if @mesasge.nil? @message.mark_as_read! :for => current_user end end private def message_params params.require(:message).permit(:body,:recipient_id) end end
class Udemy include Capybara::DSL attr_reader :title, :subtitle def initialize @title = find(:xpath, "//h1[@class='udlite-heading-xl clp-lead__title clp-lead__title--small']") @subtitle = find("[class='udlite-text-md clp-lead__headline']") end def getTextTitle @title.text end def getTextSubtitle @subtitle.text end end
class Quizmaster def start system ('clear') puts " ____ __ ___________ __ ___ __ / __ \/ / / / _/__ / / |/ /___ ______/ /____ __________ / / / / / / // / / / / /|_/ / __ `/ ___/ __/ _ \/ ___/ ___/ / /_/ / /_/ // / / /__ / / / / /_/ (__ ) /_/ __/ / (__ ) \___\_\____/___/ /____/ /_/ /_/\__,_/____/\__/\___/_/ /____/ " puts "****** Welcome to QuizMasters! ******" puts "" puts " How good is your Knowledge?" puts "" puts "*************************************" puts "" puts "Please enter (Y)- to Start Quiz (N) - Exit)" result = gets.chomp while result != 'Y' && result.chomp != 'N' puts "Please enter (Y - Start Quiz N - Exit)" result = gets.chomp end case result when "Y" return true when "N" return false end end def load_user puts "Enter you User Name" result = gets.chomp u1 = User.find_by_name(result) if u1 == nil u1 = User.create(name: result) puts "You user has been created. Please use the User Name next time.." sleep 0.75 end return u1 end def start_quiz end end
class MailSorting def initialize @posts = [] end def add_post(new_post) @posts << new_post end #the number of parcels sent to some city def num_parcels_sent_to_city(city) count = 0 @posts.each {|x| count +=1 if x.city == city} return count end #how many parcels with value higher than 10 were sent def parcels_value_more10 count = 0 @posts.each {|x| count +=1 if x.value > 10} return count end #what is the most popular address def popular_address adresses = Hash.new(0) @posts.each {|x| adresses["#{x.city} #{x.street} #{x.house} #{x.apartment}"] += 1 } adresses.max_by {|key,val| val}.first end def print @posts.each {|x| puts x} end end class Post attr_accessor :city, :street, :house, :apartment, :destination, :value def initialize(city, street, house, apartment, destination, value) @city, @street, @house, @apartment, @destination, @value = city, street, house, apartment, destination, value end def to_s "Post #{city}, #{street}, #{house}, #{apartment}, #{destination}, #{value}" end end mail_sorting = MailSorting.new mail_sorting.add_post(Post.new("Dnepr","street","17","145","Jeck",5)) mail_sorting.add_post(Post.new("Dnepr","street","18","145","John",15)) mail_sorting.add_post(Post.new("Dnepr","street","11","145","John",25)) mail_sorting.add_post(Post.new("Dnepr","street","17","145","John",9)) mail_sorting.add_post(Post.new("Dnepr","street","17","145","John",2)) mail_sorting.add_post(Post.new("Dnepr","street","17","145","John",1)) mail_sorting.print puts mail_sorting.num_parcels_sent_to_city("Dnepr") puts mail_sorting.parcels_value_more10 puts mail_sorting.popular_address
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest test "should get home" do get root_path assert_response :success assert_select "title", "War-Rails" end test "should get regolamento" do get regolamento_url assert_response :success assert_select "title", "Regolamento" end test "should get infoclan" do get infoclan_url assert_response :success assert_select "title", "InfoClan" end test "should get aboutapp" do get aboutapp_url assert_response :success assert_select "title", "AboutApp" end test "should get contatti" do get contatti_url assert_response :success assert_select "title", "Contatti" end end
require './player' require './db/song' require './playlist' require './options/list_option' require './options/play_option' require './options/stop_option' require './options/search_option' require './options/exit_option' require './options/playlist_view_option' require './watcher' # Requirements # # Your Jukebox should be able to: # - Provide a list of songs # - Search for a song by title (hint: you can use =~ in PostgreSQL) # - Add a song to a playlist # - Start playing your playlist # # You can store you actual mp3 files in the music directory # and play them using Player.play(filename) # # You can also stop the currently playing song with Player.stop # # You should use a database to store your Jukebox's song library # # Use object orientation and exceptions where appropriate # # Optional: # # Record each time a song is played and generate a report on popular songs. # # Optional 2: # # Record the start and end time stamps for when a song is played and Stopped # Include in your report what % of songs are played through # (Listeners will often skip songs they don't like so this is a good indicator # of whether they like a song or not). # class Jukebox def initialize @options = { 1 => ListOption.new, 2 => SearchOption.new, 3 => PlayOption.new, 4 => PlaylistViewOption.new, 8 => StopOption.new, 9 => ExitOption.new } end def run loop do puts "\nWhat would you like to do?\n" @options.each_pair do |id, option| puts "#{id}: #{option.message}" end puts option = @options[gets.chomp.to_i] option.perform end end end Jukebox.new.run
class ListsController < ApplicationController def new @list = List.new @friends = current_user.friends end def create @list = List.new(list_params) @list.user = current_user if @list.save flash[:success] = "List was successfully created" listUser = ListUser.new(list: @list, user: current_user) listUser.save redirect_to lists_path else render "new" end end def index @lists = current_user.lists end def show @list = List.find(params[:id]) end def destroy @list = List.find(params[:id]) @list.destroy flash[:success] = "List was successfully deleted" redirect_to lists_path end private def list_params params.require(:list).permit(:name, user_ids: []) end end
class CreateCookBooks < ActiveRecord::Migration[5.1] def change create_table :cook_books do |t| t.string :name, limit: 30 t.references :icon t.references :recipe, foreign_key: true t.timestamp :created_at t.timestamp :updated_at t.timestamps end end end
#!/usr/bin/env ruby # wthr.rb # a short script to tell me the weather # by adam defelice (ad.defelice@gmail.com) # the info here is taken from weather.gov # $ wthr hyannis # - prints the weather in hyannis # default location is lowell require 'open-uri' require 'rexml/document' require 'optparse' class WthrReport def initialize parse_args if hourly? print_hourly else print_alert if alert? print_observation end end def parse_args OptionParser.new do |opts| opts.banner = 'Usage: wthr [city] [options]' opts.on('-f [hours]', 'Prints the hourly forecast for [hours]') do |h| @hourly = true @hours_to_show = h end opts.on('-h', '--help', 'Show this message') do puts opts exit end end.parse! ARGV.each do |a| if is_valid_city? a @station = cities[a]['station'] @zone = cities[a]['zone'] @lat = cities[a]['lat'] @lon = cities[a]['lon'] end end end def alert? alert_str = open("http://alerts.weather.gov/cap/wwaatmget.php?x=#{zone}") @alert = REXML::Document.new(alert_str) alert_elem = @alert.elements['feed/entry/title'].text !alert_elem.include? 'There are no active watches, warnings or advisories' end def print_alert puts " alert:", " urgency: #{urgency}", " severity: #{severity}", " \"#{description}\"" end def hourly? @hourly ||= false end def hours_to_show @hours_to_show ||= '12' end def print_hourly puts " hour: #{hours}", " temp: #{temps}", " cloud: #{clouds}", " wind(mph): #{winds}", " humidity: #{humidities}", " precip?: #{precips}" # puts " thunder: #{thunders}" if thunder? # puts " rain: #{rains}" if rain? end def print_observation puts " weather: #{weather}", " temp: #{temp}", " wind: #{wind}", " humidity: #{humidity}%", " dewpoint: #{dewpoint}" end def is_valid_city?(c) cities.has_key? c end def station @station ||= 'KBED' end def zone @zone ||= 'MAZ005' end def lon @lon ||= '-71.32210' end def lat @lat ||= '42.63870' end def alert_data @alert_data ||= get_alert_data end def get_alert_data alert_link = @alert.elements['feed/entry/link'].attributes['href'] REXML::Document.new open(alert_link) end def urgency @urgency ||= alert_data.elements['alert/info/urgency'].text end def severity @severity ||= alert_data.elements['alert/info/severity'].text end def description description_raw = alert_data.elements['alert/info/description'].text @description ||= description_raw.strip.downcase!.gsub("\n","\n ") end def hourly_data @hourly_data ||= get_hourly_data end def get_hourly_data hourly_str = open("http://forecast.weather.gov/MapClick.php?lat=#{lat}&lon=#{lon}&FcstType=digitalDWML") REXML::Document.new hourly_str end def hours @hours ||= format get_hours end def get_hours hours = [] hourly_data.elements.each('dwml/data/time-layout/start-valid-time') do |hour| hours << hour.text[11..12] end hours end def temps @temps ||= format get_temps end def get_temps temps = [] hourly_data.elements.each('dwml/data/parameters') do |temp_type| temp_type.each_element_with_attribute('type', 'hourly') do |hourly_temps| hourly_temps.each do |temp| temps << temp.text end end end temps end def clouds @clouds ||= format get_clouds end def get_clouds clouds = [] hourly_data.elements.each('dwml/data/parameters/cloud-amount/value') do |cloud| clouds << "#{cloud.text}%" end clouds end def winds @winds ||= format get_winds end def get_winds winds = [] hourly_data.elements.each('dwml/data/parameters/wind-speed/value') do |wind| if wind.text.nil? winds << '-' else winds << wind.text end end winds end def humidities @humidities ||= format get_humidities end def get_humidities hums = [] hourly_data.elements.each('dwml/data/parameters/humidity/value') do |hum| hums << "#{hum.text}%" end hums end def precips @precips ||= format get_precips end def get_precips precips = [] hourly_data.elements.each('dwml/data/parameters/probability-of-precipitation/value') do |precip| precips << "#{precip.text}%" end precips end def format an_array an_array.map! do |e| case e.size when 1 e + ' ' when 2 e + ' ' when 3 e + ' ' when 4 e + '' end end an_array[d_t_offset..d_t_offset + hours_to_show.to_i - 1].join(' ') end def d_t_offset @d_t_offset ||= get_d_t_offset end def get_d_t_offset time = Time.new time_str = "#{'0' if time.day < 10}#{time.day.to_s}T" + "#{'0' if time.hour < 10}#{time.hour.to_s}" days_hours.index(time_str)? days_hours.index(time_str) : 0 end def days_hours @days_hours ||= get_days_hours end def get_days_hours days_hours = [] hourly_data.elements.each('dwml/data/time-layout/start-valid-time') do |dh| days_hours << dh.text[8..12] end days_hours end def obs @obs = get_obs end def get_obs obs_str = open("http://www.weather.gov/xml/current_obs/#{station}.xml") REXML::Document.new obs_str end def weather @weather ||= obs.elements['current_observation/weather'].text end def temp @temp ||= obs.elements['current_observation/temperature_string'].text end def wind @wind ||= obs.elements['current_observation/wind_string'].text end def humidity @humidity ||= obs.elements['current_observation/relative_humidity'].text end def dewpoint @dewpoint ||= obs.elements['current_observation/dewpoint_string'].text end def cities { 'lowell' => {'station' => 'KBED', 'zone' => 'MAZ005', 'lat' => '42.63870', 'lon' => '-71.32210'}, 'hyannis' => {'station' => 'KHYA', 'zone' => 'MAZ022', 'lat' => '41.70430', 'lon' => '-70.15590'} } end end WthrReport.new
class SettingsController < ApplicationController before_action :authenticate_user! def index @client = Client.find(current_user.client_id) @center = Center.where(client_id: @client.id) @users = User.where(invited_by_id: current_user.id) end end
require 'test_helper' class TraingSessionsControllerTest < ActionController::TestCase setup do @traing_session = traing_sessions(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:traing_sessions) end test "should get new" do get :new assert_response :success end test "should create traing_session" do assert_difference('TraingSession.count') do post :create, traing_session: { coach: @traing_session.coach, date: @traing_session.date, location: @traing_session.location } end assert_redirected_to traing_session_path(assigns(:traing_session)) end test "should show traing_session" do get :show, id: @traing_session assert_response :success end test "should get edit" do get :edit, id: @traing_session assert_response :success end test "should update traing_session" do put :update, id: @traing_session, traing_session: { coach: @traing_session.coach, date: @traing_session.date, location: @traing_session.location } assert_redirected_to traing_session_path(assigns(:traing_session)) end test "should destroy traing_session" do assert_difference('TraingSession.count', -1) do delete :destroy, id: @traing_session end assert_redirected_to traing_sessions_path end end
# frozen_string_literal: true class Report < ApplicationRecord mount_uploader :picture, PictureUploader belongs_to :user has_many :comments, as: :commentable, dependent: :destroy end
require 'database_connection' class Diaries attr_reader :id, :name, :input def initialize(id:, name:, input:) @id = id @name = name @input = input end def self.all result = DatabaseConnection.query('SELECT * FROM diary_entries') result.map { |entry| Diaries.new(id: entry['id'], name: entry['name'], input: entry['input']) } end def self.create(name:, input:) result = DatabaseConnection.query("INSERT INTO diary_entries (name, input) VALUES('#{name}', '#{input}') RETURNING id, name, input;") Diaries.new(id: result[0]['id'], name: result[0]['name'], input: result[0]['input']) end def self.find(id) return nil unless id result = DatabaseConnection.query("SELECT * FROM diary_entries WHERE id = '#{id}'") Diaries.new(id: result[0]['id'], name: result[0]['name'], input: result[0]['input']) end end
module Vocab No_Player_Connection = 'Non riesco ad ottenere le informazioni online. Controlla la connessione.' Player_Connected = 'Tutto OK, sei online!' Player_Banned = 'Il tuo profilo è stato disattivato.' Player_Disabled = 'Hai disabilitato l\'online.' Maintenance = "I server di gioco sono in manutenzione. Per favore, riprova più tardi." end class Window_OnlineDashboard < Window_Base def initialize(x, y, width, height) super @player = nil refresh end def refresh contents.clear return draw_no_connection if player.nil? draw_player_state draw_current_events(line_height) draw_active_bonuses end # @return [Online_Player] def player @player end def set_player(player) @player = player refresh end def draw_no_connection change_color crisis_color status = Online.service_status if status == :maintenance draw_text_wrapped(0, 0, Vocab::Maintenance) else draw_text_wrapped(0, 0, Vocab::No_Player_Connection) end change_color normal_color end def draw_player_state if player.banned? change_color power_down_color text = Vocab::Player_Banned elsif !$game_system.can_upload? change_color crisis_color text = Vocab::Player_Disabled else change_color power_up_color text = Vocab::Player_Connected end draw_text(0, 0, contents_width, line_height, text, 1) change_color normal_color end def draw_current_events(y) change_color system_color draw_text(0, y, contents_width, line_height, Vocab::Current_Events) change_color normal_color if Event_Service.current_events.size > 0 draw_event_list(y + line_height) else draw_text(0, y + line_height, contents_width, line_height, Vocab::No_Events) end end def draw_event_list(y) Event_Service.current_events.each_with_index do |event, index| _y = y + line_height * index draw_bg_rect(0, _y, contents_width, line_height) draw_text(0, _y, contents_width, line_height, event.name) text = sprintf(Vocab::Event_Dates, event.start_date_s, event.end_date_s) draw_text(0, _y, contents_width, line_height, text, 2) end end def draw_active_bonuses events = Event_Service.current_events exp = events.inject(1) { |sum, event| sum + (event.exp_rate / 100.0) - 1 } gold = events.inject(1) { |sum, event| sum + (event.gold_rate / 100.0) - 1 } drop = events.inject(1) { |sum, event| sum + (event.drop_rate / 100.0) - 1 } ap = events.inject(1) { |sum, event| sum + (event.ap_rate / 100.0) - 1 } bonus = [:exp, :gold, :ap, :drop].select { |bonus| eval(bonus.to_s) != 1} bonus_vocabs = { :exp => 'Punti esperienza', :gold => 'Monete ottenute', :drop => 'Probabilità di drop', :ap => 'PA guadagnati' } return if bonus.size == 0 width = contents_width / 2 y = contents_height - line_height * 2 change_color system_color draw_text(0, y, contents_width, line_height, Vocab::Current_Events) bonus.each_with_index do |rate, index| x = width * (index % 2) yy = y + (line_height * (index / 2)) draw_bg_rect(x + 1, yy + 1, width - 2, line_height - 2) change_color crisis_color draw_text(x + 2, yy, width, line_height, bonus_vocabs[rate]) change_color normal_color draw_text(x, yy, width - 2, line_height, sprintf('x%.02g', eval(rate.to_s)), 2) end end end
class Api::CountriesController < ApplicationController before_action :set_country, only: %i[show] def index @countries = Country.all.order(order: :asc) render json: @countries, only: %i[id name] end def show render json: @country end private def set_country @country = Country.find(params[:id]) end end
module JsonSerialization extend ActiveSupport::Concern def serialize(obj, options = {}) obj.as_json(options) end end
class Users::RegistrationsController < Devise::RegistrationsController def create build_resource(sign_up_params) if sign_up_params[:type] == "Researcher" @email_domain = sign_up_params[:email].split("@")[1] if @university = University.find_by_domain_name(@email_domain) resource.university = @university ResearcherAttribute.create(researcher: resource) else flash[:error] = 'Your email address does not match any of our partnered Universities.' redirect_to new_user_registration_path return end else ParticipantAttribute.create(participant: resource) end resource.save yield resource if block_given? if resource.persisted? flash[:success] = 'Check your inbox to finish the sign up process!' if resource.active_for_authentication? set_flash_message! :notice, :signed_up sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}" expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end protected def sign_up_params params.require(:user).permit(:email, :type) end def after_inactive_sign_up_path_for(resource) new_user_confirmation_path end def after_sign_up_path_for(_resource) studies_path end end
if (!in_list && (is_admin? || is_current_user?(user))) json.extract! user, :id, :name, :email, :fullname, :is_admin, :created_at, :updated_at json.url user_url(user, format: :json) else json.extract! user, :id, :name end
require 'yaml-web-driver/runner/browser_spec_runner' require 'yaml-web-driver/spec/action_spec' require 'yaml-web-driver/spec/page_specs' module YamlWebDriver module Spec class BrowserSpec attr_reader :main, :pages def initialize(browser_spec_docs) action_and_page_specs = browser_spec_docs.partition { |d| !d.is_a? Hash or !d.has_key? 'page' } @main = Spec::ActionSpec.new(action_and_page_specs[0]) @pages = Spec::PageSpecs.new(action_and_page_specs[1]) end def has_page?(page) @pages.has_page? page end def page(page) @pages[page] end # @return [yaml-web-driver::Runner::BrowserSpecRunner] def runner(driver) Runner::BrowserSpecRunner.new(driver, @main.actions, @pages) end end end end
class Voyage < ApplicationRecord belongs_to :vessel has_many :port_calls, dependent: :destroy end
Rails.application.routes.draw do devise_for :users # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'home#index' resources :recipes, only: [:show, :new, :create, :edit, :update, :destroy, :index] do collection do get 'search' get 'favorites' end member do post 'share' post 'favorite' delete 'unfavorite' end end resources :cuisines, only: [:show, :new, :create, :edit, :update] resources :recipe_types, only: [:show, :new, :create, :edit, :update] resources :users, only: [:show, :edit, :update, :index] do get 'recipes' end namespace :api, defaults: { format: 'json' } do resources :recipes, only: [:index, :show] do collection do get 'search' end end end end
Rails.application.routes.draw do get "/", to: redirect("/flights") namespace :api do namespace :v1 do resources :flights end end resources :flights end
class UserGroup < ApplicationRecord validates :group_name, presence: true end
require 'spec_helper' RSpec.describe MenusController, type: :controller do context 'when user not logged in' do describe 'GET #index' do it 'redirects to login page' do get :index expect(response).to redirect_to new_user_session_path end end end context 'when user logged in' do let(:user) { FactoryGirl.create(:user) } subject { FactoryGirl.create(:menu) } before do sign_in user end describe 'GET #index' do it 'renders the :index view' do get :index expect(response).to render_template :index end end describe 'GET #new' do it 'assigns the requested menu item to new menu' do get :new expect(assigns(:menu)).to be_new_record end it 'renders the :new view' do get :new expect(response).to render_template :new end end describe 'GET #show' do it 'assigns the request menu item to subject' do get :show, id: subject expect(assigns(:menu)).to eq(subject) end it 'renders the :show view' do get :show, id: subject expect(response).to render_template :show end end describe 'GET #edit' do it 'assigns the request menu item to subject' do get :edit, id: subject expect(assigns(:menu)).to eq(subject) end it 'renders the :edit view' do get :edit, id: subject expect(response).to render_template :edit end end describe 'DELETE #destroy' do before(:each) { @menu = FactoryGirl.create :menu } it 'deletes the menu_item' do expect do delete :destroy, id: @menu end.to change(Menu, :count).by(-1) end it 'redirects to index' do delete :destroy, id: @menu expect(response).to redirect_to menus_path end end end end
class Team attr_reader :team_id, :franchiseId, :teamName, :abbreviation, :stadium, :link def initialize(line) @team_id = line.split(",")[0] @franchiseId = line.split(",")[1] @teamName = line.split(",")[2] @abbreviation = line.split(",")[3] @stadium = line.split(",")[4] @link = line.split(",")[5] end end
class CreateActRelations < ActiveRecord::Migration def change create_table :act_relations do |t| t.belongs_to :user, index: true, foreign_key: true t.integer :parent_id, comment: 'ID parent', index: true t.integer :child_id, comment: 'ID child', index: true t.datetime :start_date t.datetime :end_date t.string :title t.string :title_reverse t.timestamps null: false end add_index :act_relations, [:parent_id, :child_id], name: 'index_act_parent_child', unique: true rename_index :actor_relations, 'index_parent_child', 'index_actor_parent_child' end end
# Custom hashMap challenge from CodeSignal # You are given an array of query types which should: # insert - key X is set to val Y # addToValue - increase all values by X # addToKey - increase all keys by X # get - return the value at key X # And an array of queries (values) which corresponds to the queryType array # Given test case: queryType = ["insert", "insert", "addToValue", "addToKey", "get"] query = [[1,2], [2,3], [2], [1], [3]] # Goal: implement all the querries and return the sum of all the get queries # My solution: def hashMap(queryType, query) obj = {} i = 0 all_the_gets = [] while i < queryType.size case queryType[i] when 'insert' obj[query[i][0]] = query[i][1] when 'addToKey' obj.transform_keys! { |key| key += query[i][0] } when 'addToValue' obj.transform_values! { |val| val += query[i][0] } when 'get' all_the_gets.push(obj[query[i][0]]) obj[query[i]] end i += 1 end all_the_gets.reduce(:+) end
class CreateImsExports < ActiveRecord::Migration[5.0] def change create_table :ims_exports do |t| t.string :token t.string :tool_consumer_instance_guid t.string :context_id t.string :custom_canvas_course_id t.jsonb :payload t.timestamps end add_index :ims_exports, :token end end
class Question < ActiveRecord::Base has_many :answers has_many :options, dependent: :destroy accepts_nested_attributes_for :options, reject_if: proc { |attributes| attributes['name'].blank? } scope :single_multiple_questions, {:conditions => ['type in ( ? )', ['SingleAnswerQuestion', 'MultipleAnswerQuestion']]} after_update :save_options # validate :question_validate def question_validate errors[:base] << ("1_Question should not be blank") if name.blank? errors[:base] << ("1_Question type should not be blank") if type.blank? end def boolean=(boolean) options.destroy(options) options.reload options.build(boolean) end # Since it is STI we cannot directly assign type so use this method # example: we cannot assign like question.type= # use question.question_type= def question_type=(sType) self[:type]=sType end # We can't directly access the type attribute in question. # we can access that by @question[:type] def question_type self[:type] end def new_options=(new_options) debugger new_options.collect do |option| if option[:name] options.build(option) unless (option[:name].empty? or option[:name].delete(' ').eql?('')) end end end # This setter is only for multiple or single question options # Options will be in the string form seperated by "\n" def text_options=(text_options) text_options.strip.split("\r\n").collect(&:strip).uniq.collect { |name| options.build(:name => name) } end def existing_options=(existing_options) options.reject(&:new_record?).each do |option| attributes = existing_options[option.id.to_s] if attributes and !attributes[:name].empty? and !attributes[:name].delete(' ').eql?('') option.attributes = attributes else options.find(option.id).delete end end end # This method is called in the after_update def save_options debugger options.collect { |option| option.save } end # To get the answer from the params[:questionnaire_submission][:new_answer] hash def get_answer(new_questions) # new_questions = params[:questionnaire_submission][:new_answer] question_type = QUESTION_ANSWER_CONVERTER[self.class.to_s] if ['SingleAnswer', 'MultipleAnswer'].include?(question_type) answers = new_questions[question_type] answer = answers ? answers[self.id.to_s] : nil other_answers = new_questions[SINGLE_MULTIPLE_OTHER_MAP[self.class.to_s]] other_answer = other_answers ? other_answers[self.id.to_s] : nil if question_type == 'MultipleAnswer' [answer, other_answer] else (answer || other_answer || "").to_s end else (new_questions[question_type].values if new_questions[question_type]).to_s end end end
class MoviesController < ApplicationController #include Movies::IndexTools include MoviesHelper::MoviesController #session :on def show id = params[:id] # retrieve movie ID from URI route @movie = Movie.find(id) # look up movie by unique ID # will render app/views/movies/show.<extension> by default end def index logger.info "--PARAMS = #{params}" logger.info "--SESSION = #{session.empty?}" logger.info "--FLASH = #{flash.empty?}" #no-cookied hit @box_states = Hash.new(0) @all_ratings = Movie.ratings_uniq_get @all_ratings.each{|r| @box_states[r]=1} @movies = Movie.select("*") if session.empty? logger.info "--INTO EMPTY SESSION" session[:sorted_by] = "none" session[:ratings] = @box_states logger.info "--INTO EMPTY SESSION - session = #{session}" return end #test params completeness else redirect with updated params <- session if params[:sorted_by].nil? || params[:ratings].nil? params[:sorted_by] = session[:sorted_by] if params[:sorted_by].nil? params[:ratings] = session[:ratings] if params[:ratings].nil? redirect_to movies_path(params) end ##sort ascending per title or release_date @decor_title = nil @decor_release_date = nil if params[:sorted_by] != "none" instance_variable_set("@decor_#{params[:sorted_by]}", "hilite") @movies = @movies.order("#{params[:sorted_by]} ASC") session[:sorted_by] = params[:sorted_by] end @movies = @movies.where(where_or_string(:rating, params[:ratings].keys.length), *params[:ratings].keys) @box_states.each{|k,v| @box_states[k] = 0 if !params[:ratings].has_key?(k)} session[:ratings] = params[:ratings] end def new # default: render 'new' template end def create @movie = Movie.create!(params[:movie]) flash[:notice] = "#{@movie.title} was successfully created." redirect_to movies_path end def edit @movie = Movie.find params[:id] end def update @movie = Movie.find params[:id] @movie.update_attributes!(params[:movie]) flash[:notice] = "#{@movie.title} was successfully updated." redirect_to movie_path(@movie) end def destroy @movie = Movie.find(params[:id]) @movie.destroy flash[:notice] = "Movie '#{@movie.title}' deleted." redirect_to movies_path end def index_ordered_by end end
# Create method `parrot` that outputs a given phrase and # returns the phrase def parrot(calling= "Squawk!") puts calling calling end
class AddRainForecastToCasino < ActiveRecord::Migration def change add_column :casinos, :rain_forecast, :boolean end end
class Store::Indices::InformationController < ApplicationController # GET /store/indices/information # GET /store/indices/information.json def index @store_indices_information = Store::Indices::Information.all respond_to do |format| format.html # index.html.erb format.json { render json: @store_indices_information } end end # GET /store/indices/information/1 # GET /store/indices/information/1.json def show @store_indices_information = Store::Indices::Information.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @store_indices_information } end end # GET /store/indices/information/new # GET /store/indices/information/new.json def new @store_indices_information = Store::Indices::Information.new respond_to do |format| format.html # new.html.erb format.json { render json: @store_indices_information } end end # GET /store/indices/information/1/edit def edit @store_indices_information = Store::Indices::Information.find(params[:id]) end # POST /store/indices/information # POST /store/indices/information.json def create @store_indices_information = Store::Indices::Information.new(params[:store_indices_information]) respond_to do |format| if @store_indices_information.save format.html { redirect_to @store_indices_information, notice: 'Information was successfully created.' } format.json { render json: @store_indices_information, status: :created, location: @store_indices_information } else format.html { render action: "new" } format.json { render json: @store_indices_information.errors, status: :unprocessable_entity } end end end # PUT /store/indices/information/1 # PUT /store/indices/information/1.json def update @store_indices_information = Store::Indices::Information.find(params[:id]) respond_to do |format| if @store_indices_information.update_attributes(params[:store_indices_information]) format.html { redirect_to @store_indices_information, notice: 'Information was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @store_indices_information.errors, status: :unprocessable_entity } end end end # DELETE /store/indices/information/1 # DELETE /store/indices/information/1.json def destroy @store_indices_information = Store::Indices::Information.find(params[:id]) @store_indices_information.destroy respond_to do |format| format.html { redirect_to store_indices_information_index_url } format.json { head :no_content } end end end
class ResourcesController < ApplicationController before_action(:verify_login) before_action(:set_resource) before_action(:verify_edit_or_admin) # DELETE /resources/:id def destroy @resource.destroy() head :no_content end def set_resource() @resource = Resource.find_by('id': params[:id]) @notebook = Notebook.find_by('id' => @resource.notebook_id) flash[:success] = GalleryConfig.external_resources_label + " successfully deleted." end end
require 'test_helper' class ThreeScale::SearchTest < ActiveSupport::TestCase class Model < ActiveRecord::Base self.table_name = 'accounts' include ThreeScale::Search::Scopes scope :by_fancy_scope, ->(value) { where(id: value == '1') } scope :by_another_scope, -> { where(created_at: :column) } end context "fake Model" do teardown do Model.allowed_sort_columns = [] Model.allowed_search_scopes = [] Model.default_search_scopes = [] Model.sort_columns_joins = {} end should "have right methods" do assert Model.respond_to?(:scope_search) assert Model.respond_to?(:order_by) end should "search with non allowed scope" do assert_equal(Model.all, Model.scope_search(:another_scope => "dl")) end should "search with allowed scope" do Model.allowed_search_scopes = ['fancy_scope'] assert_equal(Model.by_fancy_scope('1'), Model.scope_search(:fancy_scope => "1") ) end should "have default scope" do Model.allowed_search_scopes = ['fancy_scope'] Model.default_search_scopes = ['fancy_scope', 'another_scope'] scope = Model.by_another_scope.by_fancy_scope('1') assert_equal(scope, Model.scope_search(:fancy_scope => "1")) end should "order by allowed column with full table name" do Model.allowed_sort_columns = ['created_at'] scope = Model.order('accounts.created_at DESC') assert_equal scope, Model.order_by(:created_at, :desc) end should "order by non allowed column" do assert_equal Model.all, Model.order_by(:unknown, :desc) end end context "Search object" do should "reject blank values" do search = ThreeScale::Search.new :blank => '', :present => 'present' assert_nil search.blank assert 'present', search.present end end context "ServiceContract" do should "can search by service_id and plan_id same time" do FactoryBot.create(:service_plan) service_plan = FactoryBot.create(:service_plan) service = service_plan.service service_contract = FactoryBot.create(:service_contract, :plan => service_plan) query = { "account_query"=>"", "deleted_accounts"=>"0", "service_id"=>service.id, "plan_type"=>"", "plan_id"=>"", "state"=>"" } search = ThreeScale::Search.new(query) assert_equal [service_contract], ServiceContract.scope_search(query).order_by(nil) assert_equal [service_contract], service.account.provided_service_contracts.scope_search(query) end end context "Alert" do should "sort by timestmap" do alert_one = FactoryBot.create(:limit_alert) alert_two = FactoryBot.create(:limit_alert) assert_equal [alert_one, alert_two], Alert.order_by(:timestamp, :asc) end should "sort by timestamp and retain next scope" do assert_equal(Alert.preload(:account).order("alerts.timestamp DESC"), Alert.preload(:account).order_by(:timestamp)) end end context "Cinstance" do should "retain previous scope on search" do abc = FactoryBot.create(:cinstance, :user_key => "abc") bcd = FactoryBot.create(:cinstance, :user_key => "bcd") assert_equal [abc], Cinstance.by_user_key("abc").scope_search(:user_key => 'abc') assert_equal [bcd], Cinstance.by_user_key("bcd").scope_search(:user_key => 'bcd') assert_equal [], Cinstance.by_user_key('abc').scope_search(:user_key => 'bcd') end should "order and search" do account = FactoryBot.create(:account) abc = FactoryBot.create(:cinstance, :name => "abc", :user_account => account) bcd = FactoryBot.create(:cinstance, :name => "bcd", :user_account => account) cde = FactoryBot.create(:cinstance, :name => "cde", :user_account => account) options = {:account => account.id} array = [abc, bcd, cde] assert_equal array, Cinstance.order_by(:name, :asc).scope_search(options).to_a assert_equal array.reverse, Cinstance.order_by(:name, :desc).scope_search(options).to_a assert_equal array, Cinstance.scope_search(options).order_by(:name, :asc) assert_equal array.reverse, Cinstance.scope_search(options).order_by(:name, :desc) end should "work with all scopes" do app = FactoryBot.create(:cinstance, :name => "test") plan = app.plan options = {:account => app.user_account_id, :deleted_accounts => true, :plan_type => "free", :plan_id => plan.id, :type => "Cinstance"} assert_equal [app], Cinstance.order_by(:name).scope_search(options) end end context "ServiceContract" do should "not depend on parameters order" do sc1 = FactoryBot.create(:service_contract) sc2 = FactoryBot.create(:service_contract) plan2 = sc2.plan plan2.update_attribute :setup_fee, 30 assert plan2.paid? assert_equal ServiceContract.scope_search(:plan_id => sc2.plan_id, :plan_type => :paid), ServiceContract.scope_search(:plan_type => :paid, :plan_id => sc2.plan_id) assert_equal ServiceContract.scope_search(:plan_id => sc2.plan_id, :plan_type => :free), ServiceContract.scope_search(:plan_type => :free, :plan_id => sc2.plan_id) end end context "Account" do should "order by country name" do it = FactoryBot.create(:country, :code => "IT", :name => "Italy") zb = FactoryBot.create(:country, :code => "ZB", :name => "Zimbabwe") provider = FactoryBot.create(:provider_account) buyer_it = FactoryBot.create(:buyer_account, :provider_account => provider, :country => it) buyer_zb = FactoryBot.create(:buyer_account, :provider_account => provider, :country => zb) assert_equal [buyer_it, buyer_zb], provider.buyer_accounts.order_by('countries.name', :asc) end end test 'per_page should be minus or equal that MAX_PER_PAGE' do class FooClass < ActionController::Base include ThreeScale::Search::Helpers def params {per_page: 100} end end pagination_params = FooClass.new.send(:pagination_params) assert_equal ThreeScale::Search::Helpers::MAX_PER_PAGE, pagination_params[:per_page] end end
# Chapter 4 Trees and Graphs class Tree attr_accessor :root def initialize(root = Node.new) @root = root end end class Graph attr_accessor :nodes def initialize(nodes) @nodes = nodes end end class Node attr_accessor :value, :children def initialize(value, children = []) @value = value @children = children end def to_s value.to_s end end # 4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. z = Node.new("z") d = Node.new("d") c = Node.new("c", [d]) b = Node.new("b", [c, d]) a = Node.new("a", [b, z]) directed_graph = Graph.new([a, b, c, d, z]) def direct_route(graph) end
class DriverCity < ActiveRecord::Base belongs_to :driver belongs_to :city end
class Product < ActiveRecord::Base # Validations validates :name, presence: { message: 'Tên sản phẩm không được bỏ trống' } validates :price, presence: { message: 'Giá sản phẩm không được bỏ trống' } validates :category_id, presence: { mesage: 'Loại không được bỏ trống' } validates :color_id, presence: { message: 'Màu không được bỏ trống' } validates :size_id, presence: { message: 'Kích thước không được bỏ trống' } validates :description, presence: { message: 'Mô tả không được bỏ trống' } validates :upload_files, presence: { message: 'Phải có ít nhất một hình ảnh' } # / Validations # Associations has_many :order_details has_many :upload_files, foreign_key: 'object_id', dependent: :destroy belongs_to :category belongs_to :color belongs_to :size # / Associations end
class Photograph attr_reader :id, :name, :artist_id, :year def initialize(hash) @id = hash[:id] @name = hash[:name] @artist_id = hash[:artist_id] @year = hash[:year] end end
Upmin.configure do |config| config.models = [:document, :product_category, :product, :order, :slide, :setting] config.colors = [:light_blue, :blue_green, :dark_red, :yellow, :orange, :puprle, :gray, :brown] config.items_per_page = 10 end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) AdminUser.create!(email: 'admin@example.com', password: 'password', password_confirmation: 'password') if Rails.env.development? AdminUser.create!(email: 'chesh@chesh.info', password: 'password', password_confirmation: 'password') if Rails.env.development? Meeting.create([home_team: "Belle Vue Aces", away_team: "Rye House Rockets", date: "2018-06-20", home_rider_1: "Craig Cook", home_rider_2: "Jason Garrity", home_rider_3: "Dan Bewley", home_rider_4: "Rohan Tungate", home_rider_5: "Max Fricke", home_rider_6: "Jye Etheridge", home_rider_7: "Damian Drozdz", away_rider_1: "Krzysztof Kasprzak", away_rider_2: "Aaron Summers", away_rider_3: "Chris Harris", away_rider_4: "Stuart Robson", away_rider_5: "Scott Nicholls", away_rider_6: "Nikolaj Busk Jacobsen", away_rider_7: "Max Clegg"])
require 'rails_helper' RSpec.describe 'Cycle#update', :ledgers, type: :system do before { log_in admin_attributes } context 'when Term' do it 'edits term' do cycle_create id: 1, name: 'Mar', charged_in: 'arrears', cycle_type: 'term', due_ons: [DueOn.new(month: 3, day: 25)] cycle_page = CyclePage.new type: :term cycle_page.load id: 1 expect(cycle_page.title).to eq 'Letting - Edit Cycle' cycle_page.name = 'Jun/Dec' cycle_page.choose 'Arrears' cycle_page.order = '44' cycle_page.due_on month: 6, day: 24 cycle_page.button 'Update Cycle' expect(cycle_page).to be_success expect(Cycle.first.name).to eq 'Jun/Dec' end end context 'when Monthly' do it 'edits monthly' do cycle_create id: 1, name: 'Regular', charged_in: 'arrears', cycle_type: 'monthly', due_ons: [DueOn.new(month: 1, day: 8)], prepare: true cycle_page = CyclePage.new type: :monthly cycle_page.load id: 1 expect(page).to have_text 'Monthly' cycle_page.name = 'New Monthly' cycle_page.choose 'Arrears' cycle_page.order = '21' cycle_page.due_on day: 12, month: 0 cycle_page.button 'Update Cycle' expect(cycle_page).to be_success expect(Cycle.first.name).to eq 'New Monthly' end end it 'aborts on Cancel' do cycle_create id: 1 cycle_page = CyclePage.new cycle_page.load id: 1 cycle_page.button 'Cancel' expect(cycle_page.title).to eq 'Letting - Cycles' end it 'can error' do cycle_create id: 1, name: 'Jan/July' cycle_page = CyclePage.new cycle_page.load id: 1 cycle_page.name = '' cycle_page.button 'Update Cycle' expect(cycle_page).to be_errored end end
require 'test_helper' class TagTest < ActiveSupport::TestCase test "tag should be valid" do tag = Tag.new(name: "test") assert tag.valid? end test "name should be unique" do tag = Tag.new(name: "tag_1") assert_not tag.valid? end end
# frozen_string_literal: true require 'test_helper' class ArticleTest < ActiveSupport::TestCase test 'valid article' do article = Article.new(title: 'Title', text: 'Body text') assert article.valid? end end
class Post < ActiveRecord::Base validates_presence_of :title, :body has_many :comments, :class_name => 'PostComment', :dependent => :destroy end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Crypt # A Context object initialized specifically for the purpose of rewrapping # data keys (decrypting and re-rencryting using a new KEK). # # @api private class RewrapManyDataKeyContext < Context # Create a new RewrapManyDataKeyContext object # # @param [ Mongo::Crypt::Handle ] mongocrypt a Handle that # wraps a mongocrypt_t object used to create a new mongocrypt_ctx_t # @param [ Mongo::Crypt::EncryptionIO ] io An object that performs all # driver I/O on behalf of libmongocrypt # @param [ Hash ] filter Filter used to find keys to be updated. # alternate names for the new data key. # @param [ Mongo::Crypt::KMS::MasterKeyDocument | nil ] master_key_document The optional master # key document that contains master encryption key parameters. def initialize(mongocrypt, io, filter, master_key_document) super(mongocrypt, io) if master_key_document Binding.ctx_setopt_key_encryption_key(self, master_key_document.to_document) end Binding.ctx_rewrap_many_datakey_init(self, filter) end end end end
ISTESTING = true require "./src/wheres_joe_hatcher.rb" require "./src/cRoom.rb" require "test/unit" class Test_game_class < Test::Unit::TestCase def test_command entrance = Room.new("Entrance", "You can go north.") northroom = Room.new("The north", "So cold here") entrance.update_exits({"north" => northroom}) entrance.update_verbs({"go" => "exit", "walk" => "exit"}) northroom.update_exits({"south" => entrance}) northroom.update_verbs({"go" => "exit", "walk" => "exit"}) tester = Game.new tester.goto_room(entrance) assert_false(tester.parse_command("eat pizza")) assert_true(tester.parse_command("walk north")) assert_true(tester.parse_command("go to south")) end end
# in dev mode you can use "http://insecure.rails-assets.org" see https://rails-assets.org/#/ # NOTE: use "http://", not "https://" for proxy support source "http://rubygems.org" # Hello! This is where you manage which Jekyll version is used to run. # When you want to use a different version, change it below, save the # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: # # bundle exec jekyll serve # # This will help ensure the proper Jekyll version is running. # Happy Jekylling! gem "jekyll", "~> 3.8.6" # This is the default theme for new Jekyll sites. You may change this to anything you like. gem "minima", "~> 2.0" # If you want to use GitHub Pages, remove the "gem "jekyll"" above and # uncomment the line below. To upgrade, run `bundle update github-pages`. # gem "github-pages", group: :jekyll_plugins # If you have any plugins, put them here! group :jekyll_plugins do gem "jekyll-feed", "~> 0.6" #gem 'jekyll-manager' gem 'html-proofer' #gem 'jekyll-plantuml-url-interactive', :git => 'git://github.com/blockspacer/jekyll-plantuml-url-interactive' #gem 'jekyll-offline', :git => 'git://github.com/jeremiak/jekyll-offline.git' gem 'jekyll-graphviz' gem 'jekyll-typogrify' gem 'jekyll-picture-tag' gem 'jekyll-archives' #gem 'jekyll-sitemap', "~> 1.1.1" gem 'jekyll-gist' #gem 'jekyll-minifier' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem # and associated library. install_if -> { RUBY_PLATFORM =~ %r!mingw|mswin|java! } do gem "tzinfo", "~> 1.2" gem "tzinfo-data" end # Performance-booster for watching directories on Windows gem "wdm", "~> 0.1.0", :install_if => Gem.win_platform?
# encoding: utf-8 control "V-52461" do title "The DBMS must prevent the presentation of information system management-related functionality at an interface utilized by general (i.e., non-privileged) users." desc "Information system management functionality includes functions necessary to administer databases, network components, workstations, or servers, and typically requires privileged user access. The separation of user functionality from information system management functionality is either physical or logical and is accomplished by using different computers, different central processing units, different instances of the operating system, different network addresses, combinations of these methods, or other methods, as appropriate. An example of this type of separation is observed in web administrative interfaces that use separate authentication methods for users of any other information system resources. This may include isolating the administrative interface on a different domain and with additional access controls. If administrative functionality or information regarding DBMS management is presented on an interface available for users, information on DBMS settings may be inadvertently made available to the user.false" impact 0.5 tag "check": "Check DBMS settings and vendor documentation to verify administrative functionality is separate from user functionality. If administrator and general user functionality is not separated either physically or logically, this is a finding." tag "fix": "Configure DBMS settings to separate database administration and general user functionality. Provide those who have both administrative and general-user responsibilities with separate accounts for these separate functions." # Write Check Logic Here end
module FormHelper #--------------------------------------------------------------- def icon(name, html_options={}) html_options[:class] = ['fa', "fa-#{name}", html_options[:class]].compact content_tag(:i, nil, html_options) end #--------------------------------------------------------------- def order_url(field_name, filter_params={}) filter_params = (filter_params.to_h || {}).dup filter_params[:order] = field_name filter_params[:direction] = (filter_params[:direction] == 'asc') ? 'desc' : 'asc' return {filter: filter_params} end #--------------------------------------------------------------- def field_data(id, fields) {id: id, fields: fields.gsub("\n", "").gsub('"', "'")} end #--------------------------------------------------------------- def from_filter? params[:filter].present? && !params[:filter].key?("direction") && !params[:filter].key?("order") end #--------------------------------------------------------------- def link_to_add_workshop_image(form_builder, kind) new_object = WorkshopImage.new(kind: kind) kind_str = (kind.to_sym == :place)? '_place' : '_normal' id = new_object.object_id fields = form_builder.fields_for(:workshop_images, new_object, child_index: id) do |builder| render("workshop_image_fields", f: builder) end link_to '<i class="fa fa-plus fa-2x"></i>'.html_safe, '#', class: "btn add-workshop_image#{kind_str}", data: field_data(id, fields) end #--------------------------------------------------------------- def link_to_add_workshop_schedule(form_builder) new_object = WorkshopSchedule.new id = new_object.object_id fields = form_builder.fields_for(:workshop_schedules, new_object, child_index: id) do |builder| render("workshop_schedule_fields", f: builder) end link_to '<i class="fa fa-plus"></i> Agregar calendario'.html_safe, '#', class: "add-workshop_schedule", data: field_data(id, fields) end end
# Given a set of numbers, return the additive inverse of each. # Each positive becomes negatives, and the negatives become positives. # Example: # invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] # invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] # invert([]) == [] def invert(list) list.map(&:-@) end invert([1, -2, 3, -4, 5])
class Product < ApplicationRecord has_one_attached :image validates :title, :description, :price, presence: true end
class FixColumnSubcontractEquipment < ActiveRecord::Migration def change rename_column :subcontract_equipments, :type, :igv end end
class TagTicket < ActiveRecord::Base belongs_to :tag belongs_to :ticket end
require 'kintone/command' require 'kintone/api' class Kintone::Command::Form PATH = "form" def initialize(api) @api = api @url = @api.get_url(PATH) end def get(app) @api.get(@url, {:app => app}) end end
class Relation def initialize initialize_relations end def get_relations @relations end private def initialize_relations @relations = ActorRelation.all | ActRelation.all | ActActorRelation.all end end
require 'digest' require 'fileutils' class Indocker::DeployContext attr_reader :configuration, :logger def initialize(logger:, configuration:) @logger = logger @configuration = configuration @restart_policy = Indocker::Containers::RestartPolicy.new(configuration, logger) end def deploy(container, force_restart) @logger.info("Deploying container: #{container.name.to_s.green}") @logger.debug("Deploy dir: #{Indocker.deploy_dir}") Indocker::Docker.pull(container.image.registry_url) if !container.image.registry.is_local? container.networks.each do |network| Indocker::Docker.create_network( Indocker::Networks::NetworkHelper.name(@configuration.name, network) ) end container.volumes.each do |volume| if volume.is_a?(Indocker::Volumes::External) Indocker::Docker.create_volume( Indocker::Volumes::VolumeHelper.name(@configuration.name, volume) ) end end container.get_start_option(:scale).times do |number| arg_list = Indocker::DockerRunArgs .get(container, @configuration, number) .join(' ') hostname = Indocker::ContainerHelper.hostname(@configuration.name, container, number) # timestamp generation run_cmd = Indocker::Docker.run_command(container.image.registry_url, arg_list, container.start_command, container.get_start_option(:service_args)) env_files = container.get_start_option(:env_files, default: []) .map { |env_file| env_file = @configuration.env_files.fetch(env_file) File.read(Indocker::EnvFileHelper.path(env_file)) } .join image_id = Indocker::Docker.image_id(container.image.registry_url) timestamp = Digest::MD5.hexdigest(run_cmd + image_id.to_s + env_files) binary_path = File.join(File.expand_path(Indocker.deploy_dir), 'bin') FileUtils.mkdir_p(binary_path) binary_path = File.join(binary_path, hostname) File.open(binary_path, 'w') { |f| f.write("#!/bin/bash\n\n") f.write(run_cmd) } FileUtils.chmod('+x', binary_path) container_id = Indocker::Docker.container_id_by_name(hostname) if !container_id || @restart_policy.restart?(container, timestamp) || force_restart if container.before_start_proc container.before_start_proc.call(container, number) end if container_id Indocker::Docker.stop(hostname, skip_errors: true) else Indocker::Docker.rm(hostname, skip_errors: true) end Indocker::Docker.run(container.image.registry_url, arg_list, container.start_command, container.get_start_option(:service_args)) if container.after_start_proc container.after_start_proc.call(container, number) end @restart_policy.update(container, timestamp) else @logger.info("Skipping restart for container #{container.name.to_s.green} as no changes were found") if !container_id @restart_policy.update(container, timestamp) end end if container.after_deploy_proc container.after_deploy_proc.call(container, number) end end nil end end
class CreateQualifyings < ActiveRecord::Migration[6.0] def change create_table :qualifyings do |t| t.integer :qualifyId, index: true t.integer :raceId, index: true t.integer :driverId, index: true t.integer :constructorId, index: true t.integer :number t.integer :position t.string :q1 t.string :q2 t.string :q3 t.timestamps end end end
class AccountsController < AuthenticatedUserController onboard :account_type, with: [:type, :submit_type] def edit run Registration::Edit render cell(Registration::Cell::Edit, @model, form: @form) end def update run Registration::Update do flash[:success] = 'Saved settings!' # If they changed their password then they'll have been signed out: sign_in :account, @model, bypass: true end render cell(Registration::Cell::Edit, @model, form: @form) end # 'dashboard' lives under ApplicationController. This is because there are # two dashboards, the regular dashboard and the admin dashboard, but we can't # split it into two actions because they both live under the same path # (root_path) def type run Account::Type render cell( Account::Cell::Type, current_account, destination: result['model'], ) end def submit_type run Account::Type::Onboard redirect_to onboarding_survey_path end end
class AddForeignKeyConstraints < ActiveRecord::Migration[6.0] def change add_foreign_key :activities, :organisations, on_delete: :restrict # Already exists # add_foreign_key :activities, :activities, column: "activity_id", on_delete: :restrict # Already exists # add_foreign_key :activities, :organisations, column: "extending_organisation_id" # Column doesn't exist in this branch # add_foreign_key :activities, :organisations, column: "reporting_organisation_id" add_foreign_key :transactions, :activities, on_delete: :cascade add_foreign_key :budgets, :activities, on_delete: :cascade add_foreign_key :users, :organisations, on_delete: :restrict end end
class AddDefaultValueToJoinedDate < ActiveRecord::Migration[6.0] def change change_column_default :users, :joined, Date.today end end
class UserAvailableLanguage < ApplicationRecord belongs_to :user belongs_to :available_language end
FactoryGirl.define do factory :track do name 'Test Track' enabled true references 'references' instructions 'instruction' description 'descriptions' owner_id 11111 reviewer_id 99999 end factory :track_without_owner, class: 'Track' do name 'Test Track2' references 'references' instructions 'instruction' description 'descriptions' enabled true end end
require "rails_helper" describe Notifier do describe 'new project' do let!(:admin) { FactoryGirl.create(:admin) } let!(:user) { FactoryGirl.create(:user, mentor_id: admin.id) } let!(:project) do Project.new(id: 1, name: 'Rails 4', user_id: user.id) end let!(:email) { Notifier.new_project(project) } it 'send email to mentor in charge when intern create new project' do expect(email.to).to include(admin.email) title = "[Internbox] New Project: #{project.name} by #{user.name}" end end end
class BaselineAssessmentsController < ApplicationController include BaselineAssessmentsHelper include ThreeSixtyAssessmentsHelper skip_before_filter :authenticate skip_before_filter :verify_subscription def new @window_title = 'Baseline Assessment' @menu_section = 'toolkit' # TODO ? @user = current_user category = params[:category] # for the Baseline Mini Assessment @is_mini_assessment = ! category.nil? curr_ai = current_action_item(BaselineAssessment::COMPONENT_TYPE) event_type = category ? :user_or_lead_started_mini_baseline_assessment : :user_or_lead_started_baseline_assessment track_event(curr_ai||current_enrollment||current_lead, event_type, {} ) @assessment = BaselineAssessment.find_unexpired_and_incomplete_assessment(current_enrollment) || BaselineAssessment.new @questions = category ? BaselineAssessment.checks_for_category(category) : @assessment.unanswered_checks end # 10/26/14 Add support the mini assessment as a pre-registration activity: The baseline assessment will be created in the db # without an enrollment uuid and the assessment uuid is saved in the session and attached to the user upon registration def create assessment = current_enrollment ? current_enrollment.assessments.baseline.last : nil if assessment.nil? || assessment.created_at < 1.month.ago logger.info "Creating a new baseline assessment" assessment = BaselineAssessment.create(enrollment_uuid:current_enrollment ? current_enrollment.uuid : nil) else logger.info "Found an existing assessment" end params[:answers].each do |question_uuid, answer| next if answer == "" # bypass enpty answers check = Check.find_by_uuid(question_uuid) throw "you must provide the uuid of the question (aka check)" unless check assessment.responses.create!(check_uuid:check.uuid, value:answer) end # The assessment is created now, but may not have an enrollment. If not, we add the assessment uuid to the session # so that it can be attached to the user later on. if assessment.enrollment.nil? log "I have a newly-created baseline assessment, but no user, so I'm storing the assessment's uuid in session for later use." store_baseline_assessment_in_session(assessment) end # track the event curr_ai = current_action_item(BaselineAssessment::COMPONENT_TYPE) if assessment.complete? track_event(curr_ai||current_enrollment||current_lead, "completed_baseline_assessment", target:assessment, points:BASELINE_ASSESSMENT_POINTS) redirect_to baseline_assessment_path(assessment) elsif curr_ai||current_enrollment track_event(curr_ai||current_enrollment||current_lead, assessment.mini_complete? ? :user_or_lead_completed_mini_baseline_assessment : :user_or_lead_answered_baseline_assessment_questions, target:assessment) redirect_to action_plan_index_path else # no user, go to registration redirect_to registration_path end end def show @enrollment = current_enrollment @assessment = BaselineAssessment.where(uuid:params[:id]).first || @enrollment.assessments.baseline.last redirect_to new_baseline_assessment_path and return unless @assessment @menu_section = 'toolkit' # @baseline results, @focus_score, @positivity_score, @sleep_score, @social_score prepare_baseline_assessment_attributes(current_enrollment) prepare_three_sixty_assessment_attributes(current_enrollment) # mixpanel_track( 'Viewed Baseline Assessment Results', {type: @results.nil? ? 'benefits' : 'personality & benefits' } ) curr_ai = current_action_item(BaselineAssessment::COMPONENT_TYPE) track_event(curr_ai||current_enrollment||current_lead, :user_or_lead_viewed_baseline_assessment_results, {} ) end end
require 'test_helper' describe MutantSchoolAPIModel::Term do before do @fall2016 = TermFactory.build(:fall2016) end after do @fall2016.destroy if @fall2016.persisted? end describe '#save' do it 'creates a new term' do actual = Term.new(@fall2016.save) _(actual && actual.to_h).must_equal(@fall2016.to_h) end it 'updates an existing term' do @fall2016.save @fall2016.ends_at = '2050-05-25' # Ensure that `save` returns a Hash saved = @fall2016.save _(saved).must_be_instance_of(Hash) # Make a Term out of that Hash actual = Term.new(saved) # Ensure the new Term is the same as the old _(actual.to_h).must_equal(@fall2016.to_h) end end describe '#find' do it 'should retrieve the term that was just created' do @fall2016.save actual = Term.find(@fall2016.id) _(actual.to_h).must_equal(@fall2016.to_h) end it 'should return false if we look for a record that was just deleted' do @fall2016.save id = @fall2016.id @fall2016.destroy actual = Term.find(id) _(actual).must_equal false # _(actual).must_be_instance_of(Array) # _(actual.empty?).must_equal true end end describe '#all' do it 'should return an array of terms' do # Create a term, so there will be at least one. @fall2016.save # Make sure `all` returns an Array. actual = Term.all _(actual).must_be_instance_of Array # Make sure the first item in the Array is a Term. _(actual.first).must_be_instance_of Term end end describe '#enrollments' do it 'should return an Array of Enrollment instances if the term has enrollments' do actual = Term.find(2).enrollments _(actual).must_be_instance_of Array _(actual.first).must_be_instance_of Enrollment end end end
class Card def initialize(attributes) @front = attributes[:front] @back = attributes[:back] end def play print "#{front} > " guess = gets.chomp if correct?(guess) puts "Correct!" else puts "Sorry, the correct answer is #{back}." end end private attr_reader :front, :back def correct?(guess) guess.downcase == back.downcase end end class Deck attr_reader :cards, :name def initialize(name, cards) @name = name @cards = cards end def play cards.shuffle.each do |card| card.play end end end class FlashCardGame def initialize(decks) @decks = decks end def play loop do welcome deck = get_selected_deck if deck deck.play else break end end end private attr_reader :decks def welcome message = "Please select a deck." puts message puts "-" * message.size decks.each do |deck| print "#{deck.name} " end puts end def get_selected_deck selected_deck = gets.chomp decks.find do |deck| deck.name.downcase == selected_deck.downcase end end end class FlashCardReader def initialize(input_file) @file = File.open(input_file, "r") @deck_count = file.gets.to_i end def get_decks deck_count.times.map do deck_name = file.gets.chomp Deck.new(deck_name, get_cards) end end private attr_reader :file, :deck_count def get_cards card_count = file.gets.to_i card_count.times.map do front = file.gets.chomp back = file.gets.chomp Card.new(front: front, back: back) end end end decks = FlashCardReader.new("flash_cards_decks.txt").get_decks game = FlashCardGame.new(decks) game.play
require 'origen' module Origen class <<self # Override the Origen.reset_interface method to clear out the TestIds # configuration, so that it doesn't carry over from one flow to the next alias_method :_orig_reset_interface, :reset_interface def reset_interface(options = {}) TestIds.send(:clear_configuration_id) _orig_reset_interface(options) end end end
module ActiveRecord module Snapshot class Import def self.call(*args) new(*args).call end def initialize(version: nil, tables: []) @version = version if named_version? name = version else @version, name = SelectSnapshot.call(version) end @snapshot = Snapshot.new(name) @tables = tables end def call Stepper.call(self, **steps) end private attr_reader :snapshot, :tables, :version def config ActiveRecord::Snapshot.config end def named_version? !version.blank? && version.to_i.to_s != version.to_s end def version_downloaded? version.to_i == Version.current && File.file?(snapshot.dump) end def steps steps = {} unless version_downloaded? steps[:download] = "Download snapshot to #{snapshot.encrypted}" steps[:decrypt] = "Decrypt snapshot to #{snapshot.compressed}" steps[:decompress] = "Decompress snapshot to #{snapshot.dump}" end if tables.empty? steps[:reset_database] = "Reset database" else steps[:filter_tables] = "Filter tables" end steps[:import] = "Importing the snapshot into #{config.db.database}" steps[:save] = "Caching the new snapshot version" unless named_version? || tables.present? steps[:set_env] = "Setting database environment to #{Rails.env}" if Rails::VERSION::MAJOR >= 5 steps end def download snapshot.download end def decrypt OpenSSL.decrypt( input: snapshot.encrypted, output: snapshot.compressed ) && FileUtils.rm(snapshot.encrypted) end def decompress Bzip2.decompress(snapshot.compressed) end def reset_database Rake::Task["db:drop"].invoke Rake::Task["db:create"].invoke end def filter_tables FilterTables.call(tables: tables, sql_dump: snapshot.dump) end def import config.adapter.import(input: snapshot.dump) Rake::Task["db:schema:dump"].invoke end def set_env Rake::Task["db:environment:set"].invoke end def save Version.write(version) end end end end
# encoding: UTF-8 class Education < ActiveRecord::Base extend PersianNumbers persian_dates :started, :finished persian_numbers :average attr_accessible :average, :finished, :pursued, :started, :study_field, :teacher_id, :title, :univercity validates :title, :study_field, :univercity, :presence => {:message => 'عنوان را بنویسید'} validates_numericality_of :average, :greater_than_or_equal_to => 10.0, :less_than_or_equal_to => 20.0, :message => ' معدل را صحیح وارد کنید.' belongs_to :teachers end
class Aula < ApplicationRecord belongs_to :disciplina validates :objetivo, :realizado, presence: true validates :objetivo, :realizado, uniqueness: true end
class Status < ApplicationRecord belongs_to :user enum level: { terrible: 0, bad: 1, beginner: 2, low: 3, midterm: 4, high: 5 } validate :update_level, on: :update validates :points, :level, presence: true private def update_level case points when points < -200 self.level = 0 when -100..-1 self.level = 1 when 0..100 self.level = 2 when 101..1000 self.level = 3 when 1001..2000 self.level = 4 when points > 2000 self.level = 5 end true end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2015-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Event # The queue of events getting processed in the client. # # @since 2.0.0 class Listeners # Initialize the event listeners. # # @example Initialize the event listeners. # Listeners.new # # @since 2.0.0 def initialize @listeners = {} end # Add an event listener for the provided event. # # @example Add an event listener # publisher.add_listener("my_event", listener) # # @param [ String ] event The event to listen for. # @param [ Object ] listener The event listener. # # @return [ Array<Object> ] The listeners for the event. # # @since 2.0.0 def add_listener(event, listener) listeners_for(event).push(listener) end # Get the listeners for a specific event. # # @example Get the listeners. # publisher.listeners_for("test") # # @param [ String ] event The event name. # # @return [ Array<Object> ] The listeners. # # @since 2.0.0 def listeners_for(event) @listeners[event] ||= [] end end end end
require 'jwk/key' module JWK class OctKey < Key def initialize(key) @key = key validate end def public? true end def private? true end def validate raise JWK::InvalidKey, 'Invalid RSA key.' unless @key['k'] end def to_pem raise NotImplementedError, 'Oct Keys cannot be converted to PEM.' end def to_openssl_key raise NotImplementedError, 'Oct Keys cannot be converted to OpenSSL::PKey.' end def to_s k end def k Utils.decode_ub64(@key['k']) end end end
#!/usr/bin/env ruby module Observer def initialize @observers = [] end def adiciona_observer(observer) @observers << observer end def notifica @observers.each do |observer| observer.alerta end end end class Restaurante include Observer def qualifica(nota) puts "Restaurante recebeu nota #{nota}" notifica end def add_franquia(franquia) adiciona_observer(franquia) end end class Franquia def alerta puts "Um restaurante foi qualificado" end end rest1 = Restaurante.new rest2 = Restaurante.new franq1 = Franquia.new franq2 = Franquia.new rest1.add_franquia(franq1) rest2.add_franquia(franq1) rest2.add_franquia(franq2) rest1.qualifica(10) puts "" rest2.qualifica(7)
class Post < ApplicationRecord validates :content, presence: true, length: {maximum: 140, minimum: 1} end
class LevelNumber < ActiveRecord::Base has_many :scripts has_many :phase_typizations has_many :phase_types, through: :phase_typizations validates :name, uniqueness: true end