text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe 'users#destroy', type: :request do subject(:make_request) do jsonapi_delete "/api/v1/users/#{user.id}", headers: auth_headers(user) end describe 'basic destroy' do let!(:user) { create(:user) } it 'updates the resource' do expect(V1::UserResource).to rece...
module Bosh::Director module DeploymentPlan class AgentStateMigrator def initialize(logger) @logger = logger end def get_state(instance) @logger.debug("Requesting current VM state for: #{instance.agent_id}") agent = AgentClient.with_agent_id(instance.agent_id, instance.n...
# Добавляет аргумент pagination к полям с connection_type, и передает его в context. module Extensions class CustomConnectionExtension < GraphQL::Schema::Field::ConnectionExtension def apply field.argument(:pagination, Arguments::Pagination, required: false) super end def resolve(object:, ar...
class QuoteReminders # Search all incomplete quote nearly expired time and alert to user def self.incomplete_reminder quotes = Quote.incomplete_reminder reminders = {} quotes.each do |quote| reminders[quote.account] = '' if reminders[quote.account_id].nil? reminders[quote.account] += "I...
# frozen_string_literal: true require "json" module Fastlane module Actions class ReadJsonAction < Action def self.run(params) json_path = params[:json_path] @is_verbose = params[:verbose] print_params(params) if @is_verbose unless File.file?(json_path) put_erro...
module RSpec module Matchers class BeAKindOf include BaseMatcher def matches?(actual) super(actual).kind_of?(expected) end end # Passes if actual.kind_of?(expected) # # @example # # 5.should be_kind_of(Fixnum) # 5.should be_kind_of(Numeric) # 5.sho...
#require 'digest/sha1' module Admin class User < ActiveRecord::Base has_and_belongs_to_many :roles, join_table: :users_roles has_secure_password #-- ------------------------------------------------------------- # Validations # ## # Regular expression to verify email pattern VALID_EMA...
class AddKindToSettings < ActiveRecord::Migration def change add_column :settings, :kind, :string, default: "string", null: false end end
# coding: utf-8 require 'spec_helper' include Staticman class ProxyRequestTest include ProxyRequest end describe ProxyRequest do describe '#request_context' do context 'host is config value' do let(:request) { ProxyRequestTest.new.request_context } it { request.should be_kind_of ActionDispatch::T...
version = `cat ./version`.strip Pod::Spec.new do |s| s.name = 'CZiti-iOS' s.version = version s.summary = 'Ziti SDK for Swift (iOS)' s.homepage = 'https://github.com/openziti/ziti-sdk-swift' s.author = { 'ziti-ci' => 'ziti-ci@netfoundry.io' } s.license = { :type => 'Apache-2.0...
# https://www.codewars.com/kata/5270d0d18625160ada0000e4 def score(dice) h = dice.each_with_object(Hash.new(0)) { |e, h| h[e] += 1 } result = 0 h.each do |k, v| if v >= 3 result += case k when 1 then 1000 else k * 100 end v -= 3 end wh...
class Prime < ActiveRecord::Base validates :number, presence: true, uniqueness: true, numericality: {only_integer: true, greater_than: 0} end
FactoryBot.define do factory :order do purchase_amount {Faker::Number.between(10000000000000, 90000000000000)} payment_price {Faker::Number.between(500,30000)} end end
class CityTripsController < ApplicationController before_action :require_login def index @my_city_trips = CityTrip.my_trips(session[:user_id]) end def show @city_trip = CityTrip.find(params[:id]) end def new trip_id = params[:format] @trip = Trip.find(trip_id) ...
# frozen_string_literal: true # HideCompany class class HideCompany < ApplicationRecord belongs_to :portfolio validates :name, uniqueness: { scope: :portfolio_id } end
class AddColumnsToUsers < ActiveRecord::Migration def change add_column :users, :modelling_agency, :string add_column :users, :phone_number, :string add_column :users, :country, :string add_column :users, :town, :string end end
class CreateDepositions < ActiveRecord::Migration[6.0] def change create_table :depositions do |t| t.string :reason t.string :excuse t.string :dep_city t.string :arr_city t.datetime :departure, default: nil t.datetime :arrival, default: nil t.boolean :forward t.date...
class SpecialLinesController < ApplicationController # results page for all special line products def index @response = HTTParty.get(ENV["JSON_API_URL"] + "/products.json").sort_by { |hash| hash['id'].to_i } end # individual show page for each special line product def show unless !/\A\d+\z/.match(params[:id]...
require 'rubygems' require 'sinatra' require './environment' mime_type :ttf, "application/octet-stream" mime_type :woff, "application/octet-stream" configure do set :views, "#{File.dirname(__FILE__)}/views" set :public, "#{File.dirname(__FILE__)}/public" end error do e = request.env['sinatra.error'] Kernel.p...
class Pile < ApplicationRecord belongs_to :game has_many :cards belongs_to :game_player end
class SubscribersController < ApplicationController def create subscriber = Subscriber.new(subscriber_params) if subscriber.save flash[:success] = t('flashes.subscriber.created') else flash[:error] = t('flashes.subscriber.error') end redirect_to :back end private def subscribe...
require 'rails_helper' require 'database_cleaner' RSpec.describe Api::V1::Invoices::MerchantsController, type: :controller do describe "GET /invoice/:id/merchant" do it "returns a specific invoices merchant" do c31 = Customer.create c32 = Customer.create m1 = Merchant.create m2 = Merchan...
module Binged module Search # A class that encapsulated the Bing Web Search source # @todo Add support for adult and market filtering class Web < Base include Filter include Pageable SUPPORTED_FILE_TYPES = [:doc, :dwf, :feed, :htm, :html, :pdf, :ppt, :ps, :rtf, :text, :txt, :xls] ...
# frozen_string_literal: true class PokemonSerializer < ActiveModel::Serializer attributes :pokedex_number, :name, :pokedex_entry, :weight, :height end
module AsciiArt class Brush attr_accessor :stroke, :x_pos, :y_pos, :lifted def initialize(stroke, x, y) @stroke = stroke @x_pos = x @y_pos = y @lifted = false end def raise_or_lower @lifted = !@lifted end def move(x, y) @x_pos = x @y_pos = y end ...
require 'rubygems' require 'digest' require 'json' require 'rest-client' require 'pry' class ApiRest $url def initialize(testnet) $url = "https://gameathon.mifiel.com/api/v1/games/#{testnet}/" end def query_get(resource) puts "*********************************************************************" ...
# Scrapes all images from a given page # Command line arguments : website_url require "open-uri" require "nokogiri" count = 1 if ARGV[0] puts "Loading" html = Nokogiri::HTML(open(ARGV[0])) puts "Loaded\n\n" srcs = html.css("img") srcs.each do |img_tag| puts "Opening #{count}" open(img_tag['src']) do |img| ...
# frozen_string_literal: true class DrilldownSearchesController < ApplicationController before_action :admin_required before_action :set_drilldown_search, only: %i[show edit update destroy] def index @drilldown_searches = DrilldownSearch.all end def show; end def new @drilldown_search ||= Drilld...
require 'test_helper' class Api::UsersControllerTest < ActionDispatch::IntegrationTest # test "the truth" do # assert true # end test 'POST #create' do it "validates the presence of the user's username and password" do post :create, params: { user: {username: 'Batman@supermansucks.net', password: '...
# frozen_string_literal: true module Statistics class Views attr_reader :log # @param [Log, #lines, #extract_url_from(..), #extract_ip_from(..)] # a Log instance with corresponding interface def initialize(log) @log = log end def generate! analyze! end private # @r...
require "./ratio" class ParserError < StandardError; end class Parser def initialize(s) @s=s @pos=0 end def peak if @pos>=@s.length raise ParserError.new end @s[@pos] end def next v=self.peak @pos+=1 v end def e...
require_relative '../../../spec_helper' require_relative '../factories/position' require_relative '../factories/time_slot' require_relative '../factories/user' describe TimeSlot do before(:all) do Position.delete_all TimeSlot.delete_all User.delete_all end it "create time_slot" do lambda { ...
# -*- coding: utf-8; -*- # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file to you under the Apache License, Version 2.0 (the "License"...
require 'test_helper' class ThreeScale::SemanticFormBuilderTest < ActionView::TestCase include Formtastic::SemanticFormHelper class Dummy extend ActiveModel::Naming attr_reader :errors, :title, :author def initialize @errors = ActiveModel::Errors.new(self) @errors.add(:title, 'error 1')...
# frozen_string_literal: true require 'spec_helper' class ManyToOneSpec < AssociationFilteringSpecs before do drop_tables DB.create_table :artists do primary_key :id end DB.create_table :albums do primary_key :id foreign_key :artist_id, :artists end DB.run <<-SQL I...
class AddTargetableFieldsToTarget < ActiveRecord::Migration def change add_column :targets, :targetable_id, :integer add_column :targets, :targetable_type, :string end end
module ApplicationHelper def no_turbolink? if content_for(:no_turbolink) { data: {no_turbolink: true} } else { data: nil } end end end
class AddJobsInquiryFormToGlobalSettings < ActiveRecord::Migration def change add_column :global_settings, :jobs_inquiry_form, :text end end
# # Copyright 2011 National Institute of Informatics. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
require "test_helper" class DashboardsControllerTest < ActionController::TestCase def dashboard @dashboard ||= dashboards :one end def test_index get :index assert_response :success assert_not_nil assigns(:dashboards) end def test_new get :new assert_response :success end def t...
# @param [Method] f function def prm(f, a, b, n) h = (b - a) / n.to_f res = 2.0 (1..n).each do |i| x = a + i * h - h / 2.0 res += f.call(x) end res *= h end # @param [Method] f function def trp(f, a, b, n) h = (b - a) / (n.to_f - 1) res = f.call(a) / 2.0 (1...n - 1).each do |i| x = a + i * ...
class Admin < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_one :admin_account accepts_nested_attributes_f...
Gem::Specification.new do |s| s.name = 'forkout' s.version = '0.0.1' s.has_rdoc = false s.extra_rdoc_files = ['README', 'LICENSE'] s.summary = 'forks a block' s.description = 'forks a list to a block using Rinda, kinda unstable' s.author = 'Szczyp' s.email = 'qboos@wp.pl' s.homepage = 'http://github.c...
require 'rubygems' require 'dogapi' def set_downtime() api_key = ENV['DD_API_KEY'] app_key = ENV['DD_APP_KEY'] dog = Dogapi::Client.new(api_key, app_key) start_ts = Time.now.to_i end_ts = start_ts + (3 * 60 * 60) end_reccurrence_ts = start_ts + (1 * 7 * 24 * 60 * 60) recurrence = { 'type' => 'week...
class AddImapWorkerStatusToProfile < ActiveRecord::Migration def change add_column :profiles, :imap_worker_started_at, :timestamp add_column :profiles, :imap_worker_completed_at, :timestamp end end
# frozen_string_literal: true module Dry module Types # Schema is a hash with explicit member types defined # # @api public class Schema < Hash # Proxy type for schema keys. Contains only key name and # whether it's required or not. All other calls deletaged # to the wrapped type. ...
class ProjectType < ActiveRecord::Base MAX_TYPE_NAME = 200 has_many :feature_prices has_many :project_features, through: :feature_prices validates :type_name, presence: true, length: { maximum: MAX_TYPE_NAME } end
class ProfileEmailAccess < ActiveRecord::Base belongs_to :profile belongs_to :email_access end
# # Cookbook Name:: cubrid # Attributes:: pdo_cubrid # # Copyright 2012, Esen Sagynov <kadishmal@gmail.com> # # Distributed under MIT license # # Latest build numbers for each CUBRID PDO version in the form of 'version'=>'build_number'. build_numbers = {'9.1.0' => '0003', '9.0.0' => '0001', '8.4.3' => '0001', '8.4.0' ...
module Jekyll module MatlabDoc def loadFunctionDoc(name,style='long',codify=true,folder=nil,file=nil) if @context.registers[:site].data["settings"]["mvirt"]["useLocal"] base_url = @context.registers[:site].data["settings"]["mvirt"]["localCodePath"] else base_url = @context.registers[:s...
class User < ActiveRecord::Base validates :email, :confirmation => true validates :email_confirmation, :presence => true validates :email, uniqueness: { case_sensitive: false } has_secure_password has_one :profile has_many :comments has_many :user_workouts has_many :workouts, through: :user_workouts ...
class Gift < ApplicationRecord belongs_to :provider, class_name: 'User' belongs_to :receiver, class_name: 'User' belongs_to :meal end
class AddChampionToSeason < ActiveRecord::Migration[5.2] def change add_column :seasons, :champion_id, :integer, default: nil end end
$running_specs = true require './max_flower_shops_template.rb' require 'rspec' describe '#sort_intervals' do it 'sorts by right boundary' do expect(sort_intervals([[2,3], [1,2], [0,1]])).to eq([[0,1], [1,2], [2,3]]) end it 'takes the three shortest intervals' do expect(sort_intervals([[0,4], [1,4], [2...
require 'rails_helper' RSpec.describe Issue do describe 'validate of status' do let(:regular) { User.create(login: 'test', password: '123456', name: 'Mr. Test') } let(:manager) { User.create(login: 'manager', password: '123456', name: 'Mr. Manager', role: :manager) } [:in_progress, :resolved].each do |...
class CreateDoorCodes < ActiveRecord::Migration[6.0] def change create_table :doors_codes do |t| t.references :door, foreign_key: true, null: false t.references :code, foreign_key: true, null: false end add_index :doors_codes, [:door_id, :code_id], unique: true end end
class API::Cards < API::Base desc 'search program by tags' get '/programs/search' do payload = request.GET tags_query = payload["tags"] end desc "list all program from a certain channel" get '/programs' do @result = ProgramLib::programListV2Mobile end desc 'get program ...
require 'barometer' require 'date' class Fixnum def days # returns number that represents seconds in a day * N days self * 86400 end end # Define method for passing location and displaying weather def weather_forecast(usr_location) tomorrow = Time.now.strftime('%d').to_i + 1 barometer = Barometer.new(usr_lo...
require 'spec_helper' describe CampaignMailerHelper do before :each do include CampaignMailerHelper end it '' do end describe '#message' do it 'should return the path to a partial found in the messages folder' do partial_path = message 'test' partial_path.should == 'campaign_mai...
VAGRANT_BOX = 'bobfraser1/alpine316' VM_HOSTNAME = 'router' VM_NETWORK = 'vboxnet1' VM_IP = '192.168.60.2' VM_MEMORY = '2048' VM_CPUS = '2' PUBLIC_NET = 'eth0' PRIVATE_NET = 'eth1' INTERFACE = 'eth1' DOMAIN = 'example.com' DHCP_RANGE = '192.168.60.100,192.168.60.254,12h' Vagrant.configure('2') do |config| config.vm....
require 'factory_bot' def random_number number = Random.new number.rand(1..5) end FactoryBot.define do factory :user do sequence(:email) {|n| "user#{n}@example.com" } sequence(:username) {|n| "username#{n}" } password { "password" } password_confirmation { "password" } role { "member" } en...
class Interventi < ActiveRecord::Base #belongs_to :clienti, :foreign_key => "cliente_id" belongs_to :clienti has_many :comunicazionis, :dependent => :destroy validates :data, presence: true validates :intervento, presence: true, length: {minimum: 5 } validates :durata, presence: true end
################################################## # Generated by phansible.com ################################################## Vagrant.require_version ">= 1.5" # Check to determine whether we're on a windows or linux/os-x host, # later on we use this to launch ansible in the supported way # source: https://stacko...
class AffiliateProgramAddReviewWritingProgram < ActiveRecord::Migration def self.up add_column :affiliate_programs, :review_writing_program, :boolean, :default => true, :null => false end def self.down remove_column :affiliate_programs, :review_writing_program end end
require 'rails_helper' RSpec.describe "injurylocations/edit", type: :view do before(:each) do @injurylocation = assign(:injurylocation, Injurylocation.create!( name: "MyString", description: "MyString" )) end it "renders the edit injurylocation form" do render assert_select "form[ac...
class CarMake < ApplicationRecord belongs_to :car_post belongs_to :make_model end
# Encoding: UTF-8 # # Cookbook Name:: steam # Library:: resource_steam_app_windows # # Copyright 2015-2016, Jonathan Hartman # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www...
# one.rb # concatenating first and last name strings puts "Aaron " + "Saloff"
class Project < ApplicationRecord enum status: %i[pre_sale active closed archive] end
class CreateAdditionalLinks < ActiveRecord::Migration def self.up create_table :additional_links do |t| t.string :title t.string :tag t.boolean :published t.timestamps end AdditionalLink.create :title => "Your visa support", :tag => "http://blog.chavanga.com/2010/...
require 'rails_helper' RSpec.describe "Api::Books", type: :request do describe "GET /api/books" do it "should list all books" do FactoryBot.create(:book) FactoryBot.create(:book, title: 'Book 2') get api_books_path expect(response).to have_http_status(200) json = JSON.parse(respon...
# frozen_string_literal: true # Add 'name' column to User class AddNameToUser < ActiveRecord::Migration[5.2] def change add_column :users, :name, :string end end
require 'rails_helper' feature 'admin signs in', %Q{ As a signed up admin I want to sign in So that I can administrate to my account } do scenario 'specify valid credentials' do admin = FactoryBot.create(:admin_user) visit new_user_session_path fill_in 'Email', with: admin.email fill_in 'Pass...
require "test_helper" class Location::AchatsControllerTest < ActionDispatch::IntegrationTest setup do @location_achat = location_achats(:one) end test "should get index" do get location_achats_url assert_response :success end test "should get new" do get new_location_achat_url assert_re...
require 'test_helper' class MaileeTemplatesControllerTest < ActionController::TestCase setup do @mailee_template = mailee_templates(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:mailee_templates) end test "should get new" do get :new ...
module WastebitsClient class Invitation < Base attr_accessor :accepted_at, :claim_url, :company_id, :confirmation_token, :created_at, :email, :first_name, :id, :is_admin...
class CreateRequesters < ActiveRecord::Migration[5.2] def change unless table_exists? Requester.table_name create_table Requester.table_name do |t| t.string :name, comment: 'Identifica o nome do funcionario' t.string :email, comment: 'Identifica o email do funcionario' t.string :phon...
# == Schema Information # # Table name: student_applications # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # applicant_id :integer # semester_id :integer # why_join :text # resume_file_name :string(255)...
require 'wsdl_mapper/runtime/simpler_inspect' module WsdlMapper module Runtime class Port include SimplerInspect attr_reader :_soap_address, :_operations # @!attribute _operations # @return [Array<WsdlMapper::Runtime::Operation>] All operations contained in this port # @!attribu...
module Moonr class VariableStat < ASTElem def append another @list ||= [] @list << another self end def jseval(env) idexpr = IdExpr.new :id => id lhr = idexpr.jseval env if initialiser rhs = initialiser.jseval env value = rhs.get_value ...
# encoding: utf-8 control "V-52267" do title "The DBMS must use organization-defined replay-resistant authentication mechanisms for network access to non-privileged accounts." desc "An authentication process resists replay attacks if it is impractical to achieve a successful authentication by recording and replaying...
require "rails_helper" describe PickingTime do let(:monday) { PickingTime.create!(enabled: true, weekday: "monday", hour: "14:00", shop_id: 1) } let(:tuesday) { PickingTime.create!(enabled: true, weekday: "tuesday", hour: "10:00", shop_id: 1) } let(:wednesday) { PickingTime.create!(enabled: true, weekday: "wedne...
class Favourite < ApplicationRecord belongs_to :user belongs_to :myrecipe validates :myrecipe, presence: true, uniqueness: {scope: :user} end
class Partner < ActiveRecord::Base include PartnerRepository attr_accessible :name_ru, :description_ru, :logo has_many :partner_products validates :name_ru, presence: true state_machine initial: :active do before_transition any => :deleted do |obj, transition| obj.deleted_at = Time.current ...
module Parser module Cdl module ToDsl class HasOne < Methods def method_type :has_one end end end end end
class BtcUtils::Models::TxOut attr_reader :parent_tx def initialize parent_tx, raw @parent_tx = parent_tx @raw = raw end def amount BtcUtils::Convert.btc_to_satoshi @raw['value'] end def idx @raw['n'] end def addresses @raw['scriptPubKey']['addresses'] end def spent? res...
class Board attr_reader :max_height def self.build_stacks(stacks) Array.new(stacks) {Array.new()} end def initialize(stacks, height) raise "rows and cols must be >= 4" if stacks < 4 || height < 4 @max_height = height @stacks = Board.build_stacks(stacks) end def...
class AddDefaultToRequestStatus < ActiveRecord::Migration[6.0] def change change_column_default :requests, :request_status, "opened" end end
require_relative 'appointments' class Time attr_accessor :year, :month, :day, :hour, :minute def initialize(y, mo, d, h, mi = 0) @year = y @month = mo @day = d @hour = h @minute = mi end end
class AddDebitUriAndCreditUriToOrder < ActiveRecord::Migration def change add_column :orders, :debit_uri, :string add_column :orders, :credit_uri, :string end end
module Import class NoRelation < Resource attr_accessible :controller_logger, :input, :email, :resource_class attr_accessor :resource_class protected def parse_resource(resource) resource.gsub('*', '').strip end def append_existing_resources_criteria(resource) @...
require "test_helper" require "rbs/test" require "logger" return unless Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7.0') class RBS::Test::RuntimeTestTest < Minitest::Test include TestHelper def test_runtime_success assert_test_success assert_test_success(other_env: {"RBS_TEST_SAMPLE_SIZE" => '...
class GroupsController < ApplicationController before_filter :require_user, only: [:index, :new, :create, :invited, :join] def show @group = Group.find(params[:id]) authorize! :manage, @group respond_to do |format| format.html # show.html.erb format.json { render json: @group } e...
require 'pry' class Printer include Sorter def print_all output_1; output_2; output_3 end def output_1 puts "", "Output 1:" contacts = sorted_by_ascending_gender_and_last_name contacts.each do |contact| puts "#{contact.last_name} #{contact.first_name} #{contact.gender} #{contact.birth_da...
# encoding: UTF-8 module Decider class DeciderError < StandardError end class NotImplementedError < DeciderError def initialize(klass, method) super("#{klass.name} expects ##{method.to_s} to be defined by a subclass") end end end
require 'test_helper' describe DeliveryTypesController do setup do @shop = shops(:one) @delivery_type = delivery_types(:one) end test "should get index" do get :index, shop_id: @shop assert_response :success end test "should get new" do get :new, shop_id: @shop assert_response :succ...
module Bliss class Constraint attr_accessor :depth, :possible_values attr_reader :setting, :state def initialize(depth, setting, params={}) @depth = depth @setting = setting @possible_values = params[:possible_values].collect(&:to_s) if params.has_key?(:possible_values) @state = ...
class AddStatusToPubSubs < ActiveRecord::Migration def change add_column :pub_subs, :status, :string end end
require 'test_helper' class CategoryTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end test "sorts are stable" do # e is the expected result set and should be created in the # order we expect the array to arrive in after sorting e = [] e...
class CreateSendEmailMessages < ActiveRecord::Migration def change create_table :sent_email_messages do |t| t.string :subject t.text :to t.text :body t.string :status t.integer :user_id t.timestamps end end end