text
stringlengths
10
2.61M
# typed: true require "rbnacl" require "base64" require "openssl" require_relative "utils/constants" require_relative "encoding" def generate_account() # Generate an account. # Returns [(str, str)]: the private key and account address. signing_key = RbNaCl::Signatures::Ed25519::SigningKey.generate verify_key ...
require 'rails_helper' RSpec.describe Donut::SeedDataService do let(:seed) { YAML.safe_load(File.read("#{file_fixture_path}/test_seed.yml"), [Symbol]) } describe '#load' do before do AdminSet.destroy_all User.destroy_all described_class.load(seed) end it 'populates the admin sets fr...
Then(/^"(.*?)" should contain "(.*?)"$/) do |dropdown, text| expect(page.has_select?(dropdown, :with_options => [text])).to be true end Then(/^"(.*?)" should not contain "(.*?)"$/) do |dropdown, text| expect(page.has_no_select?(dropdown, :with_options => [text])).to be true end
module People class Reminder prepend SimpleCommand WorkRequest = Struct.new(:id, :status) def initialize(current_user, args = {}) @current_user = current_user @args = args end def call f_ids = @args[:facility_id].split(',').map { |x| x.to_bson_id } tor = time_off_request...
Rails.application.routes.draw do resources :profiles, only: %i[new create edit update destroy] devise_for :users, controllers: { sessions: 'users/sessions' } resources :blog_apps get '/recent', to: 'blog_apps#recent' get '/my_blogs', to: 'blog_apps#my_blogs' get '/blog_apps', to: 'blog_apps#index' get '/...
class LevelPlay < ActiveRecord::Base belongs_to :user belongs_to :level has_many :question_plays # has_many :questions, through: :question_plays # validates_associated :user, :level # validates :score, numericality: { only_integer: true } # validates :user_id, :level_id, :score, presence: true def q...
# coding: utf-8 require 'spec_helper' feature 'User management' do # 新しいユーザーを追加する # scenario 'adds a new user' do scenario 'adds a new user', js: true do admin = create(:admin) sign_in admin expect { create_user(admin) }.to change(User, :count).by(1) # save_and_open_page expect(current_p...
class Bus def initialize(route_number, destination) @route_number = route_number @destination = destination end def bus_can_drive return "Brum brum!" end end
#https://www.haitihub.com/download/Money-Matters-in-Haiti.pdf =begin The exchange rate of U.S. Dollars to Gourdes fluctuates with currency markets, but for many years it has been somewhere around: 1 USD = 40 HTG The Haitian Dollar is a concept ONLY. It doesn’t exist as paper or coin. 5 Gourdes = 1 Haitian Dollar. This ...
module Comportamiento_de_clase_case_class def inherited(subclass) Object.send(:remove_const, subclass.name) raise ('No se puede heredar de una case_class') end def attr_accessor(*symbols) attr_reader(*symbols) symbols.each do |symbol| self.instance_variable_set("@#{symbol}",'inicializada')...
class PatientController < ApplicationController # before_action :authenticate_user def confirm_variant() begin message = get_post_data uuid = message[:variant_uuid] raise "Variant uuid cannot be null or empty." if uuid.nil? || uuid.length == 0 variant = NciMatchPatientModels::Variant....
class Api::V1::BusinessUnitsController < ApplicationController before_action :authenticate_user! before_action :set_business, only: [:show, :edit, :update] def index #search if params[:search]!=nil and params[:search]!="" @search ="id = #{params[:search]}" else @search ="" ...
class AddIsauthorToTeam < ActiveRecord::Migration def change add_column :teams, :isauthor, :boolean end end
class AddDeleteAtToTodos < ActiveRecord::Migration def change add_column :todos, :delete_at, :datetime end end
module Fog module Compute class DigitalOceanV2 class Real def disable_backups(id) body = { :type => "disable_backups" } encoded_body = Fog::JSON.encode(body) request( :expects => [201], :headers => { 'Content-Type' => "application...
require 'spec_helper' describe AriaApi do before(:each) do AriaApi::Configuration.auth_key = "auth_key" AriaApi::Configuration.client_no = "client_no" AriaApi::Configuration.url = "url" end describe "self.make_request(params)" do it "makes a post to the configuration URL with the credentails and...
module Spree class PaymentMethodTransactionsConversionRateReport < Spree::Report DEFAULT_SORTABLE_ATTRIBUTE = :payment_method_name HEADERS = { payment_method_name: :string, payment_state: :string, months_name: :string, count: :integer } SEARCH_ATTRIBUTES = { start_date: :payments_created_from, end_date: :...
require 'uri' class Params def initialize(req, route_params = {}) @params = route_params if req.query_string @params.merge!(parse_www_encoded_form(req.query_string)) end if req.body @params.merge!(parse_www_encoded_form(req.body)) end end def [](key) @params[key.to_s] end...
require 'query_reviewer' module QueryReviewer def self.inject_reviewer # Load adapters ActiveRecord::Base adapter_class = ActiveRecord::ConnectionAdapters::MysqlAdapter if defined? ActiveRecord::ConnectionAdapters::MysqlAdapter adapter_class = ActiveRecord::ConnectionAdapters::Mysql2Adapter if defin...
# frozen_string_literal: true module Might # Paginates ActiveRecord scopes # @example # # Paginator.new(limit: 10, offset: 100).paginate(Movie.all) # # As a side effect of pagination it defines the following methods on collection: # collection#limit # collection#offset # collection#count # ...
class NewsPostsController < ApplicationController before_action :deny_access_for_non_admins, except: [:index, :show] #================================= # GET #================================= def index # @news_posts = NewsPost.all @news_posts = NewsPost.find(:all, :order => "created_at DESC") e...
# coding: utf-8 require_relative '../lib/multi_exiftool' require 'test/unit' require 'contest' require 'open3' require 'stringio' require 'yaml' module TestHelper @@fixtures = YAML.load_file('test/fixtures.yml') def use_fixture(name, &block) @fixture = @@fixtures[name] if @fixture.nil? assert false...
#Functions uses ptc_whois table and scrum_manager_condition #which contains ldap structure #Function to run actually queries which count #backlog, opened yesterday, resolved yesterday #for the user whose name is passed on # #Construct a single query which will insert #historical data into a table with user's...
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.has_role? :admin can :read, :admin end can :read, Report do |report| accessible_report_ids(user).include? report.id end # Meta Program Report Authorizations # ...
class Link < ActiveRecord::Base attr_accessible :description, :title, :url,:category_ids has_and_belongs_to_many :categories validates_presence_of :title end
require 'compass/import-once/activate' # Require any additional compass plugins here. # Output CSS files as *.min.css require 'fileutils' on_stylesheet_saved do |file| if File.exists?(file) filename = File.basename(file, File.extname(file)) File.rename(file, css_dir + "/" + filename + ".min" + File.extname(file))...
require 'rails_helper' RSpec.describe Challenge do context "60 seconds challenge" do before(:each) do @challenge = FactoryGirl.create(:challenge, lasting_time_type:"s") end it "is_second_challenge?" do expect(@challenge.is_second_challenge?).to be(true) expect(@challenge.is_minut...
class AddReadTimesToMessages < ActiveRecord::Migration[5.0] def change add_column :messages, :read_times, :integer end end
# frozen_string_literal: true require 'sinatra' require 'erb' require_relative 'memo_list' helpers do def html_escape(str) ERB::Util.html_escape(str) end end memo_list = MemoList.new get "/\(memos\)?" do @page_title = 'Memoアプリ' @memos = memo_list.data erb :index end get '/memos/new' do @page_title...
# frozen_string_literal: true class Company < ApplicationRecord validates :legal_name, presence: true validates :mail, presence: true validates :legal_number, presence: true end
class CreateRubrics < ActiveRecord::Migration def change create_table :rubrics do |t| t.string :question, null: false, unique: true t.string :qType, null: false end end end
class Project include Mongoid::Document include Mongoid::Timestamps field :name field :pivotal_tracker_project_id, :type => Integer field :owner_emails, :type => Array, :default => [] references_many :tasks references_many :time_log_entries references_many :users, stored_as: :array, inverse_of: :proje...
class Profile < ActiveRecord::Base belongs_to :industry mount_uploader :avatar, AvatarUploader default_scope { order('updated_at DESC') } validates_uniqueness_of :name searchkick end
module MongoidMapReduceHelper module Builder class GroupBy < Base before_call :before_call_context, :except => :columns def available_functions MongoidMapReduceHelper::Expression::AGGREGATION_FUNCTIONS end def before_call_context(name) if function_context.is_available?(n...
class GameItemImageUploader < BaseImageUploader include Piet::CarrierWaveExtension VERSIONS = { thumb: { size: [320, 320] }, mini_thumb: { size: [60, 60] } } DEFAULT_JPG_QUALITY = 85 DEFAULT_PNG_QUALITY = 5 if CDI::Config.enabled?(:compress_images_on_upload) process :opti...
#!/usr/bin/env ruby require_relative '../config/environment' puts 'Welcome to Tic-Tac-Slow w/ AI forthcoming' def choose_mode valid_modes = [0, 1, 2, 3] game_mode = nil mode_selected = false while mode_selected == false puts "What type of game would you like to play??\n 0 player - AI vs AI\n 1 playe...
require 'rails_helper' RSpec.describe Order, type: :model do describe "class methods" do let!(:order) { FactoryGirl.build(:solo_order) } describe "to_spreadsheet" do it "should works" do order.save(validate: false) expect(Order.count).to eq(1) expect(Order.limit(1).to_spre...
# Source: https://launchschool.com/exercises/facfe405 # Write a method that displays an 8-pointed star in an nxn grid, where n is an odd integer that is supplied as an argument to the method. The smallest such star you need to handle is a 7x7 grid. def star(n) max = "*" + " " * ((n-3)/2) + "*" + + " " * ((n-3)/2) + ...
require 'open-uri' require 'openssl' # Firefox helper module Firefox def firefox_version if platform_family?('windows', 'mac_os_x') return node['firefox']['version'] unless node['firefox']['version'] == 'latest' firefox_latest.match(/(-|%20)([\d|.]*).(exe|dmg|tar.bz2)/)[2] # http://rubular.com/r/thFO...
Rails.application.routes.draw do root 'application#index' devise_for :users resources :messages, only: %i(index edit new update destroy create) namespace :me do resource :profile, only: %i(show edit update) end end
class Friend name = "Bob" def greet(name) puts "Hello #{name}!" end puts "Hello #{name}!" end
class CreateBookings < ActiveRecord::Migration[5.0] def change create_table :bookings do |t| t.string :disciplina t.string :dias t.date :inicio t.date :fim t.integer :lab t.integer :horario t.references :user, foreign_key: true t.timestamps end end end
class Author < ActiveRecord::Base has_many :photos belongs_to :user has_many :movies, :finder_sql => 'SELECT movies.* ' + 'FROM movies ' + 'WHERE movies.author_id = #{id} OR movies.author_2_id = #{id} ' + 'OR movies.author_3_id = #{id} OR movies.author_4_id = #{id} OR movies.author_5_id =...
# this updates|downloads any new gems # # important: need to use same version of ruby [like 1.8] on both sides currently # also note: currently if you want github gems, you'll need to have github listed in your ~/.gemrc # and also you need to have ~/.gemrc setup to use hanna "just right" # # :sources: # - http://gems.r...
class Arrival < ApplicationRecord belongs_to :item validates :arrival_quantity, presence: true validates :arrival_date, presence: true validates :item_id, presence: true end
# frozen_string_literal: true module Decidim module Opinions module Admin # This class contains helpers needed to show the Opinions picker. # module OpinionsPickerHelper def opinions_picker(form, field, url) picker_options = { id: sanitize_to_id(field), ...
FactoryBot.define do factory :user do name { 'Andrey' } email { 'email@example.com' } chat_id { 456 } end end
#!/usr/bin/ruby require File.dirname(__FILE__) + "/gruff_test_case" class TestGruffStackedBar < GruffTestCase def setup @datasets = [ [:Jimmy, [25, 36, 86, 39]], [:Charles, [80, 54, 67, 54]], [:Julie, [22, 29, 35, 38]], ] @sample_labels = { 0 => '5/6', 1 => '5/15', ...
require "supernova-core" require "supernova/solr/server" require "typhoeus" require "json" class Supernova::Solr::Core < Supernova::Solr::Server DEFAULT_SOLR_PATH = "/opt/solr" def create(instance_dir = nil, data_dir = nil) instance_dir ||= DEFAULT_SOLR_PATH data_dir ||= "#{DEFAULT_SOLR_PATH}/data/#{core_...
# typed: true module AlgoSDK module Errors class AlgodRequestError < StandardError def initialize(requrl) @requrl = requrl @message = "Error while building and executing request: #{@requrl}" super(@message) end end class ArgsError < StandardError def initialize(m...
require 'rails_helper' RSpec.describe Piece, type: :model do before(:all) do @white_player = create(:user) @black_player = create(:user) end before(:each) do @game = create(:game) @game.white_player_id = @white_player.id @game.black_player_id = @black_player.id @game.save end it "sho...
require "rails_helper" feature "Tasks" do feature "#index" do scenario "show tasks of a project" do test_project = Project.create!(name: "Test Project") Task.create!(description: "Test Task", project_id: test_project.id) visit root_path click_on "projects-footer-action" click_on "p...
class Store < ApplicationRecord has_many :categories has_many :products, through: :categories end
# == Schema Information # # Table name: images # # id :integer not null, primary key # title :string # description :string # public_id :string # created_at :datetime # updated_at :datetime # class Image < ActiveRecord::Base attr_accessor :path validates :title, presence: {messag...
class FormulationIngredient < ApplicationRecord has_one :formulation has_one :ingredient end
class Job < ApplicationRecord validates :title, presence: true validates :wage_upper_bound, presence: true validates :wage_lower_bound, presence: true validates :wage_lower_bound, numericality: { greater_than: 0} end
require 'chemistry/element' Chemistry::Element.define "Indium" do symbol "In" atomic_number 49 atomic_weight 114.818 melting_point '429.91K' end
#Memcached Resource File actions :install, :configure, :delete, :uninstall default_action :install if defined?(default_action) #Name Space attribute :memcached_name, :name_attribute => true, :kind_of => String, :required => false, :default => 'default' #Main memcached settings attribute :daemonize, :kind_of => [ Tr...
require_relative 'Employee' class Manager < Employee attr_accessor :employees def initialize(name, title, salary, boss = nil, employees = []) @employees = employees super(name, title, salary, boss) end def bonus(multiplier) total = 0 @employees.each do |employee| if employee.is_a?(Manager) total +=...
class County < ApplicationRecord belongs_to :state validates :fips, uniqueness: true end
module Checkr class MotorVehicleReport < Checkr::Report def self.construct(params) accidents = params["accidents"] violations = params["violations"] report = self.new(params.except_key('accidents').except_key('violations')) report.accidents = [] unless accidents.nil? || accidents.em...
require_relative 'test_helper' require_relative '../lib/merchant_repository' require_relative '../lib/sales_engine' require_relative '../lib/csv_handler' class MerchantRepositoryTest < Minitest::Test attr_reader :merchant_repository, :engine def setup @engine = SalesEngine.new @merchant_repository = engine.merc...
class Admin::GuestsController < ApplicationController layout "admin" before_filter :set_event before_filter :set_guest, only: [:show, :update, :edit, :destroy] def index render json: @guests end def new @guest = Guest.new end def create @guest = Guest.new(guest_params) @guest.event = ...
class Box def initialize(w, h) @width, @height = w, h end # define to_s method def to_s "(w:#{@width}, h:#{@height})" # string formating to the object. end end # create object Box class box = Box.new(5, 10) # to_s method call puts "String representation of Box object is: #{box}"
class Reblog < ActiveRecord::Base belongs_to :blog belongs_to :post, counter_cache: true # note that a blog can reblog a post multiple times validates :blog, :post, presence: :true end
require 'set' class Grid ORTHOGONAL_NEIGHBORS = [ [-1, 0], [0, -1], [1, 0], [0, 1], ] DIAGONAL_NEIGHBORS = [] (-1..1).each do |x| (-1..1).each do |y| next if x == 0 && y == 0 DIAGONAL_NEIGHBORS.push([x, y]) end end attr_accessor :grid, :default, :mode protected :grid...
require 'rails_helper' RSpec.describe User, type: :model do describe '.import!' do it 'add create in database users from file' do User.import! expect(User.first.name).to eq 'Christina McArdle' expect(User.last.name).to eq 'David Behan' end it 'change users number in database' do ...
module Mobbex module Gateway class Base def initialize end # get the list of suscriptions # # return: Response object def get_subscriptions Subscription.new.list end # get subscription # # param: sub...
class User include Mongoid::Document validates_presence_of :provider, :uid, :nickname, :token validates_uniqueness_of :uid field :provider, type: String field :uid, type: String field :nickname, type: String field :name, type: String field :location, type: String field :avatar, type: String field ...
require 'test_helper' class TimeSpansControllerTest < ActionController::TestCase setup do @time_span = time_spans(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:time_spans) end test "should get new" do get :new assert_response :succe...
class PostComment < ApplicationRecord belongs_to :post belongs_to :user has_many :notifications, dependent: :destroy end
class CodesController < ApplicationController def edit @code = Code.find(params[:id]) @languages = Language.all end def new @tip = Tip.find(params[:tip_id]) @code = Code.new @languages = Language.all end def create @tip = Tip.find(params[:tip_id]) @code = @tip.codes.build(code_params)...
# frozen_string_literal: true class Comment # :nodoc: include Mongoid::Document include Mongoid::Timestamps field :message, type: String belongs_to :user belongs_to :book validates_presence_of :message index({ book: 1 }) end
class Knowledge < ActiveRecord::Base belongs_to :knowledge_level belongs_to :technology end
class GraphicsController < ApplicationController before_action :correct_graphic, only: [:edit, :upload, :rewrite] before_action :signed_in_user, only: [:new, :create, :edit, :update, :upload, :upvote, :downvote, :graphic_suka, :graphic_unsuka, :delete_graphic, :rewrite, :delete_screenshot, :delete_broke, :rejec...
When(/^I open landing page$/) do web_app.page.open end Then(/^I should be able to see landing page$/) do EventuallyHelper.eventually do expect(web_app.landing_page).to have_logo end end And(/^the navigation widget should include the following columns$/) do |menu| actual_result = web_app.landing_page.navig...
class PassengerMailer < ApplicationMailer default from: 'johannocsantos@gmail.com' def booking_confirmation @booking = params[:booking] @traveler = params[:traveler] mail(to: @traveler.email, subject: 'Booking confirmation') end end
module Hanami module Action # Glue code for full stack Hanami applications # # This includes missing rendering logic that it makes sense to include # only for web applications. # # @api private # @since 0.3.0 module Glue # Rack environment key that indicates where the action inst...
class Entry < ApplicationRecord belongs_to :user enum entry_type: { clock_in: 0, clock_out: 1, } validates :entry_type, presence: true, inclusion: entry_types.keys validates :user_id, presence: true validates :time, presence: true end
# frozen_string_literal: true class Wegift::Stock < Wegift::Response PATH = '/stock' # request/payload attr_reader :id # response/success attr_accessor :available_stock, :currency_code, :product_code, :product_name def initialize(params = {}) @id = params[:id] end # Product Stock # GET /api/b...
# frozen_string_literal: true require 'spec_helper' RSpec.describe Sidekiq::Instrumental::Middleware::Server do let(:config) { Sidekiq::Instrumental::Configuration.new } let(:middleware) { described_class.new(config) } let(:sidekiq_stats) do instance_double('Sidekiq::Stats', enqueued: 1,...
require 'rails_helper' RSpec.describe Proposal, type: :model do let(:hub) { create(:hub) } let(:participant) { create(:participant, hub_id: hub.id) } let(:site) { create(:site, participant_id: participant.id) } let(:contractor) { create(:contractor) } let(:project) { site.projects.create(FactoryGirl.build(:p...
class UserCase < ActiveRecord::Base attr_accessible :id has_many :case_workflow_values before_save :create_case_token private def create_case_token self.case_token = SecureRandom.urlsafe_base64 end end
require 'spec_helper' describe Api::V2::VotesController do before(:each) do post api_sessions_path, {:user => {:email => 'gxbsst@gmail.com', :password => 'wxh51448888'}}, {'Accept' => 'application/vnd.iwine.com; version=2'} @user = User.find_by_email('gxbsst@gmail.com') @response = res...
class MarginalizationsController < ApplicationController before_action :set_marginalization, only: [:show, :edit, :update, :destroy] before_action :set_act before_action :authenticate_user!, except: [:index, :show] # GET /marginalizations # GET /marginalizations.json def index @marginalizations = Margi...
require 'redis' require_relative 'entry' class FeedStore attr_accessor :current_list_key def initialize() @store = Redis.new @current_list_key = "global_feed" end def size @store.zcard(@current_list_key) end def all_entries feed_entry_keys = @store.zrevrange(@current_list_key, 0, size-1)...
require 'spec_helper' describe Place do subject {Place.create(name: 'sofa', price: 120, description: 'really comfy', start_availability: Date.new(2016,1,1), end_availability: Date.new(2017,1,1), user_id: 1)} describe '#name' do it 'has a name' do expect(subject.name).to eq 'sofa' end end descri...
class ChangeDateTakenToDatetimeDefault < ActiveRecord::Migration[5.2] def change change_column :articles, :date_taken, :datetime end end # default: -> { 'NOW()' }
class Patient < ActiveRecord::Base belongs_to :doctor has_many :appointments has_many :doctors, through: :appointments end
# Superdigit # Time Complexity - O(log10n)? # Space Complexity - O(log10n)? def super_digit(n) raise ArgumentErrof if n < 0 return n if n < 10 # base case sum = 0 while n / 10 > 0 sum += n % 10 n /= 10 end sum += n return super_digit(sum) end # Refined Superdigit # Time Complexity - O(...
class Faq < ActiveRecord::Base default_scope { order('score desc') } validates_presence_of :question validates :score, numericality: { greater_than_or_equal_to: 0 } end
require 'rails_helper' describe "adding races" do it "allows a user to create a race with a title" do visit new_race_path fill_in "Name", with: "La Mision" click_on("Create Race") visit races_path expect(page).to have_content("La Mision") end end
class Booking < ApplicationRecord belongs_to :dog belongs_to :user has_many :reviews validates :status, inclusion: { in: %w(approved pending rejected) } validates :start_date, presence: true validates :end_date, presence: true end
class Post < ActiveRecord::Base has_attached_file :cover_image, :styles => { :large => "1000x350>", :thumb => "100x100>" }, :default_url => "missing.png" validates_attachment_content_type :cover_image, :content_type => /\Aimage\/.*\Z/ has_one :image , :as => :imageable has_many :reviews , :as => :revie...
require_relative 'validation' Dir['./app/models/*.rb'].each {|file| require file } Dir['./app/models/transfer_ins/*.rb'].each {|file| require file } require './service/amqp_queue' require './config/fiat_config' require './app/services/transaction_import' module Fiat class TransferInImport < TransactionImport T...
require 'card' require 'rspec' describe Card do subject(:card) { Card.new(5, :S) } describe "#initialize" do it "assigns value" do expect(card.value).to eq(5) end it "assigns suit" do expect(card.suit).to eq(:S) end end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception, if: proc { |c| c.request.format =~ %r{application/json} } def index render layout: 'application' end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_many :articles has_many :likes, dependent: :dest...
require "faker" class Pokemon attr_accessor :nombre #string/cadena attr_accessor :vida #numeros 50..100 attr_accessor :ataque #numeros 1..50 def initialize @nombre = Faker::Games::Pokemon.name @ataque = Faker::Number::between(from: 1, to: 50) @vida = Faker::...
after :'development:organizations' do Repository .create_with( name: 'Sandbox', public: true ) .find_or_create_by( organization: Organization.find_by(name: 'LearningTapestry') ) end