text
stringlengths
10
2.61M
require './00_tree_node.rb' class KnightPathFinder attr_reader :move_tree def initialize(pos) @pos = pos @visited_positions = [pos] self.build_move_tree end def build_move_tree root_node = PolyTreeNode.new(@pos) queue = [root_node] until queue.empty? current = queue.shift ...
# frozen_string_literal: true class AddReadyToTests < ActiveRecord::Migration[6.1] def change add_column :tests, :ready, :boolean, default: false end end
require 'spec_helper' describe Rfi do it { should have_many(:attachments) } it { should belong_to(:employee) } describe '#responses' do before :each do sender = FactoryGirl.create(:user) @parent_rfi = FactoryGirl.create(:rfi, :sender_id => sender.id) response1 = FactoryGirl.create(:rfi, :...
=begin A fixed-length array is an array that always has a fixed number of elements. Write a class that implements a fixed-length array, and provides the necessary methods to support the following code: =end class FixedArray attr_accessor :array def initialize(number_of_elements) @array = Array.new(number_...
module Iugu class Bank < APIResource include Iugu::APIFetch def withdrawals url = "https://api.iugu.com" return APIRequest.request("GET", "#{url}/v1/transfers") end end end
class ImageAsset < ApplicationRecord has_many_attached :uploads end
class RemoveForeignKeyFromCommentsSteps < ActiveRecord::Migration[5.2] def change remove_foreign_key :comments, :steps end end
# frozen_string_literal: true module Jiji::Utils class PersistenceUtils def self.get_or_create(get, create) entity = get.call return entity if entity begin create.call rescue Mongo::Error::OperationFailure => e raise e unless e.to_s =~ /E11000/ return get.call |...
# frozen_string_literal: true # See en.csv.descriptions in ./config/locales/heliotrope.en.yml for metadata field descriptions module Sighrax class Monograph < Work private_class_method :new def contributors vector('creator_tesim') + vector('contributor_tesim') end def cover_representative ...
# You need RubyUnit and MS Excel and MSI to run this test script require 'rubyunit' require 'win32ole' require 'oleserver' class TestOLEMETHOD < RUNIT::TestCase include OLESERVER def setup @excel_app = WIN32OLE_TYPE.new(MS_EXCEL_TYPELIB, 'Application') end def test_s_new m = WIN32OLE_METHOD.new(@exc...
class CreateSubjectPoints < ActiveRecord::Migration def change create_table :subject_points do |t| t.integer :small_item_id t.integer :project_subject_id t.integer :point_50 t.integer :point_90 t.timestamps end end end
require "#{Rails.root}/db/chores/proposal_and_step_status_updater" describe ProposalAndStepStatusUpdater do describe ".run" do it "renames cancelled -> canceled for proposals" do proposal = build(:proposal, status: "cancelled") proposal.save(validate: false) ProposalAndStepStatusUpdater.run ...
unit_tests do include Sinatra::GeneralHelpers include Sinatra::WebhookHelpers test "new pr payload_type" do new_pr_payload = { 'action' => 'opened', 'repository' => {'full_name' => "org/user"}, 'number' => 1, 'pull_request' => {'number' => 1, 'body' => "awesome pr"} } ...
feature "Registration Unit - Edit" do context 'Visitor' do scenario "Access invalid" do registration_unit = create(:registration_unit) visit edit_registration_unit_path registration_unit expect(current_path).to eq new_session_path end end context 'Admin'...
When /^I run a plugin with the following methods:$/ do |methods| steps %Q{ Given a file named "check_foo" with: """ require 'nagiosplugin' class Foo < NagiosPlugin::Plugin #{methods} end Foo.new.run """ When I run `ruby check_foo` } end Then /^the plugin should print "([^"]*)"$/ do...
class AddAasmStateToItems < ActiveRecord::Migration def change add_column :items, :aasm_state, :string, null: false add_column :items, :published_at, :timestamp end end
class Report < ActiveRecord::Base belongs_to :reportable, polymorphic: true belongs_to :reporter, class_name: "User" end
class CreateQuestDefinitionModel < ActiveRecord::Migration def self.up rename_table :quests, :quest_definitions create_table :quests do |t| t.string :why t.integer :quest_definition_id t.integer :user_id t.timestamps end create_table :quest_objectives do |t...
require 'rails_helper' RSpec.describe Phone, type: :model do it 'has a valid factory' do expect(create :phone).to be_valid end end
# frozen_string_literal: true class FeedsIndexSerializer < ApplicationSerializer attributes :feeds, :next_path, :prev_path def feeds ActiveModel::Serializer::CollectionSerializer .new(object.with_articles, serializer: FeedArticlesSerializer) end def next_path File.join(root_path, 'page', object...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can...
def iterative_factorial(n) (1..n).inject(:*) end puts iterative_factorial(6) def recursive_factorial(n) # Base case return 1 if n <= 1 # Recursive call n * recursive_factorial(n-1) end puts recursive_factorial(6) # fibonacci # def fib(n) # return n if n < 2 # fib(n-1) + fib(n-2) # end # memoization...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Major.create(:name...
class AddStatsAndStatusToBattleFace < ActiveRecord::Migration def change add_column :battle_faces, :attack, :integer add_column :battle_faces, :defense, :integer add_column :battle_faces, :speed, :integer add_column :battle_faces, :status, :string add_index :battle_faces, :status end end
require 'chemistry/dsl' Chemistry::DSL.element "Cn" do symbol "Cn" atomic_number 112 atomic_weight 285 melting_point end
module ApplicationHelper def alert_class(name) alert_str = case name.to_sym when :error, :alert "alert-error" when :success "alert-success" when :info, :notice "alert-info" else "" end return "alert #{alert_str}" end end
Dado('el plan con nombre {string}') do |nombre_plan| @request = { 'nombre': nombre_plan } @response = Faraday.post(PLANES_URL, @request.to_json, 'Content-Type' => 'application/json') end Cuando('consulto los planes disponibles') do @response = Faraday.get(PLANES_URL, 'Content-Type' => 'application/json') ...
# frozen_string_literal: true class LayersController < ApplicationController before_action :set_layer, only: %i(show edit update destroy) # GET /layers # GET /layers.json def index @layers = Layer.all end # GET /layers/1 # GET /layers/1.json def show; end # GET /layers/new def new @layer...
require('spec_helper') describe('Stylist') do describe('.all') do it('will start as an empty array') do expect(Stylist.all()).to(eq([])) end end describe('#==') do it('is the same stylist if they have the same name') do stylist1 = Stylist.new({:name => "John Smith", :phone =>'312-867-530...
require 'van' require 'dockingstation' describe Van do it {expect(subject).to respond_to(:load).with(1).argument } it {expect(subject).to respond_to :unload} describe '#load' do let (:bike) {double(:bike)} it 'adds bike to van' do bike_count = subject.bikes.count subject.load(bike) expe...
require_relative './rest_shared_context' describe "device update" do include_context "rest-context" UPDATEDMODEL = 'update_model' before(:each) do Device.destroy_all end def update_device token, device_token = 'device_token', new_device_token = 'new_device_token' url = "#{@servername_with_credenti...
class Classification < ActiveRecord::Base self.table_name = 'lessons_words' acts_as_list scope: :lesson with_options inverse_of: :classifications, touch: true do belongs_to :lesson belongs_to :word end validates :lesson, :word, presence: true end
class Story < ApplicationRecord belongs_to :food belongs_to :user has_many :comment, -> { order "created_at DESC" } has_one_attached :image validates :title, presence: true validates :content, presence: true validates :location, presence: true def next # if the fir...
# TODO See if this can be refactored to make use of some of the Choices code. module FormtasticBootstrap module Inputs class BooleanInput < Formtastic::Inputs::BooleanInput include Base def to_html input_wrapping do hidden_field_html << label_with_nested_checkbox e...
task default: :usage task :usage do sh 'rake -T' end desc 'run' task :run do system('sbt run') end desc 'dev' task :dev do system('sbt "~reStart"') end
module Cypress class Version def self.current() return APP_CONFIG["version"] end def self.measures() return APP_CONFIG["measures_version"] end def self.mpl() return APP_CONFIG["mpl_version"] end end end
describe AttachmentsController do describe 'permission checking' do let (:proposal) { create(:proposal, :with_parallel_approvers, :with_observers) } let (:params) {{ proposal_id: proposal.id, attachment: { file: fixture_file_upload('icon-user.png', 'image/png') } }} before do stub_r...
class CreatePaymentTypes < ActiveRecord::Migration def up execute <<-SQL create sequence payment_types_id_seq; create table payment_types ( id integer not null default nextval('payment_types_id_seq'), type varchar(128) not null unique check (length(type) > 0), ...
class FixFieldSizesAndSuch < ActiveRecord::Migration def self.up change_column :users, :display_name, :string, :limit => 50, :null => true change_column :stanzas, :title, :string, :limit => 100, :null => false add_index :users, [:short_name], :unique => true, :name => 'short_name_unique' end def self...
json.array!(@user_shipments) do |user_shipment| json.extract! user_shipment, :id, :user_id, :shipment_id, :role json.url user_shipment_url(user_shipment, format: :json) end
class MapsController < ApplicationController layout 'mapdetail', :only => [:show, :preview, :warp, :clip, :align, :activity, :warped, :export, :metadata] before_filter :store_location, :only => [:warp, :align, :clip, :export, :edit ] before_filter :check_administrator_role, :only => [:publish, :edit] ...
class AddPostFlagsToEventPost < ActiveRecord::Migration def change add_column :event_posts, :home_flag, :boolean add_column :event_posts, :visiting_flag, :boolean end end
class ChangeWaveHeightTypeInEntries < ActiveRecord::Migration def self.up change_column :entries, :wave_height, :text end def self.down change_column :entries, :wave_height, :decimal end end
# == Schema Information # # Table name: orders # # id :integer not null, primary key # user_id :integer # total :decimal(8, 2) # status :integer default(0) # comment :string # created_at :datetime not null # updated_at :datetime not null # require 'rails_...
require 'spec_helper' describe Question do it "recognizes a question with all required attributes" do question = Factory(:question) question.valid?.should be_true end it "requires a title" do lambda { Factory(:question, title: nil) }.should raise_error ActiveRecord::RecordInvalid, "Validation failed...
require_relative 'test_helper' require_relative '../lib/invoice_item' class InvoiceItemTest < Minitest::Test def setup @invoice_item = InvoiceItem.new({:id => 6, :item_id => 7, :invoice_id => 8, :quant...
class HousesController < ApplicationController def index @house = House.first() @houses = House.search(params[:search_input]).page(params[:page] || "1").per(10) @markers = House.markefy(@houses) respond_to do |format| format.html format.js end end def search @houses = Hou...
class EntriesController < ApplicationController before_action :set_entry, only: [:show, :edit, :update, :destroy] def show end def new student = current_user.students.find(params[:student_id]) @entry = student.entries.build end def create @student = current_user.students.find(params[:st...
class AddImageIdToNotifications < ActiveRecord::Migration def change add_column :notifications, :image_id, :integer end end
# frozen_string_literal: true require 'quandl' require 'lru_redux' # === 統計的裁定取引エージェント class StatisticalArbitrageAgent include Jiji::Model::Agents::Agent def self.description <<-STR 統計的裁定取引エージェント STR end # UIから設定可能なプロパティの一覧 def self.property_infos [ Property.new('pairs', ...
require 'test_helper' class AlbumsControllerTest < ActionController::TestCase test "should get index" do get :index, :name => 'honeymoon' assert_response :success album = assigns(:album) refute_nil album assert_equal "honeymoon", album.uri_id refute_nil album.photograph assert_equal albu...
# frozen_string_literal: true # Create Import worker for background processing class ImportWorker include Sidekiq::Worker attr_accessor :import, :from_date, :user def initialize(import) self.import = import self.from_date = DateTime.new(Time.now.year - Import.get_years_to_retrieve, 1, 1) self.user =...
class AddSchedulatorIdAndSectionIdToSchedulatorRelationship < ActiveRecord::Migration def change add_column :schedule_relationships, :schedulator_id, :integer add_column :schedule_relationships, :section_id, :integer end end
# frozen_string_literal: true require 'dotenv' module Tzispa class Env def initialize(env: ENV) @env = env end def [](key) @env[key] end def []=(key, value) @env[key] = value end def key?(key) @env.key? key end def load!(path) return unless defi...
require 'article_readingtime/version' require 'nokogiri' WORDS_PER_MINUTE = 275 IMAGE_MAX = 15 IMAGE_MIN = 3 IMAGE_STEP = 1 module ArticleReadingtime def self.estimate_html(html, options = {}) wpm = options[:wpm] || WORDS_PER_MINUTE images_options = default_image_options(options[:images] || {}) doc = ...
require_relative "utils/constants" require_relative "error" require "base64" require "net/http" require "json" API_VERSION = "/v1" module AlgoSDK class KmdClient attr_reader :kmd_token, :kmd_address, :headers def initialize(kmd_token, kmd_address, headers) @kmd_token = kmd_token @kmd_address =...
## # $Id$ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' class Metasploit3 < Msf::E...
# encoding: utf-8 require File.expand_path('../spec_helper', __FILE__) describe Darian::Time do before do earth = Time.parse('2012-05-16 10:00:00 UTC') @mars = Darian::Time.from_earth(earth) end it "should convert Earth time to Mars" do expect(@mars.year).to eq 214 expect(@mars.month).to eq ...
class UserMailer < ActionMailer::Base default from: "james@animalminder.com", bcc: "james.davisphd@gmail.com" # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.user_mailer.signup_confirmation.subject # def signup_confirmation(user) @us...
Rails.application.routes.draw do delete 'advices/destroy/:id', to: 'advices#destroy', as: 'advice_cancel' scope '/(:locale)', defaults: { locale: 'es' }, constraints: { locale: /es|en/ } do # Main page get '/', to: 'welcome#index' root 'welcome#index' get 'welcome/admin' get 'welcome/super_ad...
require 'rails_helper' feature "Signing in" do background do User.create(:email => 'user@examp.com', :password => '12345678', :username => 'vasya') end scenario "Signing in with correct credentials" do visit new_user_session_path fill_in :user_email, :with => 'user@examp.com' fill_in :user_passw...
# encoding: utf-8 dir = File.join(File.dirname(__FILE__), 'darian') require File.join(dir, 'version') require File.join(dir, 'date_methods') require File.join(dir, 'time') require File.join(dir, 'date') # Darian Mars calendar. # # mars_time = Darian.from_earth(earth_time) module Darian class << self # Conver...
require 'rubycraft/block_type' module RubyCraft # A minecraft block. Its position is given by a coord[x, z, y] class Block attr_accessor :block_type, :pos, :data def initialize(blockType, data = 0) @blockType = blockType @data = 0 end def self.get(key) new BlockType.get key ...
class Mention include Mongoid::Document include Mongoid::Geospatial field :topic, type: String field :name, type: String field :slug, type: String field :depiction, type: String field :start, type: DateTime field :finish, type: DateTime field :score, type: Float field :location, type: Point spatia...
# encoding: UTF-8 class EducationalInstitution < ActiveRecord::Base include Accessable include Historiable include Usernamed include ProfileImageable include ProfileCoverImageable include PubsubConcerns::Publisher include ResourceVisibilitable include Searchable attr_accessor :relation_with_me, :can...
require_relative 'demo_app_page' class EditAccountPage < DemoAppPage path '/users/edit' validate :title, /Demo web application - Edit User\z/ section :errors element :cancel_account_button, :button, 'Cancel my account' element :update_account_btn, :button, 'Update' element :name, :fillable_field, 'user_nam...
# frozen_string_literal: true class FloatPlansController < ApplicationController secure! secure!(:float, only: %i[index refresh]) title!('Float Plans') after_action :slack_notification, only: :create def index @float_plans = FloatPlan.includes(:float_plan_onboards).all end def show @float_pla...
# build a program that asks a user for the length and width # of a room in meters # and then displays the area of the room in both sq meters and sq feet # note: 1 sq meter == 10.7639 sq ft # Example run: # # Enter the length of the room in meters: # 10 # Enter the width of the room in meters: # 7 # The area of the ...
class AddTimeCompletedToChores < ActiveRecord::Migration def change add_column :chores, :time_completed, :time end end
require 'test_helper' class MoviesControllerTest < ActionDispatch::IntegrationTest def setup @movie = movies(:one) end test "should redirect create when not logged in" do assert_no_difference 'Movie.count' do post movies_path, params: { movie: { name: "Movie1", comment: "Comment1" } } end ...
require 'qiita' require 'fileutils' require 'yaml' ACCESS_TOKEN = ENV['QIITA_ACCESS_TOKEN'] TEAM_DOMAIN = ENV['QIITA_TEAM_DOMAIN'] ARTICLE_DIR = 'data/posts/' META_DIR = 'data/meta/' EXT = '.md' META_EXT = '.yml' class QiitaExporter def initialize(access_token, team_domain) @client = Qiita::Client.new(access_to...
require_relative 'library_item' class Video < LibraryItem def initialize(director, title, num_copies, playtime) @director = director @title = title @num_copies = num_copies @playtime = playtime end def display puts "\nVideo ----- \n" \ " Director: #{@director}\n" \ " Title: #{@ti...
class AddShareOnProfileToProjectMember < ActiveRecord::Migration def change add_column :project_members, :share_on_profile, :boolean, :default => false end end
class Song < ActiveRecord::Base validates :title, presence: true validate :must_have_valid_release_date_if_released validate :must_not_release_same_song_twice_in_a_year def must_have_valid_release_date_if_released if released && release_year.nil? errors.add(:release_year, "has no release year") e...
class UserDecorator < ApplicationDecorator decorates_association :post decorates_association :comment def to_s "#{self.first_name} #{self.last_name}" end end
class StreetType < ActiveRecord::Base has_many :street_locations end
# frozen_string_literal: true require 'rails_helper' require 'pdf_fill/hash_converter' describe PdfFill::HashConverter do let(:hash_converter) do described_class.new('%m/%d/%Y') end describe '#set_value' do def verify_extras_text(text, metadata) extras_generator = hash_converter.instance_variable...
require 'PasswordHash' class Voter < ActiveRecord::Base belongs_to :election has_one :ballot, dependent: :destroy validates :name, presence: true, allow_blank: false validates_uniqueness_of :name, scope: :election_id obfuscate_id :spin => 32767 def password self.hashed_password ...
class Pin < ActiveRecord::Base has_many :users belongs_to :user end
# frozen_string_literal: true require "spec_helper" describe Decidim::Opinions::Metrics::EndorsementsMetricManage do let(:organization) { create(:organization) } let(:participatory_space) { create(:participatory_process, :with_steps, organization: organization) } let(:component) { create(:opinion_component, :pu...
class CcTool < Formula desc "Support for Texas Instruments CC Debugger." homepage "https://sourceforge.net/projects/cctool" head "https://github.com/dashesy/cc-tool.git" depends_on "boost" => :build depends_on "pkg-config" => :build depends_on "autoconf" => :build depends_on "automake" => :build depend...
class ActivitiesController < ApplicationController before_action :authenticate_user! def index @upcoming_activities = Activity.upcoming_two_weeks end end
require 'test_helper' # Most of the OrderProduct model testing is being done with the Order model because # OrderProduct is nested within Order and is edited through an order via nested attributes class OrderProductTest < ActiveSupport::TestCase test "should not create order_product with no product" do order_p...
class AddIsValidateToUsers < ActiveRecord::Migration def self.up add_column :user_profiles, :uuid, :string, :limit=>50 add_column :user_profiles, :password_reset, :string,:limit=>35 end def self.down remove_column :users, :is_validate end end
class User < ApplicationRecord # validations validates_presence_of :email, :password end
class Admin::OrderItemsController < ApplicationController def update order_item = OrderItem.find(params[:id]) order_item.update(order_item_params) order_item.order_status_auto_update order_item.make_complete_auto_update order = order_item.order redirect_to admin_order_path(order) end ...
class ChangeArticlesToPublications < ActiveRecord::Migration[5.1] def change rename_table :articles, :publications end end
require 'elasticsearch/model' class Place < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks include Hateoas has_many :reviews, dependent: :destroy, inverse_of: :place has_and_belongs_to_many :cuisines geocoded_by :address validates :name, presence: true validat...
# frozen_string_literal: true require "tmpdir" require "open3" module ZoomSlack module ProcessDetector class Mac < Base SCRIPT = "in_zoom_meeting.applescript" COMPILED_SCRIPT = "in_zoom_meeting.scptd" def initialize(open: Open3) self.open = open end def running? c...
class Post < ApplicationRecord #Won't save values with the same heading validates :heading, presence: true, uniqueness: true end
class Api::V1::TopicsController < Api::V1::ApplicationController def index valid_communities = @current_user.communities @topics = Topic.where(community_id: valid_communities.pluck(:id)).order(created_at: :desc) @topics = @topics.ransack(params[:q]).result if params[:q].present? @topics = paginate(@t...
def atoi str case str when '0' return 0 when '1' return 1 when '2' return 2 when '3' return 3 when '4' return 4 when '5' return 5 when '6' return 6 when '7' return 7 when '8' return 8 when '9' return 9 end end def string_to_integer input num = 0 tens ...
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :restaurants do # member do # post 'reviews', to: "reviews#create", as: :restaurant_reviews # end resources :reviews, only: [:create] end end
# This is rock paper scissors game # create class Scores # Add Lizard and Spock # # class history class History def initialize @history = [] end def display @history.map(&:to_s) end def <<(move) @history << move end end # class Score class Score attr_reader :points, :win_round def initi...
class AddCollegeToCourses < ActiveRecord::Migration def change add_reference :courses, :college, index: true add_foreign_key :courses, :colleges end end
class ApplicationController < ActionController::Base before_action :basic_auth before_action :configure_permitted_parameters, if: :devise_controller? # すべてのアクションの前に実行 private def basic_auth authenticate_or_request_with_http_basic do |username, password| # username == "furima" && password == "1111"...
class ActiveFamiliesController < ApplicationController def index @families = Family.active.by_last_name.page(params[:page]).per(10) end end
module Helpers def file_path(template, git, dest) File.join(fastlane_path(git.dir.path, dest), base_name(template)) end def base_name(template) File.basename(template, '.erb') end def fastlane_path(git_path, dest) File.join(git_path, dest) end end
class Realogy::Entity < ApplicationRecord self.table_name = 'realogy_entities' validates :type, presence: true validates :entity_id, presence: true, uniqueness: true validates :last_update_on, presence: true def needs_updating? self.new_record? || self.last_update_on_changed? || self.data.blank? end ...
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. # k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. # You may not alter the values ...