text
stringlengths
10
2.61M
class PagesController < ApplicationController skip_before_action :authenticate_user!, only: :home skip_after_action :verify_authorized, only: :home def home @musicians = User.all end end
class CreateTasks < ActiveRecord::Migration[5.1] def change create_table :tasks do |t| t.string :title , null: false, limit: 20 t.datetime :line t.text :memo , limit: 500 t.string :priority t.string :status t.string :label1 t.string :label2 t.integer :userId t.timestamps end end end
require './lib/discounts_page' require './lib/discount_parser' # Parses discount type by rules specified in config class DiscountTypeParser attr_reader :config def initialize(config) @config = config end def call puts "DiscountTypeParser: started parsing #{config[:url]}" discounts = page.discounts discounts += parse_next_pages if pagination? puts "DiscountTypeParser: finished parsing #{config[:url]}" discounts end private def page @page ||= DiscountsPage.new( discounts_url: config[:url], discounts_xpath: config[:discounts_xpath], discount_parser: discount_parser, pagination: config[:pagination], js: config[:js], scroll_to_load: config[:scroll_to_load] ) end def discount_parser DiscountParser.new(config[:discount]) end def parse_next_pages discounts = [] current_page = page while current_page.has_next? current_page = current_page.next discounts += current_page.discounts end discounts end def pagination? config[:pagination] end end
require 'rails_helper' RSpec.describe Task, :type => :model do it { should validate_presence_of :mailchimp_list_uid } it { should validate_presence_of :position } it { should validate_presence_of :name } it { should validate_presence_of :mission } end
#Source: http://kurtstephens.com/node/34 # Helps with date-intensive activities by about 15% require 'inline' class Fixnum inline do | builder | builder.c_raw ' static VALUE gcd(int argc, VALUE *argv, VALUE self) { if ( argc != 1 ) { rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", argc, 1); } /* Handle Fixnum#gcd(Fixnum) case directly. */ if ( FIXNUM_P(argv[0]) ) { /* fprintf(stderr, "Using Fixnum#gcd(Fixnum)\n"); */ long a = FIX2LONG(self); long b = FIX2LONG(argv[0]); long min = a < 0 ? - a : a; long max = b < 0 ? - b : b; while ( min > 0 ) { int tmp = min; min = max % min; max = tmp; } return LONG2FIX(max); } else { /* fprintf(stderr, "Using super#gcd\n"); */ return rb_call_super(1, argv); } } ' end end
class Admin::AcessoController < ApplicationController layout 'painel_admin' before_action :admin_logged_in? def index if params[:iduser].present? @usuario_id = params[:iduser] @usuario = Usuario.find(@usuario_id) @usuariocurso = Usuariocurso.select(" usuariocursos.*, cursos.name as nome_curso") .from(" usuariocursos, cursos, usuarios ") .where(" usuariocursos.usuario_id = usuarios.id AND usuariocursos.curso_id = cursos.id AND usuarios.id = ? ", @usuario_id); else redirect_to :controller => "usuarios", :action => "index" end end def delete Usuariocurso.find(params[:id]).destroy flash[:notice] = "Acesso removido com sucesso!" redirect_to :action => "index", :iduser => params[:iduser] end def novo @curso = Curso.all end def create usuarioDel = Usuariocurso.where(usuario_id: params[:acesso][:usuario_id]).where(curso_id: params[:acesso][:curso]).delete_all @usuariocurso = Usuariocurso.new @usuariocurso.usuario_id = params[:acesso][:usuario_id] @usuariocurso.curso_id = params[:acesso][:curso] @usuariocurso.data = Date.parse("#{params[:acesso][:data][6..10]}-#{params[:acesso][:data][3..4]}-#{params[:acesso][:data][0..1]}") if @usuariocurso.save flash[:notice] = "Curso atríbuido com sucesso!" redirect_to :action => "index", :iduser => params[:acesso][:usuario_id] else flash[:alert] = "Não foi possível atríbuir o curso!" render :novo end end def edit @usuario = Usuario.find_by(id: params[:iduser]) @curso = Curso.all @usuariocurso = Usuariocurso.find_by(id: params[:id]) end def update @curso = Usuariocurso.find_by(id: params[:acesso][:edit_id]) @curso.curso_id = params[:acesso][:curso] @curso.data = params[:acesso][:data] if @curso.save flash[:notice] = "Dados salvos com sucesso!" else flash[:alert] = "Não foi possível salvar os dados do faq!" end redirect_to :action => "index", :iduser => params[:acesso][:usuario_id] end end
require 'simp/cli/config/items/action/set_server_puppetdb_master_config_action' require_relative '../spec_helper' describe Simp::Cli::Config::Item::SetServerPuppetDBMasterConfigAction do before :each do @files_dir = File.expand_path( 'files', File.dirname( __FILE__ ) ) @tmp_dir = Dir.mktmpdir( File.basename(__FILE__) ) @hosts_dir = File.join(@tmp_dir, 'hosts') FileUtils.mkdir(@hosts_dir) @fqdn = 'hostname.domain.tld' @host_file = File.join( @hosts_dir, "#{@fqdn}.yaml" ) @puppet_env_info = { :puppet_config => { 'modulepath' => '/does/not/matter' }, :puppet_env_datadir => @tmp_dir } @ci = Simp::Cli::Config::Item::SetServerPuppetDBMasterConfigAction.new(@puppet_env_info) @ci.silent = true end after :each do FileUtils.remove_entry_secure @tmp_dir end describe '#apply' do before :each do item = Simp::Cli::Config::Item::CliNetworkHostname.new(@puppet_env_info) item.value = @fqdn @ci.config_items[item.key] = item item = Simp::Cli::Config::Item::PuppetDBMasterConfigPuppetDBServer.new(@puppet_env_info) item.value = 'puppet.test.local' @ci.config_items[item.key] = item item = Simp::Cli::Config::Item::PuppetDBMasterConfigPuppetDBPort.new(@puppet_env_info) item.value = 8139 @ci.config_items[item.key] = item end it 'adds puppetdb_port and puppetdb_server to <host>.yaml' do file = File.join(@files_dir, 'puppet.your.domain.yaml') FileUtils.copy_file file, @host_file @ci.apply expect( @ci.applied_status ).to eq :succeeded expected = File.join(@files_dir, 'host_with_puppetdb_config_added.yaml') expected_content = IO.read(expected) actual_content = IO.read(@host_file) expect( actual_content ).to eq expected_content end it 'replaces puppetdb_server and puppetdb_port in <host>.yaml' do @ci.config_items['puppetdb::master::config::puppetdb_server'].value = 'puppetdb.test.local' @ci.config_items['puppetdb::master::config::puppetdb_port'].value = 8239 file = File.join(@files_dir, 'host_with_puppetdb_config_added.yaml') FileUtils.copy_file file, @host_file @ci.apply expect( @ci.applied_status ).to eq :succeeded expected = File.join(@files_dir, 'host_with_puppetdb_config_replaced.yaml') expected_content = IO.read(expected) actual_content = IO.read(@host_file) expect( actual_content ).to eq expected_content end it 'fails when <host>.yaml does not exist' do @ci.apply expect( @ci.applied_status ).to eq :failed end it 'fails when cli::network::hostname item does not exist' do @ci.config_items.delete('cli::network::hostname') expect{ @ci.apply }.to raise_error( Simp::Cli::Config::MissingItemError, 'Internal error: Simp::Cli::Config::Item::SetServerPuppetDBMasterConfigAction' + ' could not find cli::network::hostname' ) end it 'fails when puppetdb::master::config::puppetdb_server item does not exist' do @ci.config_items.delete('puppetdb::master::config::puppetdb_server') file = File.join(@files_dir, 'puppet.your.domain.yaml') FileUtils.copy_file file, @host_file expect{ @ci.apply }.to raise_error( Simp::Cli::Config::MissingItemError, 'Internal error: Simp::Cli::Config::Item::SetServerPuppetDBMasterConfigAction' + ' could not find puppetdb::master::config::puppetdb_server' ) end it 'fails when puppetdb::master::config::puppetdb_port item does not exist' do @ci.config_items.delete('puppetdb::master::config::puppetdb_port') file = File.join( @files_dir,'puppet.your.domain.yaml') FileUtils.copy_file file, @host_file expect{ @ci.apply }.to raise_error( Simp::Cli::Config::MissingItemError, 'Internal error: Simp::Cli::Config::Item::SetServerPuppetDBMasterConfigAction' + ' could not find puppetdb::master::config::puppetdb_port' ) end end describe '#apply_summary' do it 'reports unattempted status when #apply not called' do expect(@ci.apply_summary).to eq( 'Setting of PuppetDB master server & port in SIMP server <host>.yaml unattempted') end end it_behaves_like "an Item that doesn't output YAML" it_behaves_like 'a child of Simp::Cli::Config::Item' end
class Laba11Result < ApplicationRecord validates :happy_numbers_quantity, uniqueness: true end
class Api::ProductsController < Api::ApplicationController before_filter :hard_authenticate!, only: :likes def index @products = Product.filter(params).feed(@current_user).page(params[:page]) end def show @product = Product.feed(@current_user).find(params[:id]) end def likes @product = Product.find(params[:id]) @like = @current_user.like! @product end end
class ActiveStore < PStore def initialize dbname super(dbname) end def create key, value transaction do db db[key] = value end end def read key transaction do db db[key] end end def update key, value exist = transaction do db db[key] end abort if exist.nil? transaction do db db[key] = value end end def delete transaction do db db.delete key end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "hashicorp/precise32" config.vm.define :web do |web_config| # alterei o ip externo para 192.168.10.30 web_config.vm.network "private_network", ip: "192.168.10.30" # agora o vagrant vai executar automaticamente # o provisionamento da VM com Puppet # executando o arquivo de manifest web.pp web_config.vm.provision "puppet" do |puppet| puppet.manifest_file = "web.pp" end end end
# frozen_string_literal: true require 'copilot/protos/cloud_controller_pb' require 'copilot/protos/cloud_controller_services_pb' module Cloudfoundry module Copilot class Client class PilotError < StandardError; end attr_reader :host, :port def initialize(host:, port:, client_ca_file:, client_key_file:, client_chain_file:, timeout: 5) @host = host @port = port @url = "#{host}:#{port}" @timeout = timeout @client_ca = File.open(client_ca_file).read @client_key = File.open(client_key_file).read @client_chain = File.open(client_chain_file).read end def health request = Api::HealthRequest.new service.health(request) end def upsert_route(guid:, host:, path: '', internal: false) route = Api::Route.new(guid: guid, host: host, path: path, internal: internal) request = Api::UpsertRouteRequest.new(route: route) service.upsert_route(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def delete_route(guid:) request = Api::DeleteRouteRequest.new(guid: guid) service.delete_route(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def map_route(capi_process_guid:, route_guid:, route_weight:) route_mapping = Api::RouteMapping.new(capi_process_guid: capi_process_guid, route_guid: route_guid, route_weight: route_weight) request = Api::MapRouteRequest.new(route_mapping: route_mapping) service.map_route(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def unmap_route(capi_process_guid:, route_guid:, route_weight:) route_mapping = Api::RouteMapping.new(capi_process_guid: capi_process_guid, route_guid: route_guid, route_weight: route_weight) request = Api::UnmapRouteRequest.new(route_mapping: route_mapping) service.unmap_route(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def upsert_capi_diego_process_association(capi_process_guid:, diego_process_guids:) request = Api::UpsertCapiDiegoProcessAssociationRequest.new( capi_diego_process_association: { capi_process_guid: capi_process_guid, diego_process_guids: diego_process_guids } ) service.upsert_capi_diego_process_association(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def delete_capi_diego_process_association(capi_process_guid:) request = Api::DeleteCapiDiegoProcessAssociationRequest.new( capi_process_guid: capi_process_guid ) service.delete_capi_diego_process_association(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end def bulk_sync(routes:, route_mappings:, capi_diego_process_associations:) request = Api::BulkSyncRequest.new( routes: routes, route_mappings: route_mappings, capi_diego_process_associations: capi_diego_process_associations ) service.bulk_sync(request) rescue GRPC::BadStatus => e raise Cloudfoundry::Copilot::Client::PilotError, "#{e.details} - #{e.metadata}" end private def tls_credentials @tls_credentials ||= GRPC::Core::ChannelCredentials.new(@client_ca, @client_key, @client_chain) end def service @service ||= Api::CloudControllerCopilot::Stub.new(@url, tls_credentials, timeout: @timeout) end end end end
require "rails_helper" RSpec.describe MainController do describe "GET root" do action { get :root } context 'then not login' do it { is_expected.to redirect_to(new_user_session_path) } end context 'then logined' do let(:current_user) { create :user } before { sign_in(current_user) } it { is_expected.to redirect_to(user_path(current_user)) } end end describe "GET whitelist" do let(:base_params) { Hash.new } let(:user) { create :user } action { get :whitelist, params: base_params.merge(format: :pac) } context "without auth token" do it { is_expected.to respond_with(:unauthorized) } end context "with auth token" do before { base_params[:auth_token] = user.authentication_token } it { is_expected.to respond_with(:moved_permanently) } end end describe "GET blacklist" do let(:base_params) { Hash.new } let(:user) { create :user } action { get :blacklist, params: base_params.merge(format: :pac) } context "without auth token" do it { is_expected.to respond_with(:unauthorized) } end context "with auth token" do before { base_params[:auth_token] = user.authentication_token } it { is_expected.to respond_with(:moved_permanently) } end end end
# RailsSettings Model class ShopConfig def self.shop_id ENV.fetch("SHOP_ID", "motzi") end def self.shop load_config_for_shop_id!(self.shop_id) # perf: reading from disk multiple times per request end def self.uses_sidekiq? self.shop.queue_adapter == "sidekiq" end def self.load_config_for_shop_id!(shop_id) Rails.application.config_for(:shop, env: shop_id).tap do |shop_hash| if shop_hash.empty? throw "No shop settings for #{shop_id}" end shop_hash[:id] = shop_id end end end
# @param {Integer[]} nums # @return {Integer} def max_sub_array(nums) max_sum = -Float::INFINITY cur_sum = 0 nums.each do |num| cur_sum = cur_sum + num max_sum = cur_sum if cur_sum > max_sum cur_sum = 0 if cur_sum < 0 end max_sum end puts max_sub_array [-2,1,-3,4,-1,2,1,-5,4]
# Problem 4: Largest palindrome product # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 99. # # Find the largest palindrome made from the product of two 3-digit numbers. # This methods compares a given number with the reverse of # the same number. It returns true if the given number is palindrome, # and false if not. def palindrome? (number) return number.to_s.reverse.eql? number.to_s end status = false largest, product, i, j = 0, 0, 999, 999 while i >= 100 j = 999 while j >= 100 product = i * j if palindrome?(product) and product > largest largest = product end j = j - 1 end i = i - 1 end puts "The largest palindrome product is #{largest}"
class SoldDoneController < ApplicationController def index #implementation year = Time.now.year - 2 @implementations = Implementation.where('N = ? AND YEAR(DAT) >= ?', 9, year).order("DAT DESC") @month_implementations_arr = [] Time.now.year.to_i.downto (Time.now.year - 1).to_i do |year| if year == Time.now.year months = Time.now.month else months = 12 end months.downto 1 do |month| if year == Time.now.year && month == Time.now.month @day = (Time.now - 1.day).day @dat = (Time.now - 1.day) @nowday = @dat.day impl = Implementation.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 9, year, month, @dat.day).first #raise impl.inspect while impl == nil do impl = Implementation.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 9, @dat.year, @dat.month, @dat.day).first @nowday = @dat.day @dat = @dat - 1.day @day = @day - 1 end @month_implementations_arr << impl.id if impl else @day = Time.new(year, month, 1).end_of_month.day @month_implementations_arr << Implementation.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 9, year, month, @day).first.id if Implementation.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 9, year, month, @day).first end @month_implementations = Implementation.where('id IN (?)',@month_implementations_arr).order("DAT DESC") end end #plan year = Time.now.year - 1 @plans = Asrt.where('N = ? AND YEAR(DAT) >= ?', 1, year).order("DAT DESC") @month_plans = [] @days_plans_arr = [] @planday = (Time.now - 1.day) @nowday = @planday pl = Asrt.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 1, @planday.year, @planday.month, @planday.day).first while pl == nil do @planday = @planday -1.day pl = Asrt.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 1, @planday.year, @planday.month, @planday.day).first @nowday = @planday end Time.now.year.to_i.downto (Time.now.year - 1).to_i do |year| if year == Time.now.year months = Time.now.month else months = 12 end months.downto 1 do |month| @day = Time.new(year,month,1).end_of_month.day @month_plans << Asrt.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 1, year, month, @day).first.id if Asrt.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 1, year, month, @day).first @days_plans_arr << Asrt.where('N = ? AND YEAR(DAT) = ? AND MONTH(DAT) = ? AND DAY(DAT) = ?', 1, year, month, @nowday.day).first end end @month_plans << Asrt.where('N = ?', 1).last.id @month_plans = Asrt.where('id IN (?)', @month_plans).order("DAT DESC") end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :user_interests, dependent: :destroy has_many :interests, through: :user_interests, dependent: :destroy has_many :messages, dependent: :destroy def conversations Conversation.includes(:messages) .where("user1_id = :id OR user2_id = :id", id: id) .order("messages.created_at DESC") end def other_user(conversation) conversation.users.include?(self) ? conversation.other_user(self) : nil end def unread_conversations conversations.select { |c| c.unread_messages?(self) } end def unread_conversations_count unread_conversations.count end def unread_conversations? unread_conversations_count > 0 end def one_avatar_url avatar_url ? avatar_url : "http://placehold.it/64x64" end end
class ApplicationController < ActionController::Base include Pundit # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized def after_sign_in_path_for(_resource) tasks_path end protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :username end private def user_not_authorized(exception) policy_name = exception.policy.class.to_s.underscore flash[:error] = I18n.t "pundit.#{policy_name}.#{exception.query}", default: 'Please sign in.' redirect_to(request.referrer || root_path) end end
require 'rest-client' before do unless request.path_info.include? '/docs' authorization_header = request.env['HTTP_AUTHORIZATION'].to_s begin response = RestClient.get('http://lb/users/by_token', headers={'Authorization' => authorization_header}) rescue RestClient::Unauthorized, RestClient::Forbidden, RestClient::UnprocessableEntity => err LOGGER.info "Unable to authorize user with header #{authorization_header}" halt 401 else USER = JSON.parse(response.body) LOGGER.info "Authorized user #{response.body}" end end end
require 'rails_helper' RSpec.describe User, type: :model do describe 'validations' do subject { FactoryBot.create(:user) } it { is_expected.to validate_presence_of(:email) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_uniqueness_of(:email) } end describe 'associations' do it { is_expected.to have_many(:user_images) } end describe 'authenticate' do let(:current_user) { create(:user) } it 'shoulda false' do expect(current_user.authenticate(password: '123321')).to be_falsy end it 'shoulda true' do expect(current_user.authenticate(password: '123123')).to be_truthy end end describe 'cryptography_password' do let(:current_user) { build(:user, password: '123123') } it 'shoulda cryptography_password' do expect(current_user.password).to eq('123123') current_user.save expect(current_user.password).to eq('4297f44b13955235245b2497399d7a93') end end end
class AddIsclosedToIncidents < ActiveRecord::Migration def change add_column :incidents, :is_closed, :boolean, default: false end end
module AdminArea module CardProducts class Form < Reform::Form feature Coercion property :annual_fee, type: Types::Form::Float property :bank_id, type: Types::Form::Int property :personal, type: Types::Form::Bool property :currency_id, type: Types::Form::Int property :image property :name, type: Types::StrippedString property :network, type: CardProduct::Network property :shown_on_survey, type: Types::Form::Bool property :type, type: CardProduct::Type validates :annual_fee, numericality: { greater_than_or_equal_to: 0 }, presence: true validates :bank_id, presence: true validates :image, presence: true, file_content_type: { allow: %w[image/jpeg image/jpg image/png] }, file_size: { less_than: 2.megabytes } validates :name, presence: true validates :network, presence: true validates :type, presence: true end end end
require "snapit/version" require "snapit/storage" require "snapit/script" require "snapit/engine" module Snapit def self.run!(path, storage) res = [] script = Snapit::Script.new(path, storage) Snapit::Engine.run(script.storage) do |driver| script.urls.each do |obj| obj.keys.each do |key| name = key url = obj[key] res << {path: driver.capture!(url, name)} end end end res end end
class BECoding::Command::Right def execute(rover) rover.spin_right end end
class ItemsController < ApplicationController def index items = Item.all render json: items end # GET /items/1 def show item = Item.find_by(params[:id]) render json: item end # POST /items def create # byebug item = Item.new(item_params) if item.save render json: item, status: :created, location: item else render json: {error: "Couldn't save"} end end # PATCH/PUT /items/1 def update item = Item.find_by(params[:id]) if item.update(item_params) render json: item else render json: {error: "Couldn't update"} end end # DELETE /items/1 def destroy item = Item.find(params[:id]) item.destroy render json: {message: "#{item.name} destroyed"} end private # Only allow a list of trusted parameters through. def item_params params.require(:item).permit(:name, :description, :condition, :price, :category_id) end end
# frozen_string_literal: true # Rating contains format for rating validation class Rating FORMAT = { numericality: { greater_than_or_equal_to: MIN_RATING, less_than_or_equal_to: MAX_RATING, only_float: true } }.freeze end
require 'spec_helper' describe Request do context 'factories', factory: true do it { create(:request).should be } it { create(:active_request).should be } it { create(:declined_request).should be } it { create(:closed_request).should be } it { create(:blocked_request).should be } end describe 'events' do let!(:user) { factory!(:sured_user) } let!(:project) { factory!(:project, user: user) } subject(:request) { factory!(:request, project: project) } let!(:account) { project.accounts.find_by_user_id(user.id) } describe '#activate' do before do request.activate! account.reload end it 'sets status to active' do should be_active end it 'sets related accounts cluster state to active' do account.should be_active end it 'requests maintain' do request.maintain_requested_at.should be end end describe '#block' do before do request.activate! request.block! account.reload end it 'sets status to blocked' do should be_blocked end it 'requests maintain' do request.maintain_requested_at.should be end end describe '#unblock' do before do request.activate! request.block! request.unblock! account.reload end it 'sets status to active' do should be_active end it 'requests maintain' do request.maintain_requested_at.should be end end describe '#close' do before do request.activate! request.block! request.close! account.reload end it 'sets status to closed' do should be_closed end it 'requests maintain' do request.maintain_requested_at.should be end end end end
class GetEpisodesJob < ActiveJob::Base queue_as :get_episodes rescue_from(StandardError) do |exception| Rails.logger.error "An exception happend #{exception.message}" end def perform(podcast) FetchFeed.new(podcast).fetch end end
# encoding: utf-8 # This is the source code for require_relative, a Ruby gem that backports that # particular feature to Ruby 1.8. # # Please check out the [README](https://github.com/steveklabnik/require_relative/blob/master/README.md) # for more information on how to build your own copy of the gem, as well as # contribute fixes. # require\_relative has no effect on Ruby 1.9 (or other versions that provide Kernel#require_relative # out of the box) unless Object.new.respond_to?(:require_relative, true) # Yep, you're looking at it! This gem is pretty small, and for good reason. # There's not much to do! We use split to find the filename that we're # looking to require, raise a LoadError if it's called in a context (like eval) # that it shouldn't be, and then require it via regular old require. # # Now, in 1.9, "." is totally removed from the $LOAD_PATH. We don't do that # here, because that would break a lot of other code! You're still vulnerable # to the security hole that caused this change to happen in the first place. # You will be able to use this gem to transition the code you write over to # the 1.9 syntax, though. def require_relative(relative_feature) file = caller.first.split(/:\d/,2).first raise LoadError, "require_relative is called in #{$1}" if /\A\((.*)\)/ =~ file require File.expand_path(relative_feature, File.dirname(file)) end end
Rails.application.routes.draw do resources :users, except: [:new] get 'welcome/index' get 'signup', to: 'users#new' resources :articles root 'welcome#index' end
class Room < ActiveRecord::Base has_many :reservations, dependent: :destroy end
require 'rails_helper' require 'database_cleaner' describe "Invoices API" do describe "GET /invoices" do it "returns a list of all invoices" do c1 = Customer.create c2 = Customer.create m1 = Merchant.create m2 = Merchant.create i1 = Invoice.create(status: "shipped", customer_id: c1.id, merchant_id: m1.id) i2 = Invoice.create(status: "other", customer_id: c2.id, merchant_id: m2.id) get "/api/v1/invoices" body = JSON.parse(response.body) invoices_status = body.map {|m| m["status"]} invoices_ids = body.map {|m| m["id"]} invoices_customer_id = body.map {|m| m["customer_id"]} invoices_merchant_id = body.map {|m| m["merchant_id"]} expect(response.status).to eq 200 expect(invoices_ids).to match_array([i1.id, i2.id]) expect(invoices_status).to match_array(["shipped", "other"]) expect(invoices_customer_id).to match_array([c1.id, c2.id]) expect(invoices_merchant_id).to match_array([m1.id, m2.id]) end end describe "GET /invoices/:id" do it "returns a specific invoice" do c1 = Customer.create m1 = Merchant.create i1 = Invoice.create(status: "shipped", customer_id: c1.id, merchant_id: m1.id) get "/api/v1/invoices/#{i1.id}" body = JSON.parse(response.body) invoice_status = body["status"] invoice_ids = body["id"] invoice_customer_id = body["customer_id"] invoice_merchant_id = body["merchant_id"] expect(response.status).to eq 200 expect(invoice_ids).to eq(i1.id) expect(invoice_status).to eq("shipped") expect(invoice_customer_id).to eq(c1.id) expect(invoice_merchant_id).to eq(m1.id) end end end
require File.expand_path("../../spec_helper", __FILE__) describe GoogleMapsApi do it "should get directions url" do url = "http://maps.googleapis.com/maps/api/directions/json" response = {routes: [{a: 1}]} query = {"origin" => "Chicago,IL", "destination" => "Denver,CO", "sensor" => "false"} req = stub_request(:get, url).with(:query => query) .to_return(:body => response.to_json, :status => 200) GoogleMapsApi.directions(query).should eq response req.should have_been_requested end it "should retrieve correct distance" do GoogleMapsApi.should_receive(:directions).with( {origin: "Chicago", destination: "Denver", sensor: false}) .and_return routes: [ {legs: [ {distance: {value: 1615982}} ]} ] GoogleMapsApi.distance("Chicago", "Denver").should eq 1615982 end it "should handle bad distance response" do GoogleMapsApi.should_receive(:directions).with( {origin: "Chicago", destination: "Denver", sensor: false}) .and_return routes: [garbage: "bad response"] GoogleMapsApi.distance("Chicago", "Denver").should eq nil end end
namespace :charts do task :migrate => :environment do ChartDoneRatio.delete_all ChartIssueStatus.delete_all ChartTimeEntry.delete_all Journal.all(:conditions => {:journalized_type => "Issue"}, :order => "id asc").each do |journal| journal.details.each do |detail| if detail.property == "attr" if detail.prop_key == "done_ratio" RedmineCharts::IssuePatch.add_chart_done_ratio(journal.issue.project_id, journal.issue.id, journal.issue.status_id, detail.value.to_i, journal.created_on) elsif detail.prop_key == "status_id" RedmineCharts::IssuePatch.add_chart_issue_status(journal.issue.project_id, journal.issue.id, detail.value.to_i, journal.created_on) end end end end TimeEntry.all(:order => "id asc").each do |t| RedmineCharts::TimeEntryPatch.add_chart_time_entry(t.project_id, t.issue_id, t.user_id, t.activity_id, t.hours, t.spent_on) end end end
# encoding: UTF-8 class Admin::PagesController < InheritedResources::Base before_filter :verify_admin before_action :authenticate_user! def create create! { admin_pages_url } end def update update! { admin_pages_url } end private def collection @pages ||= end_of_association_chain.paginate(:page => params[:page]) end def page_params params.require(:page).permit( :title, :subtitle, :description, :url, chapters_attributes: [:id, :title, :content, :position, :_destroy] ) end end
class Pantry attr_reader :stock def initialize @stock = Hash.new(0) # @stock_check = 0 end def stock_check(ingredient) @stock[ingredient] end def restock(ingredient, amount) @stock[ingredient] += amount end def enough_ingredients_for?(recipe) # Need to iterate over the ingredients required, within the recipe hash, to return a boolean determining if there are enough ingredients recipe.ingredients_required do |ingredient, amount| require "pry"; binding.pry end end
class FrameDescription < ActiveRecord::Base validates :text, presence:true validates :kind, presence:true def self.select_at_random body, kind="full" descriptions = search(body, kind) if descriptions.count == 0 raise "No descriptions available for frame(#{kind}) with: "+ "race(#{body.character.race.code}) & #{body.frame.inspect}" end Roll.random_from(descriptions) end # If there are descriptions written for that race use them, or use a general # description if not. def self.search body, kind race = body.character.race chain = FrameDescription. where(kind: kind). where("skin IS NULL OR skin = ?", race.skin) (FrameDescription.where(race:race.code).count > 0) ? chain.where(race:race.code) : chain.where(race:nil) end # Build a description in the seed. def self.manufacture text, params description = params.merge(text: text) description[:kind] = "full" unless params.keys.include?(:kind) create! description end end
require 'spec_helper' describe PostFacade do subject {PostFacade.new(user)} let(:user) { "testuser" } describe "#today_posts" do let(:result) { subject.today_posts } it "should return a PostCollectionDecorator" do expect(result).to be_kind_of PostCollectionDecorator end end describe "#user_future_posts" do let(:result) { subject.user_future_posts } it "should return a PostCollectionDecorator" do expect(result).to be_kind_of PostCollectionDecorator end end describe "#part_of_posts" do let(:result) { subject.part_of_posts } it "should return a PostCollectionDecorator" do expect(result).to be_kind_of PostCollectionDecorator end end end
class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :name t.string :image t.text :description_short t.text :description_long t.string :web_address t.string :user_id t.timestamps null: false end end end
class PropertiesController < ApplicationController before_action :set_property, only: [:show, :edit, :update, :destroy] def index @properties = Property.all end def show @station = Station.all end def new @property = Property.new 2.times { @property.stations.build } end def edit end def create @property = Property.new(property_params) if @property.save redirect_to @property, notice: 'Property was successfully created.' else render :new end end def update if @property.update(property_params) redirect_to @property, notice: 'Property was successfully updated.' else render :edit end end def destroy @property.destroy redirect_to properties_url, notice: 'Property was successfully destroyed.' end private def set_property @property = Property.find(params[:id]) end def property_params params.require(:property).permit(:property, :rent, :adress, :building_age, :remarks, stations_attributes: [:id, :name_of_railway_line, :statation_name, :how_many_minutes_walks]) end end
module ActiveRecord module ConnectionAdapters module Sqlserver module Quoting def quote(value, column = nil) case value when String, ActiveSupport::Multibyte::Chars if column && column.type == :binary column.class.string_to_binary(value) elsif quote_value_as_utf8?(value) || column && column.respond_to?(:is_utf8?) && column.is_utf8? quoted_utf8_value(value) else super end else super end end def quote_string(string) string.to_s.gsub(/\'/, "''") end def quote_column_name(column_name) column_name.to_s.split('.').map{ |name| name =~ /^\[.*\]$/ ? name : "[#{name}]" }.join('.') end def quote_table_name(table_name) return table_name if table_name =~ /^\[.*\]$/ quote_column_name(table_name) end def quoted_true '1' end def quoted_false '0' end def quoted_date(value) if value.acts_like?(:time) && value.respond_to?(:usec) "#{super}.#{sprintf("%03d",value.usec/1000)}" else super end end def quoted_utf8_value(value) "N'#{quote_string(value)}'" end def quote_value_as_utf8?(value) value.is_utf8? || enable_default_unicode_types end end end end end
class Category < ApplicationRecord has_many :camp_categories has_many :camps, through: :camp_categories end
class AddDogColumns < ActiveRecord::Migration[5.2] def change add_column :dogs, :sex, :string remove_column :dogs, :price end end
require "string_utils" class Pin < ActiveRecord::Base belongs_to :member def to_json(options = {}) result = {} result[:link] = self.link.purify_uri result[:title] = self.title.purify_html result[:created_on] = self.created_on.to_time.to_i result.to_json end end
require 'csv' require 'date' require 'stringio' require 'time' require 'zip' VpsAdmin::API::IncidentReports.config do module ParserUtils def strip_rt_prefix(subject) closing_bracket = subject.index(']') return subject if closing_bracket.nil? ret = subject[(closing_bracket+1)..-1].strip ret.empty? ? 'No subject' : ret end def strip_rt_header(body) ret = '' append = false body.split("\n").each do |line| if line.lstrip.start_with?('Ticket <URL: ') append = true elsif append ret << line end end ret.strip end end class ProkiParser < VpsAdmin::API::IncidentReports::Parser def parse incidents = {} message.attachments.each do |attachment| next if !attachment.content_type.start_with?('application/zip') string_io = StringIO.new(attachment.decoded) Zip::InputStream.open(string_io) do |io| while entry = io.get_next_entry next unless entry.name.end_with?('.csv') csv = CSV.parse(io.read, col_sep: ',', quote_char: '"', headers: true) csv.each do |row| time = Time.iso8601(row['time_detected']) assignment = find_ip_address_assignment(row['ip'], time: time) if assignment.nil? warn "PROKI: IP #{row['ip']} not found" next end key = "#{assignment.user_id}:#{assignment.vps_id}:#{assignment.ip_addr}:#{row['feed_name']}" incident = incidents[key] next if incident && incident.detected_at > time text = <<END Česky: Jménem Národního bezpečnostního týmu CSIRT.CZ Vám, v rámci projektu PRedikce a Ochrana před Kybernetickými Incidenty (PROKI, ID: VI20152020026) realizovaném v rámci Programu bezpečnostního výzkumu ČR na léta 2015 – 2020, zasíláme souhrnný report o IP adresách z Vaší sítě, které byly vyhodnoceny jako potenciálně škodlivé. English: On behalf of the National Security Team CSIRT.CZ and in connection with the project Prediction and Protection against Cybernetic Incidents (PROKI, ID: VI20152020026) implemented under the Security Research Program of the Czech Republic for the years 2015–2020, we are sending you a comprehensive report on the IP addresses from your network that have been evaluated as potentially harmful. Report: END row.each do |k, v| next if k == 'raw' text << sprintf("%-20s: %s\n", k, v) end text << sprintf("%-20s:\n", 'raw') raw = CSV.parse(row['raw'], col_sep: ',', quote_char: '"', row_sep: '\n', headers: true) raw.each do |raw_row| raw_row.each do |k, v| begin text << sprintf(" %-18s: %s\n", k, v) rescue Encoding::CompatibilityError next end end end incidents[key] = ::IncidentReport.new( user_id: assignment.user_id, vps_id: assignment.vps_id, ip_address_assignment: assignment, mailbox: mailbox, subject: "PROKI #{row['feed_name']} #{time.strftime('%Y-%m-%d')}", text: text, codename: row['feed_name'], detected_at: time, ) end end end end incident_list = incidents.values.sort do |a, b| a.detected_at <=> b.detected_at end now = Time.now proki_cooldown = ENV['PROKI_COOLDOWN'] ? ENV['PROKI_COOLDOWN'].to_i : 7*24*60*60 incident_list.select! do |incident| existing = ::IncidentReport.where( user_id: incident.user_id, vps_id: incident.vps_id, ip_address_assignment_id: incident.ip_address_assignment_id, codename: incident.codename, ).order('created_at DESC').take if existing && existing.created_at + proki_cooldown > now warn "PROKI: found previous incident ##{existing.id} for "+ "user=#{existing.user_id} vps=#{existing.vps_id} "+ "ip=#{existing.ip_address_assignment.ip_addr} code=#{existing.codename}" next(false) else incident.save! unless dry_run? next(true) end end if incident_list.empty? warn "PROKI: no new incidents found" end incident_list end end class BitNinjaParser < VpsAdmin::API::IncidentReports::Parser include ParserUtils def parse if /Your server ([^ ]+) has been/ !~ message.subject warn "BitNinja: source IP not found" return [] end addr_str = $1 body = message.decoded # . is instead of nonbreaking space... if /Timestamp \(UTC\):.(\d+\-\d+\-\d+ \d+:\d+:\d+)/ !~ body warn "BitNinja: timestamp not found" return [] end time_str = $1 begin time = DateTime.strptime("#{time_str} UTC", '%Y-%m-%d %H:%M:%S %Z').to_time rescue Date::Error => e warn "BitNinja: invalid timestamp #{time_str.inspect}" return [] end assignment = find_ip_address_assignment(addr_str, time: time) if assignment.nil? warn "BitNinja: IP #{addr_str} not found" return [] end subject = strip_rt_prefix(message.subject) text = strip_rt_header(body) if body.empty? warn "BitNinja: empty message body" return [] end incident = ::IncidentReport.new( user_id: assignment.user_id, vps_id: assignment.vps_id, ip_address_assignment: assignment, mailbox: mailbox, subject: subject, text: text, detected_at: time, ) incident.save! unless dry_run? [incident] end end class LeakIXParser < VpsAdmin::API::IncidentReports::Parser include ParserUtils def parse if /Critical security issue for ([^$]+)$/ !~ message.subject warn "LeakIX: source IP not found" return [] end addr_str = $1 body = message.decoded if /\|\s+Discovered\s+\|\s+(\d+ \w+ \d+ \d+:\d+ UTC)/ !~ body warn "LeakIX: timestamp not found" return [] end time_str = $1 begin time = DateTime.strptime("#{time_str} UTC", '%d %b %y %H:%M %Z').to_time rescue Date::Error => e warn "LeakIX: invalid timestamp #{$1.inspect}" return [] end assignment = find_ip_address_assignment(addr_str, time: time) if assignment.nil? warn "LeakIX: IP #{addr_str} not found" return [] end subject = strip_rt_prefix(message.subject) text = strip_rt_header(body) if body.empty? warn "LeakIX: empty message body" return [] end incident = ::IncidentReport.new( user_id: assignment.user_id, vps_id: assignment.vps_id, ip_address_assignment: assignment, mailbox: mailbox, subject: subject, text: text, detected_at: time, ) incident.save! unless dry_run? [incident] end end handle_message do |mailbox, message, dry_run:| check_sender = ENV['CHECK_SENDER'] ? %w(y yes 1).include?(ENV['CHECK_SENDER']) : true processed = true incidents = if /^\[rt\.vpsfree\.cz \#\d+\] PROKI \- upozorneni na nalezene incidenty/ =~ message.subject \ && (!check_sender || message['X-RT-Originator'].to_s == 'proki@csirt.cz') proki = ProkiParser.new(mailbox, message, dry_run: dry_run) proki.parse elsif /^\[rt\.vpsfree\.cz \#\d+\] Your server [^ ]+ has been registered as an attack source$/ =~ message.subject \ && (!check_sender || message['X-RT-Originator'].to_s == 'info@bitninja.com') bitninja = BitNinjaParser.new(mailbox, message, dry_run: dry_run) bitninja.parse elsif /^\[rt\.vpsfree\.cz \#\d+\] \[LeakIX\] Critical security issue for / =~ message.subject \ && (!check_sender || message['X-RT-Originator'].to_s == 'apiguardian@leakix.net') leakix = LeakIXParser.new(mailbox, message, dry_run: dry_run) leakix.parse else warn "#{mailbox.label}: unidentified message subject=#{message.subject.inspect}, originator=#{message['X-RT-Originator']}" processed = false [] end VpsAdmin::API::IncidentReports::Result.new( incidents: incidents, reply: { from: 'vpsadmin@vpsfree.cz', to: ['abuse-komentare@vpsfree.cz'], }, processed: processed, ) end end
class CashRegister attr_accessor :total, :discount, :cart def initialize(discount = 0) @total = 0 @discount = discount @cart = [] end def add_item(item, price, quantity = 1) item_hash = {} item_hash[:name] = item item_hash[:price] = price item_hash[:quantity] = quantity @cart << item_hash self.total += price * quantity end def apply_discount if @discount == 0 "There is no discount to apply." else self.total = total - total * discount.to_f / 100 "After the discount, the total comes to $#{total.to_i}." #I need to apply the discount to the total price of the register end end def items new_cart = [] @cart.each do |things| things[:quantity].times { new_cart << things[:name]} end new_cart end def void_last_transaction @cart.pop() self.total = 0 @cart.each {|item| self.total += item[:price] * item[:quantity] } self.total end end
class ProjectSchemasController < ApplicationController def index @project_schemas = ProjectSchema.all end def show @project_schema = ProjectSchema.find(params[:id]) end def new @project_schema = ProjectSchema.new end def create @project_schema = ProjectSchema.new(params[:project_schema]) if @project_schema.save redirect_to @project_schema, :notice => "Successfully created project schema." else render :action => 'new' end end def edit @project_schema = ProjectSchema.find(params[:id]) end def update @project_schema = ProjectSchema.find(params[:id]) if @project_schema.update_attributes(params[:project_schema]) redirect_to @project_schema, :notice => "Successfully updated project schema." else render :action => 'edit' end end def destroy @project_schema = ProjectSchema.find(params[:id]) @project_schema.destroy redirect_to project_schemas_url, :notice => "Successfully destroyed project schema." end end
class InfantFeedingMonth < ApplicationRecord has_many :baby_infant_feedings, dependent: :destroy end
require('minitest/autorun') require('minitest/rg') require_relative('../customer.rb') require_relative('../pub.rb') require_relative('../drink.rb') require_relative('../food.rb') class TestCustomer < Minitest::Test def setup() @drink1 = Drink.new("Jack Daniels Tennessee Whiskey", 26, 4) @drink2 = Drink.new("Grey Goose Vodka", 39, 8) @food1 = Food.new("Roast Chicken", 15, 10) @food2 = Food.new("Baked Potatoe", 5, 4) @customer1 = Customer.new("Vin Diesel", 10000, 18) @customer2 = Customer.new("Vin Diesel", 10000, 17) end def test_customer_has_name() assert_equal("Vin Diesel", @customer1.name) end def test_customer_has_cash() assert_equal(10000, @customer1.wallet) end def test_customer_drunkenness_starts_at_zero() assert_equal(0, @customer1.drunkenness_level()) end def test_customers_had_zero_drinks assert_equal(0, @customer1.drink_count()) end def test_customer_have_drink() @customer1.add_drink(@drink1) assert_equal(1, @customer1.drink_count()) end def test_can_get_total_drunkenness() @customer1.add_drink(@drink1) @customer1.add_drink(@drink2) @customer1.add_drink(@drink1) assert_equal(16, @customer1.get_total_drunkenness()) end def test_can_decrease_wallet() @customer1.decrease_wallet(39) assert_equal(9961, @customer1.wallet) end def test_check_age__customer_old_enough assert_equal(18, @customer1.age) end def test_check_age__customer_underaged assert_equal("To Young!", @customer2.check_age) end def test_increase_drunk_level @customer1.increase_drunk_level(@drink2) assert_equal(8, @customer1.drunkenness_level) end def test_food_reduces_drunkenness_level @customer1.increase_drunk_level(@drink2) @customer1.decrease_drunk_level(@food2) assert_equal(4, @customer1.drunkenness_level) end end
class AddForceMoteurToMachines < ActiveRecord::Migration[5.2] def change add_column :machines, :force_moteur, :integer end end
# == Schema Information # # Table name: reviews # # id :bigint(8) not null, primary key # user_id :integer # restaurant_id :integer # stars :integer not null # description :text default(""), not null # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' require 'date' RSpec.describe Review, :type => :model do # pending "add some examples to (or delete) #{__FILE__}" before(:all) do @restaurant = FactoryBot.create(:restaurant, :taizu) end def get_review(stars) create(:review, stars: stars, restaurant_id: @restaurant.id) end describe 'data integrity' do context 'has valid required fields' do subject(:med_review) { get_review(3) } it 'has a user' do expect(User.find(med_review.user_id)).to be_truthy end it 'has a restaurant' do expect(Restaurant.find(med_review.restaurant_id)).to be_truthy end it 'has a stars rank' do expect(med_review.stars).to be_a(Numeric) end end context 'no duplicate reviews' do it 'has different stars, user and restaurant combination per day' do Review.all.group_by { |review| review.stars }.each do |stars, reviews| unique_reviews = reviews.uniq { |review| [review.user_id, review.restaurant_id, Time.at(review.created_at).to_date] } expect(unique_reviews.size).to eq(reviews.size) end end end end describe 'active record callbacks' do before(:each) do @reviewed_restaurant = FactoryBot.create :restaurant, :taizu @two_stars_review = FactoryBot.create( :review, restaurant_id: @reviewed_restaurant.id, stars: 2 ) @four_stars_review = FactoryBot.create( :review, restaurant_id: @reviewed_restaurant.id, stars: 4 ) end context 'after save' do it 'recalculates the reviews related restaurant record average rating score' do expect(Restaurant.find(@reviewed_restaurant.id).rating).to( eq((@two_stars_review.stars + @four_stars_review.stars) / 2) ) end end context 'after destroy' do it 'recalculates the reviews related restaurant record average rating score' do @two_stars_review.destroy! expect(Restaurant.find(@reviewed_restaurant.id).rating).to( eq((@four_stars_review.stars)) ) end end end end
Then(/^I click the file a dispute link$/) do on(TransactionsDetailsPage) do |page| page.wait_for_td_page_load page.click_first_transaction_dispute_link end end And(/^I should see the dispute confirmation modal$/) do on(TransactionsDetailsPage) do |page| page.wait_for_dispute_confirmation_modal end end And(/^the dispute confirmation modal should have the correct content$/) do on(TransactionsDetailsPage) do |page| contents = page.get_dispute_confirmation_modal_elements data = data_for(:td_dispute_interstitial_modal_values) contents[:header].text.include? data["header"] contents[:closeBtn].text.should == data["close_button"] contents[:cancelBtn].text.should == data["cancel_button"] contents[:fileDisputeBtn].text.should == data["file_dispute_button"] contents[:content].text.should == data["body_content"] end end And(/^the file dispute button should call dispute claim$/) do on(TransactionsDetailsPage) do |page| page.validate_file_dispute_button_calls_dispute_claim.should == true end end
# frozen_string_literal: true require_relative '../rest/utils' require_relative '../account' require_relative '../relationship' module Mastodon module REST module Accounts include Mastodon::REST::Utils # Retrieve account of authenticated user # @return [Mastodon::Account] def verify_credentials perform_request_with_object(:get, '/api/v1/accounts/verify_credentials', {}, Mastodon::Account) end # Update authenticated account attributes # @param options [Hash] # @option options display_name [String] The name to display in the # user's profile # @option options note [String] A new biography for the user # @option options avatar [String] A base64 encoded image to display as # the user's avatar # @option options header [String] A base64 encoded image to display as # the user's header image # @option options bot [Boolean] A boolean indicating if this account # is automated # @return [Mastodon::Account] def update_credentials(opts = {}) opts[:fields] and opts.delete(:fields).each_with_index { |f, i| opts["fields_attributes[#{i}][name]"] = f[:name] opts["fields_attributes[#{i}][value]"] = f[:value] } perform_request_with_object(:patch, '/api/v1/accounts/update_credentials', opts, Mastodon::Account) end # Retrieve account # @param id [Integer] # @return [Mastodon::Account] def account(id) perform_request_with_object(:get, "/api/v1/accounts/#{id}", {}, Mastodon::Account) end # Get a list of followers # @param id [Integer] # @return [Mastodon::Collection<Mastodon::Account>] def followers(id) perform_request_with_collection(:get, "/api/v1/accounts/#{id}/followers", {}, Mastodon::Account) end # Get a list of followed accounts # @param id [Integer] # @return [Mastodon::Collection<Mastodon::Account>] def following(id) perform_request_with_collection(:get, "/api/v1/accounts/#{id}/following", {}, Mastodon::Account) end # Follow a remote user # @param uri [String] The URI of the remote user, in the format of # username@domain # @return [Mastodon::Account] def follow_by_uri(uri) perform_request_with_object(:post, '/api/v1/follows', { uri: uri }, Mastodon::Account) end # Get account endorsements # @return [Mastodon::Collection<Mastodon::Account>] def endorsements perform_request_with_collection(:get, '/api/v1/endorsements', {}, Mastodon::Account) end # Add an endorsement # @param id [Integer] # @return [Mastodon::Relationship] def add_endorsement(id) perform_request_with_object(:post, "/api/v1/accounts/#{id}/pin", {}, Mastodon::Relationship) end # Remove an endorsement # @param id [Integer] # @return [Mastodon::Relationship] def remove_endorsement(id) perform_request_with_object(:post, "/api/v1/accounts/#{id}/unpin", {}, Mastodon::Relationship) end # Get user mutes # @return [Mastodon::Collection<Mastodon::Account>] def mutes perform_request_with_collection(:get, '/api/v1/mutes', {}, Mastodon::Account) end # Get user blocks # @param options [Hash] # @option options :limit [Integer] # @return [Mastodon::Collection<Mastodon::Account>] def blocks(options = {}) perform_request_with_collection(:get, '/api/v1/blocks', options, Mastodon::Account) end # Report an account # @param id [Integer] # @param options [Hash] # @option options :status_ids [Array<Integer>] # @option options :comment [String] def report(id, options = {}) options[:account_id] = id !perform_request(:post, '/api/v1/reports', options).nil? end # Gets follow requests # @param options [Hash] # @option options :limit [Integer] # @return [Mastodon::Collection<Mastodon::Account>] def follow_requests(options = {}) perform_request_with_collection(:get, '/api/v1/follow_requests', options, Mastodon::Account) end # Accept a follow request # @param id [Integer] # @return [Boolean] def accept_follow_request(id) !perform_request(:post, "/api/v1/follow_requests/#{id}/authorize").nil? end # Reject follow request # @param id [Integer] # @return [Boolean] def reject_follow_request(id) !perform_request(:post, "/api/v1/follow_requests/#{id}/reject").nil? end end end end
# frozen_string_literal: true case expression [when expression [, expression ...] [then] code ]... [else code ] end def get_day(day) day_name = case day when 'mon' 'monday' when 'tue' 'Tuesday' when 'wed' 'Wednsday' when 'thu' 'Thursday' when 'fri' 'friday' when 'sat' 'Saturday' when 'sun' 'Sunday' else 'invalid' end day_name end puts get_day('mon')
class Admin::ContentsController < Admin::BaseController before_filter :load_page before_filter :load_row before_action :set_content, only: [:edit, :destroy] def new load_contents_if_needed @content = @row.contents.new respond_with(:admin, @page, @row, @content) end def edit end def create unless params[:content][:content_type] == "" subclass = params[:content][:content_type].constantize @content = subclass.create(row_id: @row.id, size: params[:content][:size]) else @content = Content.new(row: @row) @content.errors.add(:base, 'Escolha um tipo') end p @content.errors.to_a respond_with(:admin, @page, @row, @content) end def update @content = Content.find(params[:id]) params_name = @content.type.humanize.parameterize('_') cleaned_params = params.require(params_name).permit(:size) @content.update(cleaned_params) respond_with(:admin, @page, @row, @content) end def destroy @content.destroy respond_with(:admin, @page, @row, @content) end def sort params[:content].each_with_index do |id, index| Content.find(id).update_attributes(position: index+1) end render nothing: true end private def load_contents_if_needed unless Rails.env.production? Contents::Banner Contents::Text Contents::Client Contents::Case Contents::Testimonial Contents::Linkblock Contents::Attachment end end def load_row @row = Row.find(params[:row_id]) end def set_content @content = Content.find(params[:id]) end def content_params params.require(:content).permit(:position, :size) end end
class Ivent < ApplicationRecord belongs_to :user has_many :photos validates :ivent_title, presence: true, length: { maximum: 30 } validates :ivent_content, presence: true, length: { maximum: 100 } def self.search(search) #self.でクラスメソッドとしている if search # Controllerから渡されたパラメータが!= nilの場合は、titleカラムを部分一致検索 Ivent.where(['ivent_title LIKE ?', "%#{search}%"]) else Ivent.all #全て表示。 end end end
require 'test_helper' class CallthroughTest < ActiveSupport::TestCase def setup # Basic setup of a new system # germany = Country.create(:name => "Germany", :country_code => "49", :international_call_prefix => "00", :trunk_prefix => "0" ) Language.create(:name => 'Deutsch', :code => 'de') AreaCode.create(:country => germany, :name => "Bendorf", :area_code => "2622") @gemeinschaft_setup = GemeinschaftSetup.new @gemeinschaft_setup.country = Country.first @gemeinschaft_setup.language = Language.first current_user = @gemeinschaft_setup.build_user( :user_name => I18n.t('gemeinschaft_setups.initial_setup.admin_name'), :male => true, :email => 'admin@localhost', :first_name => 'Max', :last_name => 'Mustermann', :password => 'xxxxxxxxxx', :password_confirmation => 'xxxxxxxxxx', :language_id => Language.first.id, ) @sip_domain = @gemeinschaft_setup.build_sip_domain( :host => '10.0.0.1', :realm => '10.0.0.1', ) @gemeinschaft_setup.save super_tenant = Tenant.create( :name => GsParameter.get('SUPER_TENANT_NAME'), :country_id => @gemeinschaft_setup.country.id, :language_id => @gemeinschaft_setup.language_id, :description => I18n.t('gemeinschaft_setups.initial_setup.super_tenant_description'), ) # Admin super_tenant.tenant_memberships.create(:user_id => @gemeinschaft_setup.user.id) # Create the Super-Tenant's group: super_tenant_super_admin_group = super_tenant.user_groups.create(:name => I18n.t('gemeinschaft_setups.initial_setup.super_admin_group_name')) super_tenant_super_admin_group.user_group_memberships.create(:user_id => @gemeinschaft_setup.user.id) # Create the tenant. # @tenant = @sip_domain.tenants.build(:name => 'AMOOMA GmbH') @tenant.country = Country.first @tenant.language = Language.first @tenant.internal_extension_ranges = '10-20' @tenant.did_list = '02622-70648-x, 02622-706480' @tenant.save @tenant.tenant_memberships.create(:user_id => current_user.id) current_user.update_attributes!(:current_tenant_id => @tenant.id) # The first user becomes a member of the 'admin' UserGroup # admin_group = @tenant.user_groups.create(:name => I18n.t('gemeinschaft_setups.initial_setup.admin_group_name')) admin_group.users << current_user # User group # user_group = @tenant.user_groups.create(:name => I18n.t('gemeinschaft_setups.initial_setup.user_group_name')) user_group.users << current_user # Generate the internal_extensions # @tenant.generate_internal_extensions # Generate the external numbers (DIDs) # @tenant.generate_dids end test 'the setup should create a valid system' do # Basics # assert_equal 1, Country.count assert_equal 1, Language.count # Testing the installation # assert @gemeinschaft_setup.valid? assert @sip_domain.valid? assert current_user.valid? assert @tenant.valid? assert_equal 0, SipAccount.count assert_equal 2, Tenant.count assert_equal 1, User.count # Check the amount of phone_numbers # assert_equal 11, @tenant.phone_number_ranges.find_by_name(GsParameter.get('INTERNAL_EXTENSIONS')).phone_numbers.count assert_equal 12, @tenant.phone_number_ranges.find_by_name(GsParameter.get('DIRECT_INWARD_DIALING_NUMBERS')).phone_numbers.count end test 'that a callthrough can only be created with at least one DID' do assert_equal 0, Callthrough.count did = @tenant.phone_number_ranges.find_by_name(GsParameter.get('DIRECT_INWARD_DIALING_NUMBERS')).phone_numbers.first callthrough = @tenant.callthroughs.build assert !callthrough.valid? callthrough.phone_numbers.build(:number => did.number) assert callthrough.save assert_equal 1, Callthrough.count end # TODO Activate this after fixing unique phone_number # # test 'that one DID can not be used by two different callthroughs' do # assert_equal 0, Callthrough.count # did = @tenant.phone_number_ranges.find_by_name(GsParameter.get('DIRECT_INWARD_DIALING_NUMBERS')).phone_numbers.first # callthroughs = Array.new # (1..2).each do |i| # callthroughs[i] = @tenant.callthroughs.build # callthroughs[i].phone_numbers.build(:number => did.number) # callthroughs[i].save # end # assert callthroughs[1].valid?, '1st Callthrough is not valid' # assert !callthroughs[2].valid?, '2nd Callthrough is not valid' # end end
class CreateCategoryAssociation < ActiveRecord::Migration[5.0] def change remove_column :categories, :category_id add_reference :categories, :category, index:true end end
# coding: utf-8 # frozen_string_literal: true # This file is part of IPsec packetgen plugin. # See https://github.com/sdaubert/packetgen-plugin-ipsec for more informations # Copyright (c) 2018 Sylvain Daubert <sylvain.daubert@laposte.net> # This program is published under MIT license. module PacketGen::Plugin # Mixin for cryptographic classes # @api private # @author Sylvain Daubert module Crypto # Cryptographic error class Error < PacketGen::Error; end # Register cryptographic modes # @param [OpenSSL::Cipher] conf # @param [OpenSSL::HMAC] intg # @return [void] def set_crypto(conf, intg) @conf = conf @intg = intg return unless conf.authenticated? # #auth_tag_len only supported from ruby 2.4.0 @conf.auth_tag_len = @trunc if @conf.respond_to? :auth_tag_len end # Get confidentiality mode name # @return [String] def confidentiality_mode mode = @conf.name.match(/-([^-]*)$/)[1] raise Error, 'unknown cipher mode' if mode.nil? mode.downcase end # Say if crypto modes permit authentication # @return [Boolean] def authenticated? @conf.authenticated? || !@intg.nil? end # Check authentication # @return [Boolean] def authenticate! @conf.final if @intg @intg.update @esn.to_s if defined? @esn @intg.digest[0, @icv_length] == @icv else true end rescue OpenSSL::Cipher::CipherError false end # Encipher +data+ # @param [String] data # @return [String] enciphered data def encipher(data) enciphered_data = @conf.update(data) @intg&.update(enciphered_data) enciphered_data end # Decipher +data+ # @param [String] data # @return [String] deciphered data def decipher(data) @intg&.update(data) @conf.update(data) end # Compute and set IV for deciphering mode # @param [PacketGen::Types::String] salt # @param [String] msg ciphered message # @return [String] iv def compute_iv_for_decrypting(salt, msg) case confidentiality_mode when 'gcm' iv = msg.slice!(0, 8) real_iv = salt + iv when 'cbc' @conf.padding = 0 real_iv = iv = msg.slice!(0, 16) when 'ctr' iv = msg.slice!(0, 8) real_iv = salt + iv + [1].pack('N') else real_iv = iv = msg.slice!(0, 16) end @conf.iv = real_iv iv end # Compute and set real IV for ciphering mode # @param [String] iv IV to use # @param [String] salt salt to use # @return [void] def compute_iv_for_encrypting(iv, salt) # rubocop:disable Naming/MethodParameterName real_iv = force_binary(salt) + force_binary(iv) real_iv += [1].pack('N') if confidentiality_mode == 'ctr' @conf.iv = real_iv end end end
class GamesController < ApplicationController def new @letters = [] alphabet = ('A'..'Z').to_a 10.times { @letters.push << alphabet[rand(26)] } @letters = @letters.join end def score raise @attempt = params[:attempt] @letters = params[:letters].split('') if not_valid?(@attempt, @letters) @response = 'Those letters are not in the grid!' else url = "https://wagon-dictionary.herokuapp.com/#{@attempt}" serialized = open(url).read dict = JSON.parse(serialized) @response = dict['found'] ? 'Well Done!' : "That's not an english word!" end end def not_valid?(attempt, grid) attempt.chars do |letter| return true unless grid.include?(letter.upcase) index = grid.index(letter.upcase) grid.delete_at(index) end false end end
class Article < ActiveRecord::Base belongs_to :user validates :title ,presence:true ,length: {minimum: 3,maximum: 50} validates :description ,presence:true ,length: {minimum: 10,maximum: 5000} has_many :article_categories has_many :categories, through: :article_categories end
Rails.application.routes.draw do get '/register', to: 'rendezvous_registrations#new' get '/registration-welcome', to: 'rendezvous_registrations#welcome' resources :pictures, except: [:index] get '/gallery', to: 'pictures#index' get '/t-shirt-gallery', to: 'pictures#t_shirt_gallery' get '/pictures_recreate_versions', to: 'pictures#recreate_versions' devise_for :users, :controllers => { :users => 'users', :passwords => 'custom_devise/passwords', :registrations => 'custom_devise/registrations' }, :path => '' get '/users/synchronize_mailchimp', to: 'users#synchronize_with_mailchimp' resources :users resources :rendezvous_registrations do member do get :review get :payment patch :complete get :vehicles end end resources :rendezvous_registrations, :except => [:index] get 'payment_token', to: 'rendezvous_registrations#get_payment_token' # Admin routes get '/admin/toggle_user_session', to: 'admin#toggle_user_session' resources :admin, { :only => [:index] } namespace :admin do resources :rendezvous_registrations, { :only => [ :show, :edit, :update ] } resources :transactions, { :only => [ :create ] } get 'rendezvous_registrations/:id/cancel', to: 'rendezvous_registrations#cancel', as: 'cancel_rendezvous_registration' end # Omniauth authentication get '/auth/:provider/callback', to: 'sessions#create' root 'content_pages#index' get '/', to: 'content_pages#index' get '/faq', to: 'content_pages#faq' get '/gallery', to: 'content_pages#gallery' get '/history', to: 'content_pages#history' get '/legal_information', to: 'content_pages#legal_information' get '/schedule', to: 'content_pages#schedule' get '/vendors', to: 'content_pages#vendors' # User management get '/user_sign_up', to: 'users#sign_up' get '/user_sign_in', to: 'users#sign_in' # Picture upload get '/my-pictures', to: 'pictures#my_pictures' post '/pictures/upload(.:format)', to:'pictures#upload' # Contact form post '/contact-us', to:'content_pages#contact_us' # Send email get '/send_email', to: 'rendezvous_registrations#send_email' # AJAX routes get '/ajax/picture/delete/:id', to: 'pictures#ajax_delete' get '/ajax/find_user_by_email', to: 'users#find_by_email' get '/ajax/toggle_admin', to: 'users#toggle_admin' get '/ajax/toggle_tester', to: 'users#toggle_tester' get '/ajax/delete_users', to: 'users#delete_users' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
module Mahjong class Game attr_accessor :player1 attr_accessor :player2 attr_accessor :player3 attr_accessor :player4 attr_accessor :players def initialize(**args) @players = args[:players] @player1 = args[:players][0] @player2 = args[:players][1] @player3 = args[:players][2] @player4 = args[:players][3] @len = args[:len] end def start line_up_players # 仮実装 ba = Ba.new( players: players, order:0, renchan:0 ) ba.haipai ba.start end private def line_up_players players.shuffle! players[0].oya = true end end end
class EmailDigestNotificationWorker < BaseWorker def self.category; :notification end def self.metric; :email_digest end def perform(user_id, job_token) perform_with_tracking(user_id, job_token) do user = User.find(user_id) # Only send the digest if the user has been unavailable the entire time since the last digest digests_sent = user.email_digests_sent.value if digests_sent > 0 && user.redis.get(EmailNotifier.job_token_key(user.id, digests_sent)) == job_token && user.away_idle_or_unavailable? user.email_notifier.send_snap_notification(:all, nil, {skip_queue: true}) end true end end statsd_measure :perform, metric_prefix end
class TimeTrack < ApplicationRecord belongs_to :user scope :created_desc, -> { order(created_at: :desc) } scope :order_sleep, -> { order("-(#{TimeTrack.table_name}.wakeup_at - #{TimeTrack.table_name}.sleep_at)") } scope :in_last_week, -> { where("created_at >= ?", 7.days.ago.beginning_of_day) } def sleep_time return if wakeup_at.blank? || sleep_at.blank? total_seconds = wakeup_at - sleep_at seconds = total_seconds % 60 minutes = (total_seconds / 60) % 60 hours = total_seconds / (60 * 60) format("%<hours>02d:%<minutes>02d:%<seconds>02d", hours: hours, minutes: minutes, seconds: seconds) end end
class AddLastUpdatedByToJournalArticles < ActiveRecord::Migration def change add_column :journal_articles, :last_updated_by, :integer end end
# LTEsim Parameter Module # # Copyright Ericsson AB 2013. # # This example shows how to setup and retrieve configuration parameters for LTEsim. # # # Module that contains functions for retrieving configuration values for the LTEsim components. # # Copy this file to your home directory with a different name and edit the copy # to match your environment. # # Make sure that your version of parameters.rb is used by one of the following methods: # # Start ltesim_cli with the parameter -params <file> # # Start ltesim_cli in the same folder as your file %parameters.rb # # Add the folder with parameters.rb to the ltesim_cli search path, using the -p parameter # # Load your parameters.rb file in each test script (or in the ltesim_cli) by adding # "LteSimCli.rerequire '<path to and including parameters.rb>'" in the beginning of the script. # require 'etc' module Parameters # # Retrieve general configuration parameters. # def Parameters.getGeneralParameters() # Define and return default values default = {} # Create new log directory for each run log_dir = "-l /tmp/" + Etc.getlogin() + "_" + Time.new.strftime("%Y%m%d_%H%M%S") default[:coreParameters] = "#{log_dir}" # String containing start parameters for ltesim core # See ltesim core -help for details default[:jvm_parameters] = "" # Specify additional JVM parameters default[:logger_handlersSet] = "com.ericsson.cctt.log.RollingGzFileHandler" default[:logger_file_count] = 20 default[:logger_file_sizeLimit] = 2**30 # 2**30 = 1 GiB default[:logger_file_gzipEnabled] = true # enables gzip of rotated logs # All JMX parameters can be listed with help :launcher in the ltesim_cli return default end # # Retrieve default parameters for MME. # def Parameters.getMmeParameters() # Define and return default values default = {} default[:simulate_core] = false # Set to true if simulated core is used in the configuration. default[:mme_names] = ["mme1"] # Name of the MME component default[:mme_tais] = ["62F2281200"] # MME tracking area identity value default[:mmes] = 1 # Number of MMEs (used in multiple MME configuration) # The IP addresses must be available on the LTEsim server and reachable from the eNB CP interface default[:mme_s1ap_uris] = ["sctp://127.0.0.1:36412"] default[:s1ap_pluginFilterPath] = "/etc/alternatives/ltesim-root/ltesim/internal/ltesim-plugin-filters/com/ericsson/sps/ltesim/s1ap/filter" # Set the filter path # All JMX parameters can be listed with help :mme in the ltesim_cli return default end # # Retrieve default parameters for Paging generator. # def Parameters.getPagingGeneratorParameters() # Define and return default values default = {} default[:generate_pagings] = false # Set to true if paging generators are used in the configuration. default[:generators] = 3 # Number of paging generators default[:paging_generator_names] = ["pagings1", "pagings2", "pagings3"] # Name of the paging generators default[:imsi_ranges] = ["100000+100", "200000+100", "300000+100"] # The IMSI range which pagings are generated by each generator. default[:mme_codes] = ["AA", "AB", "AC"] # Used to generate GUMMEI default[:ue_paging_identity] = "IMSI" # Can be IMSI or STMSI # The IP addresses must be available on the LTEsim server and reachable from the eNB CP interface default[:paging_s1ap_uris] = ["sctp://127.0.1.1:36412", "sctp://127.0.1.2:36412", "sctp://127.0.1.3:36412"] default[:s1ap_checkASN1_constraints] = false # Set constraint checks to true to get info of broken ASN.1 messages default[:bundle_paging] = false # Set constraint check to true to turn paging bundle. # All JMX parameters can be listed with help :paginggenerator in the ltesim_cli return default end # # Retrieve default parameters for SGW. # def Parameters.getSgwParameters() # Define and return default values default = {} default[:sgw_names] = ["sgw1"] # Name of the Serving GWs default[:sgw_ipAddresses] = ["127.0.0.1"] default[:apn_lists] = ["ltesim-core-network,172.17.0.1/16;"] default[:sgw_LDIs] = ["30"] default[:core_network_gateway] = false # Indicates if the core network shall act # as an IP gateway to the UEs # All JMX parameters can be listed with help :sgw in the ltesim_cli return default end # # Retrieve default parameters for UE component, including L1L2 Manager # configuration parameters. # def Parameters.getUeParameters() # Define and return default values default = {} default[:start_ue_component] = false # Decide if the UE component should be started default[:name] = "ue1" # Name of the UE component default[:l1l2_managers] = "UCTOOL;uctool1" # Space separated string with TYPE;instance tuples where allowed values of TYPE is UCTOOL. default[:rrc_pluginFilterPath] = "/etc/alternatives/ltesim-root/ltesim/internal/ltesim-plugin-filters/com/ericsson/sps/ltesim/ue/rrc/filter" # UCTool specific parameters default[:uctool_ip] = "{uctool1;192.168.3.5}" # UCTOOL device name the IP address of the UCtool. # NOTE! If only IP address is given then the IP address will be # applicable for all UCTOOL managers. default[:uctool_cIds] = "{uctool1;cell11,cell12}" # UCTOOL device name and cell names used to map. # the UCTOOL cells to corresponding cells in the REC. default[:uctool_service_ip] = "{uctool1;192.168.3.19}" # UCTOOL device name and the IP address of the service requested. # NOTE! If only IP address is given then the IP address will be # applicable for all UCTOOLs. ###### Security related parameters ################################################################################### default[:ue_network_capability] = "E0E0" # UE network capabilities. See 3GPP 24.008 for more details # Used to control which integrity protection and ciphering algorithms a UE supports. default[:ue_keyDerivationAlgorithm] = "TEST_ALGORITHM" # The algorithm used during EPS AKA procedure. # Supported algorithms: # * TEST_ALGORITHM - The test algorithm defined in TS 34.108. # * MILENAGE - The milenage algorithm defined in TS 35.205. # Also used in simulated MME. default[:ue_key] = "77777777777777777777777777777777" # Used for MILENAGE default[:ue_op] = "CDC202D5123E20F62B6D676AC72CB318" # The OP used in the MILENAGE algorithm. Also used in simulated MME. ###################################################################################################################### # All JMX parameters can be listed with help :ue in the ltesim_cli return default end # # Retrieve default parameters for Radio Environment. # def Parameters.getRecParameters() # Define and return default values default = {} # Write with the following syntax: # default[:rec] = [{<first set of cell params>},{<second set of cell params>}] # # A set of cell params includes: # :cell # Cell instance name # :site # Site instance name # :pci # Physical cell identifier # :position_X # Cell position, coordinate X # :position_Y # Cell position, coordinate Y # :earfcnDl # Channel number for the central DL frequency # :transmitPower # Transmit power in dBm # :ulNoiseAndInterference # uplink N+I in dBm default[:rec] = [ { :cell => "cell11", :site => "site11", :pci => 11, :position_X => 7000, :position_Y => 7000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell12", :site => "site12", :pci => 12, :position_X => 14000, :position_Y => 7000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell21", :site => "site21", :pci => 21, :position_X => 10500, :position_Y => 13000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell22", :site => "site22", :pci => 22, :position_X => 17500, :position_Y => 13000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell31", :site => "site31", :pci => 31, :position_X => 7000, :position_Y => 19000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell32", :site => "site32", :pci => 32, :position_X => 14000, :position_Y => 19000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell41", :site => "site41", :pci => 41, :position_X => 10500, :position_Y => 25000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell42", :site => "site42", :pci => 42, :position_X => 17500, :position_Y => 25000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell51", :site => "site51", :pci => 51, :position_X => 7000, :position_Y => 31000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell52", :site => "site52", :pci => 52, :position_X => 14000, :position_Y => 31000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell61", :site => "site61", :pci => 61, :position_X => 10500, :position_Y => 37000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 },{ :cell => "cell62", :site => "site62", :pci => 62, :position_X => 17500, :position_Y => 37000, :earfcnDl => 2050, :transmitPower => -75.0, :ulNoiseAndInterference => -116.0 } ] return default end # # Retrieve default parameters for user behavior models # def Parameters.getTraffBehaviourParameters() # Define and return default values default = {} # IMSI range used by traffic models. # IMSI ranges are specified with the # following syntax (space separated string): # "<first_range> <second_range>". default[:imsiMapRange] = "262800100326000+1499 262800100329000+1499" # Size of geographical map default[:southBoundMap] = 0 default[:northBoundMap] = 42000 default[:westBoundMap] = 0 default[:eastBoundMap] = 35000 # Areas defined which are possible to use with traffic models (aka Cell Map) # # :area - naming convention for three types of areas: # Center an area with a RBS cell in the center # Handover an area with two RBS:es # Common an area containing all cells # Center: # :area => "Center11" # Area name around cell1-1 (RBS-1) # ^--- cell number # ^--- RBS number # Handover: # :area => "Handover11_21" # Area name for possible inter handover between RBS-1 and RBS-2 # ^--- cell number # ^--- RBS number # ^--- cell number # ^--- RBS number # Common: # :area => "Common", # Area common for all cells # # Boundaries, specified for all types of areas: # :southBoundary => 6900, # South boundary of area # :northBoundary => 7100, # North boundary of area # :westBoundary => 6900, # West boundary of area # :eastBoundary => 7100, # East boundary of area default[:areas] = [ { :area => "Center11", :southBoundary => 6900, :northBoundary => 7100, :westBoundary => 6900, :eastBoundary => 7100 },{ :area => "Center12", :southBoundary => 6900, :northBoundary => 7100, :westBoundary => 13900, :eastBoundary => 14100 },{ :area => "Center21", :southBoundary => 12900, :northBoundary => 13100, :westBoundary => 10400, :eastBoundary => 10600 },{ :area => "Center22", :southBoundary => 12900, :northBoundary => 13100, :westBoundary => 17400, :eastBoundary => 17600 },{ :area => "Center31", :southBoundary => 18900, :northBoundary => 19100, :westBoundary => 6900, :eastBoundary => 7100 },{ :area => "Center32", :southBoundary => 18900, :northBoundary => 19100, :westBoundary => 13900, :eastBoundary => 14100 },{ :area => "Center41", :southBoundary => 24900, :northBoundary => 25100, :westBoundary => 10400, :eastBoundary => 10600 },{ :area => "Center42", :southBoundary => 24900, :northBoundary => 25100, :westBoundary => 17400, :eastBoundary => 17600 },{ :area => "Center51", :southBoundary => 30900, :northBoundary => 31100, :westBoundary => 6900, :eastBoundary => 7100 },{ :area => "Center52", :southBoundary => 30900, :northBoundary => 31100, :westBoundary => 13900, :eastBoundary => 14100 },{ :area => "Center61", :southBoundary => 36900, :northBoundary => 37100, :westBoundary => 10400, :eastBoundary => 10600 },{ :area => "Center62", :southBoundary => 36900, :northBoundary => 37100, :westBoundary => 17400, :eastBoundary => 17600 },{ :area => "Handover11_21", :southBoundary => 7750, :northBoundary => 12250, :westBoundary => 8000, :eastBoundary => 9000 },{ :area => "Handover11_12", :southBoundary => 6500, :northBoundary => 7500, :westBoundary => 8250, :eastBoundary => 12750 },{ :area => "Handover12_21", :southBoundary => 7750, :northBoundary => 12250, :westBoundary => 11500, :eastBoundary => 12500 },{ :area => "Handover12_22", :southBoundary => 7750, :northBoundary => 12250, :westBoundary => 15000, :eastBoundary => 16000 },{ :area => "Handover21_22", :southBoundary => 12500, :northBoundary => 13500, :westBoundary => 11750, :eastBoundary => 16250 },{ :area => "Handover31_32", :southBoundary => 18500, :northBoundary => 19500, :westBoundary => 8250, :eastBoundary => 12750 },{ :area => "Handover21_31", :southBoundary => 13750, :northBoundary => 18250, :westBoundary => 8000, :eastBoundary => 9000 },{ :area => "Handover21_32", :southBoundary => 13750, :northBoundary => 18250, :westBoundary => 11500, :eastBoundary => 12500 },{ :area => "Handover22_32", :southBoundary => 13750, :northBoundary => 18250, :westBoundary => 15000, :eastBoundary => 16000 },{ :area => "Handover41_42", :southBoundary => 24500, :northBoundary => 25500, :westBoundary => 11750, :eastBoundary => 16250 },{ :area => "Handover41_51", :southBoundary => 25750, :northBoundary => 30250, :westBoundary => 8000, :eastBoundary => 9000 },{ :area => "Handover51_52", :southBoundary => 30500, :northBoundary => 31500, :westBoundary => 8250, :eastBoundary => 12750 },{ :area => "Handover61_62", :southBoundary => 36500, :northBoundary => 37500, :westBoundary => 11750, :eastBoundary => 16250 },{ :area => "Handover31_41", :southBoundary => 19750, :northBoundary => 24250, :westBoundary => 8000, :eastBoundary => 9000 },{ :area => "Handover32_41", :southBoundary => 19750, :northBoundary => 24250, :westBoundary => 11500, :eastBoundary => 12500 },{ :area => "Handover32_42", :southBoundary => 19750, :northBoundary => 24250, :westBoundary => 15000, :eastBoundary => 16000 },{ :area => "Handover41_52", :southBoundary => 25750, :northBoundary => 30250, :westBoundary => 11500, :eastBoundary => 12500 },{ :area => "Handover42_52", :southBoundary => 25750, :northBoundary => 30250, :westBoundary => 15000, :eastBoundary => 16000 },{ :area => "Handover51_61", :southBoundary => 31750, :northBoundary => 36250, :westBoundary => 8000, :eastBoundary => 9000 },{ :area => "Handover52_61", :southBoundary => 31750, :northBoundary => 36250, :westBoundary => 11500, :eastBoundary => 12500 },{ :area => "Handover52_62", :southBoundary => 31750, :northBoundary => 36250, :westBoundary => 15000, :eastBoundary => 16000 },{ :area => "Common", :southBoundary => 6500, :northBoundary => 37500, :westBoundary => 9000, :eastBoundary => 29000 } ] default[:dataGenerator] = "ipgwtg" # Use local IPGWTG # Configuration of the ipgwtg user data generator, default[:userDataGen] = "ipex.isp.sip.offset = 31000\n" + "ipex.isp.qci1.port = 31010\n" + "ipex.isp.qci2.port = 31020\n" + "ipex.isp.qci5.port = 31050\n" default[:start_isp_simulator] = true default[:ipgwtg_ipAddress] = "10.10.0.1" # IP address of the interface that can reach the PGW default[:ipgwtg_inband_signaling] = false default[:ipgwtg_port] = 32000 default[:ipgwtg_ftp_sender_connect_put] = true return default end # # Retrieve default parameters for UBsim configuration # def Parameters.getUbsimConfigParameters() # Define and return default values default = {} default[:ueTypesDir] = "" # Directory containing users UE type definitions default[:csTrafficModelsDir] = "" # Directory containing users CS traffic Models default[:psTrafficModelsDir] = "" # Directory containing users PS traffic Models default[:mobilityModelsDir] = "" # Directory containing users Mobility Models default[:visualization] = false # UBsim GUI # patches to use when starting UBsim # Given as a Java classpath, multiple element separated by ':' default[:ubsim_patches] = "" # UBsim code in UBsim project (ubsim.jar) return default end # # Configure channel models # def Parameters.getChannelModelConfigParameters() # Define and return default values default = {} default[:model_set_name] = "default_error_set" default[:pdcch_drop_dl_assignment_rate] = 1.0 default[:pdcch_drop_grant_rate] = 1.0 default[:pdsch_transport_block_decoded_error_rate] = 1.0 default[:phich_nack_to_ack_error_rate] = 1.0 default[:phich_drop_harq_feedback_rate] = 1.0 default[:pusch_transport_block_decoded_error_rate] = 1.0 default[:pusch_drop_transport_block_rate] = 1.0 default[:puxch_nack_to_ack_error_rate] = 1.0 default[:puxch_dtx_to_ack_error_rate] = 1.0 default[:puxch_ack_to_nack_error_rate] = 1.0 default[:puxch_drop_scheduling_request_rate] = 1.0 default[:dlni_noise] = 1.0 default[:dlni_interference] = 1.0 default[:dl_pathloss_min_pathloss] = 1.00 default[:dl_pathloss_max_pathloss] = 20.0 default[:dl_pathloss_time_min_to_max] = 1000 default[:dl_pathloss_distribute_ues] = true default[:pathloss_based_feedback_sinr_threshold] = 1.0 return default end end
require('minitest/autorun') require_relative('./library') require('minitest/rg') class TestLibrary < MiniTest::Test def setup @volumes = { title: "lord_of_the_rings", rental_details: { student_name: "Jeff", date: "01/12/16" } } end def test_book_list library = Library.new({ title: "lord_of_the_rings", rental_details: { student_name: "Jeff", date: "01/12/16" } }) assert_equal({ title: "lord_of_the_rings", rental_details: { student_name: "Jeff", date: "01/12/16" } }, library.list(@volumes)) end def test_query list = @volumes item = "lord_of_the_rings" assert_equal(@volumes[:rental_details], @volumes.query(list, item)) end def test_add_book library = @volumes book = { title: "test_book", rental_retails: { student_name: "Bob", date: "02/03/14" } } assert_equal("test_book", library.add_book(@volumes, book).check_book(@volumes, book) ) end end
class Task < ApplicationRecord belongs_to :user validates :name,presence: true validates :start_time,presence: true validates :end_time,presence: true end
class OrdersController < ApplicationController before_action :set_order, only: [:show, :edit, :update, :destroy] def express_checkout package = Package.find(params[:id]) response = EXPRESS_GATEWAY.setup_purchase(package.price, ip: request.remote_ip, return_url: new_order_url(package_id: package.id), cancel_return_url: panel_url, currency: "EUR", allow_guest_checkout: true, items: [{name: "Order", description: "Order description", quantity: "1", amount: package.price}] ) redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token) end # GET /orders # GET /orders.json def index @orders = current_user.orders end # GET /orders/1 # GET /orders/1.json def show end # GET /orders/new def new @order = current_user.orders.new(express_token: params[:token]) @package = Package.where(id: params[:package_id]).first if @package.present? @package_name = @package.name else redirect_to :back, notice: 'Something is missing...' end end # POST /orders # POST /orders.json def create @order = current_user.orders.new(order_params) @package = Package.find(params[:order][:package_id]) @order.package_id = @package.id @order.price = @package.price @order.ip = request.remote_ip if @order.save if @order.purchase @order.add_bids_to_user redirect_to panel_url, notice: 'Η συναλλαγή σας ολοκληρώθηκε επιτυχώς!' else render :action => "failure" end else render action: 'new' end end private # Use callbacks to share common setup or constraints between actions. def set_order @order = Order.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def order_params params.require(:order).permit(:package_id, :express_token, :express_payer_id, :ip, :first_name, :last_name, :card_type, :card_number, :card_verification, :card_expires_on) end end
require 'test_helper' class FullcalendarRailsTest < ActiveSupport::TestCase def setup @app = Dummy::Application end test "fullcalendar.js is found as an asset" do assert_not_nil @app.assets["fullcalendar"] end test "jquery-ui is found as an asset" do assert_not_nil @app.assets["jquery-ui"] end test "fullcalendar.css is found as an asset" do assert_not_nil @app.assets["fullcalendar"] end end
class MeasurementDataRenameUrlColumn < ActiveRecord::Migration def self.up rename_column :measurement_datas, :url, :uri end def self.down end end
module ReceptionistSessionsHelper def log_in_receptionist(receptionist) session[:receptionist_id] = receptionist.id end def log_out_receptionist session.delete(:receptionist_id) @current_receptionist = nil end #Returns the current logged-in user (if any). def current_receptionist @current_receptionist ||= Receptionist.find_by(id: session[:receptionist_id]) end #Returns true if the user is logged in,false otherwise. def logged_in_receptionist? !current_receptionist.nil? end end
class CphcCreateUserJob include Sidekiq::Worker sidekiq_options queue: :cphc_migration, retry: SimpleServer.env.development? def perform(facility_id) facility = Facility.find(facility_id) # TODO: How do we show the error to the user OneOff::CphcEnrollment::AuthManager.new(facility).create_user end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable has_many :items has_many :orders devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable validates :nickname, presence: true, length: { maximum: 40 } validates :password, presence: true, length: { minimum: 6 } VALID_PASSWORD_REGIX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i validates :password, format: { with: VALID_PASSWORD_REGIX } with_options presence: true, format: { with:/\A[ぁ-んァ-ン一-龥]+\z/, message: '全角文字を使用してください' } do validates :first_name validates :family_name end with_options presence: true, format: { with:/\A[ァ-ヶー-]+\z/, message: '全角カタカナで入力してください' } do validates :family_name_kana validates :first_name_kana end validates :birth_day, presence: true end
class Book < ActiveRecord::Base belongs_to :category has_and_belongs_to_many :authors validates_presence_of :title validates_presence_of :isbn end
require 'spec_helper' RSpec.describe "Product", type: :feature, vcr: true do %w(base insert kit virtual_kit).each do |product_type| context "type #{product_type}" do let(:product_class) do type = Shipwire::Utility.camelize(product_type) Object.const_get("Shipwire::Products::#{type}") end context "list" do context "without params" do it "is successful" do VCR.use_cassette("products_#{product_type}_list") do response = product_class.new.list expect(response.ok?).to be_truthy end end end context "with params" do it "is successful" do VCR.use_cassette("products_#{product_type}_list_with_params") do response = product_class.new.list( sku: "TEST-PRODUCT" ) expect(response.ok?).to be_truthy end end end end context "management" do let!(:product) do VCR.use_cassette("product_#{product_type}") do product_class.new.create(payload(product_type)) end end context "find" do it "is successful" do VCR.use_cassette("product_#{product_type}_find") do product_id = product.body["resource"]["items"].first["resource"]["id"] response = product_class.new.find(product_id) expect(response.ok?).to be_truthy end end it "fails when id does not exist" do VCR.use_cassette("product_#{product_type}_find_fail") do response = product_class.new.find(0) expect(response.ok?).to be_falsy expect(response.error_summary).to eq 'Product not found.' end end end context "update" do it "is successful" do VCR.use_cassette("product_#{product_type}_update") do product_id = product.body["resource"]["items"].first["resource"]["id"] payload = payload(product_type).deeper_merge!( description: "Super awesome description" ) response = product_class.new.update(product_id, payload) expect(response.ok?).to be_truthy end end it "fails when id does not exist" do VCR.use_cassette("product_#{product_type}_update_fail") do payload = payload(product_type).deeper_merge!( description: "Super awesome description" ) response = product_class.new.update(0, payload) expect(response.ok?).to be_falsy expect(response.error_summary).to eq 'Product not found.' end end end context "retire" do context "with string passed" do it "is successful" do VCR.use_cassette("product_#{product_type}_retire_id") do product_id = product.body["resource"]["items"].first["resource"]["id"] response = product_class.new.retire(product_id) expect(response.ok?).to be_truthy end end end context "with array passed" do it "is successful" do VCR.use_cassette("product_#{product_type}_retire_id") do product_id = product.body["resource"]["items"].first["resource"]["id"] response = product_class.new.retire([product_id, 0]) expect(response.ok?).to be_truthy end end end context "when product does not exist" do it "is successful" do VCR.use_cassette("product_#{product_type}_retire_nonexistent") do response = product_class.new.retire(0) expect(response.ok?).to be_truthy end end end end # NOTE: This is ugly and massive and I know it. I'm down to change it. def payload(type) payload = { sku: FFaker::Product.model, externalId: FFaker::Product.model, description: FFaker::Product.product, category: "OTHER", batteryConfiguration: "NOBATTERY", values: { costValue: 1, retailValue: 4 }, dimensions: { length: 1, width: 1, height: 1, weight: 1 }, flags: { isPackagedReadyToShip: 1, isFragile: 0, isDangerous: 0, isPerishable: 0, isLiquid: 0, isMedia: 0, isAdult: 0, hasInnerPack: 0, hasMasterCase: 0, hasPallet: 0 } } # First of all, to create a Kit or Virtual Kit, the base products HAVE # to exist. They will not be created here. Kits require 2 ore more # products. # Next, `externalId` is NOT the same as the product SKU. An externalId # currently cannot be set using the Shipwire website. It can only be # set by creating a product through the API or updating an existing # product using the API and setting a value for externalID. # Otherwise instead of `externalID` you can use `productID` which is # the unique Shipwire ID for that product product_contents = [ { externalId: "TEST-PRODUCT", quantity: 1 }, { externalId: "TEST-PRODUCT2", quantity: 1 } ] case type when "insert" payload.deeper_merge!( dimensions: { height: 0.1, weight: 0.1 }, masterCase: { individualItemsPerCase: 1, sku: FFaker::Product.model, description: FFaker::Product.product, dimensions: { length: 1, width: 1, height: 1, weight: 1 } }, inclusionRules: { insertWhenWorthCurrency: "USD" } ) when "kit" payload.deeper_merge!(kitContent: product_contents) when "virtual_kit" payload.deeper_merge!(virtualKitContent: product_contents) end payload end end end end end
require 'card_spring' class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :token_authenticatable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :token, :last4, :brand, :brand_string, :expiration, :first_name, :last_name, :phone_number has_many :user_cards has_many :transactions def record_card_transaction(params) card = self.user_cards.where(token: params[:card_token]).first raise("Unable to find the card") unless card transaction = Transaction.new transaction.user_card = card transaction.user = self transaction.cs_business_id = params[:business_id] transaction.cs_business_name = CardSpring::Business::ALL_ACTIVE[params[:business_id]] transaction.currency = params[:currency] transaction.amount = params[:amount] transaction.purchase_date_time = params[:purchase_date_time] transaction.event_type = params[:event_type] transaction.cs_transaction_id = params[:transaction_id] transaction.send_offerwall_invite transaction.save! end end
require "tty-progressbar" module IMDb class Downloader MIRROR = "ftp://ftp.fu-berlin.de/pub/misc/movies/database" def self.download(name) new.download(name) end def download(name) unless File.exists?("data/#{name}.list") download_file("#{name}.list.gz", "data/#{name}.list.gz") unzip_file("data/#{name}.list.gz") end File.expand_path("data/#{name}.list") end private def download_file(source, destination) system "wget #{File.join(MIRROR, source)} -O #{destination} --quiet --show-progress" end def unzip_file(filename) system "gzip --decompress --force #{filename}" end end class Extractor MOVIE_REGEX = /^ (?<title>.+)\s # Game of Thrones \((?<year>\d{4})\)\s # (1994) (\{(?<episode>.+)\})? # {The Watchers on the Wall (#4.5)} /x def self.extract(path, number) new.extract(path, number) end def extract(path, number) lines = File.open(path, encoding: "iso-8859-1:utf-8").each_line lines.next until lines.peek.start_with?("MV: ") progress_bar = TTY::ProgressBar.new(":bar :percent", total: number, width: 50, complete: "#") number.times.each_with_object([]) do |_, movies| movie = extract_movie(lines) plot = extract_plots(lines).join("\n\n") redo if movie.nil? movie[:plot] = plot movies << movie progress_bar.advance end end private def extract_plots(lines) plots = [] until lines.peek.start_with?("------") plot = lines.take_while { |line| line.start_with?("PL: ") } plots << plot.map! { |line| line.match(/^PL: /).post_match.chomp }.join(" ") 3.times { lines.next } end lines.next plots end def extract_movie(lines) text = lines.next.match(/^MV: /).post_match match = text.match(MOVIE_REGEX) lines.next return if match.nil? { title: match[:title].gsub(/^"|"$/, ""), year: match[:year].to_i, episode: match[:episode], } end end end task :import do puts "Downloading..." path = IMDb::Downloader.download("plot") puts "Extracting..." movies = IMDb::Extractor.extract(path, 10_000) puts "Importing..." $engines.each do |engine| engine.clear engine.import(movies) end end
class Api::ItemsController < ApplicationController def create @item = Item.new(item_params) if @item.save render "api/items/show" else render json: @item.errors.full_messages, status: 422 end end def item_params params.require(:item).permit(:name, :item_number, :description, :image_url, :product_info, :price, :category_id) end end
class Main helpers do def current_account @account ||= User.find_by_username( params[:username] ) || AnonymousUser.new end end get '/' do redirect '/everyone' end resource 'everyone' do |everyone| everyone.index do @items = current_account.items.latest.paginate(page: params[:page]) @page_title = "Everyone's Items" haml :'items/index' end everyone.get 'most-viewed' do @items = current_account.items.most_viewed.paginate(page: params[:page]) @page_title = "Most Popular Items" haml :'items/index' end everyone.get 'liked' do @items = current_account.likes_items.paginate(page: params[:page]) @page_title = "Most Liked Items" haml :'items/index' end end resource ':username' do |user| user.index do if User === current_account @items = current_account.items.latest.paginate(page: params[:page]) @page_title = "#{current_account.name}'s Shelf" haml :'items/index' else pass end end user.get 'tagged/:tag' do |username, tag| @items = current_account.items.tagged(params[:tag]).paginate(page: params[:page]) @page_title = "#{current_account.name}'s Shelf | Tagged #{params[:tag]}" haml :'items/index' end user.get 'most-viewed' do @items = current_account.items.most_viewed.paginate(page: params[:page]) @page_title = "#{current_account.name}'s Shelf | Most Viewed" haml :'items/index' end user.get 'liked' do @items = current_account.likes_items.latest.paginate(page: params[:page]) @page_title = "#{current_account.name}'s Liked Items" haml :'items/index' end user.get 'friends-items' do @items = current_account.friends_items.latest.paginate(page: params[:page]) @page_title = "#{current_account.name} | Friend's Items" haml :'items/index' end user.get ':id' do pass unless User === current_account @item = @account.items.find(params[:id]) @item.viewed! @page_title = "#{current_account.name} | #{@item.name}" haml :'items/show' end user.delete ":id" do login_required content_type 'text/plain' @item = current_user.items.find(params[:id]) @item.destroy { :location => user_url(@item.user) }.to_json end end resource 'items' do |items| items.new do login_required @item = Item.new(:name => params[:name]) @page_title = "Post a new Item" haml :'items/new' end items.create do login_required content_type 'text/plain' @item = current_user.items.build(params[:item]) if @item.save { location: user_url(@item.user) }.to_json else @item.errors.to_json end end end end
class MessagesController < ApplicationController before_action :load_messages, only: %i[index create] before_action :build_message, only: %i[index create] def index end def create message = current_user.messages.build(params_create) if message.save ActionCable.server.broadcast('room_channel', { message: { id: message.id, body: message.body, created_at: message.created_at, user: { id: message.user.id, username: message.user.username } } }) return render json: { status: 'ok' }, status: :ok end render json: { status: 'bad_request' }, status: :bad_request end private def load_messages @messages = Message.includes(:user).latest end def build_message @message = current_user.messages.build end def params_create params.require(:message).permit(:body) end end
FactoryBot.define do factory :observation do id { Faker::Number.unique.number } encounter_id { SecureRandom.uuid } observable_id { SecureRandom.uuid } observable_type { "BloodPressure" } user_id { SecureRandom.uuid } created_at { Time.now } updated_at { Time.now } end end
$LOAD_PATH.push File.expand_path("../lib", __FILE__) require 'version' Gem::Specification.new do |spec| spec.name = 'terrazine' spec.version = Terrazine::VERSION spec.authors = ['Aeonax'] spec.email = ['aeonax.liar@gmail.com'] spec.summary = %q(Terrazine is a parser of data structures in to SQL) spec.description = %q(You can take a look at [github](https://github.com/Aeonax/terrazine).) spec.homepage = 'https://github.com/Aeonax/terrazine' spec.license = 'MIT' spec.files = `git ls-files`.split("\n") spec.test_files = `git ls-files -- {spec,features}/*`.split("\n") spec.require_paths = ['lib'] spec.add_development_dependency 'bundler', '~> 1.16' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_dependency 'pg-hstore', '1.2.0' spec.required_ruby_version = '>= 2.3.0' end
require 'spec_helper' module Alf describe Tuple, '.type' do let(:heading){ {name: String, status: Integer} } subject{ Tuple.type(heading) } it 'returns a subclass' do expect(subject).to be_kind_of(Class) expect(subject.superclass).to be(Alf::Tuple) end it 'coerces the heading' do expect(subject.heading).to be_kind_of(Heading) end it 'sets the heading correctly' do expect(subject.heading.to_hash).to eq(heading) end it 'is aliased as []' do expect(Tuple[heading]).to be_kind_of(Class) expect(Tuple[heading]).to eq(subject) end end end
class Event include Mongoid::Document include Mongoid::Timestamps include Mongoid::Attributes::Dynamic field :account_id, type: BSON::ObjectId field :server_id, type: BSON::ObjectId belongs_to :account belongs_to :server validates_presence_of :account_id validates_presence_of :server_id end
# frozen_string_literal: true require 'rails_helper' def basic_auth(path) username = ENV['BASIC_AUTH_USER'] password = ENV['BASIC_AUTH_PASSWORD'] visit "http://#{username}:#{password}@#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}#{path}" end RSpec.describe 'フード', type: :system do before do @food = FactoryBot.build(:food) @user = FactoryBot.build(:user) end # seedファイルを読み込む before(:each) do load Rails.root.join('db/seeds.rb') end context 'フード投稿が完了するとき' do it 'adminでログインしたときに投稿することができる' do # basic認証を入力する basic_auth new_user_session_path # adminでログインする fill_in 'user[email]', with: 'admin@admin.com' fill_in 'user[password]', with: '000aaa' find('input[name="commit"]').click expect(current_path).to eq root_path # お飲み物ボタンをクリック expect(page).to have_content('お料理') visit foods_path # 新規投稿ボタンをクリック find_link('新規作成', href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in 'food[title]', with: @food.title fill_in 'food[detail]', with: @food.detail fill_in 'food[price]', with: @food.price select '今月のおすすめ', from: 'food[food_category_id]' attach_file('food[image]', 'public/images/test_image.png', make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content('投稿が完了しました') # ドリンク一覧ページに投稿した内容が存在する find_link('一覧へ戻る', href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content('今月のおすすめ') end end context 'フードの投稿ができないとき' do it 'admin以外でログインしているときは新規投稿ボタンが存在しない' do # ユーザー新規登録する user_regitstration(@user) # ログインする sign_in(@user) # ドリンク一覧ページへ遷移する expect(page).to have_content('お料理') visit foods_path # 新規投稿ボタンがないことを確認する expect(page).to have_no_content('新規作成') end end context "フードの編集" do it "adminでログインしているときに詳細ページから編集できる" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリックする expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリックする find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在することを確認する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # フードの画像をクリックする find(".index-content-image").click # 投稿した内容があるのか確認する expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.detail) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # 編集ボタンをクリックする click_on "編集" # 編集内容を入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price # 投稿するボタンをクリックする expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(0) # 編集完了ページに遷移することを確認する expect(page).to have_content("編集が完了しました") # 詳細画面に戻り、編集した内容が存在するかを確認する click_on "詳細へ戻る" expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.detail) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") end end context "フードの編集ができない時" do it "admin以外でログインしている時" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # ログアウトする click_on "ログアウト" # ユーザー新規登録する user_regitstration(@user) # ログインする sign_in(@user) # フード一覧ページへ遷移する expect(page).to have_content("お料理") visit foods_path # メニューの画像をクリックする find(".index-content-image").click # 編集ボタンがないことを確認する expect(page).to have_no_content("編集") end end context "投稿が削除できる時" do it "adminでログインしているときは削除できる" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # 詳細ページへ遷移する find(".index-content-image").click # 投稿した内容があるかを確認する expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.detail) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # 削除ボタンをクリックする click_on "削除" # 削除完了ページへ遷移する expect(page).to have_content("投稿の削除が完了しました") # 一覧ページに戻り、削除されているかを確認する click_on "一覧へ戻る" expect(page).to have_no_selector("img[src$='test_image.png']") expect(page).to have_no_content(@food.title) expect(page).to have_no_content(@food.price) end end context "削除ができない時" do it "admin以外でログインしているときは削除できない" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリックする expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # ログアウトする click_on "ログアウト" # ユーザー新規登録する user_regitstration(@user) # ログインする sign_in(@user) # フード一覧ページへ遷移する expect(page).to have_content("お料理") visit foods_path # メニューの画像をクリックする find(".index-content-image").click # 削除ボタンがないことを確認する expect(page).to have_no_content("削除") end end context "フードメニューにコメントを残す" do it "入力内容があればコメントを残すことができる" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリックする expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリックする find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # ログアウトする click_on "ログアウト" # ユーザー新規登録する user_regitstration(@user) # ログインする sign_in(@user) # フード一覧ページへ遷移する expect(page).to have_content("お料理") visit foods_path # メニューの画像をクリックする find(".index-content-image").click # コメント欄にコメント内容を入力する fill_in "food_comment[comment]", with: Faker::Lorem.characters(number: 100) # 送信ボタンをクリックする find(".comment-submit").click end end context "お気に入りボタンをクリックするとカウントが1上がる" do it "投稿内容のハートボタンをクリックする" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリックする expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリックする find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "今月のおすすめ", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("今月のおすすめ") # ハートボタンをクリックする expect do first(".fa-heart").click # 0.1秒間停止させる sleep(0.1) end.to change {FoodLike.count}.by(1) # ハートボタンをもう一度クリックするとカウントが1減る expect do first(".fa-heart").click sleep(0.1) end.to change { FoodLike.count }.by(-1) end end context "フード検索" do it "カテゴリーと検索ボタンが一致した場合に表示する" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規投稿ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "とりあえず", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("とりあえず") # とりあえずのラジオボタンをクリック find("#q_food_category_id_eq_3").click click_on "検索" # 投稿した内容が存在する expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("とりあえず") end it "検索が該当しない時" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規投稿ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "とりあえず", from: "food[food_category_id]" attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("とりあえず") # 一品料理のラジオボタンをクリック find("#q_food_category_id_eq_5").click click_on "検索" # 投稿した内容が存在しないことを確認する expect(page).to have_content("該当する商品がありませんでした") end end context "食べ放題" do it "食べ放題を許可する" do # adminでログインする visit new_user_session_path fill_in "user[email]", with: "admin@admin.com" fill_in "user[password]", with: "000aaa" find('input[name="commit"]').click expect(current_path).to eq root_path # お料理ボタンをクリック expect(page).to have_content("お料理") visit foods_path # 新規作成ボタンをクリック find_link("新規作成", href: new_food_path).click expect(current_path).to eq new_food_path # フォームを入力する fill_in "food[title]", with: @food.title fill_in "food[detail]", with: @food.detail fill_in "food[price]", with: @food.price select "とりあえず", from: "food[food_category_id]" find("#food_free_food").click attach_file("food[image]", "public/images/test_image.png", make_visible: true) # 投稿するボタンをクリック expect do find('input[value="投稿する"]').click end.to change { Food.count }.by(1) # 投稿完了ページに遷移することを確認する expect(page).to have_content("投稿が完了しました") # フード一覧ページに投稿した内容が存在する find_link("一覧へ戻る", href: foods_path).click expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("とりあえず") # 食べ放題のラベルが付いていることを確認する expect(page).to have_css(".caption") # 食べ放題のラジオボタンをクリック find("#q_free_food_eq_1").click click_on "検索" # 投稿した内容が存在する expect(page).to have_selector("img[src$='test_image.png']") expect(page).to have_content(@food.title) expect(page).to have_content(@food.price) expect(page).to have_content("とりあえず") expect(page).to have_css(".caption") end end end
class User < ApplicationRecord has_many :workouts has_many :goals has_many :workout_exercises, through: :workouts has_many :goal_exercises, through: :goals has_secure_password validates :username, :email, presence: true validates :username, :email, uniqueness: true end
require 'rails_helper' RSpec.describe User, type: :model do context 'Validations' do subject { build(:user) } it { should validate_presence_of(:username) } it { should validate_presence_of(:email) } it { should validate_presence_of(:name) } end it 'has a valid factory' do user = FactoryBot.build(:user) expect(user).to be_valid end it 'is invalid without a email' do user = FactoryBot.build(:user, email: nil) expect(user).not_to be_valid end it 'is invalid without an username' do user = FactoryBot.build(:user, username: nil) expect(user).not_to be_valid end it 'is invalid without a name' do user = FactoryBot.build(:user, name: nil) expect(user).not_to be_valid end it 'is invalid without a password' do user = FactoryBot.build(:user, password: nil) expect(user).not_to be_valid end it 'is invalid with a duplicate username' do FactoryBot.create(:user, username: 'John') user = FactoryBot.build(:user, username: 'John') user.valid? expect(user.errors[:username].size).to eq(1) end it 'is invalid with a duplicate email' do FactoryBot.create(:user, email: 'test@example.com') user = FactoryBot.build(:user, email: 'test@example.com') expect(user).not_to be_valid end end
class Fluentd::Settings::HistoriesController < ApplicationController include SettingHistoryConcern def index @backup_files = @fluentd.agent.backup_files_in_new_order.map do |file_path| Fluentd::SettingArchive::BackupFile.new(file_path) end end private def find_backup_file #Do not use BackupFile.new(params[:id]) because params[:id] can be any path. @backup_file = Fluentd::SettingArchive::BackupFile.find_by_file_id(@fluentd.agent.config_backup_dir, params[:id]) end end
module Adminpanel class Section < ActiveRecord::Base include Adminpanel::Base mount_images :sectionfiles validates_length_of :description, minimum: 10, maximum: 10, allow_blank: true, if: :is_a_phone?, message: I18n.t('activerecord.errors.messages.not_phone') validates_presence_of :description, minimum: 9, on: :update, if: :has_description validates_presence_of :key validates_presence_of :name validates_presence_of :page VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates_format_of :description, with: VALID_EMAIL_REGEX, if: :is_email?, allow_blank: true default_scope do order order: :asc end scope :of_page, -> (page) do where(page: page) end scope :with_description, -> do where.not(description: '') end def self.form_attributes [ {'description' => {'name' => 'Descripcion', 'description' => 'label', 'label' => 'Seccion'}}, {'name' => {'name' => 'name', 'label' => 'Seccion'}}, {'key' => {'name' => 'key', 'label' => 'Llave'}}, {'page' => {'name' => 'page'}}, {'sectionfiles' => {'type' => 'adminpanel_file_field', 'show' => false}}, ] end def self.icon 'tasks' end def self.display_name I18n.t('model.Section') end def description if self.has_description return super.try(:html_safe) else return super end end def self.routes_options { path: collection_name.parameterize, except: [:new, :create, :destroy] } end protected def is_email? self.key == 'email' end def is_a_phone? self.key == 'phone' end end end
require 'spec_helper' require 'quaker/tag_filter' describe Quaker::TagFilter do describe 'filter' do let(:spec) { { 'svc1' => { 'tags' => ['abcd'] }, 'svc2' => { 'tags' => ['dddd'] } } } it 'filters services by tag' do expect(subject.filter spec, ['a*']).to include 'svc1' end it 'includes all services for empty tags' do expect(subject.filter spec, []).to include 'svc1', 'svc2' expect(subject.filter spec, nil).to include 'svc1', 'svc2' end describe 'dependency resolving' do before :each do spec['redis'] = {} spec['svc1']['links'] = ['redis'] end it 'includes dependencies' do expect(subject.filter spec, ['abcd']).to include 'svc1', 'redis' end describe '`exclude_list`' do it 'includes only dependencies, but not the service' do spec['redis'] = {} spec['svc1']['links'] = ['redis'] services = subject.filter spec, ['abcd'], only_deps: true expect(services).to include 'redis' expect(services).not_to include 'svc1' end end it 'raises DependencyResolveError for missing dependencies' do spec['svc1']['links'] = ['missing_service:svc'] expect { subject.filter spec, ['abcd'] }.to raise_error(Quaker::DependencyResolveError, /missing_service for service svc1/ ) end end end end
class CreateExplanatoryNotesFiles < ActiveRecord::Migration def self.up create_table :explanatory_notes_files do |t| t.string :name t.integer :bill_id t.string :path t.text :beginning_text t.text :ending_text t.timestamps end add_index :explanatory_notes_files, :bill_id add_index :explanatory_notes_files, :path end def self.down drop_table :explanatory_notes_files end end
module Ricer::Plugins::Paste class Paste < Ricer::Plugin trigger_is :paste permission_is :voice # has_usage :execute_with_language, '<programming_language> <..text..>' # def execute_with_language(programming_language) # end has_usage '<..text..>' def execute(content) execute_upload(content) end def execute_upload(content, pastelang='text', title=nil, langkey=:msg_pasted_it) send_pastebin(title||pastebin_title, content, content.count("\n"), 'text', langkey) end def pastebin_title t :pastebin_title, user: user.name, date: l(Time.now) end def send_pastebin(title, content, lines, pastelang='text', langkey=:msg_pasted_this) Ricer::Thread.execute do begin paste = Pile::Cxg.new({user_id:user.id}).upload(title, content, pastelang) raise Ricer::ExecutionException.new("No URI") if paste.url.nil? || paste.url.empty? rply(langkey, url: paste.url, title: title, size: lib.human_filesize(paste.size), count: lines, ) rescue StandardError => e rply :err_paste_failed, reason: e.to_s end end end end end
class MZRTouchView < UIImageView weak_attr_accessor :touch def defaultTintColor @color ||= UIColor.colorWithRed(52/255.0, green:152/255.0, blue:219/255.0, alpha:0.8) end def defaultImage @image ||= begin rect = CGRectMake(0, 0, 60.0, 60.0) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) contextRef = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(contextRef, UIColor.blackColor.CGColor) CGContextFillEllipseInRect(contextRef, rect) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() image.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate) image end end def initWithImage(image, color:color) self.initWithFrame(CGRectMake(0.0, 0.0, 60.0, 60.0)).tap do self.image = image || self.defaultImage self.image = self.image.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate) self.tintColor = color || self.defaultTintColor end end def initWithCoder(decoder) fatalError("initWithCoder: has not been implemented") end end
Sequel.migration do change do create_table :home_characteristics_filters do primary_key :id String :bedrooms, :default => "" String :bathrooms, :default => "" String :sq_footage, :default => "0" end end end
class PrescriptionsController < ApplicationController def create @user = current_user @medication = Medication.last @prescriptions = PrescriptionsController.create!(user_id: @user.id, medication_id: @medication.id) render json: @prescriptions end def show @user = current_user @prescriptions = PrescriptionsController.find(@user.id) render json: @prescriptions end def update @user = current_user @prescriptions = PrescriptionsController.find(@user.id) if @prescriptions.update(prescriptions_params) render json: @prescriptions else render json: @user.errors, status: :unprocessable_entity end end def destroy @prescriptions.destroy end private def prescriptions_params params.require(:@prescriptions).permit(user_ids: [], medication_ids: []) end end
require_relative 'acceptance_helper' feature 'Show questions list', %q{ In order to find interesting question As an user I wanted to see all questions } do given(:user_own) { create(:user) } given(:another_user) { create(:user) } given!(:question) { create(:question, user: user_own) } scenario "User can't see the delete button near the other users questions" do sign_in(another_user) visit questions_path expect(page).to have_no_text('Delete') end scenario 'User push the delete button and question is deleting' do sign_in(user_own) visit questions_path click_on 'Delete' expect(page).to have_no_text(question.body) end scenario 'Non-authorizied user cannot see the delete button' do visit questions_path expect(page).to have_no_text('Delete') end end
class Event < ApplicationRecord has_many :participations has_many :circles, through: :participations has_many :checks, through: :participations has_many :errands, through: :participations has_many :twitter_informations has_many :webcatalog_informations end