text stringlengths 10 2.61M |
|---|
require 'benchmark'
# Warmup iterations
WARMUP_ITRS = ENV.fetch('WARMUP_ITRS', 15).to_i
# Minimum number of benchmarking iterations
MIN_BENCH_ITRS = ENV.fetch('MIN_BENCH_ITRS', 10).to_i
# Minimum benchmarking time in seconds
MIN_BENCH_TIME = ENV.fetch('MIN_BENCH_TIME', 10).to_i
default_path = "results-#{RUBY_ENGINE... |
class UserController < ApplicationController
get '/signup' do
if user_signed_in?
flash.next[:greeting] = "Already logged in as #{current_user.username}"
redirect '/diary-list'
else
erb :"users/new"
end
end
post '/signup' do
user = User.new(params)
if User.all.any?{|user|user.email.downcase == p... |
##
# Kernel
#
# ISO 15.3.1
module Kernel
##
# Print human readable object description
#
# ISO 15.3.1.2.9
# ISO 15.3.1.3.34
def p(*args)
i = 0
len = args.size
while i < len
__printstr__ args[i].inspect
__printstr__ "\n"
i += 1
end
args.__svalue
end
def printf(*args)... |
require 'faraday'
module Pling
module Mobilant
class Gateway < ::Pling::Gateway
handles :sms, :mobilant, :mobile
def initialize(configuration)
super
require_configuration([:key])
end
def deliver!(message, device)
params = {}
# require url parameter
... |
# frozen_string_literal: true
class AppearancesChannel < ApplicationCable::Channel
def subscribed
redis.set("user_#{current_user.slug}_online", '1')
stream_from('appearances_channel')
AppearanceBroadcastJob.perform_later(current_user.slug, true)
end
def unsubscribed
redis.del("user_#{current_use... |
# == Schema Information
#
# Table name: reviews
#
# id :integer not null, primary key
# rating :integer
# content :text
# created_at :datetime not null
# updated_at :datetime not null
# movie_id :integer
#
class Review < ActiveRecord::Base
belongs_to :movie
validates... |
# frozen_string_literal: true
module Decidim
module Opinions
module Admin
# A command with all the business logic when an admin merges opinions from
# one component to another.
class MergeOpinions < Rectify::Command
# Public: Initializes the command.
#
# form - A form ob... |
class NewsReader::Section
attr_accessor :name, :url
@@all = []
def initialize(section_hash)
@articles = []
section_hash.each {|key, value| self.send("#{key}=", value)}
@@all << self
end
def self.all
@@all
end
def add_article(article)
rais... |
class AddCookies < ActiveRecord::Migration
def self.up
create_table "cookies" do |t|
t.column "owner_type", :string, :null => false
t.column "owner_id", :integer, :null => false
t.column "text", :string, :null => false
t.column "created_at", :datetime, :null => false
t.column "usage"... |
shared_examples 'idv max step attempts' do |sp|
it 'allows 3 attempts in 24 hours', :email do
visit_idp_from_sp_with_loa3(sp)
user = register_user
max_attempts_less_one.times do
visit verify_session_path
fill_out_idv_form_fail
click_idv_continue
expect(current_path).to eq verify_... |
class Api::V1::SongsController < ApplicationController
before_action :set_song, only: [:show, :update, :destroy]
def index
@songs = Song.where(:playlist_id => params[:playlist_id])
json_response(object: @songs)
end
def create
@song = Song.create!(
title: params[:title],
... |
class ChangeDatatypeConductorIdOfConcerts < ActiveRecord::Migration
def change
change_column :concerts, :conductor_id, :integer
end
end
|
class CreateRestaurants < ActiveRecord::Migration[5.1]
def change
create_table :restaurants do |t|
t.string :name
t.string :cuisine
t.text :description
t.string :location
t.string :address
t.string :phone_number
t.integer :price_for_two
t.string :working_hours
... |
require 'helper'
class ActiveRecordTest < Minitest::Test
class PostStates < StateManager::Base
attr_accessor :before_callbacks_called
attr_accessor :after_callbacks_called
state :unsubmitted do
event :submit, :transitions_to => 'submitted.awaiting_review'
event :activate, :transitions_to =>... |
require 'import/dc_parser'
require 'import/legacy_object'
require 'import/rels_ext_parser'
class PidAlreadyInUseError < StandardError; end
class ObjectFactory
# Used by the ObjectImporter to select the right class for
# importing a fedora object.
# This code relies on assumptions about how the fedora data
#... |
# require "for_test_helper"
# describe "FOV" do
# MAP8_RING0 = [
# "#####",
# "#####",
# "##@##",
# "#####",
# "#####"
# ]
# RESULT_MAP8_RING0 = [
# " ",
# " ... ",
# " ... ",
# " ... ",
# " "
# ]
# RESULT_MAP8_RING0_90_NORTH = [
# " ",
# " ... ",
# " . ",
# " ",
# ... |
require('capybara/rspec')
require('./app')
Capybara.app = Sinatra::Application
set(:show_exceptions, false)
describe('adding a stylist', {:type => :feature}) do
it "allows a user to add a new stylist to the list" do
visit('/')
fill_in('stylist_name', :with => 'Ruby')
click_button('Add Stylist')
expe... |
require 'yajl'
module Logical::Naf
module LogParser
class Base
REGEX_OPTIONS = {
'i' => Regexp::IGNORECASE,
'x' => Regexp::EXTENDED,
'm' => Regexp::MULTILINE
}
DATE_REGEX = /((\d){8}_(\d){6})/
UUID_REGEX = /[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{... |
class ReportsController < ApplicationController
def index
redirect_to action: 'transactions'
end
def transactions
relation = Transaction.where(category_id: current_user.categories.map(&:id))
relation = relation.where('date >= ?', params[:from_date]) if params[:from_date].present?
relation = rel... |
require 'date'
module AndroidDeployment
class LogFile
def initialize(file_name)
@file = File.new("log/#{file_name}.log", 'a+')
end
def puts(message)
@file.puts "[#{DateTime.now}]" + message
@file.flush
end
def close
@file.close
end
end
end
|
class AddDetailsToUsers < ActiveRecord::Migration
def change
add_column :users, :member_id, :string, null: false, default: "", :limit => 16
add_column :users, :first_name, :string, null: false, default: ""
add_column :users, :family_name, :string, null: false, default: ""
... |
module SkuConfigs
def nitrogen
{ name: :nitrogen, image_link: "nitrogen.png", window: @window,
x: 220, y: 280, quantity: 3, height: 66, width: 60,
description: "Gives you bonus boost for certain berries.", type: :fertilizer }
end
def potassium
{ name: :potassium, image_link: "potassium.png",... |
class ProjectsController < ApplicationController
before_action :redirect_if_not_signed_in
before_action :set_user
before_action :set_project, except: [:index, :new, :create]
def index
@projects = Project.search(params[:query])
end
def new
@project = Project.new
end
def create
@project =... |
class Role < ActiveRecord::Base
ROLES = {
:admin => 'Admin',
:editor => 'Editor',
:registered => 'Registered'
}
has_and_belongs_to_many :users
validates_uniqueness_of :name
validates_presence_of :name
def self.[](value)
raise ArgumentError, "Role not available: '#{value}'" ... |
FactoryGirl.define do
factory :stage do
sequence(:url) { |n| "test#{n}-example.com" }
end
end
|
class Digg
def initialize
@resource = (Service.new("http://digg.com/api/news/popular.json")).resource
end
def get_news
news = []
@resource['data']['feed'].each do |item|
news << FilterNews.new(item)
end
news
end
private
class FilterNews
attr_reader :title, :author, :date, :url, :source
def... |
class MarkerMailer < ActionMailer::Base
def done_email(marker, user)
@marker = marker
@user = user
rel = DocumentUserRelation.find_by_document_id_and_user_id(marker.document.id, user.id)
@url = code_url(rel.code)
headers 'In-Reply-To' => marker.message_id('create', @user)
mail to: @user.email,... |
# frozen_string_literal: true
require 'test_helper'
module Vedeu
describe 'Bindings' do
it { Vedeu.bound?(:_log_).must_equal(true) }
end
module Logging
describe Log do
let(:described) { Vedeu::Logging::Log }
let(:_message) { 'Some message...' }
let(:type) { :info }
des... |
FactoryBot.define do
factory :step do
operation { "MyString" }
expected_minutes { 30.0 }
comment { "MyString" }
trait :invalid do
operation { nil }
end
trait :new_operation do
operation { "NewOperation" }
end
end
end
|
class AddOrdersColumns < ActiveRecord::Migration[6.0]
def change
add_reference :orders, :video, foreign_key: true
add_reference :orders, :user, foreign_key: true
add_reference :orders, :purchase, foreign_key: true
add_column :orders, :confirmed, :boolean, default: false
end
end
|
module GoogleApps
# Represents a domain user.
class User < Entry
get_all { "#{ENDPOINT}/#{GoogleApps.connection.domain}/user/2.0" }
get_one { |id| "#{ENDPOINT}/#{GoogleApps.connection.domain}/user/2.0/#{id}" }
post_new { "#{ENDPOINT}/#{GoogleApps.connection.domain}/user/2.0" }
put_updated { ... |
class CashRegister
attr_accessor :total, :discount, :price, :items
def initialize(discount = 0)
@total = 0
@discount = discount
@items = []
end
def add_item(item, price, amount = 1)
@price = price
@total += price * amount
@item_num = amount
i = 0
for i in 1..amount do
@it... |
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::Seh
def initialize(info = {})
super(update_info(info,
'Name' => 'HP Diagnostics Server magentservice.exe overflow',
'Description' => %q{
This module exploits a s... |
require "test_helper"
class UsersControllerTest < ActionDispatch::IntegrationTest
fixtures :users
setup do
@user = users(:one)
end
def test_should_get_new
get new_user_url
assert_response :success
end
def test_should_create_user_and_associated_loan_application
assert_difference ["User.c... |
class User < ActiveRecord::Base
include SessionsHelper
has_secure_password
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email,
presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password,
length: { minimum: 6 }
... |
class PinGroupsController < ApplicationController
before_filter :login_required
filter_access_to :all
# GET /pin_groups
# GET /pin_groups.xml
def index
@pin_groups = PinGroup.paginate :per_page=>20,:page => params[:page], :order => 'id DESC'
respond_to do |format|
format.html # index.html.erb
... |
# frozen_string_literal: true
require 'emis/models/combat_pay'
require 'emis/models/deployment'
require 'emis/models/veteran_status'
module EMIS
module Models
class DentalIndicator
include Virtus.model
attribute :separation_date, Date
attribute :dental_indicator, String
end
class Eli... |
class RoleSerializer < ApplicationSerializer
object_as :role
attributes(
:name,
:resource_type,
:resource_id,
:created_at,
:updated_at,
)
has_many :activities, serializer: ActivitySerializer
has_many :people, serializer: PersonSerializer
has_many :person_groups, serializer: PersonGroup... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'board'
require_relative 'color'
# Knight
class Knight
include Color
def initialize
@moves = [[2, 1], [2, -1], [1, 2], [-1, 2], [-2, 1], [-2, -1], [1, -2], [-1, -2]]
@min_coordinate = 0
@max_coordinate = 7
@board = Board.new(self)... |
FactoryBot.define do
factory :unit do
name { Faker::Address.secondary_address }
association :building, factory: :building
end
end
|
require 'rabbit_jobs'
require 'rake'
def rails_env
defined?(Rails) ? Rails.env : (ENV['RAILS_ENV'] || 'development')
end
def app_root
Pathname.new(ENV['RAILS_ROOT'] || Rails.root)
end
def make_dirs
%w(log tmp tmp/pids).each do |subdir|
dir = app_root.join(subdir)
Dir.mkdir(dir) unless File.directory?(d... |
class AddDoToComment < ActiveRecord::Migration
def self.up
add_column :comments, :do, :string, :default => "comment" # maybe follow
add_index :comments, [:do]
end
def self.down
remove_column :comments
end
end
|
require 'rails_helper'
RSpec.describe PurchaseAddress, type: :model do
before do
@purchase_address = FactoryBot.build(:purchase_address)
end
describe '商品購入情報登録' do
context '商品購入情報登録がうまくいくとき' do
it 'クレジットカードの情報と配送先住所の情報が正しく入力されていれば保存ができること' do
expect(@purchase_address).to be_valid
end... |
class Admin < ActiveRecord::Base
validates_inclusion_of :singleton_guard, in: [0]
def self.instance
# there will be only one row, and its ID must be '1'
if Admin.all.count == 1
return Admin.all.first
else
Admin.destroy_all
admin = Admin.create(singleton_guard: 0)
return admin
... |
class Xlsx
def self.file_names
res = []
path = Rails.root.join('tmp', 'xlsx')
Dir.open(path) do |dir|
dir.each do |f|
next if f.match(/^~/)
next unless f.match(/xlsx$/)
res.push(f)
end
end
res
end
def self.file filename, template
workbook = RubyXL::Pars... |
# frozen_string_literal: true
module Validators
class Checklists < Base
include ChecklistsValidatorHelper
def initialize(fields)
@fields = fields
end
def validate(list)
@list = list
fields.each { |field| send(field) }
end
private
attr_reader :fields, :list
def ... |
class AddResultToUserSubmissions < ActiveRecord::Migration
def change
add_column :user_submissions, :result_file, :binary
end
end
|
class PrintDetail < ApplicationRecord
acts_as_paranoid
belongs_to :job_request
include AttachmentUploader::Attachment.new(:attachment)
def as_json(*)
previous = super
# previous[:cached_attachment_data] = cached_attachment_data
previous[:attachment] = attachment
previous[:attachment_url] = atta... |
class Department
attr_accessor :id, :name
def courses
courses = Course.find_all_by_department_id(@id)
end
def add_course(course)
course.department = self
end
def self.create_table
create = "CREATE TABLE IF NOT EXISTS departments (id INTEGER PRIMARY KEY, name TEXT);"
DB[:conn].execute(creat... |
#!/usr/bin/env ruby
begin
x = 1/0
rescue ZeroDivisionError
puts "you cannot divide by zero"
ensure
@flag = 1
puts "inside ensure"
end
|
class Recipe < ActiveRecord::Base
validates :name, presence: true
validates :ingredients, presence: true
validates :instructions, presence: true
end
|
unless Kernel.respond_to?(:require_relative)
module Kernel
def require_relative(path)
require File.join(File.dirname(caller.first), path.to_str)
end
end
end
lib_dir = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift lib_dir unless $LOAD_PATH.include?(lib_dir)
os_config = File.join(lib_di... |
require 'open-uri'
require 'fileutils'
PROTOBUF_DEPS_DIR="./.protobuf"
PROTOBUF_OUT_DIR="./Sources/Tenderswift/TendermintTypes"
TENDERMINT_PROTOBUF="TendermintTypes.proto"
task default: :build_protobuf
desc "Download and properly extracts required protobuf dependency definitions"
task :get_protobuf_deps do
FileUti... |
class Filo < ActiveRecord::Base
has_many :clases
has_many :exemplares
attr_accessible :descricao, :status
self.per_page = 10
scope :busca, joins(:clases).order("filos.descricao")
validates_presence_of :descricao, :message =>" - Deve ser preenchido"
validates_uniqueness_of :descricao, :message =>... |
require 'csv'
class Personal_Log
def initialize(filename)
@filename = "#{Rails.root}/lib/#{filename}"
if file_dir_or_symlink_exists?(@filename)
readFile
else
f = File.new(@filename, "w")
f.close
readFile
end
end
private
def writeFile
CSV.open(@filename, "w") do |c... |
module EmailHelper
include Rails.application.routes.url_helpers
include ActionView::Helpers::UrlHelper
def user_url user
link_to "#{ENV['ZHISHi_URL']}/users/#{user.zhishi_id}", user.zhishi_name
end
end
|
class Manager::TaskTagSerializer < ActiveModel::Serializer
attributes :id, :text, :taggings_count
def text
object.name
end
end
|
class GameDisplay
attr_reader :rows,
:display_positions
def initialize
@header = '.A B C D'
@rows = ['1 ',\
'2 ',\
'3 ',\
'4 ']
@display_positions = {a1:[0, 1], b1:[0, 3], c1:[0, 5], d1:[0, 7],\
... |
class Group < ActiveRecord::Base
belongs_to :speciality
has_many :students
has_many :examinations
has_many :active_examinations, -> { where active: true }, class_name: 'Examination'
has_many :inactive_examinations, -> { where active: false }, class_name: 'Examination'
has_many :active_students, -> { whe... |
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... |
class AdminsessionsController < ApplicationController
before_action :set_adminsession, only: [:show, :edit, :update, :destroy]
before_action :authenticate_admin!
# GET /adminsessions
# GET /adminsessions.json
def index
@adminsessions = Adminsession.all
end
# GET /adminsessions/1
# GET /adminsess... |
class FakeStdout
attr_accessor :calls
def initialize
@calls = []
@string = ""
end
def method_missing(method, *args)
@calls << {method: method, args: args}
end
def write(str)
@string += str
method_missing(:write, strs)
end
def to_s
return "" if @calls.e... |
class Token < ActiveRecord::Base
belongs_to :formulario
validates_uniqueness_of :desc_token
end
|
class Story < ActiveRecord::Base
has_one :lead_item, class_name: 'Item'
belongs_to :author, class_name: 'User'
end
class Item < ActiveRecord::Base
belongs_to :story
end
class User < ActiveRecord::Base
has_many :stories
end |
class Post < ApplicationRecord
belongs_to :user
validates :subject, presence: true, length: { minimum: 1, maximum: 50 }
validates :body, presence: true, length: { minimum: 1, maximum: 2000 }
end
|
Factory.define(:car) do |f|
f.model { fake(:company, :name) }
f.mark { fake(:company, :name) }
f.vin { fake(:lorem, :word) }
f.production_year { Date.current - 10.years }
f.association(:user)
end
|
class S3ManifestAbility
include CanCan::Ability
def initialize
can :read, :all
end
end
|
class UsersController < ApplicationController
def login
return unless params[:username]
authenticator = Rails.env.production? ? SimpleLDAP : SimpleLDAP::Stub
data = authenticator.authenticate(params[:username], params[:password], 'ldap.stuba.sk', 389, 'ou=People,dc=stuba,dc=sk')
if data.nil?
... |
# frozen_string_literal: true
require "spec_helper"
require "fiber"
describe GraphQL::Dataloader do
class BatchedCallsCounter
def initialize
@count = 0
end
def increment
@count += 1
end
attr_reader :count
end
class FiberSchema < GraphQL::Schema
module Database
extend ... |
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length:{maximum: 140}, presence: true # limit the content length to 140 chars, and the presence: true means that the posts shouldn't be empty
end
|
class History < ActiveRecord::Base
belongs_to :user
has_many :cloths, through: :cloths_histories
has_many :cloths_histories
accepts_nested_attributes_for :cloths_histories
end
|
#Esta clase representa una tabla, donde cada renglon contiene columnas con valores asociados a dicho
#renglón y columna
class Reporte
EXTENDIDO = 101
REDUCIDO = 010
attr_reader :titulo
attr_reader :total
attr_reader :estilo
def self.datos_a=(datos)
@datos_a = datos
end
def self.datos_a
return @datos_a
... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'jekyll-pypedown/version'
Gem::Specification.new do |spec|
spec.name = "jekyll-pypedown"
spec.version = Jekyll::Pypedown::VERSION
spec.summary = "Pygments + Typogruby + kramdo... |
require "base_parser"
require "single_crochet"
require "double_crochet"
require "slip_stitch"
require "stitch_factory"
module Parsers
# Basic Stitch Parser
class BasicStitchParser < Parsers::BaseParser
def initialize(instructions)
@instructions = instructions.downcase.strip
@stitch_factory = Stitch... |
module Hotel
class Reservation
attr_reader :room, :check_in, :check_out
def initialize(room, check_in, check_out)
check_date_range(check_in, check_out)
@room = room
@check_in = check_in
@check_out = check_out
end
def check_date_range(check_in, check_out)
if check_out <=... |
puts <<~TEXT
旅行プランを選択して下さい。
1. 沖縄旅行(10000円)
2. 北海道旅行(20000円)
3. 九州旅行(15000円)
TEXT
while true
print "プランの番号を選択 > "
plan_num = gets.to_i
break if (1..3).include?(plan_num)
puts "1以上を入力して下さい。"
end
case plan_num
when 1
place = "沖縄旅行"
price = 10000
when 2
place = "北海道旅行"
p... |
class Person < ApplicationRecord
# Assoc
# Validations
validates :age, numericality: {
less_than_or_equal_to: 150
}
validates :name, :age, :alive, :gender, presence: true
# Methods
# class method
def self.order_by_age
order(:age)
end
# instance method
#callback
bef... |
#--
# Copyright (c) 2009-2010, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... |
class UserMailer < ApplicationMailer
default from: 'DONOTREPLY@ucsdmun.org'
def welcome_email(user, url)
@user = user
@url = url+"#{user.email}"
# @url = 'http://example.com/login'
mail(to: @user.email, subject: 'Welcome to Model United Nations at UCSD')
end
def change_password_mail(user)
... |
require 'spec_helper'
describe RabbitJobs::Consumer::JobConsumer do
let(:consumer) { RabbitJobs::Consumer::JobConsumer.new }
let(:job) { TestJob.new }
describe '#process_message' do
it 'parses job' do
payload = RJ::Job.serialize(TestJob)
mock(RJ::Job).parse(payload) { job }
consumer.proces... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
# The most comm... |
require "nokogiri"
require "net/http"
require "uri"
require "time"
require "facets"
require "yaml"
module Watcard
class History
def initialize(config)
@conf = config
end
def log(msg)
STDERR.puts msg
end
def history_page(date)
uri = URI.parse("https://account.watcard.uwaterloo.... |
# 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... |
# Multiply Lists
# Write a method that takes two Array arguments in which each Array contains a list of numbers, and returns a new Array that contains the product of each pair of numbers from the arguments that have the same index. You may assume that the arguments contain the same number of elements.
def multiply_li... |
require './input_functions'
module Genre
POP, CLASSIC, JAZZ, ROCK = *1..4
end
$genre_names = ['Null', 'Pop', 'Classic', 'Jazz', 'Rock']
class Track
attr_accessor :name, :location
def initialize (name, location)
@name = name
@location = location
end
end
class Album
attr_accessor :title, :artist, :genre, ... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe EventsHelper do
let(:user) { create(:user) }
let(:event) { create(:event) }
describe 'override_icon' do
let(:reg) { create(:registration, user: user, event: event) }
before { generic_seo_and_ao }
it 'generates the correct normal ... |
# json.shoes do
# @shoes.each do |shoe|
# json.set! :id do
# json.extract! :id, :name
# if shoe.photo.attached?
# json.photoUrl url_for(shoe.photo)
# end
# end
# end
# end
json.array! @shoes do |shoe|
json.extract! shoe, :id, :name, :pri... |
module Noodle
class MinimumNumberOfNodeProperties < ActiveModel::Validator
def validate(record)
record.errors.add(:empty_value, 'Node must have at least one property', strict: true) if record.node_properties.length < 1
end
end
end
|
source 'https://rubygems.org'
# Sinatra is a very simple webserver written in Ruby.
# Documentation is here: http://www.sinatrarb.com/intro.html
gem 'sinatra', '~> 1.4.5'
# Rerun causes Sinatra to auto-reload files that you change so that you do not have to restart the server after every
# change.
gem 'rerun', '~> 0.... |
# Fields:
# user_id: ScalarmUser id who has this secrets
# access_key - actually stored as hashed_access_key
# secret_key - actually stored as hashed_secret_key
class AmazonSecrets < MongoActiveRecord
Encryptor.default_options.merge!(:key => Digest::SHA256.hexdigest('QjqjFK}7|Xw8DDMUP-O$yp'))
def self.collection_... |
#this is the naive implementation of the pattern matching and, as the name implies, works at quadratic time
class QuadraticPatternsMatcher
attr_accessor :patterns
def initialize(patterns)
@patterns = patterns
end
def best_match(path)
quadratitic_match_candidates.find {|candidate| candidate.matches?(pat... |
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/myapp_admin', as: 'rails_admin'
devise_for :users, path: '', path_names: { sign_in: 'myapp_login', sign_out: 'myapp_logout' },
only: [:sessions]
apipie
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
devise_s... |
class WorkerType < ApplicationRecord
belongs_to :guard
belongs_to :worker
end
|
require 'rails_helper'
RSpec.describe "V1 Users API", :type => :request do
let!(:users) { create_list(:user, 3) }
let(:json) { JSON.parse(response.body) }
context "when request the information for users" do
it "returns a collection of all users that exists" do
get api_v1_users_path
expect(... |
require 'rails_helper'
RSpec.describe "users/edit", :type => :view do
before(:each) do
@user = assign(:user, User.create!(
:name => "MyString",
:email => "MyString",
:password => "MyString",
:age => 1,
:gender => 1,
:prefecture => "",
:home_prefecture => nil,
:job ... |
require 'samanage'
require 'csv'
api_token = ARGV[0]
input = ARGV[1]
datacenter = ARGV[2]
@samanage = Samanage::Api.new(token: api_token, datacenter: datacenter)
REPORT_FILENAME = "Report - Time Tracks - #{DateTime.now.strftime("%b-%m-%Y %H%M")}.csv"
def log_to_csv(row: , filename: REPORT_FILENAME, headers: [])
w... |
class Study < ApplicationRecord
validates :name, presence:true
validates :drug, presence:true
validates_numericality_of :age_limit, greater_than:7
validates_numericality_of :phase, less_than:6
belongs_to :study_group
has_many :sites
has_many :enrollments
has_many :subjects, through: :e... |
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
scope :registered, where(:role_id => 1)
end
|
class ProviderPhone < ApplicationRecord
belongs_to :phone
belongs_to :provider
end
|
class CategoryInventory
attr_reader :database
def initialize(database)
@database = database
end
def dataset
database.from(:categories)
end
def create(category)
dataset.insert(category)
end
def all
dataset.map { |category| Category.new(category)}
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.