text
stringlengths
10
2.61M
class RemoveNameFromGroups < ActiveRecord::Migration[6.0] def change remove_column :groups, :name end end
class Admin::DeliveriesController < AdminController before_action :set_delivery, only: [:show, :edit, :update, :destroy] set_tab :deliveries # GET /admin/deliveries # GET /admin/deliveries.json def index params[:delivery] ||= {} @deliveries = Delivery.includes(:custom).order(signed_at: :desc) if params[:delivery][:username].present? if params[:username_like_match] #changed by kailaichao, 不需要关联custom,因为delivery的receiver等于custom的username或者mobile # @deliveries = @deliveries.includes(:custom) # .where('customs.username like ?', "%#{params[:delivery][:username]}%") # .references(:customs) # end change @deliveries = @deliveries.where('reciever like ?', "%#{params[:delivery][:username]}%") else #changed by kailaichao, 不需要关联custom,因为delivery的receiver等于custom的username或者mobile # @deliveries = @deliveries.includes(:custom) # .where('customs.username = ?', params[:delivery][:username]) # .references(:customs) # end change @deliveries = @deliveries.where('reciever = ?', params[:delivery][:username]) end end # 新增了验证码快件类型,即手机用户,手机用户都是自提 if params[:need_service].present? if params[:need_service] == "2" @deliveries = @deliveries.where.not(verify_code: nil) else @deliveries = @deliveries.where(need_service: params[:need_service] == '1') end end #todo timezone https://ruby-china.org/topics/3254 @deliveries = @deliveries.after_day(params[:delivery][:after_date], :created_at) .before_day(params[:delivery][:before_date], :created_at) @deliveries = @deliveries.includes(:station).stations_match( province: params[:province], city: params[:city], district: params[:district], service_code: params[:delivery][:service_code] ) if params[:signed].present? @deliveries = @deliveries.where(status: 4) end @deliveries = @deliveries.includes(:station).page params[:page] end # GET /admin/deliveries/1 # GET /admin/deliveries/1.json def show end # GET /admin/deliveries/new def new @delivery = Delivery.new end # GET /admin/deliveries/1/edit def edit end # POST /admin/deliveries # POST /admin/deliveries.json def create @delivery = Delivery.new(delivery_params) respond_to do |format| if @delivery.save format.html { redirect_to [:admin, @delivery], notice: '创建成功!' } format.json { render action: 'show', status: :created, location: @delivery } else format.html { render action: 'new' } format.json { render json: @delivery.errors, status: :unprocessable_entity } end end end # PATCH/PUT /admin/deliveries/1 # PATCH/PUT /admin/deliveries/1.json def update respond_to do |format| if @delivery.update(delivery_params) format.html { redirect_to [:admin, @delivery], notice: '更新成功!' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @delivery.errors, status: :unprocessable_entity } end end end # DELETE /admin/deliveries/1 # DELETE /admin/deliveries/1.json def destroy #todo 删除的话统计信息会不准,如何处理? @delivery.destroy respond_to do |format| format.html { redirect_to admin_deliveries_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_delivery @delivery = Delivery.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def delivery_params params.require(:delivery).permit(:username) end end
class CreateUnits < ActiveRecord::Migration def change create_table :units do |t| t.string :name t.string :symbol t.timestamps null: false end add_column :act_indicator_relations, :unit_id, :integer, null: true add_column :measurements, :unit_id, :integer, null: true Unit.find_or_create_by(symbol: '€', name: 'Euro') end end
require 'test_helper' class CountryTest < ActiveSupport::TestCase test "has a valid factory" do assert FactoryBot.build(:country).save end test "is invalid without a name" do assert_not FactoryBot.build(:country, name: nil).save end test "is invalid without a unique name" do FactoryBot.build(:country, name: "Test123").save assert_not FactoryBot.build(:country, name: "Test123").save end end
require 'minitest/autorun' require 'minitest/pride' require_relative 'greet_me' # main test class class GreetMeTest < Minitest::Test def setup @jill = Person.new('Jill') @jack = Person.new('Jack') end def test_jack_greet_jill assert_equal(@jack.greet('Jill'), 'Hello Jill, my name is Jack') end def test_jack_greet_mary assert_equal(@jack.greet('Mary'), 'Hello Mary, my name is Jack') end def test_jill_greet_jack assert_equal(@jill.greet('Jack'), 'Hello Jack, my name is Jill') end def test_jill_name assert_equal(@jill.name, 'Jill', "Person's name could not be retrieved") end end
class Car attr_reader :fuel, :make, :model, :year def initialize (input_options) @speed = 0 @direction = 'north' @fuel = input_options[:fuel] @make = input_options[:make] @model = input_options[:model] @year = input_options[:year] end include Vehicle_Behavior def honk_horn puts "Beeeeeeep!" end def print_info p "This #{year} #{make} #{model} has #{fuel} gallons of fuel left." end end
class Activity < ApplicationRecord extend Mobility translates :name, :description FIELDS = %i[name description admin_notes].freeze has_and_belongs_to_many :disciplines has_many :activity_clubs, dependent: :destroy has_many :clubs, through: :activity_clubs has_many :links, as: :linkable validates :name, presence: true, uniqueness: true end
class PlayerSearch def initialize(query:) @query = query.to_s @words = parsed_words @results = [] end def search if words.size == 2 by_full_name end if results.empty? by_single_word end results.flatten end private def by_single_word words.map(&:downcase).each do |word| if word_is_number?(word) results << Player.where(birth_year: word.to_i) else results << Player.where('LOWER(first_name) = ?', word).or(Player.where('LOWER(last_name) = ?', word)) end end end def by_full_name results << Player.where("LOWER(first_name || ' ' || last_name) LIKE ?", "%#{words.join(' ').downcase}%") results.flatten! end def parsed_words query.gsub(/\s+/, ' ').split(' ') end def word_is_number?(word) (word =~ /\A[-+]?[0-9]+\z/) end attr_reader :query attr_accessor :results, :words end
class Institution < ApplicationRecord belongs_to :submission has_one :transcript end
require 'rspec' require './lib/redfig' describe Redfig do before :each do r = Redis.new r.flushall end describe "redfig" do it "Sets app and env" do redfig = Redfig.new app: 'my_app', env: 'my_env' redfig.app.should == 'my_app' redfig.env.should == 'my_env' end it "Sets the default prefix to 'redfig'" do redfig = Redfig.new app: 'my_app', env: 'my_env' Redis.any_instance.stub(:set) do |key| key.split(':').first.should == 'redfig' end redfig.set! 'test_key', 'test_value' end it "Lets you set a specific prefix" do redfig = Redfig.new app: 'my_app', env: 'my_env', redis: {prefix: 'my_prefix'} Redis.any_instance.stub(:set) do |key| key.split(':').first.should == 'my_prefix' end redfig.set! 'test_key', 'test_value' end it "Stores parameters in Redis" do redfig = Redfig.new app: 'my_app', env: 'my_env' redfig.set! 'test_namespace:test_key', 'test_value' key = "redfig:my_env:my_app:test_namespace:test_key" redfig.redis.get(key).should == 'test_value' end # it "Loads parameters from yml" do # file = mock 'file' # file.stub # end end end
# frozen_string_literal: true module PhraseServices # Service which will create phrase for the recipient. Given a raw data and ID # of recipient then output a Phrase and a Recipient # # @!attribute [r] recipient # @return [Recipient] the recipient who owning phrase # @!attribute [r] phrase # @return [Phrase] the created phrase # @example # PhraseServices::Creator.new({term: "String"}, recipient_uid: 1).call class Creator attr_reader :recipient, :phrase # @param [Hash<String>] data # @option data [String] :term Required # @option data [String] :spelling # @option data [String] :meaning # @param [String, Integer] recipient_uid ID of recipient from message # @return [self] def initialize(data, recipient_uid:) @data = data @recipient_uid = recipient_uid end # Create a Recipient and a Phrase if they are not existed yet # @return [self] def call @recipient = Recipient.find_or_create_by(uid: recipient_uid) @phrase = Phrase.find_or_create_by(term: data[:term], recipient: @recipient) do |phr| phr.meaning = data[:meaning] phr.spelling = data[:spelling] end self end private attr_reader :data, :recipient_uid end end
# frozen_string_literal: true require "test_helper" class ClientOptionsTest < Minitest::Test let(:app) { ->(env) { } } let(:strategy) do OmniAuth::Strategies::Netlify.new(app, "consumer_id", "consumer_secret") end test "sets name" do assert_equal "netlify", strategy.options.name end test "sets authorize url" do assert_equal "https://app.netlify.com/authorize", strategy.options.client_options.authorize_url end test "sets token url" do assert_equal "https://api.netlify.com/oauth/token", strategy.options.client_options.token_url end end
class ImportTask < ApplicationRecord enum status: [:processing, :failure, :success] mount_uploader :file, ImportTaskUploader mount_uploader :log, ImportTaskUploader def importer_class "#{importer_type}Importer".constantize end end
class Student include Mongoid::Document field :name, type: String field :grandchildren_ids, type: Array, default: [] # Validation validates :name, presence: true, uniqueness: true # Associations has_many :children, class_name: 'Student', foreign_key: 'parent_id' belongs_to :parent, class_name: 'Student', optional: true def grandchildren Student.find(grandchildren_ids) end end
require 'spec_helper' describe SportsDataApi::Nfl::Standings, vcr: { cassette_name: 'sports_data_api_nfl_standings', record: :new_episodes, match_requests_on: [:host, :path] } do let(:standings) do SportsDataApi.set_key(:nfl, api_key(:nfl)) SportsDataApi.set_access_level(:nfl, 't') SportsDataApi::Nfl.standings(2013, :REG) end let(:pats) { standings.afc[:divisions]["AFC_EAST"][:teams].first } let(:eagles) { standings.nfc[:divisions]["NFC_EAST"][:teams].first } context 'results from standings fetch' do subject { standings } it { should be_an_instance_of(SportsDataApi::Nfl::Standings) } its(:season) { should eq 2013 } its(:type) { should eq "REG" } its(:nfc) { should be_an_instance_of(Hash) } its(:afc) { should be_an_instance_of(Hash) } it '#afc' do expect(subject["AFC"]).to be_an_instance_of(Hash) expect(subject["afc"]).to be_an_instance_of(Hash) expect(subject["AFC"][:name]).to eq "AFC" expect(subject["afc"][:name]).to eq "AFC" end it '#nfc' do expect(subject["NFC"]).to be_an_instance_of(Hash) expect(subject["nfc"]).to be_an_instance_of(Hash) expect(subject["NFC"][:name]).to eq "NFC" expect(subject["nfc"][:name]).to eq "NFC" end it '#error' do expect { subject["notreal"] }.to raise_error(SportsDataApi::Nfl::Exception) end end context 'results from standings : AFC' do subject { standings.afc } it '#AFC_EAST' do expect(subject[:divisions]["AFC_EAST"]).to be_an_instance_of(Hash) expect(subject[:divisions]["AFC_SOUTH"]).to be_an_instance_of(Hash) expect(subject[:divisions]["AFC_NORTH"]).to be_an_instance_of(Hash) expect(subject[:divisions]["AFC_WEST"]).to be_an_instance_of(Hash) expect(subject[:divisions]["AFC_EAST"][:name]).to eq "AFC East" expect(subject[:divisions]["AFC_SOUTH"][:name]).to eq "AFC South" expect(subject[:divisions]["AFC_NORTH"][:name]).to eq "AFC North" expect(subject[:divisions]["AFC_WEST"][:name]).to eq "AFC West" end it '#name' do expect(subject[:name]).to eq "AFC" end it '#conferences' do expect(subject[:divisions]).to be_an_instance_of(Hash) expect(subject[:divisions].length).to eq 4 end it '#divisions' do expect(subject[:divisions]["AFC_EAST"][:name]).to eq "AFC East" expect(subject[:divisions]["AFC_EAST"][:id]).to eq "AFC_EAST" expect(subject[:divisions]["AFC_EAST"][:teams]).to be_an_instance_of(Array) expect(subject[:divisions]["AFC_EAST"][:teams].length).to eq 4 end end describe '#pats' do it '#id' do expect(pats[:id]).to eq "NE" end it '#name' do expect(pats[:name]).to eq "Patriots" end it '#market' do expect(pats[:market]).to eq "New England" end it '#overall' do expect(pats[:overall]).to be_an_instance_of(Hash) expect(pats[:overall][:wins]).to eq 12 expect(pats[:overall][:losses]).to eq 4 expect(pats[:overall][:ties]).to eq 0 expect(pats[:overall][:winning_percentage]).to eq 0.75 end it '#in_conference' do expect(pats[:in_conference]).to be_an_instance_of(Hash) expect(pats[:in_conference][:wins]).to eq 9 expect(pats[:in_conference][:losses]).to eq 3 expect(pats[:in_conference][:ties]).to eq 0 expect(pats[:in_conference][:winning_percentage]).to eq 0.75 end it '#non_conference' do expect(pats[:non_conference]).to be_an_instance_of(Hash) expect(pats[:non_conference][:wins]).to eq 3 expect(pats[:non_conference][:losses]).to eq 1 expect(pats[:non_conference][:ties]).to eq 0 expect(pats[:non_conference][:winning_percentage]).to eq 0.75 end it '#in_division' do expect(pats[:in_division]).to be_an_instance_of(Hash) expect(pats[:in_division][:wins]).to eq 4 expect(pats[:in_division][:losses]).to eq 2 expect(pats[:in_division][:ties]).to eq 0 expect(pats[:in_division][:winning_percentage]).to eq 0.667 end it '#grass' do expect(pats[:grass]).to be_an_instance_of(Hash) expect(pats[:grass][:wins]).to eq 9 expect(pats[:grass][:losses]).to eq 2 expect(pats[:grass][:ties]).to eq 0 expect(pats[:grass][:winning_percentage]).to eq 0.818 end it '#turf' do expect(pats[:turf]).to be_an_instance_of(Hash) expect(pats[:turf][:wins]).to eq 3 expect(pats[:turf][:losses]).to eq 2 expect(pats[:turf][:ties]).to eq 0 expect(pats[:turf][:winning_percentage]).to eq 0.6 end it '#scored_first' do expect(pats[:scored_first]).to be_an_instance_of(Hash) expect(pats[:scored_first][:wins]).to eq 6 expect(pats[:scored_first][:losses]).to eq 1 expect(pats[:scored_first][:ties]).to eq 0 end it '#decided_by_7_points' do expect(pats[:decided_by_7_points]).to be_an_instance_of(Hash) expect(pats[:decided_by_7_points][:wins]).to eq 7 expect(pats[:decided_by_7_points][:losses]).to eq 4 expect(pats[:decided_by_7_points][:ties]).to eq 0 end it '#leading_at_half' do expect(pats[:leading_at_half]).to be_an_instance_of(Hash) expect(pats[:leading_at_half][:wins]).to eq 7 expect(pats[:leading_at_half][:losses]).to eq 2 expect(pats[:leading_at_half][:ties]).to eq 0 end it '#last_5' do expect(pats[:last_5]).to be_an_instance_of(Hash) expect(pats[:last_5][:wins]).to eq 4 expect(pats[:last_5][:losses]).to eq 1 expect(pats[:last_5][:ties]).to eq 0 end it '#points' do expect(pats[:points]).to be_an_instance_of(Hash) expect(pats[:points][:for]).to eq 444 expect(pats[:points][:against]).to eq 338 expect(pats[:points][:net]).to eq 106 end it '#touchdowns' do expect(pats[:touchdowns]).to be_an_instance_of(Hash) expect(pats[:touchdowns][:for]).to eq 47 expect(pats[:touchdowns][:against]).to eq 39 end it '#streak' do expect(pats[:streak]).to be_an_instance_of(Hash) expect(pats[:streak][:type]).to eq "win" expect(pats[:streak][:length]).to eq 2 end end describe '#eagles' do it '#id' do expect(eagles[:id]).to eq "PHI" end it '#name' do expect(eagles[:name]).to eq "Eagles" end it '#market' do expect(eagles[:market]).to eq "Philadelphia" end it '#overall' do expect(eagles[:overall]).to be_an_instance_of(Hash) expect(eagles[:overall][:wins]).to eq 10 expect(eagles[:overall][:losses]).to eq 6 expect(eagles[:overall][:ties]).to eq 0 expect(eagles[:overall][:winning_percentage]).to eq 0.625 end it '#in_conference' do expect(eagles[:in_conference]).to be_an_instance_of(Hash) expect(eagles[:in_conference][:wins]).to eq 9 expect(eagles[:in_conference][:losses]).to eq 3 expect(eagles[:in_conference][:ties]).to eq 0 expect(eagles[:in_conference][:winning_percentage]).to eq 0.75 end it '#non_conference' do expect(eagles[:non_conference]).to be_an_instance_of(Hash) expect(eagles[:non_conference][:wins]).to eq 1 expect(eagles[:non_conference][:losses]).to eq 3 expect(eagles[:non_conference][:ties]).to eq 0 expect(eagles[:non_conference][:winning_percentage]).to eq 0.25 end it '#in_division' do expect(eagles[:in_division]).to be_an_instance_of(Hash) expect(eagles[:in_division][:wins]).to eq 4 expect(eagles[:in_division][:losses]).to eq 2 expect(eagles[:in_division][:ties]).to eq 0 expect(eagles[:in_division][:winning_percentage]).to eq 0.667 end it '#grass' do expect(eagles[:grass]).to be_an_instance_of(Hash) expect(eagles[:grass][:wins]).to eq 8 expect(eagles[:grass][:losses]).to eq 5 expect(eagles[:grass][:ties]).to eq 0 expect(eagles[:grass][:winning_percentage]).to eq 0.615 end it '#turf' do expect(eagles[:turf]).to be_an_instance_of(Hash) expect(eagles[:turf][:wins]).to eq 2 expect(eagles[:turf][:losses]).to eq 1 expect(eagles[:turf][:ties]).to eq 0 expect(eagles[:turf][:winning_percentage]).to eq 0.667 end it '#scored_first' do expect(eagles[:scored_first]).to be_an_instance_of(Hash) expect(eagles[:scored_first][:wins]).to eq 7 expect(eagles[:scored_first][:losses]).to eq 0 expect(eagles[:scored_first][:ties]).to eq 0 end it '#decided_by_7_points' do expect(eagles[:decided_by_7_points]).to be_an_instance_of(Hash) expect(eagles[:decided_by_7_points][:wins]).to eq 3 expect(eagles[:decided_by_7_points][:losses]).to eq 1 expect(eagles[:decided_by_7_points][:ties]).to eq 0 end it '#leading_at_half' do expect(eagles[:leading_at_half]).to be_an_instance_of(Hash) expect(eagles[:leading_at_half][:wins]).to eq 8 expect(eagles[:leading_at_half][:losses]).to eq 0 expect(eagles[:leading_at_half][:ties]).to eq 0 end it '#last_5' do expect(eagles[:last_5]).to be_an_instance_of(Hash) expect(eagles[:last_5][:wins]).to eq 4 expect(eagles[:last_5][:losses]).to eq 1 expect(eagles[:last_5][:ties]).to eq 0 end it '#points' do expect(eagles[:points]).to be_an_instance_of(Hash) expect(eagles[:points][:for]).to eq 442 expect(eagles[:points][:against]).to eq 382 expect(eagles[:points][:net]).to eq 60 end it '#touchdowns' do expect(eagles[:touchdowns]).to be_an_instance_of(Hash) expect(eagles[:touchdowns][:for]).to eq 53 expect(eagles[:touchdowns][:against]).to eq 43 end it '#streak' do expect(eagles[:streak]).to be_an_instance_of(Hash) expect(eagles[:streak][:type]).to eq "win" expect(eagles[:streak][:length]).to eq 2 end end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2019-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Error # Abstract base class for connection pool-related exceptions. class PoolError < Error # @return [ Mongo::Address ] address The address of the server the # pool's connections connect to. # # @since 2.9.0 attr_reader :address # @return [ Mongo::Server::ConnectionPool ] pool The connection pool. # # @since 2.11.0 attr_reader :pool # Instantiate the new exception. # # @api private def initialize(address, pool, message) @address = address @pool = pool super(message) end end end end
module API module Ver1 class Account < Grape::API format :json formatter :json, Grape::Formatter::Jbuilder resource :account do # GET /api/ver1/account desc 'Return user info.' get '', jbuilder: 'account/index' do authenticate_user! end end end end end
class User < ApplicationRecord has_many :comparsions, dependent: :destroy has_secure_password validates :name, presence: true, uniqueness: true def comparsion_names self.comparsions.pluck(:name, :id) end def self.get_random_name random_name = "" loop do random_name = Faker::FunnyName.name break if !User.find_by(name: random_name) end random_name end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) cities = { "New York" => "http://img3.wikia.nocookie.net/__cb20131222172706/glee/images/thumb/c/c8/NY-skyline.jpg/800px-NY-skyline.jpg", "Seattle" => "http://www.usapics.net/wallpapers/2012/03/seattle-tower-washington--600x800.jpg", "Boston"=> "http://guide.trustedtours.com/wp-content/uploads/2012/08/800px-Public_Garden_Boston.jpg", "Chicago"=> "http://www.altergroup.com/blog/wp-content/uploads/2010/10/downtown-chicago.jpg", "Austin"=> "https://farm6.staticflickr.com/5507/11455436595_a8a29323f9_c.jpg", "Los Angeles"=> "http://indianinkonline.com/wp-content/uploads/2014/11/palm-trees-800x600.jpg", "San Francisco"=> "http://www.forgeips.co.uk/sites/default/files/Golden_Gate_Bridge_.jpg", "Washington D.C."=> "http://ta.firefly-hosting.com/wp-content/uploads/2013/07/fireworks-washington-dc.jpg", "Portland"=> "https://waldobungie.files.wordpress.com/2011/06/dsc_0189.jpg" } cities.each {|city, image| City.create(name: city, image: image)} # User.create(nickname: "Jack Johnson") # User.create(nickname: "Jill Dorn") # User.create(nickname: "Bob Marley") categories = ['Food', 'Nightlife', 'Style', 'History', "Art", "Sports", 'Architecture', "Other"] categories.each {|category| Category.create(name: category)} # Post.create(tagline: 'This city', description: "Is the best!", city_id: 1, user_id: 1, category_id: 1, pro_or_con: 1) # Post.create(tagline: 'This city', description: "Is the worst!", city_id: 1, user_id: 2, category_id: 1, pro_or_con: 0) # Post.create(tagline: 'No, MY city', description: "Is the best!", city_id: 2, user_id: 2, category_id: 2, pro_or_con: 1) # Post.create(tagline: 'hate this city', description: "so much!", city_id: 2, user_id: 3, category_id: 2, pro_or_con: 0) # Post.create(tagline: 'Nah guys', description: "mine is totally the best!", city_id: 3, user_id: 3, category_id: 3, pro_or_con: 1) # Post.create(tagline: 'never going back here', description: "ever", city_id: 3, user_id: 1, category_id: 3, pro_or_con: 0) # Comment.create(content: "ok, whatever" , user_id: 1, post_id: 2) # Comment.create(content: "ok, whatever" , user_id: 2, post_id: 3) # Comment.create(content: "ok, whatever" , user_id: 3, post_id: 1)
SecureApi::Engine.routes.draw do constraints format: :json do # post :signup, to: 'secure_api#signup' post :login, to: 'secure_api#login' delete :logout, to: 'secure_api#logout' get :check_token, to: 'secure_api#check_token' end end
require 'collins_state' module Collins class ProvisioningWorkflow < ::Collins::PersistentState manage_state :provisioning_process, :initial => :start do |client| action :reboot_hard do |asset, p| p.logger.warn "Calling rebootHard on asset #{Collins::Util.get_asset_or_tag(asset).tag}" client.power! asset, "rebootHard" end action :reprovision do |asset, p| detailed = client.get asset p.logger.warn "Reprovisioning #{detailed.tag}" client.set_status! asset, "Maintenance", "Automated reprovisioning" client.provision asset, detailed.nodeclass, (detailed.build_contact || "nobody"), :suffix => detailed.suffix, :primary_role => detailed.primary_role, :secondary_role => detailed.secondary_role, :pool => detailed.pool end action :toggle_status do |asset, p| tag = Collins::Util.get_asset_or_tag(asset).tag p.logger.warn "Toggling status (Provisioning then Provisioned) for #{tag}" client.set_status!(asset, 'Provisioning') && client.set_status!(asset, 'Provisioned') end # No transitions are defined here, since they are managed fully asynchronously by the # supervisor process. We only defines actions to take once the timeout has passed. Each # part of the process makes an event call, the supervisor process just continuously does a # collins.managed_process("ProvisioningWorkflow").transition(asset) which will # either execute the on_transition action due to expiration or do nothing. # After 30 minutes reprovision if still in the start state - ewr_start_provisioning - collins.managed_process("ProvisioningWorkflow").start(asset) event :start, :desc => 'Provisioning Started', :expires => after(30, :minutes), :on_transition => :reprovision # After 10 minutes if we haven't seen an ipxe request, reprovision (possible failed move) - vlan changer & provisioning status - collins.mp.vlan_moved_to_provisioning(asset) event :vlan_moved_to_provisioning, :desc => 'Moved to provisioning VLAN', :expires => after(15, :minutes), :on_transition => :reprovision # After 5 minutes if we haven't yet seen a kickstart request, reboot (possibly stuck at boot) - phil ipxe event :ipxe_seen, :desc => 'Asset has made iPXE request to Phil', :expires => after(5, :minutes), :on_transition => :reboot_hard # After 5 minutes if the kickstart process hasn't begun, reboot (possibly stuck at boot) - phil kickstart event :kickstart_seen, :desc => 'Asset has made kickstart request to Phil', :expires => after(15, :minutes), :on_transition => :reboot_hard # After 45 minutes if we haven't gotten to post, reboot to reinstall - phil kickstart pre event :kickstart_started, :desc => 'Asset has started kickstart process', :expires => after(45, :minutes), :on_transition => :reboot_hard # After 45 minutes if the kickstart process hasn't completed, reboot to reinstall - phil kickstart post event :kickstart_post_started, :desc => 'Asset has started kickstart post section', :expires => after(45, :minutes), :on_transition => :reboot_hard # After 10 minutes if we haven't been moved to the production VLAN, toggle our status to get us moved - phil kickstart post event :kickstart_finished, :desc => 'Asset has finished kickstart process', :expires => after(15, :minutes), :on_transition => :toggle_status # After another 15 minutes if still not moved toggle our status again - vlan changer when discover=true event :vlan_move_to_production, :desc => 'Moved to production VLAN', :expires => after(15, :minutes), :on_transition => :toggle_status # After another 10 minutes if we're not reachable by IP, toggle the status - supervisor event :reachable_by_ip, :desc => 'Now reachable by IP address', :expires => after(10, :minutes), :on_transition => :toggle_status # Place holder for when we finish event :done, :desc => 'Finished', :terminus => true end end end
class CreateEducations < ActiveRecord::Migration def change create_table :educations do |t| t.references :consultant, index: true, null: false t.references :degree, index: true, null: false t.string :school, limit: 256 t.string :field_of_study, limit: 256 t.timestamps end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Project.destroy_all p "Projects destroyed" # users : project = Project.create!(name:'SimplyRest', description:'SAAS for restaurant owner') project2 = Project.create!(name:'What the truck', description:'Market place for renting a foodtruck for event') p "projects created"
module ActsAsAddressable module LocalInstanceMethods def home_address locations.where(primary: true).first end end end
class CreateBusinessesCategories < ActiveRecord::Migration def change create_table :businesses_categories, :id => false do |t| t.references :business, :category end add_index :businesses_categories, [:business_id, :category_id] end end
# == Schema Information # # Table name: buyers # # id :integer not null, primary key # number :integer not null # name :string(255) not null # auction_id :integer # created_at :datetime # updated_at :datetime # require 'csv' class BuyersController < ApplicationController # Defines an index action that gets all the buyers for a particular auction def index @auction = Auction.find(params[:auction_id]) @buyers = @auction.buyers respond_to do |format| format.html format.csv {render text: @buyers.to_csv} end end # Bring up the new buyer form. def new @auction = Auction.find(params[:auction_id]) @buyer = Buyer.new @buyer.auction = @auction end # Create the new buyer. def create @auction = Auction.find(params[:auction_id]) @buyer = Buyer.new(buyer_params) @buyer.auction = @auction if @buyer.save redirect_to :auction_buyers else render 'new' end end def edit @buyer = Buyer.find(params[:id]) @auction = Auction.find(params[:auction_id]) end def update @buyer = Buyer.find(params[:id]) if @buyer.update(buyer_params) redirect_to :auction_buyers else render 'edit' end end def show @auction = Auction.find(params[:auction_id]) @buyer = Buyer.find(params[:id]) end def destroy @buyer = Buyer.find(params[:id]) if @buyer.destroy redirect_to :auction_buyers end end def import @auction = Auction.find(params[:auction_id]) end def upload auction = Auction.find(params[:auction_id]) Buyer.import(params[:file], auction.id) redirect_to :auction_buyers end def invoice buyer = Buyer.find(params[:id]) pdf = InvoicePdf.new(buyer) filename = "invoice_#{buyer.number}_#{Time.now.to_i}.pdf" send_data pdf.render, filename: filename, type: "application/pdf", disposition: "inline" end private def buyer_params params.require(:buyer).permit(:number, :name) end end
require File.join(File.dirname(__FILE__), 'gilded_rose') describe GildedRose do before do items = [ Item.new(name='+5 Dexterity Vest', sell_in=10, quality=20), Item.new(name='Aged Brie', sell_in=2, quality=0), Item.new(name='Elixir of the Mongoose', sell_in=5, quality=7), Item.new(name='Sulfuras, Hand of Ragnaros', sell_in=0, quality=80), Item.new(name='Sulfuras, Hand of Ragnaros', sell_in=-1, quality=80), Item.new(name='Backstage passes to a TAFKAL80ETC concert', sell_in=15, quality=20), Item.new(name='Backstage passes to a TAFKAL80ETC concert', sell_in=10, quality=20), Item.new(name='Backstage passes to a TAFKAL80ETC concert', sell_in=5, quality=20), # This Conjured item does not work properly yet Item.new(name='Conjured Mana Cake', sell_in=3, quality=6), # <-- :O ] @gilded_rose = GildedRose.new items @gilded_rose.update_quality end describe '#update_quality' do context 'When item is "Aged Brie" and sell_in is less than 5' do it 'quality should be increased by 3' do expect(@gilded_rose.items[1].quality).to eq(3) end end context 'When item is "Sulfuras"' do it 'quantity should be 80' do expect(@gilded_rose.items[3].quality).to eq(80) end end context 'When item is "Backstage passes"' do context 'and sell_in is great than 10' do it 'quantity should be increased by 1' do expect(@gilded_rose.items[5].quality).to eq(21) end end context 'and sell_in is 10 or less than 10' do it 'quantity should be increased by 2' do expect(@gilded_rose.items[6].quality).to eq(22) end end context 'and sell_in is 5 or less than 5' do it 'quantity should be increased by 3' do expect(@gilded_rose.items[7].quality).to eq(23) end end end context 'When item is "Conjured"' do it 'quantity should be degraded by 2' do expect(@gilded_rose.items[8].quality).to eq(4) end end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) for i in 1..5 User.create name: "test#{i}", email: "test#{i}@yahoo.com", password: "testing123", admin: true, confirmed_at: Time.now end test1 = User.find_by(name: "test1") test2 = User.find_by(name: "test2") category = Category.create( name: "Sad Times", user: test1, privacy: "public" ) event = Event.create( name: "Chores", date: Time.parse('30th Oct 2018 4:00:00 PM'), end_date: Time.parse('30th Oct 2018 5:00:00 PM'), repeat: 'daily', user: test1, category: category ) event.make_host_event! EventInvite.create( sender: test1, user: test2, host_event: event )
class Node attr_accessor :value, :parent, :left_child, :right_child def initialize(value=nil, parent=nil, left_child=nil, rihgt_child=nil) @value = value @parent = parent @left_child = left_child @right_child = right_child end def insert(value) if value < @value unless @left_child.nil? @left_child.insert(value) else @left_child = Node.new(value, self) end else unless @right_child.nil? @right_child.insert(value) else @right_child = Node.new(value, self) end end end def to_s if @left_child.nil? && @right_child.nil? return "#{@value}, l:[nil], r:[nil]" elsif @left_child.nil? return "#{@value}, l:[nil], r:[#{@right_child.to_s}]" elsif @right_child.nil? return "#{@value}, l:[#{@left_child.to_s}], r:[nil]" elsif !@value.nil? return "#{@value}, l:[#{@left_child.to_s}], r:[#{@right_child.to_s}]" else return nil end 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 :get_menu private def get_menu @home_page = Page.find_by_slug(:home) unless request.path == root_path @pages = Page.all #.for_menu.where_slug_is_not :home end end
module ClarifaiRuby class TagImage attr_reader :docid, :docid_str, :url, :status_code, :status_msg, :local_id, :tags def initialize(result_doc) @docid = result_doc["docid"] @docid_str = result_doc["docid_str"] @url = result_doc["url"] @status_code = result_doc["status_code"] @status_msg = result_doc["status_msg"] @local_id = result_doc["local_id"] @tags = generate_tags result_doc["result"]["tag"] @tags_by_words = result_doc["result"]["tag"]["classes"] end private def generate_tags(tag_doc) concept_ids = tag_doc["concept_ids"] classes = tag_doc["classes"] probs = tag_doc["probs"] tags = [] if concept_ids classes.each_with_index do |c, i| tags << Tag.new(c, probs[i], concept_ids[i]) end else classes.each_with_index do |c, i| tags << Tag.new(c, probs[i]) end end tags end end end
require 'spec_helper' describe Puppet::Type.type(:postgresql_conn_validator).provider(:ruby) do let(:resource) do Puppet::Type.type(:postgresql_conn_validator).new({ name: 'testname', }.merge(attributes)) end let(:provider) { resource.provider } let(:attributes) do { psql_path: '/usr/bin/psql', host: 'db.test.com', port: 4444, db_username: 'testuser', db_password: 'testpass', } end let(:connect_settings) do { connect_settings: { PGPASSWORD: 'testpass', PGHOST: 'db.test.com', PGPORT: '1234', }, } end describe '#build_psql_cmd' do it 'contains expected commandline options' do expect(provider.validator.build_psql_cmd).to match %r{/usr/bin/psql.*--host.*--port.*--username.*} end end describe '#parse_connect_settings' do it 'returns array if password is present' do expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass']) end it 'returns an empty array if password is nil' do attributes.delete(:db_password) expect(provider.validator.parse_connect_settings).to eq([]) end it 'returns an array of settings' do attributes.delete(:db_password) attributes.merge! connect_settings expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass', 'PGHOST=db.test.com', 'PGPORT=1234']) end end describe '#attempt_connection' do let(:sleep_length) { 1 } let(:tries) { 3 } let(:exec) do provider.validator.stub(:execute_command).and_return(true) end it 'tries the correct number of times' do expect(provider.validator).to receive(:execute_command).exactly(3).times provider.validator.attempt_connection(sleep_length, tries) end end end
class Field # == Constants FEMALE = "female" MALE = "male" BIRTHDAY_FORMAT = "%m/%d/%Y" HEIGHT = 320 WIDTH = 320 def self.format_date(date) Date.strptime(date, BIRTHDAY_FORMAT) end def self.replace_userfield(fields) fields.present? ? ("?fields=" + fields.gsub("picture", "picture.width(#{WIDTH}).height(#{HEIGHT})")) : "" end def self.replace_friendfield(fields) fields.gsub("friends?", "taggable_friends?fields=").gsub("picture", "picture.width(#{WIDTH}).height(#{HEIGHT})") end end
# -*- encoding : utf-8 -*- # Klasa punktu # # Para współrzędnych geograficznych; opisuje wierzchołek wielokąta. # # === Pola # [number] nr w sekwencji # [latitude] szerokość geograficzna, +BigDecimal+, wymagane # [longitude] długość geograficzna, +BigDecimal+, wymagane # [polygon] wielokąt # class Point < ActiveRecord::Base belongs_to :polygon validates :number, :presence => true validates :latitude, :presence => true validates :longitude, :presence => true validates_numericality_of :number, :longitude, :latitude validates_inclusion_of :longitude, :in => -180..180 validates_inclusion_of :latitude, :in => -90..90 # Porównanie (tylko po współrzędnych) def ==(other) return latitude == other.latitude && longitude == other.longitude end end
describe Peatio::Auth::JWTAuthenticator do it "can authenticate valid jwt" do rsa_private = OpenSSL::PKey::RSA.generate(2048) rsa_public = rsa_private.public_key payload = { iat: Time.now.to_i, exp: (Time.now + 60).to_i, sub: "session", iss: "barong", aud: [ "peatio", "barong", ], jti: "BEF5617B7B2762DDE61702F5", uid: "TEST123", email: "user@example.com", role: "admin", level: 4, state: "active", } auth = Peatio::Auth::JWTAuthenticator.new(rsa_public, rsa_private) token = auth.encode(payload) auth.authenticate!("Bearer #{token}") end it "will raise exception for invalid jwt (expired)" do rsa_private = OpenSSL::PKey::RSA.generate(2048) rsa_public = rsa_private.public_key # payload is expired payload = { iat: Time.now.to_i, exp: (Time.now - 60).to_i, sub: "session", iss: "barong", aud: [ "peatio", "barong", ], jti: "BEF5617B7B2762DDE61702F5", uid: "TEST123", email: "user@example.com", role: "admin", level: 4, state: "active", } auth = Peatio::Auth::JWTAuthenticator.new(rsa_public, rsa_private) token = auth.encode(payload) expect { auth.authenticate!("Bearer #{token}") }.to raise_error(Peatio::Auth::Error) end it "will raise exception if no private key given for encoding" do rsa_private = OpenSSL::PKey::RSA.generate(2048) rsa_public = rsa_private.public_key auth = Peatio::Auth::JWTAuthenticator.new(rsa_public, nil) expect { token = auth.encode("xxx") }.to raise_error(ArgumentError) end it "will raise exception for invalid jwt (garbage)" do rsa_private = OpenSSL::PKey::RSA.generate(2048) rsa_public = rsa_private.public_key auth = Peatio::Auth::JWTAuthenticator.new(rsa_public, nil) expect { auth.authenticate!("Bearer garbage") }.to raise_error(/Authorization failed: Failed to decode and verify JWT/) end end
require 'spec_helper' require 'models/mr_mime/store' module MrMime RSpec.describe Store do let(:store) { described_class.new({}) } before { stub_const("#{described_class}::PREFIX", 'prefix')} describe '#set_keys' do it 'correctly stores all prefixed key-value pairs' do store.set_keys(one: 1, two: 2) expect(store['prefix.one']).to eq 1 expect(store['prefix.two']).to eq 2 end end describe '#set' do it 'correctly stores a prefixed key-value pair' do store.set(:one, 1) expect(store['prefix.one']).to eq 1 end end describe '#get' do it 'correctly retrieves a prefixed key-value pair' do store.set(:one, 1) expect(store.get(:one)).to eq 1 end end end end
class LocationsController < ApplicationController def create @location = Location.find_or_create_by(location_params) session[:location_id] = @location.id nearby ||= Location.near(@location.coords, 5) @posts ||= Post.joins(:location).select(:guid, :subject, :content).merge(nearby) end private def location_params params.require(:location).permit(:latitude, :longitude) end end
module Stax @@_root_path = nil @@_stack_list = [] @@_command_list = [] ## the stax root is defined as location of Staxfile def self.root_path @@_root_path end ## list of stacks defined in Staxfile def self.stack_list @@_stack_list end ## list of commands defined in Staxfile def self.command_list @@_command_list end ## search up the dir tree for nearest Staxfile def self.find_staxfile Pathname.pwd.ascend do |path| return path if File.exist?(file = path.join('Staxfile')) end end def self.load_staxfile @@_root_path = find_staxfile if root_path load(root_path.join('Staxfile')) require_libs require_stacks require_commands end end ## auto-require class overrides def self.require_libs %w[ base stack ].each do |file| f = root_path.join('lib', "#{file}.rb") require(f) if File.exist?(f) end end ## auto-require any stack lib files def self.require_stacks stack_list.each do |stack| f = root_path.join('lib', 'stack', "#{stack}.rb") require(f) if File.exist?(f) end end ## auto-require any command lib files def self.require_commands command_list.each do |command| f = root_path.join('lib', "#{command}.rb") require(f) if File.exist?(f) end end ## add a stack by name, creates class as needed def self.add_stack(name, opt = {}) @@_stack_list << name ## camelize the stack name into class name c = name.to_s.split(/[_-]/).map(&:capitalize).join ## create the class if it does not exist yet if self.const_defined?(c) self.const_get(c) else self.const_set(c, Class.new(Stack)) end.tap do |klass| Cli.desc("#{name} COMMAND", "#{name} stack commands") Cli.subcommand(name, klass) ## syntax to include mixins, reverse to give predictable include order opt.fetch(:include, []).reverse.each do |i| klass.include(self.const_get(i)) end klass.instance_variable_set(:@name, name) klass.instance_variable_set(:@imports, Array(opt.fetch(:import, []))) klass.instance_variable_set(:@type, opt.fetch(:type, nil)) klass.instance_variable_set(:@groups, opt.fetch(:groups, nil)) end end ## add a non-stack command at top level def self.add_command(name, klass = nil) @@_command_list << name ## class defaults to eg Stax::Name::Cmd klass ||= self.const_get(name.to_s.split(/[_-]/).map(&:capitalize).join + '::Cmd') Cli.desc(name, "#{name} commands") Cli.subcommand(name, klass) end end
class TokenError < StandardError; end class ProblemDescriptionValidator FIRST_WORDS = "What is ".freeze LAST_TOKEN = '?'.freeze VALID_TOKENS = /\d+|\s+|plus|minus|multiplied|divided|by|-/i def initialize(problem_in_words) check_begin_and_end_of(problem_in_words) @input = extract_core_data_from(problem_in_words) end def validate_and_extract_data validate_input @input end private def check_begin_and_end_of(problem_in_words) error_msg = "Problem description must start with 'What is ' and end with '?'" raise ArgumentError, error_msg unless \ problem_in_words.start_with?(FIRST_WORDS) && problem_in_words.end_with?(LAST_TOKEN) end def extract_core_data_from(problem) problem.delete_prefix(FIRST_WORDS).chop end def validate_input @input.split.each do |token| raise TokenError, "Token: '#{token}' is invalid" unless token.match?(VALID_TOKENS) end end end class Tokenizer def initialize(input) @input = input.split.delete_if { |token| token == 'by' } end def tokenize converted_tokens = [] @input.each do |token| if token.match?(/\d+/) converted_tokens << token.to_i else converted_tokens << convert_operation_symbol(token) end end converted_tokens end private def convert_operation_symbol(token) case token when 'plus' then :+ when 'minus' then :- when 'multiplied' then :* when 'divided' then :/ else raise TokenError, "Unrecognized token: #{token}." end end end class Processor def initialize(tokens) @tokens = tokens end def process # Initialize the result with te first number result = @tokens.shift # In each slice of two elements, the first is the operation the second the operand @tokens.each_slice(2) do |slice| result = result.send(slice[0], slice[1]) end result end end class WordProblem def initialize(problem_in_words) validator = ProblemDescriptionValidator.new(problem_in_words) @input = validator.validate_and_extract_data @tokens = Tokenizer.new(@input).tokenize end def answer processor = Processor.new(@tokens) processor.process end end
require 'sinatra' require 'curb' require 'json' require 'cgi' helpers do def get_server ENV['SERVER'] end end def get_oauth_token # get oauth token c = Curl::Easy.http_post('https://login.salesforce.com/services/oauth2/token', 'grant_type=password&client_id='+ ENV['CLIENT_ID'] +'&client_secret='+ ENV['CLIENT_SECRET'] +'&username='+ ENV['USERNAME'] +'&password='+ ENV['PASSWORD'] +'' ) return JSON.parse(c.body_str) end def get_quizzes(user = false, date = Date.today) # SOQL query for Quick_Quiz__c query = "SELECT Id, Name, Quiz_Date__c, Number_Correct__c, Total_Time__c, Member__r.Name FROM Quick_Quiz__c WHERE Quiz_Date__c = #{date}" if user query += " AND Member__r.Name = '#{user}'" end return do_curl(query) end def get_answers(user = false, date = Date.today) # SOQL query for Quick_Quiz_Answer__c query = "SELECT Id, Name, Language__c, Is_Correct__c, Time__c, Quick_Quiz__c, Quick_Quiz__r.Member__r.Name FROM Quick_Quiz_Answer__c WHERE Quick_Quiz__r.Quiz_Date__c = #{date}" if user query += " AND Quick_Quiz__r.Member__r.Name = '#{user}'" end query += " LIMIT 10" return do_curl(query) end def do_curl(query) oauth_response = get_oauth_token c = Curl::Easy.http_get("#{oauth_response['instance_url']}/services/data/v24.0/query?q=#{CGI::escape(query)}" ) do |curl| curl.headers['Authorization'] = "OAuth #{oauth_response['access_token']}" end r = JSON.parse(c.body_str) return r end get "/" do redirect to("/#{Date.today}") end get '/?:date' do # list out recent answers taken by users by date or TODAY #"Quick_Quiz__r"=>{"Member__r"=>{"Name"=>"John", "attributes"=>{"url"=>"/services/data/v24.0/sobjects/Member__c/a00d0000002jBvOAAU", "type"=>"Member__c"}}, #"attributes"=>{"url"=>"/services/data/v24.0/sobjects/Quick_Quiz__c/a02d0000002cUvKAAU", "type"=>"Quick_Quiz__c"}}, #"Language__c"=>"Java", "Is_Correct__c"=>true, "Name"=>"QUIZA-0024", #"attributes"=>{"url"=>"/services/data/v24.0/sobjects/Quick_Quiz_Answer__c/a01d0000002j60oAAA", "type"=>"Quick_Quiz_Answer__c"}, #"Time__c"=>20.0, "Id"=>"a01d0000002j60oAAA", "Quick_Quiz__c"=>"a02d0000002cUvKAAU" answers = get_answers(false, params[:date]) @answers = answers['records'] erb :index end get "/user/demo" do erb :user_demo end get "/user/:user" do |user| redirect to("/user/#{user}/#{Date.today}") end get "/user/:user/:date" do |user, date| # list out available quizzes taken by THE USER by date or TODAY quizzes = get_quizzes(user, date) if quizzes['records'] == [] @user = user @date = date erb :user_blank else # should take only one - then subscribe to get quiz quiz = quizzes['records'][0] # quiz['Member__r']['Name'] # user's name # quiz['Id'] # quiz id (cometd channel name) # quiz['Number_Correct__c'], quiz['Total_Time__c'], quiz['Quiz_Date__c'] @quiz = quiz #"Quick_Quiz__r"=>{"Member__r"=>{"Name"=>"John", "attributes"=>{"url"=>"/services/data/v24.0/sobjects/Member__c/a00d0000002jBvOAAU", "type"=>"Member__c"}}, #"attributes"=>{"url"=>"/services/data/v24.0/sobjects/Quick_Quiz__c/a02d0000002cUvKAAU", "type"=>"Quick_Quiz__c"}}, #"Language__c"=>"Java", "Is_Correct__c"=>true, "Name"=>"QUIZA-0024", #"attributes"=>{"url"=>"/services/data/v24.0/sobjects/Quick_Quiz_Answer__c/a01d0000002j60oAAA", "type"=>"Quick_Quiz_Answer__c"}, #"Time__c"=>20.0, "Id"=>"a01d0000002j60oAAA", "Quick_Quiz__c"=>"a02d0000002cUvKAAU" answers = get_answers(user, date) @answers = answers['records'] erb :user end end
# calculate ASCII string value of a string # use ord to calculate each ASCII value of every character # empty string should return 0 # input = string # output = integer # chars into an array and iterate through to find ASCII value of each element # add each value to a sum value and return it def ascii_value(string) ascii_array = string.chars ascii_sum = 0 ascii_array.each do |character| ascii_sum += character.ord end ascii_sum end puts ascii_value('Four score') == 984 puts ascii_value('Launch School') == 1251 puts ascii_value('a') == 97 puts ascii_value('') == 0
# Rotates development and test log files when they exceed 20 MB. # In production use a more robust system like /etc/logrotate.d/. # if Rails.env.development? || Rails.env.test? Dir.glob(Rails.root.join('log', '*.log')).each do |log_file| next if File.size(log_file) < 20_000_000 File.delete "#{log_file}.1" if File.exist?("#{log_file}.1") FileUtils.cp(log_file, "#{log_file}.1") File.truncate(log_file, 0) end end
Given /^no users exist$/ do User.delete_all end Then /^I should have ([0-9]+) users? in the database$/ do |count| User.count.should == count.to_i end When(/^I fill in "([^\"]*)" with #{capture_model}'s (\w+)$/) do |field, owner, attribute| fill_in(field, :with => model(owner).send(attribute)) end
#!/usr/bin/env ruby VERSION='1.0.0' $:.unshift File.expand_path('../../_code/lib', __FILE__) require 'commander' require 'highline/import' require 'tempfile' require 'slop' require 'octokit' require 'hashie' require 'pry' require 'awesome_print' begin # GATHER SETTINGS ################################################### slop = Slop.parse(strict: true, help: true) do banner 'Usage: db_transfer [options]' on 'd', 'database', '[required] the name of the database to transfer.', argument: true on 'source_host', '[optional] host of the db source server.', { argument: :optional, default: '198.61.228.97' } on 'dest_host', '[optional] host of the db destination server.', { argument: :optional, default: '10.176.132.158' } end raise 'Database Name, required!' unless slop.database? opts = Hashie::Mash.new(slop.to_h) # RUN COMMANDS ###################################################### date_str = Time.now.strftime('%F') puts 'Please provide server access that has access to the source_host server.' box = Hashie::Mash.new() box.user = ask(' user: ') { |q| q.default = 'kbspdev' } box.ssh_key = ask(' ssh_key: ') { |q| q.default = '~/.ssh/kbspdev-django.apps.pem' } box.host = ask(' host: ') { |q| q.default = 'django.apps.kbsp.com' } puts 'Please provide creds for SOURCE db user.' username = ask(' username: ') { |q| q.default = 'postgres' } password = ask(' password: ') { |q| q.echo = false } [ { list: [ "PGPASSWORD=#{ password } pg_dump #{ opts.database } -h #{ opts.source_host } -U #{ username } > #{ date_str }-dump.sql", ], local: false }, { list: [ "scp -i #{ box.ssh_key } #{ box.user }@#{ box.host }:/home/#{ box.user }/#{ date_str }-dump.sql ./", ], local: true }, ].each{ |c| box.local = c[:local] Commander::Commands.new(c[:list], box).run } puts 'Please provide server access that has access to the dest_host server.' box = Hashie::Mash.new() box.user = ask(' user: ') { |q| q.default = 'kbspdev' } box.ssh_key = ask(' ssh_key: ') { |q| q.default = '~/.ssh/kbspdev-platform' } box.host = ask(' host: ') { |q| q.default = '162.209.109.19' } puts 'Please provide creds for DESTINATION db user.' orig_username = username username = ask(' username: ') { |q| q.default = 'prestige_cms' } password = ask(' password: ') { |q| q.echo = false } [ { list: [ "sed -i 's/#{orig_username};/#{username};/g' ./#{ date_str }-dump.sql", "scp -i #{ box.ssh_key } ./#{ date_str }-dump.sql #{ box.user }@#{ box.host }:/home/#{ box.user }/", ], local: true }, { list: [ "PGPASSWORD=#{ password } psql #{ opts.database } -h #{ opts.dest_host } -U #{ username } < #{ date_str }-dump.sql", ], local: false }, ].each{ |c| box.local = c[:local] Commander::Commands.new(c[:list], box).run } # END ############################################################### puts '' puts '...DONE' rescue => e puts '' puts e.message puts '' puts slop end
<<<<<<< HEAD # The Company originally started in Melbourne with a product list that consisted of the following sku numbers: # 112334, 276834, 098464, 356498, 065134, 124589, 132548, 102334, 278834, #078464, 356298, 085134, 134589, 132598, 152334, 876834, 088464, 336498, #005134, 124580, 132588, 102333, 268834, 098464, 956298, 081134, 134889, # 132698 # They then expanded to Brisbane, and while Brisbane began with mostly the same product #sku list (some items they stopped stocking because they didn’t sell so well), # they also had some extras and ended up with the following list: # 132588, 102333, 268834, 098464, 956698, 081134, #134889, 132698, 112334, 276834, 098464, 356498, 065134, 132548, # 102334, 278834, 078464, 356298, 005134, 134589, 132598, 876834, # 088464, 336498, 005134, 124588 # Head office want a complete sku list with no duplicates. # Easy to do right? Now try working it out with three lines of code, you should #be able to do it with 6 words and some operators and syntax. melbourne_sku= ["112334", "276834", "098464", "356498", "065134", "124589", "132548", "102334", "278834", "078464", "356298", "085134", "134589", "132598", "152334", "876834", "088464", "336498", "005134", "124580", "132588", "102333", "268834", "098464", "956298", "081134", "134889", "132698"] brisbane_sku= ["132588", "102333", "268834", "098464", "956698", "081134", "134889", "132698", "112334", "276834", "098464", "356498", "065134", "132548", "102334", "278834", "078464", "356298", "005134", "134589", "132598", "876834", "088464", "336498", "005134", "124588"] puts (brisbane_sku + melbourne_sku).uniq ======= # The Company originally started in Melbourne with a product list that consisted of the following sku numbers: # "112334", "276834", "098464", "356498", "065134", "124589", "132548", "102334", "278834", "078464", "356298", "085134", "134589", "132598", "152334", "876834", "088464", "336498", "005134", "124580", "132588", "102333", "268834", "098464", "956298", "081134", "134889", "132698" # They then expanded to Brisbane, and while Brisbane began with mostly the same product sku list (some items they stopped stocking because they didn’t sell so well), they also had some extras and ended up with the following list: # "132588", "102333", "268834", "098464", "956698", "081134", "134889", "132698", "112334", "276834", "098464", "356498", "065134", "132548", "102334", "278834", "078464", "356298", "005134", "134589", "132598", "876834", "088464", "336498", "005134", "124588" # Head office want a complete sku list with no duplicates. # Easy to do right? Now try working it out with three lines of code, you should be able to do it with 6 words and some operators and syntax. MEL = ["112334", "276834", "098464", "356498", "065134", "124589", "132548", "102334", "278834", "078464", "356298", "085134", "134589", "132598", "152334", "876834", "088464", "336498", "005134", "124580", "132588", "102333", "268834", "098464", "956298", "081134", "134889", "132698"] BRI = ["132588", "102333", "268834", "098464", "956698", "081134", "134889", "132698", "112334", "276834", "098464", "356498", "065134", "132548", "102334", "278834", "078464", "356298", "005134", "134589", "132598", "876834", "088464", "336498", "005134", "124588"] sku_list = (MEL + BRI).uniq puts sku_list.sort >>>>>>> a66f15b560d5615b416b1045b016e9e610546faf
class BlogController def start main_menu end def main_menu puts "Welcome to My Blog!" puts "1. Read Posts" puts "2. Write Posts" choice = gets.strip case (choice.to_i) when 1 list_posts when 2 write_post else puts "Invalid Entry." main_menu end end def list_posts # - Read Posts # + Then the can select a post to read in full # + Go back to Read menu # we need to query something, the database, posts Post.print_titles puts "Which would you like to read? Type main for main menu." reading_choice = gets.strip if reading_choice.to_i == 0 main_menu else # Assume they typed in 2 post = Post.find(reading_choice) # SELECT * posts WHERE id = 2 puts "Title: #{post.title}" puts "------" puts "#{post.body}" list_posts end end def write_post puts "Enter the title for your post:" post_title = gets.strip puts "Enter the text for your post:" post_text = gets.strip post = Post.new post.title = post_title post.body = post_text post.save puts "Your post has been saved as Post #{post.id}" end end
# frozen_string_literal: true require 'controller_test' class EventInviteeMessagesControllerTest < ActionController::TestCase setup do login :uwe @event_invitee_message = event_invitee_messages(:one) end test 'should get index' do get :index assert_response :success end test 'should get new' do get :new, params: { event_invitee_message: { event_invitee_id: event_invitees(:one).id } } assert_response :success end test 'should create event_invitee_message' do assert_difference('EventInviteeMessage.count') do post :create, params: { event_invitee_message: { message_type: EventMessage::MessageType::INVITATION, body: @event_invitee_message.body, event_invitee_id: @event_invitee_message.event_invitee_id, sent_at: @event_invitee_message.sent_at, subject: @event_invitee_message.subject, } } end assert_redirected_to event_invitee_message_path(EventInviteeMessage.last) end test 'should show event_invitee_message' do login :newbie get :show, params: { id: @event_invitee_message } assert_response :success end test 'should show event_invitee_message invitation test' do get :show, params: { id: -@event_invitee_message.event_invitee.event_id } assert_response :success end test 'should get edit' do get :edit, params: { id: @event_invitee_message } assert_response :success end test 'should update event_invitee_message' do put :update, params: { id: @event_invitee_message, event_invitee_message: { message_type: EventMessage::MessageType::INVITATION, body: @event_invitee_message.body, event_invitee_id: @event_invitee_message.event_invitee_id, sent_at: @event_invitee_message.sent_at, subject: @event_invitee_message.subject, } } assert_redirected_to event_invitee_message_path(@event_invitee_message) end test 'should destroy event_invitee_message' do assert_difference('EventInviteeMessage.count', -1) do delete :destroy, params: { id: @event_invitee_message } end assert_redirected_to event_invitee_messages_path end end
## # Copyright (c) Wordchuck Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "wordchuck" gem.summary = %Q{gem for the Wordchuck website translation service} gem.description = %Q{gem for the Wordchuck website translation service for locale file generation} gem.email = "shelly@wordchuck.com" gem.homepage = "http://github.com/shellyroche/wordchuck" gem.authors = ["Shelly Roche"] gem.rubyforge_project = "wordchuck" gem.files = FileList['[A-Z]*', 'lib/**/*.rb', 'lib/tasks/*.rake', 'test/**/*.rb'] gem.add_development_dependency "thoughtbot-shoulda", ">= 0" gem.add_dependency 'rest-client', '~> 1.6.0' gem.add_dependency 'json_pure', '>= 1.4.4' gem.add_dependency 'human_hash', '>= 0.2.1' end Jeweler::GemcutterTasks.new rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.libs << 'lib' << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end begin require 'rcov/rcovtask' Rcov::RcovTask.new do |test| test.libs << 'test' test.pattern = 'test/**/test_*.rb' test.verbose = true end rescue LoadError task :rcov do abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" end end task :test => :check_dependencies task :default => :test require 'rake/rdoctask' Rake::RDocTask.new do |rdoc| version = File.exist?('VERSION') ? File.read('VERSION') : "" rdoc.rdoc_dir = 'rdoc' rdoc.title = "wordchuck #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end
class TravelAdviceController < ApplicationController FOREIGN_TRAVEL_ADVICE_SLUG = "foreign-travel-advice".freeze def index set_expiry fetch_and_setup_content_item("/" + FOREIGN_TRAVEL_ADVICE_SLUG) @presenter = TravelAdviceIndexPresenter.new(@content_item) respond_to do |format| format.html { render locals: { full_width: true } } format.atom do set_expiry(5.minutes) headers["Access-Control-Allow-Origin"] = "*" end end end end
# frozen_string_literal: true Before do |scenario| calculator_service = GrpcApiAssistant::ServiceManager.services.add_service( 'Calculator', # The name you plan to use to reference the service from within test steps 'CalculatorService' # This is the name of the generated gRPC service ) # calculator_server = GrpcApiAssistant::SecureServer.new( # '0.0.0.0', # 12345, # Helpers.get_env('PRIVATE_KEY_PASSPHRASE'), # 'server.crt', # 'ca.crt', # 'server.pem', # *calculator_service # ) calculator_server = GrpcApiAssistant::InsecureServer.new( '0.0.0.0', 12345, *calculator_service ) GrpcApiAssistant::ServerManager.servers.add_server( 'calculator_server', # A name you will use to reference this server from within test steps calculator_server # The GrpcApiAssistant::Server or SecureServer ) calculator_server.start # create a secure client # GrpcApiAssistant::ClientManager.clients.add_client( # 'Calculator', # '::Calculator::Calculator', # 'localhost', # 12345, # nil, # 'server.crt', # 'CHANNEL_NAME' # ) GrpcApiAssistant::ClientManager.clients.add_client( 'Calculator', '::Calculator::Calculator', 'localhost', 12345 ) end Before('@no_server_services_clients') do GrpcApiAssistant::ClientManager.clients.remove_all_clients GrpcApiAssistant::ServiceManager.services.remove_all_services # GrpcApiAssistant::SecureServer.stop_all GrpcApiAssistant::InsecureServer.stop_all end After do |scenario| GrpcApiAssistant::ClientManager.clients.remove_all_clients GrpcApiAssistant::ServiceManager.services.remove_all_services GrpcApiAssistant::ServerManager.servers.remove_all_servers # GrpcApiAssistant::SecureServer.stop_all GrpcApiAssistant::InsecureServer.stop_all end
require 'spec_helper' describe ChequeRunsController do let(:current_user) { FactoryGirl.create(:user) } let!(:cheque_run) { FactoryGirl.create(:cheque_run, owner: current_user) } before do basic_auth_login sign_in current_user end describe "#index" do subject { get :index } it { should be_success } it "should list cheque runs owned by current user" do subject current_user.cheque_runs.each { |cheque_run| assigns(:cheque_runs).should include(cheque_run) } end it "should list cheque runs by users of the same organization" do other_user = FactoryGirl.create(:user, organization: current_user.organization) other_cheque_run = FactoryGirl.create(:cheque_run, owner: other_user) subject assigns(:cheque_runs).should include(other_cheque_run) end it "should not list cheque runs by users of a different organization" do other_org_user = FactoryGirl.create(:user, organization: FactoryGirl.create(:organization, name: "Other Org")) other_org_cheque_run = FactoryGirl.create(:cheque_run, owner: other_org_user) subject assigns(:cheque_runs).should_not include(other_org_cheque_run) end end describe "#show" do subject { get :show, :id => cheque_run.to_param, :format => format } context "html" do let(:format) { "html" } it { should be_success } end context "zip" do let(:format) { "zip" } it { should be_success } it "returns pleasantly named zip" do subject response.headers['Content-Disposition'].should match(/cheque_run_#{cheque_run.id}\.zip/i) response.headers['Content-Type'].should == 'application/zip' end it "keeps the cheque run" do cheque_count = cheque_run.cheques.count expect { subject }.to_not change(ChequeRun, :count) Cheque.where(cheque_run_id: cheque_run.id).should have(cheque_count).cheques end end it "forbids access if user organization does not own cheque run" do rival = FactoryGirl.create(:rival) rival_run = FactoryGirl.create(:cheque_run, owner: rival) get :show, :id => rival_run.to_param, :format => "html" response.status.should == 403 end end describe "#create" do let(:upload_input) { fixture_file_upload('/cheques.csv') } let(:template) { "citibank" } subject { post :create, upload_input: upload_input, template: template } it "sets template for cheque run" do subject assigns(:cheque_run).template.should == template end it "redirects to #show" do subject response.should redirect_to cheque_run_path(assigns(:cheque_run)) end end describe "#destroy" do subject { delete :destroy, id: cheque_run.id } it "deletes the cheque run" do expect { subject }.to change(ChequeRun, :count).by(-1) end it "redirects to #index with flash message" do subject response.should redirect_to root_path flash[:notice].should =~ /delete successful/i end end end
class SessionsController < ApplicationController before_filter :require_authentication, :only => [:destroy] before_filter :require_no_authentication, :only => [:new, :create] def new end def create if user = User.authenticate(session_params[:email], session_params[:password]) self.current_user = user redirect_to edit_account_path, :notice => t("session.create.success") else flash.now[:error] = t("session.create.error") render "new" end end def destroy self.current_user = nil redirect_to login_path, :notice => t("session.destroy.success") end private def require_no_authentication if logged_in? && current_user redirect_to edit_account_path end end def session_params params[:session] || {} end end
module ScorchedEarth class EventRunner attr_reader :queue, :subscribers def initialize @queue = Queue.new @subscribers = [] end def publish(event) queue << event end def subscribe(klass, &block) subscribers << [klass, block] end def run(event) subscribers.each do |klass, block| block.call event if event.is_a? klass end end def process! processing = Array.new(queue.size) { queue.pop } processing.each do |event| run event end end end end
class Admin::PurchasesController < AdministrativeController load_and_authorize_resource helper_method :sort_column, :sort_direction # Display all the purchases def index @purchases = Purchase.unscoped.search(params[:search]) # Filter @purchases = @purchases.where('created_at <= ?', end_date) if params[:end_date].present? @purchases = @purchases.where('created_at >= ?', start_date) if params[:start_date].present? # Pagination @purchases = @purchases.order(sort_column + ' ' + sort_direction).paginate(:per_page => 20, :page => params[:page]) respond_with("admin", @purchases) end # Show individual purchase def show @purchase = Purchase.find(params[:id]) respond_with("admin", @purchase) end def new @purchase = Purchase.new respond_with("admin", @purchase) end def edit @purchase = Purchase.find(params[:id]) end # Creates new purchase def create @purchase = Purchase.new(params[:purchase]) @purchase.admin_id = current_admin @purchase.save respond_with("admin", @purchase) end # Update existing purchase def update @purchase = Purchase.find(params[:id]) @purchase.update_attributes respond_with("admin", @purchase) end # Destroy existing purchase def destroy @purchase = Purchase.find(params[:id]) @purchase.destroy respond_with("admin", @purchase) end private def sort_column Purchase.column_names.include?(params[:sort]) ? params[:sort] : "inventory_file_name" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end
module TextInterface class DisplayStorage attr_reader :storage_contents def initialize @storage_contents = [] end def add(item_to_add) storage_contents.push(item_to_add) end def display storage_contents end end end
# encoding: utf-8 require "logstash/filters/base" require "logstash/namespace" require "logstash/json" require "logstash/timestamp" require_relative "gpx/gpx_parser" require_relative "gpx/tcx_parser" class LogStash::Filters::Gpx < LogStash::Filters::Base config_name "gpx" # The configuration for the GPX filter: # [source,ruby] # source => source_field # # For example, if you have GPX data in the @message field: # [source,ruby] # filter { # gpx { # source => "message" # } # } # # The above would parse the gpx from the @message field config :source, :validate => :string, :required => true # Define the target field for placing the parsed data. If this setting is # omitted, the GPX data will be stored at the root (top level) of the event. # # For example, if you want the data to be put in the `doc` field: # [source,ruby] # filter { # gpx { # target => "doc" # } # } # # NOTE: if the `target` field already exists, it will be overwritten! config :target, :validate => :string config :document_type, :validate => :string, :default => "gpx" def register # Nothing to do here end # def register def dump_gpx(source) gpx = Guppy::GpxParser.load(source) hash_dump = { "activities" => [] } gpx.activities.each do |_activity| total_time = 0 activity = { "distance" => _activity.distance, "laps" => [] } _activity.laps.each do |_lap| total_time += _lap.time.to_i lap = { "distance" => _lap.distance, "time_in_sec" => _lap.time.to_i, "start_time" => _lap.track_points.first.time.to_s, "finish_time" => _lap.track_points.last.time.to_s, "speed" => ((_lap.time.to_f/60)/(_lap.distance.to_f/1000)) } lap["points"] = _lap.track_points.map do |track| [track.latitude, track.longitude] end activity["laps"] << lap end activity["time"] = total_time hash_dump["activities"] << activity end hash_dump["@timestamp"] = LogStash::Timestamp.at(gpx.activities.first.laps.first.track_points.first.time.to_i) hash_dump end def dump_tcx(source) tcx = Guppy::TcxParser.load(source) hash_dump = { "activities" => [] } total_time = 0 location = [] tcx.activities.each do |_activity| activity = { "distance" => _activity.distance, "sport" => _activity.sport, "date" => _activity.date.to_i, "laps" => [] } i=0 _activity.laps.each do |_lap| next if _lap.distance.to_f == 0 total_time += _lap.time.to_i lap = { "distance" => _lap.distance.to_f, "max_speed" => _lap.max_speed.to_f, "calories" => _lap.calories, "time_in_sec" => _lap.time.to_i, "pace" => (((_lap.time.to_i)/60.0)/(_lap.distance.to_f/1000)).to_f, "speed" => (_lap.distance.to_f/1000)/(_lap.time.to_f/3600), "id" => i } if _lap.track_points.count > 0 start_time = _lap.track_points.first.time lap["start_time"] = start_time.to_i lap["finish_time"] = _lap.track_points.last.time.to_i end last_altitude_point = 0.0 lap["points"] = _lap.track_points.map do |track| m = { "coordinates" => [track.longitude, track.latitude], "altitude" => track.altitude.to_f, "time" => track.time.to_i-start_time.to_i, "increase" => track.altitude.to_f-last_altitude_point } last_altitude_point = track.altitude.to_f m end location = lap["points"].first["coordinates"] if location.empty? && (_lap.track_points.count > 0) activity["laps"] << lap i+=1 end activity["time"] = total_time activity["pace"] = (activity["time"].to_f/60)/(activity["distance"].to_f/1000) activity["speed"] = (activity["distance"].to_f/1000)/(activity["time"].to_f/3600) hash_dump["activities"] << activity end hash_dump["@timestamp"] = LogStash::Timestamp.at(tcx.activities.first.date.to_i) hash_dump["@location"] = location hash_dump end def filter(event) return unless filter?(event) @logger.debug("Running GPX filter", :event => event) return unless event.include?(@source) source = event[@source] begin if @document_type.to_s == "tcx" hash_dump = dump_tcx(source) else hash_dump = dump_gpx(source) end event["@timestamp"] = hash_dump.delete("@timestamp") event["geoip"] = { "location" => hash_dump.delete("@location") } if @target event[@target] = hash_dump.clone else # we should iterate the message over the # original message hash_dump.each_pair do |k,v| event[k] = v end end filter_matched(event) rescue => e add_failure_tag(event) @logger.warn("Trouble parsing json", :source => @source, :raw => event[@source], :exception => e) return end @logger.debug("Event after gpx filter", :event => event) end private def add_failure_tag(event) tag = "_gpxnparsefailure" event["tags"] ||= [] event["tags"] << tag unless event["tags"].include?(tag) end def select_dest(event) if @target == @source dest = event[@target] = {} else dest = event[@target] ||= {} end return dest end end # class LogStash::Filters::Json
class AddGoogleMapsApiKeyToCobrandHost < ActiveRecord::Migration def self.up add_column :cobrand_hosts, :google_maps_api_key, :string remove_column :cobrands, :google_maps_api_key end def self.down remove_column :cobrand_hosts, :google_maps_api_key add_column :cobrands, :google_maps_api_key, :string end end
# This method takes an array of integers (arr). Your task is to find and then return the most # frequent integer. These integers might be positive or negative. If no most-frequent integer # exists, return nil. def find_most_frequent_integer(arr) unique = arr.uniq freq_ary = [] unique.each do |elem1| count1 = 0 arr.each do |elem2| if elem1 == elem2 count1 = count1.next end end freq_ary.push(count1) end hi_freq = 0 freq_ary.each do |elem| if elem > hi_freq hi_freq = elem end end count2 = 0 freq_ary.each do |elem| if elem == hi_freq count2 = count2.next end end if count2 > 1 return nil end return unique[freq_ary.index(hi_freq)] end
require 'spec_helper' describe JrubyMahout::CustomRescorer do let(:rescorer) { } let(:data_model) {JrubyMahout::DataModel.new("file", { :file_path => "spec/recommender_data.csv" }).data_model} let(:params) {{:similarity => "PearsonCorrelationSimilarity", :recommender => "GenericItemBasedRecommender", :neighborhood_size => 3}} let(:recommender) { JrubyMahout::Recommender.new(params) } let(:old_recommendations) {[[12, 5.0], [9, 5.0]]} before do recommender.data_model = data_model recommender.recommend(3,2,nil).should == old_recommendations end it "should override is_filtered and rescore" do is_filtered = lambda { |id| id == 12 } re_score = lambda do |id, original_score| id == 9 ? original_score + 1 : original_score end rescorer = JrubyMahout::CustomRescorer.new(is_filtered, re_score) recommender.recommend(3, 2, rescorer).should == [[9, 6.0], [26, 5.0]] end end
pdf.image "#{Rails.root}/app/assets/images/g1/logo.png", :width => 150, :at => [400,730] pdf.move_down 120 pdf.text "Data Destruction Certificate", :style => :bold, :size => 18 pdf.move_down 40 pdf.text "<strong>Business Name:</strong> #{@client.company.upcase}", :inline_format => true pdf.move_down 10 pdf.text "<strong>Job Number:</strong> #{@job.id}", :inline_format => true pdf.move_down 10 pdf.text "<strong>Date Completed:</strong> #{ @job.completion_date ? @job.completion_date.strftime("%d %B, %Y") : ''}", :inline_format => true pdf.move_down 25 pdf.text "This document certifies that all media collected on 19 February, 2013 has been three pass wiped according to the DoD 5220.22-M standard to prevent the retrieval of data. Any media that was unable to be verified as wiped has been physically destroyed." pdf.move_down 15 pdf.text "All data sanitisation is completed in our secure area. Physical destruction is also completed in the secure area - hard drives are drilled and then sent for shredding." pdf.move_down 15 pdf.text "All work has been completed by G1 Asset Management Pty Ltd." pdf.move_down 15 pdf.text "If there are any issues with this report please contact your G1 representative." pdf.move_down 45 pdf.text "Joel Prokic" pdf.text "Director" pdf.move_down 10 pdf.image "#{Rails.root}/app/assets/images/g1/signature.png", :width => 150 pdf.move_down 10 pdf.text "#{Date.today.strftime("%d %B, %Y")}" pdf.text_box "G1 Asset Management Pty Ltd | ABN. 21 151 748 953 | www.g1am.com.au Brisbane | Sydney | Melbourne | Adelaide | Perth | Osaka", :at => [0, 30], :size => 10, :align => :center
# frozen_string_literal: true require 'spec_helper' RSpec.describe Brcobranca::Remessa::Cnab400::Credisis do let(:pagamento) do Brcobranca::Remessa::Pagamento.new(valor: 199.9, data_vencimento: Date.current, nosso_numero: 123, documento: 6969, dias_protesto: '6', valor_mora: '8.00', percentual_multa: '2.00', documento_sacado: '12345678901', nome_sacado: 'PABLO DIEGO JOSÉ FRANCISCO,!^.?\/@ DE PAULA JUAN NEPOMUCENO MARÍA DE LOS REMEDIOS CIPRIANO DE LA SANTÍSSIMA TRINIDAD RUIZ Y PICASSO', endereco_sacado: 'RUA RIO GRANDE DO SUL,!^.?\/@ São paulo Minas caçapa da silva junior', bairro_sacado: 'São josé dos quatro apostolos magros', cep_sacado: '12345678', cidade_sacado: 'Santa rita de cássia maria da silva', uf_sacado: 'SP') end let(:params) do { carteira: '18', agencia: '1', conta_corrente: '2', codigo_cedente: '0027', documento_cedente: '12345678901234', digito_conta: '7', sequencial_remessa: '3', empresa_mae: 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA', pagamentos: [pagamento] } end let(:credisis) { subject.class.new(params) } context 'validações dos campos' do context '@agencia' do it 'deve ser inválido se não possuir uma agência' do object = subject.class.new(params.merge!(agencia: nil)) expect(object.invalid?).to be true expect(object.errors.full_messages).to include('Agencia não pode estar em branco.') end it 'deve ser invalido se a agencia tiver mais de 4 dígitos' do credisis.agencia = '12345' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Agencia deve ter 4 dígitos.') end end context '@digito_conta' do it 'deve ser inválido se não possuir um dígito da conta corrente' do objeto = subject.class.new(params.merge!(digito_conta: nil)) expect(objeto.invalid?).to be true expect(objeto.errors.full_messages).to include('Digito conta não pode estar em branco.') end it 'deve ser inválido se o dígito da conta tiver mais de 1 dígito' do credisis.digito_conta = '12' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Digito conta deve ter 1 dígito.') end end context '@conta_corrente' do it 'deve ser inválido se não possuir uma conta corrente' do object = subject.class.new(params.merge!(conta_corrente: nil)) expect(object.invalid?).to be true expect(object.errors.full_messages).to include('Conta corrente não pode estar em branco.') end it 'deve ser inválido se a conta corrente tiver mais de 8 dígitos' do credisis.conta_corrente = '123456789' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Conta corrente deve ter 8 dígitos.') end end context '@codigo_cedente' do it 'deve ser inválido se não possuir código do cedente' do object = subject.class.new(params.merge!(codigo_cedente: nil)) expect(object.invalid?).to be true expect(object.errors.full_messages).to include('Codigo cedente não pode estar em branco.') end it 'deve ser inválido se o código do cedente tiver mais de 4 dígitos' do credisis.codigo_cedente = '12345333' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Codigo cedente deve ter 4 dígitos.') end end context '@carteira' do it 'deve ser inválido se não possuir uma carteira' do object = subject.class.new(params.merge!(carteira: nil)) expect(object.invalid?).to be true expect(object.errors.full_messages).to include('Carteira não pode estar em branco.') end it 'deve ser inválido se a carteira tiver mais de 2 dígitos' do credisis.carteira = '123' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Carteira deve ter 2 dígitos.') end end context '@sequencial_remessa' do it 'deve ser inválido se a sequencial remessa tiver mais de 7 dígitos' do credisis.sequencial_remessa = '12345678' expect(credisis.invalid?).to be true expect(credisis.errors.full_messages).to include('Sequencial remessa deve ter 7 dígitos.') end end end context 'formatacoes dos valores' do it 'cod_banco deve ser 097' do expect(credisis.cod_banco).to eq '097' expect(credisis.nome_banco.strip).to eq 'CENTRALCRED' end it 'info_conta deve retornar com 20 posicoes as informacoes da conta' do info_conta = credisis.info_conta expect(info_conta.size).to eq 20 expect(info_conta[0..3]).to eq '0001' # num. da agencia expect(info_conta[5..12]).to eq '00000002' # num. da conta expect(info_conta[13]).to eq '7' # dígito da conta end end context 'monta remessa' do it_behaves_like 'cnab400' context 'header' do it 'informacoes devem estar posicionadas corretamente no header' do header = credisis.monta_header expect(header[1]).to eq '1' # tipo operacao (1 = remessa) expect(header[2..8]).to eq 'REMESSA' # literal da operacao expect(header[26..45]).to eq credisis.info_conta # informacoes da conta expect(header[76..78]).to eq '097' # codigo do banco expect(header[100..106]).to eq '0000003' # sequencial da remessa end end context 'detalhe' do it 'informacoes devem estar posicionadas corretamente no detalhe' do detalhe = credisis.monta_detalhe pagamento, 1 expect(detalhe[0]).to eq '1' # registro detalhe expect(detalhe[1..2]).to eq '02' # tipo do documento do cedente expect(detalhe[3..16]).to eq '12345678901234' # documento do cedente expect(detalhe[17..20]).to eq '0001' # agência expect(detalhe[22..29]).to eq '00000002' # conta corrente expect(detalhe[30]).to eq '7' # dígito da conta corrente expect(detalhe[37..61]).to eq '6969'.ljust(25) # número controle cliente expect(detalhe[62..72]).to eq '00027000123' # nosso numero expect(detalhe[73..109]).to eq ''.rjust(37, ' ') # brancos expect(detalhe[110..119]).to eq '0000000000' # número documento expect(detalhe[120..125]).to eq Date.current.strftime('%d%m%y') # data de vencimento expect(detalhe[126..138]).to eq '0000000019990' # valor do titulo expect(detalhe[139..149]).to eq ''.rjust(11, ' ') # brancos expect(detalhe[150..155]).to eq Date.current.strftime('%d%m%y') # data emissão título expect(detalhe[156..159]).to eq ''.rjust(4, ' ') # brancos expect(detalhe[160..165]).to eq '080000' # mora expect(detalhe[166..171]).to eq '020000' # multa expect(detalhe[172..204]).to eq ''.rjust(33, ' ') # brancos expect(detalhe[205..217]).to eq ''.rjust(13, '0') # desconto expect(detalhe[218..219]).to eq '01' # tipo documento sacado expect(detalhe[220..233]).to eq '00012345678901' # documento sacado expect(detalhe[234..273]).to eq 'PABLO DIEGO JOSE FRANCISCO DE PAULA JUAN' # nome sacado expect(detalhe[274..310]).to eq 'RUA RIO GRANDE DO SUL Sao paulo Minas' # endereco sacado expect(detalhe[311..325]).to eq 'Sao jose dos qu' # bairro sacado expect(detalhe[326..333]).to eq '12345678' # cep sacado expect(detalhe[334..348]).to eq 'Santa rita de c' # cidade sacado expect(detalhe[349..350]).to eq 'SP' # uf sacado expect(detalhe[351..375]).to eq ''.rjust(25, ' ') # nome avalista expect(detalhe[377..390]).to eq ''.rjust(14, ' ') # documento avalista expect(detalhe[391..392]).to eq '06' # dias para envio a protesto end end context 'arquivo' do before { Timecop.freeze(Time.local(2015, 7, 14, 16, 15, 15)) } after { Timecop.return } it { expect(credisis.gera_arquivo).to eq(read_remessa('remessa-credisis-cnab400.rem', credisis.gera_arquivo)) } end end end
require_relative '../helpers/validation' class Authentication include Validation def initialize(params) @params = params end attr_reader :params def valid_auth?; without_errors?(errors); end def render_token; user_token; end def errors errors = Array.new errors.push('"username" is missing') unless filled?(params[:username]) errors.push('"password" is missing') unless filled?(params[:password]) errors.push('User is not exist') if contains_params? && !user_exist? errors.push('Use Facebook authorization') if contains_params? && user_exist? && !has_password? errors.push('Wrong password') if contains_params? && user_exist? && !right_password? errors end private def contains_params?; filled?(params[:username]) && filled?(params[:password]); end def user_exist?; !user.nil?; end def has_password?; user_pass.nil? ? false : true; end def right_password?; has_password? && !passwords_matches? ? false : true; end def passwords_matches?; BCrypt::Password.new(user_pass) == params[:password]; end def user_pass; user.hashed_password; end def user_token; user.access_token; end def user; User.where(username: params[:username]).first; end end
require 'rails_helper' RSpec.describe 'tweets', type: :system do before do user = create(:user_1) user.confirm sign_in user create(:tweet, body: 'こんにちは。', user: user) end scenario 'ツイートを投稿したら、即反映されること' do visit root_path fill_in 'いまどうしてる?', with: 'おはようございます。' click_on 'ツイート' expect(page).to have_content 'おはようございます。' end scenario 'ツイートを削除したら、即反映されること' do visit root_path click_on '削除' expect(page).to have_no_content 'こんにちは。' end end
require 'rubygems' unless defined?(Gem) require 'rubygems/specification' require 'rake/gempackagetask' require 'rake' def gemspec @gemspec ||= begin file = File.expand_path("golia.gemspec") ::Gem::Specification.load(file) end end desc "Validates the gemspec" task :gemspec do gemspec.validate end desc "Displays the current version" task :version do puts "Current version: #{gemspec.version}" end desc "Release the gem" task :release => :package do sh "gem push pkg/#{gemspec.name}-#{gemspec.version}.gem" sh "rm -rf pkg" sh "git add .; git commit -m \"Bump to version #{gemspec.version}\"; git push origin master" end desc "Installs the gem locally" task :install => :package do sh "gem install pkg/#{gemspec.name}-#{gemspec.version}" sh "rm -rf pkg" end Rake::GemPackageTask.new(gemspec) do |pkg| pkg.gem_spec = gemspec end task :package => :gemspec
class Properties::DatafilesController < ApplicationController before_action :get_current_property def new @datafile = @property.datafiles.new if params[:id] @current_folder = @property.folders.find(params[:id]) @datafile.folder_id = @current_folder.id end end def create @folder_id = params[:id] @datafile = @property.datafiles.build(uploaded_file: params[:file]) #@datafile = @property.datafiles.build(datafile_params) @datafile.folder_id = @folder_id #flash[:notice] = "Successfully uploaded the file." if @datafile.save respond_to do |format| format.json{ render :json => @datafile } end # if @datafile.folder # redirect_to landlords_property_folder_path(@property.propertyid, @folder.parent) # else # redirect_to landlords_property_folders_path(@property.propertyid) # end else render :action => 'new' end end def destroy @datafile = @property.datafiles.find(params[:id]) @parent_folder = @datafile.folder @datafile.destroy flash[:notice] = "Successfully deleted the file." if @parent_folder redirect_to landlords_property_folder_path(@property.propertyid, @parent_folder) else redirect_to landlords_property_folders_path(@property.propertyid) end end private def get_current_property @property = Property.find(params[:property_id]) end def datafile_params params.require(:datafile).permit(:folder_id,:uploaded_file) end end
class Nutcracker < Formula homepage "https://github.com/twitter/twemproxy" url "https://github.com/twitter/twemproxy/archive/v0.4.0.tar.gz" sha1 "7bc17d4d78196abeac27c8544efd833849d03f48" head "https://github.com/twitter/twemproxy.git" bottle do cellar :any sha256 "369a87e5fc60849e8fb1b40f8df1f57406f7b86fbb7b2b5503b3b1a75fc1ecfd" => :yosemite sha256 "603e6a29b7f3c80680aa811e80e52ddbf5c5b35aa676d363ac79cdd254489d16" => :mavericks sha256 "58e30a2d345c686e6cecb492a8356d9696d9200481c55fabc7460a55ae24e162" => :mountain_lion end depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build def install system "autoreconf", "-ivf" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" (share+"nutcracker").install "conf", "notes", "scripts" end test do system "#{opt_sbin}/nutcracker", "-V" end end
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user before_filter :check_sign_in private def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def check_sign_in unless user_signed_in redirect_to log_in_path end end def user_signed_in return true if current_user end end
class DesiredObject < ActiveRecord::Base attr_accessible :name, :user_id, :category, :description #belongs_to :user belongs_to :regular_user has_many :product_candidates has_one :chosen_product #has_many :merchant_offers end
class Ville < ActiveRecord::Base before_validation :geocode def Weather forecast = ForecastIO.forecast(self.latitude, self.longitude, params: { units: 'si' }) weatherCheck = false temperatureCheck = false if forecast todayForecast = forecast.currently if todayForecast if todayForecast.summary weatherSummary = todayForecast.summary weatherCheck = true end if todayForecast.icon weatherIconName = todayForecast.icon weatherFetched = true end if todayForecast.temperature weatherTemperature = todayForecast.temperature temperatureCheck = true end end end if !weatherCheck weatherSummary =nil weatherIconName = nil end if !temperatureCheck weatherTemperature = nil end return {"weatherIconName" => weatherIconName, "weatherTemperature" => weatherTemperature, "weatherSummary" => weatherSummary} end private def geocode places= Nominatim.search(self.nom).limit(1) place=places.first if place self.latitude=place.latitude self.longitude=place.longitude end end end
class Array def to_playlist self.map do |s| { id: s.matching_id, artist_name: s.artist_name, name: s.name, image: s.resolve_image(:small), seconds: s.seconds, sc_id: s.soundcloud_id || '', token: s.token || '' } end.compact.to_json end end
class Product < ApplicationRecord validates :name, presence: true validates :name, uniqueness: true validates :price, presence: true validates :price, numericality: { greater_than: 0} validates :description, presence: true belongs_to :supplier def is_discounted? if price < 10 return true else return false end end def tax return (price * 0.09).round(2) end def total return price + tax end end
require 'sinatra/base' require 'sinatra/json' require 'mysql2' require 'json' require 'cgi' require './models/response' require './models/forum' require './models/post' require './models/thread' require './models/user' class App < Sinatra::Base helpers do # parses body for POST requests def get_body() JSON.parse(request.body.read) end # parses URL for GET requests def get_related() request.query_string.scan(/[^?]elated=([^&]*)/).flatten end end # perform before each request # prepare @params before do if request.post? @params = get_body() else @params = params @params['related'] = get_related() end end # configure database connection # create database accessors configure do set :client, Mysql2::Client.new(:host => 'localhost', :username => 'test', :database => 'perf_db', :password => 'testpassword', :cast_booleans => true) set :forum, Forum.new(settings.client) set :posts, Post.new(settings.client) set :thread, ForumThread.new(settings.client) set :user, User.new(settings.client) end # path for all requests path = '/db/api' post path + '/clear/' do clear(settings.client).to_json end get path + '/status' do database_status(settings.client).to_json end post path + '/user/create/' do json settings.user.create(@params) end get path + '/user/details/' do json settings.user.details(@params) end post path + '/user/follow/' do json settings.user.follow(@params) end get path + '/user/listFollowers/' do json settings.user.listFollowers(@params) end get path + '/user/listFollowing/' do json settings.user.listFollowing(@params) end get path + '/user/listPosts/' do json settings.user.listPosts(@params) end post path + '/user/unfollow/' do json settings.user.unfollow(@params) end post path + '/user/updateProfile/' do json settings.user.updateProfile(@params) end post path + '/forum/create/' do settings.forum.create(@params).to_json end get path + '/forum/details/' do settings.forum.details(@params).to_json end get path + '/forum/listPosts/' do settings.forum.listPosts(@params).to_json end get path + '/forum/listThreads/' do settings.forum.listThreads(@params).to_json end get path + '/forum/listUsers/' do settings.forum.listUsers(@params).to_json end post path + '/thread/close/' do settings.thread.close(@params).to_json end post path + '/thread/create/' do settings.thread.create(@params).to_json end get path + '/thread/details/' do settings.thread.details(@params).to_json end get path + '/thread/list/' do settings.thread.list(@params).to_json end get path + '/thread/listPosts/' do settings.thread.listPosts(@params).to_json end post path + '/thread/open/' do settings.thread.open(@params).to_json end post path + '/thread/remove/' do settings.thread.remove(@params).to_json end post path + '/thread/restore/' do settings.thread.restore(@params).to_json end post path + '/thread/subscribe/' do settings.thread.subscribe(@params).to_json end post path + '/thread/unsubscribe/' do settings.thread.unsubscribe(@params).to_json end post path + '/thread/update/' do settings.thread.update(@params).to_json end post path + '/thread/vote/' do settings.thread.vote(@params).to_json end post path + '/post/create/' do settings.posts.create(@params).to_json end get path + '/post/details/' do settings.posts.details(@params).to_json end get path + '/post/list/' do settings.posts.list(@params).to_json end post path + '/post/remove/' do settings.posts.remove(@params).to_json end post path + '/post/restore/' do settings.posts.restore(@params).to_json end post path + '/post/update/' do settings.posts.update(@params).to_json end post path + '/post/vote/' do settings.posts.vote(@params).to_json end end
require "rails_helper" require "spec_helper" require "byebug" RSpec.describe UsersController, :type => "controller" do before(:each) do User.delete_all # to delte all the users to make sure only are there @user = User.create!(:name=>"ABC", :email => "abc#{User.count + 1}@gmail.com", :password => "abc12345", :confirm_password =>"abc12345", :address=> "BDA", :phone => "34577884") get :login_page, {:user =>{ email: @user.email, password: @user.password } } end describe "GET index" do it "it will return equivalent number of users count from table" do @user = User.create!(:name=>"ABC", :email => "abc#{User.count + 2}@gmail.com", :password => "abc12345", :confirm_password =>"abc12345", :address=> "BDA", :phone => "34577884") expect(User.count).to eq(2) end end describe "POST create" do it "create records" post :create, {:user =>{ email: "", password: "" } } end end
# class CreateAuthors < ActiveRecord::Migration # def up # create_table :authors do |t| # t.text :name # t.text :twitter # t.timestamps #null:false # t.integer :image_id # end # end # def down # drop_table :authors # end # end
# describe '.create' do # it 'hashes the password using BCrypt' do # expect(BCrypt::Password).to receive(:create).with('abc123') # # User.create(email: 'test@example.com', password: 'abc123') # end # end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure(2) do |config| config.vm.box = "chef/centos-7.0" config.vm.define "node1" do |node1| node1.vm.network "private_network", ip: "192.168.33.10" node1.vm.hostname = "node1" node1.vm.box = "mesos-master" end config.vm.define "node2" do |node2| node2.vm.network "private_network", ip: "192.168.33.11" node2.vm.hostname = "node2" end config.vm.define "node3" do |node3| node3.vm.network "private_network", ip: "192.168.33.12" node3.vm.hostname = "node3" end config.vm.define "node4" do |node4| node4.vm.network "private_network", ip: "192.168.33.13" node4.vm.hostname = "node4" end (1..4).each do |i| config.vm.define "node#{i}" do |node| node.vm.provision "shell", inline: "sudo cp /vagrant/hosts.j2 /etc/hosts" end end end
class KebabShop < ApplicationRecord include PgSearch geocoded_by :address after_validation :geocode, if: :will_save_change_to_address? has_many :menus, dependent: :destroy has_many :reviews, dependent: :destroy has_many :schedules, dependent: :destroy mount_uploader :photo, PhotoUploader validates :name, presence: true, uniqueness: true validates :address, presence: true, uniqueness: true validates :rating, numericality: true pg_search_scope :search_by_name, against: [:name], using: { tsearch: { prefix: true } } def coordinates [latitude, longitude] end def opening_hours_today weekdays = %w(sunday monday tuesday wednesday thursday friday saturday) today_idx = Date.today.wday today_string = weekdays[today_idx] today_schedule = schedules.find_by_weekday(today_string) return "#{today_schedule.opening_hour}:00-#{today_schedule.closing_hour}:00" end end
FactoryGirl.define do factory :page do html "<html></html>" page_name "Page_name" project_id 1 end end
class Message < ApplicationRecord belongs_to :customer, class_name: 'User::Customer', optional: true belongs_to :agent, class_name: 'User::Agent', optional: true belongs_to :ticket validates_presence_of :msg validates_presence_of :ticket validate :belongs_to_any private def belongs_to_any self.errors.add(:base, "message must belong to somebody") if customer_id.blank? && agent_id.blank? end end
class SecretsController < ApplicationController before_action :require_login private def require_login return head(:forbidden) unless session[:name] end end
class RepositoriesController < ApplicationController def new if (current_user) @repository = Repository.new else flash[:notice] = "You need to login" redirect_to "/login" end end def create if (not current_user) redirect_to "/login" end @repository = Repository.new(params[:repository]) @repository.project_id = session[:project_id] session[:repository_id] = nil success = @repository && @repository.save if success && @repository.errors.empty? current_user.repositories << @repository redirect_to("/projects/get/#{@repository.project_id}") flash[:notice] = "new Repository added !" else flash[:error] = "We couldn't set up the repository, sorry. Please try again, or contact an admin (link is above)." render :action => 'new' end end def update if (not current_user) redirect_to "/login" end @repository = Repository.find(params[:id]) @repository.update session[:repository_id] = @repository.id events = [] @repository.commits.reverse.each { |c| events << c } @repository.bugs.reverse.each { |b| events << b } events.sort! { |a,b| a.created_at <=> b.created_at } @events = events.reverse # pagination a_page = 1 a_ppage = 10 if (params[:page] != nil) a_page = params[:page] end if (params[:per_page] != nil) a_ppage = params[:per_page] || 10 end options = {:page => a_page, :per_page => a_ppage} @page_results = @events.paginate(options) render :partial => 'projects/lately' end def purge if (not current_user) redirect_to "/login" end Repository.find(params[:id]).purge render :text => "Empty" end end
ActiveAdmin.register Driver do particulars = {first_name:nil, last_name: nil, nickname: nil, short_desc: nil, is_active: nil} contacts = {phone:nil, email:nil, wechat_id: nil, whatsapp_id: nil, facebook_url: nil } medias = {childsafe: nil, avatar_url: nil, card_img: nil, background_url: nil, video_url: nil } certificates = { english_communication: nil, basic_dslr: nil, basic_history: nil, driving_experience: nil, smartphone_photography: nil } all_fields = particulars.keys + contacts.keys + medias.keys + certificates.keys index do selectable_column column :first_name column :last_name column :phone column :email column :driving_years column :updated_at column :is_active actions end permit_params *all_fields, languages_attributes: [:id, :_destroy, :language_code, :proficiency], driver_cities_attributes: [:id, :city_id, :_destroy], images_attributes: [:id, :url, :url_small, :alt_text, :_destroy], driver_vehicles_attributes: [:id, :vehicle_id, :_destroy] register_fields = Proc.new do |f, fields| fields.each do |field, type| puts "Register -> #{field}: #{type}" if type f.input field, as: type else f.input field end end end form do |f| f.inputs('Particulars') do register_fields[f, particulars] f.input :description, as: :ckeditor f.has_many :driver_cities, allow_destroy: true do |city| city.input :city_id, label: 'Name', as: :select, collection: (City.all.map {|c| [c.name, c.id]}) end f.has_many :driver_vehicles, allow_destroy: true do |vehicle| vehicle.input :vehicle_id, label: 'Name', as: :select, collection: (Vehicle.all.map {|v| [v.name, v.id]}) end end f.inputs('Contacts'){ register_fields[f, contacts]} f.inputs'Intro', :multipart => true do f.input :childsafe, label: "Child Safe" f.input :video_url, label: "Youtube Url" f.input :avatar_url, :as => :file, :hint => f.driver.avatar_url.present? \ ? image_tag(f.driver.avatar_url.url(:square), class: "active_admin_img") : content_tag(:span, "No Dirver Avatar Yet") f.input :avatar_url_cache , :as => :hidden f.input :background_url, :as => :file, :hint => f.driver.background_url.present? \ ? image_tag(f.driver.background_url.url, class: "active_admin_img") : content_tag(:span, "No Dirver Background Yet") f.input :background_url_cache , :as => :hidden f.input :card_img, :as => :file, :hint => f.driver.card_img.present? \ ? image_tag(f.driver.card_img.url, class: "active_admin_img") : content_tag(:span, "No Dirver Card Image Yet"), label: "Card Image Url" f.input :card_img_cache, :as => :hidden end f.inputs 'Language' do f.has_many :languages, allow_destroy: true do |l| l.input :language_code, as: :select, collection: LanguageList::COMMON_LANGUAGES.map{|l| [l.name, l.iso_639_3]} l.input :proficiency, as: :select, collection: DriverLanguage.proficiencies.keys.to_a end end f.inputs 'Certificates' do f.input :english_communication, label: "English Communication Skill" f.input :basic_history, label: "Basic History" f.input :smartphone_photography, label: "Smart Phone Photography" f.input :basic_dslr, label: "Basic DSLR" f.input :driving_experience, label: "Years of driving expereience" end f.inputs 'Photo Gallery' do f.has_many :images, allow_destroy: true do |i| i.input :url, label: "Gallery Image" i.input :url_small,label: "Thumbnail Image" i.input :alt_text,label: "Alternative Text" end end f.actions end show do table_panel = Proc.new do |name, models, &blk| panel name do table do models.each do |m| tr do blk[m].each {|s| td s} end end end end end attributes_table do all_fields.each do |field| row field end row(:cities){ driver.cities.map(&:name).join ' ,'} row(:vehicles){ driver.vehicles.map(&:name).join ' ,'} row(:images){ driver.images.map(&:url).join ' ,'} end table_panel.call('Languages', driver.languages) do |l| [LanguageList::LanguageInfo.find(l.language_code).name, l.proficiency] end active_admin_comments end end
Rails.application.routes.draw do devise_for :users root to: "listings#index" get "/listings/list", to: "listings#list", as: "listings_list" resources :listings resources :addresses get "/purchases/success", to: "purchases#success" # webhook routing post "purchases/webhook", to: "purchases#webhook" # get purchases index get "purchases/index", to: "purchases#index" end # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html # end
require_relative '../../../gilded_rose' require_relative '../../../lib/vault/aged_brie' describe Vault::AgedBrie do subject { described_class.new(item) } describe '#update_quality' do before(:each) do subject.update_quality end context 'Aged Brie" actually increases in Quality the older it gets' do let(:item) { Item.new('Aged Brie', 5, 0) } it 'quality is increased by 1' do expect(item.quality).to eq 1 end context 'after the sell in date the quality is increased by 2' do let(:item) { Item.new('Aged Brie', -1, 1) } it 'quality is increased by 1' do expect(item.quality).to eq 3 end end end end end
# encoding: UTF-8 require 'robut' class Robut::Plugin::Quiz include Robut::Plugin # # @return [Array<String>] contains the various types of responses that are # valid usage examples that would be returned by the Help Plugin # def usage [ "#{at_nick} ask 'Should we break for lunch?'", "#{at_nick} ask for 3 minutes 'Should I continue the presentation?'", "#{at_nick} answer yes" ] end # # @param [Time] time at which the message has arrived # @param [String] sender_nick the sender # @param [String] message the message that was sent # def handle(time, sender_nick, message) # check to see if the user is asking the bot a question request = words(message).join(" ") if sent_to_me? message and is_a_valid_question? request enqueue_the_question sender_nick, request reply "@#{sender_nick}, I have added your question to the list." quizmaster end if sent_to_me? message and currently_asking_a_question? and is_a_valid_response? request process_response_for_active_question sender_nick, request end end QUESTION_REGEX = /^ask ?(choice|polar|range)? (?:question )?(?:(?:for )?(\d+) minutes?)?(.+)$/ def is_a_valid_question? message QUESTION_REGEX =~ message end ANSWER_REGEX = /^answer .+$/ def is_a_valid_response? message ANSWER_REGEX =~ message end def enqueue_the_question(sender,question) (store["quiz::question::queue"] ||= []) << [sender,question] end # # Return a new thread which will pop questions in the queue of questions # def quizmaster if not defined?(@@quizmaster) or @@quizmaster.nil? or !@@quizmaster.alive? @@quizmaster = Thread.new { pop_the_question until there_are_no_more_questions_to_pop } end @@quizmaster end def pop_the_question if popped_question = (store["quiz::question::queue"] ||= []).pop process_the_question *popped_question end end def there_are_no_more_questions_to_pop (store["quiz::question::queue"] ||= []).empty? end def currently_asking_a_question? defined? @@current_question and @@current_question end # # @param [String] sender the user proposing the question # @param [String] request the data related to the asking and the question data itself. # def process_the_question(sender,request) request =~ QUESTION_REGEX type = Regexp.last_match(1) || 'polar' question_length = Regexp.last_match(2) || '2' question_data = Regexp.last_match(3) set_current_question create_the_question_based_on_type(type,sender,question_data), question_length end # # @param [String] question_type the name of the question type which will be # converted from a String to the Class name within the current namespace. # @param [String] sender the sender of the question # @param [String] request the entire message that initiated the question # def create_the_question_based_on_type(question_type,sender,request) self.class.const_get(question_type.capitalize).new sender, request end def set_current_question(question,length_of_time) start_accepting_responses_for_this_question question reply question.ask sleep length_of_time.to_i * 60 stop_accepting_responses_for_this_question question reply "The results are in for '#{question}':" reply question.results # allow some time between the results and asking the next question sleep 10 end def start_accepting_responses_for_this_question(question) @@current_question = question end def stop_accepting_responses_for_this_question(question) @@current_question = nil end # # @param [String] sender_nick the name of the person that is responding to # the question. # @param [String] response is the answer to the question proposed. # def process_response_for_active_question(sender_nick, response) if @@current_question.handle_response sender_nick, response[/^answer (.+)$/,1] reply "Thank you, @#{sender_nick}, I have recorded your response." else reply "Sorry, @#{sender_nick}, I was unable to record that answer" end end end require_relative 'question' require_relative 'polar' require_relative 'range' require_relative 'choice'
class Task < ActiveRecord::Base include PublicActivity::Model belongs_to :project belongs_to :user has_many :assists, dependent: :destroy has_many :users, :through => :assists has_many :activities, as: :trackable, class_name: 'PublicActivity::Activity', dependent: :destroy end
# encoding: utf-8 module Preflight class Issue attr_reader :description, :rule, :attributes, :kind def initialize(description, rule, attributes = {}, kind = :error) @description = description @kind = kind if rule.is_a?(Class) @rule = rule.to_s.to_sym else @rule = rule.class.to_s.to_sym end @attributes = attributes || {} attach_attributes end def to_s @description end private def attach_attributes singleton = class << self; self end @attributes.each do |key, value| singleton.send(:define_method, key, lambda { value }) end end end end
class PageView < ActiveService::Base attribute :url attribute :referrer_url attribute :session_id belongs_to :session end
class ApplicationController < ActionController::Base protect_from_forgery before_action :authenticate_request attr_reader :current_user private def authenticate_request @current_user = if Rails.env.test? ApiUser.create(email: 'test@test.com', expiry: Time.zone.now + 1.day, password: 'password') else AuthorizeApiRequest.call(request.headers).result end render json: { error: 'Not Authorized' }, status: 401 unless @current_user end end
class Statement HEADER = "date || credit || debit || balance" def initialize(log) @log = log @formatted_log = [] end def format_statement format_entries @formatted_log.push(HEADER).reverse.join("\n") end private def format_entries @log.map do |entry| if entry[:type] == "withdrawal" @formatted_log << "#{entry[:date]} || || #{entry[:amount]}.00 || #{entry[:balance]}.00" else @formatted_log << "#{entry[:date]} || #{entry[:amount]}.00 || || #{entry[:balance]}.00" end end end end
Given(/^I send a mail to "([^"]*)"$/) do |name| @user = User.find_by(name: 'bob') @receiver = User.find_by(name: name) @user.send_message(@receiver, 'Lorem ipsum...', 'Subject') end Then(/^I should have "([^"]*)" messages$/) do |count| count = @receiver.mailbox.inbox.count expect(count).to eq count.to_i end
class Song < ApplicationRecord validates :title, :album, :artist, presence: true end
require 'rspec' require 'rules/ca/on/minimum_daily_hours' require 'rules/base' module Rules module Ca module On describe MinimumDailyHours do describe 'processing' do let(:criteria) { { minimum_daily_hours: 3.0, maximum_daily_hours: 8.0, minimum_weekly_hours: 40.0, maximum_weekly_hours: 60.0, saturdays_overtime: true, sundays_overtime: true, holidays_overtime: true, decimal_place: 2, billable_hour: 0.25, closest_minute: 8.0, region: "ca_on", scheduled_shift: OpenStruct.new(started_at: DateTime.parse("2018-01-01 6:00am"), ended_at: DateTime.parse("2018-01-01 4:30pm")) } } context 'when activity is goes beyond minimum daily hours' do subject { MinimumDailyHours.check(4.0, 3.0) } it "should be beyond minimum daily hours" do expect(subject).to be true end end context 'when activity is not over minimum daily hours' do subject { MinimumDailyHours.check(1.0, 3.0) } it "should not be beyond minimum daily hours" do expect(subject).to be false end end end end end end end
class Webpage < ActiveRecord::Base extend FriendlyId include HTTParty include HTMLGettable include HTMLSavable validates :title, length: { in: 3..255 }, allow_blank: true validates :url, presence: true, length: { in: 4..511 } friendly_id :slug_candidates, use: :slugged before_save :set_uuid, :save_html def set_uuid self.uuid = SecureRandom.uuid if self.uuid.nil? end def slug_candidates %i(title uuid) end end
class WindowDims include Hyperstack::State::Observable class << self observer :width do window_size[0] end observer :height do window_size[1] end observer :portrait? do height > width end observer :landscape? do !portrait? end observer :area do if height * width >= 768 * 1024 :large elsif height * width > 400 * 700 :medium else :small end end def grab_window_size mutate @window_size = `[jQuery(window).innerWidth(), jQuery(window).innerHeight()]` end def window_size @window_size ||= begin `jQuery(window).resize(function() {#{grab_window_size}})` grab_window_size end end end end
require 'optparse' module SubSync class OptionsParser attr_reader :direction attr_reader :file_name attr_reader :interval def initialize(argv) parse(argv) sanity_check end private def parse(argv) OptionParser.new do |opts| opts.banner = "Usage: subsync [options]" opts.on("-d", "--direction dir", String, "Direction of transformation, valid options are + and -") do |dir| @direction = dir end opts.on("-f", "--file file", String, "File to synchronize") do |file| @file_name = file end opts.on("-i", "--interval interval", String, "Interval to transform, required format hh:mm:ss,mss") do |interval| @interval = interval end opts.on("-h", "--help", "Show this message") do puts opts exit end begin argv << "-h" if argv.empty? opts.parse(argv) rescue OptionParser::ParseError => e STDERR.puts e.message, "\n", opts exit(-1) end end end def sanity_check raise "Please provide a filename with the -f parameter" if @file_name.nil? || @file_name.empty? raise "Please....I'm looking for directions!! Show me a direction, use the -d paramter" if @direction.nil? || @direction.empty? raise "Interval is not filled out, please use the -i parameter" if @interval.nil? || @interval.empty? raise "Interval is not filled out correctly, the correct format is hh:mm:ss,mss, example: 01:02:03,456" unless /\d{2}:\d{2}:\d{2},\d{3}/=~ @interval end end end
require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "user didn't sign up correctly" do get signup_path assert_no_difference "User.count" do post users_path, user:{ name: "Global", email: "user@disneyland", password: "yo", password: "famo.us" } end assert_template "users/new" end test "user signed up correctly" do get signup_path assert_difference "User.count", 1 do post_via_redirect users_path, user:{ name: "Mickey Mouse", email: "mickey@disneyland.com", password: "imCool", password_confirmation: "imCool" } end assert_template "users/show" end end
class OrganisationController < ApplicationController before_filter :login_required before_filter :organisation_user_required require_role Organisation::Group.roles_for('IT'), :only => :it_stuff require_role Organisation::Group.roles_for('Orkester', 'Riks-SMASK', 'Controller') << 'General', :only => :orchestra_stuff require_role Organisation::Group.roles_for('Personal') << 'General', :only => :hr_stuff require_role Organisation::Group.roles_for('Kårtege') << 'General', :only => :cortege_stuff require_role Organisation::Group.roles_for('Propaganda') << 'General', :only => :propaganda_stuff require_role Organisation::Group.roles_for('Hus') << 'General', :only => :house def planning_and_tasks end def beer @users = Organisation::User.find(:all, :order => "number_of_strokes DESC") end def index if current_user.member_of?('Kommitté') or current_user.member_of?('Marknadsföring') @news = Organisation::News.internal.not_archived @archived_news = Organisation::News.internal.archived else @news = Organisation::News.internal.published.not_archived @archived_news = Organisation::News.internal.published.archived end @events = Organisation::Event.upcoming @shouts = Organisation::Shout.latest_five # Beer highscore @users_by_strokes = Organisation::User.beer_top_five # Show users that has a birthday within a week @users_by_birthday = Organisation::User.birthday_within_a_week @users_by_birthday[0..2] @posts = Blog::Post.internal.published.find(:all, :limit => 4, :order => "created_at DESC") @recruitment_highscore = Funkis::User.highscore @funkis_user_count = Funkis::User.count end def show_archived_news @news = Organisation::News.internal.archived respond_to do |format| format.js do render :update do |page| @news.each do |news_item| page.insert_html :bottom, 'organisation_news', :partial => 'organisation/news/news', :locals => { :news_item => news_item } end page.hide 'show_archived_news_link' end end end end def search searchables = [Organisation::User, Organisation::Event, Organisation::Project, Organisation::WikiPage] @results = searchables.collect { |m| m.search(params[:q]) } @results.flatten! @results.compact! respond_to do |format| format.html do if @results.empty? flash[:notice] = 'Din sökning gav inga resultat.' redirect_back_or_render elsif @results.length == 1 flash[:notice] = 'Din sökning gav bara denna sida som resultat.' redirect_to @results.first else flash[:notice] = "Din sökning gav #{@results.length} resultat" end end end end def it_stuff end def swap_funkis message = "" if params[:user] != "" && params[:team] != "" @user = Funkis::User.find(params[:user]) @team = Funkis::Team.find(params[:team]) @job = @team.available_jobs.first else message = "Du måste fylla i fälten, " end if @job.nil? message += 'jobben är slut i jobblaget' elsif @user.nil? message += 'användaren hittades inte' else @user.job.update_attributes( :user_id => nil ) @job.update_attributes( :user_id => @user.id) message += "gammalt jobb nollställt: #{@user.job.save.to_s}, nytt jobb sparat: #{@job.save.to_s}" end respond_to do |format| format.html do flash[:notice] = message redirect_to :action => :it_stuff end end end def orchestra_stuff @bands = Orchestra::Band.all end def hr_stuff @funkis_user_count = Funkis::User.count @funkis_users_active_length = Funkis::User.active_users.length @funkis_users_inactive_length = Funkis::User.inactive_users.length @funkis_job_count = Funkis::Job.count @funkis_taken_jobs_length = Funkis::Job.taken_jobs.length @funkis_available_jobs_length = Funkis::Job.available_jobs.length @funkis_tshirt_xs_count = Funkis::User.tshirts[:xs] @funkis_tshirt_s_count = Funkis::User.tshirts[:s] @funkis_tshirt_m_count = Funkis::User.tshirts[:m] @funkis_tshirt_l_count = Funkis::User.tshirts[:l] @funkis_tshirt_xl_count = Funkis::User.tshirts[:xl] @funkis_tshirt_count = @funkis_tshirt_xs_count + @funkis_tshirt_s_count + @funkis_tshirt_m_count + @funkis_tshirt_l_count + @funkis_tshirt_xl_count end # Visa funkisar som tillhör en viss grupp def funkisar if !current_user.is_a?(Organisation::User) access_denied else if [ 731, 521, 691, 631 ].include?(current_user.id) # Mat-puttar, måste ha för att planera mat @mat = true @groups = Organisation::Group.find(:all) else @mat = false @groups = current_user.groups end @roles = @groups.collect do |group| group.funkis_roles.find(:all, :include => {:teams => [{:jobs => {:user => :account}}, :shifts]}) end.flatten end end def hr_stuff_organisation @users = Organisation::User.all end def cortege_stuff @teams = Cortege::Team.all @materials = Cortege::Material.all end def propaganda_stuff @bands = Orchestra::Band.all end def house @users = Organisation::User.all end # Link to active sales def sales end end
require "rails_helper" RSpec.describe ExperiencesController, type: :controller do let(:user) {FactoryGirl.create :user} let(:experience) {FactoryGirl.create :experience, user_id: user.id} subject {experience} before {sign_in user} describe "GET #edit" do before :each do get :edit, xhr: true, params: {id: experience.id} end it "assigns the requested experience to @experience" do expect(assigns(:experience)).to eq experience end it "renders the #edit view" do expect(response).to render_template :edit end end describe "PATCH #update" do it "update experience success" do patch :update, params: {id: experience.id, experience:{name: "Framgia Sys", company: "Framgia", start_time: 100.day.ago, end_time: 10.day.ago, user_id: user.id}}, xhr: true, format: "js" expect(flash[:success]).to match(I18n.t("experiences.update.update_success")) end it "update experience fail" do patch :update, params: {id: experience.id, experience:{name: "", start_time: "12/11/2017"}}, xhr: true, format: "js" end end describe "POST #create" do it "create experience success" do post :create, params: {experience:{name: "Framgia Sys", company: "Framgia", start_time: 100.day.ago, end_time: 10.day.ago, user_id: user.id}}, xhr: true, format: "js" expect(flash[:success]).to match(I18n.t("experiences.create.create_success")) end it "create experience fail" do post :update, params: {id: experience.id, experience:{name: "", start_time: "12/11/2017"}}, xhr: true, format: "js" end end describe "DELETE #destroy" do it "destroy experience success" do delete :destroy, params: {id: experience.id}, xhr: true, format: "js" expect(flash[:success]).to match(I18n.t("experiences.destroy.destroy_success")) end end end
# # Cookbook Name:: virtualmonkey # Recipe:: update_stids # # Copyright (C) 2013 RightScale, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # marker "recipe_start_rightscale" do template "rightscale_audit_entry.erb" end log " Updating the ServerTemplate IDs for old collateral" csv_file = "#{node[:virtualmonkey][:user_home]}/" + "#{node[:virtualmonkey][:virtualmonkey][:collateral_name]}/" + "csv_sheets/" + "#{node[:virtualmonkey][:virtualmonkey][:collateral_repo_branch]}.csv" execute "update_stids" do cwd "#{node[:virtualmonkey][:user_home]}/" + "#{node[:virtualmonkey][:virtualmonkey][:collateral_name]}" command "bin/update_stids --source linux --lineage" + " #{node[:virtualmonkey][:virtualmonkey][:collateral_repo_branch]}.csv" only_if { File.exists?(csv_file) } end raise "Can't find #{csv_file}" unless File.exists?(csv_file)