text
stringlengths
10
2.61M
module Raft class Goliath class HttpJsonRpcResponder < ::Goliath::API use ::Goliath::Rack::Render, 'json' use ::Goliath::Rack::Validation::RequestMethod, %w[POST] use ::Goliath::Rack::Params def initialize(node) @node = node end HEADERS = { 'Content-Type' => 'application/json' } def response(env) case env['REQUEST_PATH'] when '/request_vote' handle_errors { request_vote_response(env['params']) } when '/append_entries' handle_errors { append_entries_response(env['params']) } when '/command' handle_errors { command_response(env['params']) } else error_response(404, 'not found') end end def request_vote_response(params) print("\nnode #{@node.id} received request_vote from #{params['candidate_id']}, term #{params['term']}\n") request = Raft::RequestVoteRequest.new( params['term'], params['candidate_id'], params['last_log_index'], params['last_log_term'] ) response = @node.handle_request_vote(request) [200, HEADERS, { 'term' => response.term, 'vote_granted' => response.vote_granted }] end def append_entries_response(params) print("\nnode #{@node.id} received append_entries from #{params['leader_id']}, term #{params['term']}\n") entries = params['entries'].map { |entry| Raft::LogEntry.new(entry['term'], entry['index'], entry['command']) } request = Raft::AppendEntriesRequest.new( params['term'], params['leader_id'], params['prev_log_index'], params['prev_log_term'], entries, params['commit_index'] ) print("\nnode #{@node.id} received entries: #{request.entries.pretty_inspect}\n") response = @node.handle_append_entries(request) print("\nnode #{@node.id} completed append_entries from #{params['leader_id']}, term #{params['term']} (#{response})\n") [200, HEADERS, { 'term' => response.term, 'success' => response.success }] end def command_response(params) p params request = Raft::CommandRequest.new(params['command']) response = @node.handle_command(request) [response.success ? 200 : 409, HEADERS, { 'success' => response.success }] end def handle_errors yield rescue StandardError => e error_response(422, e) rescue Exception => e error_response(500, e) end def error_message(exception) "#{exception.message}\n\t#{exception.backtrace.join("\n\t")}".tap { |m| print("\n\n\t#{m}\n\n") } end def error_response(code, exception) [code, HEADERS, { 'error' => error_message(exception) }] end end module HashMarshalling def self.hash_to_object(hash, klass) object = klass.new hash.each_pair do |k, v| object.send("#{k}=", v) end object end def self.object_to_hash(object, attrs) attrs.each_with_object({}) do |attr, hash| hash[attr] = object.send(attr) end end end class HttpJsonRpcProvider < Raft::RpcProvider attr_reader :uri_generator def initialize(uri_generator) @uri_generator = uri_generator end def request_votes(request, cluster) sent_hash = HashMarshalling.object_to_hash(request, %w[term candidate_id last_log_index last_log_term]) sent_json = MultiJson.dump(sent_hash) deferred_calls = [] EM.synchrony do cluster.node_ids.each do |node_id| next if node_id == request.candidate_id http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'request_vote')).post( body: sent_json, head: { 'Content-Type' => 'application/json' } ) http.callback do if http.response_header.status == 200 received_hash = MultiJson.load(http.response) response = HashMarshalling.hash_to_object(received_hash, Raft::RequestVoteResponse) print("\n\t#{node_id} responded #{response.vote_granted} to #{request.candidate_id}\n\n") yield node_id, request, response else Raft::Goliath.log("request_vote failed for node '#{node_id}' with code #{http.response_header.status}") end end deferred_calls << http end end deferred_calls.each do |http| EM::Synchrony.sync http end end def append_entries(request, cluster, &block) deferred_calls = [] EM.synchrony do cluster.node_ids.each do |node_id| next if node_id == request.leader_id deferred_calls << create_append_entries_to_follower_request(request, node_id, &block) end end deferred_calls.each do |http| EM::Synchrony.sync http end end def append_entries_to_follower(request, node_id, &block) # EM.synchrony do create_append_entries_to_follower_request(request, node_id, &block) # end end def create_append_entries_to_follower_request(request, node_id) sent_hash = HashMarshalling.object_to_hash(request, %w[term leader_id prev_log_index prev_log_term entries commit_index]) sent_hash['entries'] = sent_hash['entries'].map do |obj| HashMarshalling.object_to_hash(obj, %w[term index command]) end sent_json = MultiJson.dump(sent_hash) raise 'replicating to self!' if request.leader_id == node_id print("\nleader #{request.leader_id} replicating entries to #{node_id}: #{sent_hash.pretty_inspect}\n")#"\t#{caller[0..4].join("\n\t")}") http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'append_entries')).post( body: sent_json, head: { 'Content-Type' => 'application/json' } ) http.callback do print("\nleader #{request.leader_id} calling back to #{node_id} to append entries\n") if http.response_header.status == 200 received_hash = MultiJson.load(http.response) response = HashMarshalling.hash_to_object(received_hash, Raft::AppendEntriesResponse) yield node_id, response else Raft::Goliath.log("append_entries failed for node '#{node_id}' with code #{http.response_header.status}") end end http end def command(request, node_id) sent_hash = HashMarshalling.object_to_hash(request, %w[command]) sent_json = MultiJson.dump(sent_hash) http = EventMachine::HttpRequest.new(uri_generator.call(node_id, 'command')).post( body: sent_json, head: { 'Content-Type' => 'application/json' } ) http = EM::Synchrony.sync(http) if http.response_header.status == 200 received_hash = MultiJson.load(http.response) HashMarshalling.hash_to_object(received_hash, Raft::CommandResponse) else Raft::Goliath.log("command failed for node '#{node_id}' with code #{http.response_header.status}") CommandResponse.new(false) end end end end end
class HomePageController < ApplicationController def index @systems=System.order(:name) @contacts=Contact.all end end
ActiveAdmin.register_page 'Dashboard' do menu priority: 1, label: proc{ I18n.t('active_admin.dashboard') } content title: proc{ I18n.t('active_admin.dashboard') } do now = Time.current day_ago = 1.day.ago beginning_of_day = now.beginning_of_day beginning_of_week = now.beginning_of_week beginning_of_month= now.beginning_of_month beginning_of_last_week = 1.week.ago.beginning_of_week beginning_of_last_month= 1.month.ago.beginning_of_month total_leads_last_week = Lead.created_between('pending', beginning_of_last_week, beginning_of_week).count total_approved_leads_last_week = Lead.created_between('approved', beginning_of_last_week, beginning_of_week).count total_leads_last_month = Lead.created_between('pending', beginning_of_last_month, beginning_of_month).count total_approved_leads_last_month = Lead.created_between('approved', beginning_of_last_month, beginning_of_month).count columns do column do panel 'Leads Statistics' do div id: 'lead-graph' do end end end end columns do column do panel 'Imports - Last 24 hours' do table do tr do td do text_node 'Total Imports:' end td do link_to ImportTrail.where('created_at > ?', day_ago).count, admin_import_trails_path(q: {created_at_gteq: day_ago}) end end tr do td do text_node 'Ran with no Errors:' end td class: 'text-green' do text_node ImportTrail.where('created_at > ?', day_ago).without_errors.group(:import_id).count.length end end tr do td do text_node 'Run Fault:' end td class: 'text-red' do link_to ImportTrail.where('created_at > ?', day_ago).where(error_msg: ['Unexpected Error']).group(:import_id).count.length, admin_import_trails_path(q: {created_at_gteq: day_ago, error_msg_in: ['Unexpected Error']}) end end tr do td do text_node 'Run, but no Feed:' end td class: 'text-red' do link_to ImportTrail.where('created_at > ?', day_ago).where(warning_msg: ['Feed already imported', 'Import Blank']).group(:import_id).count.length, admin_import_trails_path(q: {created_at_gteq: day_ago, warning_msg_in: ['Feed already imported', 'Import Blank']}) end end tr do td do text_node 'Ran, but with Errors:' end td class: 'text-orange' do link_to ImportTrail.where('created_at > ?', day_ago).with_errors.group(:import_id).count.length, admin_import_trails_path(q: {created_at_gteq: day_ago, error_msg_present: 1}) end end tr do td do text_node 'Inactive Imports:' end td do link_to Import.inactive.count, admin_imports_path(q: {active_eq: false}) end end end end end column do panel 'Leads Tracker' do table do tr do td do text_node 'Total Leads today:' end td do text_node Lead.where('created_at > ?', beginning_of_day).count end end tr do td do text_node 'Total Pending/Approved/Invoiced Leads today:' end td do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_from(status, beginning_of_day).count text_node '/' if i < 2 end end end tr do td do text_node "Total Pending/Approved/Invoiced Leads this week (Mon-#{now.strftime('%a')}):" end td class: 'text-green' do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_from(status, beginning_of_week).count text_node '/' if i < 2 end end end tr do td do text_node 'Total Pending/Approved/Invoiced Leads this month:' end td class: 'text-green' do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_from(status, beginning_of_month).count text_node '/' if i < 2 end end end tr do td do end end tr do td do text_node 'Total Pending/Approved/Invoiced Lead Value last week (Mon-Sun):' end td do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_between(status, beginning_of_last_week, beginning_of_week).sum(:lead_price) text_node '/' if i < 2 end end end tr do td do text_node 'Total Pending/Approved/Invoiced Lead Value last month:' end td do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_between(status, beginning_of_last_month, beginning_of_month).sum(:lead_price) text_node '/' if i < 2 end end end end end end column do panel 'User Activity' do table do tr do td do text_node 'Total Private Users:' end td do link_to User.general.count, admin_users_path(q: {role_eq: User::ROLES['PRIVATE']}) end end tr do td do text_node "Total new Private Users this week (Mon-#{now.strftime('%a')}):" end td do text_node User.general.where('created_at > ?', beginning_of_week).count end end tr do td do text_node 'Total new Private Users last week (Mon-Sun):' end td do text_node User.general.where(created_at: beginning_of_last_week..beginning_of_week).count end end tr do td do text_node 'Total new Private Users last month:' end td do text_node User.general.where(created_at: beginning_of_last_month..beginning_of_month).count end end tr do td do text_node 'Total Private Users with Alerted Saved Searches:' end td do text_node User.joins(:saved_searches).where('saved_searches.alert = ?', true).group('users.id').having('count(saved_searches.id) > ?', 0).count.keys.length end end end end end end columns do column do panel 'Boat Inventory' do table do # tr do # td do # text_node 'Total Boats:' # end # td do # text_node Boat.count # end # end tr do td do text_node 'Total active Boats:' end td class: 'text-green' do text_node Boat.active.count end end # tr do # td do # text_node 'Total inactive Boats:' # end # td class: 'text-red' do # text_node Boat.deleted.count # end # end tr do td do text_node 'Total active Power Boats:' end td do text_node Boat.active.power.count end end tr do td do text_node 'Total active Sail Boats:' end td do text_node Boat.active.sail.count end end tr do td do text_node 'Total active, not Power or Sail' end td do text_node Boat.active.not_power_or_sail.count end end end end end column do panel 'Leads Analysis' do table do tr do td do text_node 'Total Leads last week (Mon-Sun):' end td do text_node total_leads_last_week end end tr do td do text_node 'Total Pending/Approved/Invoiced Leads last week (Mon-Sun):' end td class: 'text-green' do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_between(status, beginning_of_last_week, beginning_of_week).count text_node '/' if i < 2 end end end tr do td do text_node 'Total Cancelled Leads last week (Mon-Sun):' end td class: 'text-red' do text_node Lead.cancelled.where(created_at: beginning_of_last_week..beginning_of_week).count end end tr do td do text_node 'Approval Percentage:' end td do text_node approved_percentage(total_leads_last_week, total_approved_leads_last_week) end end tr do td do end end tr do td do text_node 'Total Leads last month:' end td do text_node total_leads_last_month end end tr do td do text_node 'Total Pending/Approved/Invoiced Leads last month:' end td class: 'text-green' do %w(pending approved invoiced).each_with_index do |status, i| text_node Lead.created_between(status, beginning_of_last_month, beginning_of_month).count text_node '/' if i < 2 end end end tr do td do text_node 'Total Cancelled Leads last month:' end td class: 'text-red' do text_node Lead.cancelled.where(created_at: beginning_of_last_month..beginning_of_month).count end end tr do td do text_node 'Approval Percentage:' end td do text_node approved_percentage(total_leads_last_month, total_approved_leads_last_month) end end end end end column do panel 'Broker status' do table do tr do td do text_node 'Total Brokers' end td do text_node User.companies.count end end tr do td do text_node 'Brokers with Active Boats' end td class: 'text-green' do link_to User.companies.where('boats_count > ?', 0).count, admin_users_path(q: {role_eq: User::ROLES['COMPANY'], boats_count_greater_than: 0}) end end tr do td do text_node 'Brokers with no Active Boats' end td class: 'text-orange' do link_to User.companies.where(boats_count: 0).count, admin_users_path(q: {role_eq: User::ROLES['COMPANY'], boats_count_eq: 0}) end end end end end end render partial: 'charts' end end
class CreateRepetitions < ActiveRecord::Migration[5.2] def change create_table :repetitions do |t| t.integer :user_id, null: false t.integer :question_id, null: false t.timestamp :due_at, null: false t.integer :iteration, null: false t.integer :interval, null: false t.integer :ef, null: false t.timestamps t.index [:user_id, :question_id], unique: true t.index [:user_id, :due_at] # for search query end add_foreign_key :repetitions, :questions add_foreign_key :repetitions, :users end end
module ActionView class LookupContext module ViewPaths def find_all_templates(name, prefix = nil, partial = false) templates = [] @view_paths.each do |resolver| template = resolver.find_all(*args_for_lookup(name, prefix, partial)).first templates << template unless template.nil? end templates end end end end # wrap the action rendering for ActiveScaffold views module ActionView::Rendering #:nodoc: # Adds two rendering options. # # ==render :super # # This syntax skips all template overrides and goes directly to the provided ActiveScaffold templates. # Useful if you want to wrap an existing template. Just call super! # # ==render :active_scaffold => #{controller.to_s}, options = {}+ # # Lets you embed an ActiveScaffold by referencing the controller where it's configured. # # You may specify options[:constraints] for the embedded scaffold. These constraints have three effects: # * the scaffold's only displays records matching the constraint # * all new records created will be assigned the constrained values # * constrained columns will be hidden (they're pretty boring at this point) # # You may also specify options[:conditions] for the embedded scaffold. These only do 1/3 of what # constraints do (they only limit search results). Any format accepted by ActiveRecord::Base.find is valid. # # Defining options[:label] lets you completely customize the list title for the embedded scaffold. # def render_with_active_scaffold(*args, &block) if args.first == :super options = args[1] || {} options[:locals] ||= {} options[:locals].reverse_merge!(@last_view[:locals] || {}) if @last_view[:templates].nil? @last_view[:templates] = lookup_context.find_all_templates(@last_view[:view], controller_path, !@last_view[:is_template]) @last_view[:templates].shift end options[:template] = @last_view[:templates].shift render_without_active_scaffold options elsif args.first.is_a?(Hash) and args.first[:active_scaffold] require 'digest/md5' options = args.first remote_controller = options[:active_scaffold] constraints = options[:constraints] conditions = options[:conditions] eid = Digest::MD5.hexdigest(params[:controller] + remote_controller.to_s + constraints.to_s + conditions.to_s) session["as:#{eid}"] = {:constraints => constraints, :conditions => conditions, :list => {:label => args.first[:label]}} options[:params] ||= {} options[:params].merge! :eid => eid, :embedded => true id = "as_#{eid}-content" url_options = {:controller => remote_controller.to_s, :action => 'index'}.merge(options[:params]) if respond_to? :render_component render_component url_options else content_tag(:div, {:id => id}) do url = url_for(url_options) link_to(remote_controller.to_s, url, {:remote => true, :id => id}) << if ActiveScaffold.js_framework == :prototype javascript_tag("new Ajax.Updater('#{id}', '#{url}', {method: 'get', evalScripts: true});") elsif ActiveScaffold.js_framework == :jquery javascript_tag("$('##{id}').load('#{url}');") end end end else options = args.first if options.is_a?(Hash) @last_view = {:view => options[:partial], :is_template => false} if options[:partial] @last_view = {:view => options[:template], :is_template => !!options[:template]} if @last_view.nil? && options[:template] @last_view[:locals] = options[:locals] if !@last_view.nil? && options[:locals] end render_without_active_scaffold(*args, &block) end end alias_method_chain :render, :active_scaffold def partial_pieces(partial_path) if partial_path.include?('/') return File.dirname(partial_path), File.basename(partial_path) else return controller.class.controller_path, partial_path end end # This is the template finder logic, keep it updated with however we find stuff in rails # currently this very similar to the logic in ActionBase::Base.render for options file # TODO: Work with rails core team to find a better way to check for this. def template_exists?(template_name, lookup_overrides = false) begin method = 'find_template' method << '_without_active_scaffold' unless lookup_overrides self.view_paths.send(method, template_name, @template_format) return true rescue ActionView::MissingTemplate => e return false end end end
class Notifier < ActionMailer::Base default :from => "myhanhqt96@gmail.com" def email_friend(article, sender_name, receiver_email) @article = article @sender_name = sender_name mail :to => receiver_email, :subject => "Interesting Article" end end
class PhoneNumber < ApplicationRecord paginates_per 2 def self.create_random_phone_number flag = true phone_number = nil while flag do a = [1,2,3,4,5,6].shuffle.first if a.even? number = Time.now.to_i.to_s first_part = number[0..2].to_i second_part = number[3..5].to_i third_part = number[6..9].to_i if third_part < 1111 || second_part < 111 || first_part < 111 || number.length != 10 number = generate_random_number end else number = generate_random_number end unless self.exists?(number: number) flag = false phone_number = create(number: number) end end phone_number end def self.generate_number given_number if given_number.present? if self.exists?(number: given_number) create_random_phone_number else create(number: given_number) end else create_random_phone_number end end private def self.generate_random_number (111 + rand(889)).to_s + (111 + rand(889)).to_s + (1111 + rand(8889)).to_s end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # remember_created_at :datetime # sign_in_count :integer default(0) # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # name :string(255) # uid :integer # nickname :string(255) # location :string(255) # hireable :boolean # company :string(255) # bio :text # gravatar_id :string(255) # avatar_url :text # blog_name :string(255) # blog_description :text # created_at :datetime not null # updated_at :datetime not null # class User < ActiveRecord::Base devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :role_id, :uid, :nickname, :location, :hireable, :company, :bio, :gravatar_id, :avatar_url, :blog_name, :blog_description validates_presence_of :email, :nickname, :uid, :name validates_uniqueness_of :email, :nickname, :uid validates_presence_of :name validates :nickname, :exclusion => { :in => %w(www help support api apps status blog static dudupress dev mail db admin addons owner billing), :message => "Subdomain %{value} is reserved." } belongs_to :role has_many :comments has_many :articles def self.find_for_github_oauth(access_token, signed_in_resource=nil) auth = access_token.extra.raw_info info = access_token.info uid = access_token.uid User.logger.info auth user = find_by_uid(access_token.uid) if user user else # Create a user with a stub password. create( :uid => uid, :nickname => info.nickname, :email => info.email, :name => info.name, :blog_name => info.name, :location => auth.location, :hireable => auth.hireable, :gravatar_id => auth.gravatar_id, :avatar_url => auth.avatar_url, :company => auth.company, :bio => auth.bio, :password => Devise.friendly_token[0, 8] ) end end end
# Public: Checks which one of two integers are largest. # # num1 - The first integer number to compare with. # num2 - The second integer number to compare with. # # Examples # # max_of_two(1,5) # # => 5 # # # Returns the largest integer number def max_of_two(num1,num2) return num1 if num1 > num2 return num2 end
class Student < ActiveRecord::Base has_and_belongs_to_many(:periods) scope(:between, lambda do |start_date, end_date| where('birthday >= :start_date AND birthday <= :end_date', { :start_date => start_date, :end_date => end_date} ) end) end
require 'test_helper' class ReaderUsersControllerTest < ActionController::TestCase setup do @reader_user = reader_users(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:reader_users) end test "should get new" do get :new assert_response :success end test "should create reader_user" do assert_difference('ReaderUser.count') do post :create, :reader_user => @reader_user.attributes end assert_redirected_to reader_user_path(assigns(:reader_user)) end test "should show reader_user" do get :show, :id => @reader_user.to_param assert_response :success end test "should get edit" do get :edit, :id => @reader_user.to_param assert_response :success end test "should update reader_user" do put :update, :id => @reader_user.to_param, :reader_user => @reader_user.attributes assert_redirected_to reader_user_path(assigns(:reader_user)) end test "should destroy reader_user" do assert_difference('ReaderUser.count', -1) do delete :destroy, :id => @reader_user.to_param end assert_redirected_to reader_users_path end end
require 'spec_helper' describe Feed do it{ should have_many(:posts)} it{ should belong_to(:user)} it{ should be_public} it{ should have_many(:allowed_users)} it "returns posts in chronological, descending order" do feed = FactoryGirl.create :feed post_earlier = FactoryGirl.create :post, created_at: 1.day.ago post_later = FactoryGirl.create :post, created_at: 1.minute.ago feed.posts << post_later feed.posts << post_earlier feed.posts << post_later feed.posts.should eq([post_later, post_later, post_earlier]) end end
require 'spec_helper' describe Department do subject { Fabricate :department } it { should embed_many :homepage_docs } it { should validate_presence_of :name } it { should validate_uniqueness_of :name } it { should have_many :courses } context "Fabrication" do it "fabricates a valid department" do expect(Fabricate(:department)).to be_valid end it "fabricates a valid department with documents" do expect(Fabricate(:department_with_docs)).to be_valid end end end
FactoryGirl.define do factory :post do |f| f.title "FactoryGirl Ttile" f.body "Factory Girl Body" f.category factory: :category f.posted true f.keywords "Factory, FactoryGirl" end end
# Matchers for ChefSpec 3 if defined?(ChefSpec) def create_monit_check(check) ChefSpec::Matchers::ResourceMatcher.new(:monit_check, :create, check) end def remove_monit_check(check) ChefSpec::Matchers::ResourceMatcher.new(:monit_check, :remove, check) end end
require 'csv' CSV.generate do |csv| headers = %w[PEOPLE_ID ACCT_NAME DISPLAY_DATE AMOUNT DONATION_ID DESIGNATION MOTIVATION PAYMENT_METHOD MEMO TENDERED_AMOUNT TENDERED_CURRENCY ADJUSTMENT_TYPE] csv << headers @donations.each do |donation| csv << [donation.donor_account_id, donation.donor_account.name, donation.created_at.strftime('%m/%d/%Y'), donation.amount, donation.id, donation.designation_account_id, '', '', '', donation.amount, donation.currency, ''] end end
require 'rails_helper' RSpec.describe Color, type: :model do describe 'when the color index is picked by id' do it 'is expected to return a hash of colors' do color = Color.new.pick_by_id(1) expect(color).to eq({ id: 1, color_name: 'gray', accent: '#f4f5f7', contrast: '#374151', }) end end describe 'when the color index is picked by name' do it 'is expected to return a hash of colors' do color = Color.new.pick_by_name('gray') expect(color).to eq({ id: 1, color_name: 'gray', accent: '#f4f5f7', contrast: '#374151', }) end end end
Sequel.migration do change do create_table(:guests) do primary_key :id column :first_name, :varchar column :last_name, :varchar column :email, :varchar end end end
require 'rails_helper' describe 'Institution::create', type: :feature do let(:responsible) { create(:responsible) } let(:resource_name) { Institution.model_name.human } let!(:external_member) { create(:external_member) } before do login_as(responsible, scope: :professor) end describe '#create' do before do visit new_responsible_institution_path end context 'when institution is valid', js: true do it 'create an institution' do attributes = attributes_for(:institution) find('#institution_external_member_id-selectized').click find('div.selectize-dropdown-content', text: external_member.name).click fill_in 'institution_name', with: attributes[:name] fill_in 'institution_trade_name', with: attributes[:trade_name] fill_in 'institution_cnpj', with: attributes[:cnpj] submit_form('input[name="commit"]') expect(page).to have_current_path responsible_institutions_path success_message = I18n.t('flash.actions.create.m', resource_name: resource_name) expect(page).to have_flash(:success, text: success_message) expect(page).to have_message(attributes[:name], in: 'table tbody') end end context 'when institution is not valid', js: true do it 'show errors' do submit_form('input[name="commit"]') expect(page).to have_flash(:danger, text: I18n.t('flash.actions.errors')) message_blank_error = I18n.t('errors.messages.blank') expect(page).to have_message(message_blank_error, in: 'div.institution_name') expect(page).to have_message(message_blank_error, in: 'div.institution_trade_name') expect(page).to have_message(message_blank_error, in: 'div.institution_cnpj') expect(page).to have_message(message_blank_error, in: 'div.institution_external_member') end end end end
module Ricer::Plugins::Quote class Subscribe < Ricer::Plugin is_announce_trigger "subscribe" # Static subscribe subscribe('ricer/quote/added') do |quote| # Get instance and do it bot.get_plugin('Quote/Subscribe').announce_quote(quote) end # Instance does it def announce_quote(quote) announce_targets do |target| unless target == current_message.reply_target target.localize!.send_message(announce_message(quote)) end end end def announce_message(quote) t(:msg_announce, id: quote.id, user: sender.displayname, channel: channel.displayname, message: quote.message, ) end end end
#!/usr/bin/env ruby # frozen_string_literal: true require 'addressable' require 'fileutils' require 'json' require 'net/http' require 'uri' # Cache handling module Cache @cache_dir = '/tmp/similarweb/' def self.fetch(site) path = "#{@cache_dir}#{site}" File.read(path) if File.exist?(path) end def self.store(site, rank) FileUtils.mkdir_p(@cache_dir) File.open("#{@cache_dir}#{site}", 'w') { |file| file.write rank } end end # Similarweb API handling module Similarweb def self.api_key key = ENV['SIMILARWEB_API_KEY'] raise('Similarweb API key not set') if key.nil? keys = key.split(' ') keys[rand(0..(keys.length - 1))] end def self.fetch(site) response = Net::HTTP.get_response URI("https://api.similarweb.com/v1/similar-rank/#{site}/rank?api_key=#{api_key}") raise("#{site} doesn't have a Similarweb ranking") if response.code.eql? '404' raise("(#{response.code}) Request failed.") unless response.code.eql? '200' rank = JSON.parse(response.body)['similar_rank']['rank'] Cache.store(site, rank) rank end end status = 0 # Fetch changes diff = `git diff origin/master...HEAD entries/ | sed -n 's/^+.*"domain"[^"]*"\\(.*\\)".*/\\1/p'` # Strip and loop through diff diff.split("\n").each.with_index do |site, i| sleep 2 if i.positive? domain = Addressable::URI.parse("https://#{site}").domain rank = Cache.fetch(domain) || Similarweb.fetch(domain) failure = rank.to_i > 200_000 puts "\e[#{failure ? '31' : '32'}m#{domain} - #{rank}\e[39m" raise("Global rank #{rank} of #{domain} is above the maximum rank of 200K") if failure rescue StandardError => e puts "\e[31m#{e.message}\e[39m" status = 1 end exit(status)
require 'rails_helper' RSpec.describe LessonCategoriesController, :type => :controller do before do @user = FactoryGirl.create :user sign_in :user, @user FactoryGirl.create :course Attending.create(user_id: 1, course_id: 1, role: 2) end describe "POST create" do context 'valid' do it 'creates lesson category' do expect do post :create, course_id: 1, lesson_category: { name: "t", flagged: '0' } end.to change(LessonCategory, :count).by(1) expect(response).to redirect_to settings_course_path(1) end end context 'invlid' do it 'does not create lesson category' do expect do post :create, course_id: 1, lesson_category: { name: "", flagged: '0' } end.not_to change(LessonCategory, :count) expect(response).to redirect_to settings_course_path(1) end end end context 'DELETE destroy' do before do FactoryGirl.create :lesson_category end it 'destroys LessonCategory' do expect do delete :destroy, id: 1, course_id: 1 end.to change(LessonCategory, :count).by(-1) expect(response).to redirect_to settings_course_path(1) end end context 'PATCH update' do before do FactoryGirl.create :lesson_category end context 'valid' do it 'updates lesson category' do patch :update, id: 1, course_id: 1, lesson_category: { name: "Nazwa" } expect(LessonCategory.first.name).to eq "Nazwa" expect(response).to redirect_to settings_course_path(1) end end context 'invalid' do it 'does not update attributes' do patch :update, id: 1, course_id: 1, lesson_category: { name: "" } expect(LessonCategory.first.name).not_to eq "" expect(response).to redirect_to settings_course_path(1) end end end end
class AddCloneColumnToStories < ActiveRecord::Migration def change add_column :stories, :clone, :boolean end end
class LineItemsController < Spree::BaseController def destroy if @order = current_order @line_item = current_order.line_items.find(params[:id]) @line_item.destroy redirect_to cart_path end end end
require 'thor/actions/templater' require 'open-uri' class Thor module Actions # Gets the content at the given address and places it at the given relative # destination. If a block is given instead of destination, the content of # the url is yielded and used as location. # # ==== Parameters # source<String>:: the address of the given content # destination<String>:: the relative path to the destination root # log_status<Boolean>:: if false, does not log the status. True by default. # # ==== Examples # # get "http://gist.github.com/103208", "doc/README" # # get "http://gist.github.com/103208" do |content| # content.split("\n").first # end # def get(source, destination=nil, log_status=true, &block) action Get.new(self, source, block || destination, log_status) end class Get < Templater #:nodoc: def render @render ||= open(source).read end protected def source=(source) if source =~ /^http\:\/\// @source = source else super(source) end end def destination=(destination) destination = if destination.nil? File.basename(source) elsif destination.is_a?(Proc) destination.arity == 1 ? destination.call(render) : destination.call else destination end super(destination) end end end end
require 'prawn_charts/layers/layer' module PrawnCharts module Layers # Line (horizontal) graph. class Line < Layer def draw(pdf, coords, options={}) # Include options provided when the object was created options.merge!(@options) pdf.reset_text_marks stroke_width = (options[:relative]) ? relative(options[:stroke_width]) : options[:stroke_width] marker = options[:marker] marker_size = options[:marker_size] || 2 marker_size = (options[:relative]) ? relative(marker_size) : marker_size style = (options[:style]) ? options[:style] : '' theme.reset_outline outline_color = theme.next_outline save_line_width = pdf.line_width pdf.line_width = stroke_width #pdf.dash(length, :space => space, :phase => phase) if options[:shadow] offset = 2 px, py = (coords[0].first), coords[0].last coords.each_with_index do |coord,index| x, y = (coord.first), coord.last unless index == 0 pdf.transparent(0.5) do pdf.stroke_color = outline_color pdf.stroke_line [px+offset, height-py-offset], [x+offset, height-y-offset] end end px, py = x, y end if marker theme.reset_color coords.each do |coord| x, y = (coord.first)+offset, height-coord.last-offset color = preferred_color || theme.next_color draw_marker(pdf,marker,x,y,marker_size,color) end end end px, py = (coords[0].first), coords[0].last coords.each_with_index do |coord,index| x, y = (coord.first), coord.last unless index == 0 #pdf.text_mark "line stroke_line [#{px}, #{height-py}], [#{x}, #{height-y}]" pdf.stroke_color = outline_color pdf.stroke_line [px, height-py], [x, height-y] end px, py = x, y end if marker theme.reset_color coords.each do |coord| x, y = (coord.first), height-coord.last color = preferred_color || theme.next_color draw_marker(pdf,marker,x,y,marker_size,color) end end pdf.line_width = save_line_width end def legend_data if relevant_data? && @color retval = [] if titles && !titles.empty? titles.each_with_index do |stitle, index| retval << {:title => stitle, :color => @colors[index], :priority => :normal} end end retval else nil end end end # Line end # Layers end # PrawnCharts
require 'entity' require 'position' # A ship in the game. # id: The ship ID. # x: The ship x-coordinate. # y: The ship y-coordinate. # radius: The ship radius. # owner: The player ID of the owner, if any. If nil, the ship is not owned. # health: The ship's remaining health. # docking_status: one of (UNDOCKED, DOCKED, DOCKING, UNDOCKING) # planet: The ID of the planet the ship is docked to, if applicable. class Ship < Entity class DockingStatus UNDOCKED = 0 DOCKING = 1 DOCKED = 2 UNDOCKING = 3 ALL = [UNDOCKED, DOCKING, DOCKED, UNDOCKING].freeze end attr_reader :health, :docking_status, :planet def initialize(player_id, ship_id, x, y, hp, status, progress, planet_id) @id = ship_id @x, @y = x, y @owner = player_id @radius = Game::Constants::SHIP_RADIUS @health = hp @docking_status = status @docking_progress = progress @planet = planet if @docking_status != DockingStatus::UNDOCKED end # Generate a command to accelerate this ship. # magnitude: The speed through which to move the ship # angle: The angle in degrees to move the ship in. # return: The command string to be passed to the Halite engine. def thrust(magnitude, angle) "t #{id} #{Integer(magnitude)} #{angle.round.modulo(360)}" end # Generate a command to dock to a planet. # planet: The planet object to dock to # return: The command string to be passed to the Halite engine. def dock(planet) "d #{id} #{planet.id}" end # Generate a command to undock from the current planet. # return: The command string to be passed to the Halite engine. def undock "u #{id}" end # Determine wheter a ship can dock to a planet # planet: the Planet you are attempting to dock at # return: true if can dock, false if no def can_dock?(planet) calculate_distance_between(planet) <= planet.radius + Game::Constants::DOCK_RADIUS + Game::Constants::SHIP_RADIUS end # Move a ship to a specific target position (Entity). # It is recommended to place the position itself here, else navigate will # crash into the target. If avoid_obstacles is set to True (default), it # will avoid obstacles on the way, with up to max_corrections corrections. # Note that each correction accounts for angular_step degrees difference, # meaning that the algorithm will naively try max_correction degrees before # giving up (and returning None). The navigation will only consist of up to # one command; call this method again in the next turn to continue navigating # to the position. # target: The Entity to which you will navigate # map: The map of the game, from which obstacles will be extracted # speed: The (max) speed to navigate. If the obstacle is near, it will adjust # avoid_obstacles: Whether to avoid the obstacles in the way (simple # pathfinding). # max_corrections: The maximum number of degrees to deviate per turn while # trying to pathfind. If exceeded returns None. # angular_step: The degree difference to deviate if the path has obstacles # ignore_ships: Whether to ignore ships in calculations (this will make your # movement faster, but more precarious) # ignore_planets: Whether to ignore planets in calculations (useful if you # want to crash onto planets) # return: The command trying to be passed to the Halite engine or nil if # movement is not possible within max_corrections degrees. def navigate(target, map, speed, avoid_obstacles: true, max_corrections: 90, angular_step: 1, ignore_ships: false, ignore_planets: false) return if max_corrections <= 0 distance = calculate_distance_between(target) angle = calculate_deg_angle_between(target) ignore = [] ignore << :ships if ignore_ships ignore << :planets if ignore_planets if avoid_obstacles && map.obstacles_between(self, target, ignore).length > 0 delta_radians = (angle + angular_step)/180.0 * Math::PI new_target_dx = Math.cos(delta_radians) * distance new_target_dy = Math.sin(delta_radians) * distance new_target = Position.new(x + new_target_dx, y + new_target_dy) return navigate(new_target, map, speed, avoid_obstacles: true, max_corrections: max_corrections-1, angular_step: angular_step) end speed = distance >= speed ? speed : distance thrust(speed, angle) end # Uses the IDs of players and planets and populates the owner and planet params # with the actual objects representing each, rather than the IDs. # players: hash of Player objects keyed by id # planets: hash of Planet objects keyed by id def link(players, planets) @owner = players[@owner] @planet = planets[@planet] end # Parse multiple ship data, given tokenized input # player_id: The ID of the player who owns the ships # tokens: The tokenized input # return: the hash of Ships and unused tokens def self.parse(player_id, tokens) ships = {} count_of_ships = Integer(tokens.shift) count_of_ships.times do ship_id, ship, tokens = parse_single(player_id, tokens) ships[ship_id] = ship end return ships, tokens end # Parse a single ship's data, given tokenized input from the game # player_id: The ID of the player who owns the ships # tokens: The tokenized input # return: the ship id, ship object, and unused tokens def self.parse_single(player_id, tokens) # The _ variables are deprecated in this implementation, but the data is still # being sent from the Halite executable. # They were: velocity x, velocity y, and weapon cooldown id, x, y, hp, _, _, status, planet, progress, _, *tokens = tokens id = Integer(id) # player_id, ship_id, x, y, hp, docking_status, progress, planet_id ship = Ship.new(player_id, id, Float(x), Float(y), Integer(hp), Integer(status), Integer(progress), Integer(planet)) return id, ship, tokens end end
class Stack def initialize #create ivar to store stack here! @stack = [] end def push(el) #adds an element to the stack @stack << el end def pop #removes one element from the stack @stack.pop end def peek #returns, but doesn't remove, the top element in the stack @stack[-1] end end class Queue def initialize @queue = [] end def enqueue(el) @queue.unshift(el) end def dequeue @queue.pop end def peek @queue[-1] end end require "byebug" class Map def initialize @my_map = [] end def get end def set(key, value) pair = key, value # debugger# mapped = false @my_map.each_with_index do |subarr, i| if subarr[0] == key @my_map[i][1] = value # debugger elsif (i == @my_map.length - 1) || (@my_map == []) @my_map.push(pair) end # debugger end end def get(key) @my_map.each_with_index {|subarr, i| return subarr if subarr[0] == key} nil end def delete(key) end attr_accessor :my_map end
require 'rails_helper' RSpec.describe UserSession, type: :model do let(:us) { build :user_session } let(:dt) { DateTime.new(2000, 1, 1, 0, 0, 0) } it '正常系' do expect(us.save).to be_truthy end it 'tokenの存在性チェック' do us.token = '' expect(us.valid?).to be_falsy end it 'tokenの一意性チェック' do dup_us = us.dup us.save expect(dup_us.valid?).to be_falsy end it 'expiresの存在性チェック' do us.expires = nil expect(us.valid?).to be_falsy end it 'user_idの存在性チェック' do us.user = nil expect(us.valid?).to be_falsy end it 'set_new_tokenのテスト' do Timecop.freeze(dt) do us.set_new_token end expect(us.token) .to be_present expect(us.token) .to_not eq('token') expect(us.expires).to eq(dt + UserSession::EXPIRES_OFFSET) end it 'is_in_expiresのテスト' do us.expires = dt Timecop.freeze(dt) do expect(us.is_in_expires).to be_truthy end Timecop.freeze(dt + UserSession::EXPIRES_OFFSET + 1) do expect(us.is_in_expires).to be_falsy end end it 'delete_sessionのテスト' do Timecop.freeze(dt) do us.set_new_token us.delete_session expect(us.expires).to be < DateTime.now end end end
class AddOnboardedStateToAccounts < ActiveRecord::Migration[5.0] def change add_column :accounts, :onboarding_state, :string, default: "home_airports", null: false add_index :accounts, :onboarding_state remove_column :accounts, :onboarded_home_airports, :boolean, default: false, null: false remove_column :accounts, :onboarded_travel_plans, :boolean, default: false, null: false remove_column :accounts, :onboarded_type, :boolean, default: false, null: false remove_column :people, :onboarded_balances, :boolean, default: false, null: false remove_column :people, :onboarded_cards, :boolean, default: false, null: false end end
Spree::Order.class_eval do after_commit :touch_shipments private def touch_shipments self.shipments.update_all(updated_at: Time.now) end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :set_locale # if Rails.env.production? # before_filter :authenticate # protected # def authenticate # authenticate_or_request_with_http_basic do |username, password| # username == "jd2015" && password == "jd2015" # end # end # end private def allow_iframe response.headers.delete "X-Frame-Options" end def set_locale if cookies[:sp_locale] && I18n.available_locales.include?(cookies[:sp_locale].to_sym) l = cookies[:sp_locale].to_sym else l = I18n.default_locale cookies.permanent[:sp_locale] = l end I18n.locale = l end end
class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update, :destroy] # this 'before_filter' runs a method before the specified methods :edit and :update (ie only the owner of a profile can edit this profile). before_action :correct_user, only: [:edit, :update] # this will assure that the 'correct user' is accessing the page (i.e. an admin-only page or other user settings page) before_action :admin_user, only: [:destroy] # if the current user is not an admin, the 'destroy' method won't be executed. def index @users = User.where(paginate(page: params[:page])) # available from will_paginate on Gemfile end def new @user = User.new if request.env['PATH_INFO'] == "/registro_aluno" render :new_student elsif request.env['PATH_INFO'] == "/registro_professor" render :new_staff end end def show @user = User.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page]) #available from 'will_pagine' on Gemfile end def create @user = User.new(user_params) #uses the parameters (name: "aaa", email: "aaa",etc) posted in the URL after the 'submit' button on user/new is clicked on. #also note that '(params)' returns a hash of hashes, while (params[:user]) return the hash which contains the user's attributes. #the form is not secure just by (params[:user]), as any user can use CSRF attacks and, say, pass "admin=true" with curl and sign itself as an admin. #better to use the 'strong_params' convention of Rails 4 and permit only a pre-defined set of params to be passed by the user (see user_params below). if @user.save #default action for saved user. current_uri = request.env['PATH_INFO'] # if browsing 'http://google.com/hello/lolol', 'request.env['Path_INFO']' will return "/hello/lolol" if current_uri == "/registro_aluno" @user.update_attribute(:role, 1) elsif current_uri == "/registro_professor" @user.update_attribute(:role, 2) end role = {1 => "Aluno", 2 => "Professor"} #role for created user. # commented out since the account now needs to be activated. log_in(@user) #@user.send_activation_email # defined on /models/user.rb flash[:notice] = "#{role[@user.role]} registrado com sucesso!" #popup triggered when new account is created. # commented out since the account now needs to be activated. session[:user_id] = @user.id #session for the user is not created alongside the own user. # commented out since the account now needs to be activated. redirect_to @user #equivalent to 'redirect_to(user_url(@user))', rails infer the 'user_url()' method #redirect_to root_url else redirect_to root_url #renders the form page (the view [new], not the route [signup]) again (with errors output) if the user wasn't valid. end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update_attributes(user_params) # 'user_params' is used here to make use of the strong_params feature and prevent the mass assignment vulnerability (which could enable an user changing its account status to 'admin' for instance) flash[:success] = "Profile information was successfully updated." redirect_to @user else render 'edit' end end def destroy # 'destroy' and note 'delete' because while 'delete' only erases an user, 'destroy' runs validations before doing so. User.find(params[:id]).destroy flash[:success] = "User deleted." redirect_to users_url end private #private methods which are better off running exclusively on the back end of the app. def user_params #prevents CSRF attacks params.require(:user).permit(:name, :email, :password, :password_confirmation) #for the 'user' method in the 'params' object, only these attributes can be passed; all the rest are banned. end # Moved this method to application_controller.rb # def logged_in_user # unless logged_in? # store_location # defined on sessions_helper.rb # flash[:danger] = "Please log in." # redirect_to login_url # else # current_user # end # end def correct_user # define a method to check if the page requested by the user corresponds to the page the account should have access to. @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) # defined on helpers/sessions_helper.rb end def admin_user redirect_to(root_url) unless current_user.role == 1 # if the request wasn't sent by an admin, redirect to URL. Impossibilitate attacks to the website via command line (since even though the link is not displayed, the request can be sent unless specifically forbidden) end end
module CardValues SUITS = [ "♣︎", "♦︎", "♥︎", "♠︎" ] VALUES = { 2=>"2", 3=>"3", 4=>"4", 5=>"5", 6=>"6", 7=>"7", 8=>"8", 9=>"9", 10=>"10", 11=>"J", 12=>"Q", 13=>"K", 14=>"A" } HANDS = { high_card?:0, one_pair?:1, two_pair?:2, three_of_a_kind?:3, straight?:4, flush?:5, full_house?:6, four_of_a_kind?:7, straight_flush?:8 } end
# frozen_string_literal: true require 'rails_helper' RSpec.describe PropertiesController, type: :controller do let(:current_user) { create(:user) } let(:session) { { user_id: current_user.id } } let(:landlord1) { create(:landlord) } let(:landlord2) { create(:landlord) } let(:tenant1) { create(:tenant) } let(:tenant2) { create(:tenant) } let(:params) { {} } describe 'GET #tenancy_rent_record' do context 'when user is logged in' do let!(:property1) { create(:property, landlord_email: landlord1.email, rented: true, tenants_emails: tenant1.email, tenancy_security_deposit: 1500, tenancy_monthly_rent: 1500, tenancy_start_date: '07/02/2020') } let!(:property2) { create(:property, landlord_email: landlord2.email, rented: true, tenants_emails: tenant2.email, tenancy_security_deposit: 1500, tenancy_monthly_rent: 1500, tenancy_start_date: '07/02/2020') } subject { get :tenancy_rent_record, params: params, session: session } it 'property is rented and have valid details' do subject expect(property1.rented).to eq true expect(property2.rented).to eq true expect(property1.tenancy_monthly_rent).not_to be nil expect(property2.tenancy_monthly_rent).not_to be nil expect(property1.tenancy_security_deposit).not_to be nil expect(property2.tenancy_security_deposit).not_to be nil end it 'tenants information is/are available' do tenant1.update(property_id: property1.id) tenant2.update(property_id: property2.id) subject expect(property1.alltenants.map(&:id)).to eq([tenant1.id]) expect(property2.alltenants.map(&:id)).to eq([tenant2.id]) expect(property1.alltenants.map(&:email)).to eq([tenant1.email]) expect(property2.alltenants.map(&:email)).to eq([tenant2.email]) expect(property1.alltenants.map(&:full_name)).to eq([tenant1.full_name]) expect(property2.alltenants.map(&:full_name)).to eq([tenant2.full_name]) end it 'responds with 200 OK' do subject expect(response).to have_http_status(:ok) end end context 'when user is not logged in' do let(:current_user) { create(:user) } let(:session) { { user_id: current_user.id } } subject { get :tenancy_rent_record} it 'returns http forbidden status' do subject expect(response).to have_http_status(:forbidden) end it 'renders error page' do subject expect(response).to render_template('errors/not_authorized') end end end end
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are 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. require_relative 'utils' module FFWD # Struct used to define all fields related to an event. EventStruct = Struct.new( # The time at which the event was collected. :time, # The unique key of the event. :key, # A numeric value associated with the event. :value, # The host from which the event originated. :host, # The source event this event was derived from (if any). :source, # A state associated to the event. :state, # A description associated to the event. :description, # A time to live associated with the event. :ttl, # Tags associated with the event. :external_tags, # Tags which are statically provided by the internal implementation. :fixed_tags, # Attributes (extra fields) associated with the event. :external_attr, # Attributes which are statically provided by the internal implementation. :fixed_attr ) # A convenience class for each individual event. class Event < EventStruct def self.make opts = {} new(opts[:time], opts[:key], opts[:value], opts[:host], opts[:source], opts[:state], opts[:description], opts[:ttl], opts[:tags], opts[:fixed_tags], opts[:attributes], opts[:fixed_attr]) end # maintained for backwards compatibility, but implementors are encouraged # to use internal/external attributes directly. def attributes FFWD.merge_hashes fixed_attr, external_attr end def tags FFWD.merge_sets fixed_tags, external_tags end # Convert event to a sparse hash. def to_h d = {} d[:time] = time.to_i if time d[:key] = key if key d[:value] = value if value d[:host] = host if host d[:source] = source if source d[:state] = state if state d[:description] = description if description d[:ttl] = ttl if ttl if t = tags and not t.empty? d[:tags] = t end if a = attributes and not a.empty? d[:attributes] = a end d end end end
class AdminsController < ApplicationController before_action :redirect def index @users = User.where(approved: true) end def new @admin = Admin.new end def create @admin = Admin.new(admin_register_params) if @admin.save redirect_to admins_path, notice: 'Successfully created new Admin!' else redirect_to admins_new_path, alert: @admin.errors.full_messages.first end end protected def admin_register_params params.require(:admin).permit(:email, :password, :password_confirmation) end end
class OrdersController < ApplicationController before_action :set_order, except: [:new, :create, :show] # don't want to show only current order before_action :set_products, only: [:add_product, :update_quantity, :checkout] before_action :check_order, only: [:add_product] before_action :totals, only: [:update_quantity, :checkout] #:update_quantity, def new @order = Order.new end def create end def shipping @purchase_info = PurchaseInfo.new end def edit end def update end def show if Order.find_by(id: params[:id]).nil? flash[:notice] = "This order does not exist." redirect_to root_path else @order = Order.find(params[:id]) @products = @order.products # @stati = @order.order_products.map { |op| op.status } # unless (@stati.include? "pending") || (@stati.include? "paid") # @order.update(status:"complete") # end # commenting out above now does not update the orders status to # complete once all OPs are shipped # put a guard here to remove products from cart if you own it # (happens if bought as a guest then signed in) unless @products == nil? totals end end end def add_product if check_order flash[:notice] = "You already have this product in your cart!" redirect_to order_path(current_order) else @product = Product.find(params[:product_id]) if @product.inventory == 0 flash[:notice] = "This product is out of stock. Check back soon!" redirect_to root_path else @orderproduct = OrderProduct.new( order_id: current_order.id, product_id: params[:product_id], quantity: params[:quantity], status: "pending") if @orderproduct.save redirect_to order_path(current_order) # changes url else flash.now[:notice] = "There was a problem adding this item to the cart." # render doesn't show notice b/c generates page first render :show end end end end def remove_product @orderproduct = OrderProduct.find_by(order_id: current_order.id, product_id: params[:product_id]) @orderproduct.destroy redirect_to order_path(current_order) # why doesn't need to be current_order.id? end def update_quantity @orderproduct = OrderProduct.find_by(order_id: current_order.id, product_id: params[:product_id]) if @orderproduct.update(quantity: params[:quantity]) redirect_to order_path(current_order) else flash.now[:notice] = "There was problem updating your order." render :show end end def checkout @purchase_info = PurchaseInfo.new(params.require(:purchase_info).permit(:address, :address2, :city, :state, :zip_code)) if @purchase_info.save @order = current_order @products = current_order.products if @products @products.each do |product| @shippings = [] @shippings << HTTParty.post("http://localhost:4000/rates.json",{:body => {:origin => {:country => 'US', :state => "#{product.user.seller_state}", :city => "#{product.user.seller_city}", :zip => "#{product.user.seller_zipcode}"}, :destination => {:country => 'US', :state => "#{params[:purchase_info][:state]}", :city => "#{params[:purchase_info][:city]}", :zip => "#{params[:purchase_info][:zip_code]}"}, :package => {:weight => "#{product.weight}", :height => "#{product.height}", :depth => "#{product.depth}", :length => "#{product.length}"}}}) end end @purchase_info = PurchaseInfo.new current_order.products.each do |product| if product.inventory == 0 #make check inv method? flash[:notice] = "We are currently out of stock. Please modify your order." redirect_to order_path(current_order) elsif OrderProduct.find_by(product_id: product.id, order_id: current_order.id ).quantity > product.inventory flash[:notice] = "We have #{product.inventory} of those in stock. Please modify your order." redirect_to order_path(current_order) else # product.update( # inventory: product.inventory - OrderProduct.find_by( # product_id: product.id, # order_id: current_order.id # ).quantity) end end else render :shipping end end def start_purchase @purchase_info = PurchaseInfo.new(purchase_params) @purchase_info[:order_id] = current_order.id end def complete_purchase # @purchase_info = PurchaseInfo.new(purchase_params) # @purchase_info[:order_id] = current_order.id current_order.update(status: "paid") # session[:order_id] = nil # reset current order current_order.order_products.each do |op| op.update(status: "paid") end if @purchase_info.save flash[:notice] = "Thank you for your purchase! Your order should be shipped within 7-10 business days!" current_order = Order.new # This needs to archive paid order and open a new one redirect_to root_path else flash[:notice] = "There was an error processing your order." render :checkout end end private def check_user @orderu = current_order.user_id @orderu == session[:user_id] end # Checks if product already exists in an order def check_order @product = Product.find(params[:product_id]) OrderProduct.find_by(product_id: @product.id, order_id: current_order.id).present? end # Checks if any products in order are owned by the buyer # def check_products # @order = Order.find(params[:id]) # @user = User.find(@order.user_id) # @products = @order.products.each do |product| # if product.user_id == @user.id # flash[:notice] = "#{product} has been removed from your order!" # OrderProduct.find_by(product_id:product.id, # order_id: @order.id).destroy # end # end # end def set_order @order = current_order end def set_products @products = current_order.products end def totals @items = current_order.order_products.map { |x| x.quantity } @item_total = @items.inject(:+) @subtotals = @products.map do |product| product.price * OrderProduct.find_by( product_id: product.id, order_id: @order.id ).quantity end @total = @subtotals.reduce(:+) end def purchase_params params.require(:purchase_info).permit( :first_name, :last_name, :billing_first, :billing_last, :credit_card_number, :expiration_date, :cvv, :billing_address, :billing_address2, :billing_city, :billing_state, :billing_zip_code ) end helper_method :check_user end
name 'test' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' license 'Apache 2.0' description 'A test cookbook for lvm' version '0.1.0' depends 'lvm'
require 'test_helper' require 'generators/ember/bootstrap_generator' class BootstrapGeneratorTest < Rails::Generators::TestCase include GeneratorTestSupport tests Ember::Generators::BootstrapGenerator destination File.join(Rails.root, "tmp", "generator_test_output") setup :prepare_destination test "Assert folder layout and .gitkeep files are properly created" do run_generator [] assert_new_dirs end test "create bootstrap" do run_generator [] assert_file "#{ember_path}/ember-app.js.es6" assert_file "#{ember_path}/router.js.es6" end test "create bootstrap with and custom path" do custom_path = ember_path("custom") run_generator ["-d", custom_path] assert_file "#{custom_path}/ember-app.js.es6" assert_file "#{custom_path}/router.js.es6" end test "create bootstrap with custom app name" do run_generator ["-n", "MyApp"] assert_file "#{ember_path}/ember-app.js.es6", /MyApp = / assert_file "#{ember_path}/router.js.es6" end test "Uses config.ember.app_name" do with_config app_name: 'Blazorz' do run_generator assert_file "#{ember_path}/ember-app.js.es6", /Blazorz = / assert_file "#{ember_path}/router.js.es6" end end test "Uses config.ember.ember_path" do custom_path = ember_path("custom") with_config ember_path: custom_path do run_generator assert_file "#{custom_path}/ember-app.js.es6" assert_file "#{custom_path}/router.js.es6" end end end
Rails.application.routes.draw do resources :products # root 'welcome#index' end
class WordsAndMeaningsController < ApplicationController before_action :confirm_logged_in def index @words = Word.all.order("words.word ASC") end def show @word = Word.find(params[:id]) @meanings = Meaning.where("word_id=?",params[:id]) end def new # @word = Word.new @meaning = Meaning.new end def edit @word = Word.find(params[:id]) end def delete @word = Word.find(params[:id]) end def create @word = Word.new(word_params) @meaning = Meaning.new(meaning_params) if @word.save @meaning.word_id = @word.id if @meaning.save flash[:notice] = "Word has been saved succesfully" redirect_to(:action =>'show', :id => @word.id) end else render('new') end end def destroy word = Word.find(params[:id]).destroy Meaning.where(:word_id => params[:id]).destroy_all flash[:notice] = "Word '#{word.word}' has been destroyed succesfully" redirect_to(:action => 'index') end private def word_params params.require(:word).permit(:word, :synonym, :antonym) end private def meaning_params params.require(:word).permit(:figurative, :meaning, :example, :form) end end
class SightingsController < ApplicationController def index @sightings = Sighting.all if params[:region_id].nil? @sightings = Sighting.all else @sightings = Sighting.where(:region_id => params[:region_id]) end end def new @sighting = Sighting.new(params[:sighting]) # make an instance of new/inject it into view/ # make a hash called region_options that holds all the regions available to select from # in the form key and value @regions = Region.all render('sightings/new.html.erb') #render view end def create end def show end def edit end def update end def destroy end end
module CityRenderTreeHelper class Render class << self attr_accessor :h, :options def render_node(h, options) @h, @options = h, options node = options[:node] node.root? ? " <div class='span3'><div class='well well-small'> <h2 class='no-margin'>#{ show_link }</h2> #{ children } </div></div> " : "<li>#{ show_link }</li>" end def show_link "#{ h.link_to_category(options[:node], options[:city]) }" end def children unless options[:children].blank? "<ul>#{ options[:children] }</ul>" end end end end end
# @param {Integer[]} nums # @return {Boolean} def can_jump(nums) size = nums.size last_known_good = size - 1 (size-2).downto(0) do |i| last_known_good = i if i + nums[i] >= last_known_good end last_known_good == 0 end
class Organization < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :description, presence: true has_many :locations has_and_belongs_to_many :eligibilities def self.filter_organizations(params = {}) @organizations = Organization.all FilterOrganizations.new({organizations: @organizations, eligibilities: params[:eligibilities], query_type: params[:query_type]}).call end end
require './lib/engine' describe Engine do before do @e = 0 @n = Math::PI/2 @w = Math::PI @s = Math::PI*3/2 @engine = Engine.new(6,7) end it 'move forward to North' do @engine.process 'f', @n expect(@engine.x).to eq(6) expect(@engine.y).to eq(8) end it 'move backward to North' do @engine.process 'b', @n expect(@engine.x).to eq(6) expect(@engine.y).to eq(6) end it 'move forward to South' do @engine.process 'f', @s expect(@engine.x).to eq(6) expect(@engine.y).to eq(6) end it 'move backward to South' do @engine.process 'b', @s expect(@engine.x).to eq(6) expect(@engine.y).to eq(8) end it 'move forward to East' do @engine.process 'f', @e expect(@engine.x).to eq(7) expect(@engine.y).to eq(7) end it 'move backward to East' do @engine.process 'b', @e expect(@engine.x).to eq(5) expect(@engine.y).to eq(7) end it 'move forward to West' do @engine.process 'f', @w expect(@engine.x).to eq(5) expect(@engine.y).to eq(7) end it 'move backward to West' do @engine.process 'b', @w expect(@engine.x).to eq(7) expect(@engine.y).to eq(7) end end
class TasksMailer < ApplicationMailer def notify_task_owner(task, current_user) @task = task @owner = @task.user if @owner == current_user return end if @owner.email.present? mail(to: @owner.email, subject: "You got a new comment!") end end end
require 'test_helper' class TestOraclesControllerTest < ActionController::TestCase setup do @test_oracle = test_oracles(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:test_oracles) end test "should get new" do get :new assert_response :success end test "should create test_oracle" do assert_difference('TestOracle.count') do post :create, test_oracle: { content: @test_oracle.content } end assert_redirected_to test_oracle_path(assigns(:test_oracle)) end test "should show test_oracle" do get :show, id: @test_oracle assert_response :success end test "should get edit" do get :edit, id: @test_oracle assert_response :success end test "should update test_oracle" do patch :update, id: @test_oracle, test_oracle: { content: @test_oracle.content } assert_redirected_to test_oracle_path(assigns(:test_oracle)) end test "should destroy test_oracle" do assert_difference('TestOracle.count', -1) do delete :destroy, id: @test_oracle end assert_redirected_to test_oracles_path end end
class Player < ActiveRecord::Base belongs_to :team belongs_to :user has_many :score, :dependent => :destroy scope :top_scorer_for_teams, ->(team_ids) { where(team_id: team_ids).maximum(:points) } default_scope { order(:position) } class << self def for_user(game,user) team_ids = game.teams.pluck(:id) Player.where(team_id: team_ids, user_id: user.id).first end end def game self.team.game end def times_at_position(position) Player.where(user_id: self.user_id, position: position.to_s).count end def least_played_position f = times_at_position(:front) b = times_at_position(:back) f > b ? :back : :front end ## # Gives a point to the player # def score s = Score.new s.game = self.game s.player = self return false unless s.save s end ## # Takes away a point from the player # def unscore s = Score.for_player(self).last if s s.player = self return false unless s.destroy end s end ## # Sets the player to win the game # def win self.user.inc_stat(:wins) self.won = true self.finish end ## # Sets the player lose the game # def lose self.user.inc_stat(:losses) self.won = false self.finish end ## # finishes the game and stores a stat on position playing # def finish self.points_against = self.other_team.score self.user.inc_stat(('played_'+self.position).to_sym) self.user.inc_stat(:games) self.user.recalculate_ratios self.user.do_score self.save end ## # Tells if this player is the top scorer for the game # def top_scorer? team_ids = self.team.game.teams.pluck(:id) Player.top_scorer_for_teams(team_ids) == self.points end ## # Get the players team color # def team_color self.team.color.downcase end ## # Get the other team's color # def other_teams_color self.team_color == 'yellow' ? 'black' : 'yellow' end ## # Get the opposing team of the player # def other_team self.team.other_team end def inc_score_stats self.user.inc_stat(:scores) self.user.inc_stat(:score_as_front) if self.position == 'front' self.user.inc_stat(:score_as_back) if self.position == 'back' self.other_team.players.each do |p| p.user.inc_stat(:scored_against) p.user.inc_stat(:scored_against_as_front) if p.position == 'front' p.user.inc_stat(:scored_against_as_back) if p.position == 'back' end if self.other_team end def dec_score_stats self.user.dec_stat(:scores) self.other_team.players.each do |p| p.user.dec_stat(:scored_against) p.user.dec_stat(:scored_against_as_front) if p.position == 'front' p.user.dec_stat(:scored_against_as_back) if p.position == 'back' end if self.other_team end end
control '5_Appliance_NTP_5.1' do title 'Validate permissions and configuration of /etc/ntp.conf file' describe file ('/etc/ntp.conf') do it { should be_owned_by 'root' } it { should be_grouped_into 'root' } its('mode') { should cmp '0640' } end describe ntp_conf('/etc/ntp.conf') do its('setting_name') { should eq 'value' } its('restrict') { should include 'default kod nomodify notrap nopeer noquery'} its('restrict') { should include '-6 default kod nomodify notrap nopeer noquery'} its('restrict') { should include '127.0.0.1'} its('restrict') { should include '-6 ::1'} end end control '5_Appliance_NTP_5.2' do title 'Validate permissions and configuration of /etc/ntp.conf file' describe package ('ntp') do it {should be_installed} it {should be_enabled} it {should be_running} end end
require File.expand_path(File.join(File.dirname(__FILE__), *%w[.. .. spec_helper])) describe '/customers/show' do before :each do assigns[:customer] = @customer = Customer.generate!(:description => 'Test Customer') @apps = Array.new(3) { App.generate!(:customer => @customer) } end def do_render render '/customers/show' end it 'should display the name of the customer' do do_render response.should have_text(Regexp.new(@customer.name)) end it 'should display the description of the customer' do do_render response.should have_text(Regexp.new(@customer.description)) end it 'should include a link to edit the customer' do do_render response.should have_tag('a[href=?]', edit_customer_path(@customer)) end it 'should include a link to delete the customer if it is safe to delete the customer' do @customer.stubs(:safe_to_delete?).returns(true) do_render response.should have_tag('a[href=?]', customer_path(@customer), :text => /[Dd]elete/) end it 'should not include a link to delete the customer if it is not safe to delete the customer' do @customer.stubs(:safe_to_delete?).returns(false) do_render response.should_not have_tag('a[href=?]', customer_path(@customer), :text => /[Dd]elete/) end it 'should list the hosts the customer has deployments on' do deployed_services = Array.new(2) { DeployedService.generate! } @customer.apps << deployed_services.collect(&:app).flatten.uniq do_render @customer.hosts.each do |host| response.should have_text(Regexp.new(host.name)) end end it 'should include a link to add a new app' do do_render response.should have_tag('a[href=?]', new_customer_app_path(@customer)) end it 'should list the apps the customer owns' do do_render @apps.each do |app| response.should have_text(Regexp.new(app.name)) end end it 'should show a summary for each app' do @apps.each do |app| template.expects(:summarize).with(app) end do_render end describe 'parameters' do before :each do @customer.parameters = { 'field 1' => 'value 1', 'field 2' => 'value 2' } end it 'should show parameters for this customer' do do_render @customer.parameters.each_pair do |parameter, value| response.should have_text(/#{parameter}.*#{value}/) end end end end
require 'spec_helper' describe "delivery_requests/show" do before(:each) do @delivery_request = assign(:delivery_request, stub_model(DeliveryRequest, :name => "Name", :email => "Email", :telephone => "Telephone", :address => "Address", :postal_code => "Postal Code", :city => "City", :longitude => "Longitude", :latitude => "Latitude", :country => "Country", :serial_numbers => "Serial Numbers", :manufacturers => "Manufacturers", :crystalline_silicon => "Crystalline Silicon", :amorphous_micromorph_silicon => "Amorphous Micromorph Silicon", :laminates_flexible_modules => "Laminates Flexible Modules", :concentration_PV => "Concentration Pv", :CIGS => "Cigs", :CdTe => "Cd Te", :length => "Length", :witdh => "Witdh", :height => "Height", :weight => "Weight", :reason_of_disposal => "Reason Of Disposal", :modules_condition => "Modules Condition" )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers rendered.should match(/Name/) rendered.should match(/Email/) rendered.should match(/Telephone/) rendered.should match(/Address/) rendered.should match(/Postal Code/) rendered.should match(/City/) rendered.should match(/Longitude/) rendered.should match(/Latitude/) rendered.should match(/Country/) rendered.should match(/Serial Numbers/) rendered.should match(/Manufacturers/) rendered.should match(/Crystalline Silicon/) rendered.should match(/Amorphous Micromorph Silicon/) rendered.should match(/Laminates Flexible Modules/) rendered.should match(/Concentration Pv/) rendered.should match(/Cigs/) rendered.should match(/Cd Te/) rendered.should match(/Length/) rendered.should match(/Witdh/) rendered.should match(/Height/) rendered.should match(/Weight/) rendered.should match(/Reason Of Disposal/) rendered.should match(/Modules Condition/) end end
Blog::Application.routes.draw do get 'tags/:tag', to: 'articles#index', as: :tag resources :articles root to: 'articles#index' end
require 'rails_helper' describe Item do context 'attributes' do it { is_expected.to respond_to(:name) } it { is_expected.to respond_to(:description) } it { is_expected.to respond_to(:unit_price) } it { is_expected.to respond_to(:merchant_id) } it { is_expected.to respond_to(:updated_at) } it { is_expected.to respond_to(:created_at) } end context 'relationships' do it { is_expected.to belong_to(:merchant) } it { is_expected.to have_many(:invoice_items) } it { is_expected.to have_many(:invoices) } end end
class LandingController < ApplicationController def index @message = Message.new end def create @message = Message.new(params[:message]) if @message.valid? # TODO Send message here NotificationsMailer.new_message(@message).deliver redirect_to root_url, notice: "Message sent! Thank you for contacting us." else flash.now.alert = "Please fill all fields." render "index" end end end
class User < ApplicationRecord # So what this is saying is that a user will have a relationship with the memos and that a user can have # many memos and that it must have a name and an email but the name does not have to be unique but the email # does meaning if that a user signs up with the same name they will be accepted but not if they have the same # email has_many :memos validates :name, presence: true validates :email, presence: true, uniqueness: true # 1. Hash password before saving a User before_save :encrypt_password # 2. Generate a token for authentication before creating a User before_create :generate_token # 3. Adds a virtual password field, which we will use when creating a user attribute :password, :string def self.authenticate(email, password) # What this self.authenticate function essentially does for us is that is first finds the user by email to see if the user even exists before authenticating user = self.find_by_email(email) # Then what happens next is that we essentially hash the passed that the user has passed in and compare it to the hashed version that we have stored in our database and see # if the two hahsed passwords match and if they match successfully then the user has been authenticated properly but if the two do not match then user will be returned nil if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) # What is salting a password? # So in this case what we are doing is that this function takes in two parameters and those two parameters are password and user.password_salt and what that does is salt the # password that has been given and compares it against the salted version of the users stored password and then we hash that password and compare that hashed version to the hashed # version that the user has in the database # THE FUNCTION IS USED WHEN THE USER IS LOGGING IN WHICH IS SIMILAR TO SEE IF THE USER IS VERIFIED user else nil end end # Essentially what this function does for is is that we are encrypting the users password when the user signs up def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) end end # Generates a token for a user def generate_token token_gen = SecureRandom.hex self.token = token_gen token_gen end end
class Fertilizer < ActiveRecord::Base belongs_to :user has_many :fertilizations, dependent: :destroy validates_presence_of :name, :n, :p, :k, :s, :ca, :mg, :b end
require 'order' describe Order do let(:dish) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) } let(:dish2) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) } let(:dish3) { double(:dish, name: (0...8).map { (65 + rand(26)).chr }.join) } let(:quant) { rand(2...10) } let(:quant2) { rand(2...10) } let(:price) { rand(1...10) } let(:price2) { rand(1...10) } let(:menu) { double(:menu, view: {dish.name => price, dish2.name => price2}) } subject(:order) { described_class.new(menu)} describe '#initialize' do it 'is empty' do expect(order.summary).to be_empty end it 'has a total of zero' do expect(order.summary[:total]).to eq 0 end end describe '#add' do context 'valid order' do before{ order.add(dish, quant) ; order.add(dish2, quant) } let(:expected) { (menu.view[dish.name] + menu.view[dish2.name]) * quant } it 'adds the dish to the order' do expect(order.summary).to include(dish.name, dish2.name) end it 'adds the dish to the order the correct amount of times' do expect(order.summary[dish.name]).to eq quant end it 'updates the total' do expect(order.summary[:total]).to eq expected end end context 'item on menu' do it 'raises an error' do expect{ order.add(dish3, quant) }.to raise_error(Order::MENU_ERR) end end end end
module ApplicationHelper def include_css_for_controller(_controller_name) file = Rails.root.join('app', 'assets', 'stylesheets', "#{_controller_name}.scss") stylesheet_link_tag _controller_name if File.exist?(file) end end
# $LICENSE # Copyright 2013-2014 Spotify AB. All rights reserved. # # The contents of this file are 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. require_relative '../../utils' module FFWD::TCP class Connection INITIAL_TIMEOUT = 2 # default flush period, if non-zero will cause the connection to be buffered. DEFAULT_FLUSH_PERIOD = 10 # default amount of bytes that the outbound connection will allow in its # application-level buffer. DEFAULT_TCP_OUTBOUND_LIMIT = 2 ** 20 attr_reader :log, :peer, :reporter_meta def self.prepare opts opts[:flush_period] ||= DEFAULT_FLUSH_PERIOD opts[:tcp_outbound_limit] ||= DEFAULT_TCP_OUTBOUND_LIMIT opts[:ignored] = (opts[:ignored] || []).map{|v| Utils.check_ignored v} opts end def initialize log, host, port, handler, config @log = log @host = host @port = port @handler = handler @config = config @tcp_outbound_limit = config[:tcp_outbound_limit] @peer = "#{host}:#{port}" @closing = false @reconnect_timeout = INITIAL_TIMEOUT @reporter_meta = {:component => @handler.plugin_type, :peer => peer} @timer = nil @c = nil @open = false end # Start attempting to connect. def connect @c = EM.connect @host, @port, @handler, self, @config log.info "Connect to tcp://#{@host}:#{@port}" log.info " config: #{@config.inspect}" end # Explicitly disconnect and discard any reconnect attempts.. def disconnect log.info "Disconnecting from tcp://#{@host}:#{@port}" @closing = true @c.close_connection if @c @timer.cancel if @timer @c = nil @timer = nil end def send_event event @c.send_event event end def send_metric metric @c.send_metric metric end def send_all events, metrics @c.send_all events, metrics end def connection_completed @open = true @log.info "Connected tcp://#{peer}" @reconnect_timeout = INITIAL_TIMEOUT unless @timer.nil? @timer.cancel @timer = nil end end def unbind @open = false @c = nil if @closing return end @log.info "Disconnected from tcp://#{peer}, reconnecting in #{@reconnect_timeout}s" unless @timer.nil? @timer.cancel @timer = nil end @timer = EM::Timer.new(@reconnect_timeout) do @reconnect_timeout *= 2 @timer = nil @c = EM.connect @host, @port, @handler, self, *@args end end # Check if a connection is writable or not. def writable? not @c.nil? and @open and @c.get_outbound_data_size < @tcp_outbound_limit end end end
class Product < ActiveRecord::Base has_many :order_products has_many :product_orders, :through => :order_products scope :visible, -> { where(:visible => true) } validates_presence_of :name, :price, :bonus_points validates_numericality_of :quantity, :greater_than_or_equal_to => 0 mount_uploader :product_index_image, ProductImageUploader mount_uploader :product_show_image, ProductShowImageUploader end
class ApplicationController < ActionController::Base respond_to :json protect_from_forgery with: :exception rescue_from ActionController::UnknownFormat, ActionController::RoutingError do render_frontend end def render_frontend render text: 'ROUND loading...', layout: true end def tim? !!session[:tim] end helper_method :tim? end
panel t("reports.name.#{params[:action]}", :time_group => time_group_t, :time_period => time_period_t), :class => :table do block do @report = resource.visits_summary(params).sort {|a,b| a[params[:action]].to_i <=> b[params[:action]].to_i } if @report.empty? h3 t('reports.no_visits_recorded') else @total_visits = @report.map{|v| v.visits.to_i }.sum store @report.to_table(:percent_of_visits => @total_visits) end end end
class CreateBooksCategories < ActiveRecord::Migration[5.1] def change create_table :books_categories, { :primary_key => :id_category } do |t| t.string :category_name t.string :category_description t.timestamps end end end
class CreateTemplates < ActiveRecord::Migration def change create_table :templates do |t| t.string :name t.text :description t.string :keywords t.text :authors t.boolean :recommended t.string :source t.string :type t.text :documentation t.timestamps end add_index :templates, :keywords add_index :templates, :name create_table :images do |t| t.string :image_id t.string :name t.string :source t.text :description t.string :categories t.boolean :recommended t.string :type t.text :links t.text :command t.text :ports t.text :expose t.text :environment t.text :volumes t.integer :template_id t.timestamps end add_index :images, :image_id, unique: true add_index :images, :source end end
# frozen_string_literal: true # This version doesn't quite match Primer's third video # In his version, the original blobs mutate into specific other "species" of blobs # Mine individually mutates each stat. class Simulation def initialize(num_blobs, stats) @blobs = [] init_blobs(num_blobs, stats) end def init_blobs(num_blobs, stats) num_blobs.times do @blobs.push Blob.new(stats) end end def tick blobs_alive.each do |blob| blob.live_die # print blob.stats # puts "" if blob.alive? && blob.replicate? @blobs.push Blob.new(blob.new_stats(blob.stats)) end end display end def average_stat(stat_num) average = 0 blobs_alive.each do |blob| average += blob.stats[stat_num] end average /= blobs_alive.length end def display line_width = 30 stats = [ ['Total Blobs:', blobs_alive.length.to_s], ['Average Death Rate', average_stat(0).ceil(3).to_s], ['Average Replication Rate', average_stat(1).ceil(3).to_s], ['Average Mutation Rate', average_stat(2).ceil(3).to_s] ] stats.each do |stat| puts stat[0].ljust(line_width) + stat[1].rjust(line_width) end end def blobs_alive alive = [] @blobs.each do |blob| alive.push blob if blob.alive? end alive end end class Blob def initialize(stats) @death_rate = stats[0] @repli_rate = stats[1] @mutat_rate = stats[2] @alive = true end def alive? @alive end def live_die @alive = false if rand < @death_rate end def replicate? rand < @repli_rate end def stats [@death_rate, @repli_rate, @mutat_rate] end def mutate?(num) num < @mutat_rate end def new_stats(parent_stats) new_stats = [] parent_stats.each do |stat| mut_amount = rand if mutate?(mut_amount) 'mutation' # plus or minus? if rand > 0.5 new_stats.push (stat + mut_amount) else new_stats.push (stat - mut_amount) end else new_stats.push stat end end new_stats end end puts 'How many blobs shall we start with?' num_blobs = gets.to_i puts 'Press enter to start with basic stats (D, R, M):' # death rate, replicaction rate, mutation rate stats = [rand, rand, rand] puts stats gets.chomp sim = Simulation.new(num_blobs, stats) puts 'Press Enter for new tick. Type in anything to stop program' input = gets.chomp while input.empty? sim.tick input = gets.chomp end
require 'test_helper' class FeedbacksControllerTest < ActionController::TestCase def setup @admin = create(:admin) @writer = create(:writer) @submission = create(:submission, writer: @writer) @desc = create(:description, submission: @submission) @scrpi_response = create(:response, description: @desc) @feedback = create(:feedback, response: @scrpi_response) end test "should get new" do sign_in :writer, @writer get :new assert_response :success end test "should get index" do sign_in :admin, @admin get :index assert_response :success end test "should get show" do sign_in :admin, @admin get :show, id: @feedback end test "should save feedback" do sign_in :writer, @writer assert_difference("Feedback.count",1) do post :create, feedback: { rating: 1, comments: "good good good", complaints: "no no no", redressed: false } end assert_redirected_to root_path end test "shouldn't save feedback without rating" do sign_in :writer, @writer assert_difference("Feedback.count",0) do post :create, feedback: { rating: nil, comments: "good good good", complaints: "no no no", redressed: false, response_id: @scrpi_response } end assert_redirected_to response_path(@scrpi_response) end end
require 'rails_helper' RSpec.describe 'Items Index API' do before :each do FactoryBot.reload end describe 'happy path' do it 'fetch all items if per page is really big' do merchant = create(:merchant) items = create_list(:item, 50, merchant: merchant) get '/api/v1/items?per_page=250000' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true) expect(items).to have_key(:data) expect(items[:data]).to be_an(Array) expect(items[:data].count).to eq(50) end it 'fetch all items, a maximum of 20 at a time' do merchant = create(:merchant) items = create_list(:item, 50, merchant: merchant) get '/api/v1/items' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true)[:data] expect(items.count).to eq(20) items.each do |item| expect(item).to have_key(:id) expect(item).to have_key(:type) expect(item).to have_key(:attributes) expect(item[:attributes]).to have_key(:name) expect(item[:attributes]).to have_key(:description) expect(item[:attributes]).to have_key(:unit_price) expect(item[:attributes]).to have_key(:merchant_id) expect(item[:id]).to be_a(String) expect(item[:type]).to be_a(String) expect(item[:attributes]).to be_a(Hash) expect(item[:attributes][:name]).to be_a(String) expect(item[:attributes][:description]).to be_a(String) expect(item[:attributes][:unit_price]).to be_a(Float) expect(item[:attributes][:merchant_id]).to be_a(Integer) end end it 'fetching page 1 is the same list of first 20 in db' do merchant = create(:merchant) 80.times do |index| Item.create!(name: "Item-#{index + 1}", description: Faker::GreekPhilosophers.quote, unit_price: Faker::Commerce.price, merchant: merchant) end get '/api/v1/items?page=1' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true)[:data] expect(items.count).to eq(20) expect(items.first[:attributes][:name]).to eq("Item-1") expect(items.last[:attributes][:name]).to eq("Item-20") end it 'fetch first page of 50 items' do merchant = create(:merchant) 80.times do |index| Item.create!(name: "Item-#{index + 1}", description: Faker::GreekPhilosophers.quote, unit_price: Faker::Commerce.price, merchant: merchant) end get '/api/v1/items?per_page=50&page=1' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true)[:data] expect(items.count).to eq(50) expect(items.first[:attributes][:name]).to eq("Item-1") expect(items.last[:attributes][:name]).to eq("Item-50") end it 'fetch second page of 20 items' do merchant = create(:merchant) 80.times do |index| Item.create!(name: "Item-#{index + 1}", description: Faker::GreekPhilosophers.quote, unit_price: Faker::Commerce.price, merchant: merchant) end get '/api/v1/items?page=2' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true)[:data] expect(items.count).to eq(20) expect(items.first[:attributes][:name]).to eq("Item-21") expect(items.last[:attributes][:name]).to eq("Item-40") end it 'fetch a page of items which would contain no data' do merchant = create(:merchant) items = create_list(:item, 50, merchant: merchant) get '/api/v1/items?page=5' expect(response).to be_successful items = JSON.parse(response.body, symbolize_names: true)[:data] expect(items.count).to eq(0) expect(items).to be_empty end end describe 'sad path' do it 'fetching page 1 if page is 0 or lower' do merchant = create(:merchant) items = create_list(:item, 50, merchant: merchant) get '/api/v1/items?page=1' page1 = JSON.parse(response.body, symbolize_names: true)[:data] get '/api/v1/items?page=0' page2 = JSON.parse(response.body, symbolize_names: true)[:data] expect(response).to be_successful expect(page2.count).to eq(20) expect(page1).to eq(page2) end end end
# Zustand (state) + Configuration (params) #SRM_KernelBased_Config = Struct.new(:tau_m, :tau_ref, :ref_weight, :const_threshold, :arp) class SRM_KernelBased_Config attr_reader :tau_m, :tau_ref, :ref_weight, :const_threshold, :arp def initialize(tau_m: 0.0, tau_ref: 0.0, ref_weight: 0.0, const_threshold: 0.0, arp: 0.0) @tau_m = tau_m @tau_ref = tau_ref @ref_weight = ref_weight @const_threshold = const_threshold @arp = arp end def create_neuron Neuron_SRM_KernelBased.new(self) end end class Neuron_SRM_KernelBased attr_reader :mem_pot def initialize(cfg) @cfg = cfg @end_of_refr_period = 0.0 @last_spike_time = 0.0 @mem_pot = 0.0 end # Returns true if neuron fires, otherwise false. def spike(timestamp, weight) # Time since end of last absolute refractory period delta = timestamp - @end_of_refr_period # Abort if still in absolute refractory period return false if delta < 0.0 # Calculate dynamic threshold # Border condition: threshold = const_threshold (delta = inf) # ignore this border case. threshold = @cfg.const_threshold + @cfg.ref_weight * Math.exp(-delta / @cfg.tau_ref) # We don't have to care about the border case, # because @mem_pot is 0.0 at the beginning, so # whatever value @last_spike_time has, it does not # matter. d = timestamp - @last_spike_time if @cfg.tau_m > 0.0 decay = Math.exp(-d / @cfg.tau_m) @mem_pot *= decay @mem_pot += weight else @mem_pot = weight end # Update last spike time @last_spike_time = timestamp if @mem_pot >= threshold @end_of_refr_period = timestamp + @cfg.arp true else false end end end # tau_ref? K = SRM_KernelBased_Config.new(arp: 0.5, tau_m: 0.04, tau_ref: 0.5, const_threshold: 1.1) # Filter all spikes below 0.6 out Input = SRM_KernelBased_Config.new(arp: 1.0, tau_m: 0.0, tau_ref: 0.5, ref_weight: 0.0, const_threshold: 0.6) p K, Input n1 = Input.create_neuron p n1 for i in 1..100 t = i / 10.0 puts "------------------------------" p t fire = n1.spike(t, 0.6) p fire p n1 end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :word do name "MyString" definition "MyText" example "MyText" end end
class Api::QuestionsController < ApplicationController def index @questions = Question.all(); if topic_id @questions = Topic.find(topic_id).questions end render :index end def create @question = Question.new(question_params) if (current_user) @question.author_id = current_user.id else @question.author_id = 1 end if @question.save @user = current_user render :create else render json: { base: @question.errors.full_messages } end end def show @question = Question.find(params[:id]) render :show end def update @question = Question.find(params[:id]) if @question.update_attributes(question_params); render :show else render json: { base: @question.errors.full_messages } end end def destroy @question = Question.find(params[:id]) @question.destroy render :show end private def question_params params.require(:question).permit( :title, :description, topic_ids: [] ) end def topic_id params[:topic_id] end end
module ModelErrorMessages class Configuration attr_accessor :single_error_in_paragraph attr_accessor :prepend_html attr_accessor :append_html attr_accessor :classes attr_writer :configuration def initialize reset true end def reset @single_error_in_paragraph = true @prepend_html = '' @append_html = '' @classes = lambda do |model| [ 'alert', 'alert-danger', model.class.model_name.param_key + '-error-messages' ].join(' ') end end end def self.configuration @configuration ||= Configuration.new end def self.configure yield configuration end end
class Admin < ActiveRecord::Base attr_accessible :name, :phone_number, :email #validation validates :name, :presence => true validates :phone_number, :presence => true, :format => { :with => /\A[0-9]{10,14}\Z/, :message => 'only 10 to 12 digits allowed'}, :uniqueness => true validates :email, :presence => true, :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => "Email not valide" }, :uniqueness => true #callback before_validation :validate_email before_destroy :delete_user def validate_email errors.add(:email, 'all ready exist') if !(Student.find_by_email(self[:email]).nil? and Teacher.find_by_email(self[:email]).nil?) end def delete_user if !User.joins(:role).where(:roles => {:name => 'Admin'}, :users => { :employee_id => self[:id]}).nil? User.find_by_email(self[:email]).destroy end end end
require "spec_helper" require "securerandom" RSpec.describe CryptoEnvVar::Utils do describe "JSON serialization of Hashes" do let(:data) do { "ROMULUS" => SecureRandom.urlsafe_base64(100), "NUMA_POMPILIUS" => SecureRandom.urlsafe_base64(100), "TULLUS_HOSTILIUS" => SecureRandom.urlsafe_base64(100), "ANCUS_MARCIUS" => SecureRandom.urlsafe_base64(100), "LUCIUS_TARQUINIUS_PRISCUS" => SecureRandom.urlsafe_base64(100), "SERVIUS_TULLIUS" => SecureRandom.urlsafe_base64(100), "LUCIUS_TARQUINIUS_SUPERBUS" => SecureRandom.urlsafe_base64(100) } end it "serializes and deserializes Ruby Hashes" do json = described_class.serialize(data) expect(json).to be_a(String) out = described_class.deserialize(json) expect(out).to eql(data) end end describe "base64 encoding of raw data" do let(:data) { SecureRandom.random_bytes(1000) } specify "the raw data is indeed raw" do expect(data).to be_a String expect(data.force_encoding("UTF-8").valid_encoding?).to be false expect(data.ascii_only?).to be false end it "encodes and decodes bytes as a string" do base64 = described_class.encode(data) expect(base64).to be_a String expect(base64).to_not eql(data) out = described_class.decode(base64) expect(out).to eql(data) end specify "the encoded string is printable and portable" do base64 = described_class.encode(data) expect(base64.force_encoding("UTF-8").valid_encoding?).to be true expect(base64.ascii_only?).to be true end end end
class BlacklistedUsernamesController < ApplicationController def add usernames = split_param(:usernames) existing_usernames = Settings.get_list(:blacklisted_usernames) usernames = (existing_usernames | usernames).map(&:strip).reject(&:empty?).sort.join(',') Settings.set(:blacklisted_usernames, usernames) render_json Settings.get_list(:blacklisted_usernames) end end
module Todoable # Client for the Todoable API class Client API_ENDPOINT = "http://todoable.teachable.tech/api".freeze MEDIA_TYPE = "application/json".freeze AUTH_PATH = "/authenticate".freeze LISTS_PATH = "/lists".freeze attr_accessor :username, :password, :token def initialize @username = user @password = user_password end def authenticate_user result = HTTParty.post( API_ENDPOINT + AUTH_PATH, basic_auth: { username: @username, password: @password }, headers: { "Content-Type" => MEDIA_TYPE, "Accept" => MEDIA_TYPE } ) handle_response(result) @token = result["token"] end def get(path) url = generate_url(path) response = HTTParty.get(url, headers: set_headers) handle_response(response) response end def post(path, params) url = generate_url(path) response = HTTParty.post(url, body: params.to_json, headers: set_headers) handle_response(response) response end def patch(path, params) url = generate_url(path) response = HTTParty.patch(url, body: params.to_json, headers: set_headers) handle_response(response) response end def delete(path) url = generate_url(path) response = HTTParty.delete(url, headers: set_headers) handle_response(response) response end def put(path) url = generate_url(path) response = HTTParty.put(url, headers: set_headers) handle_response(response) response end private def user ENV["TODOABLE_USERNAME"] end def user_password ENV["TODOABLE_PASSWORD"] end def generate_url(path) "#{API_ENDPOINT}#{path}" end def handle_response(response) raise Todoable::ValidationError.new("Vallidation error with error response #{response.body}") if response.code == 422 raise Todoable::NotAuthenticatedError.new("Authentication failed, please re-authenticate!") if response.code == 401 raise Todoable::NotFoundError.new("Resource not found") if response.code == 404 end def set_headers raise "Not authenticated, please authenticate!" unless @token { "Content-Type" => "application/json", "Accept" => "application/json", "Authorization" => "Token token=#{@token}" } end end end
# Class to perform math on time-formatted strings. # Only implemented method is #add, which accepts a time string of # format '[H]H:MM {AM|PM}', adds the specified number of minutes # and outputs a similarly formatted string with the new time. class TimeStringCalc HOUR_RANGE = (1..12) # Allowed range of input hours. MIN_RANGE = (0..59) # Allowed range of input minutes. TIME_FORMATTER = "%d:%02d %s" # How output times should look. DAYPART_ADDITION = { # How many minutes are added by AM/PM? 'AM' => 0, 'PM' => 12*60 } # Add the given components. # # time_str - String representing the time to add to. # mins_to_add - Integer number of minutes to increase time_str by. # # Example: # # add("11:15 AM", 90) # # => "12:45 PM" # # Returns the new time String. def add(time_str, mins_to_add) parse_input(time_str, mins_to_add) calculate end # Figure out the raw number of minutes in our output time then # construct the output time string from that number. # # Returns the new time String. def calculate total_mins = hour_in_mins + @min + @mins_to_add TIME_FORMATTER % time_components(total_mins) end # The funny rules that format a raw time amount as AM/PM. # Make sure the hour returned is mod 24 in case the addition has # overflowed us into a different day. # # total_mins - Integer minute count to translate into time components # # Returns an [Integer,Integer,String] Array ready for formatting. def time_components(total_mins) hour = (total_mins/60) % 24 mins = total_mins % 60 case hour when 0 then [12, mins,'AM'] when 1..11 then [hour, mins,'AM'] when 12 then [hour, mins,'PM'] when 13..23 then [hour-12, mins,'PM'] end end # Convert an hour number to the equivalent in minutes, # accounting for AM/PM rules. # # Returns the number of minutes for the current @hour and @daypart. def hour_in_mins @hour -= 12 if @hour == 12 @hour*60 + DAYPART_ADDITION[@daypart] end # Parse and validate our input. # Run a regex over the time to extract its components and make sure it # meets our required format. Also ensure that the second arg is # actually an integer. We could validate that the inputs are in range # using the regular expression, but that would make it unreadable, so # use a separate validation method. # # Returns nothing special, but sets class variables. def parse_input(time_str, mins_to_add) unless time_str =~ /\A(\d\d?):(\d\d) ([AP]M)\Z/ raise TimeFormatError.new "'#{time_str}' not in format like '9:15 AM'" end @hour,@min,@daypart = [$1.to_i, $2.to_i, $3] unless (@mins_to_add=mins_to_add).is_a? Integer raise ArgumentError.new "#{mins_to_add} is not an Integer." end unless inputs_in_range? raise BadTimeError.new "#{time_str} is not a valid time" end end # Verify that the components of our time input make sense. # This should return false if passed a fake time like '13:99 PM'. # AM/PM not validated since the regex does this already. # # Returns a Boolean indicating the validity of our inputs. def inputs_in_range? HOUR_RANGE.include?(@hour) and MIN_RANGE.include?(@min) end end class TimeFormatError < ArgumentError;end class BadTimeError < RangeError;end
require 'spec_helper' require 'ios_toolchain/config_bootstrapper' RSpec.describe IosToolchain::ConfigBootstrapper do let(:project_root) { Dir.mktmpdir } let(:project_analyzer) { double('ProjectAnalyzer') } subject { IosToolchain::ConfigBootstrapper.new(project_analyzer) } describe('#bootstrap!') do let(:config_file_path) { File.join(project_root, '.ios_toolchain.yml') } before(:each) do allow(project_analyzer).to receive(:project_root).and_return(project_root) allow(project_analyzer).to receive(:project_file_path).and_return('project_file_path') allow(project_analyzer).to receive(:default_scheme).and_return('DefaultScheme') allow(project_analyzer).to receive(:app_targets).and_return(['Target1', 'Target2']) allow(project_analyzer).to receive(:test_targets).and_return(['Target1Tests', 'Target2Tests']) allow(project_analyzer).to receive(:ui_test_targets).and_return(['Target1UITests', 'Target2UITests']) allow(project_analyzer).to receive(:provisioning_path).and_return('provisioning_path') allow(project_analyzer).to receive(:crashlytics_framework_path).and_return('crashlytics_framework_path') subject.bootstrap! end it('writes a .ios_toolchain.yml file to project root') do expect(File.exists?(config_file_path)).to be(true) end describe('contents') do let(:yaml) { YAML.load_file(config_file_path) } it('writes correct project-file-path') do expect(yaml['project-file-path']).to eq('project_file_path') end it('writes correct default-scheme') do expect(yaml['default-scheme']).to eq('DefaultScheme') end it('writes default-sdk') do expect(yaml['default-sdk']).to eq('iphoneos10.2') end it('writes default-32bit-test-device') do expect(yaml['default-32bit-test-device']).to eq("'iOS Simulator,OS=10.2,name=iPhone 5'") end it('writes default-64bit-test-device') do expect(yaml['default-64bit-test-device']).to eq("'iOS Simulator,OS=10.2,name=iPhone 7'") end it('writes correct app-targets') do expect(yaml['app-targets']).to eq(['Target1', 'Target2']) end it('writes correct test-targets') do expect(yaml['test-targets']).to eq(['Target1Tests', 'Target2Tests']) end it('writes correct ui-test-targets') do expect(yaml['ui-test-targets']).to eq(['Target1UITests', 'Target2UITests']) end it('writes suggested provisioning-path') do expect(yaml['provisioning-path']).to eq('./provisioning') end it('writes correct crashlytics-framework-path') do expect(yaml['crashlytics-framework-path']).to eq('crashlytics_framework_path') end end end end
describe Represent::ResultsNormalized do let(:substance1) { Substance.new(name: 'Caffeine', common_name: 'Coffee', is_dangerous: false) } let(:test_kit1) { TestKit.new(name: 'marq', color: Color.new(name: 'red1')) } let(:test_kit2) { TestKit.new(name: 'blob', color: Color.new(name: 'red1')) } let(:results) {[ Result.new( colors: [Color.new(name: 'red2')], substance: substance1, test_kit: test_kit1, is_reacting: true, hint: 'looks cool', line_number: 1, ), Result.new( colors: [Color.new(name: 'blue2')], substance: substance1, test_kit: test_kit2, is_reacting: true, hint: 'looks even cooler', line_number: 2, ) ]} let!(:data) { Represent::ResultsPlain.call(results) } it 'builds results with dependent objects included' do expect(data[:results].count).to eq(2) result0 = data[:results][0] expect(result0[:substance][:name]).to eq(substance1.name) expect(result0[:test_kit][:name]).to eq(test_kit1.name) result1 = data[:results][1] expect(result1[:substance][:name]).to eq(substance1.name) expect(result1[:test_kit][:name]).to eq(test_kit2.name) end end
require "tick_tock/card" module TickTock class Punch < Value.new(:time_now) def self.default with(time_now: Time.method(:now)) end def card(subject: nil, parent_card: nil) Card.with( subject: subject, parent_card: parent_card, time_in: nil, time_out: nil ) end def in(card) card.with(time_in: time_now.call) end def out(card) card.with(time_out: time_now.call) end def parent_card_of(card) card.parent_card end end end
class RegionsController < ApplicationController before_action :set_region!, except: [:create, :index, :new] def index @regions = Region.all respond_to do |f| f.json {render json: @regions} f.html {render :index} end end def show @region = Region.find(params[:id]) end def edit end def new @region = Region.new end def create @region = Region.new end def update @region.update(region_params) if @region.save redirect_to @region else reder :edit end end private def set_region! @region = Region.find(params[:id]) end def region_params params.require(:region).permit(:country) end end
# frozen_string_literal: true require 'singleton' module Departments module Intelligence module Services ## # Validations for the inputs / outputs of the methods in {Departments::Intelligence} module. class Validation include Singleton def intelligence_query?(query) if query.class == Shared::IntelligenceQuery ip_address?(query.friendly_resource_ip) collect_format?(query.collect_format) return end error_message = "#{self.class.name} - #{__method__} - #{query}" error_message += " must be an instance of #{Shared::IntelligenceQuery.name}." throw StandardError.new(error_message) end def ip_address?(value) return if value.class == Integer && value.positive? error_message = "#{self.class.name} - #{__method__} - #{value} must be a positive #{Integer.name}." throw StandardError.new(error_message) end def collect_format?(value) return if Shared::IntelligenceFormat.formats.include?(value) error_message = "#{self.class.name} - #{__method__} - #{value}" error_message += "must be one of #{Shared::IntelligenceFormat.name} formats." throw StandardError.new(error_message) end end end end end
class String def from_german_to_f self.gsub(',', '.').to_f end end class Float def to_german_s self.to_s.gsub('.', ',') end end class CommissionsValueCombiner KEYS = [ 'Commission Value', 'ACCOUNT - Commission Value', 'CAMPAIGN - Commission Value', 'BRAND - Commission Value', 'BRAND+CATEGORY - Commission Value', 'ADGROUP - Commission Value', 'KEYWORD - Commission Value' ] def combine(hash) KEYS.each do |key| hash[key] = (@cancellation_factor * @saleamount_factor * hash[key][0].from_german_to_f).to_german_s end return hash end end
module YACCL module RelationshipServices def get_object_relationships(repository_id, object_id, include_sub_relationship_types, relationship_direction, type_id, filter, include_allowable_actions, max_items, skip_count, succinct=false) required = {succinct: succinct, cmisselector: 'relationships', repositoryId: repository_id, objectId: object_id} optional = {includeSubRelationshipTypes: include_sub_relationship_types, relationshipDirection: relationship_direction, typeId: type_id, filter: filter, includeAllowableActions: include_allowable_actions, maxItems: max_items, skipCount: skip_count} perform_request(required, optional) end end end
require 'csv' namespace :test do task :csv => :environment do CSV.open('issues_with_orders.csv','wb') do |csv| CSV.foreach(Rails.root.join('issues.csv')) do |line| id = line[0] subject = line[1] created_on = line[2] closed_on = line[3] budget = line[4] task = Task.find_by_external_id(id.to_s) unless task csv << [id,subject,created_on, closed_on, 'No task/order', budget] next unless task end if (orders = task.orders) && task.orders.any? csv << [id,subject,created_on, closed_on, orders.first.name, task.budget] else csv << [id,subject,created_on, closed_on, 'No order', budget] end end end end task :internal => :environment do Rake::Task["test:coffee"].invoke Rake::Task["test:coffee_new_sql"].invoke files = Dir.glob('spec/*_spec.js') messages = [] files.each do |file| begin Rake::Task["sql_data:load"].execute sh("jasmine-node --junitreport #{file}") rescue => e messages << file end end if messages.any? puts "Files with errors:" messages.each { |m| puts m } end end task :coffee => :environment do files = Dir.glob('spec/*_spec.coffee') messages = [] files.each do |file| next if file.match(/new_sql/) begin Rake::Task["sql_data:load"].execute sh("jasmine-node --coffee --junitreport #{file}") rescue => e messages << file end end if messages.any? puts "Files with errors:" messages.each { |m| puts m } end end task :coffee_new_sql => :environment do files = Dir.glob('spec/*new_sql*_spec.coffee') messages = [] files.each do |file| begin Rake::Task["sql_data:load2"].execute sh("jasmine-node --coffee --junitreport #{file}") rescue => e messages << file end end if messages.any? puts "Files with errors:" messages.each { |m| puts m } end end task :cf => :environment do Rake::Task["sql_data:load"].execute sh("jasmine-node --coffee --verbose --junitreport spec/complete_order_commission_spec.coffee") end end
class NotificationsMailer < ActionMailer::Base default :from => "sales@sweepevents.com" default :to => "sales@sweepevents.com" def new_message(message) @message = message mail(:subject => "Website Contact Request", :body => "Name: #{@message.name}\nEmail: #{@message.email}\nDescription: #{@message.content}") end end
class Knotebook < ActiveRecord::Base belongs_to :user has_many :knotings, :order => :position, :dependent => :destroy has_many :knotes, :through => :knotings, :order => 'knotings.position', :before_add => :set_knote_user # has_many :conceptualizations # has_many :concepts, :through => :conceptualizations, :source => :topic has_many :comments, :as => :commentable has_many :favorites, :foreign_key => :original_id self.inheritance_column = "knotebook_type" validates_length_of :title, :within => 3..80 validates_length_of :abstract, :within => 10..400 # validates_presence_of :knotes validates_presence_of :title, :abstract # accepts_nested_attributes_for :knotes, :reject_if => :all_blank default_scope :include => [:user, :knotings, :knotes], :conditions => { :knotebook_type => "Knotebook", :ignore => false } named_scope :featured, :conditions => { :featured => true } def self.everyone(whom) with_exclusive_scope { find(whom || :all) } end searchable do text :title, :boost => 8 text :abstract, :boost => 7 # text :author, :boost => 4 do # user.login # end text :subtitle, :boost => 6 do knotes.map &:title end text :content, :boost => 5 do knotes.map &:content end text :concept, :boost => 10 do knotes.map &:concepts_list end string :knotebook_type end def self.model_name name = ActiveSupport::ModelName.new "knotebook" name.instance_eval do def plural; pluralize; end def singular; singularize; end end return name end def build_favorite(knote_ids=[], options={}) favorite = self.favorites.build(options.merge attributes) knotes = Knote.find(knote_ids) favorite.knotes = knote_ids.inject([]){|res,val| res << knotes.detect {|k| k.id == val.to_i }} favorite end def build_knote if !knotes.empty? && knotes.last.new_record? knotes.last else knotes.build end end def set_knote_user(knote) if knote.user.nil? knote.new_record? ? knote.user_id = user_id : knote.update_attribute(:user_id, user_id) end end def self.all_of_dems(id) with_exclusive_scope { find(id) } end def add_topics(*args) args.each do |arg| arg = arg.split(Concept::CONCEPT_DELIMITER) if arg.is_a? String arg.each do |topic| topic = Concept.find_or_create_by_name(topic) topics << topic unless topics.index(topic) end end end def original Knotebook.find(original_id) end def concepts_list self.knotes.map(&:concepts).flatten.uniq.map(&:name) end def concepts concepts_list.join(Concept::CONCEPT_DELIMITER) end def topics topics_list.join(', ') end def topics_list topics.collect(&:name) end # def concepts_list # knotes.collect(&:concepts_list).flatten.uniq # end # # def set_concepts # tags.each do |t| # t.tags knotes.collect(&:tags).flatten.uniq # end # end # # def add_concept(concept) # tags.each do |t| # t._add_tags concept # end # end def self.to_fixture File.open(File.expand_path("test/fixtures/#{table_name}.yml", RAILS_ROOT), "w") do |file| file << self.find(:all).inject("---\n") do |s, record| self.columns.inject(s+"#{record.id}:\n") do |s, c| s+" #{{c.name => record.attributes[c.name]}.to_yaml[5..-1]}" end end end end def author self.user.name end end
module Paramable module IntanceMethods def to_param name.downcase.gsub(' ', '-') end end end
class Recipe < ActiveRecord::Base belongs_to :user has_many :ingredients, dependent: :destroy validates :name, presence: true validates :instruction, length: { maximum: 1000 } validates :user_id, presence: true end
require 'minitest/autorun' require_relative '../board.rb' class TestBoard < Minitest::Test def test_for_3x3Board board = Board.new(3,3) result = [['-','-','-'],['-','-','-'],['-','-','-']] assert_equal(result, board.board_table) end def test_for_4x4Board board = Board.new(4,4) result = Array.new(4,'-'){ Array.new(4,'-')} assert_equal(result, board.board_table) end def test_printBoard_4_x_4 board = Board.new(4,4) board.printBoard end def test_printBoard_27_x_27 board = Board.new(27,27) board.printBoard end end
# frozen_string_literal: true require_relative './modules/accessor.rb' require_relative './modules/instance_counter.rb' require_relative './modules/validation.rb' class Station include InstanceCounter, Accessor, Validation attr_reader :name attr_accessor :trains REGEXP = /[a-z]/i.freeze validate :name, :format, REGEXP @@stations_list = [] def initialize(name) @name = name @trains = [] @@stations_list << self register_instance validate! end def trains_each @trains.each { |train| yield(train) } end def self.all @@stations_list end def add_train(train) @trains << train end def send_train(train) @trains.delete(train) end end
class CreateTerritories < ActiveRecord::Migration def change create_table :territories do |t| t.string :name, uniqueness: true t.jsonb :zips, default: '{}' t.jsonb :zones, default: '{}' t.timestamps null: false end add_index :territories, :name end end
#require "spec_helper" describe "Viewing an individual movie" do it "show the movie's details" do # Arrange movie = Movie.create(movie_attributes(image: open("#{Rails.root}/app/assets/images/movie.jpg"), total_gross: 300_000_000.00)) # Action visit movie_url(movie) # Assert expect(page).to have_text(movie.title) expect(page).to have_text(movie.description) expect(page).to have_text(movie.rating) expect(page).to have_text(movie.released_on) expect(page).to have_text("$300,000,000.00") expect(page).to have_text(movie.cast) expect(page).to have_text(movie.director) expect(page).to have_text(movie.duration) #expect(page).to have_selector("img[src$='#{movie.image_file_name}']") expect(page).to have_selector("img[src$='#{movie.image.url(:small)}']") end it "shows a placeholder image when the movie image is not available" do movie = Movie.create(movie_attributes(image: nil)) # Action visit movie_url(movie) # Assert expect(page).to have_text(movie.title) expect(page).to have_selector("img[src$='placeholder.png']") # src$='' somehow acts a wildcard for any img tag #expect(page).to have_selector("img[src$='']") end it "shows the total gross if the total gross is $50M or more" do # Arrange movie = Movie.create(movie_attributes(total_gross: 50_000_000)) # Action visit movie_url(movie) # Assert expect(page).to have_text("$50,000,000.00") end it "shows 'Flop!' if the total gross is less than $50M" do # Arrange movie = Movie.create(movie_attributes(total_gross: 49_999_999.99)) # Action visit movie_url(movie) # Assert expect(page).to have_text("Flop!") end it "shows the movie's fans and genres in the side bar" do # Arrange movie = Movie.create!(movie_attributes) fan1 = User.create!(user_attributes(name: "Joe", username: "joe", email: "joe@example.com")) fan2 = User.create!(user_attributes(name: "Mary", username: "mary", email: "mary@example.com")) genre1 = Genre.create!(genre_attributes(name: "Action")) genre2 = Genre.create!(genre_attributes(name: "Comedy")) movie.fans << fan1 movie.genres << genre1 # Action visit movie_url(movie) # Assert within("aside#sidebar") do expect(page).to have_text(fan1.name) expect(page).not_to have_text(fan2.name) expect(page).to have_text(genre1.name) expect(page).not_to have_text(genre2.name) end end it "shows the movie's title in the page title" do # Arrange movie = Movie.create!(movie_attributes(title: "Iron Man")) # Action visit movie_url(movie) # Assert expect(page).to have_title("Flix - #{movie.title}") end it "has an SEO-friendly URL" do # Arrange movie = Movie.create!(movie_attributes(title: "X-Men: the Last Stand")) # Action visit movie_url(movie) # Assert expect(current_path).to eq("/movies/x-men-the-last-stand") end end
class InstagramAuth < Authorization def self.model_name Authorization.model_name end def auth_type return "Instagram" end def access_client auth_client_obj = OAuth2::Client.new(Rails.application.config.auth["instagram"][:client_id], Rails.application.config.auth["instagram"][:client_secret], {:site => 'https://api.instagram.com', :authorize_url => "/oauth/authorize", :token_url => "/oauth/access_token"}) auth_client_obj end def access_url url=self.access_client.auth_code.authorize_url(:response_type => "code", :redirect_uri => Rails.application.config.auth["instagram"][:redirect_uri]) end def access_token access_token_obj = OAuth2::AccessToken.new(self.access_client,auth_token) return access_token_obj end def is_expired? false end def check_valid?(result) true end def check_access_token access_client = self.access_client begin access_token = access_client.auth_code.get_token(params[:code],{:redirect_uri=>Rails.application.config.auth["instagram"][:redirect_uri],:token_method=>:post}) self.auth_token=access_token.token rescue self.errors.add :base, "Couldn't get Instagram authorization!!" end end def instagram_client Instagram.client(:access_token => self.auth_token) end def get_photos(limit = 5) client = self.instagram_client photos = client.user_recent_media(:count => limit) photos end end
class ApiChecklistsForUserContext < ApiBaseContext def initialize(user) super end def execute Checklist.for_user(@user).select(:id, :name, :description).all end end
class RoundsController < ApplicationController # GET /rounds # GET /rounds.json def index rounds_decorator = RoundsDecorator.new(Round.all) current_round = Round.current_round respond_to do |format| format.html format.json do render json: { round: current_round, fixtures: current_round.fixture_stats, rounds: rounds_decorator.all_data } end end end # GET /rounds/1 # GET /rounds/1.json def show round_decorator = RoundDecorator.new(Round.find_by(id: params[:id])) respond_to do |format| format.html format.json { render json: { round: round_decorator, fixtures: round_decorator.fixture_stats } } end end private # Never trust parameters from the scary internet, only allow the white list through. def round_params params.fetch(:round, {}) end end
require 'csv' require_relative 'order' module Grocery class OnlineOrder < Order SHIPPING_COST = 10 attr_reader :customer_id, :status def initialize(id, products, customer_id, status=:pending) super(id, products) @customer_id = customer_id @status = status end def total if products.length > 0 return super + SHIPPING_COST end return 0.0 end def add_product(product_name, product_price) if @status == :paid || @status == :pending return super else raise ArgumentError.new("Too late to add a new product") end end def self.order_from_line(line) products = self.products_from_line(line) return Grocery::OnlineOrder.new(line[0].to_i, products, line[2].to_i, "#{line[3]}".to_sym) end def self.all(file) orders = [] CSV.open(file, "r").each do |line| orders << self.order_from_line(line) end return orders end def self.find_by_customer(customer_id, file) customer_orders = [] CSV.open(file, "r").each do |line| if line[2] == customer_id.to_s customer_orders << self.order_from_line(line) end end if customer_orders.length > 0 return customer_orders else raise ArgumentError.new("Customer not found") end end end #end of class OnlineOrder end #end of module Grocery
require 'spec_helper' require_relative '../../app/models/user' module LunchZone describe 'user' do let(:user) { User.create(:nickname => 'hungryguy', :email => 'a@example.com') } let(:restaurant1) { Restaurant.create(:name => 'QQ Sushi') } let(:restaurant2) { Restaurant.create(:name => 'Academic') } it 'has restaurants via cravings' do user.new_craving(restaurant1) user.new_craving(restaurant2) user.restaurants.all.should == [restaurant1, restaurant2] end describe 'to_json' do it 'excludes the partnerpedia_employee field' do user.to_json.should_not match(/partnerpedia_employee/) end it 'excludes the token field' do user.to_json.should_not match(/token/) end end end end
require 'rack/test' require 'bundler' Bundler.require(:test) require 'capybara/rspec' ENV['RACK_ENV'] = 'test' require File.expand_path '../../application.rb', __FILE__ # VCR.configure do |c| # c.cassette_library_dir = 'spec/cassettes' # c.hook_into :webmock # end RSpec.configure do |config| include Rack::Test::Methods def app Rack::URLMap.new( '/api' => ApiController ) end Capybara.app = app config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) begin DatabaseCleaner.start ensure DatabaseCleaner.clean end end config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.shared_context_metadata_behavior = :apply_to_host_groups config.filter_run_when_matching :focus config.disable_monkey_patching! config.warnings = true config.default_formatter = 'doc' if config.files_to_run.one? config.order = :random Kernel.srand config.seed RspecApiDocumentation.configure do |config| config.app = app config.format = :json end config.include JsonSpec::Helpers end