text
stringlengths
10
2.61M
require 'spec_helper' module Alf describe Database, '.new' do let(:adapter){ Adapter.new(nil) } after do expect(subject.adapter).to be_kind_of(Adapter) end context 'on a single adapter' do subject{ Database.new(adapter) } it 'uses the specified adapter' do expect(subject.adapter).to be(adapter) end it 'uses default options' do expect(subject.schema_cache?).to be_truthy end end context 'on an adapter to be coerced' do subject{ Database.new(Path.dir) } it 'coerces the adapter' do expect(subject.adapter).to be_kind_of(Adapter::Folder) end it 'uses default options' do expect(subject.schema_cache?).to be_truthy end end context 'when passing options' do subject{ Database.new(adapter, schema_cache: false) } it 'set the options correctly' do expect(subject.schema_cache?).to be_falsey end end context 'when a block is given' do subject{ Database.new(adapter){|d| @seen = d } } it 'yields the block' do expect(subject).to be_kind_of(Database) expect(@seen).to be_kind_of(Database::Options) end end end end
require 'my_service_name/log' require 'dry-container' module MyServiceName extend self def dependencies(container: Dry::Container.new, eagerly_initialize: true) # https://github.com/dry-rb/dry-container # require 'my_dependency_here' require 'my_service_name/interactors/add_six' require 'my_service_name/interactors/my_interactor' require 'my_service_name/repositories/handoff_to_legacy_request_repository' # When to use memoize? # Memoize should be used when registering thread-safe instances, so they # can be (and will be) reused by all threads. This means that you # **MUST NOT** add non-thread-safe instances as memoized instances, or there # will be fireworks. # # When instances have non-thread-safe internal state, we register instead # factory classes, which can be used to generate instances that will be # private to their creator. # register containers here container.register(:env) { ENV } container.register(:add_six, memoize: true) { Interactors::AddSix.new(container) } container.register(:my_interactor, memoize: true) { Interactors::MyInteractor.new } container.register(:handoff_to_legacy_request_repository, memoize: true) { Repository::HandoffToLegacyRequestRepository.new } eagerly_initialize(container) if eagerly_initialize container end def eagerly_initialize(container) container.each_key do |dependency| container.resolve(dependency) end end end
class VinNumbersApi < Grape::API params do requires :vin, type: String, desc: 'the vin number' end route_param :vin do desc 'Decode an vin_number' post do vin_number = VinNumber.find_or_create_by_vin_number(permitted_params[:vin]) represent vin_number, with: VinNumberRepresenter end end end
require 'spec_helper' def login(user) OmniAuth.config.mock_auth[:identity] = OmniAuth::AuthHash.new({ provider: 'identity', uid: user.id }) post '/auth/identity/callback', screen_name: user.screen_name, password: 'password1' end describe 'Expenses' do let(:user) { create(:user) } let(:other_user) { create(:user) } before { login(user) } describe 'GET /expenses' do let!(:expenses) { create_list(:expense, 3, user: user) } let!(:other_user_expense) { create(:expense, user: other_user) } context 'html' do let(:path) { '/expenses' } before { get path } it '支出一覧画面を表示する' do expect(response).to be_success end end context 'json' do let(:path) { '/expenses.json' } before { xhr :get, path} it '支出一覧を取得する' do expected_amounts = expenses.map(&:amount) actual_amounts = json['expenses'].map { |e| e['amount'] } expect(actual_amounts).to match_array(expected_amounts) end end end describe 'GET /expenses/:id' do let(:path) { "/expenses/#{expense.id}" } before { xhr :get, path } context '自分の支出情報' do let(:expense) { create(:expense, user: user) } it '取得できる' do actual_expense = json['expense'] expect(actual_expense['id'] ).to eq(expense.id) expect(actual_expense['amount']).to eq(expense.amount) expect(actual_expense['accrued_on']).to eq(expense.accrued_on.to_s) expect(actual_expense['url'] ).to eq(expense_url(expense)) end end context '他のユーザの支出情報' do let(:expense) { create(:expense, user: other_user) } it '取得できない' do expect(response).to redirect_to('/404.html') end end end describe 'POST /expenses' do let(:path) { '/expenses' } before { post path, params } context 'パラメータが正しいとき' do let(:params) { { expense: attributes_for(:expense, amount: 300) } } it '作成に成功し、showにリダイレクトする' do created_expense = Expense.last expect(created_expense.amount).to eq(params[:expense][:amount]) expect(response).to redirect_to(action: :show, id: created_expense.id) end end context 'パラメータの支出金額がnilのとき' do let(:params) { { expense: attributes_for(:expense, amount: nil) } } it 'エラー情報を含んだjsonを取得する' do expect(json['errors']).to eq(["Amount can't be blank"]) end end end describe 'PUT /expenses/:id' do let!(:expense) { create(:expense, user: user) } let(:path) { "/expenses/#{expense.id}" } before { put path, params } context 'パラメータが正しいとき' do let(:params) { { expense: attributes_for(:expense, amount: 300) } } it '更新に成功し、showにリダイレクトする' do updated_expense = Expense.find(expense.id) expect(updated_expense.amount).to eq(params[:expense][:amount]) expect(response).to redirect_to(action: :show, id: expense.id) end end context 'パラメータの支出金額がnilのとき' do let(:params) { { expense: attributes_for(:expense, amount: nil) } } it 'エラー情報を含んだjsonを取得する' do expect(json['errors']).to eq(["Amount can't be blank"]) end end end describe 'DELETE /expenses/:id' do let!(:expense) { create(:expense, user: user) } let(:path) { "/expenses/#{expense.id}" } before { delete path } it '支出情報の削除に成功する' do expect(response.status).to eq(204) expect { Expense.find(expense.id) }.to raise_error end end end
class AccessPolicy include AccessGranted::Policy def configure role :administrator, { is_admin: true } do can :create, Employee can :read, Employee can :update, Employee can :destroy, Employee can :create, Department can :read, Department can :update, Department can :destroy, Department can :create, Inventory can :read, Inventory can :update, Inventory can :destroy, Inventory can :create, Account can :read, Account can :update, Account can :destroy, Account role :director do can :read, Employee can :read, Department can :read, Inventory can :read, Account role :manager do can :create, Employee can :read, Employee can :update, Employee can :destroy, Employee can :read, Department can :create, Inventory can :read, Inventory can :update, Inventory can :destroy, Inventory can :create, Account can :read, Account can :update, Account can :destroy, Account role :employee do can :read, Department can :read, Inventory can :update, Inventory can :destroy, Inventory can :read, Account can :update, Account end end
require 'spec_helper' describe KeywordsController do describe 'GET #index' do fixtures :templates it 'returns all the keywords as JSON' do expected = [ { keyword: 'blah', count: 1 }, { keyword: 'wordpress', count: 1 }, { keyword: 'wp', count: 1 } ] get :index, format: :json expect(response.body).to eq expected.to_json end end end
# Copyright 2010 Mark Logic, 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. require 'rubygems' require 'nokogiri' require 'ActiveDocument/search_result' module ActiveDocument class SearchResults include Enumerable attr_reader :facets def initialize(results) @results_document = Nokogiri::XML(results) end def total Integer(@results_document.xpath("/corona:response/corona:meta/corona:total/text()").to_s) end def execution_time Integer(@results_document.xpath("/corona:response/corona:meta/corona:executionTime/text()").to_s) end def start Integer(@results_document.xpath("/corona:response/corona:meta/corona:start/text()").to_s) end def page_length total - start + 1 end def each(&block) nodeset = @results_document.xpath("/corona:response/corona:results/corona:result") if nodeset.length == 1 yield SearchResult.new(nodeset[0]) else @results_document.xpath("/corona:response/corona:results/corona:result").each {|node| yield SearchResult.new(node)} end end def [](index) SearchResult.new(@results_document.xpath("/corona:response/corona:results/corona:result")[index]) end def length @results_document.xpath("/corona:response/corona:results/corona:result").length end end end
class MoveRememberTokenFromRegisteredToVerification < ActiveRecord::Migration def change add_column :verifications, :remember_token, :string remove_column :registered_clubs, :remember_token end end
require 'faker' class Post < ActiveRecord::Base belongs_to :category validates :secret_key, uniqueness: true validates :title, presence: true def self.get(params) Post.where(title: params[:post]).first end def self.secret_get(params) Post.where(secret_key: params[:secret_key]).first end def self.post_update(params) post = Post.find(params[:post_id].to_i) post.title = params[:title] post.description = params[:description] post.price = params[:price].to_i post.category = Category.where(name: params[:category]).first post.save post end def self.new_post(params) created_post = Post.create(fill_attrs(params)) Category.get(params).posts << created_post created_post end def self.fill_attrs(params) title = params[:title] description = params[:description] price = params[:price].to_i secret_key = Faker::Lorem.characters(char_count = 9) {title: title, description: description, price: price, secret_key: secret_key} end def edit(post_id, updates) self.update(post_id, updates) end end
# frozen_string_literal: true require 'stannum/constraints' module Stannum::Constraints # Namespace for Hash-specific constraints. module Hashes autoload :ExtraKeys, 'stannum/constraints/hashes/extra_keys' autoload :IndifferentExtraKeys, 'stannum/constraints/hashes/indifferent_extra_keys' autoload :IndifferentKey, 'stannum/constraints/hashes/indifferent_key' end end
class CreateTrparams < ActiveRecord::Migration[5.0] def change create_table :trparams do |t| t.float :pxx t.float :pkz t.float :snom t.float :ukz t.float :io t.float :qkz t.belongs_to :mpoint, index: true t.timestamps end end end
class Tag < ActiveRecord::Base has_many :tagposts has_many :posts, through: :tagposts end
require_relative './shared_examples/display_sticky_newsletter_spec' RSpec.describe StickyNewsletterVisibility, type: :helper do let(:request) { double('request', url: url, base_url: base_url) } let(:base_url) { 'http://example.com' } describe 'whitelisted' do context 'article' do let(:url) { 'http://example.com/en/articles/saving-money' } it 'displays sticky newsletter' do expect(display_sticky_newsletter?).to be(true) end end end describe '#black_listed?' do context 'sensitive article' do let(:url) { 'http://example.com/en/articles/choosing-your-executor' } it_behaves_like 'shuns_sticky_newsletter' end context 'cross-domain blog page' do let(:url) { 'http://example.com/blog' } it_behaves_like 'shuns_sticky_newsletter' end %w(en cy).each do |locale| context 'home page' do let(:url) { "http://example.com/#{locale}" } it_behaves_like 'shuns_sticky_newsletter' end context 'category slugs' do let(:url) { "http://example.com/#{locale}/categories/insurance" } it_behaves_like 'shuns_sticky_newsletter' end context 'corporate slugs' do let(:url) { "http://example.com/#{locale}/corporate/" } it_behaves_like 'shuns_sticky_newsletter' end context 'tools slugs' do let(:url) { "http://example.com/#{locale}/tools/" } it_behaves_like 'shuns_sticky_newsletter' end context 'videos slugs' do let(:url) { "http://example.com/#{locale}/videos/" } it_behaves_like 'shuns_sticky_newsletter' end context 'corporate_categories slugs' do let(:url) { "http://example.com/#{locale}/corporate_categories/" } it_behaves_like 'shuns_sticky_newsletter' end context 'sitemap slugs' do let(:url) { "http://example.com/#{locale}/sitemap" } it_behaves_like 'shuns_sticky_newsletter' end context 'users slugs' do let(:url) { "http://example.com/#{locale}/users" } it_behaves_like 'shuns_sticky_newsletter' end end end end
class GalleryController < ApplicationController verify :xhr => true, :only => [:on_new_photoset, :create_photo_set, :on_photo_set_item], :add_flash => {:error => 'Invalid request!'}, :redirect_to => {:action => :index} verify :params => :photo_set, :only => :create_photo_set, :add_flash => {:error => 'Invalid request! (photo_set param required)'}, :redirect_to => {:action => :index} verify :params => :photo, :only => :create_photo, :add_flash => {:error => 'Invalid request! (photo param required)'}, :redirect_to => {:action => :index} verify :params => :id, :only => :on_photo_set_item, :add_flash => {:error => 'Invalid request! (id param required)'}, :redirect_to => {:action => :index} def index @photo_sets = PhotoSet.find :all @uncategorized_photos_num = Photo.count(:conditions => {:photo_set_id => nil}) end def on_new_photoset @photo_set = PhotoSet.new remote_render_partial(:new_photoset_form, 'new_photo_set_form') end def create_photo_set PhotoSet.create(params[:photo_set]) render :update do |p| p.replace_html :photo_sets, render(:partial => 'photo_set_item', :collection => PhotoSet.find(:all)) p << "$('new_photo_set_link').show()" end end def on_photo_set_item @photo_set = PhotoSet.find(params[:id]) @photos = @photo_set.photos remote_render_collection(:photos, 'photo_item', @photos) end def on_uncategorized_photo_set_item @photos = Photo.find(:all, :conditions => {:photo_set_id => nil, :parent_id => nil}) remote_render_collection(:photos, 'photo_item', @photos) end def on_new_photo @photo = Photo.new @photo_set_options = [['Select Photoset', nil]] + PhotoSet.options remote_render_partial(:new_photo_form, 'new_photo_form') end def create_photo @photo = Photo.create(params[:photo]) flash_notice 'Photo successfully created' p @photo.errors.full_messages redirect_to :action => :index end end
class DtEmpresaRequestSerializerUser < ActiveModel::Serializer attributes :id, :empresa, :fecha, :titulo, :estado, :DT_RowAttr, :bg_color, :state_color, :empresa_hash def empresa object.empresa.decorate.user_table_info end def empresa_hash empresa = object.empresa.decorate { :id => empresa.id, :nombre=> empresa.nombre, :telefono => empresa.phone, :email => empresa.email } end def titulo object.request.title || "" end def fecha object.date.strftime("%d/%m/%y - %H:%M") rescue "" end def estado object.state_to_user2 end def bg_color object.state_to_staff_color end def state_color bg_color end def DT_RowAttr {:r_id=>object.id} end end
# in order to run the console with project environment rails console # or rails c # to list all classes in models, even if they are not using ORMs Dir['**/models/**/*.rb'].map {|f| File.basename(f, '.*').camelize.constantize } # run server in current folder ruby -run -e httpd . -p 9090 # create rails-api (gem rails-api should be instaled prior to that) rails-api new . -T -d sqlite3 # . - in current directory # -T - without test # -d sqlite - specifying database to use (-d postgresql) #rspec generation rails g rspec:request APIDevelopment # will create spec/request/api_development_spec.rb with description "ApiDevelopment" # ALTERNATIVE SERVERS # for example PUMA # add to Gemfile gem 'puma', '~>3.6', '>=3.6.0', :platforms=>:ruby # some error messaging not inmlemented if run in windows # if on windows, stay with WEBrick at least while developng group :development do gem 'webrick', '~>1.3', '>=1.3.1', :platforms=>[:mingw, :mswin, :x64_mingw, :jruby] end # find configuration on https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#config # save file config/puma.rb
class RewardsUser < ActiveRecord::Base belongs_to :reward belongs_to :user end
class RenameColumnPurchaseOrderIdToOrderId < ActiveRecord::Migration def change rename_column :provisions, :purchase_order_id, :order_id 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) require 'open-uri' require 'json' puts 'Parsing ingredients...' url = 'https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list' ingredients_serialized = open(url).read ingredients_hash = JSON.parse(ingredients_serialized) ingredients = [] ingredients_hash['drinks'].each do |hash| ingredients << hash['strIngredient1'] end ingredients.each do |ingredient| new_ingredient = Ingredient.new(name: ingredient) new_ingredient.save! end puts 'finished!' # puts "adding urls" # cocktail1 = Cocktail.find(1) # cocktail2 = Cocktail.find(2) # cocktail3 = Cocktail.find(3) # cocktail4 = Cocktail.find(4) # cocktail1.url = 'https://www.papillesetpupilles.fr/wp-content/uploads/2006/07/Mojito-%C2%A9sanneberg-shutterstock.jpg' # cocktail2.url = 'https://assets.afcdn.com/recipe/20180705/80274_w648h344c1cx2378cy1278cxt0cyt0cxb4799cyb3199.jpg' # cocktail3.url = 'https://www.thespruceeats.com/thmb/YlhdecRcUlxy5o5TFfcmqv1CQiw=/450x0/filters:no_upscale():max_bytes(150000):strip_icc()/gin-tonic-5a8f334b8e1b6e0036a9631d.jpg' # cocktail4.url = 'https://static.vinepair.com/wp-content/uploads/2018/03/moscow-card.jpg' # cocktail1.save # cocktail2.save # cocktail3.save # cocktail4.save # puts "finished!"
require 'test_helper' class ConsultationTypesControllerTest < ActionDispatch::IntegrationTest setup do @consultation_type = consultation_types(:one) end test "should get index" do get consultation_types_url assert_response :success end test "should get new" do get new_consultation_type_url assert_response :success end test "should create consultation_type" do assert_difference('ConsultationType.count') do post consultation_types_url, params: { consultation_type: { name: @consultation_type.name, price: @consultation_type.price, status: @consultation_type.status, user_id: @consultation_type.user_id } } end assert_redirected_to consultation_type_url(ConsultationType.last) end test "should show consultation_type" do get consultation_type_url(@consultation_type) assert_response :success end test "should get edit" do get edit_consultation_type_url(@consultation_type) assert_response :success end test "should update consultation_type" do patch consultation_type_url(@consultation_type), params: { consultation_type: { name: @consultation_type.name, price: @consultation_type.price, status: @consultation_type.status, user_id: @consultation_type.user_id } } assert_redirected_to consultation_type_url(@consultation_type) end test "should destroy consultation_type" do assert_difference('ConsultationType.count', -1) do delete consultation_type_url(@consultation_type) end assert_redirected_to consultation_types_url end end
class Api::PurchasesController < ApiController class UnsupportedService < PurchaseError; end before_filter :authenticate_user_from_token! rescue_from PurchaseError, with: :bad_request rescue_from UnsupportedService, with: :not_found rescue_from PurchaseEnvironmentPolicy::Error, with: :forbidden def create request_metadata = { user_agent: request.user_agent, request_id: request.uuid, ip: request.ip, remote_ip: request.remote_ip, jailbroken: request.headers['X-Jailbroken'] } @tip = find_tip # CHANGE TO # @purchase = current_user.purchase_tip(@tip) # ALL OF IT LIVES IN THAT METHOD if current_user.purchases.pluck(:tip_id).include? @tip.id raise BadRequestError, "User #{current_user.id} has already purchased this tip" end @purchase = case params[:service].to_sym when :itunes service_object = ItunesPurchaseCreator.new purchase = service_object.(current_user, @tip, params[:transaction_id], params[:receipt_data], request_metadata: request_metadata) @verification = service_object.verification purchase when :reputation CreateReputationPurchase.new.(current_user, @tip, request_metadata: request_metadata) when :compliment PurchaseComplimentTip.new.(current_user, @tip, request_metadata: request_metadata) else raise UnsupportedService, 'The specified service is not currently supported.' end if @purchase @tip = ConsumerTip.new(@tip, current_user) render status: :created else message = if @verification @verification.result_message else # TODO (reputation purchase) end raise PurchaseError, message end end private def find_tip params.require :id ::Tip.published.fuzzy_find! params[:id] end private def purchase_params params.require :service params.permit *%w{ service receipt_data transaction_id } end memoize :purchase_params end
class Code < ActiveRecord::Base has_many :authorships has_many :authors, :through => :authorships has_many :comments, :dependent => :destroy, :order => 'created_at desc' has_many :working_comments, :class_name => 'Comment', :conditions => { :works_for_me => true } has_many :failure_comments, :class_name => 'Comment', :conditions => { :works_for_me => false } named_scope :popular, :order => 'comments_count desc' named_scope :unpopular, :order => 'comments_count asc' define_index do indexes :name, :sortable => true indexes description indexes homepage indexes rubyforge indexes github indexes slug_name indexes summary end def code_slug_name self.slug_name end def code_name self.name end def permalink URL_ROOT + code_slug_name end def works? has_no_failure_comments? && has_working_comments? end def has_working_comments? working_comments.any? end def has_no_working_comments? !has_working_comments? end def number_of_working_comments working_comments.count end def has_failure_comments? failure_comments.any? end def has_no_failure_comments? !has_failure_comments? end def number_of_failure_comments failure_comments.count end def has_homepage_url? self.homepage =~ /^http:/i end def description_or_summary return description unless description.blank? return summary end def to_json(options = {}) default_only = ["name", "description", "summary", "homepage", "rubyforge", "code_type"] options[:only] = (options[:only] || []) + default_only options[:methods] = :permalink super(options) end def to_xml(options = {}) default_only = ["name", "description", "summary", "homepage", "rubyforge", "code_type"] options[:only] = (options[:only] || []) + default_only super(options) do |xml| xml.permalink permalink end end def gem_version Gem::Version.new(self.latest_version) end def update_from_spec uri = URI.parse("http://rubygems.org") if spec = Gem::SpecFetcher.fetcher.fetch_spec([name, gem_version], uri) update_attributes({ :description => spec.description, :homepage => spec.homepage, :rubyforge => spec.rubyforge_project, :summary => spec.summary }) spec.authors.each do |author| auther = Author.find_or_create_by_name(author) authors << author end end end # def self.new_from_gem_spec(spec) # f = find_or_initialize_by_name(spec.name.to_s) # if f.new_record? # f.attributes = {:description => spec.description, :homepage => spec.homepage, :rubyforge => spec.rubyforge_project, :summary => spec.summary} # f.code_type = "gem" # f.save! # spec.authors.each do |author| # a = Author.find_or_create_by_name(author) # f.authors << a # end # logger.info("Imported Gem: #{f.name}") # else # logger.info("Gem #{spec.name} already existed") # end # rescue => e # logger.info("Could not create code from gem spec\n #{spec.inspect}") # end def self.import(name, version) code = find_or_initialize_by_name(name) code.latest_version = version.to_s code.save end def self.compatibility total = Comment.count total = 1 if total == 0 Comment.working.size * 100 / total end private validates_uniqueness_of :name, :slug_name validates_presence_of :name, :slug_name before_validation_on_create :set_slug_name def set_slug_name self.slug_name = slug_name_from_name || self.rubyforge end include ActiveSupport::Inflector # really? def slug_name_from_name parameterize(self.name) end end
namespace :cache do def foo(s) Fyle.find_each do |f| if f.type_negotiation == s puts "gotcha (#{s}) #{f}" # f.cache_file = nil # f.save end end end desc 'remove cached files, type is: all, text, pdf, xml, html' task :clear, [:type] => :environment do |t, args| case args.type when 'pdf' foo ::Fyle::PDF_TEXT when 'text' foo ::Fyle::PLAIN_TEXT when 'xml' foo ::Fyle::XML_TEI_TEXT when 'html' foo ::Fyle::HTML_TEXT end end desc 'report how many cached versus uncached' task report: :environment do c = 0 nc = 0 Fyle.find_each do |f| f.cache_file.blank? ? (nc+=1) : (c+=1) end puts "cached: #{c}" puts "not cached: #{nc}" end end
class Pub attr_reader :name, :till def initialize(name, till) @name = name @till = till @drinks = [] end def drink_count return @drinks.count end def add_drink(drink) @drinks << drink end def serve(customer, drink) first_index_of_drink = @drinks.index(drink) drink_is_not_in_stock = first_index_of_drink.nil? return if drink_is_not_in_stock @drinks.delete_at(first_index_of_drink) customer.buy(drink) @till += drink.price() end end
class ChoreScheduler < ActiveRecord::Base belongs_to :chore #the last chore it scheduled attr_accessible :default_bids, :respawn_time has_paper_trail serialize :default_bids, Hash def schedule_next(run_at_time) old_chore = self.chore new_chore = nil new_auction = nil Chore.transaction do #make a new chore that expires (respawn_time) after the current one new_chore = old_chore.class.new #update the new chore's attributes new_chore.name = old_chore.name new_chore.due_date = old_chore.due_date + self.respawn_time if new_chore.start_date old_chore.start_date=old_chore.start_date + self.respawn_time end #make a new auction that expires (respawn_time) after the old one new_auction = Auction.new new_auction.expiration_date = old_chore.auction.expiration_date + self.respawn_time new_chore.auction = new_auction #hacky solution to make it connect the chore to the auction (bad) new_chore.auctions_count = 1 new_chore.chore_scheduler = self #save both items new_auction.save new_chore.save end #schedule calling this function again in respawn_time self.delay( run_at: run_at_time + self.respawn_time).schedule_next(run_at_time + self.respawn_time) #also close the auction when it is supposed to be closed new_auction.delay(:run_at => new_auction.expiration_date).close #set to track the new chore, forget about the old one self.chore = new_chore self.save end def self.get_default_bid(user) return self.default_bids[user.id] end end
class MessagesController < ApplicationController before_action :authenticate_user_admin! def create @message = Message.new(message_params) render plain: 'ERROR' and return unless @message.save if user_signed_in? ActionCable.server.broadcast( 'message_channel', message: @message, message_user_name: @message.user.name, time: @message.updated_at.strftime('%m/%d %H:%M '), message_count: @message.shop.messages.count ) elsif admin_signed_in? ActionCable.server.broadcast( 'message_channel', message: @message, message_user_name: @message.admin.name, time: @message.updated_at.strftime('%m/%d %H:%M '), message_count: @message.shop.messages.count ) end end private def message_params message_params = params.require(:message).permit(:text).merge(shop_id: params[:shop_id]) if user_signed_in? message_params.merge(user_id: current_user.id) elsif admin_signed_in? message_params.merge(admin_id: current_admin.id) end end end
class CreateWorkflows < ActiveRecord::Migration[5.1] def change create_table :workflows do |t| t.string :open t.string :backlog t.string :wip t.string :testing t.string :done t.string :flagged t.integer :cycle_time t.integer :lead_time t.references :setting, foreign_key: true t.timestamps end end end
Rails.application.routes.draw do devise_for :users resources :posts do get :search, on: :collection end resources :comments, only: %i[create] root 'posts#index' end
$:.unshift(File.dirname(__FILE__)) require_relative 'materialize_components/badge.rb' require_relative 'materialize_components/base.rb' require_relative 'materialize_components/breadcrumb.rb' require_relative 'materialize_components/button.rb' require_relative 'materialize_components/chip.rb' require_relative 'materialize_components/errors.rb' require_relative 'materialize_components/fixed_action_button.rb' require_relative 'materialize_components/icon_badge.rb' require_relative 'materialize_components/icon.rb' require_relative 'materialize_components/preloader.rb' require_relative 'materialize_components/spinner.rb' require_relative 'materialize_components/version.rb' module MaterializeComponents # Convenience methods for easy access to # the various components inside the gem # Badges def self.badge content return Badge.new(content) end def self.new_badge content return Badge::New.new(content) end # Breadcrumb def self.breadcrumb return Breadcrumb.new end # Button def self.button content return Button.new(content) end def self.flat_button content return Button.new(content).flat end def self.disabled_button content return Button.new(content).disabled end def self.large_disabled_button content return Button.new(content).disabled.large end def self.wave_button content return Button.new(content).waves end def self.button_with_icon icon return Button::WithIcon.new(icon) end def self.button_with_icon_right icon return Button::WithIcon.new(icon).icon_right end def self.wave_button_with_icon icon return Button::WithIcon.new(icon).waves end def self.wave_button_with_icon_right icon return Button::WithIcon.new(icon).waves.icon_right end def self.floating_button icon return Button::Floating.new(icon) end def self.wave_floating_button icon return Button::Floating.new(icon).waves end # Chip def self.chip content return Chip.new(content) end def self.chip_with_icon icon return Chip::WithIcon.new(icon) end # FAB def self.fixed_action_button icon return FixedActionButton.new(icon) end # Icon Badge def self.icon_badge icon return IconBadge.new(icon) end def self.icon_badge_large icon return IconBadge::Large.new(icon) end # Icon def self.icon icon return Icon.new(icon) end # Preloader def self.preloader return Preloader.new end def self.preloader_determinate width return Preloader.new.determinate(width) end def self.preloader_indeterminate width return Preloader.new.indeterminate end # Spinner def self.spinner return Spinner.new end def self.red_spinner return Spinner.new.red end def self.blue_spinner return Spinner.new.blue end def self.red_spinner return Spinner.new.green end def self.yellow_spinner return Spinner.new.yellow end end
module ETL #:nodoc: module Processor #:nodoc: # Base class for pre and post processors. Subclasses must implement the +process+ method. class Processor def initialize(control, configuration) @control = control @configuration = configuration after_initialize if respond_to?(:after_initialize) end protected # Get the control object def control @control end # Get the configuration Hash def configuration @configuration end # Get the engine logger def log Engine.logger end end end end
class TaxonUsagesController < ApplicationController def show @taxon_usage = TaxonUsage.new(id: params[:id]) render partial: "taxon_usage", locals: { taxon_usage: @taxon_usage } end end
class Riddle attr_reader :riddle, :answer, :id, :name @@riddles = {} @@total_rows = 0 def initialize(name, riddle, answer, id) @name = name.downcase @riddle = riddle.downcase @answer = answer.downcase @id = id || @@total_rows += 1 end def save() @@riddles[self.id] = Riddle.new(self.name, self.riddle, self.answer, self.id) end def guess(ans) if ans.downcase.split == self.answer.split return true else return false end end def self.all() @@riddles.values() end def self.find(id) @@riddles[id] end def ==(riddle_to_compare) self.riddle() == riddle_to_compare.riddle() && self.name == riddle_to_compare.name && self.answer == riddle_to_compare.answer end def self.clear @@riddles = {} @@total_rows = 0 end def update(name, riddle, answer) @name = name @riddle = riddle @answer = answer end def delete() @@riddles.delete(self.id) end end
require 'nokogiri' require 'set' require_relative 'lib/boss' require_relative 'lib/factory' require_relative 'lib/capability' require_relative 'lib/observation' module SOSHelper Urls = ["http://cgis.csrsr.ncu.edu.tw:8080/swcb-sos-new/service", "http://cgis.csrsr.ncu.edu.tw:8080/epa-sos/service", "http://cgis.csrsr.ncu.edu.tw:8080/epa-aqx-sos/service"].freeze Relics = ["offering","observedProperty", "featureOfInterest", "procedure", "spatialFilter", "temporalFilter", "responseFormat"].freeze ObservationRequest = File.open('request/getObservation.xml') { |f| Nokogiri::XML(f) }.freeze end # o = SOSHelper::GetObservation.new # o.filter({:offering => "鳳義坑"}).filter({:observedProperty => "urn:ogc:def:phenomenon:OGC:1.0.30:rainfall_1day"}) # c = o.filter({:temporalFilter => :during }) # p c
require 'savon' module OCR class Free_ocr < OCR::Ocr attr_accessor :convert_to_bw private def init super() end def ocr_recognize raise Exception, 'You should set image file' unless @file request = { 'image' => File.open(@file, 'rb') { |f| [f.read].pack('m*') } } request[:username] = @username if @username client = Savon::Client.new('http://www.free-ocr.co.uk/ocr.asmx?WSDL') response = client.request(:analyze) do soap.body = request end return false if have_error? response.body set_text response.body[:analyze_response][:analyze_result] end def have_error? response return true && set_error("No response") unless response.has_key?(:analyze_response) return true && set_error("No response") unless response[:analyze_response].has_key?(:analyze_result) end end end
class PokeLocsController < ApplicationController def search if params[:lat].blank? || params[:lng].blank? render json: {errors: ["lat or lng must be specify"]}, status: :bad_request return end lat = params[:lat].to_f lng = params[:lng].to_f list = PokeLoc.current_list(lat: lat, lng: lng) @poke_locs = WatchedPokemon.filter(list, lat: lat, lng: lng) end end
class CreateCampsites < ActiveRecord::Migration[6.1] def change create_table :campsites do |t| t.string :name t.string :state t.string :address t.string :phone_number t.string :website t.text :description t.boolean :full_hookups t.boolean :partial_hookups t.boolean :fishing t.boolean :showers t.boolean :bathrooms t.string :map_img_url t.string :site_img_url t.string :season t.timestamps end end end
class CreateGameScenarios < ActiveRecord::Migration def change create_table :game_scenarios do |t| t.text :faces t.text :viable_words t.integer :max_score end end end
class GithubsController < ApplicationController before_action :login_github # /githubs Get list of repositories def index @list = @github&.repos&.list end # github/id Get repo details def show if params["id"].present? @project = @github&.repos&.get_by_id(params["id"]) if @project.present? @chartData = GithubApis.get_datewise_commits(current_user, @github, @project, params["daterange"]) end end end private def login_github @github = current_user.login_github end end
namespace :today_question do desc "Rake task to update new daily questions" task update: :environment do puts "#{Time.now} Updating daily questions..." list = Question.where(author_id: 1) numbers = (0..(list.count-1)).to_a.sample 5 numbers.each do |number| question = list[number] question.selected_date = Date.today question.save end puts "#{Time.now} - Success!" end end
shared_examples_for "controller_activity_logging" do before(:all) do sorcery_reload!([:activity_logging]) end specify { expect(subject).to respond_to(:current_users) } let(:user) { create_new_user } before(:each) { user } it "'current_users' is empty when no users are logged in" do expect(subject.current_users.size).to eq 0 end it "logs login time on login" do now = Time.now.in_time_zone login_user expect(user.last_login_at).not_to be_nil expect(user.last_login_at.utc.to_s).to be >= now.utc.to_s expect(user.last_login_at.utc.to_s).to be <= (now.utc+2).to_s end it "logs logout time on logout" do login_user now = Time.now.in_time_zone logout_user expect(User.last.last_logout_at).not_to be_nil expect(User.last.last_logout_at.utc.to_s).to be >= now.utc.to_s expect(User.last.last_logout_at.utc.to_s).to be <= (now+2).utc.to_s end it "logs last activity time when logged in" do sorcery_controller_property_set(:register_last_activity_time, true) login_user now = Time.now.in_time_zone get :some_action last_activity_at = User.last.last_activity_at expect(last_activity_at).to be_present expect(last_activity_at.utc.to_s).to be >= now.utc.to_s expect(last_activity_at.utc.to_s).to be <= (now+2).utc.to_s end it "logs last IP address when logged in" do login_user get :some_action expect(User.last.last_login_from_ip_address).to eq "0.0.0.0" end it "updates nothing but activity fields" do original_user_name = User.last.username login_user get :some_action_making_a_non_persisted_change_to_the_user expect(User.last.username).to eq original_user_name end it "'current_users' holds the user object when 1 user is logged in" do login_user get :some_action expect(subject.current_users).to match([User.sorcery_adapter.find(user.id)]) end it "'current_users' shows all current_users, whether they have logged out before or not." do user1 = create_new_user({:username => 'gizmo1', :email => "bla1@bla.com", :password => 'secret1'}) login_user(user1) get :some_action clear_user_without_logout user2 = create_new_user({:username => 'gizmo2', :email => "bla2@bla.com", :password => 'secret2'}) login_user(user2) get :some_action clear_user_without_logout user3 = create_new_user({:username => 'gizmo3', :email => "bla3@bla.com", :password => 'secret3'}) login_user(user3) get :some_action expect(subject.current_users.size).to eq 3 expect(subject.current_users[0]).to eq User.sorcery_adapter.find(user1.id) expect(subject.current_users[1]).to eq User.sorcery_adapter.find(user2.id) expect(subject.current_users[2]).to eq User.sorcery_adapter.find(user3.id) end it "does not register login time if configured so" do sorcery_controller_property_set(:register_login_time, false) now = Time.now.in_time_zone login_user expect(user.last_login_at).to be_nil end it "does not register logout time if configured so" do sorcery_controller_property_set(:register_logout_time, false) now = Time.now.in_time_zone login_user logout_user expect(user.last_logout_at).to be_nil end it "does not register last activity time if configured so" do sorcery_controller_property_set(:register_last_activity_time, false) now = Time.now.in_time_zone login_user get :some_action expect(user.last_activity_at).to be_nil end it "does not register last IP address if configured so" do sorcery_controller_property_set(:register_last_ip_address, false) ip_address = "127.0.0.1" login_user get :some_action expect(user.last_activity_at).to be_nil end end
require "liminal_hooks" require "active_record/remove_validator" module SpreeSite class Engine < Rails::Engine def self.activate # Add your custom site logic here Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare &method(:activate).to_proc # # Spree v0.50.0 causes application rake tasks to be run twice, a fix has been committed but has not yet been # officially released, so backport for now. This can be removed when next upgrading Spree. # # http://railsdog.lighthouseapp.com/projects/31096/tickets/1792-spree-causes-rake-tasks-to-be-invoked-twice # https://github.com/spree/spree/commit/fb5490157dfe3cd4d7da6e20a0fe61065b097639 # def load_tasks end end end
require_relative './glyphs' module DataMetaXtra # ANSI control sequences. module AnsiCtl # https://en.wikipedia.org/wiki/ANSI_escape_code # Skip ANSI Escape sequences unless this env var is defined and set to 'yes' SKIP_ANSI_ESC = ENV['DATAMETA_USE_ANSI_CTL'] != 'yes' include Glyphs # ANSI escape operation start OP = SKIP_ANSI_ESC ? '' : 27.chr + '[' # ANSI atribute divider. When the ANSI seqs are disabled, this takes care of concatenating those. ATRB_DIV = SKIP_ANSI_ESC ? ';' : '' # Plain text PLAIN = SKIP_ANSI_ESC ? '' : '0' # Reset sequence RESET = SKIP_ANSI_ESC ? '' : "#{OP}m" # Styles: # Bold BOLD = SKIP_ANSI_ESC ? '' : '1' # Dimmed DIM = SKIP_ANSI_ESC ? '' : '2' # Underline ULINE = SKIP_ANSI_ESC ? '' : '4' # Blinking BLINK = SKIP_ANSI_ESC ? '' : '5' # Reverse graphics REVERSE = SKIP_ANSI_ESC ? '' : '7' # Hidden text - to enter passwords HIDDEN = SKIP_ANSI_ESC ? '' : '8' # Reset Bold REBOLD = SKIP_ANSI_ESC ? '' : "2#{BOLD}" # Reset Dim REDIM = SKIP_ANSI_ESC ? '' : "2#{DIM}" # Reset Underline REULINE = SKIP_ANSI_ESC ? '' : "2#{ULINE}" # Reset Blink REBLINK = SKIP_ANSI_ESC ? '' : "2#{BLINK}" # Reset reverse graphics REREVERSE = SKIP_ANSI_ESC ? '' : "2#{REVERSE}" # Reset hidden text REHIDDEN = SKIP_ANSI_ESC ? '' : "2#{HIDDEN}" # Foregrounds: # Default foreground F_DEF = SKIP_ANSI_ESC ? '' : '39' # Black foreground F_BLACK = SKIP_ANSI_ESC ? '' : '30' # Red foreground F_RED = SKIP_ANSI_ESC ? '' : '31' # Green foreground F_GREEN = SKIP_ANSI_ESC ? '' : '32' # Brown foreground F_BROWN = SKIP_ANSI_ESC ? '' : '33' # Yellow, alias for BROWN foreground F_YELLOW = SKIP_ANSI_ESC ? '' : F_BROWN # blue foreground F_BLUE = SKIP_ANSI_ESC ? '' : '34' # Purple foreground F_PURPLE = SKIP_ANSI_ESC ? '' : '35' # Magenta, alias or PURPLE foreground F_MAGENTA = SKIP_ANSI_ESC ? '' : F_PURPLE # Cyan foreground F_CYAN = SKIP_ANSI_ESC ? '' : '36' # Light Grey foreground F_LGREY = SKIP_ANSI_ESC ? '' : '37' # Light Gray, alias for GREY foreground F_LGRAY = SKIP_ANSI_ESC ? '' : F_LGREY # Dark Grey foreground F_DGREY = SKIP_ANSI_ESC ? '' : '90' # Dark Gray, alias for GRAY foreground F_DGRAY = SKIP_ANSI_ESC ? '' : F_DGREY # Light Red foreground F_LRED = SKIP_ANSI_ESC ? '' : '91' # Light Green foreground F_LGREEN = SKIP_ANSI_ESC ? '' : '92' # Light Brown foreground F_LBROWN = SKIP_ANSI_ESC ? '' : '93' # Light Yellow, alias for BROWN foreground F_LYELLOW = SKIP_ANSI_ESC ? '' : F_LBROWN # Light Blue foreground F_LBLUE = SKIP_ANSI_ESC ? '' : '94' # Light Purple foreground F_LPURPLE = SKIP_ANSI_ESC ? '' : '95' # Light Magenta, alias for PURPLE foreground F_LMAGENTA = SKIP_ANSI_ESC ? '' : F_LPURPLE # Light Cyan foreground F_LCYAN = SKIP_ANSI_ESC ? '' : '96' # Light White foreground F_WHITE = SKIP_ANSI_ESC ? '' : '97' # Close the ANSI Escape Sequence CL = SKIP_ANSI_ESC ? '' : 'm' # Black background B_BLACK = SKIP_ANSI_ESC ? '' : '40' # Red background B_RED = SKIP_ANSI_ESC ? '' : '41' # Green background B_GREEN = SKIP_ANSI_ESC ? '' : '42' # Brown background B_BROWN = SKIP_ANSI_ESC ? '' : '43' # Yellow, alias for BROWN background B_YELLOW = SKIP_ANSI_ESC ? '' : B_BROWN # Blue background B_BLUE = SKIP_ANSI_ESC ? '' : '44' # Purple background B_PURPLE = SKIP_ANSI_ESC ? '' : '45' # Magenta, alias for PURPLE background B_MAGENTA = SKIP_ANSI_ESC ? '' : B_PURPLE # Cyan background B_CYAN = SKIP_ANSI_ESC ? '' : '46' # Light Grey background B_LGREY = SKIP_ANSI_ESC ? '' : '47' # Light Gray, alias for GRAY background B_LGRAY = SKIP_ANSI_ESC ? '' : B_LGREY # Dark Grey background B_DGREY = SKIP_ANSI_ESC ? '' : '100' # Dark Gray, alias for GRAY background B_DGRAY = SKIP_ANSI_ESC ? '' : B_DGREY # Plain background B_PLAIN = SKIP_ANSI_ESC ? '' : '49' # Default background B_DEFAULT = SKIP_ANSI_ESC ? '' : B_PLAIN # Light Red background B_LRED = SKIP_ANSI_ESC ? '' : '101' # Light Green background B_LGREEN = SKIP_ANSI_ESC ? '' : '102' # Light Brown background B_LBROWN = SKIP_ANSI_ESC ? '' : '103' # Light Yellow, alias for BROWN background B_LYELLOW = SKIP_ANSI_ESC ? '' : B_LBROWN # Light Blue background B_LBLUE = SKIP_ANSI_ESC ? '' : '104' # Light Purple background B_LPURPLE = SKIP_ANSI_ESC ? '' : '105' # Light Magenta, alias for PURPLE background B_LMAGENTA = SKIP_ANSI_ESC ? '' : B_LPURPLE # Light Cyan background B_LCYAN = SKIP_ANSI_ESC ? '' : '106' # Light White background B_WHITE = SKIP_ANSI_ESC ? '' : '107' # All Styles with names STYLES = { BOLD => 'BOLD', DIM => 'DIM', ULINE => 'ULINE', BLINK => 'BLINK', REVERSE => 'REVERSE', HIDDEN => 'HIDDEN', REBOLD => 'RE-BOLD', REDIM => 'RE-DIM', REULINE => 'RE-ULINE', REBLINK => 'RE-BLINK', REREVERSE => 'RE-REVERSE', REHIDDEN => 'RE-HIDDEN' } # All Foregrounds with names FORES = { F_DEF => 'F_DEF', F_BLACK => 'F_BLACK', F_RED => 'F_RED', F_GREEN => 'F_GREEN', F_BROWN => 'F_BROWN', F_BLUE => 'F_BLUE', F_PURPLE => 'F_PURPLE', F_CYAN => 'F_CYAN', F_LGREY => 'F_LGREY', F_DGREY => 'F_DGREY', F_LRED => 'F_LRED', F_LGREEN => 'F_LGREEN', F_LBROWN => 'F_LBROWN', F_LBLUE => 'F_LBLUE', F_LPURPLE => 'F_LPURPLE', F_LCYAN => 'F_LCYAN', F_WHITE => 'F_WHITE', } # All Backgrounds with names BACKS = { B_BLACK => 'B_BLACK', B_RED => 'B_RED', B_GREEN => 'B_GREEN', B_BROWN => 'B_BROWN', B_BLUE => 'B_BLUE', B_PURPLE => 'B_PURPLE', B_CYAN => 'B_CYAN', B_LGREY => 'B_LGREY', B_DGREY => 'B_DGREY', B_DEFAULT => 'B_DEFAULT', B_LRED => 'B_LRED', B_LGREEN => 'B_LGREEN', B_LBROWN => 'B_LBROWN', B_LBLUE => 'B_LBLUE', B_LPURPLE => 'B_LPURPLE', B_LCYAN => 'B_LCYAN', B_WHITE => 'B_WHITE', } # convenient test for all styles def test puts out = '' BACKS.keys.each { |b| FORES.keys.each { |f| STYLES.keys.each { |s| out << %<#{LLQBIG}#{OP}#{s};#{f};#{b}m#{FORES[f]}/#{BACKS[b]}:#{STYLES[s]}#{RESET}#{RRQBIG}> if out.length > 240 puts out out = '' end } } print "\n" } puts end module_function :test end end
require 'test_helper' class CreateFactoriesTest < ActionDispatch::IntegrationTest # test message test " gets new sheet form and create new sheet" do # gets new sheet path -> emulating user behaviour were user selet the option to create a new record get new_factory_path # assert whether we have the new path reached for the template assert_template 'factories/new' # assert wether we have created a new sheet # by checking the difference in count assert_difference 'Factory.count', 1 do # submission of a new form handled by the create action which is a # HTTP POST request to create a new sheet with the below attirbutes post_via_redirect factories_path, factory: {name: "A factory name", address: "A factory address"} end # asserting the the show view whether it contains # one of the strings passed in at creation -> # "aName" should be visible in the reponse body assert_template 'factories/show' assert_match "A factory name", response.body end end
require 'rails_helper' describe "nav system" do it 'goes to the root path when clicking the logo' do visit trips_path click_on "BikeShare" expect(current_path).to eq(root_path) end it 'redirects to stations index when you click on Stations' do visit root_path click_on "Stations" expect(current_path).to eq(stations_path) end it 'redirects to trips index when you click on Trips' do visit root_path click_on "Trips" expect(current_path).to eq(trips_path) end end
class RemoveTranscriptionFromVoicemails < ActiveRecord::Migration[5.2] def change remove_column :voicemails, :transcription, :text end end
# The Vehicle model class Vehicle < ApplicationRecord validates :name, :desc, :state_id, presence: true belongs_to :state before_validation :set_default_state, on: :create delegate :name, to: :state, prefix: true def as_json(options = {}) super(options.merge(methods: [:state_name])) end def next_state! if (next_state = state.next) update(state_id: next_state.id) else false end end private def set_default_state self.state_id = State.ordered.first.id end end
=begin Create an array with the following values: 3,5,1,2,7,9,8,13,25,32. Print the sum of all numbers in the array. Also have the function return an array that only include numbers that are greater than 10 (e.g. when you pass the array above, it should return an array with the values of 13,25,32 - hint: use reject or find_all method) =end x = [3,5,1,2,7,9,8,13,25,32] def gt10 (arr) sum = 0 arr.each {|i| "#{sum += i}"} puts "sum is #{sum}" y = [] # arr.each {|i| y << i if i > 10} arr.reject {|i| y << i if i > 10} # puts y return y end # puts gt10 x =begin Create an array with the following values: John, KB, Oliver, Cory, Matthew, Christopher. Shuffle the array and print the name of each person. Have the program also return an array with names that are longer than 5 characters. =end names = ["John", "KB", "Oliver", "Cory"," Matthew", "Christopher"] def shuffle (arr) puts arr.shuffle y = [] arr.each {|i| y << i if i.length > 5} return y end # puts shuffle names =begin Create an array that contains all 26 letters in the alphabet (this array must have 26 values). Shuffle the array and display the last letter of the array. Have it also display the first letter of the array. If the first letter in the array is a vowel, have it display a message. =end arr = Array("a".."z").to_a # puts arr def letters(arr) puts arr = arr.shuffle puts arr.at(0) puts arr.at(25) end # puts letters arr =begin Generate an array with 10 random numbers between 55-100. =end arr = [] def randarray(arr) (1..10).each {|i| arr << rand(55..100)} # puts rand(55..100) return arr end # puts randarray(arr) =begin Generate an array with 10 random numbers between 55-100 and have it be sorted (showing the smallest number in the beginning). Display all the numbers in the array. Next, display the minimum value in the array as well as the maximum value =end arr = [] def randsortarray(arr) (1..10).each {|i| arr << rand(55..100)} # puts arr return arr.sort end # puts randsortarray(arr) =begin Create a random string that is 5 characters long (hint: (65+rand(26)).chr returns a random character) Generate an array with 10 random strings that are each 5 characters long =end def randomstring x = [] (1..5).each { x.push (1..5).map { (65+rand(26)).chr }.join } # x.push (1..5).map { (65+rand(26)).chr }.join # x = Array(1..10) # x.each {|i| x << (1..5).map { (65+rand(26)).chr }.join} puts x end randomstring
class LeaguePresenter < BasePresenter presents :league def to_s league.name end def link link_to league.name, league_path(league) end def description # rubocop:disable Rails/OutputSafety league.description_render_cache.html_safe # rubocop:enable Rails/OutputSafety end def list_group_item_class if league.hidden? 'list-group-item list-group-item-warning' elsif league.running? 'list-group-item list-group-item-info' else 'list-group-item list-group-item-success' end end end
# encoding: utf-8 module Kinopoisk class Movie require 'open-uri' require 'nokogiri' attr_accessor :id, :url HEADERS = { "Accept" => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', "Accept-Language" => 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4', 'Host' => 'www.kinopoisk.ru', 'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.63 Safari/537.31' } def initialize(url, title = nil) @id = url.match(/\d+/).to_a.last @url = url end def title document.search("//h1[@itemprop='name']")[0].children.text rescue nil end def author document.xpath("//td")[10].elements.children.text rescue nil end def cast_members document.search("//li[@itemprop='actors']").map do |actor| actor.children.text end.reject{|name| name =='...' || name == nil} end def countries document.xpath("//td")[4].elements.children.text.split(",").map{ |c| c.strip } rescue nil end def slogan document.xpath("//td")[6].children.text rescue nil end def description text = document.search("//div[@itemprop='description']").text rescue nil end def director document.search("//td[@itemprop='director']/a").map{ |d| d.children.text.strip } rescue nil end def genres document.xpath("//td")[22].elements. map{|a| a.children.text} .reject{ |g| g == '...' || g == 'слова'} rescue nil end def duration document.search("//td[@id='runtime']").inner_html.strip.to_i end def poster begin res = document.xpath("//a[@class='popupBigImage']")[0].attributes["onclick"].value res.match(/\'(.*?)\'/)[1] rescue nil end end def producer document.xpath("//td")[12].elements. map{|a| a.children.text} .reject{ |g| g == '...'} rescue nil end def rating document.search("//span[@class='rating_ball']")[0].text rescue nil end def thumbnail images = document.search("//img[@src*=/images/']").map do |item| "http://www.kinopoisk.ru#{item.attributes['src']}" end images.reject{ |item| item !~ /images\/film\// }.first end def year if (tr = document.search("//table[@class='info ']")).present? else tr = document.search("//table[@class='info']") end tr.search("//tr").first.search("//td")[2].elements.xpath("a").children.text.to_i rescue nil end def budget document.search("//td[@class='dollar']").first.elements.xpath("a").children.text.gsub('$','') rescue nil end private def document @document ||= Kinopoisk::Movie.find_by_url(@url) end def self.find_by_url(url) begin Nokogiri::HTML(open(url, HEADERS)) rescue nil end end end end
module Twigg # Class which computes an approximation of the Flesch Reading Ease metric for # a given piece of English-language text. # # @see {http://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests} class Flesch def initialize(string) @string = string end def reading_ease # from wikipedia: ease = 206.835 - 1.015 * (total_words / total_sentences.to_f) - 84.6 * (total_syllables / total_words.to_f) # beware NaN values (usually caused by empty commit messages), # incompatible with JSON ease.nan? ? 206.835 : ease end private # Returns approximate count of words in the receiver. def total_words words.size end # Returns an array of "words" in the receiver. "Words" are defined as # strings of consecutive "word" characters (as defined by the regex # short-hand, `\w`). def words @words ||= @string.split(/\b/).select { |w| w.match /\w/ } end # Returns approximate total count of sentences in the receiver. def total_sentences @string.split(/\.+/).size end # Returns approximate total count of syllables in the receiever. def total_syllables words.inject(0) { |memo, word| memo + syllables(word) } end # Returns an approximate syllable count for `word`. # # Based on: {http://stackoverflow.com/questions/1271918/ruby-count-syllables} def syllables(word) # words of 3 letters or less count as 1 syllable; rare exceptions (eg. # "ion") are not handled return 1 if word.size <= 3 # - ignore final es, ed, e (except for le) # - consecutive vowels count as one syllable word. downcase. gsub(/W+/, ' '). # suppress punctuation sub(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, ''). sub(/^y/, ''). scan(/[aeiouy]{1,2}/). size end end end
class Message < ActiveRecord::Base attr_accessible :body after_create :notify private def notify Notification.create(event: "New Notification") end end
class TwilioAdapter def initialize @client = Twilio::REST::Client.new end def lookup(phone_number) number = phone_number.delete("^0-9") result = client.lookups.phone_numbers(number).fetch LookupResult.new(phone_number: result.phone_number) rescue Twilio::REST::RestError LookupResult.new(phone_number: nil) end def send_message(to:, from:, body: nil, media_url: nil, status_url: nil) client.messages.create( to: to, from: from, body: body, media_url: Array.wrap(media_url), status_callback: status_url ) SendMessageResult.new(sent?: true) rescue Twilio::REST::RestError => e SendMessageResult.new(sent?: false, error: e.error_message) end def create_call(url:, to:, from:, **options) participant = @client.calls.create( url: url, to: to, from: from, **options ) CallResult.new(sid: participant.sid, connected?: true) rescue Twilio::REST::RestError => e CallResult.new(connected?: false, error: e.error_message) end def end_conference(conference_sid) conference = @client.conferences(conference_sid).fetch conference.update(status: "completed") if conference.status != "completed" true rescue Twilio::REST::RestError false end def update_conference_participant(conference_sid, participant_sid, params: {}) @client.conferences(conference_sid).participants(participant_sid).update(params) true rescue Twilio::REST::RestError false end def update_call(sid:, url:, method: "POST") @client.calls(sid).update(url: url, method: method) true rescue Twilio::REST::RestError false end def cancel_call(sid) call = @client.calls(sid).fetch call = call.update(status: "canceled") unless call_completed?(call.status) if call.status == "canceled" true else end_call(sid) end rescue Twilio::REST::RestError false end def end_call(sid) call = @client.calls(sid).fetch call.update(status: "completed") unless call_completed?(call.status) true rescue Twilio::REST::RestError false end def request(url) response = JSON.parse( @client.request("api.twilio.com", "80", "GET", url).to_json ).with_indifferent_access Result.success(body: response[:body]) rescue Twilio::REST::RestError Result.failure("Failed to fetch URL") end private attr_reader :client def call_completed?(status) ["canceled", "completed", "failed", "busy", "no-answer"].include?(status) end end
require_relative "welcome_menu" require_relative "../data/order_handler" require_relative "../data/product_handler" require_relative "../data/database_handler" require "Date" #Menu which presents financial information to the user. module FinancialMenu #Shows financial main menu in the console. def FinancialMenu.show system "cls" puts "============================================================" puts "Financials:" puts " 1. Price list" puts " 2. Edit prices" puts " 3. Financial summary" puts " 0. Return" puts "============================================================" puts "What do you want to do?" get_choice end #Gets the user's choice (of which submenu to display). def FinancialMenu.get_choice choice = gets.chomp #Handles the input from the user. Easily extendable for later. case choice when "1" then show_prices when "2" then show_edit_prices when "3" then show_financials when "0" then WelcomeMenu::show else FinancialMenu.show end end #Shows a table of product prices to the user. def FinancialMenu.show_prices system "cls" #Gets the types of products in the system. product_categories = (ProductHandler::get_selection).keys.flatten #Calculates the format of the table to display the data in name_length = product_categories.sort { |a,b| a.to_s.length <=> b.to_s.length } table_length_name = name_length.last.to_s.length+5 bprice_length = product_categories.sort { |a,b| a.price_base.to_s.length <=> b.price_base.to_s.length } table_length_bprice = bprice_length.last.price_base.to_s.length+5 hprice_length = product_categories.sort { |a,b| a.price_hr.to_s.length <=> b.price_hr.to_s.length } table_length_hprice = hprice_length.last.price_hr.to_s.length+5 dprice_length = product_categories.sort { |a,b| a.price_day.to_s.length <=> b.price_day.to_s.length } table_length_dprice = dprice_length.last.price_day.to_s.length+5 table_format = " %-#{table_length_name}s %#{table_length_bprice}s %#{table_length_hprice}s %#{table_length_dprice}s" #Displays it in table. puts "============================================================" puts "Price list:\n\n" puts table_format % ["", "Base", "Hourly", "Daily"] puts table_format % ["Product", "Price", "Price", "Price"] puts " --------------------------------------------------------" product_categories.each { |product| puts table_format % [product.to_s, "$"+product.price_base.to_s, "$"+product.price_hr.to_s, "$"+product.price_day.to_s] } puts " --------------------------------------------------------" puts "\n" puts "============================================================" puts "Press Enter to return" gets FinancialMenu::show end #Shows submenu for product prices, and lets the user change the prices. def FinancialMenu.show_edit_prices system "cls" #Gets the types of products in the system. product_categories = (ProductHandler::get_selection).keys.flatten #Shows menu of products, letting the user choose which price to change. puts "============================================================" puts "Edit prices:" product_categories.each_index { |i| puts " #{i+1}. #{product_categories[i].to_s}" } puts " 0. Return" puts "============================================================" puts "What prices do you want to edit?" choice = gets.to_i #If choice is valid, let's the user change the products prices. if choice > 0 and choice <= product_categories.length system "cls" product = product_categories[choice-1] puts "Changing prices for #{product}".upcase puts "==========================================================" puts "Input a new price for each type.\n" + "The price will not change if the input is invalid or empty.\n\n" #Sets price only if it is valid (i.e. positive integer) puts "Base price:" b_price = Integer(gets.chomp) rescue b_price = -1 b_price_old = product.price_base product.price_base = b_price if b_price >= 0 puts "Hourly price:" h_price = Integer(gets.chomp) rescue h_price = -1 h_price_old = product.price_hr product.price_hr = h_price if h_price >= 0 puts "Daily price:" d_price = Integer(gets.chomp) rescue d_price = -1 d_price_old = product.price_day product.price_day = d_price if d_price >= 0 puts "\nNEW PRICES, #{product.to_s.upcase}:" puts "Base $#{product.price_base} (old $#{b_price_old})" puts "Hourly $#{product.price_hr} (old $#{h_price_old})" puts "Daily $#{product.price_day} (old $#{d_price_old})" puts "==========================================================" puts "PRESS ENTER TO RETURN" DatabaseHandler::update_prices(product, product.price_base, product.price_hr, product.price_day) gets FinancialMenu::show else #Else, either go back or inform the user of invalid menu choice. if choice == 0 FinancialMenu::show else Messenger::show_error("Invalid menu choice") unless choice == 0 show_edit_prices end end end #Shows table of a summary of the financials (income, total and by month). def FinancialMenu.show_financials system "cls" #gets all paid orders. orders = OrderHandler::get_orders paid_orders = orders.select { |order| not order.is_active? } #calculates total price total_price = 0 paid_orders.each { |order| total_price += order.get_price } #calculates how wide the table columns should be table_length_product = 0 table_length_customer = 0 table_length_price = 0 paid_orders.each do |order| prod_length = order.product.to_s.length table_length_product = prod_length if prod_length > table_length_product cust_length = order.customer.to_s.length table_length_customer = cust_length if cust_length > table_length_customer price_length = order.get_price.to_s.length table_length_price = price_length if price_length > table_length_price end table_length_product += 5 table_length_customer += 5 table_length_price += 5 #converts collected format data to format string table_format = " %-#{table_length_product}s %-#{table_length_customer}s %#{table_length_price}s" #Creates monthly financial data monthly_list = Hash.new paid_orders.each do |order| month = "#{Date::MONTHNAMES[order.stop_time.month]} #{order.stop_time.year}" unless monthly_list.has_key?(month) monthly_list[month] = [0, 0] end monthly_list[month][0] += order.get_price monthly_list[month][1] += 1 end #shows total, followed by monthly, income data puts "============================================================" puts "Financial summary:\n\n" puts table_format % ["Article", "Customer", "Income"] puts " --------------------------------------------------------" paid_orders.each { |order| puts table_format % [order.product.to_s, order.customer.to_s, "$"+order.get_price.to_s] } puts " --------------------------------------------------------" puts table_format % ["Total:", "", "$"+total_price.to_s] puts "\n" puts table_format % ["Month", "Rentals", "Income"] puts " --------------------------------------------------------" monthly_list.each { |month,info| puts table_format % [month, info[1].to_s, "$"+info[0].to_s]} puts " --------------------------------------------------------\n\n" puts "============================================================" puts "Press Enter to return" gets FinancialMenu::show end end
# == Schema Information # # Table name: students # # id :integer not null, primary key # email :string # first_name :string # graduation_year :integer # last_name :string # created_at :datetime not null # updated_at :datetime not null # describe Student, "#enrollments" do it "returns the enrollments that are associated to the student", points: 1 do student = Student.new student.save other_student = Student.new other_student.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.save other_enrollment = Enrollment.new other_enrollment.student_id = student.id other_enrollment.save not_this_enrollment = Enrollment.new not_this_enrollment.student_id = other_student.id not_this_enrollment.save expect(student.enrollments).to match_array([enrollment, other_enrollment]) end end describe Student, "#courses" do it "returns the courses that the student is enrolled in", points: 1 do student = Student.new student.save other_student = Student.new other_student.save course = Course.new course.save not_this_course = Course.new not_this_course.save other_course = Course.new other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.courses).to match_array([course, other_course]) end end describe Student, "#departments" do it "returns the departments that the student is taking courses in", points: 1 do student = Student.new student.save other_student = Student.new other_student.save math_department = Department.new math_department.name = "Math" math_department.save theater_department = Department.new theater_department.name = "Theater" theater_department.save physics_department = Department.new physics_department.name = "Physics" physics_department.save course = Course.new course.department_id = math_department.id course.save not_this_course = Course.new not_this_course.department_id = theater_department.id not_this_course.save other_course = Course.new other_course.department_id = physics_department.id other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.departments).to match_array([math_department, physics_department]) end end describe Student, "#departments" do it "doesn't return duplicate departments", points: 1 do student = Student.new student.save other_student = Student.new other_student.save math_department = Department.new math_department.name = "Math" math_department.save theater_department = Department.new theater_department.name = "Theater" theater_department.save physics_department = Department.new physics_department.name = "Physics" physics_department.save course = Course.new course.department_id = math_department.id course.save not_this_course = Course.new not_this_course.department_id = theater_department.id not_this_course.save other_course = Course.new other_course.title = "Physics 101" other_course.department_id = physics_department.id other_course.save last_course = Course.new last_course.title = "Advanced Physics" last_course.department_id = physics_department.id last_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.departments).to match_array([math_department, physics_department]) end end describe Student, "#year" do it "returns approximate year based off of graduation year", points: 1 do student = Student.new student.graduation_year = Date.today.year + 4 student.save expect(student.year).to eql("Freshman") end end describe Student, "#year" do it "returns approximate year based off of graduation year", points: 1 do student = Student.new student.graduation_year = Date.today.year + 3 student.save expect(student.year).to eql("Sophomore") end end describe Student, "#year" do it "returns approximate student year based off of graduation year", points: 1 do student = Student.new student.graduation_year = Date.today.year + 2 student.save expect(student.year).to eql("Junior") end end describe Student, "#year" do it "returns approximate student year based off of graduation year", points: 1 do student = Student.new student.graduation_year = Date.today.year + 1 student.save expect(student.year).to eql("Senior") end end describe Student, "#year" do it "returns approximate student year based off of graduation year", points: 1 do student = Student.new student.graduation_year = Date.today.year student.save expect(student.year).to eql("Alumnus") end end describe Student, "#full_name" do it "returns students full name", points: 1 do student = Student.new student.first_name = "Chloe" student.last_name = "Price" student.save expect(student.full_name).to eql("Chloe Price") end end describe Student, "#fall_classes" do it "returns students fall courses", points: 1 do student = Student.new student.save other_student = Student.new other_student.save course = Course.new course.term_offered = "Fall" course.save not_this_course = Course.new not_this_course.term_offered = "Winter" not_this_course.save other_course = Course.new other_course.term_offered = "Fall" other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.fall_classes).to match_array([course, other_course]) end end describe Student, "#winter_classes" do it "returns students winter courses", points: 1 do student = Student.new student.save other_student = Student.new other_student.save course = Course.new course.term_offered = "Winter" course.save not_this_course = Course.new not_this_course.term_offered = "Spring" not_this_course.save other_course = Course.new other_course.term_offered = "Winter" other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.winter_classes).to match_array([course, other_course]) end end describe Student, "#spring_classes" do it "returns students spring courses", points: 1 do student = Student.new student.save other_student = Student.new other_student.save course = Course.new course.term_offered = "Spring" course.save not_this_course = Course.new not_this_course.term_offered = "Summer" not_this_course.save other_course = Course.new other_course.term_offered = "Spring" other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.spring_classes).to match_array([course, other_course]) end end describe Student, "#summer_classes" do it "returns students summer courses", points: 1 do student = Student.new student.save other_student = Student.new other_student.save course = Course.new course.term_offered = "Summer" course.save not_this_course = Course.new not_this_course.term_offered = "Fall" not_this_course.save other_course = Course.new other_course.term_offered = "Summer" other_course.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = student.id enrollment.course_id = other_course.id enrollment.save enrollment = Enrollment.new enrollment.student_id = other_student.id enrollment.course_id = other_course.id enrollment.save expect(student.summer_classes).to match_array([course, other_course]) end end
# frozen_string_literal: true # rubocop:todo all shared_examples 'message with a header' do let(:collection_name) { 'test' } describe 'header' do describe 'length' do let(:field) { bytes.to_s[0..3] } it 'serializes the length' do expect(field).to be_int32(bytes.length) end end describe 'request id' do let(:field) { bytes.to_s[4..7] } it 'serializes the request id' do expect(field).to be_int32(message.request_id) end end describe 'response to' do let(:field) { bytes.to_s[8..11] } it 'serializes the response to' do expect(field).to be_int32(0) end end describe 'op code' do let(:field) { bytes.to_s[12..15] } it 'serializes the op code' do expect(field).to be_int32(opcode) end end end end
class SurveyTungsController < ApplicationController # GET /survey_tungs # GET /survey_tungs.xml def index @survey_tungs = SurveyTung.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @survey_tungs } end end # GET /survey_tungs/1 # GET /survey_tungs/1.xml def show @survey_tung = SurveyTung.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @survey_tung } end end # GET /survey_tungs/new # GET /survey_tungs/new.xml def new @survey_tung = SurveyTung.new #3.times do question = @survey_tung.question_tungs.build 2.times { question.answers.build } #end respond_to do |format| format.html # new.html.erb format.xml { render :xml => @survey_tung } end end # GET /survey_tungs/1/edit def edit @survey_tung = SurveyTung.find(params[:id]) end # POST /survey_tungs # POST /survey_tungs.xml def create @survey_tung = SurveyTung.new(params[:survey_tung]) respond_to do |format| if @survey_tung.save format.html { redirect_to(@survey_tung, :notice => 'Survey tung was successfully created.') } format.xml { render :xml => @survey_tung, :status => :created, :location => @survey_tung } else format.html { render :action => "new" } format.xml { render :xml => @survey_tung.errors, :status => :unprocessable_entity } end end end # PUT /survey_tungs/1 # PUT /survey_tungs/1.xml def update @survey_tung = SurveyTung.find(params[:id]) respond_to do |format| if @survey_tung.update_attributes(params[:survey_tung]) format.html { redirect_to(@survey_tung, :notice => 'Survey tung was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @survey_tung.errors, :status => :unprocessable_entity } end end end # DELETE /survey_tungs/1 # DELETE /survey_tungs/1.xml def destroy @survey_tung = SurveyTung.find(params[:id]) @survey_tung.destroy respond_to do |format| format.html { redirect_to(survey_tungs_url) } format.xml { head :ok } end end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe RailsAdmin::Config::Sections::List do describe '#fields_for_table' do subject { RailsAdmin.config(Player).list } it 'brings sticky fields first' do RailsAdmin.config Player do list do field(:number) field(:id) field(:name) { sticky true } end end expect(subject.fields_for_table.map(&:name)).to eq %i[name number id] end it 'keep the original order except for stickey ones' do RailsAdmin.config Player do list do configure(:number) { sticky true } end end expect(subject.fields_for_table.map(&:name)).to eq %i[number] + (subject.visible_fields.map(&:name) - %i[number]) end end end
require "helpers/integration_test_helper" require "integration/factories/images_factory" class TestImages < FogIntegrationTest include TestCollection def setup @subject = Fog::Compute[:google].images @factory = ImagesFactory.new(namespaced_name) end def test_get_specific_image image = @subject.get(TEST_IMAGE) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_specific_image_from_project image = @subject.get(TEST_IMAGE,TEST_IMAGE_PROJECT) refute_nil(image, "Images.get(#{TEST_IMAGE}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end def test_get_from_family image = @subject.get_from_family(TEST_IMAGE_FAMILY) refute_nil(image,"Images.get_from_family(#{TEST_IMAGE_FAMILY}) should not return nil") assert_equal(image.family, TEST_IMAGE_FAMILY) assert_equal(image.project, TEST_IMAGE_PROJECT) end end
class ConsumersController < ApplicationController skip_before_filter :verify_authenticity_token before_filter :authenticate! respond_to :json def index # TODO: Refactor hacky code if params[:producer_id] producer_id = params[:producer_id] producer = Producer.find(producer_id) return unauthorized unless owns(producer) consumers = producer.consumers respond_with(consumers, status: :ok, location: consumers_path) elsif params[:ids] consumer_ids = params[:ids] consumers = Consumer.find(consumer_ids) json_consumers = [] consumers.each do |consumer| return unauthorized unless owns(consumer) webhooks = consumer.webhooks consumer = consumer.as_json consumer[:webhook_ids] = webhooks.map(&:id) json_consumers << consumer end respond_with(json_consumers, status: :ok, location: consumers_path) end end def show consumer_id = params[:id] consumer = Consumer.find(consumer_id) return unauthroized unless owns(consumer) c = consumer.as_json webhooks = consumer.webhooks c[:failed_webhook_ids] = consumer.webhooks.select {|w| w.failed}.map(&:id) c[:webhook_count] = webhooks.count c[:webhook_ids] = webhooks.map(&:id) respond_with( { consumer: c}, status: :ok, location: consumer ) end def create consumer = consumer_params producer_id = consumer[:producer_id] producer = Producer.find(producer_id) return unauthorized unless owns(producer) consumer = Consumer.create(consumer) respond_with(consumer, status: :created, location: consumer) end def destroy stuff = {consumer: :destroyed} consumer = Consumer.find(params[:id]) consumer.destroy render json: stuff, status: :ok end private def consumer_params params.require(:consumer).permit(:name, :producer_id) end end
# Number letter counts # Problem 17 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, # then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out # in words, how many letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred # and forty-two) contains 23 letters and 115 (one hundred and fifteen) # contains 20 letters. The use of "and" when writing out numbers is in # compliance with British usage. def number_word_char_count (1..1000).map(&:english_word).join.count_chars end class String def count_chars self.gsub(/\s+/, '').length end end class Fixnum def english_word if self <= 20 number_words[self].capitalize else num_str = self.to_s.split('') case num_str.length when 2 # digits tens = number_words[(num_str.first + '0').to_i].capitalize ones = '' if num_str.last != '0' ones = ' ' + number_words[num_str.last.to_i].capitalize end tens + ones when 3 # digits hundreds = number_words[num_str.first.to_i].capitalize + ' Hundred' tens = '' ones = '' # 20 & above if num_str[1].to_i > 1 tens = number_words[(num_str[1] + '0').to_i].capitalize + ' ' if num_str.last != '0' ones = number_words[num_str.last.to_i].capitalize end end # teens if num_str[1] == '1' ones = number_words[num_str[1,2].join.to_i].capitalize end # no tens, just ones if num_str[1] == '0' && num_str.last != '0' ones = number_words[num_str.last.to_i].capitalize end if num_str[1,2] == %w[0 0] hundreds else hundreds + ' and ' + tens + ones end when 4 'One Thousand' end end end private def number_words { 0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety' } end end
module Kuhsaft class PublishState extend ActiveModel::Translation UNPUBLISHED = 0 PUBLISHED = 1 PUBLISHED_AT = 2 attr_reader :name attr_reader :value def initialize(options) options.each_pair { |k, v| instance_variable_set("@#{k}", v) if respond_to?(k) } end def self.all @all ||= [ PublishState.new(name: 'published', value: PUBLISHED), PublishState.new(name: 'unpublished', value: UNPUBLISHED), PublishState.new(name: 'published_at', value: PUBLISHED_AT) ] end end end
class Sellers::DashboardController < ApplicationController def show @seller = Seller.find_by(slug: params[:slug]) end end
class AddDeletedAtToUsers < ActiveRecord::Migration def change add_column :users, :deleted_at, :datetime add_column :users, :archive, :integer add_index :users, :archive end end
class Admin::AdminSettingController < AdminAreaController def index @new_organization = Organization.new end def add_organization if !params[:organization][:name].present? flash[:alert] = "Invalid organization name" else @new_organization = Organization.new(org_params) @new_organization.save flash[:notice] = "Organization added successfully" end redirect_to admin_admin_setting_index_path end def remove_organization if params[:remove_organization] != "" Organization.where(id: params[:remove_organization]).destroy_all flash[:notice] = "Organization removed successfully" else flash[:alert] = "Please select an organization" end redirect_to admin_admin_setting_index_path end def org_params params.require(:organization).permit(:name) end end
#!/usr/bin/env ruby # encoding: utf-8 # File: version.rb # Created: 23/05/2014 # # (c) Michel Demazure <michel@demazure.com> # production de rapports pour Jacinthe module JacintheReports # access methods for Jacinthe module Jaccess VERSION = '1.2.7' end end
class CreateSimCards < ActiveRecord::Migration def self.up create_table :sim_cards do |t| t.integer :sim_card_provider_id t.string :sim_number t.boolean :auto_order_card t.integer :sip_account_id t.string :auth_key t.string :state t.text :log t.timestamps end end def self.down drop_table :sim_cards end end
module IControl::LocalLB ## # The ProfileFTP interface enables you to manipulate a local load balancer's FTP profile. class ProfileFTP < IControl::Base set_id_name "profile_names" class ProfileFTPStatisticEntry < IControl::Base::Struct; end class ProfileFTPStatistics < IControl::Base::Struct; end class ProfileFTPStatisticEntrySequence < IControl::Base::Sequence ; end ## # Creates this FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def create super end ## # Deletes all FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_all_profiles super end ## # Deletes this FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_profile super end ## # Gets the statistics for all the FTP profile. # @rspec_example # @return [ProfileFTPStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def all_statistics super end ## # Gets the data channel port for this FTP profile. # @rspec_example # @return [ProfilePortNumber] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def data_channel_port super end ## # Gets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def default_profile super end ## # Gets a list of all FTP profile. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def list super end ## # Gets the state that if true, enable horizontal security for this FTP profile. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def security_enabled_request_state super end ## # Gets the statistics for this FTP profile. # @rspec_example # @return [ProfileFTPStatistics] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def statistics super end ## # Gets the state that if true, automatically translate RFC2428 extended requests EPSV # and EPRT to PASV and PORT when talking to IPv4 servers. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def translated_extended_request_state super end ## # Gets the version information for this interface. # @rspec_example # @return [String] def version super end ## # Determines whether this profile are base/pre-configured profile, or user-defined # profile. # @rspec_example # @return [boolean] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def is_base_profile super end ## # Resets the statistics for this FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def reset_statistics super end ## # Sets the data channel port for this FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfilePortNumber] :ports The data channel port for the specified FTP profiles. def set_data_channel_port(opts) opts = check_params(opts,[:ports]) super(opts) end ## # Sets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [String] :defaults The default profiles from which the specified profiles will get default values. def set_default_profile(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # Sets the state that if true, enable horizontal security for this FTP profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The translate extended request states for the specified profiles. def set_security_enabled_request_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the state that if true, automatically translate RFC2428 extended requests EPSV # and EPRT to PASV and PORT when talking to IPv4 servers. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The translate extended request states for the specified profiles. def set_translated_extended_request_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # A struct that describes statistics for a particular FTP profile. # @attr [String] profile_name The profile name. # @attr [IControl::Common::StatisticSequence] statistics The statistics for the profile. class ProfileFTPStatisticEntry < IControl::Base::Struct icontrol_attribute :profile_name, String icontrol_attribute :statistics, IControl::Common::StatisticSequence end ## # A struct that describes profile statistics and timestamp. # @attr [IControl::LocalLB::ProfileFTP::ProfileFTPStatisticEntrySequence] statistics The statistics for a sequence of profiles. # @attr [IControl::Common::TimeStamp] time_stamp The time stamp at the time the statistics are gathered. class ProfileFTPStatistics < IControl::Base::Struct icontrol_attribute :statistics, IControl::LocalLB::ProfileFTP::ProfileFTPStatisticEntrySequence icontrol_attribute :time_stamp, IControl::Common::TimeStamp end ## A sequence of ProfileFTP statistics. class ProfileFTPStatisticEntrySequence < IControl::Base::Sequence ; end end end
require 'rails_helper' RSpec.feature "Adding Comments" do before do @johndoe = User.create(:email =>"johndoe@gmail.com", :password => "password@123") @fred = User.create(:email =>"fred@gmail.com", :password => "password@123") @article = Article.create!(title: "Title one", body: "Body of article one", user: @johndoe) login_as(@johndoe) #uses Warden end scenario "- signed in user adds a comment" do visit '/' click_on @article.title expect(page).to have_content('Body of article one') fill_in 'Add a comment', with: 'An amazing Article' click_button 'Add Comment' expect(page).to have_content('Comment was added successfully') expect(page.current_path).to eq(article_path(@article)) expect(page).to have_content("An amazing Article") end end
# -*- coding: utf-8 -*- # localeの設定 execute "setting locale" do command "localedef -f UTF-8 -i ja_JP ja_JP" not_if "locale | grep ja_JP.UTF-8" end template "/etc/sysconfig/i18n" do owner 'root' group 'root' mode "0644" end
git "nosy" do repository "https://github.com/wkral/Nosy.git" reference "master" destination File.join(node.base.home_dir, node.nosy.dir) action :sync user node.base.user group node.base.group end template File.join(node.base.home_dir, "bin/nosy") do owner node.base.user group node.base.group mode "0755" source "nosy-shell.erb" end
class Booking < ApplicationRecord belongs_to :user belongs_to :product # validations validates :user, :product, :time, :status, presence: true end
Rails.application.routes.draw do root 'tweets#index' resources :tweets do resources :comments, only: %i[new edit update create destroy] end devise_for :users # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
class Agent < ActiveRecord::Base has_one :account, as: :accountable, dependent: :destroy belongs_to :company has_many :sent_messages, :as => :sender, :class_name => 'Message' has_many :received_messages, :as => :receiver, :class_name => 'Message' end
require 'rails_helper' RSpec.describe RatingsController, :type => :controller do let(:valid_attributes) { attributes_with_foreign_keys(:rating) } let(:invalid_attributes) { attributes_for(:invalid_rating) } context 'unauthenticated' do it 'redirects to sign in page when unauthenticated' do get :index expect(response).to redirect_to(new_user_session_path) end end context 'authenticated' do let(:user) { create(:user) } before(:each) do sign_in(user) end describe 'POST create' do describe 'with valid params' do it 'creates a new Recipe' do expect { post :create, rating: valid_attributes }.to change(Rating, :count).by(1) end it 'creates a new Rating with the valid attributes' do post :create, rating: valid_attributes new_rating = assigns(:rating).reload expect(new_rating.title).to eq valid_attributes['title'] expect(new_rating.comments).to eq valid_attributes['comments'] expect(new_rating.value).to eq valid_attributes['value'] expect(new_rating.recipe_id).to eq valid_attributes['recipe_id'] expect(new_rating.user_id).to eq user.id end it 'assigns a newly created rating as @rating' do post :create, rating: valid_attributes expect(assigns(:rating)).to be_a(Rating) expect(assigns(:rating)).to be_persisted end it 'redirects to the associated recipe ' do post :create, rating: valid_attributes expect(response).to redirect_to(controller: :recipes, action: :show, id: assigns(:rating).recipe_id ) end end describe 'with invalid params' do it 'does not save the rating in the database' do expect { post :create, rating: invalid_attributes }.to_not change(Rating, :count) end it 'assigns a newly created but unsaved rating as @rating' do post :create, rating: invalid_attributes expect(assigns(:rating)).to be_a_new(Rating) end it 're-renders the new template' do post :create, rating: invalid_attributes expect(response).to render_template('new') end end end describe 'PATCH update' do let(:existing_rating) do create(:rating_with_recipe, title: 'My Rating', user_id: user.id) end let(:updated_rating_params) do attributes_with_foreign_keys(:rating, title: 'New Title', value: 5, comments: 'New Comment') end describe 'with valid params' do it 'updates the requested rating' do patch :update, id: existing_rating, rating: updated_rating_params existing_rating.reload expect(existing_rating.title).to eq 'New Title' expect(existing_rating.value).to eq 5 expect(existing_rating.comments).to eq 'New Comment' expect(existing_rating.user_id).to eq user.id expect(existing_rating.recipe_id).to_not eq updated_rating_params[:recipe_id] end it 'assigns the requested rating as @rating' do patch :update, id: existing_rating, rating: updated_rating_params expect(assigns(:rating)).to eq(existing_rating) end it 'redirects to the associated recipe' do patch :update, id: existing_rating, rating: updated_rating_params expect(response).to redirect_to(controller: :recipes, action: :show, id: assigns(:rating).recipe_id ) end end describe 'with invalid params' do let(:updated_rating_params) do attributes_for(:rating_with_recipe, title: nil, user_id: user.id) end it 'does not update the requested rating when mandatory filed missing' do patch :update, id: existing_rating, rating: updated_rating_params existing_rating.reload expect(existing_rating.title).to eq 'My Rating' end it 'assigns the rating as @rating' do patch :update, id: existing_rating, rating: updated_rating_params expect(assigns(:rating)).to eq(existing_rating) end it 're-renders the edit template' do patch :update, id: existing_rating, rating: updated_rating_params expect(response).to render_template('edit') end end describe 'authorization failures' do let(:existing_rating_different_user) do create(:rating_with_recipe_and_user, title: 'My Rating') end it 'does not update the requested rating when rating belongs to someone else' do patch :update, id: existing_rating_different_user, rating: updated_rating_params existing_rating.reload expect(existing_rating.title).to eq 'My Rating' end end end describe 'DELETE destroy' do it 'destroys the requested rating' do rating = create(:rating) expect { delete :destroy, id: rating }.to change(Rating, :count).by(-1) end it 'redirects to the ratings list' do rating = create(:rating) delete :destroy, id: rating expect(response).to redirect_to(ratings_url) end end end end
# 10/10/13 DH: Let's Monkey-patch the baby...it's a Ruby thing... :) Spree::AppConfiguration.class_eval do #preference :use_store_credit_minimum, :float, :default => 0.0 preference :pencil_pleat_multiple, :float preference :deep_pencil_pleat_multiple, :float preference :double_pleat_multiple, :float preference :triple_pleat_multiple, :float preference :eyelet_pleat_multiple, :float # Following numbers are in 'cm' preference :returns_addition, :integer preference :side_hems_addition, :integer preference :turnings_addition, :integer preference :fabric_width, :integer # Following numbers are in '£/m' preference :cotton_lining, :float preference :cotton_lining_labour, :integer preference :blackout_lining, :float preference :blackout_lining_labour, :integer preference :thermal_lining, :float preference :thermal_lining_labour, :integer preference :curtain_maker_email, :string preference :width_help, :string preference :drop_help, :string preference :lining_help, :string preference :pleat_help, :string preference :romancart_storeid, :integer end # These values get automatically put into the 'spree_preferences' table in the DB on startup...nice! # (along with those from 'spree.rb' and the '/admin' interface) Spree::Config[:pencil_pleat_multiple] = 2.5 Spree::Config[:deep_pencil_pleat_multiple] = 2.5 Spree::Config[:double_pleat_multiple] = 2.75 Spree::Config[:triple_pleat_multiple] = 2.75 Spree::Config[:eyelet_pleat_multiple] = 2 # Following numbers are in 'cm' Spree::Config[:returns_addition] = 12 Spree::Config[:side_hems_addition] = 20 Spree::Config[:turnings_addition] = 20 Spree::Config[:fabric_width] = 137 # Following numbers are in '£/m' Spree::Config[:cotton_lining] = 4 Spree::Config[:blackout_lining] = 4.8 Spree::Config[:thermal_lining] = 4.5 Spree::Config[:cotton_lining_labour] = 4 Spree::Config[:blackout_lining_labour] = 4 Spree::Config[:thermal_lining_labour] = 4 #Spree::Config[:mails_from] = "sales@bespokesilkcurtains.com" Spree::Config[:curtain_maker_email] = "doughazell@gmail.com" Spree::Config[:width_help] = "Enter the length of the curtain pole or track in centimetres. Click for measuring advice." Spree::Config[:drop_help] = "Enter the drop of the curtain in centimetres. Click for measuring advice." Spree::Config[:lining_help] = "Choose cotton lined if you want a classic \"full\" curtain. Use blackout lining for bedrooms. Use thermal lining if you want to minimise your energy bills. Thermal lining lets in as much light as a standard cotton lining and is not a blackout lining option." Spree::Config[:pleat_help] = "Choose a pencil pleat for a more informal look and a single, double or triple pleat for a formal look." Spree::Config[:romancart_storeid] = 61379
class User < ActiveRecord::Base include NeoNode attr_accessible :password, :password_confirmation, :name attr_accessor :password, :password_confirmation has_many :emails, :conditions => {:verification_code => nil}, :dependent => :destroy has_many :emails_to_verify, :class_name => "Email", :foreign_key => :user_id, :conditions => "verification_code IS NOT NULL", :dependent => :destroy has_many :phones, :conditions => {:verification_code => nil}, :dependent => :destroy has_many :phones_to_verify, :class_name => "Phone", :foreign_key => :user_id, :conditions => "verification_code IS NOT NULL", :dependent => :destroy has_many :websites, :conditions => {:verification_code => nil}, :dependent => :destroy has_many :websites_to_verify, :class_name => "Website", :foreign_key => :user_id, :conditions => "verification_code IS NOT NULL", :dependent => :destroy has_many :identities, :after_add => :connect_via_neo4j, :dependent => :destroy has_many :profile_pictures has_many :education_attributes, :dependent => :destroy has_many :work_attributes, :dependent => :destroy has_many :posts has_many :applications validates_confirmation_of :password validates_presence_of :password, :on => :create validates_presence_of :name before_save :encrypt_password after_save :clear_background_picture after_save :set_mixpanel_attributes after_touch :set_mixpanel_attributes # after_create :create_credport_identity after_save :update_credport_identity def encrypt_password if password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) end end def clear_background_picture if self.background_picture_changed? and old = self.background_picture_was match = old.match /https?:\/\/(.*)\/(.*)/ if match[1] == "credport-backgroundpictures.s3.amazonaws.com" storage = Fog::Storage.new( :provider => 'AWS', :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'], :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :region => 'us-east-1' ) directory = storage.directories.get( 'credport-backgroundpictures' ) remote_file = directory.files.get( URI.unescape match[2] ) remote_file.destroy end end end def connect_via_neo4j(identity) neo.execute_query(" START identity=node:nodes_index(id = {identity}), user=node:nodes_index(id = {user}) CREATE UNIQUE user-[:identity]->identity ", { :identity => identity.neo_id, :user => self.neo_id }) if identity.persisted? end def create_credport_identity identity = Identity.new({ :uid => self.to_param, :name => self.name.empty? ? "Anonymous User" : self.name, :url => Rails.application.routes.url_helpers.user_url(self, :host => 'credport.org', :protocol => 'http'), :image => self.image, :context => IdentityContext.find_by_name(:credport) }) identity.user = self identity.save! end def update_credport_identity # self.credport_identity.update_attributes({ # :uid => self.to_param, # :name => self.name.empty? ? "Anonymous User" : self.name, # :url => Rails.application.routes.url_helpers.user_url(self, :host => 'credport.org', :protocol => 'https'), # :image => self.image, # :context => IdentityContext.find_by_name(:credport) # }) end # Querying def self.find_by_identity(uid, context_name) identity = Identity.includes(:user).find_by_uid_and_context_name(uid, context_name) identity.nil? ? nil : identity.user end def self.find_by_email(email) email = Email.find_by_email email email ? email.user : nil end def self.find_by_md5_hash(emailhash) email = Email.find_by_md5_hash emailhash email ? email.user : nil end def self.authenticate(email, password) user = self.find_by_email email user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) ? user : nil end # Attributes def first_name self.name.split(' ').first end def credport_identity credport_identity = self.identities.find_by_context_id IdentityContext.find_by_name :credport credport_identity = self.create_credport_identity unless credport_identity credport_identity end def third_identities self.identities.where 'context_id not in (?)', IdentityContext.find_by_name(:credport) end def image image = profile_pictures.first.url if profile_pictures.count > 0 if image.nil? image = ActionController::Base.asset_host + ActionController::Base.helpers.asset_path("user.png") image = 'http://localhost:5000/' + ActionController::Base.helpers.asset_path("user.png") if Rails.env == 'development' end image end def add_education(edu, application_name) school = Entity.find_or_create!(edu[:school]) EducationAttribute.create edu.except!(:school).merge({:added_by => Application.find_by_name(application_name), :user => self, :school => school}) end def add_workplace(work, application_name) ap work[:workplace] workplace = Entity.find_or_create!(work[:workplace]) WorkAttribute.create work.except!(:workplace).merge({:added_by => Application.find_by_name(application_name), :user => self, :workplace => workplace}) end def reviews Connection. joins(:to_identity, :context => :connection_context_protocols) .includes(:from) .includes(:to) .includes(:context) .where(:to_id => self.identities, :context_id => ConnectionContext.where({:connection_context_protocols => {:name => 'text-protocol'}}) ) end def credport_recommendation_written_by(writer) reviews = Recommendation.where(:recommender_id => writer.credport_identity, :recommended_id => self.credport_identity) end def credport_review_written_by(writer) reviews = Connection.where(:from_id => writer.credport_identity, :to_id => self.credport_identity, :context_id => ConnectionContext.where({:name => %w{credport_friend_recommendation credport_colleague_recommendation credport_family_recommendation credport_other_recommendation}}) ) end def credport_recommendations_to_approve Recommendation.where :recommended_id => self.credport_identity, :connection_in_db_id => nil end def to_param (id+100000).to_s(16).reverse end def serializable_hash(options = {}) hash = super(options) hash['id'] = to_param hash.delete 'password_hash' hash.delete 'password_salt' hash.delete 'created_at' hash.delete 'updated_at' hash end def self.find_by_param(param) self.find_by_id(param.reverse.to_i(16)-100000) if param end def self.find_param(param) self.find(param.reverse.to_i(16)-100000) end # tracking def mixpanel @mixpanel = Mixpanel::Tracker.new Rails.configuration.mixpanel_key, {} end def set_mixpanel_attributes # set which identities are connected setting_hash = {} self.identities.each{ |identity| setting_hash[identity.context.name] = 'true'} mixpanel.set(self.to_param, { :'$ip' => '', :name => self.name, :param => self.to_param, :created => self.created_at, :identities => self.identities.count, :photos => self.profile_pictures.count, :reviews => self.reviews.count }.merge(setting_hash), {}) mixpanel.set(self.to_param, { :email => self.emails.first.email }) unless self.emails.empty? end def mixpanel_set(props = {}, params = {}) mixpanel.delay(:queue => 'mixpanel').set self.to_param, props, params end def mixpanel_increment(props = {}, params = {}) mixpanel.delay(:queue => 'mixpanel').increment self.to_param, props, params end def mixpanel_track(event, props = {}, params = {}) props.merge!({:distinct_id => self.to_param, :mp_name_tag => "#{self.to_param} - #{self.name}" }) mixpanel.delay(:queue => 'mixpanel').track event, props, params end # actions def request_recommendation_by_email(email) end end
# frozen_string_literal: true module Dynflow module Utils # Heavily inspired by rubyworks/pqueue class PriorityQueue def initialize(&block) # :yields: a, b @backing_store = [] @comparator = block || :<=>.to_proc end def size @backing_store.size end def top @backing_store.last end def push(element) @backing_store << element reposition_element(@backing_store.size - 1) end def pop @backing_store.pop end def to_a @backing_store end private # The element at index k will be repositioned to its proper place. def reposition_element(index) return if size <= 1 element = @backing_store.delete_at(index) index = binary_index(@backing_store, element) @backing_store.insert(index, element) end # Find index where a new element should be inserted using binary search def binary_index(array, target) upper = array.size - 1 lower = 0 while upper >= lower center = lower + (upper - lower) / 2 case @comparator.call(target, array[center]) when 0 return center when 1 lower = center + 1 when -1 upper = center - 1 end end lower end end end end
class Customer attr_reader :name def initialize(name) @name = name @books = [] end def add_book_to_customer(book) @books << book end def customer_book_count return @books.count end end
# == Schema Information # # Table name: people # # id :integer not null, primary key # full_name :string(255) # title :string(255) # bio :text # created_at :datetime not null # updated_at :datetime not null # class Person < ActiveRecord::Base attr_accessible :bio, :full_name, :title, :addresses_attributes validates_presence_of :full_name validates_presence_of :title has_many :addresses accepts_nested_attributes_for :addresses end
class CreateRelatedTransactions < ActiveRecord::Migration def change create_table :related_transactions do |t| t.integer :transaction_id t.integer :other_transaction_id t.boolean :archived, default: false t.timestamps end add_index :related_transactions, :transaction_id add_index :related_transactions, :other_transaction_id add_index :related_transactions, :archived end end
class Neovim < Formula desc "Ambitious Vim-fork focused on extensibility and agility" homepage "http://neovim.io" head "https://github.com/neovim/neovim.git" option "without-debug", "Don't build with debInfo." depends_on "cmake" => :build depends_on "libtool" => :build depends_on "automake" => :build depends_on "autoconf" => :build depends_on "pkg-config" => :build depends_on "gettext" => :build depends_on :python => :recommended if MacOS.version <= :snow_leopard resource "libuv" do url "https://github.com/libuv/libuv/archive/v1.4.2.tar.gz" sha256 "b9e424f69db0d1c3035c5f871cd9d7a3f4bace0a4db3e974bdbfa0cf95f6b741" end resource "msgpack" do url "https://github.com/msgpack/msgpack-c/archive/cpp-1.0.0.tar.gz" sha256 "afda64ca445203bb7092372b822bae8b2539fdcebbfc3f753f393628c2bcfe7d" end resource "luajit" do url "http://luajit.org/download/LuaJIT-2.0.4.tar.gz" sha256 "620fa4eb12375021bef6e4f237cbd2dd5d49e56beb414bee052c746beef1807d" end resource "luarocks" do url "https://github.com/keplerproject/luarocks/archive/0587afbb5fe8ceb2f2eea16f486bd6183bf02f29.tar.gz" sha256 "c8ad50938fed66beba74a73621d14121d4a40b796e01c45238de4cdcb47d5e0b" end resource "unibilium" do url "https://github.com/mauke/unibilium/archive/v1.1.4.tar.gz" sha256 "8b8948266eb370eef8100f401d530451d627a17c068a3f85cd5d62a57517aaa7" end resource "libtermkey" do url "https://github.com/neovim/libtermkey/archive/8c0cb7108cc63218ea19aa898968eede19e19603.tar.gz" sha256 "21846369081e6c9a0b615f4b3889c4cb809321c5ccc6e6c1640eb138f1590072" end resource "libvterm" do url "https://github.com/neovim/libvterm/archive/1b745d29d45623aa8d22a7b9288c7b0e331c7088.tar.gz" sha256 "3fc75908256c0d158d6c2a32d39f34e86bfd26364f5404b7d9c03bb70cdc3611" end resource "jemalloc" do url "https://github.com/jemalloc/jemalloc/releases/download/3.6.0/jemalloc-3.6.0.tar.bz2" sha256 "e16c2159dd3c81ca2dc3b5c9ef0d43e1f2f45b04548f42db12e7c12d7bdf84fe" end def install ENV.deparallelize ENV["HOME"] = buildpath resources.each do |r| r.stage(buildpath/".deps/build/src/#{r.name}") end build_type = build.with?("debug") ? "RelWithDebInfo" : "Release" system "make", "CMAKE_BUILD_TYPE=#{build_type}", "DEPS_CMAKE_FLAGS=-DUSE_BUNDLED_BUSTED=OFF", "CMAKE_EXTRA_FLAGS=\"-DCMAKE_INSTALL_PREFIX:PATH=#{prefix}\"", "VERBOSE=1", "install" end def caveats; <<-EOS.undent If you want support for Python plugins such as YouCompleteMe, you need to install a Python module in addition to Neovim itself. Execute `:help nvim-python` in nvim or see http://neovim.io/doc/user/nvim_python.html for more information. EOS end test do (testpath/"test.txt").write("Hello World from Vim!!") system bin/"nvim", "-u", "NONE", "+s/Vim/Neovim/g", "+wq", "test.txt" assert_equal "Hello World from Neovim!!", File.read("test.txt").strip end end
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = "coda-jekyll-theme" spec.version = "0.1.15" spec.authors = ["Vipul Barodiya"] spec.email = ["sonumeewa@gmail.com"] spec.summary = "A theme for jekyll" spec.homepage = "https://www.github.com/sonumeewa/coda-jekyll-theme" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").select { |f| f.match(%r!^(assets|_layouts|_includes|_data|blog|index.html|_sass|LICENSE|README)!i) } spec.add_runtime_dependency "jekyll", "~> 3.8.5" spec.add_runtime_dependency "jekyll-paginate" spec.add_runtime_dependency "jekyll-seo-tag" spec.add_runtime_dependency "jekyll-sitemap" spec.add_development_dependency "bundler", "~> 2.0.2" spec.add_development_dependency "rake", "~> 12.0" end
puts "What is the hamster's name?" hamster_name = gets.chomp puts "What is the volume level from 1-10?" volume = gets.to_i puts "What is the fur color?" fur_color = gets.chomp puts "Is the hamster a good candidate for adoption?" adoption = gets.chomp puts "What is the hamster's estimated age?" age = gets.chomp if age.empty? age_mod = nil else age_mod = age.to_i end puts "The hamster's name is #{hamster_name}. The volume level is #{volume}. The fur color is #{fur_color}. If you were to ask if the hamster is a good candidate for adoption, then the answer would be #{adoption}. The age of the hamster is #{age_mod} years old!"
# coding: utf-8 require 'spec_helper' feature 'Create request', js: true do let!(:cluster) { factory!(:cluster) } let!(:project) { factory!(:project) } scenario 'with valid data' do sign_in project.user visit project_path(project) click_on 'Создать заявку' within '.popover' do fill_in 'CPU-часы', with: '10' fill_in 'Размер, GB', with: '10' click_button 'Создать' end expect(page).to have_content('Заявка создана') end end
class CreateVotations < ActiveRecord::Migration[5.0] def change create_table :votations do |t| t.references :user, foreign_key: true t.references :appointment, foreign_key: true t.integer :result t.boolean :access, default: false t.timestamps end end end
class Glslang < Formula desc "OpenGL and OpenGL ES reference compiler for shading languages" homepage "https://www.khronos.org/opengles/sdk/tools/Reference-Compiler/" url "https://github.com/KhronosGroup/glslang/archive/3.0.tar.gz" sha256 "91653d09a90440a0bc35aa490d0c44973501257577451d4c445b2df5e78d118c" head "https://github.com/KhronosGroup/glslang.git" bottle do cellar :any_skip_relocation sha256 "d5de78fc374f3c92cdf8f06f1518405346c63b42ffd7ad53bb153c27bd00a935" => :sierra sha256 "770943fa3e43b765e303cc88da1aa0bf2455f91cc0e84a636bfadd517cc87776" => :el_capitan sha256 "111206ad8b23ca9f78fa5657d371056e238f3eabf747d48001115d85f4ea88bf" => :yosemite sha256 "4d22c058983e127f3dbb02d86ef6d6cb94fcc5b87c5f3e46802b8b157d56e1c9" => :mavericks end depends_on "cmake" => :build def install mkdir "build" do system "cmake", "..", *std_cmake_args system "make" system "make", "install" # Version 3.0 of glslang does not respect the overridden CMAKE_INSTALL_PREFIX. This has # been fixed in master [1] so when that is released, the manual install commands should # be removed. # # 1. https://github.com/KhronosGroup/glslang/commit/4cbf748b133aef3e2532b9970d7365304347117a bin.install Dir["install/bin/*"] lib.install Dir["install/lib/*"] end end test do (testpath/"test.frag").write <<~EOS #version 110 void main() { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } EOS (testpath/"test.vert").write <<~EOS #version 110 void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } EOS system "#{bin}/glslangValidator", "-i", testpath/"test.vert", testpath/"test.frag" end end
require 'spec_helper' describe 'A product' do fixtures :products context 'being viewed by a search engine' do before do @product = products(:with_seo) visit product_path(@product) end it "should contain the SEO meta description" do within('head') do page.should have_css("meta[name=\"description\"][content=\"#{@product.seo_description}\"]") end end it "should contain the SEO meta keywords" do within('head') do page.should have_css("meta[name=\"keywords\"][content=\"#{@product.seo_keywords}\"]") end end end end
class MusicImporter attr_accessor :file_path def initialize(file_path) @path = file_path end def path @path end def files @files = [] Dir["#{@path}/*"].each do |file| file_name = file.split("mp3s/")[1] @files << file_name end @files end def import files = self.files files.each do |file| Song.create_from_filename(file) end end end
require 'rails_helper' describe Product do let(:product) {Product.create!(name: "race bike")} let(:user) {User.create!(first_name: "Rey", last_name: "Kuizon", email: "test@gmail.com", password: "password")} before do product.comments.create!(rating: 1, user: user, body: "Awful bike!") product.comments.create!(rating: 3, user: user, body: "Ok bike!") product.comments.create!(rating: 5, user: user, body: "Great bike!") end # TEST PRODUCT AVERAGE RATING context "when the product has comments" do it "returns an average rating of all comments" do expect(product.average_rating).to eq 3 end end # PRODUCT VALIDATION TEST context " validation test" do it "is not valid without a name" do expect(Product.new(name:nil)).not_to be_valid end it "is not valid without a description" do expect(Product.new(description:nil)).not_to be_valid end it "is not valid without a color" do expect(Product.new(colour:nil)).not_to be_valid end it "is not valid without a price" do expect(Product.new(price:nil)).not_to be_valid end it "is not valid without a image" do expect(Product.new(image_url:nil)).not_to be_valid end end end
require 'spec_helper' describe Yast do it "should have a version" do Yast.const_defined?("VERSION").should be_true end describe "Configuration" do Yast::Configuration::DEFAULT_OPTIONS.each_key do |key| it "should set the #{key}" do Yast.configure do |config| config.send("#{key}=", key) end Yast.send(key).should == key end end end describe "Reset configuration" do Yast::Configuration::DEFAULT_OPTIONS.each_pair do |key, value| it "should set the default #{key}" do Yast.configure do |config| config.send("#{key}=", key) config.reset end Yast.send(key).should == value end end end end
class BackgroundSerializer include FastJsonapi::ObjectSerializer attributes :background_url end
class DropDreamDatesTable < ActiveRecord::Migration[6.1] def change drop_table :dream_dates add_column :dreams, :date, :string end end
class MigrateUuidToVersionFive < ActiveRecord::Migration[5.0][5.0] def change change_table :approvals, id: :uuid do end end end
require 'spec_helper' describe Wildcat::Team do it { should validate_presence_of(:name) } it { should validate_presence_of(:nickname) } it { should validate_presence_of(:abbreviation) } it { should validate_presence_of(:location) } it { should validate_presence_of(:conference) } it { should validate_presence_of(:division) } end
# # Exodus::NewSeatGenerator # # MT19937に基づく擬似乱数生成器を用いて席替えを行う # シャッフルはメルセンヌツイスタに基づく擬似乱数生成器を生成して行います。 # 擬似乱数生成器のシード値は以下のフォーマットで定義するものとします。 # hhmmss (h : Hour, m : Minute, s : Second) require 'rubygems' require 'gtk2' $:.unshift File.dirname(__FILE__) module Exodus class NewSeatGenerator attr_accessor :name_array def load_students_name students = [] begin File.open("./bin/student_list", encoding: "utf-8").read.each_line { |line| students << line.to_s unless line.empty? } rescue => e puts "#{e} : Please prepare students list in bin/" end return students end # 黒板が見えなくて前の席を確保したい人のための機能 def removal_bad_eyesight(name_array, eject_target) eject_target.each { |t| name_array.delete(t.to_s) } return name_array end def save_new_seat(new_seat) file = File.open("./bin/student_list", "w") do |line| new_seat.each { |e| line.puts e } end end # Array#shuffle!(random: rng)を使う def generate(hhmmss, bad_eyesighter_names) self.name_array = removal_bad_eyesight(load_students_name, bad_eyesighter_names) self.name_array.shuffle!#(random: Random.new(hhmmss.to_i)) # name_array = load_students_name.shuffle!(random: Random.new(hhmmss.to_i)) entry_object_array = [] self.name_array.each do |name| entry = Gtk::Entry.new entry.set_text(" " + name.to_s) entry.set_editable(false) entry_object_array << entry end return entry_object_array end end end
require 'spec_helper' describe Estatic::Configuration do let(:file) { File.expand_path(File.dirname(__FILE__) + '/../fixtures/file.csv') } describe '.initialize' do it 'should set default values if no block is given' do configuration = described_class.new expect(configuration.chunk).to eq(8) expect(configuration.title).to eq('Estatic') end end describe 'attr_accessors' do let(:configuration) { described_class.new } describe '#chunk' do it 'returns configuration chunk value' do expect(configuration.chunk).to eq(8) end end describe '#chunk=' do it 'sets configuration chunk value' do configuration.chunk = 13 expect(configuration.chunk).to eq(13) end end describe '#title' do it 'returns configuration title value' do expect(configuration.title).to eq('Estatic') end end describe '#title=' do it 'sets configuration title value' do configuration.title = 'Estatico' expect(configuration.title).to eq('Estatico') end end end end
#require 'builder' class PayrollResultsXmlExporter < PayrollResultsExporter def initialize(company, department, person, person_number, payroll) super(company, department, person, person_number, payroll) end def export_xml builder = Builder::XmlMarkup.new(indent: 2) builder.instruct! :xml, version: "1.0", encoding: "UTF-8" payroll_description = payroll_period.description builder.payslips do |xml_payslips| xml_payslips.payslip do |xml_payslip| xml_payslip.employee do |xml_employee| xml_employee.personnel_number employee_numb xml_employee.common_name employee_name xml_employee.department employee_dept end xml_payslip.employer do |xml_employer| xml_employer.common_name employer_name end xml_payslip.results do |xml_results| xml_results.period payroll_description payroll_result.each do |payroll_result| tag_result = payroll_result.first val_result = payroll_result.last xml_results.result do |xml_result| item_export_xml(payroll_config, payroll_names, tag_result, val_result, xml_result) end end end end end builder.target! end def item_export_xml(pay_config, pay_names, tag_refer, val_result, xml_element) tag_item = pay_config.find_tag(val_result.tag_code) tag_concept = pay_config.find_concept(val_result.concept_code) tag_name = pay_names.find_name(tag_refer.code) val_result.export_xml(tag_refer, tag_name, tag_item, tag_concept, xml_element) end end
module ActiveRecordFiles class Collection attr_accessor :json_file delegate :[], :[]=, :to_json, :push, :length, to: :json_file def initialize(klass) @klass = klass @json_file = load_file(build_path(@klass)) end def write File.write(build_path(@klass), @json_file.to_json) end protected def load_file(path) if File.file?(path) JSON.parse File.read(path) else File.open(path, 'w') { |io| io.write([].to_json) } [] end end def build_path(klass) Pathname.new(klass.configurations[:root]) + "#{klass.name.underscore.pluralize}.json" end end end
Pod::Spec.new do |s| # 简介 s.name = 'JXTAlertManager' s.summary = 'A library easy to use UIAlertView and UIAlertViewController on iOS.' s.authors = { 'kukumaluCN' => '1145049339@qq.com' } s.social_media_url = 'https://www.jianshu.com/u/c8f8558a4b1d' # 版本信息 s.version = '1.0.2' s.license = { :type => 'MIT', :file => 'LICENSE' } # 地址 s.homepage = 'https://github.com/kukumaluCN/JXTAlertManager' s.source = { :git => 'https://github.com/kukumaluCN/JXTAlertManager.git', :tag => s.version.to_s } # 系统 s.requires_arc = true s.platform = :ios, '8.0' s.ios.deployment_target = '8.0' # 文件 s.source_files = 'JXTAlertManager/**/*.{h,m}' # s.public_header_files = 'JXTAlertManager/**/*.{h}' # s.resources = "JXTAlertManager/JXTAlertManager/*.xcassets" # 依赖 # s.libraries = 'sqlite3' # s.frameworks = 'UIKit', 'CoreFoundation', 'QuartzCore' # s.dependency "JSONKit", "~> 1.4" end
# Control the Loop # Modify the following loop so it iterates 5 times instead of just once. # iterations = 1 # # loop do # puts "Number of iterations = #{iterations}" # break # end # I tried, but wasn't exactly sure how to solve this. Funnily, I found it easy to formulate an answer in a while loop. It just made more sense. iterations = 0 while iterations <= 4 puts "Number of iterations = #{iterations}" iterations += 1 end # Solution # iterations = 1 # loop do # puts "Number of iterations = #{iterations}" # iterations += 1 # break if iterations > 5 # end # Funnily enough, I knew that we needed an increment and a conditional, but was fuzzy on where to put them. I suppose I could have spent some more time to figure it out, but when I could come up with a different solution, my brain just says: "Solved. Done. Moving on." # Another thing, this particular use of the "break if + condition" construction appears in the material for the first time here. It was not in the Loops chapter. I think had it been there, and I had a little practice, then I could have come up with the solution. # Just retyping a version of the solution for my brain/fingers x = 1 loop do puts "Something happens this many times: #{x}" x += 1 break if x >10 end