text
stringlengths
10
2.61M
# frozen_string_literal: true module NIO VERSION = "2.2.0".freeze end
require "graphql_server/batch_loaders/base_record_loader" # Batch-load: look up many records using a common key module GraphQLServer::BatchLoaders class RecordListLoader < BaseRecordLoader def perform(keys) records = query(keys) keys.each do |key| matching_records = records.select { |r| r.pu...
class CreateAdmissions < ActiveRecord::Migration def change create_table :admissions do |t| t.belongs_to :collection, index: true t.integer :user_id t.string :secret t.boolean :signed, default: false t.boolean :available, default: true t.hstore :detail t.timestamps null:...
class CompanySerializer include JSONAPI::Serializer attributes :name, :image_url, :job_listings end
# frozen_string_literal: true class Representative < ApplicationRecord has_many :news_items, dependent: :delete_all def self.civic_api_to_representative_params(rep_info) reps = [] rep_info.officials.each_with_index do |official, index| title_temp, ocdid_temp = each_helper(rep_info,...
# == Schema Information # # Table name: tags # # id :integer not null, primary key # name :string # created_at :datetime not null # updated_at :datetime not null # slug :string # class Tag < ActiveRecord::Base extend FriendlyId friendly_id :slug_candidates, use: :s...
class Question < ActiveRecord::Base has_many :answers, dependent: :destroy has_many :attachments, as: :attachable, dependent: :destroy belongs_to :user accepts_nested_attributes_for :attachments, allow_destroy: true validates :title, :body, :user, presence: true end
require "test_helper" require 'base64' describe Rugged do it "can convert hex into raw oid" do raw = Rugged::hex_to_raw("ce08fe4884650f067bd5703b6a59a8b3b3c99a09") b64raw = Base64.encode64(raw).strip assert_equal "zgj+SIRlDwZ71XA7almos7PJmgk=", b64raw end it "converts hex into raw oid correctly" do...
class StorySplaceJoin < ActiveRecord::Base validates :story_id, :splace_category_id, presence: true belongs_to :story belongs_to :splace_category end
require 'bundler/gem_tasks' def mri? RUBY_ENGINE == "ruby" end def jruby? defined?(JRuby) end desc "run tests" task default: [:test] if mri? || jruby? if mri? require 'rake/extensiontask' Rake::ExtensionTask.new('did_you_mean') do |ext| ext.name = "method_receiver" ext.lib_dir = "lib/d...
class Spectator < ApplicationRecord has_many :bookings validates :email, uniqueness: true before_save :check_age_validity before_validation :check_email_validity private def check_age_validity unless self.age.is_a? Integer self.age = 0 end end def check_email_vali...
class Traveller def initialize @browser = Watir::Browser.new end def visit(url) @browser.goto url end def login(usr, pwd, confirmation_page) @browser.text_field(type: 'email').set usr @browser.text_field(type: 'password').set pwd @browser.button(type: 'submit').click @browser.wait_u...
class BookInStock def initialize(isbn, price) @isbn = isbn @price = price end def inspectX "#{@isbn} - #{@price}" end end b1 = BookInStock.new("a", 10) puts "#{b1}" p b1
require "spec_helper" describe Kickstart::Version do before do @version = described_class.new "F21" end context "#at_least?" do it "returns false for higher version numbers" do expect(@version.at_least?("F99")).to be_falsy end it "returns true for lower version numbers" do expect(@...
# frozen_string_literal: true require "test_helper" class TimeSeriesPointTest < ActiveSupport::TestCase %i[sample].each do |time_series_point| test "time_series_points(:#{time_series_point}) is valid" do model = time_series_points(time_series_point) assert model.valid?, "Expected time_series_points(...
class Solution < ApplicationRecord validates :answer, presence: true, uniqueness: true belongs_to :problem end
require 'logger' require 'snmp2mkr/config_types/oid' require 'snmp2mkr/mib' require 'snmp2mkr/oid' require 'snmp2mkr/vhost' require 'snmp2mkr/send_requests/metrics' module Snmp2mkr class Collector def initialize(host, metrics_state_holder:, host_manager:, sender_queue: nil, logger: Logger.new(File::NULL), mib: M...
require 'test_helper' class CassandraObject::AttributeMethodsTest < CassandraObject::TestCase test 'read and write attributes' do issue = Issue.new assert_nil issue.read_attribute(:description) issue.write_attribute(:description, nil) assert_nil issue.read_attribute(:description) issue.write_at...
class CreateProfessors < ActiveRecord::Migration def change create_table :professors do |t| t.string :name, null: false t.string :email, null: false, unique: true t.string :password_digest, null: false t.boolean :is_approved, null: false, default: false t.boolean :is_admin, null: ...
# redMine - project management software # Copyright (C) 2006-2008 Jean-Philippe Lang # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any...
# frozen_string_literal: true require 'rails_helper' describe ExamsController do let(:user) { create :user } before { session[:user_id] = user.id } describe '#index' do subject { get :index } it 'renders the template' do expect(subject).to render_template :index end it 'assigns @exams' d...
module Bsale class Config attr_accessor :access_token, :content_type, :version, :extension, :headers def initialize @extension = ".json".freeze @content_type ||= 'application/json'.freeze @version ||= '1'.freeze end def headers { 'access_token' => @access_token, 'Content-Type...
require 'rails_helper' feature 'User can log_out', %q( The user must be able to log out to end the session ) do given(:user) { create(:user) } background { visit new_user_session_path } scenario 'User log out' do login(user) click_on 'Log out' expect(page).to have_content 'Signed out successfull...
class CreateServers < ActiveRecord::Migration[6.0] def change create_table :servers do |t| t.string :ip_address t.integer :main_1, null: false t.integer :main_2, null: false t.integer :main_3, null: false t.integer :main_4, null: false t.integer :sub, null: false t.timest...
class Department < ActiveRecord::Base has_many :users has_many :lessons end
class AccountsController < ApplicationController def show @account = Account.find(1) end def update @account = Account.find(params[:id]) @account.update_attributes(account_params) redirect_to account_url(@account) end private def account_params params.require(:account).permit(:balance...
class Users::PostsController < ApplicationController before_filter :authorize expose(:post) { current_user.posts.new(params[:post]) } expose(:user_post) { current_user.posts.find(params[:id]) } def create if post.save redirect_to :dashboard else render :new end end def update ...
# requires "phpmd/phpmd" in the composer.json require-dev section # more details http://phpmd.org/ desc "Creating PHP Mess Detector report" task :phpmd do debug = fetch(:enable_mess_detector_debug, false) exclude = "--exclude Resources" capifony_pretty_print "--> Creating PHP Mess Detector report" if d...
Tritracker2::Application.routes.draw do devise_for :users root to: "pages#index" get '/home', to: "pages#home", as: 'home' get "/workouts/new", to: "workouts#new", as: 'new_workout' get "/workouts", to: "workouts#index", as: 'workouts' post "/workouts", to: "workouts#create" end
class Node attr_reader :data attr_accessor :next_node def initialize(data) @data = data @next_node = nil end end
require "../factory/*" class TableLink < Factory def table_link(caption:, url:) super(caption: caption, url: url) end def make_html "<li><a href=\"#{url}\">#{caption}</a></li>\n" end end
class User < ApplicationRecord has_secure_password validates :username, uniqueness: { case_sensitive: false } has_many :tickets, foreign_key: :customer_id, class_name: 'Ticket' has_many :owners, through: :tickets has_many :owned_tickets, foreign_key: :owner_id, class_name: 'Ticket' has_many :c...
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/plans' # Requires targets, plan_name, return_expects to be set. # Requires expect_action to be defined. shared_examples 'action tests' do it 'runs' do expect_action result = run_plan(plan_name, 'nodes' => targets) expect(result).to b...
# frozen_string_literal: true require_relative 'key_generator' # Handles mining transactions class Transaction attr_reader :address_of_sender, :address_of_receiver, :amount, :signature def initialize(address_of_sender, address_of_receiver, amount) @address_of_sender = address_of_sender @address_of_receiv...
RSpec.describe CarmenBuilds::Builders::Builder do context 'work in tmp dir' do describe '#tmdir' do let(:builder) {CarmenBuilds::Builders::Builder} let(:tmpdir) {builder.tmpdir} let(:config) {create(:config)} it "create tmp dir" do expect(File).to exist(File.join(tmpdir)) en...
class DroppedVerse include Mongoid::Document include Mongoid::Timestamps include ActionView::Helpers::DateHelper extend ActionView::Helpers::TextHelper belongs_to :user belongs_to :verse delegate :title, :text, :to => :verse field :location, type: Array index location: "2d" validates :location, ...
require 'json' module SkeletorApi module FaradayMiddleware class ApiKey < Faraday::Middleware def initialize(app,options) @key = options.fetch(:key) super(app) end def call(env) env[:request_headers]["Authorization"] = "SkeletorSecret key=#{@key}" @app.call(env)...
class GroupesController < ApplicationController before_action :set_groupe, only: [:show, :edit, :update, :destroy] before_action :Gmin, only: [:Rand] # GET /groupes # GET /groupes.json def index @groupes = Groupe.all @personnes = Personne.all end # GET /groupes/1 # GET /groupes/1.json def sh...
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # created_at :datetime not null # updated_at :datetime not null # password_digest :string(255) # class User < ActiveRec...
require 'digest/md5' module Ipizza::Provider class Nordea::AuthenticationRequest < Ipizza::AuthenticationRequest attr_accessor :params attr_accessor :service_url def sign(key_path) key = File.read(key_path).strip params['MAC'] = Digest::MD5.hexdigest(mac_data_string(key)).upcase end...
class RemovePositionIdFromCandidates < ActiveRecord::Migration def change remove_column :candidates, :position_id, :integer add_reference :candidates, :position, index: true end end
module Anonymized class Anonymizer DEFAULT_BATCH_SIZE = 10_000 class << self attr_accessor :custom_anonymization_functions, :function_schema, :batch_size def configure(&_block) yield(self) if block_given? end def before_hook(&block) @before_hook = block end ...
require 'rails_helper' feature 'User edits Participant', js: true do scenario 'and sees the updated Participant' do given_i_am_viewing_the_participant_list when_i_update_a_participants_details then_i_should_see_the_updated_details end def given_i_am_viewing_the_participant_list protocol = creat...
class BookingsController < ApplicationController before_action :set_params, only: [:show] def index @bookings = Booking.where(moment_id: params[:moment_id].to_i) end def show @booking = Booking.find(params[:id]) end def new @moment = Moment.find(params[:moment_id]) @booking = Booking.new ...
class Catagory < ApplicationRecord has_many :plans has_many :photos default_scope -> {order('id asc')} has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end
class Calculadora def sumar(a,b) if a.class==Integer and b.class==Integer return a+b else return "solo operaciones con numeros" end end def resta(a,b) c= a-b return c end def multiplicar(a,b) c=a*b return c e...
module TestdroidAPI class Config < CloudResource def initialize(uri, client, params={}) super uri, client, "config", params @uri, @client = uri, client sub_items :parameters end end end
class ApplicationController < ActionController::Base # track actions automatically before_action :configure_permitted_parameters, if: :devise_controller? protect_from_forgery with: :exception protected def configure_permitted_parameters attrs = [:username, :email, :password, :password_confirmation, :remember...
require 'yaml' require_relative '../classes/reader.rb' module OopLibrary def self.generateReadersData readers = [ Reader.new("Ivan Ivanov", "ivan@ivanov.com", "Dnipro", "Mechnikova", "2"), Reader.new("Peter Petrov", "peter@petrov.com", "Dnipro", "Artema", "6"), Reader.new("John Smith", "john@smith.com", "D...
# spec/requests/scenarios/show_spec.rb require 'rails_helper' RSpec.describe 'show scenario (GET scenario)', type: :request do let(:user) { create(:user) } let(:admin) { create(:user, :admin) } let!(:scenario) { create(:scenario, user: admin) } let(:scenario_id) { scenario.id } let!(:questions) { create_list...
require 'spec_helper' describe "WorkoutPages" do subject { page } let(:user) { FactoryGirl.create(:user) } before { sign_in user } describe "workout creation" do before { visit root_path } describe "with invalid information" do it "should not create a workout" do expect { click_button "...
require "test_helper" class HelpLinkTest < ActionDispatch::IntegrationTest test "demo help link is rendering, Markdown works" do sign_in_dummy_administrator! visit("/admin/blog_posts") assert page.has_content?("Markdown Help") visit("/admin/help/markdown-help") assert page.has_content?("paragrap...
module TinymceFilemanager class Attach include Mongoid::Document include Mongoid::Timestamps::Short mount_uploader :file, TinymceFilemanager::FileUploader field :file, type: String field :ext, type: String field :size, type: String field :filename, type: String before_save :secondary...
require "test_helper" class CongfigurationTest < ActiveSupport::TestCase test "can't assign unknown config" do assert_raises NoMethodError do Tolaria.configure do |config| config.bullshit = "ಠ_ಠ" end end end test "can't pass a block to Tolaria.config" do assert_raises ArgumentEr...
class SharepointTradeArticle include Indexable self.settings = { index: { analysis: { analyzer: { custom_analyzer: { tokenizer: 'standard', filter: %w(standard asciifolding lowercase snowball), }, phrase_match_analyzer: { ...
class PostsController < ApplicationController before_action :ensure_signed_in def index @user = User.find(params[:user_id]) @posts = Post.where(user_id: @user.id) posts = @posts.order("created_at desc") render json: posts end def all render json: { posts: Post.order("created_at...
# Method name: print_horizontal_pyramid # Input: a number n # Returns: Nothing # Prints: a pyramid consisting of "*" characters that is "n" characters tall # at its tallest # # For example, print_horizontal_pyramid(4) should print # # * # *** # ***** # ******* def print_horizontal_pyramid(height) (1..h...
require 'test_helper' require_relative 'base_integration_test' class RegisterTest < IntegrationTest test 'create a user' do visit '/' find('.navbar').click_on('Register') assert page.has_content?('Register for iSENSE') fill_in 'user_name', with: 'Mark S.' fill_in 'user_email', with: 'm...
Rails.application.routes.draw do scope :api do devise_for :users, only: %i[sessions registrations], controllers: { sessions: 'api/users/sessions', registrations: 'api/users/registrations' } post 'work_logs/clock_in', to: 'api/work_logs#clock_in' post 'work_logs/clock_out', to: 'api/work_l...
require 'json' class GitSshIdentitySwitch def initialize(config_path:, init_config: false) if init_config create_config_file else load_config(config_path) end end def create_config_file @config = { 'users' => [ ] } output = File.open(config_path, 'w') output.c...
class CreatePackages < ActiveRecord::Migration def self.up create_table :packages do |t| t.string :name t.text :description t.string :kind t.datetime :expires_on t.string :logo_file_name t.string :logo_content_type t.integer :logo_file_size t.datetime :logo_updated_...
class AddSnapshotToMailingSchedule < ActiveRecord::Migration def change add_attachment :mailing_schedules, :snapshot end end
require File.dirname(__FILE__) + '/../../spec_helper' describe 'S3.put_bucket' do before(:all) do @s3 = Fog::AWS::S3.gen end after(:all) do @s3.delete_bucket('fogputbucket') end it 'should return proper attributes' do actual = @s3.put_bucket('fogputbucket') actual.status.should == 200 en...
Rails.application.routes.draw do root :to => 'posts#index' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' resources :posts, except: [:create] resources :images, only: [:new, :create] end
class Professor < ActiveRecord::Base attr_accessible :institution, :name has_and_belongs_to_many :publications end
Rails.application.routes.draw do concern :commentable do resources :comments end resources :posts, concerns: :commentable root to: 'posts#index' devise_for :users resources :users end
class ChangeCourseNumberingsToStrings < ActiveRecord::Migration def change remove_column :courses, :new_number remove_column :courses, :old_number add_column :courses, :new_number, :string add_column :courses, :old_number, :string end end
require 'rails_helper' describe 'User logins in to the app' do scenario 'Can see a list of repos' do VCR.use_cassette('user_can_see_repos') do user = create(:user) allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) visit '/' expect(current_path).to e...
# == Schema Information # # Table name: items # # id :integer not null, primary key # size :string(255) # color :string(255) # status :string(255) # price_sold :decimal(, ) # sold_at :datetime # style_id :integer # crea...
# Pizza (Product) Classes # Super Class class Pizza attr_reader :name, :dough, :sauce def toppings @toppings = @toppings || [] end def prepare puts "Preparing `#{ name }`" puts "Tossing dough..." puts "Adding sauce... `#{ sauce }`" puts "Adding toppings:" toppings.each do |topping| ...
require 'active_support' require 'active_support/core_ext' require 'rest-client' require 'json' require 'slack/client' module Slack class << self attr_accessor :token delegate :channels, :messages, :users, :options=, to: :client def configure(&block) yield configuration end private d...
# frozen_string_literal: true module Decidim module Opinions # A cell to display when a opinion has been published. class OpinionActivityCell < ActivityCell def title I18n.t( "decidim.opinions.last_activity.new_opinion_at_html", link: participatory_space_link ) ...
require 'chef_helper' describe 'metrics', type: :rake do let(:gitlab_registry_image_address) { 'dev.gitlab.org:5005/gitlab/omnibus-gitlab/gitlab-ce-qa' } let(:gitlab_version) { '10.2.0' } let(:image_tag) { 'omnibus-12345' } let(:version_manifest) { { "software": { "gitlab-rails": { "locked_version": "123445" }...
=begin Glassomium - web-based TUIO-enabled window manager http://www.glassomium.org Copyright 2012 The Glassomium Authors 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 h...
class ChangeOrdToIntegerInTracks < ActiveRecord::Migration[5.2] def change change_column :tracks, :ord, 'integer USING CAST(ord AS integer)' end end
class PrintDetailsController < ApplicationController before_action :authorize_user, only: [:new, :edit, :create, :update, :destroy] before_action :set_print_detail, only: [:show, :edit, :update, :destroy] # GET /print_details # GET /print_details.json def index @print_details = PrintDetail.all end #...
module WebPageParser require 'nokogiri' require 'open-uri' class PageParser attr_reader :doc attr_accessor :title, :charset, :compatible, :viewport, :description, :language, :keywords, ...
# case式と正規表現オブジェクト p (/Ruby/ === "I love Ruby").class p case "I love Ruby" when /Ruby/ then; "Ruby!" when /Java/ then; "Java!" end
module Onebox module Engine class GitlabBlobOnebox < GithubBlobOnebox include Engine include LayoutSupport matches_regexp(/^https?:\/\/(www\.)?gitlab\.com.*\/blob\//) def layout @layout ||= Layout.new('githubblob', record, @cache) end def initialize(link, cache = nil...
class ArquitecturasController < ApplicationController # GET /arquitecturas # GET /arquitecturas.json def index @arquitecturas = Arquitectura.all respond_to do |format| format.html # index.html.erb format.json { render json: @arquitecturas } end end # GET /arquitecturas/1 # GET /arq...
class ProjectsController < ApplicationController before_action :authenticate_user! after_action :verify_authorized, :except => :index after_action :verify_policy_scoped, :only => :index def index @projects = policy_scope(Project) end def show @project = Project.find_by id: params[:id] @contri...
require Rails.root.join('lib/auth_token') class Api::Users::SessionsController < ApplicationController skip_before_action :verify_authenticity_token, only: [:create] respond_to :json def create email = auth_params[:email] password = auth_params[:password] @user = password_auth email, password if e...
require 'rails/generators/active_record' module Adminpanel class GalleryGenerator < ActiveRecord::Generators::Base source_root File.expand_path("../templates", __FILE__) desc "Generate the resource files necessary to use a model" def generate_model template 'gallery_template.rb', "app/models/adminp...
require 'scraperwiki' require 'mechanize' case ENV['MORPH_PERIOD'] when 'thismonth' period = 'thismonth' when 'lastmonth' period = 'lastmonth' else period = 'thisweek' end puts "Getting '" + period + "' data, changable via MORPH_PERIOD environment"; starting_url = 'http://pdonline.goldcoast.qld.gov.au/mastervie...
require_relative "piece" require_relative "stepable" class Knight < Piece include Stepable def symbol if color == :b "♞" else "♘" end end protected def move_diffs [[-2, -1], [-2, 1], [2, -1], [2, 1], [-1, 2], [1, 2], [-1, -2], [1, -2]] end end if __FILE__ == $PROGRAM_NAME b...
require 'pry' class Song attr_accessor :name, :artist, :genre @@count = 0 @@artists = [] @@genres = [] @@all = [] def initialize (name, artist, genre) @name = name @artist = artist @genre = genre @@artists << self.artist @@genres << self.genre @@coun...
require_relative 'game' describe Game do let(:game) {Game.new('elephant')} it "sums the amount of total guesses" do expect(game.total_guesses).to eq 8 end it "returns the index of the letter" do expect(game.find_index('e')).to eq [0, 2] end it "returns a string with guessed letters filled in" do expe...
# write a program that will ask a user for an input # of a word or multiple words # and give back the number of characters # spaces should not be counted as a character # Examples: # # input # Please write word or multiple words: walk # # output # There are 4 characters in "walk". # # input # Please write word or ...
class AddDefaultCountryToLair < ActiveRecord::Migration def change change_column(:lairs, :country, :string, { default: "USA" }) end end
class Oauth::ApplicationsController < Doorkeeper::ApplicationsController before_filter :authenticate_user! before_action :check_owner, only: [:show,:update, :destroy,:edit] def index @applications = current_user.oauth_applications end def create @application = Doorkeeper::Application.new(application...
module IssueRepresenter include Roar::JSON property :id property :comment property :status property :priority property :created_at property :component, :extend => ComponentRepresenter, :class => Component property :issue_type, :extend => IssueTypeRepresenter, :class => IssueType collection :required_...
namespace :arduino do desc "Listen to Arduino port and write to DB" task listen: :environment do port_str = "/dev/cu.usbmodem1411" #may be different for you baud_rate = 9600 data_bits = 8 stop_bits = 1 parity = SerialPort::NONE sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits,...
class CreateGames < ActiveRecord::Migration[5.2] def change create_table :games do |t| t.string :player t.boolean :over, default: false t.boolean :won, default: false t.timestamps end end end
require 'rails_helper' RSpec.describe Evaluation, type: :model do describe "validations" do it { is_expected.to validate_presence_of(:rating) } it { is_expected.to validate_presence_of(:remark) } it { is_expected.to validate_presence_of(:date) } end describe "association with students" do it { ...
class User < ApplicationRecord has_many :purchase_logs has_many :products, through: :purchase_logs end
class GamesController < ActionController::API before_action :set_game, only: [:show, :check, :flag] def show render json: @game.as_json end def check @game = Game.find(params[:id]) @game.check(params[:row].to_i, params[:col].to_i) @game.save render json: @game.as_json end def flag ...
json.set! post.id do json.extract! post, :id, :title, :description, :created_at json.created_at post.created_at.strftime("%F %T") json.photoUrl url_for(post.photo) end
require 'spec_helper' describe 'Series System' do describe 'Creating Agencies' do let!(:agency) { create(:json_agent_corporate_entity, :dates_of_existence => [{ :label => 'existence', :date_type => 'range', ...
module Hydra::Works class GetRelatedObjectsFromGenericFile ## # Get related objects from a generic_file. # # @param [Hydra::Works::GenericFile::Base] :parent_generic_file to which the child objects are related # # @return [Array<Hydra::Works::GenericFile::Base>] all related objects def s...
class V1::Dashboards::Manager::SurveysController < V1::BaseController include V1::MessageHelper before_filter :setup def index surveys = Survey::Info.last(20) aas = ActiveModel::ArraySerializer mts = ::Manager::Survey::InfoSerializer render json: aas.new(surveys, each_serializer: mts) end de...