text
stringlengths
10
2.61M
# == Schema Information # # Table name: victim_replies # # id :bigint(8) not null, primary key # reply :string # created_at :datetime not null # updated_at :datetime not null # campaign_id :bigint(8) # # Indexes # # index_victim_replies_on_campaign_id (campaign_id) # # For...
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| if Vagrant.has_plugin?("vagrant-cachier") config.cache.scope = :box end config.vm.define :centos do |host| host.vm.box = "bento/centos-6.7" host.vm.hostname = "centos.example" if private_network_ip = ENV["VAGRANT_CENTOS"]...
class Episode < ActiveRecord::Base has_many :comments validates :name, presence: true, length: { maximum: 20 } validates :script, presence: true, length: { maximum: 500 } validates :good_num, presence: true validates :bad_num, presence: true validates :comment_num, presence: true end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Ch...
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true def notify_admins(message) SendTelegramNotificationJob.perform_async(message) end end
class AddPhoneToUserHelp < ActiveRecord::Migration def change add_column :user_helps, :phone, :string, default: '12312414' add_column :user_helps, :open, :boolean, default: false add_column :user_helps, :solve, :boolean, default: false add_column :user_helps, :open_chat, :boolean, default: false end...
require 'spec_helper' describe StoragesController do render_views let(:user) { User.make! } before(:each) do sign_in user @deployment = given_resources_for([:deployment], :user => user)[:deployment] @storage = @deployment.storages.first @storages = @deployment.storages @params = {:deployment...
Gem::Specification.new do |s| s.name = 'tensorflow' s.version = '0.0.1' s.date = '2016-06-21' s.email = 'arafat.da.khan@gmail.com' s.summary = 'A Machine learning gem for Ruby.' s.description = 'TensorFlow is an open source software library for numerical computation using da...
class RemoveSplunkuseridFromInputLog < ActiveRecord::Migration def change remove_column :input_logs, :splunk_user_id, :integer end end
# frozen_string_literal: true # Borrowed from [config gem](https://github.com/rubyconfig/config) # See: https://github.com/rubyconfig/config/blob/master/lib/config/options.rb module ActiveSettings class Config < OpenStruct def each(*args, &block) marshal_dump.each(*args, &block) end def key?(ke...
class RenameSitePhaseToContext < ActiveRecord::Migration[6.1] def change rename_table :site_phases, :contexts end end
# 08_launchconfig_and_asg # called from main.rb # a part of ruby-aws-microservice # # Author: Cody Tubbs (codytubbs@gmail.com) 2017-05-07 # https://github.com/codytubbs # # rubocop:disable LineLength # Comment to rid length warnings from `rubocop' def launch_configuration(asg, sg_tcp_80_priv, sg_tcp_22_priv, i...
require 'delivery/base' require 'oli_pusher' module GenericNotificationsRails module Delivery class Device < Base def deliver(notification,device) options = { badge: notification.person.notification_badge_count } GenericNotificationsRails::OliPusher.send_notification([ device.identifier ],n...
# frozen_string_literal: true require 'test_helper' class AddressTest < ActiveSupport::TestCase setup do @addr = addresses(:one) @addr2 = addresses(:two) end test 'a valid address succeeds' do assert @addr.save end test 'person_id must be present' do @addr.person_id = nil refute @addr....
class Admin::IdeaNotesController < Admin::IdeasBaseController before_filter :require_role_idea_moderator_of_instance helper_method :instance, :idea, :notes, :note, :ideas rescue_from ActiveRecord::RecordInvalid, :with => :render_errors def index render :update do |page| notes and note r...
#!/usr/bin/ruby class BaseClass def just_print a = "Third", b = "Fourth" puts "Parent class, 1st Argument: #{a}, 2nd Argument: #{b}" end end class DerivedClass < BaseClass def just_print a, b puts "Derived class, 1st Argument: #{a}, 2nd Argument: #{b}" #Passes both Argu...
require 'spec_helper' describe Location do before(:each) do @attr = { :description => "Front" } end it "should create a new instance given a valid attribute if the cause string doesn't already exist'" do valid_location = Location.create!(@attr) valid_location.should be_valid end it "s...
require 'json' require 'pp' class User attr_accessor :name, :email, :permissions def initialize(name, email) @name = name @email = email @permissions = User.get_permissions_from_file end def self.get_permissions_from_file file = File.read('UserPermissions.json') JSON.load(file) end d...
require 'rails_helper' RSpec.describe VisitsController, type: :controller do describe '#create' do it 'creates a visit' do skatepark = create(:skatepark) user = create(:user) post :create, skatepark_id: skatepark.id, user_id: user.id expect(Visit.last.skatepark_id).to eq(skatepark.id) ...
require 'json' require 'syslog/logger' require "uri" require "net/http" @log = Syslog::Logger.new 'IRRIGATION_RUNNER' INSTRUCTIONS_DIRECTORY = '/home/pi/irrigation_instructions' SWITCHER_URL = 'http://192.168.0.203/' RAINY_DAY_PRECIPITATION_THRESHOLD = 2.5 WINDY_THRESHOLD ...
# load/dump environment settings from YAML module Remindr class Environment < Struct.new(:server, :client, :alarm) require 'yaml' def self.load(file = '.remindr') file = File.join(ENV['HOME'],file) opts = if file && File.exists?(file) YAML::load(open(file)) else ...
#!/usr/bin/ruby # To be a drop-in replacement for any existing interface, you should implement # the following methods; # - separate: # - basic: Outputs a basic message, that should always be shown. # - info: Ouputs a message with informational content. Generally shown unless # quiet mode is enabled. # - extra...
class InquiriesController < ApplicationController def new @rooms = Room.all @inquiry = Inquiry.new end def create @rooms = Room.all @inquiry = Inquiry.new(inquiry_params) if @inquiry.save NotificationMailer.send_notification(@inquiry.name, @inquiry.email, @inquiry.content).deliver_later...
class Location < ActiveRecord::Base belongs_to :restaurant validates :address, :zip, presence: true validates :city, length: { maximum: 120 } validates :state, length: { maximum: 2 } end
FactoryGirl.define do factory :resume_paragraphy do title { Faker::Lorem.word } text { Faker::Lorem.sentence } sequence(:sequence) profile_resume nil end end
require 'omf/job_service/dumper' module OMF::JobService class Dumper # Simple example of a script to dump an entire experiment database from a # PostreSQL server into dump file suitable for importing into SQLite3 # # This could be used to customise the 'Download/Dump Data' button of the # 'Execut...
# Recipe model class Recipe < ActiveRecord::Base # Associate users and recipes belongs_to :user # Associate recipes and ingredients has_and_belongs_to_many :ingredients validates :name, presence: true validates :description, presence: true validates :instructions, presence: true acts_as_taggable end
class CreateStorages < ActiveRecord::Migration def change create_table :storages do |t| t.references :storagetype t.integer :storage_number t.string :status t.timestamps end add_index :storages, :storagetype_id end end
# -*- coding: utf-8 -*- module Utf8TortureTest # --------------------------------------------------------------------------- # # 1. Some correct UTF-8 text # # module SomeCorrectUTF8Text THE_GREEK_WORD_KOSME = "\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5" INTERNATIONALIZATION_AS...
require 'spec_helper' describe Company do let(:company) { described_class.new } it { should validate_presence_of(:name) } it { should have_many(:phone_numbers) } it "has a phone number" do company.phone_numbers.build number: "333-3333" expect(company.phone_numbers.first.number).to eq('333-3333') e...
class Strategy < ActiveRecord::Base belongs_to :user has_many :indicators, dependent: :destroy has_many :collaborations accepts_nested_attributes_for :indicators, reject_if: :all_blank, allow_destroy: true CLASSIFICATIONS = ["crossover", "momentum", "threshold"] def owner?(user) self.user == user e...
class Restaurant < ApplicationRecord validates :name, :description, :event_time, presence: true validates :description, :length => {:maximum => 150} validates :avatar, presence: { message: "You will need to pick a logo for your restaurant" } belongs_to :user geocoded_by :address after_validation :geoco...
class AddOptionsToOrder < ActiveRecord::Migration def change add_column :orders, :deliver_tickets, :boolean add_column :orders, :checkin_tickets, :boolean add_column :orders, :service_charge_override, :decimal add_column :orders, :agent_checkout, :boolean add_column :orders, :tickets_delivered_at,...
require 'spec_helper' require 'immutable/hash' describe Immutable::Hash do describe '#dig' do let(:h) { H[:a => 9, :b => H[:c => 'a', :d => 4], :e => nil] } it 'returns the value with one argument to dig' do expect(h.dig(:a)).to eq(9) end it 'returns the value in nested hashes' do expect...
FactoryGirl.define do factory :second_factor do trait :email do name 'Email' end trait :mobile do name 'Mobile' end end end
class MoviesController < ApplicationController before_action :authenticate_user!, only: %i(new create edit update) before_action :get_movies, only: %i(index destroy) before_action :set_movie_by_user, only: %i(edit update destroy) before_action :set_movie, only: :show def index; end def show; end def ne...
class AddTeacherRefToActivity < ActiveRecord::Migration[4.2] def change add_reference :activities, :teacher, index: true, foreign_key: true add_column :activities, :year, :integer add_column :activities, :semester, :integer add_column :activities, :activity_type, :string end end
class CreateKitchens < ActiveRecord::Migration[5.1] def change create_table :kitchens do |t| t.integer :user_id, null: false t.integer :city_id, null: false t.string :name, null: false t.string :cuisine, null: false t.integer :size, null: false t.string :feast_time, null: false...
class Indocker::SshResultLogger def initialize(logger) @logger = logger end def log(result, error_message) if result.exit_code == 0 puts result.stdout_data else @logger.error(error_message) puts result.stdout_data result.stderr_data.to_s.split("\n").each do |line| @lo...
# frozen_string_literal: true class Time MORNING = 6...12 DAY = 12...18 EVENING = 18..23 NIGHT = 0...6 SAY_GOOD_MORNING = 'Доброе утро!' SAY_GOOD_DAY = 'Добрый день!' SAY_GOOD_EVENING = 'Добрый вечер!' SAY_GOOD_NIGHT = 'Доброй ночи!' def self.hello return SAY_GOOD_MORNING if MORNING.include? no...
require 'test_helper' class Web::Admin::UsersControllerTest < ActionController::TestCase def setup admin = create :user, :admin sign_in admin @course = create :course @user = create :user @attrs = attributes_for :user end test "should get index" do get :index assert_response :success...
Rails.application.routes.draw do devise_for :users resources :chatrooms, only: %i(index show new create) root "chatrooms#index" end
require "cucumber_booster_config/cucumber_file" module CucumberBoosterConfig class Injection CUCUMBER_FILES = [ "cucumber.yml", "config/cucumber.yml" ] def initialize(path, report_path, options = {}) @path = path @report_path = report_path @dry_run = options.fetch(:dry_ru...
class Viewer attr_accessor :first_name, :last_name @@all = [] def initialize(first_name, last_name) @first_name = first_name @last_name = last_name self.class.all << self end def self.all @@all end def self.find_by_name(name) find_by(name) end def name "#{first_name} #{las...
class Clone::WorksheetProblemCloneController < ApplicationController def new parent = WorksheetProblem.find_by_worksheet_id_and_problem_number(params[:worksheet_id].to_i, params[:problem_number].to_i) @math_problem = parent.math_problem clone = @math_problem.dup @worksheet_problem = WorksheetProblem.n...
require "nokogiri" require "active_support/memoizable" require "google_scholar/version" module GoogleScholar ROOT_URL = 'http://scholar.google.com' end require "google_scholar/page" require "google_scholar/article"
class Song < ActiveRecord::Base validates :title, presence: true validates :release_year, presence: true, if: :is_released? validates :release_year, numericality: {less_than: 2018}, allow_nil: true validate :same_title_by_artist_in_same_year def is_released? self.released == true end def not_relea...
require_relative 'hotel' module ReservationSystem class Block include Reservable attr_reader :rooms, :block_rate, :start_date, :nights, :dates_blocked def initialize(start_date, nights, rooms_list, block_rate) @rooms = rooms_list @start_date = start_date @nights = nights @dates_b...
module Fetchers class InvalidVimeoResponse < RuntimeError; end class Vimeo include HTTParty format :json attr_reader :title, :description, :thumbnail_url # Fetchs json from Vimeo API def self.parse(url) url = "http://vimeo.com/api/v2/video/#{extract_id url}.json" response = get(ur...
require 'rails_helper' RSpec.describe "Items Actions", type: :request do describe "GET /api/v1/items" do before(:each) do @items = [Item.create(name: "adam1", description: "description1", image_url: "test.url.1"), Item.create(name: "adam2", description: "description2", image_url: "test.url.2"), Item.create...
require 'opener/ners/base' require 'nokogiri' require 'slop' require_relative 'ner/version' require_relative 'ner/cli' module Opener ## # Primary NER class that takes care of delegating NER actions to the language # specific kernels. # # @!attribute [r] options # @return [Hash] # class Ner attr_r...
module Pile module Helpers require 'tempfile' # Construct a new header as specified in the example in the documentation # of the +Header+ class. def new_example_header header = Header.new ({'id' => ['identity', '#'], 'address line' => ['address']}), 'ID', 'Name', 'Addr...
# frozen_string_literal: true def name @name ||= Dir["*.gemspec"].first.split(".").first end def version @version ||= File.read("lib/#{name}.rb")[/^\s*VERSION\s*=\s*['"](?'version'\d+\.\d+\.\d+)['"]/, "version"] end task default: :test require "rake/testtask" Rake::TestTask.new(:test)
# frozen_string_literal: true # == Schema Information # # Table name: users # # id :bigint not null, primary key # address :string # allow_password_change :boolean default(FALSE) # confirmation_sent_at :datetime # confirmation_token :string # confirmed...
# == Schema Information # # Table name: users # # id :integer not null, primary key # username :string not null # email :string not null # password_digest :string not null # session_token :string not null # create...
class Album < ActiveRecord::Base has_many :songs def songs_attributes=(songs) songs.each do |key, song| #byebug unless song['title'] == '' @song = self.songs.find_or_create_by(title: song['title']) @song.update(song) end end end end
class ContributionsController < ApplicationController def new @story = Story.find(params[:story_id]) @contribution = @story.contributions.new @contribution.image = "Animals/#{1+rand(15).ceil}.png" end def create @story = Story.find(params[:story_id]) @contribution = @story.contributions.new(c...
class Friendship < ActiveRecord::Base belongs_to :creator, class_name: "User" belongs_to :admirer, class_name: "User" end
# frozen_string_literal: true module UseCase class ViewBoard def initialize(board_gateway:) @board_gateway = board_gateway end EMPTY_BOARD = [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]].freeze def execute(*) { board: board? ? board : ...
require 'rails_helper' RSpec.describe GigsController, type: :controller do let(:user) { create(:user, :kind_organization) } let(:organization) { create(:organization, user: user) } let(:valid_attributes) { { title: "Help the dogs!", description: "Lets help the poor lill dogs!", start_date:...
require 'digest' class ::Digest::MD5 < ::Digest::Base def self.md5(*args) new(*args) end def intialize(str = nil, *rest) @data = str end def block_length 64 end def digest_length 16 end alias :length :size def finish data = Type.coerce_to(@data, String, :to_s) sum = data...
def valid_number?(number_string) number_string.to_i.to_s == number_string end loop do puts "Please enter the numerator:" dividend = gets.chomp !valid_number?(dividend) \ ? (next puts "Only integers are allowed.") : loop do puts "Please enter the denominator:" divisor = gets.chomp if !...
require File.dirname(__FILE__) + '/../test_helper' require 'roles_controller' # Re-raise errors caught by the controller. class RolesController; def rescue_action(e) raise e end; end class RolesControllerTest < Test::Unit::TestCase fixtures :roles def setup @controller = RolesController.new @request =...
# frozen_string_literal: true require 'singleton' require 'redis' module Departments module Intelligence module Services ## # Redis services, like {https://redis.io/clients Redis Client}, for the {Departments::Intelligence} module. class RedisUtils include Singleton def client...
class Meeting < ActiveRecord::Base has_many :user_meetings has_many :attendees, through: :user_meetings, source: :attendee end
class TasksController < ApplicationController get '/tasks/new' do if is_logged_in? erb :'/tasks/new' else redirect to '/login' end end get '/tasks/new/batch' do erb :'/tasks/batch_new' end post '/tasks' do if is_logged_in? ...
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime...
# test file: vim_test.rb # require 'vimbrain/vim/command' require 'vimbrain/vim/user_dialog' class Array def to_vim_list '[' + self.map { |o| "'"+o.to_s+"'" }.join(', ') + ']' end end
class ProductsController < ApplicationController load_and_authorize_resource helper_method :sort_column, :sort_direction require 'csv' def index @products = @products.includes(:category).includes(:selling_units) @products = filter_and_sort(@products, params) @products = @products.paginate(page...
# Creating travel organizer # Program will ask user for date, time(military), airline, flight number, departure city or airport and desination # input will be stored in data base # input will be presented # input will have ability for updating or deletetion # program will loop unless user types exit # any and all input...
require 'optparse' require 'optparse/time' require 'ostruct' require 'pp' require 'fileutils' require 'open3' require 'date' include FileUtils class Optparser # # Return a structure describing the options. # def self.parse(args) # The options specified on the command line will be collected in *options*. ...
require 'flannel/wrappable' require 'flannel/feed_parser' require 'flannel/file_cache' require 'flannel/block_cutter' module Flannel def self.quilt markup, params={} @cache = params[:cache] return nil unless markup cutter = Flannel::BlockCutter.new text_blocks = cutter.cut markup text_block...
class CountryHoliday < ActiveRecord::Base belongs_to :country belongs_to :holiday end
require_relative "../require/macfuse" class S3fsMac < Formula desc "FUSE-based file system backed by Amazon S3" homepage "https://github.com/s3fs-fuse/s3fs-fuse/wiki" url "https://github.com/s3fs-fuse/s3fs-fuse/archive/v1.90.tar.gz" sha256 "75fad9560174e041b273bf510d0d6e8d926508eba2b1ffaec9e2a652b3e8afaa" li...
class Alumno def initialize(nota1, nota2, nota3) @nota1 = nota1 @nota2 = nota2 @nota3 = nota3 end def calcular_promedio promedio = ((@nota1 + @nota2 + @nota3) / 3.0).round(2) return promedio end def determinar_aprobacion if (calcular_promedio >= 13) "Aprobado" else "Desaprob...
class UsersController < ApplicationController before_action :logged_in_user, only: [:edit, :update] before_action :correct_user, only: [:edit, :update] respond_to :html, :json def preferences @user = User.find(session[:user_id]) respond_modal_with @user end def show @user = User.find(params[:id]) ...
class CreateStatistics < ActiveRecord::Migration def change create_table :statistics do |t| t.references :match, null: false t.string :score, limit: 10 t.string :net, limit: 10 t.string :putts, limit: 10 t.string :penalties, limit: 10 t.string :average_driver_length, limit: 10 ...
class Category < ActiveRecord::Base attr_accessible :name, :permalink has_many :posts def to_param "#{id}-#{permalink}" end end
class Antibody < ActiveRecord::Base cattr_reader :per_page @@per_page = 10 belongs_to :target, :counter_cache => true belongs_to :source, :counter_cache => true belongs_to :host_species, :class_name => 'Species' has_many :validations, :order => "category desc" validates_presence_of :target_id, :source_id,...
require 'test_helper' class MovementsControllerTest < ActionDispatch::IntegrationTest def setup @admin = users(:admin) @user = users(:user) @movement = movements(:movement1) @statement = statements(:statement1) @concept = 'Ingreso de ponsan' @description = 'Ingreso de Ponsan de la vivienda ...
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 :sections, dependent: :destroy has_many :it...
class User < ActiveRecord::Base # attr_accessor :password_digest attr_accessor :password validates :email, :session_token, :password_digest, presence: true, uniqueness:true after_initialize :ensure_session_token def self.generate_session_token SecureRandom::urlsafe_base64(16) end def reset_session_t...
class CompletionsController < ApplicationController # GET /completions # GET /completions.json def index @completions = Completion.all respond_to do |format| format.html # index.html.erb format.json { render json: @completions } end end # GET /completions/1 # GET /completions/1.jso...
class UsersController < ApplicationController before_action :set_before, except: [:index, :new, :create] def index end def show @publicbooks = @user.owner_books.where(is_public: true) @draftbooks = @user.owner_books.where(is_public: false) @publiccomments = @user.comments.where(is_public: true) @draf...
When(/^I follow the Check In link$/) do visit checkin_path end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def login_redirect_path login_path(:return_to => request.request_uri) end def datetime_to_strtime date_time date_time.strftime("%H:%M") end end
require "lita/standups/models/standup_session" module Lita module Standups module Models class StandupResponse < Base include Ohm::Callbacks include Ohm::Timestamps include Ohm::DataTypes attribute :status attribute :user_id attribute :answers, Type::Array ...
require "spec_helper" require_relative "../lib/carrierwave_dimensions/processor" class TestUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick process store_dimensions: { width_column: :image_width, height_column: :image_height } end class UploadModel attr_accessor :image_width, :image_hei...
Rails.application.routes.draw do root 'dashboards#index' resources :dashboards, only: [:index] end
require 'sinatra/base' require 'multi_json' require 'jbuilder' module Sinatra module Jbuilder VERSION = "1.0" def jbuilder(object, status:200, type: :json) content_type type response.status = status ::Jbuilder.encode do |json| json.set! :meta do json.status status ...
class AddInfoToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :alamat, :string add_column :users, :telp, :string end end
# == Schema Information # # Table name: comments # # id :integer not null, primary key # message :text # user_id :integer # video_id :integer # name :string(255) # email :string(255) # created_at :datetime # updated_at :datetime # class Comment < ActiveRecord::Base include...
class LikesController < ApplicationController before_action :require_login, :only => [:create, :destroy] before_action :set_like, :only => [:destroy] def create @like = Like.new(whitelisted_like_params) @like.user = current_user if @like.save flash[:success] = "Like was recorded." els...
class Poll < ActiveRecord::Base # TODO: Cannot change poll strategy in the middle of polling VOTING_STRATEGIES = ['SingleVoteStrategy', 'MultipleChoiceStrategy'] has_many :poll_choices, dependent: :destroy has_many :votes, through: :poll_choices has_many :citizens, -> { uniq }, through: :votes has_many :k...
class ServiceResult attr_reader :object def initialize(object) @object = object end def error? @object.is_a?(Error) end end
module RubyBranch module API module Resources class Link LINK_LENGTH_LIMIT = 2000 def create_safely(analytics: {}, data: {}, settings: {}) build(analytics: analytics, data: data, settings: settings) rescue Errors::LinkLengthExceedError create(analytics: analytic...
# frozen_string_literal: true # Framework for inputing date as a hash key and # the balance total as a value class Bank attr_accessor :total, :time def initialize @total = 0 @time = {} end def deposit(sum) @total += sum end def withdrawl(sum) @total -= sum end def input_time @tim...
class KeyGenerator attr_accessor :key def initialize(key = nil) @key = key || rand(100000).to_s.rjust(5, "0") end end
class ApplicationCable::Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_user end protected def find_verified_user session = cookies.encrypted[Rails.application.config.session_options[:key]].with_indifferent_access User.find_b...
class AddsPartialAddressToDeliverCoordinators < ActiveRecord::Migration def change add_column :deliver_coordinators, :partial_address, :string, null: false, default: '' end end