text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe 'users#destroy', type: :request do subject(:make_request) do jsonapi_delete "/api/v1/users/#{user.id}", headers: auth_headers(user) end describe 'basic destroy' do let!(:user) { create(:user) } it 'updates the resource' do expect(V1::UserResource).to receive(:find).and_call_original expect { make_request expect(response.status).to eq(200), response.body }.to change { User.count }.by(-1) expect { user.reload } .to raise_error(ActiveRecord::RecordNotFound) expect(json).to eq('meta' => {}) end end end
module Bosh::Director module DeploymentPlan class AgentStateMigrator def initialize(logger) @logger = logger end def get_state(instance) @logger.debug("Requesting current VM state for: #{instance.agent_id}") agent = AgentClient.with_agent_id(instance.agent_id, instance.name) state = agent.get_state { Config.job_cancelled? } @logger.debug("Received VM state: #{state.pretty_inspect}") verify_state(instance, state) @logger.debug('Verified VM state') state.delete('release') if state.include?('job') state['job'].delete('release') end state end def verify_state(instance, state) unless state.kind_of?(Hash) @logger.error("Invalid state for '#{instance.vm_cid}': #{state.pretty_inspect}") raise AgentInvalidStateFormat, "VM '#{instance.vm_cid}' returns invalid state: " + "expected Hash, got #{state.class}" end end end end end
# Добавляет аргумент pagination к полям с connection_type, и передает его в context. module Extensions class CustomConnectionExtension < GraphQL::Schema::Field::ConnectionExtension def apply field.argument(:pagination, Arguments::Pagination, required: false) super end def resolve(object:, arguments:, context:) args = arguments.dup context[:pagination] = args.delete(:pagination) super(object: object, arguments: args, context: context) end end end
class QuoteReminders # Search all incomplete quote nearly expired time and alert to user def self.incomplete_reminder quotes = Quote.incomplete_reminder reminders = {} quotes.each do |quote| reminders[quote.account] = '' if reminders[quote.account_id].nil? reminders[quote.account] += "Incomplelte quote no #{quote.id} is nearly expired \n" end ActiveRecord::Base.transaction do reminders.each do |k, v| Mailboxer::Notification.notify_all(k.users, 'Incomplete Quotes reminder', v, send_mail = false) end end end end
# frozen_string_literal: true require "json" module Fastlane module Actions class ReadJsonAction < Action def self.run(params) json_path = params[:json_path] @is_verbose = params[:verbose] print_params(params) if @is_verbose unless File.file?(json_path) put_error!("File at path #{json_path} does not exist. Verify that the path is correct ❌") return nil end json_content = File.read(json_path) begin JSON.parse(json_content, symbolize_names: true) rescue put_error!("File at path #{json_path} has invalid content. ❌") end end def self.put_error!(message) UI.user_error!(message) raise StandardError, message end def self.description "Read a json file and expose a hash with symbolized names as result" end def self.details "Use this action to read a json file and access to it as Hash with symbolized names" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :json_path, description: "Path to json file", is_string: true, optional: false, verify_block: proc do |value| UI.user_error!("You must set json_path pointing to a json file") unless value && !value.empty? end), FastlaneCore::ConfigItem.new(key: :verbose, description: "verbose", optional: true, type: Boolean) ] end def self.print_params(options) table_title = "Params for read_json #{Fastlane::Json::VERSION}" FastlaneCore::PrintTable.print_values(config: options, hide_keys: [], title: table_title) end def self.return_value "Hash" end def self.authors ["Martin Gonzalez"] end def self.is_supported?(_platform) true end end end end
module RSpec module Matchers class BeAKindOf include BaseMatcher def matches?(actual) super(actual).kind_of?(expected) end end # Passes if actual.kind_of?(expected) # # @example # # 5.should be_kind_of(Fixnum) # 5.should be_kind_of(Numeric) # 5.should_not be_kind_of(Float) def be_a_kind_of(expected) BeAKindOf.new(expected) end alias_method :be_kind_of, :be_a_kind_of end end
#require 'digest/sha1' module Admin class User < ActiveRecord::Base has_and_belongs_to_many :roles, join_table: :users_roles has_secure_password #-- ------------------------------------------------------------- # Validations # ## # Regular expression to verify email pattern VALID_EMAIL_REGEX = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i ## # Regular expression to verify password pattern. # # Password must be between 6 and 40 characters long, and include at least one upper case, lower case, digit and special character except white space VALID_PASSWORD_REGEX = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#\$%^&*-=_\[\]\{\}\:\;\'\"\\\,\.<>\?\/]).{6,40}$/ validates :user_name, presence: true, length: { in: 6..50 } validates :user_id, presence: true, confirmation: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :password, on: :create, presence: true, confirmation: true, length: { within: 6..40 } validates :password, on: :update, confirmation: true, length: { within: 6..40 }, if: :password_digest_changed? #-- ------------------------------------------------------------- # Callbacks # before_validation do self.user_id = user_id.downcase if attribute_present?('user_id') @user_id_confirmation = @user_id_confirmation.downcase if defined? @user_id_confirmation end before_create do create_session_token end before_save do self.user_id = user_id.downcase end #-- ------------------------------------------------------------- # Methods # # Create session token def User.new_session_token SecureRandom.urlsafe_base64 end # Making digest of the token def User.digest(token) Digest::SHA1.hexdigest(token.to_s) end def set_salt! self.salt = Digest::SHA1.hexdigest("#{self.user_id}#{rand(1073741824..2147483647)}") end private def create_session_token self.session_token = User.digest(User.new_session_token) end end end
class AddKindToSettings < ActiveRecord::Migration def change add_column :settings, :kind, :string, default: "string", null: false end end
# coding: utf-8 require 'spec_helper' include Staticman class ProxyRequestTest include ProxyRequest end describe ProxyRequest do describe '#request_context' do context 'host is config value' do let(:request) { ProxyRequestTest.new.request_context } it { request.should be_kind_of ActionDispatch::TestRequest } it { request.host.should be_eql 'example.com' } end end end
version = `cat ./version`.strip Pod::Spec.new do |s| s.name = 'CZiti-iOS' s.version = version s.summary = 'Ziti SDK for Swift (iOS)' s.homepage = 'https://github.com/openziti/ziti-sdk-swift' s.author = { 'ziti-ci' => 'ziti-ci@netfoundry.io' } s.license = { :type => 'Apache-2.0', :file => 'LICENSE' } s.platform = :ios s.source = { :http => "https://github.com/openziti/ziti-sdk-swift/releases/download/#{s.version}/CZiti-iOS.framework.tgz" } s.source_files = '*.{swift,h,m}' s.swift_version = '5.0' s.public_header_files = '*.h' # s.xcconfig = { 'ENABLE_BITCODE' => 'NO', 'CLANG_ENABLE_MODULES' => 'YES', 'SWIFT_VERSION' => '5.0' } # s.xcconfig = { 'ENABLE_BITCODE' => 'NO', 'ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES' => 'YES' } s.xcconfig = { 'ENABLE_BITCODE' => 'NO' } s.frameworks = "Foundation" s.ios.deployment_target = '13.4' s.ios.vendored_frameworks = 'CZiti.framework' end
# https://www.codewars.com/kata/5270d0d18625160ada0000e4 def score(dice) h = dice.each_with_object(Hash.new(0)) { |e, h| h[e] += 1 } result = 0 h.each do |k, v| if v >= 3 result += case k when 1 then 1000 else k * 100 end v -= 3 end while v > 0 do result += case k when 1 then 100 when 5 then 50 else 0 end v -= 1 end end result end
class Prime < ActiveRecord::Base validates :number, presence: true, uniqueness: true, numericality: {only_integer: true, greater_than: 0} end
FactoryBot.define do factory :order do purchase_amount {Faker::Number.between(10000000000000, 90000000000000)} payment_price {Faker::Number.between(500,30000)} end end
class CityTripsController < ApplicationController before_action :require_login def index @my_city_trips = CityTrip.my_trips(session[:user_id]) end def show @city_trip = CityTrip.find(params[:id]) end def new trip_id = params[:format] @trip = Trip.find(trip_id) @city_trip = CityTrip.new end def create @city_trip = CityTrip.new(trip_id: params[:city_trip][:trip_id], city_id: params[:city_trip][:city_id]) if @city_trip.save redirect_to city_trip_path(@city_trip) else render :edit end end def edit @city_trip = CityTrip.find(params[:id]) @trip = @city_trip.trip end def update @city_trip = CityTrip.find(params[:id]) @trip = @city_trip.trip @city_trip.update(city_id: params[:city_trip][:city_id]) if @city_trip.save redirect_to city_trip_path(@city_trip) else render :edit end end def destroy city_trip = CityTrip.find(params[:id]) city_trip.destroy flash[:notice] = "Your wishlist item has been deleted." redirect_to welcome_path end private def require_login return head(:forbidden) unless session.include? :user_id end end
# frozen_string_literal: true # HideCompany class class HideCompany < ApplicationRecord belongs_to :portfolio validates :name, uniqueness: { scope: :portfolio_id } end
class AddColumnsToUsers < ActiveRecord::Migration def change add_column :users, :modelling_agency, :string add_column :users, :phone_number, :string add_column :users, :country, :string add_column :users, :town, :string end end
class CreateDepositions < ActiveRecord::Migration[6.0] def change create_table :depositions do |t| t.string :reason t.string :excuse t.string :dep_city t.string :arr_city t.datetime :departure, default: nil t.datetime :arrival, default: nil t.boolean :forward t.datetime :forward_dep, default: nil t.datetime :forward_arr, default: nil t.string :delay t.string :alert_date t.timestamps end end end
class SpecialLinesController < ApplicationController # results page for all special line products def index @response = HTTParty.get(ENV["JSON_API_URL"] + "/products.json").sort_by { |hash| hash['id'].to_i } end # individual show page for each special line product def show unless !/\A\d+\z/.match(params[:id]) # If params[:id] is an integer @each_product = HTTParty.get(ENV["JSON_API_URL"] + "/products/" + params[:id] + ".json") session[:product_id] = @each_product["id"] redirect_to "/"+@each_product["department"].gsub(/\s+/, "-")+"/"+@each_product["name"].downcase.gsub(/\s+/, "-") else # If params[:id] is not an integer unless session[:product_id].nil? # If session[:product_id] is not nil @each_product = HTTParty.get(ENV["JSON_API_URL"] + "/products/" + session[:product_id].to_s + ".json") # Reset session to prevent infinite loop reset_session else # If session[:prduct_id] is nil HTTParty.get(ENV["JSON_API_URL"] + "/products.json").each do |product| if params[:id] === product["name"].downcase.gsub(/\s+/, "-") && product["department"] === "special lines" # If the downcased and dashed product name equals params[:id] session[:product_id] = product["id"] redirect_to "/"+product["department"].gsub(/\s+/, "-")+"/"+product["name"].downcase.gsub(/\s+/, "-") return end end # If the downcased and dashed product name does not match any products redirect_to "/special-lines/" end end end private def product_params params.require(:product).permit([:name, :department, :category, :summary, :focus, :banner_id, :thumbnail_id, :thumb_caption, :plan_type, :id, :cta_route, :productImg_id]) end end
require 'rubygems' require 'sinatra' require './environment' mime_type :ttf, "application/octet-stream" mime_type :woff, "application/octet-stream" configure do set :views, "#{File.dirname(__FILE__)}/views" set :public, "#{File.dirname(__FILE__)}/public" end error do e = request.env['sinatra.error'] Kernel.puts e.backtrace.join("\n") 'Application error' end helpers do def partial(template, options = {}) options.merge!(:layout => false) haml("shared/#{template}".to_sym, options) end end get '/shared/:page_name' do @page_name = params[:page_name] haml "shared/#{@page_name}".to_sym, :layout => false end get '/:folder/:page_name' do @page_name = params[:page_name] @folder = params[:folder] haml "#{@folder}/#{@page_name}".to_sym, :layout => :'layouts/main' end get '/:page_name' do @page_name = params[:page_name] haml @page_name.to_sym, :layout => :'layouts/main' end get '/' do @page_name = 'home' @wrapper_width = params[:wrapper_width].to_f @gutter_width = params[:gutter_width].to_f @wrapper_margin = params[:wrapper_margin].to_f # Wrapper @wrapper_real_width = @wrapper_width - @wrapper_margin*2 #Gutter @gutter_width_percent = @gutter_width*100/@wrapper_real_width #Base Columns @half = (100 - @gutter_width_percent)/2 @third = (100 - @gutter_width_percent*2)/3 @quarter = (100 - @gutter_width_percent*3)/4 @fifth = (100 - @gutter_width_percent*4)/5 @sixth = (100 - @gutter_width_percent*5)/6 #Column Multiples @twothird = @third*2 + @gutter_width_percent @threequarter = @quarter*3 + @gutter_width_percent*2 @twofifth = @fifth*2 + @gutter_width_percent @threefifth = @fifth*3 + @gutter_width_percent*2 @fourfifth = @fifth*4 + @gutter_width_percent*3 @fivesixth = @sixth*5 + @gutter_width_percent*4 #Offsets @push_half = @half + @gutter_width_percent @push_third = @third + @gutter_width_percent @push_quarter = @quarter + @gutter_width_percent @push_fifth = @fifth + @gutter_width_percent @push_sixth = @sixth + @gutter_width_percent @push_twothird = @twothird + @gutter_width_percent @push_threequarter = @threequarter + @gutter_width_percent @push_twofifth = @twofifth + @gutter_width_percent @push_threefifth = @threefifth + @gutter_width_percent @push_fourfifth = @fourfifth + @gutter_width_percent @push_fivesixth = @fivesixth + @gutter_width_percent #split haml :index, :layout => :'layouts/main' end
class Pile < ApplicationRecord belongs_to :game has_many :cards belongs_to :game_player end
class SubscribersController < ApplicationController def create subscriber = Subscriber.new(subscriber_params) if subscriber.save flash[:success] = t('flashes.subscriber.created') else flash[:error] = t('flashes.subscriber.error') end redirect_to :back end private def subscriber_params params.require(:subscriber).permit(:email) end end
require 'rails_helper' require 'database_cleaner' RSpec.describe Api::V1::Invoices::MerchantsController, type: :controller do describe "GET /invoice/:id/merchant" do it "returns a specific invoices merchant" do c31 = Customer.create c32 = Customer.create m1 = Merchant.create m2 = Merchant.create i1 = Invoice.create(status: "shipped", customer_id: c31.id, merchant_id: m1.id) i2 = Invoice.create(status: "other", customer_id: c32.id, merchant_id: m2.id) get :show, id: i1.id, format: :json body = JSON.parse(response.body) invoice_merchant_id = body["id"] expect(response.status).to eq 200 expect(invoice_merchant_id).to eq(m1.id) end end end
module Binged module Search # A class that encapsulated the Bing Web Search source # @todo Add support for adult and market filtering class Web < Base include Filter include Pageable SUPPORTED_FILE_TYPES = [:doc, :dwf, :feed, :htm, :html, :pdf, :ppt, :ps, :rtf, :text, :txt, :xls] # @param [Binged::Client] client # @param [String] query The search term to be sent to Bing # @param [Hash] options def initialize(client, query=nil, options={}) super(client, query) @source = :web set_paging_defaults end # Add filtering based on a file type # # @example # web_search.file_type(:pdf) # Isolate search to PDF files # # @param [Symbol] type A symbol of a {SUPPORTED_FILE_TYPES} # @return [self] # @see http://msdn.microsoft.com/en-us/library/dd250876.aspx Description of all supported file types def file_type(type) @query['Web.FileType'] = type if SUPPORTED_FILE_TYPES.include?(type) self end end end end
# frozen_string_literal: true class PokemonSerializer < ActiveModel::Serializer attributes :pokedex_number, :name, :pokedex_entry, :weight, :height end
module AsciiArt class Brush attr_accessor :stroke, :x_pos, :y_pos, :lifted def initialize(stroke, x, y) @stroke = stroke @x_pos = x @y_pos = y @lifted = false end def raise_or_lower @lifted = !@lifted end def move(x, y) @x_pos = x @y_pos = y end def move_up move(@x_pos, @y_pos - 1) end def move_down move(@x_pos, @y_pos + 1) end def move_left move(@x_pos - 1, @y_pos) end def move_right move(@x_pos + 1, @y_pos) end end end
require 'rubygems' require 'digest' require 'json' require 'rest-client' require 'pry' class ApiRest $url def initialize(testnet) $url = "https://gameathon.mifiel.com/api/v1/games/#{testnet}/" end def query_get(resource) puts "*********************************************************************" puts "[Getting data from ==> #{$url}#{resource}]" puts "" response = RestClient::Request.execute( :method => :get, :url => $url.to_s + resource.to_s, :ssl_version => 'SSLv23' ) return JSON.parse(response, symbolize_names: true) end def query_post(payload, resource) puts "*********************************************************************" puts "[Sending POST data to ==> #{$url}#{resource}]" puts "" response = RestClient::Request.execute( :method => :post, :url => $url.to_s + resource.to_s, :payload => payload.to_json, :ssl_version => 'SSLv23', :headers => { :content_type => :json, :accept => :json } ) return JSON.parse(response, symbolize_names: true) rescue RestClient::Exception => e puts "" puts "ERROR Inspect: #{e.inspect}" puts "ERROR Response: #{e.response}" puts "************************************************" end def get_blocks puts "Getting last blocks..." response = query_get('blocks') return response end def get_last_target puts "Getting last target..." response = query_get('target') return response[:target] end def get_pool_info puts "Getting pool..." response = query_get('pool') return response end end
# Scrapes all images from a given page # Command line arguments : website_url require "open-uri" require "nokogiri" count = 1 if ARGV[0] puts "Loading" html = Nokogiri::HTML(open(ARGV[0])) puts "Loaded\n\n" srcs = html.css("img") srcs.each do |img_tag| puts "Opening #{count}" open(img_tag['src']) do |img| img_name = img_tag['src'].split("/") img_name = img_name[img_name.length-1] file = open(img_name, 'w') puts "Writing" file.write(img.read) file.close puts "Done\n\n" count += 1 end end end
# frozen_string_literal: true class DrilldownSearchesController < ApplicationController before_action :admin_required before_action :set_drilldown_search, only: %i[show edit update destroy] def index @drilldown_searches = DrilldownSearch.all end def show; end def new @drilldown_search ||= DrilldownSearch.new render :new end def edit; end def create @drilldown_search = DrilldownSearch.new(drilldown_search_params) if @drilldown_search.save redirect_to drilldown_searches_path, notice: 'Drilldown search was successfully created.' else new end end def update if @drilldown_search.update(drilldown_search_params) redirect_to drilldown_searches_path, notice: 'Drilldown search was successfully updated.' else render :edit, status: :unprocessable_entity end end def destroy @drilldown_search.destroy redirect_to drilldown_searches_url, notice: 'Drilldown search was successfully destroyed.' end private def set_drilldown_search @drilldown_search = DrilldownSearch.find(params[:id]) end def drilldown_search_params search_params = params.dig(:drilldown_search, :parameters) if search_params.is_a? String begin params[:drilldown_search][:parameters] = JSON.parse(search_params) rescue JSON::ParserError # Use the string end end params.require(:drilldown_search).permit(:model, :count, parameters: {}) end end
require 'test_helper' class Api::UsersControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end test 'POST #create' do it "validates the presence of the user's username and password" do post :create, params: { user: {username: 'Batman@supermansucks.net', password: ''}} expect(response).to status(422) end end end
# frozen_string_literal: true module Statistics class Views attr_reader :log # @param [Log, #lines, #extract_url_from(..), #extract_ip_from(..)] # a Log instance with corresponding interface def initialize(log) @log = log end def generate! analyze! end private # @return [Hash] the resulting hash # must be overwritten accordingly def analyze!; end end end
require "./ratio" class ParserError < StandardError; end class Parser def initialize(s) @s=s @pos=0 end def peak if @pos>=@s.length raise ParserError.new end @s[@pos] end def next v=self.peak @pos+=1 v end def expect(f) v=self.peak if f.call(v) self.next v else raise ParserError.new end end def char(c) self.expect(lambda{|v|v==c}) end def number s="" begin self.char("-") g=-1 rescue => error g=1 end while true begin s+=self.expect(lambda{|v|"1234567890".index(v)!=nil}) rescue => error break end end if s.length!=1&&s[0]=="0" raise ParserError.new end begin v=Integer(s)*g rescue =>error raise ParserError.new end Ratio.new(v,1) end def eof if @s.length!=@pos raise ParserError.new end end def factor begin self.char("(") rescue =>error return self.number end v=self.expr char(")") v end def term x=self.factor while true begin op=self.expect(lambda{|c|c=="*"||c=="/"}) rescue => error break end case op when "*" x=x*self.factor when "/" x=x/self.factor end end x end def expr x=self.term while true begin op=self.expect(lambda{|c|c=="+"||c=="-"}) rescue => error break end case op when "+" x=x+self.term when "-" x=x-self.term end end x end def parse v=self.expr eof v end end
require_relative '../../../spec_helper' require_relative '../factories/position' require_relative '../factories/time_slot' require_relative '../factories/user' describe TimeSlot do before(:all) do Position.delete_all TimeSlot.delete_all User.delete_all end it "create time_slot" do lambda { FactoryGirl.create(:time_slot) }.should change(TimeSlot, :count).by(1) end context "Validation with scope and association" do it "is not valid if exists time slot which have position with same person" do time_slot1 = FactoryGirl.create(:time_slot, :starts_at => "2012-10-11".to_date, :ends_at => "2012-10-13".to_date) time_slot2 = FactoryGirl.create(:time_slot, :starts_at => "2012-10-15".to_date, :ends_at => "2012-10-16".to_date) user = FactoryGirl.create(:user) user_2 = FactoryGirl.create(:user) position1 = FactoryGirl.create(:position, :time_slot => time_slot1, :user => user) position2 = FactoryGirl.create(:position, :time_slot => time_slot2, :user => user) position3 = FactoryGirl.create(:position, :time_slot => time_slot2, :user => user_2) time_slot2.reload time_slot2.starts_at = "2012-10-12".to_date time_slot2.should_not be_valid time_slot2.errors[:base].should_not be_empty end it "is valid if exists time slot which have position with same person" do time_slot1 = FactoryGirl.create(:time_slot, :starts_at => "2012-10-11".to_date, :ends_at => "2012-10-13".to_date) time_slot2 = FactoryGirl.create(:time_slot, :starts_at => "2012-10-14".to_date, :ends_at => "2012-10-16".to_date) user = FactoryGirl.create(:user) position1 = FactoryGirl.create(:position, :time_slot => time_slot1, :user => user) position2 = FactoryGirl.build(:position, :time_slot => time_slot2, :user => user) time_slot2.starts_at = "2012-10-15".to_date time_slot2.should be_valid time_slot2.errors[:base].should be_empty end end end
# -*- coding: utf-8; -*- # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file to you 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. # # However, if you have executed another commercial license agreement # with Crate these terms will supersede the license and you may use the # software solely pursuant to the terms of the relevant commercial agreement. require_relative '../spec_helper' describe "Post#array" do before(:all) do ActiveRecord::Migration.class_eval do create_table :posts do |t| t.string :title t.integer :comment_count t.array :tags, array_type: :string t.array :votes, array_type: :integer t.array :bool_arr, array_type: :boolean end end ensure_status('GREEN') Post.reset_column_information end after(:all) do ActiveRecord::Migration.class_eval do drop_table :posts end end describe "#array column type" do let(:array) { %w(hot fresh) } let(:votes) { [9, 8, 7] } let(:bool_arr) { [true, false, true] } let(:post) { Post.create!(title: 'Arrays are awesome', tags: array, votes: votes, bool_arr: bool_arr) } context 'create' do it 'should store and return an array' do p = Post.find(post.id) p.tags.should be_a Array p.votes.should be_a Array p.bool_arr.should be_a Array p.tags.should eq array p.votes.should eq votes p.bool_arr.should eq bool_arr end it 'should find the post by array value' do post = Post.create!(title: 'Arrays are awesome', tags: array, votes: votes) refresh_posts Post.where("'fresh' = ANY (tags)").should include(post) end end context '#update' do it 'should update and existing array value' do post = Post.create!(title: 'Arrays are awesome', tags: array, votes: votes) refresh_posts new_tags = %w(ok) post.update_attributes!(tags: new_tags) refresh_posts post.reload post.tags.should eq new_tags end end end end
require 'test_helper' class ThreeScale::SemanticFormBuilderTest < ActionView::TestCase include Formtastic::SemanticFormHelper class Dummy extend ActiveModel::Naming attr_reader :errors, :title, :author def initialize @errors = ActiveModel::Errors.new(self) @errors.add(:title, 'error 1') @errors.add(:title, 'error 2') @errors.add(:author, 'error 1') @errors.add(:author, 'error 2') @title = 'title' @author = 'author' end end def test_select_input user = FactoryBot.create(:simple_user) semantic_form_for(user, url: '', as: :dummy) do |f| f.input(:notifications, as: :select).html_safe end end test 'inline errors' do dummy = Dummy.new # # Inline errors # buffer = TestOutputBuffer.new buffer.concat( semantic_form_for(dummy, :url => '', as: :dummy) do |f| f.input(:title, inline_errors: :list).html_safe end ) html_doc = Nokogiri::HTML(buffer.output) # errors as list assert html_doc.css('li#dummy_title_input ul.errors').present? # # Normal behaviour # buffer = TestOutputBuffer.new buffer.concat( semantic_form_for(dummy, :url => '', as: :dummy) do |f| f.input(:title).html_safe end ) # test errors as sentence html_doc = Nokogiri::HTML(buffer.output) assert_equal 'error 1 and error 2', html_doc.css('li#dummy_title_input p.inline-errors').text # # Should be independent and no affect to other fields # buffer = TestOutputBuffer.new buffer.concat( semantic_form_for(dummy, :url => '', as: :dummy) do |f| f.input(:title, inline_errors: :list).html_safe + f.input(:author).html_safe end ) html_doc = Nokogiri::HTML(buffer.output) # errors of title as list assert html_doc.css('li#dummy_title_input ul.errors').present? # errors of author as sentence assert_equal 'error 1 and error 2', html_doc.css('li#dummy_author_input p.inline-errors').text end end
# frozen_string_literal: true require 'spec_helper' class ManyToOneSpec < AssociationFilteringSpecs before do drop_tables DB.create_table :artists do primary_key :id end DB.create_table :albums do primary_key :id foreign_key :artist_id, :artists end DB.run <<-SQL INSERT INTO artists SELECT i FROM generate_series(1, 10) i; INSERT INTO albums (artist_id) SELECT (i % 10) + 1 FROM generate_series(1, 100) i; SQL class Artist < Sequel::Model one_to_many :albums, class: 'ManyToOneSpec::Album' end class Album < Sequel::Model many_to_one :artist, class: 'ManyToOneSpec::Artist' end end after do drop_tables end def drop_tables DB.drop_table? :albums, :artists end describe "association_filter through a many_to_one association" do it "should support a simple filter" do ds = Album.association_filter(:artist){|a| a.where{mod(id, 5) =~ 0}} assert_equal 20, ds.count assert_equal %(SELECT * FROM "albums" WHERE (EXISTS (SELECT 1 FROM "artists" WHERE (("artists"."id" = "albums"."artist_id") AND (mod("id", 5) = 0)) LIMIT 1))), ds.sql record = ds.order_by{random.function}.first assert_includes [5, 10], record.artist_id end end describe "association_exclude through a many_to_one association" do it "should support a simple filter" do ds = Album.association_exclude(:artist){|a| a.where{mod(id, 5) =~ 0}} assert_equal 80, ds.count assert_equal %(SELECT * FROM "albums" WHERE NOT (EXISTS (SELECT 1 FROM "artists" WHERE (("artists"."id" = "albums"."artist_id") AND (mod("id", 5) = 0)) LIMIT 1))), ds.sql record = ds.order_by{random.function}.first refute_includes [5, 10], record.artist_id end end end
class AddTargetableFieldsToTarget < ActiveRecord::Migration def change add_column :targets, :targetable_id, :integer add_column :targets, :targetable_type, :string end end
module ApplicationHelper def no_turbolink? if content_for(:no_turbolink) { data: {no_turbolink: true} } else { data: nil } end end end
class AddJobsInquiryFormToGlobalSettings < ActiveRecord::Migration def change add_column :global_settings, :jobs_inquiry_form, :text end end
# # Copyright 2011 National Institute of Informatics. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. require 'test_helper' class WaitingProposalTest < ActiveSupport::TestCase # Replace this with your real tests. # called before every single test def setup proposal = Proposal.new(:name => 'test', :software => Software.find_by_name("nova"), :state => 'init') @wp = WaitingProposal.new(:proposal => proposal, :operation => 'install') end # called after every single test def teardown end test "should not save WaitingProposal without proposal" do @wp.proposal = nil assert !@wp.save end test "should not save WaitingProposal without operation" do @wp.operation = nil assert !@wp.save end test "should not save WaitingProposal with the operation and proposal_id" do @wp.save wp_new = WaitingProposal.new(:proposal => @proposal, :operation => 'install') assert !wp_new.save end test "should save WaitingProposal with correct operations" do operations = ['install', 'uninstall', 'test'] operations.each{|ope| @wp.operation = ope assert @wp.save } end test "should save WaitingProposal" do assert @wp.save end end
require "test_helper" class DashboardsControllerTest < ActionController::TestCase def dashboard @dashboard ||= dashboards :one end def test_index get :index assert_response :success assert_not_nil assigns(:dashboards) end def test_new get :new assert_response :success end def test_create assert_difference("Dashboard.count") do post :create, dashboard: { total_count: dashboard.total_count, user_id: dashboard.user_id, user_id: dashboard.user_id, website: dashboard.website } end assert_redirected_to dashboard_path(assigns(:dashboard)) end def test_show get :show, id: dashboard assert_response :success end def test_edit get :edit, id: dashboard assert_response :success end def test_update put :update, id: dashboard, dashboard: { total_count: dashboard.total_count, user_id: dashboard.user_id, user_id: dashboard.user_id, website: dashboard.website } assert_redirected_to dashboard_path(assigns(:dashboard)) end def test_destroy assert_difference("Dashboard.count", -1) do delete :destroy, id: dashboard end assert_redirected_to dashboards_path end end
# @param [Method] f function def prm(f, a, b, n) h = (b - a) / n.to_f res = 2.0 (1..n).each do |i| x = a + i * h - h / 2.0 res += f.call(x) end res *= h end # @param [Method] f function def trp(f, a, b, n) h = (b - a) / (n.to_f - 1) res = f.call(a) / 2.0 (1...n - 1).each do |i| x = a + i * h res += f.call(x) end res = (res + f.call(b) / 2.0) * h end def f1(x) x ** 3 * Math.exp(2 * x) end def f2(x) 1.0 / (x * Math.log(x) ** 2) end # @param [Method] f function def run(f, a, b, n) prm_f1 = prm(f, a, b, n) trp_f2 = trp(f, a, b, n) puts "f = #{f.name}, a = #{a}, b = #{b}, c = #{n}" puts "prm = #{prm_f1}" puts "trp = #{trp_f2}" puts "Average: #{(prm_f1 + trp_f2) / 2.0}" puts end n = 256 run(method(:f1), 0.0, 0.8, n) run(method(:f2), 2.0, 2.5, n)
class Admin < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_one :admin_account accepts_nested_attributes_for :admin_account after_create :initialize_admin_account private def initialize_admin_account a = AdminAccount.new do |a| a.admin_id = self.id a.name = self.name a.subdomain = self.subdomain end if a.save self.admin_account = a else raise "Error creating account" end end end
Gem::Specification.new do |s| s.name = 'forkout' s.version = '0.0.1' s.has_rdoc = false s.extra_rdoc_files = ['README', 'LICENSE'] s.summary = 'forks a block' s.description = 'forks a list to a block using Rinda, kinda unstable' s.author = 'Szczyp' s.email = 'qboos@wp.pl' s.homepage = 'http://github.com/Szczyp/forkout' s.files = %w(LICENSE README Rakefile) + Dir.glob("{bin,lib,spec}/**/*") s.require_path = "lib" s.files = Dir["{lib, test}/**/*", "[A-Z]*"] s.platform = Gem::Platform::RUBY end
require 'rubygems' require 'dogapi' def set_downtime() api_key = ENV['DD_API_KEY'] app_key = ENV['DD_APP_KEY'] dog = Dogapi::Client.new(api_key, app_key) start_ts = Time.now.to_i end_ts = start_ts + (3 * 60 * 60) end_reccurrence_ts = start_ts + (1 * 7 * 24 * 60 * 60) recurrence = { 'type' => 'weeks', 'period' => 1, 'week_days' => ['Fri'], 'until_date' => end_reccurrence_ts } # Schedule downtime dog.schedule_downtime('mmpxy01p', :start => start_ts, :end => end_ts, :recurrence => recurrence) end
class AddImapWorkerStatusToProfile < ActiveRecord::Migration def change add_column :profiles, :imap_worker_started_at, :timestamp add_column :profiles, :imap_worker_completed_at, :timestamp end end
# frozen_string_literal: true module Dry module Types # Schema is a hash with explicit member types defined # # @api public class Schema < Hash # Proxy type for schema keys. Contains only key name and # whether it's required or not. All other calls deletaged # to the wrapped type. # # @see Dry::Types::Schema class Key extend ::Dry::Core::Deprecations[:"dry-types"] include Type include Dry::Equalizer(:name, :type, :options, inspect: false, immutable: true) include Decorator include Builder include Printable # @return [Symbol] attr_reader :name # @api private def initialize(type, name, required: Undefined, **options) required = Undefined.default(required) do type.meta.fetch(:required) { !type.meta.fetch(:omittable, false) } end unless name.is_a?(::Symbol) raise ArgumentError, "Schemas can only contain symbol keys, #{name.inspect} given" end super(type, name, required: required, **options) @name = name end # @api private def call_safe(input, &block) type.call_safe(input, &block) end # @api private def call_unsafe(input) type.call_unsafe(input) end # @see Dry::Types::Nominal#try # # @api public def try(input, &block) type.try(input, &block) end # Whether the key is required in schema input # # @return [Boolean] # # @api public def required? options.fetch(:required) end # Control whether the key is required # # @overload required # @return [Boolean] # # @overload required(required) # Change key's "requireness" # # @param [Boolean] required New value # @return [Dry::Types::Schema::Key] # # @api public def required(required = Undefined) if Undefined.equal?(required) options.fetch(:required) else with(required: required) end end # Make key not required # # @return [Dry::Types::Schema::Key] # # @api public def omittable required(false) end # Turn key into a lax type. Lax types are not strict hence such keys are not required # # @return [Lax] # # @api public def lax __new__(type.lax).required(false) end # Make wrapped type optional # # @return [Key] # # @api public def optional __new__(type.optional) end # Dump to internal AST representation # # @return [Array] # # @api public def to_ast(meta: true) [ :key, [ name, required, type.to_ast(meta: meta) ] ] end # @see Dry::Types::Meta#meta # # @api public def meta(data = Undefined) if Undefined.equal?(data) || !data.key?(:omittable) super else self.class.warn( "Using meta for making schema keys is deprecated, " \ "please use .omittable or .required(false) instead" \ "\n" + Core::Deprecations::STACK.() ) super.required(!data[:omittable]) end end private # @api private def decorate?(response) response.is_a?(Type) end end end end end
class ProjectType < ActiveRecord::Base MAX_TYPE_NAME = 200 has_many :feature_prices has_many :project_features, through: :feature_prices validates :type_name, presence: true, length: { maximum: MAX_TYPE_NAME } end
class ProfileEmailAccess < ActiveRecord::Base belongs_to :profile belongs_to :email_access end
# # Cookbook Name:: cubrid # Attributes:: pdo_cubrid # # Copyright 2012, Esen Sagynov <kadishmal@gmail.com> # # Distributed under MIT license # # Latest build numbers for each CUBRID PDO version in the form of 'version'=>'build_number'. build_numbers = {'9.1.0' => '0003', '9.0.0' => '0001', '8.4.3' => '0001', '8.4.0' => '0002'} # The default version of CUBRID PDO driver to install. default['cubrid']['version'] = "9.1.0" # For CUBRID 8.4.1 use PDO driver 8.4.0 as they are compatible. # No separeate PDO driver version was released for CUBRID 8.4.1. set['cubrid']['pdo_version'] = node['cubrid']['version'] == "8.4.1" ? "8.4.0" : node['cubrid']['version'] # the version of a CUBRID PDO driver to install from PECL set['cubrid']['pdo_version'] = "#{node['cubrid']['pdo_version']}.#{build_numbers[node['cubrid']['pdo_version']]}" # the name of a PECL package to install CUBRID PDO driver set['cubrid']['pdo_package'] = "PDO_CUBRID-#{node['cubrid']['pdo_version']}" case node["platform"] when "centos", "redhat", "fedora" # the location of PHP configuration directory set['cubrid']['php_ext_conf_dir'] = '/etc/php.d' # PHP 5.3.3 installed via YUM seems to be missing "libgcrypt-devel" library which is required to build PECL packages. set['cubrid']['php533_deps'] = ["libgcrypt-devel"] else set['cubrid']['php_ext_conf_dir'] = '/etc/php5/conf.d' set['cubrid']['php533_deps'] = [] end # the full path of pdo_cubrid.ini set['cubrid']['pdo_ext_conf'] = "#{node['cubrid']['php_ext_conf_dir']}/pdo_cubrid.ini" # the directives which should be placed in pdo_cubrid.ini files; these are populate to pdo_cubrid.ini.erb template of this cookbook. set['cubrid']['pdo_directives'] = {:extension => "pdo_cubrid.so"}
module Jekyll module MatlabDoc def loadFunctionDoc(name,style='long',codify=true,folder=nil,file=nil) if @context.registers[:site].data["settings"]["mvirt"]["useLocal"] base_url = @context.registers[:site].data["settings"]["mvirt"]["localCodePath"] else base_url = @context.registers[:site].data["settings"]["mvirt"]["gitURL"] end if base_url.nil? warnstr = "no raw git url given." print warnstr return "" end if folder.nil? folder = @context.registers[:page]["folder"] end if file.nil? file = @context.registers[:page]["filename"] end if file.nil? warnstr = "file given for function #{name}" print warnstr return "" end file_url = "#{base_url}#{folder}#{file}" print ":" output = "" if codify output = "\n~~~ matlab" end append = false found = false count=0 require 'open-uri' open(file_url).each do |line| if append if line.strip.start_with?"%" l = line.strip output = "#{output}#{l}\n" count=count+1 else append=false end if count==1 and not style.eql?"long" append=false end end if line.strip.start_with?"function" and line.include?" #{name}(" #start output after function ... = name append = true if codify output = "#{output}\n" else output = "#{output}\n" end lineNum = count found=true end end if not found print "#{name} not found in #{file_url}\n" end if codify output = "#{output} ~~~\n" end return "#{output}" end end end Liquid::Template.register_filter(Jekyll::MatlabDoc)
class User < ActiveRecord::Base validates :email, :confirmation => true validates :email_confirmation, :presence => true validates :email, uniqueness: { case_sensitive: false } has_secure_password has_one :profile has_many :comments has_many :user_workouts has_many :workouts, through: :user_workouts after_create :create_profile def workouts_per_week self.workouts.where(created_at: 7.days.ago..Time.current).count end def workouts_last_two_days self.workouts.where(created_at: 2.days.ago..Time.current).count end def endurance self.workouts.where(time_domain: 15..60).count end def power self.workouts.where(time_domain: 5..14).count end end
class Gift < ApplicationRecord belongs_to :provider, class_name: 'User' belongs_to :receiver, class_name: 'User' belongs_to :meal end
class AddChampionToSeason < ActiveRecord::Migration[5.2] def change add_column :seasons, :champion_id, :integer, default: nil end end
$running_specs = true require './max_flower_shops_template.rb' require 'rspec' describe '#sort_intervals' do it 'sorts by right boundary' do expect(sort_intervals([[2,3], [1,2], [0,1]])).to eq([[0,1], [1,2], [2,3]]) end it 'takes the three shortest intervals' do expect(sort_intervals([[0,4], [1,4], [2,4], [3,4]])).to eq([[3,4], [2,4], [1,4]]) end end describe '#get_new_occupied_plots' do it 'updates empty plots' do expect(get_new_occupied_plots(0, [0,1], [])).to eq([1]) expect(get_new_occupied_plots(0, [0,5], [])).to eq([1,1,1,1,1]) end it "adds leading 0s when the left boundary is less than the interval's left boundary" do expect(get_new_occupied_plots(2, [4,6], [])).to eq([0,0,1,1]) end it 'updates populated plots by adding 1 to each index that is in the interval' do expect(get_new_occupied_plots(2, [2,6], [0,1,0,1])).to eq([1,2,1,2]) end it 'leaves indexes as 3 (the left boundary and plots are corrected elsewhere)' do expect(get_new_occupied_plots(2, [4,6], [0,1,2,1,0])).to eq([0,1,3,2,0]) end end describe '#get_new_left_boundary' do it 'returns itself and the plots when nothing needs to change' do expect(get_new_left_boundary(0, [0,1])).to eq([0, [0,1]]) expect(get_new_left_boundary(5, [0,2])).to eq([5, [0,2]]) end it 'resets itself and plots when one of the indexes is 3' do expect(get_new_left_boundary(0, [3])).to eq([1, []]) expect(get_new_left_boundary(5, [1,2,3])).to eq([8, []]) end it 'drops each plot before the 3' do expect(get_new_left_boundary(0, [3,2,1,0])).to eq([1, [2,1,0]]) end it 'handles leading 0s' do expect(get_new_left_boundary(0, [0,3])).to eq([2, []]) end end describe '#add_interval' do let(:initial_state) { { num_flower_shops: 0, left_boundary: 0, occupied_plots: [], } } it 'updates the num_flower_shops' do new_state = add_interval([0,1], initial_state) expect(new_state[:num_flower_shops]).to eq(1) end it 'updates the occupied plots' do new_state = add_interval([0,1], initial_state) expect(new_state[:occupied_plots]).to eq([1]) new_state2 = add_interval([0,1], new_state) expect(new_state2[:occupied_plots]).to eq([2]) new_state3 = add_interval([0,1], new_state2) expect(new_state3[:occupied_plots]).to eq([]) new_state4 = add_interval([1,5], new_state3) expect(new_state4[:occupied_plots]).to eq([1,1,1,1]) new_state5 = add_interval([3,5], new_state4) expect(new_state5[:occupied_plots]).to eq([1,1,2,2]) end it 'updates the left boundary' do new_state = add_interval([0,1], initial_state) expect(new_state[:left_boundary]).to eq(0) new_state2 = add_interval([0,1], new_state) new_state3 = add_interval([0,1], new_state2) expect(new_state3[:left_boundary]).to eq(1) end end
require 'rails_helper' RSpec.describe Issue do describe 'validate of status' do let(:regular) { User.create(login: 'test', password: '123456', name: 'Mr. Test') } let(:manager) { User.create(login: 'manager', password: '123456', name: 'Mr. Manager', role: :manager) } [:in_progress, :resolved].each do |new_status| subject { issue.update_attributes(status: new_status) } context 'when unassigned' do let(:issue) { Issue.create(title: 'test', author: regular) } it { expect(subject).to be_falsey } end context 'when assigned' do let(:issue) { Issue.create(title: 'test', author: regular, manager: manager ) } it { expect(subject).to be_truthy } end end end end
class CreateDoorCodes < ActiveRecord::Migration[6.0] def change create_table :doors_codes do |t| t.references :door, foreign_key: true, null: false t.references :code, foreign_key: true, null: false end add_index :doors_codes, [:door_id, :code_id], unique: true end end
class API::Cards < API::Base desc 'search program by tags' get '/programs/search' do payload = request.GET tags_query = payload["tags"] end desc "list all program from a certain channel" get '/programs' do @result = ProgramLib::programListV2Mobile end desc 'get program details' get '/programs/:program_id' do program_id = params[:program_id] @result = ProgramLib::programDetailsV2Mobile(program_id) end desc "list all liked programs" post '/programs' do mivo_id = request.POST["mivo_id"] mivo_secret = request.POST["mivo_secret"] @result = ProgramLib::likedProgramsV2Mobile(mivo_id, mivo_secret) end desc "tags a program" put '/programs/:program_id/tags' do program_id = params[:program_id] payload = request.POST mivo_id = payload["mivo_id"] mivo_secret = payload["mivo_secret"] tags = payload["tags"] UserLib::tagProgram(mivo_id, mivo_secret, program_id, tags) end desc "like a program" post '/programs/:program_id/like' do mivo_id = request.POST["mivo_id"] mivo_secret = request.POST["mivo_secret"] program_id = params[:program_id] @result = UserLib::likeProgram(mivo_id, mivo_secret, program_id) end desc "unlike a program" post "/programs/:program_id/unlike" do mivo_id = request.POST["mivo_id"] mivo_secret = request.POST["mivo_secret"] program_id = params[:program_id] @result = UserLib::unlikeProgram(mivo_id, mivo_secret, program_id) end end
require 'barometer' require 'date' class Fixnum def days # returns number that represents seconds in a day * N days self * 86400 end end # Define method for passing location and displaying weather def weather_forecast(usr_location) tomorrow = Time.now.strftime('%d').to_i + 1 barometer = Barometer.new(usr_location) weather = barometer.measure weather.forecast.each do |forecast| what_day = forecast.starts_at.day if what_day == tomorrow day_name = "Tomorrow" else day_name = forecast.starts_at.strftime('%A') end puts "#{day_name} forecast: #{forecast.icon} with a low of #{forecast.low.f.to_s} and a high of: #{forecast.high.f.to_s}" end end # Retrieve Location print "Please enter your location [Zip code]: " location = gets.chomp.to_s weather_forecast(location)
require 'spec_helper' describe CampaignMailerHelper do before :each do include CampaignMailerHelper end it '' do end describe '#message' do it 'should return the path to a partial found in the messages folder' do partial_path = message 'test' partial_path.should == 'campaign_mailer/messages/test_message' end end describe '#table' do it 'should return the path to a partial found in the tables folder' do partial_path = table 'test' partial_path.should == 'campaign_mailer/tables/test_table' end end describe '#footer' do it 'should return the path to a partial found in the footers folder' do partial_path = footer 'test' partial_path.should == 'campaign_mailer/footers/test_footer' end end end
VAGRANT_BOX = 'bobfraser1/alpine316' VM_HOSTNAME = 'router' VM_NETWORK = 'vboxnet1' VM_IP = '192.168.60.2' VM_MEMORY = '2048' VM_CPUS = '2' PUBLIC_NET = 'eth0' PRIVATE_NET = 'eth1' INTERFACE = 'eth1' DOMAIN = 'example.com' DHCP_RANGE = '192.168.60.100,192.168.60.254,12h' Vagrant.configure('2') do |config| config.vm.box = VAGRANT_BOX config.vm.hostname = VM_HOSTNAME config.vm.network 'private_network', name: VM_NETWORK, ip: VM_IP config.vm.synced_folder '.', '/vagrant', disabled: true config.vm.provision 'shell', path: 'scripts/iptables.sh', env: { 'PUBLIC_NET' => PUBLIC_NET, 'PRIVATE_NET' => PRIVATE_NET } config.vm.provision 'shell', path: 'scripts/dnsmasq.sh', env: { 'INTERFACE' => INTERFACE, 'DOMAIN' => DOMAIN, 'DHCP_RANGE' => DHCP_RANGE } config.vm.provision 'shell', path: 'scripts/dhcp-hosts.sh' config.vm.provider 'virtualbox' do |vm| vm.name = VM_HOSTNAME vm.memory = VM_MEMORY vm.cpus = VM_CPUS end end
require 'factory_bot' def random_number number = Random.new number.rand(1..5) end FactoryBot.define do factory :user do sequence(:email) {|n| "user#{n}@example.com" } sequence(:username) {|n| "username#{n}" } password { "password" } password_confirmation { "password" } role { "member" } end factory :meme do user { FactoryBot.create(:user) } title { Faker::Book.title } imageUrl { "https://t2.rbxcdn.com/d7128e13ae4f5209537769b757512c23" } description { Faker::Hipster.sentence(3, false, 2) } end factory :review do user { FactoryBot.create(:user) } meme { FactoryBot.create(:meme) } rating { random_number } comment { Faker::Hipster.paragraph(3, false, 2) } end end
class Interventi < ActiveRecord::Base #belongs_to :clienti, :foreign_key => "cliente_id" belongs_to :clienti has_many :comunicazionis, :dependent => :destroy validates :data, presence: true validates :intervento, presence: true, length: {minimum: 5 } validates :durata, presence: true end
################################################## # Generated by phansible.com ################################################## Vagrant.require_version ">= 1.5" # Check to determine whether we're on a windows or linux/os-x host, # later on we use this to launch ansible in the supported way # source: https://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby def which(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = File.join(path, "#{cmd}#{ext}") return exe if File.executable? exe } end return nil end ansible_dir = 'ansible' galaxy_roles_file = "#{ansible_dir}/galaxy_roles.yml" def require_plugin(name) unless Vagrant.has_plugin?(name) puts <<-EOT.strip #{name} plugin required. Please run: "vagrant plugin install #{name}" EOT exit end end require_plugin 'vagrant-hostmanager' require_plugin 'vagrant-host-shell' Vagrant.configure("2") do |config| config.vm.provider :virtualbox do |v| v.name = "symfony" v.customize [ "modifyvm", :id, "--name", "symfony", "--memory", 1024, "--natdnshostresolver1", "on", "--cpus", 1, ] end config.vm.box = "ubuntu/trusty64" config.hostmanager.ip_resolver = proc do |vm, resolving_vm| if hostname = (vm.ssh_info && vm.ssh_info[:host]) `vagrant ssh -c "hostname -I"`.split()[1] end end config.vm.network :private_network, type: "dhcp" config.ssh.forward_agent = true ############################################################# # Ansible provisioning (you need to have ansible installed) ############################################################# if which('ansible-playbook') # Handle ansible galaxy roles if File.exist?("#{galaxy_roles_file}") config.vm.provision :host_shell do |host_shell| host_shell.inline = "ansible-galaxy install -r #{galaxy_roles_file} -p #{ansible_dir}/roles/galaxy -f" end end config.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/playbook.yml" ansible.limit = 'symfony' ansible.groups = {"vagrant" => ["symfony"] } end else config.vm.provision :shell, path: "ansible/windows.sh", args: ["symfony.vagrant"] end config.vm.synced_folder( ".", "/vagrant", type: "nfs", nfs_udp: true, nfs_version: 3 ) config.hostmanager.enabled = true config.hostmanager.manage_host = true config.hostmanager.ignore_private_ip = false config.hostmanager.include_offline = true config.vm.define 'symfony' do |node| node.vm.hostname = 'symfony.vagrant' node.hostmanager.aliases = %w(symfony.vagrant) end end
class AffiliateProgramAddReviewWritingProgram < ActiveRecord::Migration def self.up add_column :affiliate_programs, :review_writing_program, :boolean, :default => true, :null => false end def self.down remove_column :affiliate_programs, :review_writing_program end end
require 'rails_helper' RSpec.describe "injurylocations/edit", type: :view do before(:each) do @injurylocation = assign(:injurylocation, Injurylocation.create!( name: "MyString", description: "MyString" )) end it "renders the edit injurylocation form" do render assert_select "form[action=?][method=?]", injurylocation_path(@injurylocation), "post" do assert_select "input[name=?]", "injurylocation[name]" assert_select "input[name=?]", "injurylocation[description]" end end end
class CarMake < ApplicationRecord belongs_to :car_post belongs_to :make_model end
# Encoding: UTF-8 # # Cookbook Name:: steam # Library:: resource_steam_app_windows # # Copyright 2015-2016, Jonathan Hartman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require_relative 'resource_steam_app' class Chef class Resource # A custom resource for Steam for Windows # # @author Jonathan Hartman <j@p4nt5.com> class SteamAppWindows < SteamApp URL ||= 'https://steamcdn-a.akamaihd.net/client/installer/SteamSetup.exe' .freeze PATH ||= ::File.expand_path('/Program Files (x86)/Steam').freeze provides :steam_app, platform_family: 'windows' # # Download and install the Steam Windows package. # action :install do download_path = ::File.join(Chef::Config[:file_cache_path], ::File.basename(URL)) remote_file download_path do source URL action :create only_if { !::File.exist?(PATH) } end windows_package 'Steam' do source download_path installer_type :nsis action :install end end # # Use a windows_package resource to uninstall Steam. # action :remove do windows_package 'Steam' do action :remove end end end end end
# one.rb # concatenating first and last name strings puts "Aaron " + "Saloff"
class Project < ApplicationRecord enum status: %i[pre_sale active closed archive] end
class CreateAdditionalLinks < ActiveRecord::Migration def self.up create_table :additional_links do |t| t.string :title t.string :tag t.boolean :published t.timestamps end AdditionalLink.create :title => "Your visa support", :tag => "http://blog.chavanga.com/2010/04/your-visa-support.html", :published => true end def self.down drop_table :additional_links end end
require 'rails_helper' RSpec.describe "Api::Books", type: :request do describe "GET /api/books" do it "should list all books" do FactoryBot.create(:book) FactoryBot.create(:book, title: 'Book 2') get api_books_path expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json.length).to eq 2 expect(json[0]["title"]).to eq('First book') end end describe "GET /api/books/:id" do before(:each) do @book = FactoryBot.create :book end it "should get a book by id" do get api_book_path(@book.id) expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["title"]).to eq('First book') end end describe "POST /api/books/" do before(:each) do @book = FactoryBot.build :book end it "should create a book" do post api_books_path, params: { book: { title: @book.title, author: @book.author, number_of_pages: @book.number_of_pages, review: @book.review } } expect(response).to have_http_status(201) json = JSON.parse(response.body) expect(json["title"]).to eq('First book') end end describe "PUT /api/books/:id" do before(:each) do @book = FactoryBot.create :book end it "should update a book" do put api_book_path(@book.id), params: { book: { title: 'Book updated' } } expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["title"]).to eq('Book updated') end end describe "DELETE /api/books/:id" do before(:each) do @book = FactoryBot.create :book end it "should delete a book" do delete api_book_path(@book.id) expect(response).to have_http_status(204) end end end
# frozen_string_literal: true # Add 'name' column to User class AddNameToUser < ActiveRecord::Migration[5.2] def change add_column :users, :name, :string end end
require 'rails_helper' feature 'admin signs in', %Q{ As a signed up admin I want to sign in So that I can administrate to my account } do scenario 'specify valid credentials' do admin = FactoryBot.create(:admin_user) visit new_user_session_path fill_in 'Email', with: admin.email fill_in 'Password', with: admin.password click_button 'Log in' expect(page).to have_content('Signed in successfully') end scenario 'specify invalid credentials' do visit new_user_session_path click_button 'Log in' expect(page).to have_content('Invalid Email or password') expect(page).to_not have_content('Sign Out') end end
require "test_helper" class Location::AchatsControllerTest < ActionDispatch::IntegrationTest setup do @location_achat = location_achats(:one) end test "should get index" do get location_achats_url assert_response :success end test "should get new" do get new_location_achat_url assert_response :success end test "should create location_achat" do assert_difference('Location::Achat.count') do post location_achats_url, params: { location_achat: { acceleration: @location_achat.acceleration, nom_voiture: @location_achat.nom_voiture, photo: @location_achat.photo, prix: @location_achat.prix, puissance: @location_achat.puissance, vitesse_max: @location_achat.vitesse_max } } end assert_redirected_to location_achat_url(Location::Achat.last) end test "should show location_achat" do get location_achat_url(@location_achat) assert_response :success end test "should get edit" do get edit_location_achat_url(@location_achat) assert_response :success end test "should update location_achat" do patch location_achat_url(@location_achat), params: { location_achat: { acceleration: @location_achat.acceleration, nom_voiture: @location_achat.nom_voiture, photo: @location_achat.photo, prix: @location_achat.prix, puissance: @location_achat.puissance, vitesse_max: @location_achat.vitesse_max } } assert_redirected_to location_achat_url(@location_achat) end test "should destroy location_achat" do assert_difference('Location::Achat.count', -1) do delete location_achat_url(@location_achat) end assert_redirected_to location_achats_url end end
require 'test_helper' class MaileeTemplatesControllerTest < ActionController::TestCase setup do @mailee_template = mailee_templates(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:mailee_templates) end test "should get new" do get :new assert_response :success end test "should create mailee_template" do assert_difference('MaileeTemplate.count') do post :create, :mailee_template => @mailee_template.attributes end assert_redirected_to mailee_template_path(assigns(:mailee_template)) end test "should show mailee_template" do get :show, :id => @mailee_template.to_param assert_response :success end test "should get edit" do get :edit, :id => @mailee_template.to_param assert_response :success end test "should update mailee_template" do put :update, :id => @mailee_template.to_param, :mailee_template => @mailee_template.attributes assert_redirected_to mailee_template_path(assigns(:mailee_template)) end test "should destroy mailee_template" do assert_difference('MaileeTemplate.count', -1) do delete :destroy, :id => @mailee_template.to_param end assert_redirected_to mailee_templates_path end end
module WastebitsClient class Invitation < Base attr_accessor :accepted_at, :claim_url, :company_id, :confirmation_token, :created_at, :email, :first_name, :id, :is_admin, :is_approver, :last_name, :updated_at, :user_id alias :is_admin? :is_admin alias :is_approver? :is_approver def claim(token) self.class.patch(self.access_token, "/invitations/#{@id}", :body => { :token => token }) end def company unless @company @company = Company.get_by_id(self.access_token, @company_id) end end def delete self.class.delete(self.access_token, "/invitations/#{@id}", :body => {}) end def resend self.class.post(self.access_token, "/invitations/#{@id}/resend", :body => { :claim_url => self.claim_url }) end def save self.class.post(self.access_token, '/invitations', :body => { :claim_url => self.claim_url, :company_id => self.company_id, :email => self.email, :is_admin => self.is_admin, :is_approver => self.is_approver, :first_name => self.first_name, :last_name => self.last_name }) end def user unless @user @user = User.get_by_id(self.access_token, @user_id) end end def self.all(access_token, options={}) options = options.with_indifferent_access query = { :page => 1, :per_page => PER_PAGE }.with_indifferent_access query.merge!(options) get(access_token, '/invitations', { :query => query }) end def self.for_token(access_token, token) get(access_token, "/invitations/#{token}") end def self.for_company(access_token, company_id) get(access_token, "/companies/#{company_id.to_i}/invitations") end end end
class CreateRequesters < ActiveRecord::Migration[5.2] def change unless table_exists? Requester.table_name create_table Requester.table_name do |t| t.string :name, comment: 'Identifica o nome do funcionario' t.string :email, comment: 'Identifica o email do funcionario' t.string :phone, comment: 'Identifica o telefone do funcionario' t.numeric :requester_id, comment: 'Identifica o id do zendesk funcionario' t.integer :status, default: 1, comment: 'Identifica se ativo ou inativo o funcionario 0-Inativo 1-Ativo' t.timestamps end end end end
# == Schema Information # # Table name: student_applications # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # applicant_id :integer # semester_id :integer # why_join :text # resume_file_name :string(255) # resume_content_type :string(255) # resume_file_size :integer # resume_updated_at :datetime # phone :string(255) # year :string(255) # class StudentApplication < ActiveRecord::Base belongs_to :applicant belongs_to :semester has_attached_file :resume validates_attachment :resume, content_type: { content_type: "application/pdf" }, size: { in: 0..1.megabytes } validates_attachment_presence :resume has_one :final_decision, as: :decisionable validates :applicant_id, presence: true validates :semester_id, presence: true after_create :create_final_decision validates :why_join, presence: true validates :phone, presence: true validates :year, presence: true end
require 'wsdl_mapper/runtime/simpler_inspect' module WsdlMapper module Runtime class Port include SimplerInspect attr_reader :_soap_address, :_operations # @!attribute _operations # @return [Array<WsdlMapper::Runtime::Operation>] All operations contained in this port # @!attribute _soap_address # @return [String] URL of the SOAP service # @param [WsdlMapper::Runtime::Api] api The API this port belongs to # @param [WsdlMapper::Runtime::Service] service The service this port belongs to def initialize(api, service) @_api = api @_service = service @_soap_address = nil @_operations = [] end # Force preloading of requires for all contained operations def _load_requires @_operations.each(&:load_requires) end end end end
module Moonr class VariableStat < ASTElem def append another @list ||= [] @list << another self end def jseval(env) idexpr = IdExpr.new :id => id lhr = idexpr.jseval env if initialiser rhs = initialiser.jseval env value = rhs.get_value lhr.put_value value end @list && @list.inject(lhr) do |acc, stat| stat.jseval env end Result.new :type => :normal, :value => :empty, :target => :empty end end end
# encoding: utf-8 control "V-52267" do title "The DBMS must use organization-defined replay-resistant authentication mechanisms for network access to non-privileged accounts." desc "An authentication process resists replay attacks if it is impractical to achieve a successful authentication by recording and replaying a previous authentication message. Techniques used to address this include protocols using nonces (e.g., numbers generated for a specific one-time use) or challenges (e.g., TLS, WS_Security), and time synchronous or challenge-response one-time authenticators. Replay attacks, if successfully used against a database account, could result in access to database data. A successful replay attack against a non-privileged database account could result in a compromise of data stored on the database. Oracle Database enables you to encrypt data that is sent over a network. There is no distinction between privileged and non-privileged accounts. Encryption of network data provides data privacy so that unauthorized parties are not able to view plain-text data as it passes over the network. Oracle Database also provides protection against two forms of active attacks. Data modification attack: An unauthorized party intercepting data in transit, altering it, and retransmitting it is a data modification attack. For example, intercepting a $100 bank deposit, changing the amount to $10,000, and retransmitting the higher amount is a data modification attack. Replay attack: Repetitively retransmitting an entire set of valid data is a replay attack, such as intercepting a $100 bank withdrawal and retransmitting it ten times, thereby receiving $1,000. AES and Triple-DES operate in outer Cipher Block Chaining (CBC) mode. The DES algorithm uses a 56-bit key length. false" impact 0.5 tag "check": "Review DBMS settings to determine whether organization-defined replay-resistant authentication mechanisms for network access to non-privileged accounts exist. If these mechanisms do not exist, this is a finding. To check that network encryption is enabled and using site-specified encryption procedures, look in SQLNET.ORA, located at $ORACLE_HOME/network/admin/sqlnet.ora. (Note: This assumes that a single sqlnet.ora file, in the default location, is in use. Please see the supplemental file "Non-default sqlnet.ora configurations.pdf" for how to find multiple and/or differently located sqlnet.ora files.) If encryption is set, entries like the following will be present: SQLNET.CRYPTO_CHECKSUM_TYPES_SERVER= (SHA-1) SQLNET.ENCRYPTION_TYPES_SERVER= (AES256) SQLNET.CRYPTO_CHECKSUM_SERVER = required SQLNET.CRYPTO_CHECKSUM_TYPES_CLIENT= (SHA-1) SQLNET.ENCRYPTION_TYPES_CLIENT= (AES256) SQLNET.CRYPTO_CHECKSUM_CLIENT = requested (The values assigned to the parameters may be different, the combination of parameters may be different, and not all of the example parameters will necessarily exist in the file.)" tag "fix": "Configure DBMS, OS and/or enterprise-level authentication/access mechanism to require organization-defined replay-resistant authentication mechanisms for network access to non-privileged accounts. If appropriate, apply Oracle Data Network Encryption to protect against replay mechanisms." # Write Check Logic Here end
require "rails_helper" describe PickingTime do let(:monday) { PickingTime.create!(enabled: true, weekday: "monday", hour: "14:00", shop_id: 1) } let(:tuesday) { PickingTime.create!(enabled: true, weekday: "tuesday", hour: "10:00", shop_id: 1) } let(:wednesday) { PickingTime.create!(enabled: true, weekday: "wednesday", hour: "10:00", shop_id: 1) } let(:thursday) { PickingTime.create!(enabled: true, weekday: "thursday", hour: "10:00", shop_id: 1) } let(:friday) { PickingTime.create!(enabled: true, weekday: "friday", hour: "10:00", shop_id: 1) } let(:saturday) { PickingTime.create!(enabled: true, weekday: "saturday", hour: "18:00", shop_id: 1) } let(:sunday) { PickingTime.create!(enabled: true, weekday: "sunday", hour: "18:00", shop_id: 1) } describe "#time" do it "returns the related time" do Timecop.travel(2013, 8, 16, 1, 45, 0) do expect(monday.time).to eq(Time.new(2013, 8, 19, 14, 0, 0)) expect(tuesday.time).to eq(Time.new(2013, 8, 20, 10, 0, 0)) expect(wednesday.time).to eq(Time.new(2013, 8, 21, 10, 0, 0)) expect(thursday.time).to eq(Time.new(2013, 8, 22, 10, 0, 0)) expect(friday.time).to eq(Time.new(2013, 8, 16, 10, 0, 0)) expect(saturday.time).to eq(Time.new(2013, 8, 17, 18, 0, 0)) expect(sunday.time).to eq(Time.new(2013, 8, 18, 18, 0, 0)) end end end describe "#next_time" do it "returns monday at monday before picking time" do Timecop.travel(2013, 8, 12, 10, 20, 0) do setup_picking_schedule expect(described_class.next_time(1).time).to eq(Time.new(2013, 8, 12, 14, 0, 0)) end end it "returns tuesday at monday after picking time" do Timecop.travel(2013, 8, 12, 14, 20, 0) do setup_picking_schedule expect(described_class.next_time(1).time).to eq(Time.new(2013, 8, 13, 10, 0, 0)) end end it "returns friday at friday before picking time" do Timecop.travel(2013, 8, 16, 1, 45, 0) do setup_picking_schedule expect(described_class.next_time(1).time).to eq(Time.new(2013, 8, 16, 10, 0, 0)) end end end describe "#+" do context "before picking time" do around do |example| Timecop.travel(2013, 8, 12, 1, 45, 0) do example.run end end before { setup_picking_schedule } context "on business days" do it "returns 0 for 0" do expect(monday + 0).to eq(0) end it "returns 1 for 1" do expect(monday + 1).to eq(1) end it "returns 2 for 2" do expect(monday + 2).to eq(2) end it "returns 3 for 3" do expect(monday + 3).to eq(3) end it "returns 4 for 4" do expect(monday + 4).to eq(4) end end context "on weekends" do it "returns 5 for 5" do expect(monday + 5).to eq(5) end it "returns 6 for 6" do expect(monday + 6).to eq(6) end end end context "after picking time" do around do |example| Timecop.travel(2013, 8, 12, 14, 45, 0) do example.run end end before { setup_picking_schedule } context "on business days" do it "returns 1 for 0" do expect(monday + 0).to eq(1) end it "returns 2 for 1" do expect(monday + 1).to eq(2) end it "returns 3 for 2" do expect(monday + 2).to eq(3) end it "returns 4 for 3" do expect(monday + 3).to eq(4) end end context "on weekends" do it "returns 5 for 4" do expect(monday + 4).to eq(5) end it "returns 6 for 5" do expect(monday + 5).to eq(6) end it "returns 7 for 6" do expect(monday + 6).to eq(7) end end end end def setup_picking_schedule monday tuesday wednesday thursday friday saturday sunday end end
class Favourite < ApplicationRecord belongs_to :user belongs_to :myrecipe validates :myrecipe, presence: true, uniqueness: {scope: :user} end
class Partner < ActiveRecord::Base include PartnerRepository attr_accessible :name_ru, :description_ru, :logo has_many :partner_products validates :name_ru, presence: true state_machine initial: :active do before_transition any => :deleted do |obj, transition| obj.deleted_at = Time.current obj.order_at = 0 end before_transition :deleted => any do |obj, transition| obj.deleted_at = nil end state :active state :deleted event :restore do transition :deleted => :active end event :mark_as_deleted do transition :active => :deleted end end mount_uploader :logo, PartnerLogoUploader end
module Parser module Cdl module ToDsl class HasOne < Methods def method_type :has_one end end end end end
class BtcUtils::Models::TxOut attr_reader :parent_tx def initialize parent_tx, raw @parent_tx = parent_tx @raw = raw end def amount BtcUtils::Convert.btc_to_satoshi @raw['value'] end def idx @raw['n'] end def addresses @raw['scriptPubKey']['addresses'] end def spent? resp = BtcUtils.client.tx_out @parent_tx.id, idx !resp end end
class Board attr_reader :max_height def self.build_stacks(stacks) Array.new(stacks) {Array.new()} end def initialize(stacks, height) raise "rows and cols must be >= 4" if stacks < 4 || height < 4 @max_height = height @stacks = Board.build_stacks(stacks) end def add(token, stack_index) if @stacks[stack_index].length < @max_height @stacks[stack_index] << token true else false end end def vertical_winner?(token) # How can vertical wins happen? (0...@stacks.length).each do |stack| count = 0 (0...@max_height).each do |i| if @stacks[stack][i] == token count += 1 end end return true if count == @max_height end false end def horizontal_winner?(token) (0...@max_height).any? { |i| @stacks.all? { |stack| token == stack[i] } } # Why does this not work? # How can horizontal wins happen? # Paste from vertical_winner then work from there end def winner?(token) horizontal_winner?(token) || vertical_winner?(token) end # This Board#print method is given for free and does not need to be modified # It is used to make your game playable. def print @stacks.each { |stack| p stack } end end
class AddDefaultToRequestStatus < ActiveRecord::Migration[6.0] def change change_column_default :requests, :request_status, "opened" end end
require_relative 'appointments' class Time attr_accessor :year, :month, :day, :hour, :minute def initialize(y, mo, d, h, mi = 0) @year = y @month = mo @day = d @hour = h @minute = mi end end
class AddDebitUriAndCreditUriToOrder < ActiveRecord::Migration def change add_column :orders, :debit_uri, :string add_column :orders, :credit_uri, :string end end
module Import class NoRelation < Resource attr_accessible :controller_logger, :input, :email, :resource_class attr_accessor :resource_class protected def parse_resource(resource) resource.gsub('*', '').strip end def append_existing_resources_criteria(resource) @existing_resources_criteria << "(#{resource_class.table_name}.name = ?)" @existing_resources_criteria_values << resource end def import_resources log "#{parsed_resources_missing.length} of #{@parsed_resources.length} new #{resource_class.name.humanize.pluralize}." new_resources_data = [] parsed_resources_missing.each do |resource| new_resources_data << new_record(resource) end log "Creating #{new_resources_data.length} new #{resource_class.name.humanize.pluralize}." unless new_resources_data.empty? resource_class.import(columns, new_resources_data, :validate => false) end end def parsed_resources_missing @parsed_resources_missing ||= @parsed_resources.select{|r| !collection(false).map(&:second).include?(r) } end def new_record(resource) [resource] end def columns [:name] end end end
require "test_helper" require "rbs/test" require "logger" return unless Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0') class RBS::Test::RuntimeTestTest < Minitest::Test include TestHelper def test_runtime_success assert_test_success assert_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => '30'}) assert_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => '100'}) assert_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => 'ALL'}) end def test_runtime_test_error_with_invalid_sample_size string_err_msg = refute_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => 'yes'}) assert_match(/E, .+ ERROR -- rbs: Sample size should be a positive integer: `.+`\n/, string_err_msg) zero_err_msg = refute_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => '0'}) assert_match(/E, .+ ERROR -- rbs: Sample size should be a positive integer: `.+`\n/, zero_err_msg) negative_err_msg = refute_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => '-1'}) assert_match(/E, .+ ERROR -- rbs: Sample size should be a positive integer: `.+`\n/, negative_err_msg) end def run_runtime_test(other_env:) SignatureManager.new(system_builtin: true) do |manager| manager.files[Pathname("foo.rbs")] = <<EOF class Hello attr_reader x: Integer attr_reader y: Integer def initialize: (x: Integer, y: Integer) -> void def move: (?x: Integer, ?y: Integer) -> void end EOF manager.build do |env, path| (path + "sample.rb").write(<<RUBY) class Hello attr_reader :x, :y def initialize(x:, y:) @x = x @y = y end def move(x: 0, y: 0) @x += x @y += y end end hello = Hello.new(x: 0, y: 10) RUBY env = { "BUNDLE_GEMFILE" => File.join(__dir__, "../../../Gemfile"), "RBS_TEST_TARGET" => "::Hello", "RBS_TEST_OPT" => "-I./foo.rbs" } _out, err, status = Open3.capture3(env.merge(other_env), "ruby", "-rbundler/setup", "-rrbs/test/setup", "sample.rb", chdir: path.to_s) return [err, status] end end end def assert_test_success(other_env: {}) result = run_runtime_test(other_env: other_env) assert_operator result[1], :success? end def refute_test_success(other_env: {}) err, status = run_runtime_test(other_env: other_env) refute_operator status, :success? err end end
class GroupsController < ApplicationController before_filter :require_user, only: [:index, :new, :create, :invited, :join] def show @group = Group.find(params[:id]) authorize! :manage, @group respond_to do |format| format.html # show.html.erb format.json { render json: @group } end end def index @groups = current_user.groups respond_to do |format| format.html # index.html.erb format.json { render json: @groups } end end def new @group = Group.new end def create @group = Group.new(params[:group]) if @group.save @group.users_groups.create(:user_id => current_user.id) flash[:notice] = "Your group has been created." redirect_to group_path(@group) else flash[:notice] = "There was a problem creating your group." render :action => :new end end def edit @group = Group.find(params[:id]) authorize! :manage, @group end def update @group = Group.find(params[:id]) authorize! :manage, @group if @group.update_attributes(params[:group]) flash[:notice] = "Group updated!" redirect_to group_path else render :action => :edit end end # TODO: Make the invitation sign up more seamless def invited @invite = GroupInvitation.find_by_token(params[:token]) @group = @invite.group @members = @group.users if @members.include?(current_user) flash[:notice] = "You are already a part of #{@group.name}." redirect_to group_path(@group) else respond_to do |format| format.html # join.html.erb end end end def join # FIXME: This isn't very DRY @invite = GroupInvitation.find_by_token(params[:token]) @group = @invite.group @members = @group.users if @members.include?(current_user) flash[:notice] = "You are already a part of #{@group.name}." else flash[:notice] = "You have joined #{@group.name}" @group.users_groups.create(:user_id => current_user.id) end redirect_to group_path(@group) # TODO: Delete the invite? Mark for deletion? end def leave @group = Group.find(params[:id]) authorize! :manage, @group @user_group = UsersGroups.find_by_user_id_and_group_id(current_user.id, @group.id) @user_group.destroy redirect_to root_path end end
require 'pry' class Printer include Sorter def print_all output_1; output_2; output_3 end def output_1 puts "", "Output 1:" contacts = sorted_by_ascending_gender_and_last_name contacts.each do |contact| puts "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end; puts"" end def output_2 puts "Output 2:" contacts = sorted_by_ascending_birthdate_and_last_name contacts.each do |contact| puts "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end; puts"" end def output_3 puts "Output 3:" contacts = sorted_by_last_name_descending contacts.each do |contact| puts "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end; puts"" end def email_output_1 contacts = sorted_by_ascending_gender_and_last_name contacts.map do |contact| "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end end def email_output_2 contacts = sorted_by_ascending_birthdate_and_last_name contacts.map do |contact| "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end end def email_output_3 contacts = sorted_by_last_name_descending contacts.map do |contact| "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_date.strftime("%-m/%-d/%Y")} #{contact.favorite_color}" end end def email_all [email_output_1, email_output_2, email_output_3] end end
# encoding: UTF-8 module Decider class DeciderError < StandardError end class NotImplementedError < DeciderError def initialize(klass, method) super("#{klass.name} expects ##{method.to_s} to be defined by a subclass") end end end
require 'test_helper' describe DeliveryTypesController do setup do @shop = shops(:one) @delivery_type = delivery_types(:one) end test "should get index" do get :index, shop_id: @shop assert_response :success end test "should get new" do get :new, shop_id: @shop assert_response :success end test "should create delivery_type" do assert_difference('DeliveryType.count') do post :create, delivery_type: { name: 'Tipo de envio 2', shop: @shop}, shop_id: @shop end assert_redirected_to shop_delivery_types_path(@shop) end test "should get edit" do get :edit, shop_id: @shop, id: @delivery_type assert_response :success end end
module Bliss class Constraint attr_accessor :depth, :possible_values attr_reader :setting, :state def initialize(depth, setting, params={}) @depth = depth @setting = setting @possible_values = params[:possible_values].collect(&:to_s) if params.has_key?(:possible_values) @state = :not_checked end def tag_names @depth.split('/').last.gsub('(', '').gsub(')', '').split('|') end # TODO should exist another method passed! for tag_name_required ? def run!(hash=nil) @state = :not_checked #@field.each do |field| #if @state == :passed # break #end case @setting when :tag_name_required, :tag_name_suggested content = nil if hash #puts "#{@depth.inspect} - required: #{required.inspect}" found = false self.tag_names.each do |key| if hash.keys.include?(key) found = true break end end if found @state = :passed else if @setting == :tag_name_required #puts "hash: #{hash.inspect}" #puts "self.tag_names: #{self.tag_names.inspect}" @state = :not_passed end end else @state = :passed end when :content_values if hash found = false self.tag_names.each do |key| content = hash[key] #puts content #puts @possible_values.inspect if @possible_values.include?(content.downcase) found = true break end end @state = (found ? :passed : :not_passed) end #when :not_blank # if hash.has_key?(field) and !hash[field].to_s.empty? # @state = :passed # else # @state = :not_passed # end end #end @state end def ended! case @setting when :tag_name_required, :content_values if @state == :not_checked @state = :not_passed end end end def detail #self.ended! # TODO esto es una chota de codigo groncho! returned = case @state when :not_passed case @setting when :tag_name_required [@depth, "missing"] when :content_values [@depth, "invalid"] #when :not_blank # [@field.join(" or "), "blank"] #when :possible_values # [@field.join(" or "), "invalid"] end when :passed case @setting when :tag_name_required, :tag_name_suggested [@depth, "exists"] when :content_values [@depth, "valid"] end when :not_checked case @setting when :tag_name_suggested [@depth, "suggested"] end end returned end def reset! @state = :not_checked end # Builds a collection of constraints that represent the given settings # # @param [String] depth # The tag depth on which the given constraints will work # # @param [Hash] settings # # @return [Array<Bliss::Constraint>] that represents the given settings # # @example # Bliss::Constraint.build_from_settings(["root", "child"], {"tag_name_required" => false}) # def self.build_from_settings(depth, settings) constraints = [] depth_name = Bliss::Constraint.depth_name_from_depth(depth, settings["tag_name_values"]) settings.each_pair { |setting, value| case setting when "tag_name_required" if value == true constraints.push(Bliss::Constraint.new(depth_name, :tag_name_required)) else constraints.push(Bliss::Constraint.new(depth_name, :tag_name_suggested)) end when "content_values" constraints.push(Bliss::Constraint.new(depth_name, :content_values, {:possible_values => value})) end } constraints end def self.depth_name_from_depth(depth, tag_name_values) depth_name = nil if not tag_name_values depth_name ||= depth.join('/') else # TODO esto funciona solo en el ultimo step del depth :/ # es decir, devolveria: root/(ad|item) # pero nunca podria devolver: (root|base)/(ad|item) # # una solucion seria la busqueda de bifurcaciones en las anteriores constraints para armar un depth_name completo depth_name = depth[0..-2].join('/') depth_name << "/" if depth_name.size > 0 depth_name << "(#{tag_name_values.join('|')})" end # TODO Analyze creating a Depth model for handling of path/depth/tree during constraint creation # depth # {"root" => {"ad" => {}}} # path => "root/(ad|item)" # depth => 2 # tree => {"root" => {["ad", "item"] => nil}} # tree.recurse(true) # return depth_name end end end
class AddStatusToPubSubs < ActiveRecord::Migration def change add_column :pub_subs, :status, :string end end
require 'test_helper' class CategoryTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end test "sorts are stable" do # e is the expected result set and should be created in the # order we expect the array to arrive in after sorting e = [] e << r1 = Category.create(:name => "Apple") e << r1_1 = r1.children.create(:name => "fritter") e << r2 = Category.create(:name => "apple") e << r2_1 = r2.children.create(:name => "Fritter") e << r2_1_1 = r2_1.children.create(:name => "with sauce") e << r2_2 = r2.children.create(:name => "fritter") e << r2_2_1 = r2_2.children.create(:name => "with sauce") e << r2_2_1_1 = r2_2_1.children.create(:name => "and fries") e << r3 = Category.create(:name => "Banana") e << r4 = Category.create(:name => "Chocolate") e << r4_1 = r4.children.create(:name => "fudge") e << r4_1_1 = r4_1.children.create(:name => "sundae") assert_equal e, e.shuffle.sort end end # == Schema Information # # Table name: categories # # id :integer primary key # name :string(255) # parent_id :integer # created_at :timestamp # updated_at :timestamp #
class CreateSendEmailMessages < ActiveRecord::Migration def change create_table :sent_email_messages do |t| t.string :subject t.text :to t.text :body t.string :status t.integer :user_id t.timestamps end end end