text
stringlengths
10
2.61M
class Equipment < ApplicationRecord belongs_to :equipment_type has_many :components has_many :images, as: :parent end
class ItemRevenueSerializer include FastJsonapi::ObjectSerializer attribute :name do |item| object = Item.find(item.id) object.name end attribute :description do |item| object = Item.find(item.id) object.description end attribute :unit_price do |item| object = Item.find(item.id) o...
desc "This task is called by the Heroku scheduler add-on" task :update_feed do puts "Updating feed..." puts "done." end
describe TodoList do let(:list) { TodoList.new(["do the dishes", "mow the lawn"]) } it "stores the list items given on initialization" do expect(list.get_items).to eq ["do the dishes", "mow the lawn"] end it "adds an item to the list" do list.add_item("mop") expect(list.get_items).to eq ["do the d...
#!/usr/bin/env ruby # :title: PlanR::Ident =begin rdoc Object describing the contents of a file or buffer. (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> =end module PlanR =begin rdoc Identification of code or data. The structure of the Ident object is derived from the output of libmagic and the file(1...
class CreateUps < ActiveRecord::Migration # ups # #额定容量 rated capacity #输出电压 output voltage #输入电压 input voltage #输入电压范围 voltage range #标称后备时间 backup time #转换时间 transition time #类型 ups_type #并机数量 link qty # #电池电压 battery voltage   #电池容量 battery capacity #电池型号 battery model #电池品牌 battery br...
class Asteroids::TransformComponent include Gamey::Component attr_accessor :position, :rotation def initialize @position = Gamey::Vector2.new @rotation = Gamey::Angle.in_degrees(0) end end
class AddDuedateToTasks < ActiveRecord::Migration def change add_column :tasks, :duedate, :date add_column :tasks, :hasduedate, :boolean end end
require File.dirname(__FILE__) + '/../../spec_helper' describe 'EC2.create_volume' do before(:all) do @ec2 = Fog::AWS::EC2.gen end after(:all) do @ec2.delete_volume(@volume_id) end it "should return proper attributes" do actual = @ec2.create_volume('us-east-1a', 1) actual.body['availabilit...
# Use the ruby documentation to determine what this code will print. # https://docs.ruby-lang.org/en/2.6.0/syntax/calling_methods_rdoc.html#label-Default+Positional+Arguments # When the method defines default arguments you do not need to supply all the arguments to the method. # Ruby will fill in the missing argum...
require 'rails_helper' include AdminHelpers RSpec.feature 'Updating admin profile' do scenario 'with valid data as an admin' do @admin = create(:admin) login_as(@admin, scope: :admin) visit admin_path click_on(class: 'profile-pic') click_on(class: 'my-profile-btn') expect(page).to have_con...
class Api::NavbarController < ApplicationController def index @animes = Anime.all end end
class Users::InvitationsController < Devise::InvitationsController protect_from_forgery before_action :configure_invite_params, only: [:create] before_action :configure_accept_invitation_params, only: [:update] def new super end def create params[:user][:team_id] = current_user.team_id params[...
class CreateSessionTable < ActiveRecord::Migration[5.0] def self.up create_table :sessions do |t| t.string :share_key t.string :init_color t.string :admin t.timestamps end end def self.down drop_table :sessions end end
class AddForeignKey < ActiveRecord::Migration def self.up add_foreign_key :places, :users, column: :user_id, primary_key: :id end end end
class Year def self.leap?(year) =begin Leap year rules: on every year that is evenly divisible by 4 except every year that is evenly divisible by 100 unless the year is also evenly divisible by 400 =end if (year % 4 == 0) leap = true if (year % 100 == 0) leap = false if...
# ================================================================================ # Part: # Desc: # ================================================================================ class PaymentMethod include Mongoid::Document include Mongoid::Timestamps # ...
# frozen_string_literal: true class MovieExporterJob < ApplicationJob queue_as :default def perform(user_id:, file_path:, **_args) MovieExporterService.new.call(file_path) MovieExportMailer.send_file(user_id, file_path).deliver_later end end
class Question < ActiveRecord::Base belongs_to :category has_many :choices has_many :responses, :through => :choice validates_presence_of :question def self.get_q_and_a(ids) left_outer_joins(:choices) .select(:id, :question) .select('choices.id as choice_id, choices.choice, choices.correct, choic...
# frozen_string_literal: true module Files class Settings attr_reader :options, :attributes def initialize(attributes = {}, options = {}) @attributes = attributes || {} @options = options || {} end # string - All supported image types def image_regex @attributes[:image_regex] ...
require 'byebug' require_relative '00_tree_node.rb' class KnightPathFinder attr_reader :visited, :root_node, :queue def initialize(start_pos) @root_node = PolyTreeNode.new(start_pos) @visited = [start_pos] @queue = [] build_move_tree end def self.valid_moves(pos) valids = [] valids ...
module VM2 class VM attr_accessor :name attr_accessor :debug attr_accessor :mem attr_accessor :pc attr_accessor :rel_base attr_accessor :status attr_accessor :input attr_accessor :output attr_accessor :input_fn attr_accessor :output_fn def initialize(mem) @name ...
module Exchanges module Cryptoid extend ExchangeMethods extend self def configured? !!settings["addresses"] end def pairs @pairs ||= Config.market.pairs(exchange_name) rescue NameError [] end def btc_pair symbol ticker symbol end def addresses ...
#### Writtten By: Oryan Omer#### #Declare Environment GUI = false # Enable/Disable GUI RAM = 2048 # Default memory size in MB # Network configuration DOMAIN = ".xxx" NETWORK = "192.168.50." NETMASK = "255.255.255.0" SYNC_FOLDER = "/opt/elk" #...
class AddFkToSubjects < ActiveRecord::Migration def up add_foreign_key "subjects", "streams", name: "subject_fk" end def down remove_foreign_key "subjects", name: "subject_fk" end end
require 'faraday' require_relative 'resumen_presenter' class ResumenService def self.get_resumen(id_telegram) response = Faraday.get("#{ENV['API_URL']}/resumen?id=#{id_telegram}&from=telegram") return ResumenPresenter.parse_resumen(response.body) if response.status == 200 return 'Parece que no estás afi...
class GymClassSerializer < ActiveModel::Serializer attributes :id, :level, :description, :start_time, :end_time, :formatted_students, :formatted_class_workout_plans # has_one :user # has_many :class_students has_many :class_workouts # has_many :students, through: :class_students has_many :workout_plans, th...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/bionic64" config.vm.hostname = "magento2-devbox" config.vm.network "private_network", ip: "192.168.33.10" # Virtual box config config.vm.provider "virtualbox" do |vb| vb.gui = false vb.memory = "2048" ...
class AddCanceledAtToPickUps < ActiveRecord::Migration def change rename_column(:pick_ups, :started_at, :canceled_at) end end
module Projects module Workers class CheckStatusProject class CheckStatusProjectError < StandardError; end include Sidekiq::Worker sidekiq_options queue: 'projects', retry: true def perform(project_id) project = Project.find(project_id) result = Projects::Interactors::Chec...
class Bookkeeper < Formula desc "Replicated log service for building replicated state machines" homepage "https://bookkeeper.apache.org/" url "https://apache.claz.org/bookkeeper/bookkeeper-4.5.0/bookkeeper-server-4.5.0-bin.tar.gz" sha256 "757abd3083291cb28d6a40342ac6e34b3b802ecc36ba5487a08df92bccc9768e" bott...
require_relative '../spec_helper' feature "User sessions, as a user, I can" do background do @user = create :user end scenario "sign in with correct credentials" do visit root_path click_link 'Login' within("#session") do fill_in 'Email', :with => 'user@example.com' fill_in 'Password...
class MyCar protected attr_writer :color public attr_reader :color attr_reader :year def initialize(year, color, model) @year = year @color = color @model = model @speed = 0 end def self.gas_milage(miles, gallons) puts "#{miles / gallons} miles per gallon of gas" end def spee...
class EmployeesController < ApplicationController before_action :find_one, except: %i[create index] def index @employees = Employee.all render json: @employees, status: :ok end def show render json: @employee, status: :ok end def create @employee = Employee.new(employee_params) if @em...
class UserCheesesController < ApplicationController before_action :authenticate_user!, only: [:new, :edit, :destroy] def index user_cheeses = UserCheese.all.page params[:page] render locals: { user_cheeses: user_cheeses } end def show if UserCheese.exists?(params[:id]) user_cheese = UserChee...
Given /^I have a "([^"]*)"$/ do |specfile| @spec = load_yaml(specfile) end Given /^a "([^"]*)" that I want to check$/ do |template_file| @template_file = template_file end When /^I start the test$/ do end Then /^I want to see the correct "([^"]*)"$/ do |result| if result == "template-error" lambda { che...
Rails.application.routes.draw do devise_for :users root to: 'pages#home' end
class Company < ActiveRecord::Base belongs_to :sector validates_presence_of :name, :latest_price validates_uniqueness_of :name end
require 'spec_helper' describe "BasicAuthenticator" do context "given an instance of BasicAuthenticator" do before do data_store = Stormpath::DataStore.new "", "", {}, "" allow(test_api_client).to receive(:data_store).and_return(data_store) auth_result = Stormpath::Authentication::Authenticati...
Given /^the following images exist:$/ do |table| end Then /^I should find an image with alternate text "(.*)"$/ do |alt_text| page.should have_css("img[alt='#{alt_text}']") end
class Populater::ArticlesOfficers def self.populate matcher = OfficerMatcher.new Article.find_each do |article| matches = matcher.matches(article.body || "") matches.each do |officer| if !article_precedes_officer?(article, officer) ArticlesOfficer.create( officer: off...
require 'byebug' class UsersController < ApplicationController def index ## if query exists in params ## filter it... this is gonna be a method in our models if params[:user_name] user = User.where(user_name: params[:user_name]) render json: user else users...
# RELEASE 2: NESTED STRUCTURE GOLF # Hole 1 # Target element: "FORE" array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]] # attempts: p array[1][1][2][0] # ============================================================ # ============================================================ # Hole 2 # Target elemen...
require 'spec_helper' describe 'Defining schema' do let(:rom) { ROM.setup(sqlite: SEQUEL_TEST_DB_URI) } before do seed(rom.sqlite.connection) end after do deseed(rom.sqlite.connection) end describe '.define' do it 'returns schema with relations' do rom.schema do base_relation(:...
# You have software to take payment from a customer # There are 4 ways to pay, and they are all very similar. # One day, you are paying by cash, and you realize you never calculated the tax! # So you went in to your code and added order.compute_tax to the pay_by_cash method. # Everything was great, until you realized y...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'emailage/version' Gem::Specification.new do |spec| spec.name = "emailage" spec.version = Emailage::VERSION spec.authors = ["Emailage DEV Team"] spec.email = [...
class Plane def initialize(type, id) @type = type @id = id end end
class AddTestToPurchases < ActiveRecord::Migration def change add_column :purchases, :internal_ref, :string add_index :purchases, :internal_ref, unique: true add_column :purchases, :test, :boolean, default: false end end
require 'pry' require 'pry-byebug' def calculate_upvotes(story, category) # Write code so that: # If the Story is about cats multiply the upvotes by 5 # If the Story is about bacon multiply the upvotes by 8 # If the Story is about Food it gets 3 times the upvotes. #For example: # "Cats frolic despite tuna ...
#!/usr/bin/env ruby require "json" require 'bosh_deployment_resource' working_dir = ARGV[0] request = JSON.parse(STDIN.read) source = request.fetch("source") params = request.fetch("params") target_file = params["target_file"] target = if target_file File.read(File.expand_path(target_file, working_dir)).str...
class RenameAssociationToAssoc < ActiveRecord::Migration def change rename_table :associations, :assocs end end
# frozen_string_literal: true require 'client' describe 'ログ取得' do before(:context) do register_logs end after(:context) do @agent_registry.remove_source('aaa') Jiji::Model::Logging::LogData.drop end before(:example) do @client = Jiji::Client.instance end it 'GET /logs/rmt でリアルトレードのログを...
class MatchupsController < ApplicationController def new @matchup = Matchup.new(primary_id: primary_id, secondary_id: secondary_id, series_max: 5) end def create @matchup = Matchup.create(primary_id: primary_id, secondary...
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" public_ip_list = ["", "10.87.65.235", "10.87.65.236", "10.87.65.237", "10.87.65.238"] private_ip_list = ["", "10.10.65.235", "10.10.65.236", "10.10.65.237", "10.10.65.238"] Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| (1..4).each do...
class AddPnAuthKeyToUsers < ActiveRecord::Migration def change add_column :users, :pn_auth_key, :string end end
# frozen_string_literal: true class Collaborator < ApplicationRecord belongs_to :company belongs_to :manager, class_name: "Collaborator", optional: true has_many :managed, class_name: "Collaborator", dependent: :nullify, foreign_key: "manager_id" validates :name, presence: true validates_uniqueness_of :ema...
require File.dirname(__FILE__) + '/test_helper.rb' require 'action_view/test_case' class CoreExtTest < Test::Unit::TestCase include ActionView::Helpers::FormTagHelper include ActionView::Helpers::UrlHelper include ActionView::Helpers::TagHelper include ActionViewExtensions include PrototypeHelperExtensions ...
require 'java' module URLFetch module UFS #Url Fetch Service import com.google.appengine.api.urlfetch.URLFetchServiceFactory import com.google.appengine.api.urlfetch.FetchOptions import com.google.appengine.api.urlfetch.HTTPHeader import com.google.appengine.api.urlfetch.HTTPRequest import com.go...
class AgreementsController < ApplicationController def index @agreements = Agreement.all end def new @agreement = Agreement.new end def create @agreement = Agreement.new(agreement_params) if @agreement.save redirect_to agreements_path, notice: 'Agreements was successfully created!' ...
class EmployeeProfilesController < ApplicationController def show @profile = EmployeeProfile.find(params[:id]) end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe BoardsController, type: :controller do context 'with signed in user' do login_user let(:project) { create(:project, creator: @current_user) } describe '#index' do context 'with project permission' do let(:boards) { create...
require 'minitest_helper' class GraphTest < MiniTest::Unit::TestCase def test_graph_create word_graph = Graph.create(['moo', 'meow'], WordNode) graph = Graph.create(['moo', 'meow']) assert_equal WordNode, word_graph.nodes_hash.first[1].class assert_equal Node, graph.nodes_hash.first[1].class end ...
class Article attr_accessor :title, :url, :content def initialize(title, url, content) @title = title @url = url @content = content end end
require File.expand_path("../lib/page_number", __FILE__) require "date" Gem::Specification.new do |s| s.name = "page_number" s.version = PageNumber::VERSION s.date = Date.today s.summary = "Utility methods for pagination page and per page that make sure you'll always have a valid number."...
require 'rails_helper' RSpec.describe Robot, :type => :model do context "#alive?" do let(:wall_e) { Robot.new } it "should return true if healthy" do puts "hola" puts wall_e.salute puts wall_e.salute2 expect(wall_e.alive?).to be true end end end
desc "Send daily notification email to project users" task :send_daily_notifications => [ :environment ] do Project.active.each do |project| puts "Enqueuing job to send notifications for '#{project.title}'" if Rails.env.production? SendDailyNotificationsJob.perform_later(project.id) else SendD...
class AlphabetController < UIViewController def viewDidLoad super self.title = "Alphabet" @table = UITableView.alloc.initWithFrame(self.view.bounds) @table.autoresizingMask = UIViewAutoresizingFlexibleHeight self.view.addSubview(@table) @table.dataSource = self @table.delegate = self ...
require 'github_api' class LanguagesController < ApplicationController include Constants NOT_FOUND_CODE = 404 def search end def show username = params[:username] @language = if user_exists?(username) FindLanguage.new(username).find else NOT_FOUND end end private def us...
# # Cookbook Name:: postgresql # Recipe:: default # # Copyright 2012 Damien DUPORTAL <damien.duportal@gmail.com> # https://github.com/dduportal/dadou-chef-recipes # # This recipe will configure your system to use the official postgresql repositories # pgsql_major_version = node['postgresql']['version']['major'] pgsql_...
class AddPhoneToTikets < ActiveRecord::Migration def self.up add_column :tikets, :phone, :string end def self.down remove_column :tikets, :phone end end
module HBase module Model class TableDescriptor < Record attr_accessor :name attr_accessor :column_families end end end
require 'rubygems' require 'activerecord' class DmHamlScaffoldGenerator < Rails::Generator::NamedBase attr_reader :controller_name, :controller_class_path, :controller_file_path, :controller_class_nesting, :controller_class_nesting_depth, ...
require 'rails_helper' RSpec.describe 'タスク管理機能', type: :system do let!(:user) { FactoryBot.create(:user) } let!(:task) { FactoryBot.create(:task, title: '該当タスクの内容が表示される', priority: '低', user: user)} let!(:task1) { FactoryBot.create(:task, title: 'task1', task_deadline: '002021-11-01', status: '未着手', priority: '高'...
Tolaria.configure do |config| config.help_links << { title: "Markdown Help", slug: "markdown-help", markdown_file: "#{Rails.root}/app/views/admin/help/markdown-help.md" } config.markdown_renderer = "Rails::Markdown" config.menu_categories = [ "Prose", "Media", "Settings", ] end
class AddColumnsToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :name, :string add_column :users, :address, :text add_column :users, :birthday, :date add_column :users, :phone, :string add_column :users, :student, :boolean, default: false end end
require_relative 'spec_helper.rb' describe RPS::Player do it "exists" do expect(RPS::Player).to be_a(Class) end it "has a name" do player = RPS::Player.new("Jack", 123) expect(player.name).to eq("Jack") end it "has a unique id" do RPS::Player.class_variable_set :@@counter, 0 expect(RPS:...
include Literal def self.from_node node size = node.children.size first = node.children[0] second = node.children[1] if (size == 2) && first.nil? && second.is_a?(::Symbol) literal = new literal.string = second literal end end
module Specmon class Build < ActiveRecord::Base has_many :failures, -> { where(success: false) }, class_name: 'Example' has_many :examples has_many :examples_runtime_gt_1, -> { where('run_time >= 1.0') }, class_name: 'Example' has_many :examples_runtime_gt_0_5_lt_1, -> { where('run_time >= 0.5').where...
require 'spec_helper' describe TicketComment do let(:comment) { FactoryGirl.build :ticket_comment } # factory it { should have_a_valid_factory } # associations it { should belong_to(:ticket) } it { should belong_to(:author) } # validations it { should validate_presence_of(:body) } it { shoul...
###### # Exercise 3, HW1 # Runs a TCP server on port 888, which displays a fortune cookie to clients connecting to the server. # Eugene Wolfson # No preconditions # At the prompt in the containing folder enter: # > ruby exercise2.rb ###### require 'socket' # Get sockets from stdlib require 'exercise2' ...
class CreateResources < ActiveRecord::Migration def change create_table :resources do |t| t.string :slug # articles url path id t.string :title t.string :seo_title t.string :seo_description t.string :seo_keywords t.text ...
require 'digest/md5' class PromotionsController < ApplicationController include DefaultAssetHost before_action :set_promotion, only: [:show, :update, :destroy, :chat, :shop, :toggle_follow] caches_action :index, layout: false, cache_path: Proc.new { |request| etag = if @subject.present? @subject.upd...
pg_dba = input('pg_dba') pg_dba_password = input('pg_dba_password',) pg_db = input('pg_db') pg_host = input('pg_host') pg_audit_log_dir = input('pg_audit_log_dir') control "V-72907" do title "When invalid inputs are received, PostgreSQL must behave in a predictable and documented manner that reflects organizat...
require 'thread' module Skype class Events class << self def on(event) case event when :chatmessage_received Skype::Api.instance.on_notification("CHATMESSAGE (.*) STATUS RECEIVED") do |chatmessage_id| yield Chatmessage.new(chatmessage_id) end when :...
class CreateParticipants < ActiveRecord::Migration def change create_table :participants do |t| t.references :user, index: true, foreign_key: true t.string :contact_phone t.boolean :usyd_student t.string :study t.integer :age t.boolean :resident t.string :residence ...
FactoryBot.define do factory :url do key { "aj9+LCqfeKw=" } source { "https://example.com" } clicked { 2 } end end
# frozen_string_literal: true require 'jiji/test/test_configuration' require 'jiji/test/data_builder' describe Jiji::Model::Trading::Utils::PricingUtils do include_context 'use data_builder' let(:tick) do Jiji::Model::Trading::Tick.new({ EURUSD: data_builder.new_tick_value(1), USDJPY: data_builde...
require 'rails/generators/base' require 'securerandom' module CamaleonCms module Generators class GemPluginGenerator < Rails::Generators::Base source_root File.expand_path('gem_plugin_template', __dir__) argument :plugin_name, type: :string, default: 'my_plugin' desc 'This generator create all b...
# # Cookbook Name:: freebsd # Provider:: port # # Copyright 2016, Alexander Zubkov # # 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 # # Unles...
class Review < ActiveRecord::Base belongs_to :pant belongs_to :user belongs_to :pant_instance has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>", :full => "600x600" } #enum attributes enumerate :hip_fit, :with => HipFit enumerate :waist_fit, :with => WaistFit enumerate ...
class Band <ActiveRecord::Base validates(:name, presence: true) has_and_belongs_to_many(:venues) before_save(:capitalize_name) private define_method(:capitalize_name) do self.name = name.capitalize end end
class Api::V1::HolidaySerializer include FastJsonapi::ObjectSerializer attributes :holiday_date end
require 'dowl_opt_parse' module Dabooks::CLI extend self def run(argv=ARGV) argv = ['help'] if argv.empty? run_subcommand(argv.shift, argv) end def run_subcommand(subcommand_name, argv) subcommand = subcommand_class(subcommand_name) unless subcommand puts("Unknown subcommand: #{subcomma...
set(:release_path) { File.join(releases_path, "current") } set(:releases_path) { File.join(deploy_to) } namespace :deploy do desc "Setup a GitHub-style deployment." task :setup, :except => { :no_release => true } do run "git clone #{repository} #{current_path}" end desc "Update the deployed code." t...
class AddSpamUrl < ActiveRecord::Migration def change add_column :messages, :spam_url, :string end end
class FontArimoNerdFont < Formula version "2.3.3" sha256 "2e1a2ce9a02a5367b2bbaf80c1476942762f063daae6c8c2321bd0870b7cc92c" url "https://github.com/ryanoasis/nerd-fonts/releases/download/v#{version}/Arimo.zip" desc "Arimo Nerd Font (Arimo)" desc "Developer targeted fonts with a high number of glyphs" homepa...
module MasterRecord def self.string lambda{|val| "'#{val}'"} end def self.integer lambda{|val| val.to_s} end module Factory def self.build(prefix,datum,field_info) raise "must use ruby version 1.9.1" unless RUBY_VERSION >= '1.9.1' fields = field_info.keys.map{|k| ":" + k.to_s} m...
ActiveAdmin.register Formation do scope :all scope "Avec Talents", :has_talents, default: true permit_params :title, :type_of_formation, :ranking index do selectable_column column :id column :title column :type_of_formation column :ranking actions end end
# # Test de la sous-class PFtp::Rapport # require 'spec_helper' require_in_other_class 'pftp' describe PFtp::Rapport, :ftp => true do before(:all) do Site::init end describe "La classe" do it "la constante FOLDER_RAPPORT doit être définie et avoir la bonne valeur" do defined?(PFtp::Rapport::FOLDER_RAPP...
class TasksController < ApplicationController respond_to :json def index tasks = Task.includes(:epic).active.rank(:rank) json = tasks.to_json(include: :epic) render json: json end def show respond_with Task.find(params[:id]) end def create respond_with Task.create(params["task"].permi...